Friday, December 16, 2011

SQL0575N View or materialized query table "SCHEMA.TABLE_NAME" cannot be used because it has been marked inoperative. SQLSTATE=51024

exceptionCOM.ibm.db2.jdbc.DB2Exception: [IBM][CLI Driver][DB2/SUN64] SQL0575N  View or materialized query table "SCHEMA.TABLE_NAME" cannot be used because it has been marked inoperative.  SQLSTATE=51024

OR

 51024(-575)[IBM][CLI Driver][DB2/SUN64] SQL0575N  View or materialized query table "SCHEMA.TABLE_NAME" cannot be used because it has been marked inoperative.  SQLSTATE=51024
 (0.45 secs)

If you get above exception in JAVA or while executing query in DB2, possible reason could be the view or materialized query table name has been marked inoperative because a table, view, alias, or privilege upon which it is dependent has been removed.

Please report this error to your database administrator so that they may grant privilege for that table, view or alias.

java.lang.IllegalArgumentException: Illegal pattern character 'AT'

I got below mentioned error, while trying to add characters other than pre defined date pattern.

Exception in thread "main" java.lang.IllegalArgumentException: Illegal pattern character 'AT'
    at java.text.SimpleDateFormat.compile(SimpleDateFormat.java:769)
    at java.text.SimpleDateFormat.initialize(SimpleDateFormat.java:576)
    at java.text.SimpleDateFormat.(SimpleDateFormat.java:501)
    at java.text.SimpleDateFormat.(SimpleDateFormat.java:476)

To add your desire Characters or String you need to by-pass it using escape sequence. Please see the correct syntax below. Note the escape character single quote ('), whatever you want to pass a Characters or String need to by-pass it using escape character single quote (').

Correct Syntax:

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdFormat =  new SimpleDateFormat("yyyy-MM-dd 'AT' hh:mm:ss");
String strDate = sdFormat.format(cal.getTime());
System.out.println("Now : "+strDate);

Output:

Now : 2011-12-16 AT 03:57:40

Thursday, December 15, 2011

A repository hook failed

A repository hook failed
svn: Commit blocked by pre-commit hook (exit code 1) with output:
Please enter a log message to commit

I got above error while commiting my changes into SVN repository. As the error suggest "Please enter a log message to commit". Make sure you enter a message for commiting. It expects a message to commit, make sure that the message box is not left blank.

CLI0611E Invalid column name. SQLSTATE=S0022

COM.ibm.db2.jdbc.DB2Exception: [IBM][JDBC Driver] CLI0611E  Invalid column name. SQLSTATE=S0022
    at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.rsException(Unknown Source)
    at COM.ibm.db2.jdbc.app.DB2ResultSet.findColumn(Unknown Source)
    at COM.ibm.db2.jdbc.app.DB2ResultSet.getString(Unknown Source)

As the get above error suggest, The column name specified in the Query or in resultSet is invalid.

resultSet.getString("COLUMN_NAME");

Please re-check all the column names against table name and make sure it is correct.

SQL1336N The remote host "serverX" was not found

Exception in thread "main" COM.ibm.db2.jdbc.DB2Exception: [IBM][CLI Driver] SQL1336N The remote host "serverX" was not found.

at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.throw_SQLException(Unknown Source)
at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.check_return_code(Unknown Source)
at COM.ibm.db2.jdbc.app.DB2Connection.connect(Unknown Source)
at COM.ibm.db2.jdbc.app.DB2Connection.(Unknown Source)
at COM.ibm.db2.jdbc.app.DB2Driver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)

If you get above error, one possible reason could be the alias name used could be pointing to wrong database server.

Connection con=DriverManager.getConnection("jdbc:db2:ALIASNAME","username","password");

In my case ALIASNAME was required to point serverX but it was referring to serverY. I knew the solution but I did not know how to do it. I asked my database administrator (DBA) to have a look at the issue. What he told me is, he has to uncatalog and catalog it with the correct server.

Truly speaking I don’t know the meaning of these terms "uncatalog and catalog", I asked him let me know the solution as this issue may arise in future too. He told as i am a programmer, i cannot do the task which a DBA can do... Is it really?

So dear friends I may disappoint you and I apologize for that. But if this is the case with yours please contact with your database administrator.
 

Java : Simple way to get UTC/GMT date-time

In Java when you create a new Date OR Calendar object, it is initialized to the current time but in the local timezone where the program is running. For example, for a program running in India, creates a TimeZone object based on Indian Standard Time.

In your java carrier you may need to get an UTC time (Coordinated Universal Time) or GMT time (Greenwich Mean Time). For this java provides a simple class known as TimeZone, which help us to get date/time from any geographical region accross the globe. All you need to do is pass correct time zone abbreviation.

To know more about TimeZone, see API.

Below are the examples of few time zone abbreviations

AbbrNameUTC offset
AKSTAlaska Standard TimeUTC−09
ASTAtlantic Standard TimeUTC−04
CETCentral European TimeUTC+01
CTChina TimeUTC+08
ISTIndian Standard TimeUTC+05:30
SGTSingapore TimeUTC+08
UTCCoordinated Universal TimeUTC

Get list of all time zone abbreviations, click here.

/* UTCDates.java */

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

public class UTCDates {

    public static void main(String[] args) {
   
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdFormat =  new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
        String strDate;
       
        sdFormat.setTimeZone(TimeZone.getDefault());
        strDate = sdFormat.format(cal.getTime());
        System.out.println("Now : "+strDate);
       
        sdFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        strDate = sdFormat.format(cal.getTime());
        System.out.println("UTC : "+strDate);
    }

}

Output :

Now : 2011-12-15T05:25:22
UTC : 2011-12-15T11:55:22


Also Apache provides us an API to do this. To know more about it, click here.


You need to download commons-lang-x.x.jar and set it in classpath for example commons-lang-2.1.jar file.
To download commons-lang-x.x.jar, click here.

/* UTCDates.java */

import java.util.Calendar;

import org.apache.commons.lang.time.DateFormatUtils;

public class UTCDates {

    public static void main(String[] args) {
       
        Calendar cal = Calendar.getInstance();
        String strDate;       
       
        strDate = DateFormatUtils.ISO_DATETIME_FORMAT.format(cal.getTime());
        System.out.println("Now : "+strDate);
       
        strDate = DateFormatUtils.formatUTC(cal.getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern());
        System.out.println("UTC : "+strDate);
    }

}

More formats

FastDateFormatPattern
ISO_DATETIME_FORMATyyyy-MM-dd'T'HH:mm:ss
ISO_DATETIME_TIME_ZONE_FORMATyyyy-MM-dd'T'HH:mm:ssZZ
ISO_DATE_FORMATyyyy-MM-dd
ISO_DATE_TIME_ZONE_FORMATyyyy-MM-ddZZ
ISO_TIME_FORMAT'T'HH:mm:ss
ISO_TIME_TIME_ZONE_FORMAT'T'HH:mm:ssZZ
ISO_TIME_NO_T_FORMATHH:mm:ss
ISO_TIME_NO_T_TIME_ZONE_FORMATHH:mm:ssZZ
SMTP_DATETIME_FORMATEEE, dd MMM yyyy HH:mm:ss Z

Friday, December 9, 2011

SQL0206N, SQL0180N & SQL0408N

I observed below mentioned error while working with DB2 query.

Error :
 S0022(-206)[IBM][CLI Driver][DB2/SUN64] SQL0206N  "2" is not valid in the context where it is used.  SQLSTATE=42703
 (0.58 secs)

Solution :
This error occurs when u try to compare OR assign values of different datatypes. For example COUNT = '2' will throw above error because COUNT is INT and you are trying to assing STRING to it. To avoid above error make sure datatypes are correct.

Error :

  22007(-180)[IBM][CLI Driver][DB2/SUN64] SQL0180N  The syntax of the string representation of a datetime value is incorrect.  SQLSTATE=22007
 (0.73 secs)

Solution :

This error occurs when working with DATETIME datatypes. Usually when assigning or comparing STRING to a DATETIME value.

If you need to compare / assign a STRING to DATETIME use below syntax.

DATETIME_VARIABLE = TIMESTAMP ('2011-12-08-15.49.26.000625')

Error :
  22005(-408)[IBM][CLI Driver][DB2/SUN64] SQL0408N  A value is not compatible with the data type of its assignment target.  Target name is "DATETIME_VARIABLE".  SQLSTATE=42821
 (0.48 secs)


To convert a character string to a date or time value, you can use:

TIMESTAMP ('2002-10-20 12:00:00')
DATE ('2002-10-20')
DATE ('10/20/2002')
TIME ('12:00:00')
TIME ('12.00.00')

The TIMESTAMP(), DATE() and TIME() functions accept many other formats.

Wednesday, December 7, 2011

java.io.FileNotFoundException: log4j.xml (No such file or directory)

If you get below mentioned error

log4j:ERROR Could not parse url [file:log4j.xml].
java.io.FileNotFoundException: log4j.xml (No such file or directory)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.(FileInputStream.java:106)
        at java.io.FileInputStream.(FileInputStream.java:66)
        at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:70)
        at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:161)
        at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
        at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
        at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
        at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
        at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:180)
        at org.apache.log4j.xml.DOMConfigurator$2.parse(DOMConfigurator.java:612)
        at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:711)
        at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:618)
        at org.apache.log4j.helpers.OptionConverter.selectAndConfigure(OptionConverter.java:470)
        at org.apache.log4j.LogManager.(LogManager.java:122)
        at org.slf4j.impl.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:73)
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:242)
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:254)
        at org.quartz.impl.StdSchedulerFactory.(StdSchedulerFactory.java:274)

Possible reason could be JVM is not able to find the provided file log4j.xml. Make sure the file is present in the location and You could pass the file in command line as shown below.

java -Dlog4j.configuration=file:/home/log4j.xml com.TestJava

OR add directly in your Java code.

System.setProperty("log4j.configuration", "/home/log4j.xml");

If you are using Eclipe IDE you can pass through VM arguments by steps shown below

Right click on Java -> Run As -> Run Configurations.. -> Arguments tab -> VM arguments

add the below code

-Dlog4j.configuration=file:/home/log4j.xml

Apply -> Run

SQLSTATE=42501

If you get below mentioned error for DB2

42501(-551)[IBM][CLI Driver][DB2/SUN64] SQL0551N  "USER" does not have the privilege to perform operation "SELECT" on object "SCHEMA.TABLE_NAME".  SQLSTATE=42501 (0.48 secs)

As the error suggest your SQL administrator has not given privilege to perform SELECT operation on the particular table / View. Contact your SQL administrator and ask to grant privilege to perform operations on the table.

Invalid SQL syntax. SQLSTATE=37000

If you get below mentioned error for DB2

37000(-99999)[IBM][CLI Driver] CLI0118E  Invalid SQL syntax. SQLSTATE=37000 (0.03 secs)

As the error suggest, There could be a syntax error in the SQL. Please make sure that all the syntax for the SQL query is correct. Cross check for the syntax error.

Unresolved compilation problem

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Unhandled exception type Exception

A java file cannot be ran unless and until it is compilation error free. JVM compiler understands any syntax error or compile time error before it could create runable byte code (.class file). Hence JVM can run a java program only after successful compilation. Look for the compile time error if you get above error.

JVM will run the code no matter if there is any run time exception. If there is any run time exception that will handled at run time accordingly. You must ensure that atleast a code do not contains any syntax error and is compileable.

How to solve compile error?

Solving compilation error is very simple, all you need to do is follow all rules and regulation of JVM. To solve compilation error you need to check for Syntax error, Scope of a variable, Non reachable statements, Exceptions handling etc

Solving compilation error is simple because it can be viewed. A simple Google search can solve your compilation error. Also IDEs like Eclipse, NetBeans etc has advance features which can show any compile error while wring the code itself i.e. before even compilation.

How to solve run time error/exceptions?

My personal experience says solving a RUN time error could me very tough in some cases. You may even require to spend overnight to solve a simple run time exceptions because it cannot be viewed by compiler. In most cases there is a data issue. Run time exception could be simply a null pointer exception which occurs because the object is null.

Example :

Code
System.out.println(tempStr.trim());
Can throw
Exception in thread "main" java.lang.NullPointerException
because tempStr is null.

The answer to the above question is debugging i.e. try to debug your code. Put logs wherever you doubt for the values. In the above example if you print the value of tempStr you will recognize the root cause of the exception. Also try to put exception handling codes i.e. try { .. } catch (Exception ex) {..} wherever you doubt for the values.

Source File Declaration Rules in Java


C:\folder>javac test.java
test.java:9: class Test is public, should be declared in a file named Test.java
public class test
       ^
1 error

The above error appeared because the source file declaration rules in java says that If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Test { } must be in a source code file named Test.java. Also note that in Java everything is case-sensitive hence test and Test are treated as two different things.

Below are the rules associated with declaring classes, import statements, and package statements in a source file.

  • There can be only one public class per source code file.
  • Comments can appear at the beginning or end of any line in the source code file; they are independent of any of the positioning rules discussed here.
  • If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Test { } must be in a source code file named Test.java.
  • If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present.
  • If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn't a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements, the class declaration must be the first line in the source code file.
  • import and package statements apply to all classes within a source code file. In other words, there's no way to declare multiple classes in a file and have them in different packages, or use different imports.
  • A file can have more than one nonpublic class.
  • Files with no public classes can have a name that does not match any of the classes in the file

How to send mail using MAILX command in UNIX / LINUX

Simple MAILX command

Below is the syntax to send simple mail using mailx command in UNIX / Linux.
You can use it as command line or used it in your shell script.


$ mailx -s "Mail Subject" test@xyz.com
type body of the mail
...
..
EOT (Ctrl+d)
$

Send attachment using MAILX command

In some cases you may have to send attachment in the mail. Lets see the syntax of sending an attachment using mailx command.

Below is the syntax to attach a file while sending a mail using mailx command in LINUX / UNIX


( cat /root/MailBody.txt
uuencode /root/file_name.txt file_name.txt 
) | mailx -s "Mail Subject" test@xyz.com


Here file_name.txt is the attachment to be attached in the mail
AND MailBody.txt is the text body of the mail.

Simple Cryptography example in Java

The Java security APIs span a wide range of areas, including cryptography, public key infrastructure, secure communication, authentication, and access control. Java security technology provides the developer with a comprehensive security framework for writing applications, and also provides the user or administrator with a set of tools to securely manage applications.
Source : http://www.oracle.com/technetwork/java/javase/tech/index-jsp-136007.html

javax.crypto.Cipher
This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework.
Cipher API : http://docs.oracle.com/javase/6/docs/api/javax/crypto/Cipher.html

Cipher: initialized with keys, these used for encrypting/decrypting data. There are various types of algorithms: symmetric bulk encryption (e.g. AES, DES, DESede, Blowfish, IDEA)
http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html

Blowfish 
Blowfish has a 64-bit block size and a variable key length from 1 bit up to 448 bits
Blowfish Wiki : http://en.wikipedia.org/wiki/Blowfish_%28cipher%29

To run this example you will need below mentioned JAR files in classpath.
jce.jar
rt.jar


If you are using JDK 6 or higher version, These JAR files are implicitly present. You can cross verify in JRE folder. Probably in "C:\Program Files\Java\jre6\lib"

Hence C:\Program Files\Java\jre6\lib\jce.jar and C:\Program Files\Java\jre6\lib\rt.jar are implicitly set in your classpath.

Below is the sample self explanatory Java program using Blowfish Cipher. Directly you can run the program and see output.

Simple Blowfish Cipher Example in java

/* SimpleCryptography.java */

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class SimpleCryptography {
    
    private String AlgoName = "Blowfish";
    
    private String keyString = "DesireSecretKey";
    
    public String encrypt(String sValue) throws Exception {
        
        SecretKeySpec skeySpec = new SecretKeySpec(keyString.getBytes(), AlgoName);
        Cipher cipher = Cipher.getInstance(AlgoName);
        
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        
        byte[] encrypted = cipher.doFinal(sValue.getBytes());
        
        BASE64Encoder bASE64Encoder = new BASE64Encoder();
        String enStr = bASE64Encoder.encodeBuffer(encrypted);    
        
        return enStr;
    }
    
    public String decrypt(String sValue) throws Exception {
        
        SecretKeySpec skeySpec = new SecretKeySpec(keyString.getBytes(), AlgoName);
        Cipher cipher = Cipher.getInstance(AlgoName);
        
        BASE64Decoder bASE64Decoder = new BASE64Decoder();
        byte decrytByt[] = bASE64Decoder.decodeBuffer(sValue);
        
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        
        byte decrypted[] = cipher.doFinal(decrytByt);
        
        String deStr = new String(decrypted).trim();
        
        return deStr;
    }
    
    public static void main(String[] args) throws Exception {
        
        SimpleCryptography obj = new SimpleCryptography();
        
        String password = "MadanChaudhary";
        
        System.out.println("password : "+password);
        
        String encrypted_password = obj.encrypt(password);
        
        System.out.println("encrypted_password : "+encrypted_password);
        
        String decrypted_password = obj.decrypt(encrypted_password);
        
        System.out.println("decrypted_password : "+decrypted_password);

    }
}

Output :

password : MadanChaudhary
encrypted_password : 0LpwIuI0V+44sbZ5w3CCZw==

decrypted_password : MadanChaudhary

Below are the known Errors and exceptions I observed while writing this program.

1.
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)

2.
java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)

3.
java.security.NoSuchAlgorithmException: Cannot find any provider supporting MyAlgo
    at javax.crypto.Cipher.getInstance(DashoA13*..)
Exception in thread "main" java.security.NoSuchAlgorithmException: Cannot find any provider supporting MyAlgo
    at javax.crypto.Cipher.getInstance(DashoA13*..)

4.
java.security.InvalidKeyException: Invalid key length: 16 bytes
    at com.sun.crypto.provider.DESCipher.engineGetKeySize(DashoA13*..)
    at javax.crypto.Cipher.b(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
Exception in thread "main" java.security.InvalidKeyException: Invalid key length: 16 bytes
    at com.sun.crypto.provider.DESCipher.engineGetKeySize(DashoA13*..)
    at javax.crypto.Cipher.b(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)

5.
java.security.NoSuchAlgorithmException: Cannot find any provider supporting DSA
    at javax.crypto.Cipher.getInstance(DashoA13*..)
Exception in thread "main" java.security.NoSuchAlgorithmException: Cannot find any provider supporting DSA
    at javax.crypto.Cipher.getInstance(DashoA13*..)

6.
javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)

7.
java.lang.IllegalStateException: Cipher not initialized
    at javax.crypto.Cipher.c(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)
Exception in thread "main" java.lang.IllegalStateException: Cipher not initialized
    at javax.crypto.Cipher.c(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)

8.
Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)


9. Warnings

$javac SimpleCryptography.java

SimpleCryptography.java:6: warning: sun.misc.BASE64Decoder is Sun proprietary API and may be removed in a future release
import sun.misc.BASE64Decoder;
               ^
SimpleCryptography.java:7: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
import sun.misc.BASE64Encoder;
               ^
SimpleCryptography.java:24: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
        BASE64Encoder bASE64Encoder = new BASE64Encoder();
        ^
SimpleCryptography.java:24: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
        BASE64Encoder bASE64Encoder = new BASE64Encoder();
                                          ^
SimpleCryptography.java:35: warning: sun.misc.BASE64Decoder is Sun proprietary API and may be removed in a future release
                BASE64Decoder bASE64Decoder = new BASE64Decoder();
                ^
SimpleCryptography.java:35: warning: sun.misc.BASE64Decoder is Sun proprietary API and may be removed in a future release
                BASE64Decoder bASE64Decoder = new BASE64Decoder();
                                                  ^
6 warnings

Friday, December 2, 2011

A pseudo attribute name is expected.

If you get below mentioned error

[Fatal Error] :1:54: A pseudo attribute name is expected.
Exception in thread "main" org.xml.sax.SAXParseException: A pseudo attribute name is expected.
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)

Possible reason could be the version and encoding information provided is not formatted correctly.
Please used the below syntax and try again.

?>

Note the ? at the end, I have missed that and it gave above error.

XML document structures must start and end within the same entity.

If you get below mentioned error

[Fatal Error] :1:7717: XML document structures must start and end within the same entity.
Exception in thread "main" org.xml.sax.SAXParseException: XML document structures must start and end within the same entity.
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)

As the error suggest XML document is not formatted properly. Kindly go through the XML and look for any missing tags.

Indenting XML Output in Java

Here is a simple JAVA program for Indenting / Formatting a long XML string. You can provide a XML as a string OR can provide XML from a file according to your requirement.

Formatting an XML can be useful for reading or just simply pretty printing it.

Here is a complete tested code you can directly run the program and see the output.

/* IndentXML.java */

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class IndentXML {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, TransformerException
    {
       
        //get the factory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
       
        //Using factory get an instance of document builder
        DocumentBuilder db = dbf.newDocumentBuilder();
       
        //providing XML string to be indented
       
String xmlStringToIndent = "<AllEmployee><Employee><Name>Ram</Name><Designation>Programmer</Designation><Department>Development</Department></Employee><Employee><Name>Shyam</Name><Designation>TL</Designation><Department>Finanace</Department></Employee><Employee><Name>Geeta</Name><Designation>Manager</Designation><Department>HR</Department></Employee></AllEmployee>";
       
        //converting String to InputStream
        InputStream inStr = new ByteArrayInputStream(xmlStringToIndent.getBytes());
       
        Document doc = db.parse(inStr);
       
        //Output file
        File outputFile = new File("c:/indentedOutputXmlFile.xml");
        OutputStream outSrc = new FileOutputStream(outputFile);
       
        //creating a transformer
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer  = transFactory.newTransformer();
       
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
       
        transformer.transform(new DOMSource(doc), new StreamResult(outSrc));
       
        System.out.println("OutputFile created sucessfully!! "+outputFile.getPath());

    }

}


Input XML

String xmlStringToIndent = "<AllEmployee><Employee><Name>Ram</Name><Designation>Programmer</Designation><Department>Development</Department></Employee><Employee><Name>Shyam</Name><Designation>TL</Designation><Department>Finanace</Department></Employee><Employee><Name>Geeta</Name><Designation>Manager</Designation><Department>HR</Department></Employee></AllEmployee>";


Output XML

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<AllEmployee>
     <Employee>
          <Name>Ram</Name>
          <Designation>Programmer</Designation>
          <Department>Development</Department>
     </Employee>
     <Employee>
          <Name>Shyam</Name>
          <Designation>TL</Designation>
          <Department>Finanace</Department>
     </Employee>
     <Employee>
          <Name>Geeta</Name>
          <Designation>Manager</Designation>
          <Department>HR</Department>
     </Employee>
</AllEmployee>



 Note :

If you are passing XML string and it contains double quotes ("). Make to to bypass it by adding backward slash (\").

I observer below mentioned error when the string contained space in the beginning as show below.

String xmlStringToIndent = " <AllEmployee><Employee><Name>Ram</Name><Designation>Programmer ....."

Note the space in the beginning of the string. Make sure your XML is formatted properly.

Error

[Fatal Error] :1:7: The processing instruction target matching "[xX][mM][lL]" is not allowed.
Exception in thread "main" org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
    at com.hewitt.hre.fadv.IndentXML.main(IndentXML.java:43)

Friday, November 25, 2011

SQLSTATE=42903

 I was in need to pass a max value in where condition. My folly, what i did is :

Incorrect : Select * from table_name where field = MAX(field);




Got below mentioned error in DB2

  42903(-120)[IBM][CLI Driver][DB2/SUN64] SQL0120N  Invalid use of an aggregate function or OLAP function.  SQLSTATE=42903
 (0.47 secs)

Correct :

Correct way is Inline Query

Select * from table_name where files = (Select MAX(filed) from table_name);

SQLSTATE=42601

 I was in need to fetch top n rows from a particular table in DB2. I got below mentioned error when tried with some incorrect syntax.

 42601(-104)[IBM][CLI Driver][DB2/SUN64] SQL0104N  An unexpected token "1" was found following "Select TOP ".  Expected tokens may include:  "".  SQLSTATE=42601
 (0.45 secs)

Correct Syntax :

Select * from table_name where filed = 'Some condition' order by field FETCH FIRST 10 ROWS ONLY;

SQLSTATE=42807

I got below mentioned error while updating a View in DB2.

 42807(-150)[IBM][CLI Driver][DB2/SUN64] SQL0150N  The target fullselect, view, typed table, materialized query table, or staging table in the INSERT, DELETE, UPDATE, or MERGE statement is a target for which the requested operation is not permitted.  SQLSTATE=42807

As the error suggest administrator have not given update permission to the user. Ask administrator to give access, else it would not be possible.

Tuesday, November 15, 2011

Step by step guide to install MySQL



Step 1. Download MySQL Installer (mysql-advanced-5.5.8-win32.msi) file from the website of MySQL 




Go to URL http://www.mysql.com/downloads/mysql/

MySQL Installer provides an easy to use, wizard-based installation experience for all your MySQL software needs. Included in the product are the latest versions of:

MySQL Server
All of our support connectors
Workbench and sample models
Sample databases
Documentation


Step 2. After downloading  the installer file e.g mysql-advanced-5.5.8-win32.msi

Open the file. It will start installer wizard. Please go throw the screen shot below.

Mostly you do not have to change the default setting, just continue with the wizard.








At this point, Note the port number. Default port number is 3306, If you wish you could change it else let go by default port number.




At this point, put password for security and note that password for login latter.


You are almost done...


Step 3. Now that MySQL is installed, You can confirm it by login to it.

Try through  Start - All programms - My SQL.

If you cannot start the server through  Start - All programms - My SQL

The best way to login without any problem is.
Go to command prompt. The folder where MySQL is installed.
Probably Program Files\MySQL\MySQL Server 5.5\bin
Use Command : mysql -u root -p
Put the password and you are in the database.



DB2 : Get all column name of a particular Table

Query :


SELECT TABNAME,COLNAME from SYSCAT.COLUMNS where TABNAME='table_name'


You can use above mentioned query for getting all column name of a particular table in DB2.

Could not determine current working directory

If you get below mentioned error



Error occurred during initialization of VM
java.lang.Error: Properties init: Could not determine current working directory.
        at java.lang.System.initProperties(Native Method)
        at java.lang.System.initializeSystemClass(System.java:1070)


There could be two possible reasons.

1. You have not set the proper classpath, If this the case then make sure you set JAVA_HOME path in class path.

2.  You do not have the permission to start the java process in that directory, Simply ask your UNIX / LINUX administrator to grant the access.

Also you can try running the java process from your home directory.


Connection authorization failure occurred. Reason: User ID or Password invalid.

If you get below mentioned error


Exception in thread "main" com.ibm.db2.jcc.b.bo: [jcc][t4][2013][11249][3.53.95]
 Connection authorization failure occurred.  Reason: User ID or Password invalid. ERRORCODE=-4214, SQLSTATE=28000
        at com.ibm.db2.jcc.b.bd.a(bd.java:674)
        at com.ibm.db2.jcc.b.bd.a(bd.java:60)
        at com.ibm.db2.jcc.b.bd.a(bd.java:120)
        at com.ibm.db2.jcc.t4.b.o(b.java:2018)
        at com.ibm.db2.jcc.t4.b.c(b.java:1646)
        at com.ibm.db2.jcc.t4.bb.r(bb.java:793)
        at com.ibm.db2.jcc.t4.bb.k(bb.java:349)
        at com.ibm.db2.jcc.t4.bb.c(bb.java:133)
        at com.ibm.db2.jcc.t4.b.Oc(b.java:1271)
        at com.ibm.db2.jcc.t4.b.b(b.java:1192)
        at com.ibm.db2.jcc.t4.b.B(b.java:5098)
        at com.ibm.db2.jcc.t4.b.c(b.java:750)
        at com.ibm.db2.jcc.t4.b.b(b.java:693)
        at com.ibm.db2.jcc.t4.b.a(b.java:376)
        at com.ibm.db2.jcc.t4.b.(b.java:312)
        at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:214)
        at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:224)
        at java.sql.DriverManager.getConnection(Unknown Source)
        at java.sql.DriverManager.getConnection(Unknown Source)


As the error suggest, The login credentials are not matching. Please make sure that user name and password are correct.

Also check for correct URL. Make sure that all login credentials are correct.

Connection authorization failure occurred. Reason: Security mechanism not supported. ERRORCODE=-4214, SQLSTATE=28000

If you get mentioned error



Exception in thread "main" com.ibm.db2.jcc.b.bo: [jcc][t4][201][11237][3.53.95]
Connection authorization failure occurred.  Reason: Security mechanism not supported. ERRORCODE=-4214, SQLSTATE=28000
        at com.ibm.db2.jcc.b.bd.a(bd.java:674)
        at com.ibm.db2.jcc.b.bd.a(bd.java:60)
        at com.ibm.db2.jcc.b.bd.a(bd.java:120)
        at com.ibm.db2.jcc.t4.b.o(b.java:1981)
        at com.ibm.db2.jcc.t4.b.a(b.java:1554)
        at com.ibm.db2.jcc.t4.bb.b(bb.java:3405)
        at com.ibm.db2.jcc.t4.bb.a(bb.java:332)
        at com.ibm.db2.jcc.t4.bb.a(bb.java:112)
        at com.ibm.db2.jcc.t4.b.l(b.java:1247)
        at com.ibm.db2.jcc.t4.b.b(b.java:1120)
        at com.ibm.db2.jcc.t4.b.c(b.java:707)
        at com.ibm.db2.jcc.t4.b.b(b.java:693)
        at com.ibm.db2.jcc.t4.b.a(b.java:376)
        at com.ibm.db2.jcc.t4.b.(b.java:312)
        at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:214)
        at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:224)
        at java.sql.DriverManager.getConnection(Unknown Source)
        at java.sql.DriverManager.getConnection(Unknown Source)


As the error suggest, You are not authorized to access the database. I am not sure on this, possibly this could be the one reason for the above error.


Try using different Driver,


I was using DB2 Universal Driver, when i got above error

Class.forName("com.ibm.db2.jcc.DB2Driver");
con=DriverManager.getConnection("jdbc:db2://hostname:port/Schema","username","password");

Jar file : db2jcc.jar


I switched to App JDBC Driver, and it solved the error.

Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
con=DriverManager.getConnection("jdbc:db2:Test","uername","passowrd");

Jar file : db2java.jar


To download Jar files : Click here

If still you face the issue, contact your server administrator.

DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704

If you get below mentioned error


Exception in thread "main" com.ibm.db2.jcc.b.eo: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=SCHEMA.TABLE_NAME, DRIVER=3.53.95
        at com.ibm.db2.jcc.b.bd.a(bd.java:676)
        at com.ibm.db2.jcc.b.bd.a(bd.java:60)
        at com.ibm.db2.jcc.b.bd.a(bd.java:127)
        at com.ibm.db2.jcc.b.gm.c(gm.java:2484)
        at com.ibm.db2.jcc.b.gm.d(gm.java:2461)
        at com.ibm.db2.jcc.b.gm.a(gm.java:1962)
        at com.ibm.db2.jcc.t4.db.g(db.java:138)
        at com.ibm.db2.jcc.t4.db.a(db.java:38)
        at com.ibm.db2.jcc.t4.t.a(t.java:32)
        at com.ibm.db2.jcc.t4.sb.h(sb.java:141)
        at com.ibm.db2.jcc.b.gm.bb(gm.java:1933)
        at com.ibm.db2.jcc.b.gm.a(gm.java:2799)
        at com.ibm.db2.jcc.b.gm.a(gm.java:604)
        at com.ibm.db2.jcc.b.gm.executeQuery(gm.java:588)

Possible reason could be Table do not present in that schema. Please make sure that you provide correct schema name and table name. Also check for typo in Table name or Schema name.

I got the above error when i mistakenly passed wrong table name for the schema. Hope it resolved your error.

Exception java.net.ConnectException: Error opening socket to server

If you get below mentioned error

Exception in thread "main" com.ibm.db2.jcc.b.un: [jcc][t4][2043][11550][3.53.95] Exception java.net.ConnectException: Error opening socket to server hostname/10.10.5.5 on port 3,934 with message: Connection timed out. ERRORCODE=-4499, SQLSTATE=08001
        at com.ibm.db2.jcc.b.bd.a(bd.java:319)
        at com.ibm.db2.jcc.b.bd.a(bd.java:337)
        at com.ibm.db2.jcc.t4.xb.a(xb.java:378)
        at com.ibm.db2.jcc.t4.xb.(xb.java:76)
        at com.ibm.db2.jcc.t4.a.x(a.java:263)
        at com.ibm.db2.jcc.t4.b.a(b.java:1789)
        at com.ibm.db2.jcc.b.jb.a(jb.java:530)
        at com.ibm.db2.jcc.b.jb.(jb.java:486)
        at com.ibm.db2.jcc.t4.b.(b.java:310)
        at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:214)
        at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:224)
        at java.sql.DriverManager.getConnection(DriverManager.java:582)
        at java.sql.DriverManager.getConnection(DriverManager.java:185)
Caused by: java.net.ConnectException: Connection timed out
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
        at java.net.Socket.connect(Socket.java:529)
        at com.ibm.db2.jcc.t4.y.run(y.java:34)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.ibm.db2.jcc.t4.xb.a(xb.java:372)
        ... 11 more


As the error suggest, The database server's port is not open to establish connection with your server or local machine hence it is throwing Socket error. Just verify this error by using Telnet command, If this is the case then contact your server administrator to open the port on the destination server.

I am not sure on this, possibly this could be the one reason for the above error.