Tag Archives: java

How to download PDF file from url on MVC controller

To download a remote file (like a PDF) redirecting to response output, use these instructions to update a your Spring MVC controller:

@RequestMapping(value="/viewAttach", method = RequestMethod.GET)
public ModelAndView viewAttach(@RequestParam(value="article_id", required = true) String article_ref, HttpSession session, HttpServletResponse response) 
	/* *** Remember to check if Session still valid  *** */
	try {
		URL url = new URL(remoteURL);        	
		response.setHeader("Content-disposition", "attachment;filename=" + filename);
		//Set the mime type for the response
		// URLConnection connection = url.openConnection();
		InputStream is = url.openStream();
		BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
		int len;
		byte[] buf = new byte[1024];
		while ( (len = is.read(buf)) > 0 ) {
			outs.write(buf, 0, len);
	} catch (MalformedURLException e) {
		logger.error("Error ModelAndView.viewMain - MalformedURLException : " + e.toString() + " -- " + e.getStackTrace()[0].toString());
		return null;
	} catch (IOException e) {
		logger.error("Error ModelAndView.viewMain - IOException : " + e.toString() + " -- " + e.getStackTrace()[0].toString());
		return null;
	return null;
Tagged ,

How to switch between different JVM in Ubuntu

Sometime is needed to install different JVM on Ubuntu server due to application compatibility or software development purposes. To switch between different JVM in ubuntu from command line, use this command:

sudo update-alternatives --config java

and this menu will appear:

There are 2 choices for the alternative java (providing /usr/bin/java).
  Selection    Path                                            Priority   Status
* 0            /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java   1071      auto mode
  1            /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java   1061      manual mode
  2            /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java   1071      manual mode
Tagged ,

Put SQL result into a map

To extract two or more object (in this sample two Integer) from a DB and putting into a map, use this:

final Map<Integer,Integer> topic = new HashMap<Integer,Integer>();
getJdbcTemplate().query(sqlCommand, new Object[] {query_parameter}, new RowMapper<Object>(){
	public Object mapRow(ResultSet rs, int arg1) throws SQLException {
		topic.put(rs.getInt("integer1"), rs.getInt("integer2"));
		return null;

To read all values:

Iterator<Map.Entry<Integer, Integer>> users = userScheduledToday.entrySet().iterator();
while ( users.hasNext() ) {
	Map.Entry<Integer, Integer> entry = users.next();
	logger.debug("Key: " + entry.getKey() + " - Value: " + entry.getValue());
Tagged , ,

Dynamic Web Module 3.0 requires Java 1.6 or newer

I’m using STS and I configured my Web application to use Maven but, when I try to use Maven > Update project configuration, I’m getting this really annoying project error:

Dynamic Web Module 3.0 requires Java 1.6 or newer. [...] Maven WTP Configuration Problem
One or more constraints have not been satisfied.

STS/Eclipse are configured to use Java 1.6 but my project apparently isn’t. So I go change that, but it doesn’t fix that error, and any time I update project config with Maven, it’s back to using JRE 1.5 and my Java source files are no longer on the build path as source files. This because the Maven compiler plugin doesn’t use Eclipse settings and just imposes its own defaults, i.e. Java 5, unless otherwise configured by a POM. And since a “Dynamic Web Project” uses Servlet 3.0 it requires Java 6.

To fix, just add under the top-level POM:

Tagged ,

Resolving java.lang.OutOfMemoryError: PermGen

Today our Alfresco doesn’t start due to this error:

java.lang.OutOfMemoryError: PermGen

The PermGen (permanent generation) holds data needed by the virtual machine to describe objects that do not have an equivalence at the Java language level like objects describing classes and methodse. So often large, complex apps will need lots of PermGen space. Similarly if you are doing frequent war/ear/jar deployments to running servers like Tomcat or JBoss you may need to issue a server restart after a few deploys or increase your PermGen space.

To increase the PermGen space use something like:


The default is 64MB.

Note that Xmx is separate from the PermGen space, so increasing Xmx will not help with the PermGen errors (PermGen memory is in addition to the Xmx memory)

Java has other settings that could help control how much memory it uses:

-Xmx sets the maximum memory heap size
-Xms sets the minimum memory heap size.

Tagged ,

Download Alfresco content from Java using Spring

To download content stored on Alfresco repository using Java, this is one possible way:

String url = "http://localhost:18080/alfresco/d/a/workspace/SpacesStore/" + attach.getNode_ref() + "/" + attach.getAttach_filename() + "?ticket=" + ticket;
return new ModelAndView("redirect:" + url);

Where getNode_ref() is a method that returns the node reference ID and getAttach_filename() returns the file name. In that case the authentication ticket is attached to the request because the Alfresco guest user is disable.

To view the content instead of dowload it, change the url into:

Tagged , ,

Use of LIKE clause in sql prepared statement

Suppose you have a where condition with like clause:

AND ( UPPER(C.ndg) LIKE UPPER('%test%') OR UPPER(C.ndg_name) LIKE UPPER('%test%') )

on Java you should write something like that:

AND ( UPPER(C.ndg) LIKE UPPER('%?%') OR UPPER(C.ndg_name) LIKE UPPER('%?%') )

but, when you fill the paramter with SimpleJdbcTemplate(), this exception will be raised:

PreparedStatementCallback; SQL []; The column index is out of range: 1, number of columns: 0.; nested exception is org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.

This happens because with prepared statement you need to remove the ‘ but, now, how can I write the condition with ‘%’ char?

Simple, you need to sorround the paramter with ‘%’ like that:

sqlString += " and ( UPPER(C.ndg) like UPPER(?) or UPPER(C.ndg_name) like UPPER(?) ) ";
getJdbcTemplate().query(sqlString, new Object[] {"%" + searchForm.getNdg() + "%", "%" + searchForm.getNdg() + "%"}, new ViewCGRowMapper());
Tagged , ,

Query Alfresco Web script using REST

With Spring 3 querying a REST-based service it’s easy. For first, you need to authenticate on Alfresco repository using an Alfresco Ticket instead of an explicit user name and password. A ticket represents a pre-authenticated user who has already performed the login process. To log in, the url is:


Assuming the userid and password are correct, Alfresco will respond back with this simple XML:

<!--?xml version="1.0" encoding="UTF-8"?-->

Using Spring and Java you should write something like that:

RestTemplate restTemplate = new RestTemplate();
Map params = new HashMap();
params.put("user", login);
params.put("password", password);
String url = "http://localhost:8081/alfresco/service/api/login?u={user}&amp;pw={password}";
Source result = restTemplate.getForObject(url, Source.class, params);
XPathOperations xpath = new Jaxp13XPathTemplate();			
this.authenticationTicket = xpath.evaluateAsString("//ticket", result);

The RestTemplate was introduced in Spring 3 to give REST access the same support as JDBC, passing a Map of keywords and values. It serves as a wrapper to hide all the details in accessing REST resources, including opening and closing connection objects and converting responses to Java objects. Source class is the return type.

Once authenticated, we are ready to call Web script to query Alfresco repository:


This web script returns an XML like that:


The above response needs some configuration to marshall objects to XML. All we need to do is define it in our application context and, for that to work fine, you need to tell the marshaller which annotated classes you have:

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <property name="messageConverters">
            <bean id="messageConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
                <property name="marshaller" ref="marshaller" />
                <property name="unmarshaller" ref="marshaller" />
<bean name="marshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
    <property name="autodetectAnnotations" value="true"/>
    <property name="annotatedClasses">

At this point we can simply instantiate a RestTemplate object by calling the getBean method on the application context. This is the Java code to do that:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("alfresco-context.xml");
RestTemplate restTemplate = applicationContext.getBean("restTemplate", RestTemplate.class);	
Map<String, String> params = new HashMap<String, String>();
params.put("ticket", this.authenticationTicket);	
params.put("keyword", key);	
String url = "http://localhost:8081/alfresco/service/kipcast/search/brand.xml?q={keyword}&alf_ticket={ticket}";
Brands brandList = (Brands) restTemplate.getForObject(url, Brands.class, params);

Last thing is modify the two beans Brands and Brand putting the proper annotations to both classes:

public class Brands {
	List<Brand> brandList = new ArrayList<Brand>(); 
    public List<Brand> getBrands() {
        return brandList;
	public void setBrands(List<Brand> brandList) {
	    this.brandList = brandList;
	public void addBrands(Brand brand) {
public class Brand {
	private String nodeRef;
	private String name;
	private String relatedCommonName;
	private String supplierName;
        // Getter and setter methods

For more details please take a look to thekspace.com, tedwise.com and springsource.com.

Tagged , ,