Alfred’s Computing Weblog

Alfred Java-cored Computing Weblog

Java | ERROR: java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String

leave a comment »

ERROR: java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String

Story:
Ok, I hits the above error when I try to loop through the request parameters, and print out all parameter Key and Value.
The ClassCastException is a general exception, it will be thrown when you try to cast an Apple to an Orange. Thats simple!
When the first time I read this exception message, “[Ljava.lang.String; cannot be cast to java.lang.String”, I though there is some typo in the compiler 😛
What is the difference between “[Ljava.lang.String” and “java.lang.String”?
From the wording itself, quite straight forward. The later do not have “[L”, but what is the “[L”?
Thanks for some stupid errors I hit before, I recall that the “[L” is the representation of Array object!

CODE / SOLUTION:
Here is the way I used to print out all parameter Key and Value. I’m not sure its a correct / best way, but its works!

Map paramMap = request.getParameterMap();
Iterator iter = paramMap.entrySet().iterator();
while(iter.hasNext()) {
    Entry<String, String[]> entry =  (Entry<String, String[]>) iter.next();
    String key = entry.getKey();
    String value = entry.getValue()[0];
    logger.debug("key[{}] value[{}]", key, value);
}
Advertisements

Written by Alfred

June 22, 2010 at 20:08

Posted in Java

Tagged with , , ,

Struts1 | Forward Page

leave a comment »

This is a simple and quick solution to forward / go to a page in struts1.

In normal case, we have to call to a class extending ActionForm before you’re going to the next JSP page. For cases that you do not need any action to perform before you reach that JSP, you can call the class org.apache.struts.actions.ForwardAction. So that, you only have to prepare the JSP file and do the configuration in struts-config.xml as below.

<action-mappings>
    ....
    <action path="/ForwardLogin"
        parameter="/WEB-INF/pages/login/login.jsp"
        type="org.apache.struts.actions.ForwardAction"
        scope="request"
        validate="false"/>
    ....
<action-mappings>

Written by Alfred

June 19, 2009 at 15:28

Posted in Struts1

Tagged with ,

Disable BEEP sound in Terminal

leave a comment »

I’m not sure this is the best solution or not, but its work!
This is an output of my google when I want to disable the error beep sound in terminal.
The beep sound I’m talking about is the annoying sounds like
“beep” or “tuuu” when you’re over pressing backspace or type something wrong in terminal.

The solution that I’m going to share here is COPY from netty5.
I feel that its very useful especially to those who is not familiar with terminal,
coz everything can be done by few mouse clicks.

1. Move your pointer to the top-left corner of your desktop.
2. Click on “Applications” > “Accessories” > “Terminal”. A terminal will be pop up.
3. On the Terminal, click on “Edit” > “Profiles..”. A small windows named “Profile” will be pop up and a “Default” profile is selected by default.
4. Click on “Edit” in the Profile window. Another small window will be pop up.
5. Click on “General” tab, UNCHECK the “Terminal bell”, and close all poped up windows. And you’re done. no more “beeeep” or “tuuuuu” sounds 🙂

FYI, I’m using Ubuntu 9.04 at the moment.

Written by Alfred

June 16, 2009 at 18:36

Posted in linux

Tagged with , , ,

Java | How to access Enum’s public method?

leave a comment »

Enum is an enumerated types, a special type in Java that used to hold static information.
Eg: the state of a connection (CONNECTING, CONNECTED, DISCONNECTED, etc), the day (MONDAY, TUESDAY, etc).
Besides of defining a status, we also can include some useful features of the Enum and write it as a method in the Enum.
Here is a simple example I write to show how to access to Enum’s method.

I have a Enum here, named “Day”:

package alfred.playground;

public enum Day {

	MONDAY, TUESDAY,
	WEDNESDAY, THURSDAY,
    FRIDAY, SATURDAY,
    SUNDAY;

	public boolean isWeekday() {
		return (equals(MONDAY) ||
				equals(TUESDAY) ||
				equals(WEDNESDAY) ||
				equals(THURSDAY) ||
				equals(FRIDAY));
	}

	public boolean isWeekend() {
		return (equals(SATURDAY) || equals(SUNDAY));
	}

}

And, here is the test program:

		Day day1 = Day.THURSDAY;
		System.out.println(String.format("[%s] is weekend? [%b]", day1, day1.isWeekend()));
		/*$>  [THURSDAY] is weekend? [false] */

		Day day2 = Day.SATURDAY;
		System.out.println(String.format("[%s] is weekend? [%b]", day2, day2.isWeekend()));
		/*$>  [SATURDAY] is weekend? [true] */

In order to call Enum’s method, we can not just directly call as usual class’s method “myClass.doSomething()”.
Instead, we must assign a value to the Enum before we can invoke the method.

For shorter codes, we can simplified the code by skipping the value assignment line:

		System.out.println(String.format("[%s] is weekend? [%b]", Day.FRIDAY, Day.FRIDAY.isWeekday()));
		/*$>  [FRIDAY] is weekday? [true] */

Written by Alfred

April 2, 2009 at 16:27

Posted in Java

Tagged with ,

Ant | FTP built file

with one comment

I was asked to do synchronization for binaries files between different machine.
The build tool used in the projects is Apache Ant.

The architecture is look like this :
development machine ---> deployment machine (host) --->  development machine (mirror)

Developer(s) is coding in development machine, so that the latest code is keep in development machine.
(the code has to be committed to svn, but its out of today’s scope)
Currently, developer is using Apache Ant to build the project (JAR/WAR) files.
Due to development machine and deployment machine (host) is the same physical machine, developer use the Ant Copy task to copy the latest built JAR file from build path to deployment path.

My main task for today is to ‘copy’ the latest version in deployment host to deployment mirror.
Keep in mind, the deployment host and deployment mirror is not in same physical machine. Therefore, we can not use Ant-Copy in this case.
In normal linux environment, we have several options to send file from 1 host to another, such as FTP, SFTP, SCP and etc.
For this case, I choose Ant-Ftp to FTP the files from development machine to deployment mirror.
The code that I’m going to DISCLOSE below can perfectly do the mentioned task.

...
	<!-- Synchronise Deployment Mirror -->
	<target name="sync-deploy-mirror">
	    <antcall target="copyJarToTempDir"/>
		  <antcall target="ftpToMirror"/>
	    <antcall target="deleteTempDir"/>
  </target>

	<!-- Copy required JARs to temp directory -->
	<target name="copyJarToTempDir" depends="main">
	    <copy file="${jar.dir}/my_proj_a.jar" tofile="${temp.dir}/1my_proj_a.jar.jar"/>
		  <copy file="${jar.dir}/my_proj_z.jar" tofile="${temp.dir}/0my_proj_z.jar.jar"/>
	</target>

	<!-- FTP JARs from temp directory to remote host-->
	<target name="ftpToMirror">
      <ftp server="${deploy.mirror.ip}"
           port="${default.ftp.port}"
           remotedir="${deploy.mirror.target.dir}"
           userid="${deploy.mirror.userid}"
           password="${deploy.mirror.password}"
           passive="yes"
           depends="yes"
           binary="yes">
         <fileset dir="${temp.dir}">
             <include name="**/*.jar"/>
         </fileset>
      </ftp>
  </target>

	<!-- Delete temp directory -->
	<target name="deleteTempDir">
	    <delete dir="${temp.dir}"/>
	</target>
...

The main target of our case is sync-deploy-mirror.
Its like the main method in normal programming, it calls 3 sub-targets: copyJarToTempDir, ftpToMirror and deleteTempDir.

Target copyJarToTempDir, as named is to copy the latest built JAR file to a temporary folder.
Pls take a closer look at this line . It means this target is depends on another target called main.
Why it need to depends on another target?
Basically, the main target is defined to build the project. As defined in this way, Ant will runs the main target before it executes copyJarToTempDir.
Therefore I can ensure that I can get the latest built JAR file to copy to temporary folder.
Another question rises, why do I need to copy latest JAR to another folder? As I just want to FTP latest JAR to another machine.
This question will be answer shortly as we proceed to the target that doing FTP.

Target ftpToMirror is FTP files from local to remote host.
The main attributes like IP, username, password, etc are defined in ftp tag.
In FTP tag, it only supports fileset directory, which means it can FTP every files (including subfolder) under the defined fileset.
Due to some business requirement, the original jar name (in Ant build path) may not be same (name) with its copy in deployment machine.
Therefore, I need to do copyJarToTempDir target to copy all built (required in deployment) JAR file to a temporary file.
Then, FTP every file in temporary folder (those file should be named as in deployment machine) to deployment mirror.

Target deleteTempDir is like a helper target as its used to remove temporary folder as the folder is no longer useful after FTP is done.

Written by Alfred

February 19, 2009 at 12:10

Posted in ant

Tagged with , , , , ,

Ant | Connection Reset

leave a comment »

error during FTP transfer: java.net.SocketException: Connection reset

The above is the latest collection of error I hit during my first touch with Mr. Ant, Apache 😛
From the error message, it hints that there must be something wrong with connection/network.
To troubleshoot network related problem, wireshark always is your best partner.
This is the trace I captured when I execute Ant-Ftp.

trace_ftp_reset_conn

Based on the trace on hand, I got the clearer picture now.
The trace shows that, the client (192.168.9.74) was sent a FTP handshake request to server (192.168.9.23).
The server replied with a RST flag. Generally, RST flag brings the meaning of ‘Reset’.
From a source I get from www,
The reset flag is used when a segment arrives that is not intended for the current connection.
That’s clear that the server rejected the FTP initial request from client.

By doing some checking on the services running in server, I found that the FTP service in server is not running 😦
That’s why the FTP initial request from client is rejected by the server.

When working in such internetworking environment, some times its not your code/configuration problem. This is another lesson learned..

Written by Alfred

February 18, 2009 at 12:42

Posted in ant, network

Tagged with , , ,

Ant | NoClassDefFoundError + MalformedServerReplyException

with 3 comments

Could not create type ftp due to java.lang.NoClassDefFoundError: org/apache/commons/net/ftp/FTPClientConfig

I trying to do ftp via apache ant’s target.
I get the above error as I tried to execute the ant-ftp target with default ant (v.1.7.1) package.
From the error message, its stated clear that there is missing of class named FTPClientConfig under package org.apache.commons.net.ftp.
Therefore, the first comes to my mind is I’m missing the JAR file that contains mentioned class file.
I quickly google and download the latest commons-net and place the JAR files into Ant’s lib folder (../apache-ant-1.7.1/lib/).

Wow.. The problem solved by putting the commons net JAR into Ant’s Lib folder.
But, yet another error comes out. Another problem solving process begin…

========================================================

error during FTP transfer: org.apache.commons.net.MalformedServerReplyException:
Could not parse response code. Server Reply: SSH-1.99-OpenSSH_3.9p1

I have no idea what this error message talking about.
From a quick googled, I know that the error message is meaning the remote host is expecting SSH instead of FTP.
It looks strange because I’m trying to do FTP, not SSH. So, I double the probably root couse, which is the ant xml

.....
<target name="ftp-test">
    <ftp server="${remote.host.ip}"
         port="22"
         remotedir="${remote.host.target.dir}"
         userid="${remote.host.userid}"
         password="${remote.host.password}"
         passive="yes"
         depends="yes"
         binary="yes">
        <fileset dir="${jar.dir}/${ant.project.name}.jar">
            <include name="**/*.jar"/>
        </fileset>
    </ftp>
</target>
.....

I tried to double check every variables, and I did not find any doubtful stuff.
By looking again and again, then only I see the doubtful configuration — port.
The port 22 is default port for SSH! I think this is the main reason commons-net expecting SSH from me.
I change the port to 21 (default FTP port) and test again.

Yet, another error message shown. The mission continue… 🙂

Written by Alfred

February 17, 2009 at 16:59