Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, July 23, 2010

Make a Map from a list, perl style

Make a Map from a varargs list. Useful for iBatis parameterClass objects.

Friday, April 23, 2010

Populate a DTO with mock data

Problem:
Every so often i need to have a list of some simple DTOs in order to build a screen. The DTOs need to be populated from the database, but the query is not ready. Its somewhat painful to write dummy data creation methods over and over again.

Solution:
Using Groovy(though not required), Spring and a bit of reflection i cover most of the simple DTOs.



To use, pass the class a list of which you expect

Wednesday, July 30, 2008

foreach to iterate over a map in 1.5

When you iterate over a map you need to usually get the key and the value, use this to get them both without having to use the key to get the value!



This also happens to not raise any unchecked warnings which you would have to @SuppressWarnings("unchecked")

Custom tags: passing in maps or other datatypes that arent strings

problem:
I needed to pass a hashmap into a custom tag. This hashmap was to be created on the jsp page using jstl, and then passed into the tag as an attribute.
For some reason i was not able to find the solution with just one google query.

solution:

1. first, to create a hashmap on the jsp using jstl and add some stuff to it:


2. next, add another attribute to your tag in the tld file:


3. finally, pass the hashmap into your tag .. <tag someName="${something}" /> and make sure that the setter in the tag takes in a Map

Monday, June 23, 2008

obfuscated java code sample

This piece of java code compiles and runs. It is the most obfuscated java snippet i've ever seen.




requires java 1.5

Sunday, April 27, 2008

appfuse 1.8.1 ehcache NoSuchMethodError

Problem:
I installed appfuse-light-all 1.8.1, installed acegi security, and ajax. After doing a build i get the following error when Spring starts up:

Error creating bean with name 'userManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]
.... bunch of other errors ...
Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: net.sf.ehcache.Cache.<init>

Solution:
The problem here is that i am using an older version of ehcache for some reason. Doing a bit more digging shows that i have the following versions of ehcache in my M2 repository:
[M2_REPO]/net/sf/ehcache/ehcache/1.2.3/
[M2_REPO]/net/sf/ehcache/ehcache/1.3.0/

version 1.2.3 is what is messing things up for me, it gets loaded by Spring first and causes the error. Deleting that directory does not work because "ant deploy" does the following if the dependency is missing:

Buildfile: build.xml
[artifact:dependencies] Downloading: net/sf/ehcache/ehcache/1.2.3/ehcache-1.2.3.jar
[artifact:dependencies] Downloading: net/sf/ehcache/ehcache/1.2.3/ehcache-1.2.3.jar

Now, since i dont know how to use MAVEN, i cant remove the code that fetches the old version, so i do the evil hack to prevent it from being created:

remove the directory "1.2.3", make a copy of "1.3.0" directory, call it "1.2.3". rename all the files inside to say 1.3.0 instead of 1.2.3.

Also, if you are deploying to tomcat as a directory, you might need to go into the webapps directory in tomcat, locate your app, and its WEB-INF and delete ehcache-1.2.3.jar thats is probably there now.

Now you can use appfuse.

if anyone knows of a better way to solve this, leave a comment.

Wednesday, April 09, 2008

Teamsite DCR java parser


Working with teamsite DCRs is painful. This is my attempt to make it a little bit less painful.

I made this program in order to make it easier to edit and parse teamsite data capture records. I should have done this a long time ago, and actually this is the first step towards freeing myself from OpenDeploy.

Anyway, here is the code for the parser:



Note: The code above does not yet truly support replicants, as in, you cant say 'give me the 3rd text field from the 2nd replicant..' unless you can figure out the xpath for it, which somewhat defeats the purpose of having a DCR parser.


Here is a driver class that uses my parser in order to do something silly.



in order to use this parser you will need the following libs:
- JDOM
- JAXEN

Thursday, January 24, 2008

Java: reading / writing international characters

It is actually very easy to support international characters in java. The only trick is knowing the charset that the text is encoded in. Most of the time is a safe bet to try UTF-8 if you dont know. If you use Apache's HTTPClient it has methods to get the charset of the stream you are reading from.


Wednesday, December 05, 2007

regex to split a document into words

Say you wanted to split a document into words, but works like are'nt shouldnt be split on the ' and numbers like 10,004,333 should remain intact, but other punctuation should be removed from the resulting word array.

A good way to do this is using Scanner's findWithinHorizon and a regular expression. This way you dont need to read the entire document into memory before processing it.

Thursday, November 29, 2007

Java: Understanding Weak References

The other day i was reading programming at reddit and stumbled on this article:
Understanding Weak References which was a good read but i still had some questions, so i turned to Java Developer Forums for help. I didnt get flamed! (much). What i got was a very good response from a user named kdgregory which is note-to-dogself worthy.

My questions are in blue boxes:
If weak references are great at stopping leaks, why not use them all the time?

They're great at stopping leaks in the situation where you're attaching data to an object that (should) have a limited lifetime. If you used a regular map (most likely an IdentityHashMap), you'd be creating a strong reference to the object via the map, so it would never be collected, even when there are no other references to it (I call this a leak, other people don't).

For example, ThreadLocal uses weak references, because they'll be cleared when the thread ends.

ObjectOutputStream should use weak references (and a changed protocol) so that it can be used in long-running conversations without constantly calling reset(). But it doesn't.

"WeakHashMap works exactly like HashMap, except that the keys (not the values!) are referred to using weak references."
  • does this imply that hashmap stores values in weak refs, if so, why?
  • should i use WeakHashMap for tasks where i will have another reference to objects i put into the map. ie i dont put my only ref into this map?

No, HashMap doesn't use weak references for either key or value. The author's wording (and for that matter, the JDK JavaDoc wording) is a little misleading.

One typical use for weak references is in a canonicalizing map to reduce memory consumption with duplicated data. With such a map, you would store an object as both key and value, and retrieve the canonical value when presented with an arbitrary key -- think String.intern(). However, you can't use WeakHashMap to do this without wrapping the value in a weak reference also.

When do i not use weak references ?

Most of the time. Any reference object means that you have to access your original object in two steps (have to call get() on the reference) rather than just one. And normally, you'd know the lifetime of your objects.

Friday, November 09, 2007

extract links using htmlparser

i have come to realize that even though i love to do everything in regex, extracting links with regex is not really the best idea.

the best idea is to use htmlparser to extract the links.

This code sniplet will extract links from a page body, and given the link where the body was found it will resolve the relative links. This is tailored to be used by a crawler.

Tuesday, October 16, 2007

extract links from a webpage

this is useful if you decide to make a web crawler, and dont want to bother with an html parser. You have to read the body of the page into a string, and then use this regex to extract all the links.

supported link types: <img src=...<a href=...


an absolute url is in the form of "http://something.com/blah"
a relative url is in the form of "/something/path.blee"

now you can figure out what to do with these...

Monday, October 08, 2007

Remove HTML tags regex

when using an HTML parser is too much work, you may want to use a small regex to remove all the html tags

this is java:

Monday, March 26, 2007

Using EL in custom tags as attributes

Problem:
I was working on a custom tag and i needed to pass it a bean from a JSP page kind of like this:
<customtag var="${somebean.something.else}">
I realized that what i was getting inside my custom tag was a String, not my bean.

Solution:
You need to use the ExpressionEvaluator to evaluate the expression, and get the bean, here is the code i used in my SimpleTag: (i was getting a Date object by the way)




Edit Aug 7, 2008:
It has come to my attention that in jsp 2.0 the EL expressions are evaluated before being passed to the custom tags, so you dont need to do any of this crap anymore.

Friday, February 16, 2007

How To: Implement RMI from scratch

The java.lang.reflect.Proxy class will let you provide an arbitrary implementation for an interface.

So, start with that on the client. Figure out how to produce a factory for interface objects. Understand how the proxy invocation works.

Then, create a socket connection to the server. Wrap it with an ObjectInputStream/ObjectOutputStream.

Now you need to define a protocol between client and server. For example, let's say that the client sends an integer object ID, followed by a method name, followed by an array of parameters. The server needs to find the object, and invoke the appropriate method. Then it needs to send the result back to the client.

Then you can get into distributed GC ...

source: java dev forums

Monday, January 29, 2007

NoClassDefFoundError: com/sun/mail/util/SharedByteArrayInputStream

problem:
when trying to send mail i get error: NoClassDefFoundError: com/sun/mail/util/SharedByteArrayInputStream

solution:
get mail.jar and put it on your classpath

http://java.sun.com/products/javamail/downloads/index.html

Friday, January 26, 2007

Java: find nested balanced tags

Problem:
I needed to parse out some divs from a html page, and java's regex cant do it. atleast when you have arbitrary number of nested balanced elements.

Solution:

Use at your own risk.

Monday, January 15, 2007

nice regex util class, replaceAll

elliotth.blogspot.com/java-implementation-of-rubys-gsub.html

Here is an example of what this does:
String result = new Rewriter("([0-9]+) US cents") {
public String replacement() {
long dollars = Long.parseLong(group(1))/100;
return "$" + dollars;
}
}.rewrite("5000 US cents");
System.out.println(result);

prints>> $50

nice!

Friday, August 18, 2006

Unsupported major.minor version 48.0

Problem:
Unsupported major.minor version 48.0

solution:
what you are running was compiled on 1.4 and you are running 1.3 or older

Wednesday, July 12, 2006

Problem: MANIFEST.MF missing class-path inside JAR

Problem:
MANIFEST.MF missing class-path: inside JAR.

Solution:
Put a blank like at the end of the manifest file.