Maven Buil section for WAR

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <!-- <version>2.5.1</version> -->
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <debug>true</debug>
                    <debuglevel>lines,vars,source</debuglevel>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <warName>${project.artifactId}</warName>
                    <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
                    <webResources>
                        <resource>
                            <directory>src/main/webapp/</directory>
                            <includes>
                                <include>index.html</include>
                            </includes>
                        </resource>
                        <resource>
                            <directory>src/main/webapp/WEB-INF</directory>
                            <includes>
                                <include>jboss-web.xml</include>
                            </includes>
                            <targetPath>WEB-INF</targetPath>
                        </resource>
                    </webResources>
                </configuration>
            </plugin>
        </plugins>
    </build>

Default value in HIBERNATE Database independently

How to initialize Field in Hibernate @Entity without using @Column( columnDefenition=”” ) ?
WHY?
Because columnDefinition is DB dependently option.

Imagine you have some @Entity :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    @Column( name = "insstmp", nullable = false )
    @Type( type = "org.joda.time.contrib.hibernate.PersistentDateTime" )
    private DateTime insstmp;// date without time

    @Column( name = "updstmp", nullable = false )
    @Type( type = "org.joda.time.contrib.hibernate.PersistentDateTime" )
    private DateTime updstmp;// date without time

    /**
     * We set default value in case if the value is not set yet.
     */

    @PrePersist
    public void prePersist() {

        if ( this.updstmp == null ) {
            // Default value
            this.updstmp = getUpdstmp();
        }
        if ( this.insstmp == null ) {
            // Default value
            this.insstmp = getInsstmp();
        }
    }


    /**
     * Getter.
     *
     * @return the insstmp
     */

    public final DateTime getInsstmp() {

        return insstmp == null ? new DateTime( DateTimeZone.UTC ) : insstmp;
    }

    /**
     * Getter.
     *
     * @return the updstmp
     */

    public final DateTime getUpdstmp() {

        return updstmp == null ? new DateTime( DateTimeZone.UTC ) : updstmp;
    }

Java String Anagrams

Problem
Two strings and are called anagrams if they consist same characters, but may be in different orders. So the list of anagrams of is .

Given two strings, print Anagrams if they are anagrams, print Not Anagrams if they are not. The strings may consist at most English characters; the comparison should NOT be case sensitive.

This exercise will verify that you can sort the characters of a string, or compare frequencies of characters.

Sample Input 0

anagram
margana

Sample Output 0

Anagrams

Sample Input 1

anagramm
marganaa
Sample Output 1:

Not Anagrams

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    /**
     * Two strings and are called anagrams if they consist same characters, but may be in different orders. So
     * the list of anagrams of is .
     *
     * Given two strings, print Anagrams if they are anagrams, print Not Anagrams if they are not. The strings
     * may consist at most English characters; the comparison should NOT be case sensitive.
     *
     * This exercise will verify that you can sort the characters of a string, or compare frequencies of
     * characters.
     *
     * @param a
     * @param b
     *
     * @return
     */

    static boolean isAnagram( String a, String b ) {

        Collection<String> s1 = new ArrayList<>();

        for (int i = 0; i < a.length(); i++) {
            s1.add( String.valueOf( a.charAt( i ) ).toUpperCase() );
        }

        boolean result = true;
        for (int i = 0; i < b.length(); i++) {
            String charAt = String.valueOf( b.charAt( i ) ).toUpperCase();
            if ( !s1.contains( charAt ) ) {
                result = false;
            } else {
                s1.remove( charAt );
                //System.out.print( charAt + " : " );
                //System.out.println( s1 );
            }
        }

        return s1.size() > 0 ? false : result;
    }

Java String Compare

Problem
Given a string, find out the lexicographically smallest and largest substring of length .

[Note: Lexicographic order is also known as alphabetic order dictionary order. So “ball” is smaller than “cat”, “dog” is smaller than “dorm”. Capital letter always comes before smaller letter, so “Happy” is smaller than “happy” and “Zoo” is smaller than “ball”.]

Input Format

First line will consist a string containing english alphabets which has at most characters. 2nd line will consist an integer .

Output Format

In the first line print the lexicographically minimum substring. In the second line print the lexicographically maximum substring.

Sample Input

1
2
welcometojava
3

Sample Output

1
2
ava
wel

Explanation

Here is the list of all substrings of length :

1
2
3
4
5
6
7
8
9
10
11
wel
elc
lco
com
ome
met
eto
toj
oja
jav
ava

Among them ava is the smallest and wel is the largest.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
 * Copyright 2016. ABN Software. All Rights reserved.<br>
 * <br>
 * Created ..... 3 окт. 2016 г.<br>
 * <br>
 */

package info.abnsoft.java.HackerRank.sep2016;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

/**
 * @author annik
 *
 */

public class SolutionStringLexi {

    public static void main( String[] args ) {

        /*
         * Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named
         * Solution.
         */

        Scanner sc = new Scanner( System.in );
        String str = sc.nextLine();
        int count = sc.nextInt();
        sc.close();
//        System.out.println(str);
//        System.out.println(count);
        // splitted words :
        List<String> splitted = new ArrayList<String>();
        // sorted words
        List<String> result = new LinkedList<String>();
        if ( str.length() <= count ) {
            result.add( str );
        } else {
            for (int i = 0; i <= str.length() - count; i++) {
                //            System.out.println(str.substring(i,i+count));
                splitted.add( str.substring( i, i + count ) );
            }
            String cur = splitted.get( 0 );
            result.add( cur ); // add 1st element

            System.out.println( splitted );

            // TODO : if size==0 ?
            for (int i = 1; i < splitted.size(); i++) {
                boolean notFoundMin = true;
                for (int j = 0; j < result.size(); j++) {
                    cur = result.get( j );
                    if ( isLexicSmaller( splitted.get( i ), cur ) ) {
                        // when arr[i] is smaller insert at first
                        result.add( j, splitted.get( i ) );
                        notFoundMin = false;
//                        cur = splitted.get( i );
                        break;
                    }
                }
                if ( notFoundMin ) {
                    result.add( splitted.get( i ) ); // add at the end of list
//                    cur = splitted.get( i );
                }
            }
        }
        System.out.println( result );
        System.out.println( ( (LinkedList<String>) result ).getFirst() );
        System.out.println( ( (LinkedList<String>) result ).getLast() );
    }

    /*
     * When a < b returns true, else FALSE.
     */

    private static boolean isLexicSmaller( String a, String b ) {

        boolean result = false;
        int i = -1;
        do {
            i++;
            if ( a.charAt( i ) != b.charAt( i ) ) {
                if ( a.charAt( i ) < b.charAt( i ) ) {
                    result = true;
                }
            }
        } while (a.charAt( i ) == b.charAt( i ) && i < ( a.length() - 1 ));
        return result;
    }

}

SAMPLE : Java String.matches()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
 * Copyright 2013. ABN Software. All Rights reserved.<br>
 * <br>
 * Homepage .... http://www.ABNsoft.info<br>
 * <br>
 * Project ..... ABNTest<br>
 * Package ..... ABNTest<br>
 * File name ... StringMatch.java<br>
 * <br>
 * Author ...... Andre<br>
 * Created ..... 18.04.2013<br>
 * <br>
 */

package info.abnsoft.java.trying;

import java.util.regex.Pattern;

/**
 * @author annik
 *
 */

public class StringMatch
{
    public static void main(final String[] args) {
        //
        final StringBuffer sb = new StringBuffer( "<response>\n"+
"    <category>client</category>\n"+
"    <action>Login</action>\n"+
"    <code>1000</code>\n"+
"    <msg>Command completed successfully</msg>\n"+
"    <value>L115:no value</value>\n"+
"    <resData>\n"+
"    </resData>\n"+
"    <cltrid>RM.2013.04.18.1366294770248</cltrid>\n"+
"    <svtrid>RM.2013.04.18.1366294770248-API-SRV</svtrid>\n"+
"    <chksum>8fc683ce8d7772f91ac28224fa3e6cc0</chksum>\n"+
"</response>\n" );
       
        System.out.println(sb.toString());
       
        System.out.println("\n\n======================");
        final String pattern0 = "(?s).*" + "</response>" + ".*";
        System.out.println(pattern0);
       
        if (sb.toString().toLowerCase().matches(pattern0)) {
            System.out.println("MATCH");
        }else {
            System.out.println(" ! FAILED");
        }
       
        System.out.println("\n\n======================");
        final String pattern1 = "(?m)(?s)" + "</response>" + "";
        System.out.println(pattern1);
       
        if (sb.toString().toLowerCase().matches(pattern1)) {
            System.out.println("MATCH");
        }else {
            System.out.println(" ! FAILED");
        }
       
        System.out.println("\n\n======================");
        final String pattern2 = "" + "</response>" + "";
        final Pattern p = Pattern.compile(pattern2, Pattern.MULTILINE+Pattern.DOTALL);
        System.out.println(p.matcher(sb.toString().toLowerCase()).find());  //true


    }
}

that code above will print follow :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<response>
    <category>client</category>
    <action>Login</action>
    <code>1000</code>
    <msg>Command completed successfully</msg>
    <value>L115:no value</value>
    <resData>
    </resData>
    <cltrid>RM.2013.04.18.1366294770248</cltrid>
    <svtrid>RM.2013.04.18.1366294770248-API-SRV</svtrid>
    <chksum>8fc683ce8d7772f91ac28224fa3e6cc0</chksum>
</response>



======================
(?s).*</response>.*
MATCH


======================
(?m)(?s)</response>
 ! FAILED


======================
true

MySQL enum in HIBERNATE

How to provide corresponding hibernate Entity and MySQL ENUM type ?

1
enum('Active','Pending','Cancelled','Suspend')

With ANNOTATION :

1
2
@Column(name="status", columnDefinition="enum('Active','Pending','Cancelled','Suspend')")
public String status;

With XML config :

1
2
3
4
5
<property
   name="status"
   column="STATUS"
   type="string"
   not-null="true" />

MAVEN Error assembling WAR : webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]

I try to assemble war using maven and I get :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 13.761s
[INFO] Finished at: Tue Apr 09 02:46:52 GST 2013
[INFO] Final Memory: 6M/18M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.1.1:war (default-war) on project RegMaster: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.1.1:war (default-war) on project RegMaster: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.MojoExecutionException: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
    at org.apache.maven.plugin.war.WarMojo.execute(WarMojo.java:175)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 19 more
Caused by: org.codehaus.plexus.archiver.ArchiverException: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
    at org.codehaus.plexus.archiver.war.WarArchiver.initZipOutputStream(WarArchiver.java:149)
    at org.codehaus.plexus.archiver.zip.AbstractZipArchiver.createArchiveMain(AbstractZipArchiver.java:346)
    at org.codehaus.plexus.archiver.zip.AbstractZipArchiver.execute(AbstractZipArchiver.java:250)
    at org.codehaus.plexus.archiver.AbstractArchiver.createArchive(AbstractArchiver.java:871)
    at org.apache.maven.archiver.MavenArchiver.createArchive(MavenArchiver.java:543)
    at org.apache.maven.plugin.war.WarMojo.performPackaging(WarMojo.java:225)
    at org.apache.maven.plugin.war.WarMojo.execute(WarMojo.java:159)
    ... 21 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

solution is :

1
2
3
4
5
6
7
<plugin>            
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-war-plugin</artifactId>
  <configuration>
    <webXml>src\main\webapp\WEB-INF\web.xml</webXml>        
  </configuration>
</plugin

How to add DATABASE access in Dynamic Web Project ?

We will get such structure :

Add DATABSE in Dynamic Web Projet

Add DATABSE in Dynamic Web Projet

1. Create in your WEB_ROOT these folders: WEB-INF/database
2. Create file “datapase.properties” :

1
2
3
4
5
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc\:postgresql\://109.197.1.1\:5433/yourDB
jdbc.username=yourLogin
jdbc.password=yourPWD
jdbc.showSql=true

3. Create DataSource.xml file – it contains bean “dataSource” and gets value from “datapase.properties” file :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>/WEB-INF/database/database.properties</value>
    </property>
</bean>
 
<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>
 
</beans>

4. Create Hibernate.xml file – it cares about Spring Transactions, Hibernate Session Factory :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?xml version="1.0" encoding="UTF-8"?>
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       ">


    <!-- Hibernate transaction manager -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- Hibernate session factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

        <property name="dataSource">
            <ref bean="dataSource" />
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <!-- +1 -->
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <!-- Enable Hibernate's automatic session context management
                   Spring manages the transaction, and it doesn't need of that the session is holding in a
                   hibernate thread.
               <prop key="hibernate.current_session_context_class">thread</prop>
               -->
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop>

            </props>
        </property>

        <property name="packagesToScan" value="ru.tomatch.admin.model" />

        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>

        <property name="exposeTransactionAwareSessionFactory">
            <value>false</value>
        </property>


    </bean>
</beans>

5. And last file applicationContext.xml :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   
    <!-- Database Configuration -->
    <import resource="./database/DataSource.xml"/>
    <import resource="./database/Hibernate.xml"/>
 
    <!-- Auto scan the components -->
    <context:component-scan base-package="some.your.package1" />    
    <context:component-scan base-package="some.your.package2" />    

</beans>

ABN ENUM :

My Enum ;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
 * Copyright 2013. ABN Software. All Rights reserved.<br>
 * <br>
 * Homepage .... http://www.ABNsoft.info<br>
 * <br>
 * Project ..... RegMaster<br>
 * Package ..... RegMaster<br>
 * File name ... OnicEnumAction.java<br>
 * <br>
 * Author ...... Andre<br>
 * Created ..... 12.03.2013<br>
 * <br>
 */

package net.regmaster.onlinenic.enumtype;

/**
 * @author annik
 *
 */

public enum OnicEnumAction {

    GREETING("Greeting"),
    LOGIN("Login"),
    LOGOUT("Logout");

    private String key;

    private OnicEnumAction(String key) {
        this.key = key;
    }

    public String getValue() {
        return this.key;
    }

    /**
     * This method is simple Enum Factory by key.
     *
     * @param key
     * @return
     * @throws Exception
     */

    public static OnicEnumAction getEnum(String key) throws Exception {
        //
        OnicEnumAction res = null;

        for (OnicEnumAction action : OnicEnumAction.values()) {
            if (action.getValue().equals(key)) {
                res = action;
                break;
            }
        }
        //
        if (res == null) {
            throw new Exception("Unknow Enum key : " + key+". Check your Enum.");
        }
        return res;
    }

}