Saturday, April 26, 2008

The Most Used JVM Parameters

It happens that I need to google for the some JVM parameters over and over again each time I need them. On the first place is a remote debugging. On the second endorsed. On the third... Oh well. Let's just put it here.



And here is a very good collection of JVM Options

Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html

Wednesday, April 16, 2008

Passing Query Parameters over HTTP

When you start to learn HTML Forms you learn something like:

method - The HTTP method for sending data to the action URL. Default is get.
method="get": This method sends the form contents in the URL: URL?name=value&name=value.

method="post": This method sends the form contents in the body of the request.
(taken from http://www.w3schools.com)


Pretty clear, right?

But what happens when you use POST and add parameters to URL:
form action="URL?name=value&name=value" method="POST"
Will it work?
The answer is yes. It will. Some of the parameters will be passed on URL and some in the body and it will be transparent for the server side.

Is it OK? It looks like bug...
Well, it isn't bug. The HTTP spec (RFC 2616) defines HTTP url as
http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]

for all HTTP verbs. Including POST.
It's HTML spec that defines how the method POST should treat a form data: to put it in the message body and so on; and there is no problem at all to add another query params to the URL.

And what happens if you want to POST a real body? Something that isn't parameters, may be atom message to update Blogger or something?
How would the server know that the body of the message is a body and not a list of parameters?

So here are the rules:
SRV.4.1.1 When Parameters Are Available
The following are the conditions that must be met before post form data will
be populated to the parameter set:
1. The request is an HTTP or HTTPS request.
2. The HTTP method is POST
3. The content type is application/x-www-form-urlencoded
4. The servlet has made an initial call of any of the getParameter family of methods
on the request object.
If the conditions are not met and the post form data is not included in the
parameter set, the post data must still be available to the servlet via the request
object’s input stream. If the conditions are met, post form data will no longer be
available for reading directly from the request object’s input stream.
(From Servlet Specification 2.3)


In addition to these rules, the parameters are not available in case of chunking. I didn’t find this part in spec, but I tested it and it just doesn’t work.

So it as it appears, it's very difficult to get a POSTed body as parameter. You must not use chunking, you must define content type as application/x-www-form-urlencoded and you must to call any of the getParameter family of methods on the request object. Right? It looks very difficult, but it what the most of the people do by default. It was exactly what I did, when I invoked a very simple HTTP call from java application.

So for the clients the best solution, in my opinion, is always ensure that you set proper content type. That's the way you tell the server: the body cotains parameters or the body contains the real body.

For servers the solution is: always call getParameter BEFORE starting reading the body. Checking content type can be also helpful.

Monday, April 14, 2008

printf (sprintf) in Java

Do you know this feeling that you need some very-very common functionality, which has to be implemented dozens of times and you still has no idea how to do it in Java?

One great example is "printf" or "sprintf" function from C. Almost everyone, who starts learning C, develops "Hello Word" application using printf.
And what happens when you move from C to Java? "There is no printf", I was told, when I started to learn Java, "but you don't really need it. User StringBuffers (StringBuilder since Java 5) to build strings and it will work just fine in most cases." And that what I did. And I have really got used to it.

And surprise! Since Java 5 there is "printf" in Java. As everything in Java it's a class and it's called Formatter (java.util.Formatter).
You can read the Java Doc to see how to use it, but there is a shortcut for sprintf: The class String now contains two methods format(String format, Object ... args) and format(Locale l, String format, Object ... args) that work almost exactly like sprintf.

Personally I'm feeling really ashamed that it took me two years of using Java 5 to discover this functionality.

Wednesday, April 9, 2008

Cut and Paste of strings in Eclipse

One important feature of IntelliJ that Eclipse was lacking (at least I thought so) is an automatic escaping when pasting strings.
So it appeared that Eclipse does not lack this feature, but for some reason it's unchecked by default and it's not easy to find it.

And here it is:
Windows --> Preferences --> Java --> Editor --> Typing --> In string literals --> Escape text when pasting into string literals


Recommended Reading

1. Guards! Guards!
2. Witches Abroad
3. Wyrd Sisters

Tuesday, April 8, 2008

EclEmma 1.3.1 - Java Code Coverage for Eclipse

A very nice plugin that shows code coverege.
It supports:
* Local Java application
* Eclipse/RCP application
* JUnit test
* JUnit plug-in test
* TestNG test
* Equinox OSGi framework

EclEmma web site
Update site for eclipse: http://update.eclemma.org/

Enjoy!

Monday, April 7, 2008

Useful Software

Some time ago I decided to organize the utility software I'm using.
Now I have organized it using the Google Spreadsheets:



I'll be glad if you notify me about the interesting software you using that doesn't appear in this list.


Original post

IDE Survey

Let's do a short survey on what IDE are you using for Java development.
The survey is available on the main page of this blog.
If you have any additional comments, please post them here.
The survey will be available for the following two weeks and I'll post the results here.

Update: I have extended the survey till the end of April.

Saturday, April 5, 2008

Very nice visualization of HTTP status codes:

http://thoughtpad.net/alan-dean/http-headers-status.jpg

via http://thoughtpad.net/alan-dean/http-headers-status.html
via some guy, who mailed me these nice links.
Just discovered two very-very nice features of Eclipse:
1. Build in TCP/IP monitor that acts as intercepting proxy. No need for special Fiddler configuration or TCPMON anymore.
2. Ctrl+3. Click it and type "tcp monitor" or "new class" and see what happens.

P.S. Btw, the feature that all IntelliJ users was so proud of: the ability to find class by its capital letters is also supported. I'm not sure when it was added to IDE, but now it just works. Example: Click Ctrl+Shift+T and type "SB" you'll get both StringBuilder and StringBuffer.

Original post

Thursday, April 3, 2008

Removing informational balloons in Windows

The following registry file will do the job:

remove_balloons.reg
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
"EnableBalloonTips"=dword:00000000



via Ynet (Hebrew)

Arguments to run Eclipse

Usually when you run eclipse, you need to put some arguments to the command line. Many people do it, but doesn't know that eclipse also takes arguments from the file eclipse.ini, which is located in the eclipse root folder.

No paying attention to this file, sometimes causes errors during the start-up. Furthermore, the behavior of Eclipse often becomes different from the expected.

So the first purpose of this post is to increase awareness regarding the eclipse.ini file.

The second purpose is to keep an example of eclipse.ini here:

-showsplash
org.eclipse.platform
-clean
-vm
C:\jdk1.5.0_11\bin\javaw.exe
-vmargs
-XX:MaxPermSize=256m
-Xms512m
-Xmx512m


To sum it up:
1. Most of the arguments that are needed to run Eclipse I put to eclipse.ini file.
2. The only argument I add to shortcut is -data <path to workspace> in order to specify the workspace.

1/05/2009: Make Eclipse Faster:
-showsplash
org.eclipse.platform
-framework
plugins\org.eclipse.osgi_3.4.3.R34x_v20081215-1030.jar
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms512m
-Xmx512m
-XX:PermSize=256m
-XX:MaxPermSize=256m
-Xverify:none
-XX:+UseConcMarkSweepGC
-XX:+CMSClassUnloadingEnabled
-XX:+CMSPermGenSweepingEnabled

How to get context of another war in tomcat

Lets say you have two web applications that run in the same tomcat server.
And for some weird reason you want to call code of the other war.


You can write something like this in your servlet/jsp to get the context of the other war:
javax.servlet.ServletContext context = application.getContext("otherWarName");


Now, when you have context to the war, you can access the objects under it. In example, you can include the other jsp in your request:
javax.servlet.RequestDispatcher rd = context.getRequestDispatcher("other.jsp");
rd.include(request, response);


Looks simple? Well, it is. It even works on jboss, but it does not in tomcat: application.getContext("otherWarName") returns null, so you'll get the NullPointerException.

The missing part is configured in the conf/server.xml. You'll need to define cross context for the applications that you want to be accessible from the other applications. Under the host element add:
<context path="/otherWarName" debug="0" reloadable="true" crosscontext="true"></context>


Recommended Reading

1. Professional Apache Tomcat 6 (WROX Professional Guides)
2. Tomcat 6 Developer's Guide
3. Pro Apache Tomcat 6


Original post

Configuring HTTP Proxy in Java

Sometime ago I needed to configure a proxy for an example applications that has used both Axis, Axis2 and JAX-WS as SOAP Engines.

Usually to configure proxy you need to define the following system properties, when you start a JVM:
-Dhttp.proxySet=true -Dhttp.proxyHost=<host> -Dhttp.proxyPort=<port>


But unfortunately it doesn't always work. Actually it did work only for Axis.
So here are the solutions that worked:

In Axis2 it's possible to add the following code to the client that will copy proxy settings from system properties:
ServiceClient serviceClient = stub._getServiceClient();
Options options = serviceClient.getOptions();
if (System.getProperty("http.proxySet", "false").equals("true")) {
ProxyProperties proxyProperties = new ProxyProperties();
proxyProperties.setProxyName(System.getProperty("http.proxyHost"));
proxyProperties.setProxyPort(Integer.parseInt(System.getProperty("http.proxyPort")));
// set username and password if you need them
options.setProperty(HTTPConstants.PROXY, proxyProperties);
}


In JAX-WS you may set the proxy in the code:
if (System.getProperty("http.proxySet", "false").equals("true")) {
ProxySelector.setDefault(new ProxySelector() {

@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
throw new RuntimeException("Proxy connect failed", ioe);
}

@Override
public List select(URI uri) {
return Arrays.asList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort")))));
}
});


Recommended Reading

1. Effective Java (2nd Edition)
2. Java™ Puzzlers: Traps, Pitfalls, and Corner Cases
3. Mort

Running "cmd" from current page in Windows Explorer

The following registry file will do the job:

cmd_here.reg
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\shell\CMD here]

[HKEY_CLASSES_ROOT\Directory\shell\CMD here\command]
@="C:\\WINDOWS\\System32\\cmd.exe /k cd \"%1\""



Original post

Wednesday, April 2, 2008

XML Serialization

I have always wondered how to serialize xml to string. Actually in the last years I have implemented this functionality at least twice using different approaches. I think it's time to post the two favorite ways how to do it, just to avoid implementing this functionality once again.

Here is one way:
public static void writeNode(Node node, Writer output) {
DOMImplementation domImpl = node.getOwnerDocument().getImplementation();
DOMImplementationLS domImplLS = (DOMImplementationLS)domImpl.getFeature("LS", "3.0");
LSSerializer serializer = domImplLS.createLSSerializer();
LSOutput serializerOut = domImplLS.createLSOutput();
serializerOut.setCharacterStream(output);
serializer.write(node, serializerOut);
}


Here is another way:
public static void nodeToStream(Node node, OutputStream stream) throws Exception {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(node), new StreamResult(stream));
}



The second way looks more elegant but it is slower. However, it can be improved by pooling transformers, which will probably make it less elegant.

The second way can be enhanced to produce a pretty xml:
public static String prettyPrintXML(Node node) throws Exception {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("indent", "yes");
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "3");
StringWriter output = new StringWriter();
transformer.transform(new DOMSource(node.getOwnerDocument()),
new StreamResult(output));
return output.toString();
}

About

Hello!

This blog contains set of memos with the technical issues that I found to be worth memorizing.

In example, how many times did you need to serialize xml to string in Java?
Personally I have already implemented this functionality several times, while each implementation of cause starts with some googleing.

Another example is Windows Registry. The are a lot of tricks that can be performed in registry, but who remembers them? In the best case, you just remember that there is a trick...

So I decided to put notes to the blog. First, it will make easier for me to find them later. Second, other people may also find them useful.

I named this blog "Tarlog on Java" since Java is the main programming language that I use and this will probably effect most of the posts here.

If you are reading this blog and find something here useful, don't hesitate to comment. It's always a very nice feeling to be read.

Thank you and enjoy reading,
Tarlog.