Wednesday, October 28, 2009

Problem !!! java.lang.ClassNotFoundException: [Ljava.lang.String

This, java.lang.ClassNotFoundException: [Ljava.lang.String is killing me a lot. I've suspected so many things about it, but actually is quite different. Its also mentioned in sun's bug database

Here are some of the solutions i've found in different sites;

1.http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434149

This link recommends the following actions to solve this bug:

1) Add -Dsun.lang.ClassLoader.allowArraySyntax=true if you want to use a
library for which you don't have the source with JDK6

2) Change loader.loadClass( name ) to Class.forName( name, false, loader ) if
you own the code.

class org.apache.catalina.loader.WebAppClassLoader
uses this code to load classes:

clazz = loader.loadClass(name);

Can you please change the sections of code where this line is used (1352 and
others) to
clazz = Class.forName( name, false, loader);



2. http://dev.bostone.us/2009/02/23/javaxfacesfacesexception-javalangclassnotfoundexception-ljavalangstring/
  • jdk1.6 unlike 1.5 it will not attempt to load class (java.lang.String) by name by default
  • it is easily solvable by locating JVM runtime in Eclipse's preferences (Window->Preferences->Installed JREs), highlighting the entry and adding runtime parameter -Dsun.lang.ClassLoader.allowArraySyntax=true
links:
  • https://blog.coremedia.com/cm/post/2672591/RE_Java_6_javalangClassNotFoundException_LjavalangString_exception.html
  • http://forums.java.net/jive/thread.jspa?threadID=15823

Sunday, October 11, 2009

A simple secure MIME message SendMail function

Here is a simple secure MIME message sendMail function;


public boolean sendMail(String to, String subject, String text) {

Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", Constants.SMTP_HOST_NAME);
props.put("mail.smtp.port", Constants.SMTP_HOST_PORT);
props.put("mail.smtp.auth", "true");

Authenticator auth = new SMTPAuthenticator();

Session mailSession = Session.getInstance(props, auth);

try{
Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(Constants.SMTP_MESSAGE_SENDER));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(subject);
message.setHeader("MIM9
message.setHeader("Content-Type", "text/html");
message.setContent(text, "text/html");

transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
return true;
} catch (MessagingException messagingException) {
messagingException.printStackTrace();
return false;
} catch (Exception exception){
exception.printStackTrace();
return false;
}


}

private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = Constants.SMTP_AUTH_USER;
String password = Constants.SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}

Friday, August 28, 2009

Oracle Sequence ID increase by double

if you are using trigger to generate sequence then might happened that the trigger is called twice. So to prevent from increasing the id value here is a little trick

CREATE OR REPLACE TRIGGER TRG_ABC BEFORE INSERT ON ABC
FOR EACH ROW
BEGIN
if :NEW.ID is null
then SELECT ABC_SEQ.NEXTVAL INTO :NEW.ID FROM DUAL;
end if;
END;

Thursday, August 27, 2009

Oracle: use timestamp to convert string to date


You can use the timestamp keyword to convert a string to Date:

select * from retail_transactions where posted_date >= timestamp '2008-12-01 00:00:00';

Monday, July 20, 2009

How to convert String date into Date obj

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

try
{
Date today = df.parse("10/12/2009"); //converts String object into Date Object
System.out.println("Today = " + df.format(today)); //formats the Date object accourding to the format mentioned above
} catch (ParseException e)
{
e.printStackTrace();
}

Wednesday, June 10, 2009

Javascript confirm in aj4:commandLink in JSF

<a4j:commandLink onclick="if (! window.confirm('Are you sure?') ) {return false}" immediate = "true" >

don't forget to add immediate = 'true';


Thursday, March 19, 2009

Setting Java Managed Bean into Session

FacesContext.getCurrentInstance().getExternalContext()
               .getSessionMap().put( "testBean",
                     testBean );

TestBean testBean = (TestBean)FacesContext.getCurrentInstance().getExternalContext()
               .getSessionMap().get( "testBean")

How-to get or remove a jsf backing bean from session?

To reset session bean

FacesContext
.getCurrentInstance()
.getApplication()
.createValueBinding( "#{yourBeanName}").setValue(FacesContext.getCurrentInstance(), null );



To get session bean reference

Object obj = FacesContext
.getCurrentInstance()
.getApplication()
.createValueBinding("#{yourBeanName}")
.getValue(FacesContext.getCurrentInstance());
 
YourSessionBean bean = (YourSessionBean)obj;

Sunday, March 8, 2009

Prepended L in Exception

Have you ever saw an exception with L padded before a exception???


like .executeQuery(Ljava/lang/String;)Ljava/sql/ResultSet  while running an application in your application server ?
It means that this method cannot be found on server.

The solution is to restart the server...


ISO 8583 Encoder / Decoder

This page might help you if you want to encode and decode a test message

Saturday, March 7, 2009

Getting HTTP Session in JSF


Here is a way to get HttpSession...

import javax.faces.context.FacesContext;
// …..
public void addInSession() {
MySession mySession = new MySession();
mySession.setName(getMsg());
/* .getSession(bool), true if we want to create new session, if want to
use old
session then false
*/
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
session.setAttribute(”sessionObj”, mySession);
if (session.getAttribute(”sessionObj”) != null) {
MySession mySavedSession = (MySession) session.getAttribute(”sessionObj”);
System.out.println(”HTTP Session: ” + mySavedSession.getName());
} else {
// do something
}
}

Tuesday, January 27, 2009

Configure OracleDataSource in Struts

Following is the configuration to be defined in <data-sources> and </data-sources>

Things to be remember while defining the OracleDataSource in Struts are
  1. URL should be in uppercase otherwise it will throw following exception

    java.sql.SQLException: Invalid Oracle URL specified: OracleDataSource.makeURL

  2. username and password should be defined in URL string and not separate property. Otherwise it will throw following exception

    java.sql.SQLException: invalid arguments in call

<data-source type="oracle.jdbc.pool.OracleDataSource"
key="ods">
<set-property property="driverClassName"
value="oracle.jdbc.driver.OracleDriver" />
<set-property property="URL"
value="jdbc:oracle:thin:username/password@localhost:1521:dbname" />
<!--
Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to 0 for no limit.
-->
<!--
Maximum number of idle dB connections to retain in pool.
Set to 0 for no limit.
-->
<!--
Maximum time to wait for a dB connection to become available
in ms, in this example 5 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<set-property property="maxWait" value="5000" />
<set-property property="readOnly" value="true" />
<set-property property="autoCommit" value="false" />
</data-source>

Sunday, January 25, 2009

Oracle 10g : How to pass ARRAYS to Oracle using Java?

Here i'm trying to send an array of integers as a parameter to a callablestatement.


import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;

import javax.sql.DataSource;

import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import oracle.sql.StructDescriptor;

import com.cs.datasource.CardSellerDataSource;

public class TestMessageBroadCasting {

public static void main(String args[]) {

try {
DataSource dataSource = ... ...;

Connection connection = dataSource.getConnection();


String sql = "{call package_name.proc_name(?, ?, ?, ?, ?, ?)}";


Integer [] arr = {1 , 2};
ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(
"RESELLERLIST", connection);
ARRAY array = new ARRAY(arrayDescriptor, connection, arr);


CallableStatement callableStatement = (oracle.jdbc.driver.OracleCallableStatement)connection.prepareCall(sql);
callableStatement.setInt(1, 1);
callableStatement.setString(2, "A for apple"
+ System.currentTimeMillis());
callableStatement.setArray(3, array);
callableStatement.setString(4, "0");
callableStatement.setInt(5, 0);
callableStatement.setString(6, "");
callableStatement.registerOutParameter(4, Types.VARCHAR);
callableStatement.registerOutParameter(5, Types.INTEGER);
callableStatement.registerOutParameter(6, Types.VARCHAR);
callableStatement.execute();

String b = callableStatement.getString(6);
System.out.println("message : " + b);

} catch (SQLException e) {
e.printStackTrace();
}

}
}



So, first define an array of integer

Integer [] arr = {1 , 2};

We need a ArrayDescriptor.

ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(
"VALUELIST", connection);

VALUELIST is the name of the type defined in your database(Oracle)


Two points we need to note are 
  1. VALUELIST must be defined in SCHEMA LEVEL rather than PACKAGE LEVEL
  2. VALUELIST must always be typed in uppercase letter.
The errors you might get while not defining the name of the type well is
java.sql.SQLException: invalid name pattern: ... ...





Tuesday, January 20, 2009

Know the name of currently executing method in Java

This method is used to get the name of method currently executing.

protected String getCurrentlyExecutingMethodName() {
  Throwable t = new Throwable(); 
  StackTraceElement[] elements = t.getStackTrace(); 
  if (elements.length <= 0) return "[No Stack Information Available]";
  // elements[0] is this method
  if (elements.length < 2) return null;
  return elements[1].getMethodName();
}

Monday, January 12, 2009

Unable to open folder by double clicking...

If double clicking a folder opens search page then try one of the followings

  1. in run type regsvr32 /i shell32.dll
  2. Press Ok 
Or
  1. In registry search for 'MountPoint2' and delete all entries