Friday, July 19, 2013

JAVA : Calculate Money With BigDecimal or Int, Long

When we calculate 1.00 - 0.90, the answer is not 0.1 but 0.09999999999999998.

The float and double types are primarily designed for scientific calculations.  If we want to get exact answer, we can use int, long or BigDecimal.

Like:
BigDecimal a = new BigDecimal("1.00");
BigDecimal b = new BigDecimal("0.90");

BigDecimal c = a.subtract(b);

It's less convenient than using a primitive arithmetic type. An alternative choice is to use int or long.


Reference:
<Effective Java> Chapert 7 

How to create JAX-RPC webservice Client with Netbeans

The JAX-RPC is  the old encoded style for webservice, netbeans doesn’t support this style anymore. The default webservice style is JAX-WS.  We need to install extra plugin if we want to call the RPC style webservice.

For the normal java application, we can find the solution here:

After the above steps, we can get two folders : ‘Generated Sources’ and ‘Web Service References’. Go to the class where you are going to call the method from the webservice, then right click, you can insert code. That is it.

For maven project, there are several ways to call RPC webservice: axis, ant and CFX.
I used axis to call the service for my project.

Step 1:
Download the wsdl files, and put this file in the folder “src/main.resources/META-INF/wsdl”.
You can get this file by creating the webservice client in the normal java application project, then copy this folder to the maven project.

Step 2:
Define the pom file. Here is my POM file: 

<groupId>com.medallion</groupId>
    <artifactId>ClientWS_Maven</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>ClientWS_Maven</name>
    <url>http://maven.apache.org</url>

    <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <targetJdk>1.6</targetJdk>
    </properties>
   
    <dependencies>
       
    <dependency>
   <groupId>javax.activation</groupId>
   <artifactId>activation</artifactId>
   <version>1.1</version>
       
    </dependency>

       <dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.3</version>
    </dependency>
   
       <dependency>
           <groupId>junit</groupId>
           <artifactId>junit</artifactId>
           <version>3.8.1</version>
           <scope>test</scope>
       </dependency>
       
       <dependency>
           <groupId>org.apache.axis</groupId>
           <artifactId>axis</artifactId>
           <version>1.4</version>
           <scope>compile</scope>
       </dependency>
       <dependency>
           <groupId>org.apache.axis</groupId>
           <artifactId>axis-jaxrpc</artifactId>
           <version>1.4</version>
           <scope>compile</scope>
       </dependency>
       <dependency>
           <groupId>commons-discovery</groupId>
           <artifactId>commons-discovery</artifactId>
           <version>0.4</version>
           <scope>compile</scope>
       </dependency>
       <dependency>
           <groupId>wsdl4j</groupId>
           <artifactId>wsdl4j</artifactId>
           <version>1.6.2</version>
           <scope>compile</scope>
       </dependency>
    </dependencies>
    <build>
       <sourceDirectory>src/main/java</sourceDirectory>
       <resources>
           <resource>
               <directory>src/main/resources</directory>
           </resource>
           <resource>
               <directory>src/main/autogen</directory>
           </resource>
       </resources>
         
       <plugins>      
           <plugin>
               <groupId>org.apache.maven.plugins</groupId>
               <artifactId>maven-compiler-plugin</artifactId>
               <version>2.3.2</version>
               <configuration>            
                   <source>1.6</source>
                   <target>1.6</target>
               </configuration>
           </plugin>
           <plugin>
               <groupId>org.codehaus.mojo</groupId>
               <artifactId>axistools-maven-plugin</artifactId>
               <version>1.4</version>
               <executions>
                   <execution>
                       <id>ax-ws-autogen</id>
                       <phase>generate-sources</phase>
                       <goals>
                           <goal>wsdl2java</goal>
                       </goals>
                   </execution>
               </executions>
               <configuration>
                   <useEmitter>true</useEmitter>
                   <packageSpace>com.medallion.clientws_maven</packageSpace>
                   <sourceDirectory>src/main/resources/META-INF/wsdl</sourceDirectory>
                   <wsdlFiles>
                       <wsdlFile>cminterface.asmx.wsdl</wsdlFile>                           
                   </wsdlFiles>
                   <outputDirectory>src/main/autogen</outputDirectory>
               </configuration>
           </plugin>
          
       </plugins>
    </build>   
</project>


step3:
Right click on the project node, test it.

Step4:

Go to the folder src/main/autogen/, you can find the generated code.

Step5:
We can call the webservice now. We used wsdl2java to generate java file locally, then we can call it directly just like calling the local class.

public class App
{
    public static void main( String[] args ) throws ServiceException, RemoteException
    {
       
        com.medallion.clientws_maven.CMInterface cmInterface = new com.medallion.clientws_maven.CMInterfaceLocator();
        com.medallion.clientws_maven.CMInterfaceSoap_PortType stub = cmInterface.getCMInterfaceSoap();
        
        stub.login("User", "password");
        
    }
}
We can also call the webservice directly.. Please refer this log:

Tuesday, May 7, 2013

Convert the relative path into absolute url

When we download the image in the website with java, the src in the img is relative, how could we download the image based on this relative?

We can try to convert the relative path into absolute url, then we save the img like writing one file.

 URL pageUrl = new URL(pageurl);
 URL imgurl1 = new URL(pageUrl, relativepath);

Wednesday, November 7, 2012

[LeetCode] Longest palindromic substring

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

Another Linear time solution, please see This link

Java Code:
   
    

public String longestPalindrome(String s) {
         String palindrom = "";
        int maxLen = 0;
        
        int index1 = 0, index2 = 0;
        int i = 0;
        while(i < 2*s.length()){
            index1 = i/2;
            index2 = i/2 + i%2;
            
            while(index1 >= 0 && index2 < s.length() && s.charAt(index2) == s.charAt(index1)){     
                index1--;
                index2++;
            }
            
            if(index2 > index1 && maxLen < (index2 - index1 - 1)) {
                palindrom = s.substring(index1+1, index2);
                maxLen = index2 - index1 - 1; 
            }
            
            i++;
        }
        
        return palindrom;
    }

[Leetcode] Longest common prefix

Write a function to find the longest common prefix string amongst an array of strings. 

解题思路:
1. 遍历数组,找出当前commonprefix下一个str的commonprefix。
2. 查看数组里所有的变量的第i位置上的字符相等否
   public String longestCommonPrefix(String[] strs) {
        String prefix = "";
        
        if(strs.length == 0) return prefix;
        
        prefix = strs[0];
        
        for(int i = 1; i < strs.length && prefix.length() > 0; i++){
            
            int j = 0;
            
            while(j < prefix.length() && j < strs[i].length() && prefix.charAt(j) == strs[i].charAt(j)) j++;
            
            prefix = prefix.substring(0, j);
        }
        
        return prefix;
    }





public String longestCommonPrefix(String[] strs) {
         String res = "";
        if(strs.length == 0) return res;
        res = strs[0];
        
        for(int i = 0; i < res.length(); i++){         
            for(int j = 1; j < strs.length; j++){
                if(i >= strs[j].length() || strs[j].charAt(i) != res.charAt(i)){
                    return res.substring(0, i);
                }
            }
        }
        
        return res;
    }

[LeetCode]Insert Interval

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]

解题思路: insertion sort 的演变

Java Code:
public List insert(List intervals, Interval newInterval) {
           List res = new ArrayList(intervals);
        
        int s = 0;
        
        // at index s, the start is correct. we need to merge the end.
        while(s < intervals.size() && newInterval.start >= intervals.get(s).start){
            s++;
        }
        
        if(s > 0 && newInterval.start <= intervals.get(s-1).end){
            s--;
        }else{
            res.add(s, newInterval);
        }
        
        res.get(s).end = Math.max(newInterval.end, res.get(s).end);
        s++;
              
       while( s < res.size() && newInterval.end >= res.get(s).start){
           newInterval.end = Math.max(newInterval.end, res.get(s).end);
           res.remove(s);
       }
        
        return res;
    }

[LeetCode] Convert sorted array to binary search tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

Java Code:
  
public TreeNode sortedArrayToBST(int[] num) {
        return sortedSubArrayToBST(num, 0, num.length-1);
    }
      
      public TreeNode sortedSubArrayToBST(int[] num, int begin, int end){
          if( begin > end) return null;
          int middle = (begin+end)/2;
          
          TreeNode root = new TreeNode(num[middle]);
          
          root.left = sortedSubArrayToBST(num, begin, middle-1);
          root.right = sortedSubArrayToBST(num, middle+1, end);
          
          return root;
    }