Pages

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, September 29, 2013

java.lang.NoSuchMethodError: antlr.collections.AST.getLine()

After adding Velocity to my Spring Web Application, I'm getting this error:


29.09.2013 22:44:26  WARN (AbstractMessageListenerContainer.java:696) - Execution of JMS message listener failed, and no ErrorHandler has been set.
java.lang.NoSuchMethodError: antlr.collections.AST.getLine()I

...

The error is due by the conflicts between two differents version of "antlr". You need to exclude the version from velocity-tool.

So add the following exclusion to the velocity-tools maven dependency.


  <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-tools</artifactId>
            <version>2.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>antlr</artifactId>
                    <groupId>antlr</groupId>
                </exclusion>
            </exclusions>
   </dependency>

Tuesday, September 10, 2013

JPA / Hibernate - On Delete Set NULL

It's impossible to configure a ON DELETE SET NULL with JPA / Hibernate.

To achieve this, you could define a @PreRemove method that specify the fields to set NULL.

Here's an example:

...

/**
 * The persistent class for the user database table.
 */
@Entity
@Table(name = "`user`")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(unique = true, nullable = false)
    private Long id;

    @Column(length = 255)
    private String address;

    @Column(length = 255)
    private String city;

    @Column(nullable = false, length = 2)
    private String country;

    @Column(nullable = false, length = 255)
    private String email;

    @Column(name = "is_active", nullable = false)
    private Boolean isActive;

    @Column(nullable = false, length = 255)
    private String name;

    @Column(nullable = false, length = 40)
    private String password;

    @Column(length = 15)
    private String phone;

    @Column(name = "postal_code", length = 7)
    private String postalCode;

    @Column(nullable = false, length = 2)
    private String province;

    @Column(length = 1)
    private String role;

    @ManyToMany
    @JoinTable(
            schema = "stratageme_ca",
            name = "favourite_product"
            , joinColumns = {
            @JoinColumn(name = "user_id", nullable = false)
    }
            , inverseJoinColumns = {
            @JoinColumn(name = "product_id", nullable = false)
    }
    )
    private List<Product> products;

    @OneToMany(mappedBy = "user")
    private List<PurchaseOrder> purchaseOrders;

    @OneToOne(mappedBy = "user")
    private SavedCart savedCart;

    @OneToMany(mappedBy = "specialist")
    private List<Store> storesSpecialist;


    @OneToMany(mappedBy = "director")
    private List<Store> storesDirector;

    @OneToMany(mappedBy = "vp")
    private List<Store> storesVp;

    @OneToMany(mappedBy = "conseiller")
    private List<Store> storesConseiller;

    @OneToMany(mappedBy = "user")
    private List<Territory> territories;

    @ManyToOne
    @JoinColumn(name = "all_under_banner_id")
    private Banner banner;

    @ManyToOne
    @JoinColumn(name = "title_id")
    private Title title;

    public User() {
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getAddress() {
        return this.address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return this.city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return this.country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Boolean getIsActive() {
        return this.isActive;
    }

    public void setIsActive(Boolean isActive) {
        this.isActive = isActive;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhone() {
        return this.phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPostalCode() {
        return this.postalCode;
    }

    public void setPostalCode(String postalCode) {
        this.postalCode = postalCode;
    }

    public String getProvince() {
        return this.province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getRole() {
        return this.role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public List<Product> getProducts() {
        return this.products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }

    public List<PurchaseOrder> getPurchaseOrders() {
        return this.purchaseOrders;
    }

    public void setPurchaseOrders(List<PurchaseOrder> purchaseOrders) {
        this.purchaseOrders = purchaseOrders;
    }

    public SavedCart getSavedCart() {
        return this.savedCart;
    }

    public void setSavedCart(SavedCart savedCart) {
        this.savedCart = savedCart;
    }


    public List<Store> getStoresSpecialist() {
        return storesSpecialist;
    }

    public void setStoresSpecialist(List<Store> storesSpecialist) {
        this.storesSpecialist = storesSpecialist;
    }

    public List<Store> getStoresDirector() {
        return storesDirector;
    }

    public void setStoresDirector(List<Store> storesDirector) {
        this.storesDirector = storesDirector;
    }

    public List<Store> getStoresVp() {
        return storesVp;
    }

    public void setStoresVp(List<Store> storesVp) {
        this.storesVp = storesVp;
    }

    public List<Store> getStoresConseiller() {
        return storesConseiller;
    }

    public void setStoresConseiller(List<Store> storesConseiller) {
        this.storesConseiller = storesConseiller;
    }

    public List<Territory> getTerritories() {
        return this.territories;
    }

    public void setTerritories(List<Territory> territories) {
        this.territories = territories;
    }

    public Banner getBanner() {
        return this.banner;
    }

    public void setBanner(Banner banner) {
        this.banner = banner;
    }

    public Title getTitle() {
        return this.title;
    }

    public void setTitle(Title title) {
        this.title = title;
    }


    /**
     * Pre Remove to set ON DELETE SET NULL
     */
    @PreRemove
    public void preRemove(){
        for(Store s : storesConseiller){
            s.setConseiller(null);
        }

        for(Store s : storesSpecialist){
            s.setSpecialist(null);
        }

        for(Store s : storesDirector){
            s.setDirector(null);
        }

        for(Store s : storesVp){
            s.setVp(null);
        }

    }


}

Wednesday, March 21, 2012

SOAP Web Services - Generating Java artifacts with WSIMPORT

Hi

The Java JDK comes with an easy tool to generate Java Web Services artifacts. Prefer this method instead of JBoss wsconsume because if your JBoss is too old, it will lead to some random error (ClassCastException...)

You just have to type the following command.

wsimport -s source -p com.mypackage http://mywsdlpath
:8080/method?wsdl

Friday, February 10, 2012

SOAP Web Services - Generating Java artifacts, JAX-WS

If you want to consume web services with Java and JBoss, you can use the JBoss tool "wsconsume" to build all the artifacts used to talk with the SOAP Web Service.

You need JBoss to achieve this.

The tool is in JBoss/bin. It is named wsconsume.sh

Here are the steps to generates the aritfacts
  1. Use the following command to generate the artifacts: wsconsume.sh -k -p com.mypackage http://127.0.0.1:8080/ws/jaxws/test?wsdl
  2. The tool will generate all the Java class required

Have fun!

Tuesday, August 9, 2011

Java -=- Regex find example

Here's a simple example that shows how to find the value of different groups in a string with a regular expression.

Pattern pattern = Pattern.compile("^([a-zA-Z0-9]*)_(\\d*)?_?(.*)-\\d*_.*$");
Matcher m = pattern.matcher(resourceFile.getName());

if (m.find()) {
    String destinationNickname = m.group(1);
    String jobnumber = m.group(2);
    String originalFileName = m.group(3);
} 

Test your regex with this site: http://www.regexplanet.com/simple/index.html

Tuesday, July 19, 2011

Monday, June 13, 2011

Java -=- Listing directories

Hi!

If you want to list only the directories in Java, you can use the following code:

File dir = new File("/My/Directory/Path");
File[] directories = dir.listFiles((FilenameFilter) DirectoryFileFilter.INSTANCE);
for (int i = 0; i < directories.length; i++) {
    // Each file is a directory
    directories[i].getAbsolutePath();
}

Friday, June 10, 2011

Java -=- Renaming a file

To rename a file, simply do the following:


// File (or directory) with old name
File file = new File("oldname");

// File (or directory) with new name
File file2 = new File("newname");

// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
    // File was not successfully renamed
}

Java -=- Moving a file

To move a file from a directory to another, simply do the following:


// File (or directory) to be moved
File file = new File("filename");

// Destination directory
File dir = new File("directoryname");

// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
// File was not successfully moved
}

Friday, April 29, 2011

Java -=- How to copy file using Apache IOUtils

Here is a code snippet that explain how to copy a file using IOUtils. You can get Apache IOUtils at http://commons.apache.org/io/download_io.cgi

InputStream in = null;
OutputStream out = null;

try {
    // Ensure folder is created
    FileUtils.forceMkdir(new File("/Users/yann/myfolder"));

    in = new FileInputStream(new File("/Users/yann/from.txt"));
    out = new FileOutputStream(new File("/Users/yann/myfolder", "to.txt"));

    IOUtils.copy(in, out);

} finally {
    IOUtils.closeQuietly(in);
    IOUtils.closeQuietly(out);
}

Wednesday, April 27, 2011

JAD Java Decompiler Download Mirror

Since http://www.kpdus.com/ is not available anymore, JAD is now hard to find.

Here's a mirror containing all the versions of JAD. This article is a copy of Tomas Varaneckas's site (http://www.varaneckas.com/jad).

 

Installation

Unzip jad.zip file into any appropriate directory on your hard drive.
This will create two files:
  • an executable file named 'jad.exe' (Windows 9x/NT/2000) or 'jad' (UNIX)
  • README file 'Readme.txt', which contains the short user's manual
For UNIX users: make 'jad' executable: chmod a+x jad
No further setup is required.

Disclaimer

JAD is Copyright 1997-2001 Pavel Kouznetsov. All rights reserved. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE IN ON-LINE CONTROL OF AIRCRAFT, AIR TRAFFIC, AIRCRAFT NAVIGATION OR AIRCRAFT COMMUNICATIONS; OR IN THE DESIGN, CONSTRUCTION, OPERATION OR MAINTENANCE OF ANY NUCLEAR FACILITY. THE AUTHOR DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OFFITNESS FOR SUCH USES. YOU MUST REPRESENT AND WARRANT THAT YOU WILL NOT USE THE SOFTWARE FOR SUCH PURPOSES

Wednesday, November 17, 2010

Java -=-Increase heap size

If Java runs out of memory, the following error occurs:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
This can have two reasons:
  • Your Java application has a memory leak. There are tools like YourKit Java Profiler that help you to identify such leaks.
  • Your Java application really needs a lot of memory (more than 128 MB by default!). In this case the Java heap size can be increased using the following runtime parameters:
java -Xms -Xmx
Defaults are:
java -Xms32m -Xmx128m
You can set this either in the Java Control Panel or on the command line, depending on the environment you run your application.

Monday, November 15, 2010

Java -=- Parsing a Date Using a Custom Format

DateFormat formatter = new SimpleDateFormat("MM/dd/yy"); 
Date date = (Date)formatter.parse("01/29/02"); 

Friday, August 27, 2010

Write text file in Java

Hi!

Here is an example code to create a text file an put some contents in it. This program will create a file called write.txt.


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.Writer;
import java.io.FileNotFoundException;
import java.io.IOException;

public class WriteTextFileExample
{
    public static void main(String[] args)
    {
        Writer writer = null;

        try
        {
            String text = "This is a text file";

            File file = new File("write.txt");
            writer = new BufferedWriter(new FileWriter(file));
            writer.write(text);
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                if (writer != null)
                {
                    writer.close();
                }
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}

Monday, April 26, 2010

JBoss + RestEasy = STDERR at JBoss startup

If you use JBoss and RestEasy, it's possible that you get some STDERR errors in your JBoss logs. If you get theses errors, it's because you don't put the SL4J library in your classpath. To use Log4J and RestEasy, you must put slf4j-log4j12-X.X.X.jar and slf4j-api-X.X.X.jar in your classpath. You can find theses files by downloading the latest SLF4J distribution.


Example of logs before putting SL4J libs

12:18:00,109 INFO  [TomcatDeployer] deploy, ctxPath=/XXX, warUrl=.../tmp/deploy/tmp250404096618978916XXX.ear-contents/XXX-war-exp.war/
12:18:00,423 ERROR [STDERR] 129 [main] INFO org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap - Adding listed @Provider class XXX.util.exceptionmapper.XXXExceptionMapper
12:18:00,439 ERROR [STDERR] 145 [main] INFO org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap - Adding listed @Provider class XXX.util.exceptionmapper.EJBExceptionMapper
12:18:00,451 ERROR [STDERR] 156 [main] INFO org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap - Adding listed @Provider class XXX.util.exceptionmapper.JSONExceptionMapper
12:18:00,457 ERROR [STDERR] 163 [main] INFO org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap - Adding listed @Provider class XXX.util.exceptionmapper.GeneralExceptionMapper
12:18:00,500 ERROR [STDERR] 206 [main] INFO org.jboss.resteasy.plugins.providers - Added built in provider DataSourceProvider
12:18:00,508 ERROR [STDERR] 214 [main] INFO org.jboss.resteasy.plugins.providers - Added built in provider DefaultTextPlain
12:18:00,515 ERROR [STDERR] 221 [main] INFO org.jboss.resteasy.plugins.providers - Added built in provider org.jboss.resteasy.plugins.providers.StringTextStar
...

12:18:00,851 ERROR [STDERR] 557 [main] INFO org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap - Adding jndi resource XXX/XXXBean/local
...

12:18:01,508 INFO  [EARDeployer] Started J2EE application: file:/Users/yann/jboss-4.2.3.GA/server/default/deploy/XXX.ear
12:18:01,759 INFO  [Http11Protocol] Starting Coyote HTTP/1.1 on http-127.0.0.1-8081
12:18:01,786 INFO  [AjpProtocol] Starting Coyote AJP/1.3 on ajp-127.0.0.1-8009


Example of logs after putting SL4J libs

12:18:00,109 INFO  [TomcatDeployer] deploy, ctxPath=/XXX, warUrl=.../tmp/deploy/tmp250404096618978916XXX.ear-contents/XXX-war-exp.war/
12:18:00,423 INFO  [ResteasyBootstrap] Adding listed @Provider class XXX.util.exceptionmapper.XXXExceptionMapper
12:18:00,439 INFO  [ResteasyBootstrap] Adding listed @Provider class XXX.util.exceptionmapper.EJBExceptionMapper
12:18:00,451 INFO  [ResteasyBootstrap] Adding listed @Provider class XXX.util.exceptionmapper.JSONExceptionMapper
12:18:00,457 INFO  [ResteasyBootstrap] Adding listed @Provider class XXX.util.exceptionmapper.GeneralExceptionMapper
12:18:00,500 INFO  [providers] Added built in provider DataSourceProvider
12:18:00,508 INFO  [providers] Added built in provider DefaultTextPlain
12:18:00,515 INFO  [providers] Added built in provider org.jboss.resteasy.plugins.providers.StringTextStar
...

12:18:00,851 INFO [ResteasyBootstrap] Adding jndi resource XXX/XXXBean/local
...

12:18:01,508 INFO  [EARDeployer] Started J2EE application: file:/Users/yann/jboss-4.2.3.GA/server/default/deploy/XXX.ear
12:18:01,759 INFO  [Http11Protocol] Starting Coyote HTTP/1.1 on http-127.0.0.1-8081
12:18:01,786 INFO  [AjpProtocol] Starting Coyote AJP/1.3 on ajp-127.0.0.1-8009

Sunday, March 21, 2010

Java -=- @SuppressWarnings() possible values

Hi! 

Here is the list of possible @SuppressWarnings. This annotation remove selected warnings in Java  code. To use is, simply put @SuppressWarnings("cast") for one type, and @SuppressWarnings({"boxing", "cast"}) for more than one type. 
  • all to suppress all warnings
  • boxing to suppress warnings relative to boxing/unboxing operations
  • cast to suppress warnings relative to cast operations
  • dep-ann to suppress warnings relative to deprecated annotation
  • deprecation to suppress warnings relative to deprecation
  • fallthrough to suppress warnings relative to missing breaks in switch statements
  • finally to suppress warnings relative to finally block that don’t return
  • hiding to suppress warnings relative to locals that hide variable
  • incomplete-switch to suppress warnings relative to missing entries in a switch statement (enum case)
  • nls to suppress warnings relative to non-nls string literals
  • null to suppress warnings relative to null analysis
  • rawtypes to suppress warnings relative to un-specific types when using generics on class params
  • restriction to suppress warnings relative to usage of discouraged or forbidden references
  • serial to suppress warnings relative to missing serialVersionUID field for a serializable class
  • static-access to suppress warnings relative to incorrect static access
  • synthetic-access to suppress warnings relative to unoptimized access from inner classes
  • unchecked to suppress warnings relative to unchecked operations
  • unqualified-field-access to suppress warnings relative to field access unqualified
  • unused to suppress warnings relative to unused code

Tuesday, March 2, 2010

Catching com.arjuna.ats.internal.jta.transaction.arjunacore.commitwhenaborted exception

Hi!

If you want semantically clear application exception you should perform a flush() operation from inside the container-managed transaction at the moment just before you are ready to complete the method. It allows you to handle an exception while you are in control, without the container interfering (EJBException) and potentially worse - swallowing your persistence layer exception (go find it in container logs).

If you've got an exception from the flush() call, then you can catch it on the service layer and throw an application exception that the client can recognize.

Example:

try{
     manager.persist(relationshipDocumentType);
     manager.flush();

}catch (Exception e){
     ...
}


The exception will be catched and you will be able to do what you want.

Friday, February 19, 2010

IntelliJ Community Edition

Hi!

The guys from Jetbrains offer now a community edition of the well known IntelliJ. This version has core feature for Java developpers. It compete with Open Source players like Eclipse and NetBeans.

You can grab your copy of Intellij Community Edition at http://www.jetbrains.com/idea/download/index.html

ERROR: column notation .id applied to type name, which is not a composite type

Hi!

When doing an EJB3 web application with PostgreSQL I have this error message when I try to do a simple SELECT query on my table "user".

After investigation, I've found that:

User is a reserve table in PostgreSQL. We must not have a table named like this! By changing the name of the table, it corrects the problem!!!

Monday, January 25, 2010

JBoss - Encoding UTF-8 lost in application with EJB3

While developping a web application using EJB3 and JBoss, I've got a strange issue. The database (PostgreSQL) was in UTF-8, and the front end was also specifying UTF-8. But when I retrieve french characters with accents, they aren't showed correctly. It seems they are broken with ISO 8859-1 characters between the database and the JPA layer.

In ordrer to resolve the problem, I found that we need to force JBoss to use UTF-8. To do that, open {JBOSS_HOME}/bin/run.conf and add JVM option

-Dfile.encoding=UTF-8