Andrea Girardi - It's my blog!

Tag: java (page 2 of 3)

dataSource: The name of the property, following JavaBean naming conventions.

Suppose you defined TemplateDao Spring bean in this way:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">	
	<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>	
	<property name="url"><value>jdbc:mysql://${mysql.hostname}:${mysql.port}/${mysql.db}</value></property>
	<property name="username"><value>${mysql.user}</value></property>
	<property name="password"><value>${mysql.password}</value></property>
</bean>	
 
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<property name="dataSource" ref="dataSource"/>
</bean> 
 
<bean id="TemplateRequestDao" class="com.afm.admin.dao.mysql.TemplateDaoMySql">
	<property name="dataSource" ref="dataSource" />
</bean>

and you get this error message: The name of the property, following JavaBean naming conventions. The reason is probably you forgot to extend your implementation class:

public class TemplateDaoMySql extends JdbcDaoSupport implements TemplateDao {
 
	@Override
	public List<TemplateRequest> getTemplateRequest(UserProfile userProfile) {
		// TODO Auto-generated method stub
		return null;
	}
 
}

Time lost to fix this issue: more or less 1 hour. Image the how many I was frustrated when I discovered what was the problem.

Velocity generates NullPointerException while evaluating template

While evaluating template with Velocity I am affecting a null point exception but happened only on production environment because it seems that the application is trying to write to tomcat/bin the velocity.log file but it failed due to the permission. I tried to add velocity.property file:

# Fri Dec  6 10:14:26 EST 2013 - Mandatory to prevent Velocity null point exception
runtime.log.logsystem.class=org.apache.velocity.runtime.log.NullLogSystem

but, after every startup I get the same error and, to fix that, it seems to be mandatory to remove the workdir tomcat folder. It’s not acceptable so, I tried to add this row before init the velocity:

Velocity.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");

Of course, my next step is to migrate to Freemarker because Velocity isn’t really under active development any more.

Cannot nest ‘PRJ/src/main/resource’ inside ‘PRJ/src’

I created a new Web application using Eclipse and, after Enabling Maven, I get this error updating the project:

Cannot nest 'PRJ/src/main/resource' inside 'PRJ/src'. To enable the nesting exclude 'main/' from 'PRJ/src'

Basically I removed the folder /src and create folder /src/main/java, /src/main/resources etc and this fight with the sourceDirectory tag in Build section of maven pom. To fix that, just remove this row and update the project:

<sourceDirectory>src/</sourceDirectory>

Spring-data: Cannot use a complex object as a key value

I was trying to figured out how to solve this issue. Basically I’m saving a user profile bean that contains multiple occurrences of other beans inside him. Something like date:

public class UserProfile {
 
	List<Class1> classes1;
	List<Class2> classes2;
 
	Integer int1;
	Map<String, Class3> classes3;
 
}

I was working fine until I changed a getter adding some business functionalities and surrounding all lines with a try / catch. Of course, I putted the exception message on the log using adding this definition inside the bean:

protected final Log logger = LogFactory.getLog(getClass());

Good point for me, everything worked fine until I updated the object in Mongo. Holy crap, I got the “Cannot use a complex object as a key value” exception and I spent two hours trying to change the beans (of course I did a lot of other changes after the fatal adding of business logic inside my bean). Exhausted, I contacted my colleague Max (@maxfarnea) and he told me, “when I got this error, I removed the log inside a bean”. Ipso facto, I removed the log entry from my bean, added a throws exception instead of a try / catch and tested! Well done @maxfarnea, it works!

I learned two lesson today: one, don’t put log into beans that need to be stored using spring-data and, two, if you are in pain, ask, talk, don’t be silly, don’t waste your time!!! Stackoverflow.com is a good point to start (and my blog either, of course) but never is more helpful than a quick chat with a colleague!

No suitable driver found for jdbc:mysql://localhost:3306/schema

If the exception “Could not get JDBC Connection; nested exception is java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/schema” is raised probably you forgot to add the

<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>

property to your dataSource bean:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">		
	<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
	<property name="url"><value>jdbc:mysql://172.16.0.11:3306/test_vale</value></property>
	<property name="username"><value>root</value></property>
	<property name="password"><value>password</value></property>
</bean>

How to call a function whose name is stored in a string variable

The objective is simple, create a method which load a class dynamically, access its method and passing their parameters value and getting the return value at run-time. To do that is possible to use Java reflection.

try {
	Class<?> clazz = Class.forName("package.myclass");
	Method mth = clazz.getDeclaredMethod("method", String.class, String.class);
	Object source_class = clazz.newInstance(); 
}
catch (SecurityException ex) {				
	return null;
}
catch (NoSuchMethodException ex) {
	return null;
}
catch (IllegalArgumentException ex) {
	return null;
} 
catch (IllegalAccessException ex) {
	return null;
} 
catch (InvocationTargetException ex) {
	return null;
}
 
logger.debug((String) mth.invoke(source_class, "Param1", "Test ${medicationGenericName}"));

In this case the method needs two string as parameter and returns a string.

If the constructor of the class needs a parameter (i.e. the application context because the @Autowired doesn’t works), this is the code needed:

Class<?> clazz = Class.forName("package.myclass");
Constructor <?> constructor = clazz.getDeclaredConstructor(ApplicationContext.class);
Method mth = clazz.getDeclaredMethod("method", String.class, String.class);				
Object source_class = constructor.newInstance(applicationContext);

‘Must Override a Superclass Method’ Errors after importing a project into Eclipse

Eclipse is defaulting to Java 1.5, when you want it to use Java 1.6.

You have classes implementing interface methods, which in Java 1.6 can be annotated with @Override; however, in Java 1.5, @override could only be applied to methods overriding a superclass method.

Go to your project/ide preferences and set the “Java compiler level” to 1.6 and also make sure you select JRE 1.6 to execute your program from Eclipse. Check also the JRE System Library on Java Build Path properties of your project.

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
		response.setContentType("application/pdf");
 
		// 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)) &gt; 0 ) {
			outs.write(buf, 0, len);
		}
		outs.close();
 
	} 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;
 
}

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

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());
}
Olderposts Newerposts

Copyright © 2019 Andrea Girardi – It's my blog!

Theme by Anders NorenUp ↑