Alfred’s Computing Weblog

Alfred Java-cored Computing Weblog

Archive for the ‘Java’ Category

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException

leave a comment »

ERROT:
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException

STORY:
I was setting up a Spring powered web application for testing.
I edited the configurations files (*.xml) to add in some new configuration for testing / POC.
The following error is shown when I deployed the WAR file in tomcat
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 40 in XML document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'bean'. One of '{"http://www.springframework.org/schema/beans":description, "http://www.springframework.org/schema/beans":meta, "http://www.springframework.org/schema/beans":constructor-arg, "http://www.springframework.org/schema/beans":property, "http://www.springframework.org/schema/beans":qualifier, "http://www.springframework.org/schema/beans":lookup-method, "http://www.springframework.org/schema/beans":replaced-method, WC[##other:"http://www.springframework.org/schema/beans"]}' is expected.

SOLUTION:
As highlighted above, there is error in the mentioned XML file.
After I opened the XML file, I found that is some missed-closed bean definition ABOVE the mentioned line (Line 40 in XML).
The error bean definition as below:

<bean id="accountManager" class="alfred.sandbox.AccountManager">

Added in a BLACK SLASH “/” to close the bean definition properly will solve the error:

<bean id="accountManager" class="alfred.sandbox.AccountManager"/>

Written by Alfred

September 15, 2011 at 17:40

Java | Loop a Map

leave a comment »

I think this is the best way I found to loop through a Map in Java.

public void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println("Key:" + pairs.getKey() + ", Value:" + pairs.getValue());
    }
}

Reference Source

Written by Alfred

June 29, 2011 at 11:27

Posted in Java

Tagged with , ,

Plain text shows Encoded Chars

leave a comment »

Just started to have a chance to try out Spring 3.0, a lot of new features introduced, yet not enough time to read up all features.

I started a simple web apps project to try out Spring 3.0. The web apps is pretty simple, a REST server alike. Client init HTTP calls to the web apps with specific Servlet name and parameter, the web apps will returns the result JSON with Plain text mode. Since I am using Spring MVC, the result is printed with JSTL.

Sample call from client: http://myserver.com/getUser?userId=001

Expected result from server:
{“name”:”Bob”,”age”:”30″,”gender”:”male”}

I get what I expected when I test my web apps with browser.

But the ‘interesting’ comes when I test it with little Java Post program (use HttpClient, init HTTP call and inspect the result).
I did not get the expected result, I get below:
{&#034;name&#034;:&#034;Bob&#034;,&#034;age&#034;:&#034;30&#034;,&#034;gender&#034;:&#034;male&#034;}

All double-quat / quotation being replaced with ", its clearly the contain is being HTML encoded.

Below are my trouble-shooting steps:
Step 1. Check tomcat configuration
– Ensure the tomcat UTF-8 by default. More info
Step 2. Check web apps JSPs
– Ensure all JSP are UTF-8 as default encoding.

But both Step 1 & 2 does not fix my problem yet.
Step 3. Google “jstl without html encoded”
– Finally, I get the answer 🙂
– add in escapeXML properties when printing the result in JSTL
Before: <c:out value="${result}" />
After: <c:out value="${result}" escapeXml=”false”/>
Tutorial – Output with / without Encode

Lesson Learn:
When you want to print a PLAIN TEXT with JSTL, do remember to include escapeXML="false" to ensure that end user will get the actual expected result without HTML/XML encoded.

Written by Alfred

June 28, 2011 at 15:54

Posted in HTML, Java, Spring

Tagged with ,

Spring | NoSuchMethodError: GenericTypeResolver

with 4 comments

ERROR: java.lang.NoSuchMethodError: org.springframework.core.GenericTypeResolver.resolveTypeArguments(Ljava/lang/Class;Ljava/lang/Class;)[Ljava/lang/Class;

STORY:
I am starting a new webapps recently, since its a new webapps, I decided to use the latest Spring version 3.1.0.M2. Everything looks fine when the development is still in standalone environment. After dive into the development, the webapps I’m working on need to ‘talk’ to some other existing components in the system. After I have integrated my webapps with the existing components and I restart my tomcat, I get the error java.lang.NoSuchMethodError: org.springframework.core.GenericTypeResolver.resolveTypeArguments(Ljava/lang/Class;Ljava/lang/Class;)[Ljava/lang/Class;

First of all, for Java developer, when you see ‘NoSuchMethodError’, you will directly check the existence of the mentioned method in your JAR file. But ‘sadly’ the mentioned class file and method is there.

SOLUTION:
Thanks to Google, I got my answer in Spring Forum. The answer is pretty simple, I have more than 1 version of Spring in the classpath. As mentioned earlier, the new webapps is running on latest Spring (v3.1.0.M2) but the existing components I integrates with only running on Spring v2.5. So, pls ensure that there is only ONE SPRING VERSION in your classpath.

Written by Alfred

June 20, 2011 at 18:02

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);
}

Written by Alfred

June 22, 2010 at 20:08

Posted in Java

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 ,

Convert ArrayList to Array

leave a comment »

This is a basic Java conversion stuff. I want to convert an ArrayList to a normal Array.
Here is a sample I did and I would like to share it out to anyone who found its useful. 😉

The test driver…

.....
List arrayList_ = new ArrayList();
arrayList_.add("alpha");
arrayList_.add(new String("beta"));
arrayList_.add(new Integer(3));
arrayList_.add(new Float(4.00));
arrayList_.add(new Boolean(true));
.....
Object[] array_ = arrayListToArray(arrayList_);
for (int i=0; i<array_.length; i++) {
    System.out.println("&#91;" + i + "&#93; " + array_&#91;i&#93;);
}
// $>[0] alpha
// $>[1] beta
// $>[2] 3
// $>[3] 4.0
// $>[4] true
.....

The conversion happen here…

private Object[] arrayListToArray(List arrayList) {
    Object[] array = new Object[arrayList.size()];
    arrayList.toArray(array);
    return array;
}

Written by Alfred

December 30, 2008 at 18:11

Posted in Java

Tagged with , , ,