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

Heap vs Stack vs Perm Space

Heap space: All live objects are allocated here.
Stack space: Stores references to the object for variable in method call or variable instantiation.
Perm space: Stores loaded classes information

For example:

Student std = new Student();

After executing the line above memory status will be like this.

Heap: stores "new Student()"
Stack: stores information about "std"
Perm Space: stores information about Student class

JVM config

-Xms512m -Xmx1024m -XX:PermSize=64MB -XX:MaxPermSize=512M

-Xms512m: JVM heap initial size
-Xmx1024m: JVM heap max size

----java.lang.OutOfMemory

Perm: Permanate generation
-XX:PermSize: JVM perm initial size
-XX:MaxPermSize=512ML JVM perm max size

----java.lang.OutOfMemoryError: PermGen space

How to debug in Eclipse with webshpsere

Go to http://localhost:8091/ibm/console/, login in.

Servers->Server Types->WebShpere application servers->server1
Additional Properties->Debugging service
Check "Enable service at server startup"
Check "JVM debug port", usually it's 7777, this is the port number that you will use.
Click Apply, then click Save directly to the master configuration.
A restart on WebShpere is needed.

In Eclipse, Run->Debug Configurations->Remote Java Application
Create a new Debug Configuration, make sure host as localhost, and port as 7777, also attach source.

How to debug Java code originated by ANT script in Eclipse

Need add the followings to the ant target that you are intended to debug.

   
      
      
       ...
    

When you run this target, it will say "[java] Listening for transport dt_socket at address: 5432", and stop here for you to debug.
You need go to Run->Debug Configurations->Remote Java Application
Create a new Debug Configuration

Host: localhost
Port: 5432

Also attach source.

If you run it, it will go to the debugging point.

Get Lapsed Time in Java

long startTime = System.currentTimeMillis();
System.out.println("start getting super session: " + startTime);

long endTime = System.currentTimeMillis();
System.out.println("end getting super session: " + endTime);
System.out.println("time taken in seconds: " + (endTime - startTime)/1000);
System.out.println("time taken in mill seconds: " + (endTime - startTime));

SimpleDateFormat


LetterDate or Time ComponentPresentationExamples
GEra designatorTextAD
yYearYear1996; 96
MMonth in yearMonthJuly; Jul; 07
wWeek in yearNumber27
WWeek in monthNumber2
DDay in yearNumber189
dDay in monthNumber10
FDay of week in monthNumber2
EDay in weekTextTuesday; Tue
aAm/pm markerTextPM
HHour in day (0-23)Number0
kHour in day (1-24)Number24
KHour in am/pm (0-11)Number0
hHour in am/pm (1-12)Number12
mMinute in hourNumber30
sSecond in minuteNumber55
SMillisecondNumber978
zTime zoneGeneral time zonePacific Standard Time; PST; GMT-08:00
ZTime zoneRFC 822 time zone-0800

must override a superclass method

I just did an update from Mercurial, and I found one of the class having compilation error on one of the method.

XXXXX must override a superclass method

I do notice that method has an annotation called "@Override". A quick search, I found that's because my Eclipse's compilation level is set as 1.5.

Preferences->Java->Compiler
Make sure Compiler compliance level set as 1.6

Changes between different Java JDK

Last week, one of my colleague told me that there is some compilation error in his project, while I checked mine, I have no problem, then quickly I found the problem: I am using JDK 1.6, while he is using 1.5. The culprit is a method from String class isEmpty(), which is a total new method at JDK 1.6, this incident prompts me to think if there is way to quickly find out the changes between different JDK.

I found this link , which shows differences between between 5.0 fcs and 6 Beta.

1.6
1.7

Get current user name and machine name in Java

    System.out.println(System.getProperty("user.name"));
    java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
    System.out.println(localMachine.getHostName());

Cannot load 64-bit SWT libraries on 32-bit JVM in Eclipse

Let's end this once for all.

You got this problem is because you are using 64bits Eclipse, but your ant target is using 32bit JDK.

It's OK to use 32bit JDK in Eclipse, but you'll have problem when your ant need some GUI prompt, at this point, it will call Eclipse to generate this GUI prompt which is 64 bits, and now we'll have problem.

Solutions:
1. Use 32bit Eclipse
2. For those ant targets which require GUI prompt, change JRE to 64bits JDK.

Faster Copy Files

 
public static void copyFile(File sourceFile, File destFile) throws IOException 
{
  if (!destFile.exists()) 
  {
    destFile.createNewFile();
  }

  FileChannel source = null;
  FileChannel destination = null;
  try 
  {
    source = new FileInputStream(sourceFile).getChannel();
    destination = new FileOutputStream(destFile).getChannel();
    destination.transferFrom(source, 0, source.size());
  } 
  finally 
  {
    if (source != null) 
    {
      source.close();
    }
    if (destination != null) 
    {
      destination.close();
    }
  }
}
    
Link

XStream

http://xstream.codehaus.org/
http://www.ibm.com/developerworks/xml/library/x-xstream/
Library of serializing object to XML and deserializing object back from XML
1) Example of converting a list of object into a XML file:
public boolean XStream2XML(List importEntryList, String strOutXMLFilePath) 
{
  XStream xs = new XStream();

  //by default, xstream will use class's full name
  //you could use alias to avoid that
  xs.alias("entryList", List.class);
  xs.alias("importentry", ImportEntry.class);
  xs.alias("attribute", Attribute.class);

  try 
  {
    FileOutputStream fs = new FileOutputStream(strOutXMLFilePath);
    xs.toXML(importEntryList, fs);
    //a simpler version
    //String xml = xs.toXML(importEntryList);
    fs.close();
  } 
  catch (Exception e1) 
  {
    //e1.printStackTrace();
    return false;
  }

  return true;
}
2) Example of converting XML back to Java Object
String xml = "......";
Person newJoe = (Person)xstream.fromXML(xml);

Java Preferences

Here is the situation, you want to save some user preferences, for example, I like certain columns for a given table, I don't want to customize it every time, I'd like to save it. Originally, I thought I might need a configuration file to achieve this, but soon I realize that it would be a pain, first of all, where to put this file? if my application is achieved, I don't even have the access the application folder. Secondly, every time I update the file, I need search this file and remove the old entry. I think there got to be a better way to do this.

Link
Link

In windows, it's stored under
HKEY_CURRENT_USER\Software\JavaSoft\Prefs

Just so we know, that we could import and export part of Registry, in this way, if we change our machine, we could just export/import and go.

Read a file in Classpath

new BufferedReader(new InputStreamReader(Q5Service.class.getResourceAsStream("/Extents.csv")));

How to print String Array

import java.util.Arrays;

Arrays.toString(arr);

Get All Time Zones in Java

isEmpty vs isBlank

You can see isBlank() is more thorough than isEmpty().

Viewing the Contents of a JAR File

jar tf <jar file name>

The t option indicates that you want to view the table of contents of the JAR file.
The f option indicates that the JAR file whose contents are to be viewed is specified on the command line.

You could also use v option, which will give you additional information.

OperationCommand
To create a JAR filejar cf jar-file input-file(s)
To view the contents of a JAR filejar tf jar-file
To extract the contents of a JAR filejar xf jar-file
To extract specific files from a JAR filejar xf jar-file archived-file(s)
To run an application packaged as a JAR file (requires the Main-class manifest header)
java -jar app.jar
To invoke an applet packaged as a JAR file
<applet code=AppletClassName.class
        archive="JarFileName.jar"
        width=width height=height>
</applet>

JSON in Java


Download the zip from here.

Here is a snippet code how to use it: