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

Wednesday, June 9, 2021

[Java][Mysql][Resolved] java.Sql.SQLException:unable to retrieve metadata for procedure

 Error message:

java.Sql.SQLException:unable to retrieve metadata for procedure

Source code:

CallableStatement cstmt = (CallableStatement) con.prepareCall("BEGIN sp_get_test_detail(?,?); END;");

cstmt.setString(1,strClipId);

cstmt.setString(2.strPubDate);

Solution:

Check your the statement you call stored procedure is correct, for my case, I have used the orcale syntax but not mysql, here is the correction:

CallableStatement cstmt = (CallableStatement) con.prepareCall("CALL sp_get_test_detail(?,?);");

cstmt.setString(1,strClipId);

cstmt.setString(2.strPubDate);


Tuesday, February 2, 2021

[java][Resolved] java.SQL.Exception: Invalid column index

 Erorr message:

java.SQL.Exception: Invalid column index

source code:

cstmt = (OracleCallableStatment) con.prepareCall('BEGIN SP_TEST(?,?,?,?,?,?,?)');

cstmt.setInt(1,40030485);

cstmt.setString(2,"filepath");

cstmt.setString(3,"%/temp/%");

cstmt.setString(4,"Y");

cstmt.registerOutParameter(5,OrcaleTypes.NUMBER);

cstmt.registerOutParameter(6,OrcaleTypes.DECIMAL);

cstmt.registerOutParameter(7,OrcaleTypes.VARCHAR);

cstmt.registerOutParameter(8,OrcaleTypes.CURSOR);


For my case, it looks the I called store procedure with incorrect parameters, and the error not related to column :

cstmt = (OracleCallableStatment) con.prepareCall('BEGIN SP_TEST(?,?,?,?,?,?,?,?)');

cstmt.setInt(1,40030485);

cstmt.setString(2,"filepath");

cstmt.setString(3,"%/temp/%");

cstmt.setString(4,"Y");

cstmt.registerOutParameter(5,OrcaleTypes.NUMBER);

cstmt.registerOutParameter(6,OrcaleTypes.DECIMAL);

cstmt.registerOutParameter(7,OrcaleTypes.VARCHAR);

cstmt.registerOutParameter(8,OrcaleTypes.CURSOR);


Tuesday, June 16, 2020

[Java][Example] Anonymous Object

public class Anony{
  private int x = 6;
  public static void main(String[] args){
    int x =4;
    new Anony().new Cell().doSth();
  }
  class Cell{
    coid doSth(){
      System.out.println("print key "+x);
    }
  }
}

The result is "print key 6".
line 5 "new Anony()" and "new Cell()" is the syntax to create anonymous object of Anony class and Cell class.

More example:
https://www.tutorialspoint.com/Anonymous-object-in-Java

Sunday, June 14, 2020

[Java][Netbean][Resolved] java.lang.ClassNotFoundException : com.mysql.jdbc.Driver

  1. Download jar file from internet, for mycase, it's mysql-connetior-java-5.1.25-bon.jar you can visit Orcale website to download: https://dev.mysql.com/downloads/connector/j/.
  2. Right click your project in solution explorer and select "properties"
  3. Click library in your right menu
  4. Click "complie" tab.
  5. Click Add "Jar/Folder", and then selection the jar you just download.
  6. Click "OK" button
Reference:
解决java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Tuesday, May 12, 2020

[Java][Resolved] StringBuilder cannot find symbol subString(int)

Problem Hint :
Cannot find symbol
Symbol: method substring(int)
location: class java.lang.StringBuilder

Run Time error msg:
Exceptiom in thread "main" javaa.lang.RuntimeException: Uncompilable source code at testb.Main.main (Main.java:17) Java Result:1

Source code:
public class Main {
 public static void main(String[] args) {
  StringBuilder s1 = new StringBuilder("Java");
                String s2 = "Love";
                s1.append(s2);
                s1.substring(4);
 }
}
Data type of s1 is StringBuilder, problem I face is an Compatible problem, there is substring method in 1.5 and later version but in StringBuilder but not in 1.5.

So what you do in 1.5version below is not trying to use substring() method in StringBuilder, you can inital a String and assign content in StringBuilder to that String, and use substring() method in String(). Or you can upgrade your Java verios yo 1.5 or above.

Reference:
https://javatutorialhq.com/java/lang/stringbuilder-class-tutorial/substring-method-example/

Monday, May 4, 2020

[Struts][Resolved] Iterator get data from List Array

Suppose you have a source with DataType List<Equip> named equipStatusList.
and there are some field named "code" and "desciption".
<s:iterator value-"equipStatusList" status="statusTitle">
  <th width>
    <div onclick="javascript:toggleSort('${equipStatusList[statusTitle.index].code}')">
      <s:property value="equipStatusList[#statusTitle.index].desciption" />
      <s:if test="%{sortBy[0]==equipStatusList[#statusTitle.index].code}">
        <s:if test='%{sortOrder=="asc"}'>
          &uArr;
        </s:if>
        <s:else>
          &dArr;
        </s:else>
      </s:if>
    </div>
  </th>
</s:iterator>

Wednesday, April 29, 2020

[Struts][Example] Iterator get data from List

Suppose you have a source with DataType List<Equip> named equipStatusList.and there are some field named "code" and "description".
This is an example of the struts iterator used in view with Spring framework:
<s:iterator value="equipStatusList" status="statusTitle">
  <div onclick="javascript:toggleSort('${equipStatusList[statusTitle.index].code}')">
    <s:property value="equipStatusList[#statusTitle.index].desciption" />
    <s:if test="%{sortBy[0]==equipStatusList[#statusTitle.index].code}">
      <s:if test='%{sortOrder=="asc"}'>
        &uArr;
      </s:if>
      <s:else>
        &dArr;
      </s:else>
    </s:if>
  </div>
</s:iterator>
index is used for get index of each iterator item.
and than use this index number to access your List item.

Reference:

https://struts.apache.org/tag-developers/iterator-tag.html

Tuesday, April 28, 2020

[Struts][Example] Iterator get data from array

You can use <s:property> assess items of Iterator,
or use .index to know the index for assisting get the item value.
Here is an example supposing you have a source with DataType int[] array named statusCounts.
<s:iterator value="statusCounts" status="count">
  <s:if test='%{statusCounts[#count.index]>0}'>
    <s:property>
  </s:if>
  <s:else>
    &nbsp;
  </s:else>
</s:iterator>
Reference:
https://struts.apache.org/tag-developers/iterator-tag.html
https://stackoverflow.com/questions/19856296/to-access-the-index-value-of-struts-iterator-in-scriptlet-array-index

Monday, April 27, 2020

[Java][Jasper][Resolved] jasper text field is blank when 0

[Java][Jasper][Resolved] jasper text field is blank when 0 Cannot found direct solution again but got a great idea from community of jaspersoft: It's by shrije :
"using an expression set zero to null value. and use "blank when null" option in text box."
For my case, suppose you defined a element named countA, with source data type java.lang.Integer. You have 2 things to do:
  1. Add isBlankWhenNull attrubute in your textField and set it as "true"
  2. Use a condition check in textFieldExpression element check if your field not 0, print null.
Example:
<textField isBlankWhenNull="true">
    <reportElement x="345" y="0" width="100" height="20" />
    <textElement textAlignment="Center" verticalAllignment="Middle">
        <font pdfFontname="MSung-light" pdfEncoding="UniCNS-UCS2-H" isPadfEmbedded="true" />
    </textElement>
    <textFieldExpression class="java.lang.Integer">
        $F{countA}.intValue()!=0?$F{countA}:null
    </textFieldExpression>
</textField>

Sunday, April 26, 2020

[Java][Jasper][Resolved] Incompatible conditional types Integer and int

Source code:
<textfieldexpression class="java.lang.Integer">
    {$F{erCount}>0?$F{erCount}:-1}
</textfieldexpression>
Correction:
<textfieldexpression class="java.lang.Integer">
    {$F{erCount}.intValue()>0?$F{erCount}:new Integer(-1)}
</textfieldexpression>
Remarks:
If you don't put that -1 into Integer construtor, you would get Incompatible conditional types Integer and int again.

Referecne:
https://community.jaspersoft.com/questions/536346/incompatible-operand-types-integer-and-int 

Saturday, April 25, 2020

[Java][Jasper][Resolved] Load array data source to detail

I searched for long time can't found the solution directly on internet, so I read the tutorialspoint pages and found element can be used.   Suppose you have a data source named "statusCounts" with type int[], and want to show the content in report: Firstly, you need to define element in element, put it into your field element list:
<field name="countA" class="java.lang.Integer">
    <fieldDescription><![CDATA[statusCounts[0]]]></fieldDescription>
</field>
<field name="countB" class="java.lang.Integer">
    <fieldDescription><![CDATA[statusCounts[1]]]></fieldDescription>
</field>
<field name="countC" class="java.lang.Integer">
    <fieldDescription><![CDATA[statusCounts[2]]]></fieldDescription>
</field>
And then call your field in detail element. In my example I put it into textFieldExpression elememt:
<textField>
    <reportElement x="345" y="0" width="100" height="20" />
    <textElement textAlignment="Center" verticalAllignment="Middle">
        <font pdfFontname="MSung-light" pdfEncoding="UniCNS-UCS2-H" isPadfEmbedded="true" />
    </textElement>
    <textFieldExpression class="java.lang.Integer">
        $F{countA}
    </textFieldExpression>
</textField>
<textField>
    <reportElement x="445" y="0" width="100" height="20" />
    <textElement textAlignment="Center" verticalAllignment="Middle">
        <font pdfFontname="MSung-light" pdfEncoding="UniCNS-UCS2-H" isPadfEmbedded="true" />
    </textElement>
    <textFieldExpression class="java.lang.Integer">
        $F{countB}
    </textFieldExpression>
</textField>
<textField>
    <reportElement x="545" y="0" width="100" height="20" />
    <textElement textAlignment="Center" verticalAllignment="Middle">
        <font pdfFontname="MSung-light" pdfEncoding="UniCNS-UCS2-H" isPadfEmbedded="true" />
    </textElement>
    <textFieldExpression class="java.lang.Integer">
        $F{countC}
    </textFieldExpression>
</textField>
Reference:
https://www.tutorialspoint.com/jasper_reports/jasper_report_fields.htm


Wednesday, April 8, 2020

[Java][Example] copy file

This is a simple method using FileInputStream and FileOutStream to copy file, you need to read the file content as bytes and use FileOutStream to write into a new file.

Remember import these package:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

Content:
try {
File sourceFile = new File("CCI29032020_2.jpg");
File newFile = new File("CCI29032020_2_new.jpg");
FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(newFile);
byte[] data = new byte[(int) sourceFile.length()];
fis.read(data);
fos.write(data);
fis.close();
fos.close();
}catch(IOException e) {
e.printStackTrace();
}

Tuesday, April 7, 2020

[Java][Exerise] Valid Palindrome

Method 1 - work method
class Solution {
    public boolean isPalindrome(String s) {
        if(s.isEmpty()) return true;
        String cleanStr = s.toLowerCase().replaceAll("[^a-z0-9]","");
        int end = cleanStr.length()-1;
        for(int start=0; start<(cleanStr.length()/2);start++){
            if(cleanStr.charAt(start)!=cleanStr.charAt(end))
                return false;
            end--;
        }
        return true;
    }
}

Method 2 - cleanest method
class Solution {
    public boolean isPalindrome(String s) {
        if(s.length() == 0) return true;
        StringBuilder sb = new StringBuilder(s.toLowerCase().replaceAll("[^a-z0-9]", ""));             
        return sb.toString().equals(sb.reverse().toString());
    }
}


method 3 - work method with replaceAll
class Solution {
    public boolean isPalindrome(String s) {
        if(s.isEmpty()) return true;
        String cleanStr = s.toLowerCase().replaceAll("[^a-z0-9]","");
        int start = 0;
        int end   = cleanStr.length()-1;
       
        while(start<end){
            if(cleanStr.charAt(start)!=cleanStr.charAt(end)){
                return false;
            }
            end--;
            start++;
        }
        return true;
    }
}

Method 4 - fast method without replaceAll
class Solution {
    public boolean isPalindrome(String s) {
        if(s.isEmpty()) return true;
        int start = 0;
        int end   = s.length()-1;
       
        while(start<end){
            char startChar = Character.toLowerCase(s.charAt(start));
            char endChar = Character.toLowerCase(s.charAt(end));
           
            if(!Character.isLetterOrDigit(startChar)){
                start++;
                continue;
            }
            if(!Character.isLetterOrDigit(endChar)){
                end--;
                continue;
            }
         if(startChar!=endChar){
                return false;
            }
            end--;
            start++;
        }
        return true;
    }
}


Method 5 - fast method checking with ascii code

From this table we can found the range of 0-9 us 48-57, and a-z are 97-122.
class Solution {
    public boolean isPalindrome(String s) {
        if(s.isEmpty()) return true;
        int start = 0;
        int end   = s.length()-1;
       
        while(start<end){
            int startChar = (int) Character.toLowerCase(s.charAt(start));
            int endChar   = (int) Character.toLowerCase(s.charAt(end));
           
            if(!((startChar>=48 && startChar<=57)||(startChar>=97 && startChar<=122))){
                start++;
                continue;
            }
            if(!((endChar>=48 && endChar<=57)||(endChar>=97 && endChar<=122))){
                end--;
                continue;
            }
         if(startChar!=endChar){
                return false;
            }
            end--;
            start++;
        }
        return true;
    }
}

Wednesday, April 1, 2020

[Java][Exerise] First Unique Character in a String

Method 1 (28s)
Use LinkedHaspMap Count occurance of Character in String
class Solution {
    public int firstUniqChar(String s) {
        if(s.length()==0) return -1;
        LinkedHashMap<Character, Integer> map = new LinkedHashMap<Character, Integer>();
        for(int i=0; i<s.length(); i++){
            char c = s.charAt(i);
            if(map.containsKey(c)){
                map.put(c,map.get(c)+1);
            }else{
                map.put(c,1);
            }
        }
        for(Character key: map.keySet()){
            Integer value = map.get(key);
            if(value == 1){
                return s.lastIndexOf(String.valueOf(key));
            }
        }
        return -1;
    }
}
Method 2 (7s)
This method faster than method 1 for 4 time.
class Solution {
    public int firstUniqChar(String s) {
        if(s.length()==0) return -1;
        int[] counts = new int[26];
        for(int i=0; i<s.length(); i++)
            counts[s.charAt(i)-'a']++;
        for(int i=0; i<s.length(); i++){
            if(counts[s.charAt(i)-'a'] == 1)
                return i;
        }
        return -1;
    }
}

Sunday, March 29, 2020

[Java][Resolved] String constructor invocation surriund with...


This is a warming by netbean and the warming message is :
String constructor invocation surround with...

source :
String s = new String("leg");


Since String class in immutable in Java and it's not memory efficient. To correct the warming, please remove the string constructor invocation and useconstructor argument directly.
String s = "leg";

Reference:
https://www.inf.unibz.it/~calvanese/teaching/05-06-ip/lecture-notes/uni02/node25.html
https://help.semmle.com/wiki/display/JAVA/Inefficient+String+constructor

Saturday, March 14, 2020

[Java][Exercise] Valid Anagram


Given two strings s and t, write a function to determine if t is an anagram of s.

Bad method 1
class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())
            return false;
       
        ArrayList<Character> chars = new ArrayList<Character>();
        for(char c:s.toCharArray()){
            chars.add(c);
        }
        for(int i=0; i< t.length(); i++){
            int index = chars.indexOf(t.charAt(i));
            if (index >= 0){
                chars.remove(index);
            }
        }
        return chars.isEmpty();
    }
}


Bad method 2 (same effectivity as method 1)
class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())
            return false;
        for(int i=0; i< t.length(); i++){
            int index = s.indexOf(t.charAt(i));
            if(index>=0){
                s = s.substring(0,index)+s.substring(index+1,s.length());
            }
        }
        return s.isEmpty();
    }
}

Better method
class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())
            return false;
        StringBuilder sb = new StringBuilder(s);
        for(int i=0; i< t.length(); i++){
            int index = sb.indexOf(Character.toString(t.charAt(i)));
            if(index>=0){
                sb.deleteCharAt(index);
            }
        }
        return sb.length()==0;
    }
}

Good method 1
class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())
            return false;
        char[] str1 = s.toCharArray();
        char[] str2 = t.toCharArray();
        Arrays.sort(str1);
        Arrays.sort(str2);
        return Arrays.equals(str1, str2);
    }
}

Good methods 2
public boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) {
        return false;
    }
    int[] counter = new int[26];
    for (int i = 0; i < s.length(); i++) {
        counter[s.charAt(i) - 'a']++;
        counter[t.charAt(i) - 'a']--;
    }
    for (int count : counter) {
        if (count != 0) {
            return false;
        }
    }
    return true;
}

Thursday, January 16, 2020

[Java][Exercise] Impletment of swap and bubble sort

Swap is a act of exchanging the values of the variables mutually. In this article, logic of swap will be used for exchange 2 values for using in bubble search, it will be used if a number bigger than folowing number.Here is the logic of swap function:
public class Main{
  public static void main(String[] args){
    int a = 9;
    int b = 5;
    int[] c = swap(a,b);
    System.out.println(a+":"+b);
    System.out.println(c[0]+":"+c[1]);
  }
  public static int[] swap(int arg1, int arg2){
    int temp = arg2;
    arg2 = arg1;
    arg1 = temp;
    return new int[]{arg1, arg2};
  }
}
Result:
9:5
5:9

By wiki defination, "bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted." To understand what is bubble sort, let have an example with 5 numbers, right now we have 5 numbers 9,8,7,6,5 in decreasing order, and want to sort them in in increasing order, how can we do that with bubble sort?

We would compare the first pair of 2 numbers (with index 0 and index 1), and swap(excahnge the valueables) them if first value bigger than latter one.and then repeat this action on next pair of 2 numbers (with index 1 and index 2) until the last number in this set is compared. If we using [9,8,7,6,5] as instance, there are 4 passes is required.

First pass
source  :   9,8,7,6,5
1st swap:   8,9,7,6,5
2nd swap:   8,7,9,6,5
3rd swap:   8,7,6,9,5
4th swap:   8,7,6,5,9

Second pass:
source  :   8,7,6,5,9
1st swap:   7,8,6,5,9
2nd swap:   7,6,8,5,9
3rd swap:   7,6,5,8,9

Third pass:
source  :   7,6,5,8,9
1st swap:   6,7,5,8,9
2nd swap:   6,5,7,8,9

Fourth pass:
source  :   6,7,5,8,9
1st swap:   5,6,7,8,9

The first for-loop is the passes for comparing each number item in source array.The second for-loop is for comparing each number item in a pass. Swap logic would applied in script inside these 2 for-loop to do in-place sorting:
public class Main{
  public static void main(String[] args){
    int[] arr = new int[]{9,8,7,6,5};
    System.out.println(Arrays.toString(bubbleSort(arr)));
  }
  public static int[] bubbleSort(int[] arr){
    for(int count=arr.length;1<count;count--){
      for(int i=1;i<arr.length;i++){
        if(arr[i-1]>arr[i]){
          int temp = arr[i-1];
          arr[i-1] = arr[i];
          arr[i] = temp;
          count++;
        }
      }
    }
    return arr;
  }
}
input : [9,8,7,6,5]
output: [5,6,7,8,9]

Reference

https://4xsc.com/java-swap/
https://en.wikipedia.org/wiki/Bubble_sort
https://en.wikipedia.org/wiki/In-place_algorithm
https://en.wikipedia.org/wiki/Swap_(computer_programming)

Monday, January 6, 2020

[Java][Example] Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.

Answer1 : Works but is a bad answer O(n^2)
Use a hashmap to store the indexs of nums1 and nums2 matched.
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
        ArrayList<Integer> arrList = new ArrayList<Integer>();
       
        for(int i=0; i<nums1.length; i++){
            for(int j=0; j<nums2.length; j++){
                if(nums1[i]==nums2[j]){
                    if(!hm.containsKey(i) && !hm.containsValue(j)){
                        hm.put(i, j);
                        arrList.add(nums1[i]);
                    }
                }
            }
        }
       
        int[] result = new int[arrList.size()];
        for(int i=0; i<arrList.size(); i++){
            result[i] = arrList.get(i);
        }
        return result;
    }
}

Better Solution O(n):
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i: nums1){
            if(map.containsKey(i)){
                map.put(i, map.get(i)+1);
            }else{
                map.put(i, 1);
            }
        }
        ArrayList<Integer> list = new ArrayList<Integer>();
        for(int i: nums2){
            if(map.containsKey(i)){
                if(map.get(i)>1){
                    map.put(i, map.get(i)-1);
                }else{
                    map.remove(i);
                }
                list.add(i);
            }
        }
        int[] result = new int[list.size()];
        int i =0;
        while(i<list.size()){
            result[i]=list.get(i);
            i++;
        }
        return result;
    }
}

Friday, January 3, 2020

[Java][Resolved] java arraylist remove by int value

public int singleNum(int[] nums) {
  ArrayList<Integer> al = new ArrayList<Integer>();
    for(int num: nums){
      if(!al.contains(num)){
        al.add(num);
      }else{
        al.remove(num);
      }
  }
  return al.get(0);
}

Run and get "IndexOutOfBoundsException" on al.remove(num);, this line call remove(int index) but not remove(Object o) so cause this error.

For instance, content of nums is new int[]{99,98}, and al.remove(99) means remove the item in ArrayList named al at index 99. This item not exist and exeception throws.
What we should do is cast variable num from privaitive type to an Integer object :
public int singleNum(int[] nums) {
  ArrayList<Integer> al = new ArrayList<Integer>();
    for(int num: nums){
      if(!al.contains(num)){
        al.add(num);
      }else{
        al.remove(Integer.valueOf(num));
      }
  }
  return al.get(0);
}

Reference
https://stackoverflow.com/questions/21795376/java-how-to-remove-an-integer-item-in-an-arraylist
https://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html)

[Java] A simple way to print array using toString() and deepToString()

By using these method of Arrays, no need use for loop to print array anymore !
===== (1) ======
Arrays.toString(boolean[] a)
Arrays.toString(byte[] a)
Arrays.toString(char[] a)
Arrays.toString(double[] a)
Arrays.toString(float[] a)
Arrays.toString(int[] a)
Arrays.toString[long[] a)
Arrays.toString[Object[] a)
Arrays.toString[short[] a)

This function returns string representation of the contents of the specified array.
The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings. You can use any primitive type array or object array as argument,  Returns "null" if a is null.
Example:
String[] fruits = new String[]{"Apple","Orange","Banana"};
System.out.println(Arrays.toString(fruits));

Result:
[Apple,Orange,Banana]

===== (2) ======
Arrays.deepToString(Object[] a)
This is a status method to returns a string representation of the "deep contents" of the specified array such as 2d array:
int[] cordinates = new int[]{{1,2},{3,4},{3,6}};
System.out.println(Arrays.deepToString(cordinates));

Result:
[[1,2],[1,3],[1,4]]

Reference:
https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html