Category Archives: IT Stuff

Get a list of Object from jdbcTemplate()

Sometime happens get a list of object from database and, to do that without call a RowMapper, use this:

List<Object> strings = (List<Object>) jdbcTemplate.queryForList(query, Object.class);

This is a sample to get a list of String:

List<String> strings = (List<String>) jdbcTemplate.queryForList(query, String.class);
Tagged

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!

Tagged , ,

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>
Tagged , , ,

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);
Tagged

‘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.

Tagged

JSP Error : Attribute qualified names must be unique within an element

Today I updated an old Spring MVC application to Apache Tomcat 7 and some other newer jars and, when I started it, I get this error:

SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [/CG] threw exception [/WEB-INF/view/main.jsp (line: 2, column: 0) /WEB-INF/view/include.jsp (line: 3, column: 75) Attribute qualified names must be unique within an element] with root cause
org.apache.jasper.JasperException: /WEB-INF/view/main.jsp (line: 2, column: 0) /WEB-INF/view/include.jsp (line: 3, column: 75) Attribute qualified names must be unique within an element

After some search i find out that using single attribute multiple time in a single tag throw this error(it works with no problem in previous version!!!)

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

I removed the duplicated “prefix” tag and everything worked fine! (…ehm… everything? Of course not… but this exception has been fixed)

Tagged ,

Debug content model in Alfresco

When you need to customize Alfresco content model, not always everything works fine so, it’s necessary to find a way to check if your model is correct or not. It’s possible to use the built-in Get Class Definitions webscript to debug. Basically, you can use this webscript to see if an expected content type exists on Alfresco or not. You can also use this webscript to see if an expected content type exists on Alfresco or not. All you have to do is to call the webscript with your class name which in this case myroot:mycontent for me.

http://localhost:8086/alfresco/service/api/classes/myroot_mycontent

Or you can call the same webscript without a class name, in this case webscript will dump every content type that exists on Alfresco.

The response will be something like that:

 
   {
      "name": "labtest:Labtest_content",
      "isAspect": false,
      "isContainer": false,
      "title": "Labtest content model",
      "description": "",
      "parent":
      {
         "name": "cm:content",
         "title": "content",
         "url": "/api/classes/cm_content"
      },
      "defaultAspects":
      {
         "sys:referenceable":
         {
            "name": "sys:referenceable",
            "title": "Referenceable",
            "url": "/api/classes/labtest_Labtest_content/property/sys_referenceable"
         },
         "sys:localized":
         {
            "name": "sys:localized",
            "title": "Translation",
            "url": "/api/classes/labtest_Labtest_content/property/sys_localized"
         },
         "cm:auditable":
         {
            "name": "cm:auditable",
            "title": "Auditable",
            "url": "/api/classes/labtest_Labtest_content/property/cm_auditable"
         }
      },
      "properties":
      {
         "cm:name":
         {
            "name": "cm:name",
            "title": "Name",
            "description": "Name",
            "dataType": "d:text",
            "defaultValue": null,
            "multiValued": false,
            "mandatory": true,
            "enforced": true,
            "protected": false,
            "indexed": true,
            "url": "/api/classes/labtest_Labtest_content/property/cm_name"
         },
         "labtest:Labtest_result_name":
         {
            "name": "labtest:Labtest_result_name",
            "title": "Labtest result name [java uses to get this content]",
            "description": "",
            "dataType": "d:text",
            "defaultValue": null,
            "multiValued": false,
            "mandatory": false,
            "enforced": false,
            "protected": false,
            "indexed": true,
            "url": "/api/classes/labtest_Labtest_content/property/labtest_Labtest_result_name"
         },
         "cm:content":
         {
            "name": "cm:content",
            "title": "Content",
            "description": "Content",
            "dataType": "d:content",
            "defaultValue": null,
            "multiValued": false,
            "mandatory": false,
            "enforced": false,
            "protected": false,
            "indexed": true,
            "url": "/api/classes/labtest_Labtest_content/property/cm_content"
         }
      },
      "associations":
      {
 
         "labtest:labtest_static_components":
         {
            "name": "labtest:labtest_static_components",
            "title": "Labtest static components",
            "url": "/api/classes/labtest_Labtest_content/association/labtest_labtest_static_components",
            "source":
            {
               "class": "labtest:Labtest_content",
 
               "mandatory": true,
               "many": true
            },
            "target":
            {
               "class": "labtest:Labtest_static_component",
 
               "mandatory": false,
               "many": true
            }
         }
         ,
         "labtest:labtest_dynamic_components":
         {
            "name": "labtest:labtest_dynamic_components",
            "title": "Labtest dynamic components",
            "url": "/api/classes/labtest_Labtest_content/association/labtest_labtest_dynamic_components",
            "source":
            {
               "class": "labtest:Labtest_content",
 
               "mandatory": true,
               "many": true
            },
            "target":
            {
               "class": "labtest:Labtest_dynamic_component",
 
               "mandatory": false,
               "many": true
            }
         }
      },
      "childassociations":
      {
 
 
      },
      "url": "/api/classes/labtest_Labtest_content"
   }
Tagged

Analyzie MS Exchange log

Sometime happens to receive some interesting requests from the business like “Hey man, take a look if there are some strange access to our web mail”. This tool it’s really useful for this kind of task: Log Parser Studio

It requires (in this case) a IISW3CLOG and a simple query like that:

SELECT TOP 20 cs-username AS UserID, 
	cs(User-Agent) AS Application, 
	cs-uri-stem AS Vdir,
	c-ip AS CLIENT,
	cs-method,
	COUNT(*)
FROM '[LOGFILEPATH]'
WHERE cs-uri-stem LIKE '%OWA%'
GROUP BY UserID, Application, Vdir, Client, cs-method
ORDER BY COUNT(*) DESC

That’s all!

Tagged ,

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;
 
}
Tagged ,

Import oracle expdata file to different user

To import an Oracle exported file with *nix command line, use this command:

imp \'/ as sysdba\'  file=expdat.dmp fromuser=ORIGINALUSER touser=DESTINATIONUSER
Tagged