28/07/2013

[Java 4] Download file from portlet

Scenario: Java 4, Spring 2, WebSphere 6, JSR-168. How the hell do I let the user download a file from a portlet?

The file is extracted from a database and does not exist on the server's filesystem yet; redirecting to a servlet to create and send the response which contains the file to download fails with a generic:

java.lang.IllegalStateException: Can't invoke sendRedirect() after certain methods have been called

More specifically, that method can not be invoked after any of the following methods of the ActionResponse interface has been called:
  •         setPortletMode
  •         setWindowState
  •         setRenderParameter
  •         setRenderParameters
  •         removePublicRenderParamter
And currently I don't know whether it's Spring or WebSphere calling one of those forbidden methods silently.

[Java] Get current user from portlet

To get the user currently authenticated on the portal from a portlet, you may use:

Principal p = request.getUserPrincipal();

you may then call the getName method to get the UID of the user. If the user is not authenticated or the page is not protected, the Principal object is null.

[Java] Get extension from filename

To extract the extension from a given filename in Java, you may try:

 String yourfilename = "something.ext";  
 String[] tokens = yourfilename.split("\\.(?=[^\\.]+$)");  
 String extension = tokens[1].toLowerCase();  

This works even if filename contains multiple dots, however it's not an accurate way of determining a file type.

[Java] Send mail

Here's an example on how to send HTML emails to multiple recipients, without attachments, via Java.

This Mailer class was written in Java 4 and relies upon the javax.mail.* libraries, providing a method send which takes 4 parameters:
  • List:rcptTo - "TO" recipients
  • List:ccs - "CC" recipients
  • String:subject - message subject
  • String:body - message body

13/07/2013

[Java 4] Replace placeholder word in string

Should you be unlucky and have to work with Java 4, you may find it lacking many of the convenient features found in later versions.

One of them is the ability to replace a placeholder word in a String with little effort. What you can do is use the replaceAll method:

String str = "some string with a #placeholder# inside";
str=str.replaceAll("#placeholder#", "value");

Note that it will search for and replace ALL matches it finds, making it viable as a placeholder substitution method while it's pretty useless if you have to replace a single word; in that case, you may find the replaceFirst method more suitable.

Remember in any case that the first parameter is parsed as a regular expression meaning that you'll have to escape reserved characters such as "$" if your placeholder contains them. Another very important thing to remember is that, since String objects are immutable in Java, if you don't assign the return value to some variable, the substitution won't have any effect.
 

01/07/2013

[Java] Convert InputStream to String

This code snippet is the work of Pavel Repin from StackOverflow, and it's highly useful if work in Java. It allows you to easily convert an InputStream to a String taking advantage of the Scanner class, plus, since it's a native Java class, you don't need to download additional jars:

 public static String convertStreamToString(java.io.InputStream is) {  
   java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");  
   return s.hasNext() ? s.next() : "";  
 }  

[Java] Print document programmatically

Should you need to print a document from your Java application, you may find this code snippet, from the Java AWT Desktop class, useful:

 import java.awt.Desktop;  
 import java.io.File;  
 import java.io.IOException;  
   
 public class Main{  
   public static void main (String [] args){  
     try {  
       File f = new File("PATH_TO_FILE_TO_PRINT");  
       Desktop.getDesktop().print(f);  
     } catch (IOException e) {  
       // Handle the exception here if needed  
       e.printStackTrace();  
     }  
   }  
 }  

note however, that the command runs on the same machine where the JVM is running! If the application you're accessing runs on a separate host machine, it will not work at all; instead you may think of creating an applet to run this code on the client machine, passing the file to print as a parameter (remote paths are fine too!)