Saturday, May 19, 2012

Programmatically compile Java class


Programmatically compile Java class:

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class Main {
  public static void main(String[] args) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int result = compiler.run(null, null, null, "Hello.java");

    System.out.println("Compile result code = " + result);
  }
}
 


Cascade type - EJB 3.0


Cascade type - EJB 3.0:

The cascade type specifies the set of operations that can be cascaded to a related entity. CascadeType can have different values: PERSIST, MERGE, REMOVE, REFRESH, and ALL.
PERSIST is similar to an insert command. Specifying a CascadeType of PERSIST implies that a persist operation will be cascaded from a parent entity to its child entity.

MERGE is similar to an update command. Specifying a CascadeType of MERGE implies that a merge operation will be cascaded from a parent entity to its child entity.

REMOVE is similar to a delete command. Specifying a CascadeType of REMOVE implies that a remove operation will be cascaded from a parent entity to its child entity.

REFRESH reloads the related entity from the database when the referring entity is refreshed.

If you do not specify a cascade type, no operations are cascaded.


Fetch Type - Lazy vs. Eager Loading in EJB 3.0

Fetch Type - Lazy vs. Eager Loading in EJB 3.0:

The fetch type is used to specify the data-fetching strategy that a persistence provider uses to fetch data from the database. FetchType is used on the @Basicannotation, @LOB annotation, and relationship annotations such as OneToMany, ManyToMany, ManyToOne, and OneToOne. The default for fetchTypeis EAGER, except for a ManyToMany and a OneToMany relationship, for which the default is LAZY. A fetchType of EAGER means that a persistence provider will load the attribute of an entity along with the entity, whereas a fetchType of LAZY is a hint to the provider that the attribute need not be fetched along with the entity, or we can say that In eager loading we will fetch all the values from the Persistent storage and cache it. It will make serious performance issues. There we use lazy loading to avoid that.

Keep in mind that a FetchType of EAGER is a requirement on the persistence provider, whereas a fetchType of LAZY is only a hint. So even though you may specify the fetchType to be LAZY, the persistence provider may choose to load the attribute eagerly.
A FetchType of lazy benefits Large Objects and Relationships in which the attributes are not accessed immediately when the entity is loaded.The attributes are loaded whenever required.

Example:

@Entity
public class Order {
@OneToMany(fetchType=FetchType.EAGER, ...)
public Collection<OrderLineItem> getLineItems(){
return lineItems;
}
}

@Entity
public class Order {
@OneToMany(fetchType=FetchType.LAZY, ...)
public Collection<OrderLineItem> getLineItems(){
return lineItems;
}
}


Advantages of EJB 3.0

Advantages of EJB 3.0:

The below are the some of the advantages of using EJB 3.0


  1. More work is done by container,less by developer
  2. Everything is a POJO(Plain old java object)
  3. Simplify programming model
  4. Hibernate like ORM(Object Relational Mapping)
  5. Dependency injection
  6. Annotations(Requires Java 5)
  7. Bean specifies what it needs through metadata
  8. No longer written to unneeded container interfaces
  9. Deployment descriptor no longer required


FTP Upload/Download with Java

The below java code will help us to Download/Upload files from/To FTP server.

import java.io.*;
import java.net.*;

public class FTPClient {
    public final String host;
    public final String user;
    protected final String password;
    protected URLConnection ftpurl;

    public FTPClient(String host, String user, String password) {
        this.host = host;
        this.user = user;
        this.password = password;
        this.ftpurl = null;
    }

    private URL createURL(String destfile) throws MalformedURLException {
        if (user == null)
            return new URL("ftp://" + host + "/" + destfile + ";type=i");
        else
            return new URL("ftp://" + user + ":" + password + "@" + host +"/" + destfile + ";type=i");
    }

    protected InputStream openDownloadStream(String destfile) throws Exception {
        URL url = createURL(destfile);
        ftpurl = url.openConnection();
        InputStream is = ftpurl.getInputStream();
        return is;
    }

    protected OutputStream openUploadStream(String targetfile) throws Exception {
        URL url = createURL(targetfile);
        ftpurl = url.openConnection();
        OutputStream os = ftpurl.getOutputStream();
        return os;
    }

    protected void close() {
        ftpurl = null;
    }

    public void Upload(String sourcefile, String destfile) {
        try {
            OutputStream os = openUploadStream(destfile);
            FileInputStream is = new FileInputStream(sourcefile);
            byte[] buf = new byte[33554432];
            int c;
            while (true) {
                c = is.read(buf);
                if (c <= 0)
                    break;
                os.write(buf, 0, c);
            }
            os.close();
            is.close();
            close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
        }
    }

    public void Download(String sourcefile, String destfile) {
        try {
            InputStream is = openDownloadStream(destfile);
            FileOutputStream os = new FileOutputStream(sourcefile);
            byte[] buf = new byte[41943040];//Buffer size set to 40 MB ,change based on the file size
            int c;
            while (true) {
                c = is.read(buf);
                if (c <= 0)
                    break;
                os.write(buf, 0, c);
            }
            is.close();
            os.close();
            close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
        }
    }
}