- Describe the life cycle of a bean in Spring.
- What is the difference between singleton and prototype bean? Give an example when you would want to use one or the other.
- What are the advantages of using Spring?
- What are the main features of Spring?
- What is Dependency Injection/IOC?
- What are the three types of dependency injection? Which ones do Spring support?
- Name all the 7 modules of Spring and describe what they are.
- What's Bean Factory? What's Application Context? Describe the differences and when would you want to use one or the other?
- What is auto wiring? Name all five modes.
- Name two ways of accessing Hibernate using Spring.
- What is AOP?
- What is Aspect?
- What is JointPoint?
- What is Advice? Name 5 type of Advice.
- Why use declarative over programmatic transaction management?
- What are the main differences between EJB CMT and Spring's declarative transaction management?
- Does Spring's transaction management support transaction context over remote calls?
- Describe the main differences between EJB and Spring.
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Sunday, 18 September 2011
Core Spring Questions
Spring questions:
Saturday, 17 September 2011
J2EE Questions
Continuing from last post with basic questions, it's time for J2EE questions:
- What is J2EE?
- What are the 4 J2EE components?
- What is multi tiered architecture?
- What is the difference between a 3 tiered architecture and 3 layered architecture?
- What is a J2EE container? What 7 services does it provide?
- Describe JAR, WAR and EAR files.
- What is EJB and what is its role?
- What are the main differences between EJB 2.1 and EJB 3.0+?
- What's the difference between Session Bean, Entity Bean, and Message Driven Bean and give an example where each should be used.
- When would you want to use Stateful Session Bean?
- What is the difference between Bean Managed Persistence (BMP) and Container Managed Persistence (CMP)?
- What is deployment descriptor?
- What is the role of JNDI?
- What problems can you see using Java enum persisted in a database?
Friday, 16 September 2011
Core Java Questions
After nearly a decade in Java world, it is time to think about the basics (most people say Core Java). Anyone that has been in the Java industry for a long time should know the answer to all of the following questions, and if not, it is time to refresh your memory and maybe get excited again on what made you like Java in the first place. I'm not going to provide the answers since they are just a Google away, so here we go:
- What is the difference between ArrayList and Vector?
- What are the differences between Comparable and Comparator?
- Name design patterns that you use in Java. Give some examples.
- Implement a Singleton design pattern in Java. Why Singleton? Is the Singleton class that you created thread safe? What about the clone() method?
- What are the differences between Heap, Perm and Stack space?
- Explain how HashMap works in Java. Which method/s are used when put() or get() is called? What is the benefit of having immutable keys in HashMap?
- Explain how Java Garbage Collection works. Explain in terms of young generation, survivor 1 and 2, tenured generation and permanent generation. Can you force garbage collection?
- What JVM memory tuning options can you use to improve performance?
- Explain how Serialization works in Java. Include methods that are involved during the serialization/deserialization. What is serialVersionUID? What could happen when serialVersionUID is missing?
- What's so special about declaring a variable in a Java interface?
- What is the difference between executing run() and start() in Java thread?
- Explain why String is immutable? If it weren't, what would be the implications?
- Can you write an immutable object?
- What is the difference between creating String using new() and literal?
- What is the difference between Enumeration and Iterator?
- Explain deadlock. What would you check in the code that might cause deadlocks?
- Explain Checked and Unchecked Exception.
- When is finalize() method called?
- Explain transient modifier.
- Explain volatile modifer.
- What is the difference between public, private and default?
- What is operator precedence in Java?
- What is the difference between abstract class and interface?
- What is the difference between method override and method overload?
- Explain polymorphism, inheritance, and encapsulation.
- What is a wrapper class?
- Explain autoboxing
- Why would you use synchronized block instead of synchronized method?
- What is the difference between method wait() and sleep()?
- What is the difference between & and && operator?
- What is the difference between >> and >>> operator?
- In JDBC, which one is faster, Statement or PreparedStatement? Why?
I will be adding more questions later. Stay tuned!
Wednesday, 10 March 2010
Maven Plugin Dependency Duplication
Maven is a great build tool, and it has saved me from taking care of all the libraries and dependency hell, but it is not perfect, at least not in the version that I used (2.0.6). I wanted to use a newer version of one of the hibernate libraries, so I specified the new version in my project pom xml. The problem was that in the final war file, I had both the new version and the old version of the library. One of the plugin dependency actually depends on an older hibernate library, hence Maven automatically included both libraries. It is actually a known bug in 2.0.6 (see MNG-2972) and it's fixed in 2.0.9, so upgrading my Maven to 2.0.9 did the trick.
Monday, 8 March 2010
Transaction Pitfalls
Just thought that I need to post this very useful article about common transaction mistakes in Java platform. It's just so easy to assume that transaction works and then in the end (or worse, in production), you find out that it does not work as intended. The classic "Transaction Rollback" mistake is surprisingly common. I've seen this again and again as people assume that this would work automatically.
Thursday, 14 May 2009
Null Check for Java Bean Properties
I was trying to find out an easy way to check nulls in my Java Bean. There is this filter screen where I need to throw an Exception if all the properties are blank. This is required so that the database don't get hit with "Search All" query. I used BeanUtils from Apache Commons to get all the properties and StringUtils to check if the property is blank. Here is a snippet of the code that I used:
.
.
.
Map<String, String> map = BeanUtils.describe(searchCriteria);
boolean allBlank = true;
if (map != null) {
for (String key : map.keySet()) {
if ("class".equalsIgnoreCase(key) || "metaClass".equalsIgnoreCase(key))
continue;
if (StringUtils.isNotBlank(map.get(key))) {
LOG.info("key " + key + " is not null");
allBlank = false;
break;
}
}
}
if (allBlank) {
throw new IllegalArgumentException("searchCriteria cannot be blank"));
}
.
.
.
Labels:
java
Wednesday, 26 November 2008
java.lang.ClassCastException: oracle.sql.BLOB
This is by far the most annoying problem I've ever had. What ClassCastException??? This is my code:
It turned out that there are 2 Oracle JDBC jars in my Tomcat directory (common/lib and WEB-INF/lib), so I removed the one from WEB-INF, restarted the application, and it all worked fine.
oracle.sql.BLOB blob = (oracle.sql.BLOB) resultSet.getObject("fileBlob");
It turned out that there are 2 Oracle JDBC jars in my Tomcat directory (common/lib and WEB-INF/lib), so I removed the one from WEB-INF, restarted the application, and it all worked fine.
Tuesday, 9 September 2008
Custom Authentication Using Spring Security
Customising Spring Security could be a challenge as there seems to be lack of practical examples. Recently I tried to customise my login page when authentication fails. I found this blog really useful: Spring Security - Using custom Authentication Processing Filter
Monday, 14 July 2008
Spring Security (Acegi) and Sitemesh
Sitemesh is a great tool to decorate your java-based web page. I am currently using it to decorate my web application so that I can have the menu on the left panel, a header, and a footer withouth worrying about including it in all my jsp pages. Spring Security (formerly known as Acegi Security System) is another great tool that I also use together with Sitemesh for authentication and authorisation. My Spring Security "authorize" tag recently did not work properly, and the problem was because in my web.xml, I declared Sitemesh BEFORE Spring Security. Spring Security would clean up before Sitemesh is able to decorate the pages, causing Spring Security tags to stop working. The solution is to declare Sitemesh after Spring Security.
Thursday, 10 April 2008
Spring JMS
Using Spring JMS to send and receive messages to Queues is not difficult nowadays. I followed this tutorial in order to communicate to IBM MQ Series with no problem. It is simple, straightforward, and you can set up your applications in a very short amount of time.
Wednesday, 9 April 2008
Groovy Scripting
I've recently had a chance to use Groovy in my workplace. The script checks all connections to test server, including database connections and web services. It tries to log in using web services to all test servers and gives results.
This link provides a very good overview for Groovy starters, but the web service part is quite old, because now groovyws is much easier to use instead of groovysoap.
This link provides a very good overview for Groovy starters, but the web service part is quite old, because now groovyws is much easier to use instead of groovysoap.
Tuesday, 1 April 2008
Timezone and Daylight Savings
Recently I've had problems with Timezones becaus this year, Daylight Saving Time is extended for 1 week in NSW. The trouble is, there is no world time zone authority, and this has caused some dramas in the applications that I am looking after. The good news is that Sun has released a Java patch to fix Java's timezone database. For more information, see: http://java.sun.com/javase/timezones/DST_faq.html
Labels:
java
Thursday, 20 March 2008
Schema Spy
SchemaSpy is a database reverse engineering tool that generates information about your database, including relationships, constraints, columns, and it even detects potential anomalies that may exist in your database. In order to maximise the benefit, you'd need to install GraphViz so that the HTML report would include nice graphical stuff.
I recently downloaded both software and run it against an Oracle database with this command:
I installed the latest Oracle Express Edition so that I get the latest Oracle client and JDBC driver. Make sure ORACLE_HOME is set, and include "GraphViz\bin" and "ORACLE_HOME\bin" in your PATH.
I recently downloaded both software and run it against an Oracle database with this command:
# java -jar schemaSpy_3.1.1.jar -cp "D:\oraclexe\..\jdbc\lib\ojdbc14.jar"
-t ora -db [dbname] -s [schema] -u [user] -p [password] -cid -o output
I installed the latest Oracle Express Edition so that I get the latest Oracle client and JDBC driver. Make sure ORACLE_HOME is set, and include "GraphViz\bin" and "ORACLE_HOME\bin" in your PATH.
Monday, 10 March 2008
JBoss Deployment Order
JBoss by default deploys ear files before war files, but if you want to have this changed, here is how to do it:
- Edit C:\jboss-4.2.0.GA\server\default\conf\xmdesc\org.jboss.deployment.MainDeployer-xmbean.xml
- Look for EnhancedSuffixOrder
- Under descriptors tag, there is a value tag, and you would see "value" attribute
- Change the priority of the file type that you want. The format is "priority:file type" (the bigger the number, the lower the priority)
Thursday, 6 March 2008
Sun Tech Days
I've been attending Sun Tech Days in Darling Harbour. I attended the "Enterprise Track", but wanted to go to the "Desktop Track" at around 12:20 to check out "Java SE 6 Top 10 Features and Java SE 7", but it was full. It turned out that I was not the only one planning to do such a thing. I met some colleagues and ex-colleagues and had a time to catch up during lunch. The afternoon sessions were, I have to say, more useful to me, as there were practical examples and demos that I can relate to.
A few attendees asked an interesting question during the last session. The question was something like "If I was to create a java application with RDBMS back end, which framework should I use?". This is definitely one of the questions that I had always wanted to ask. It was a very good question, I thought, given the vast amount of frameworks that java developers can use in order to create an application. Well, there was no definite answer. Each framework has its own advantage/disadvantage. Spring's advantage, for example, is its ability to unit test business logic outside the container, and also AOP is useful. It is also interesting to note that Glassfish server now almost matches Tomcat in terms of startup time. I did notice that when the presenter started the server using NetBeans, it was pretty quick.
Anyway, I had fun in the event, and we had free lunch, dinner, and drinks, both alcoholic and non alcoholic..
A few attendees asked an interesting question during the last session. The question was something like "If I was to create a java application with RDBMS back end, which framework should I use?". This is definitely one of the questions that I had always wanted to ask. It was a very good question, I thought, given the vast amount of frameworks that java developers can use in order to create an application. Well, there was no definite answer. Each framework has its own advantage/disadvantage. Spring's advantage, for example, is its ability to unit test business logic outside the container, and also AOP is useful. It is also interesting to note that Glassfish server now almost matches Tomcat in terms of startup time. I did notice that when the presenter started the server using NetBeans, it was pretty quick.
Anyway, I had fun in the event, and we had free lunch, dinner, and drinks, both alcoholic and non alcoholic..
Labels:
java
Tuesday, 26 February 2008
Canoo WebTest
I have been looking for unit testing my web pages and came across Canoo WebTest recently. I have to say it is a very simple tool to use, flexible, produce excellent reports, and it supports groovy scripting language as well for more complicated tests. By following the screencast, I was able to start testing my web pages in less than half an hour.
Tuesday, 19 February 2008
File Download In Spring
In order to implement a file download in Spring, the key is returning null instead of a ModelAndView object. This controller that I created below is specifically for text/ascii data. You'd need to change the content type appropriately in order to download other file types.
public class DownloadController implements Controller {
/*
* Spring dependency injection
*/
private XService xService;
public void setxService(
XService xService) {
this.xService = xService;
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String idStr = request.getParameter("id");
if (idStr != null) {
long id = Long.parseLong(idStr);
String data = xService.getData(id);
doDownload(request, response, data, "file" + idStr + ".xml");
}
return null;
}
private void doDownload(HttpServletRequest request,
HttpServletResponse response, String data, String filename)
throws IOException {
int length = data.length();
ServletOutputStream op = response.getOutputStream();
response.setContentType("text/plain");
response.setContentLength(data.length());
response.setHeader("Content-Disposition",
"attachment; filename=\"" + filename + "\"");
byte[] bbuf = data.getBytes();
op.write(bbuf, 0, length);
op.flush();
op.close();
}
}
Accessing EJB 3 from Spring 2.5
Spring 2.5 now supports EJB 3 access, and it could not be any easier! Here is the spring xml snippet to achieve it:
<beans>
...
<!-- *** EJBs *** -->
<!-- REMOTE JNDI CONNECTION -->
<bean id="remoteJndiTemplate"
class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">
org.jnp.interfaces.NamingContextFactory
</prop>
<prop key="java.naming.provider.url">
localhost
</prop>
<prop key="java.naming.security.principal">
username
</prop>
<prop key="java.naming.security.credentials">
mycredentials
</prop>
</props>
</property>
</bean>
<bean id="abstractRemoteSlsb" abstract="true"
class="org.springframework.ejb.access.
SimpleRemoteStatelessSessionProxyFactoryBean">
<property name="lookupHomeOnStartup" value="false">
<property name="jndiTemplate">
<ref bean="remoteJndiTemplate" />
</property>
</bean>
<bean id="myService" parent="abstractRemoteSlsb">
<property name="jndiName"
value="myapp/MySessionBeanImpl/remote">
<property name="businessInterface"
value="au.com.package.name.MySessionBean">
</bean>
...
</beans>
Friday, 15 February 2008
Logging A StackTrace Exception
Logging an error seems to be a very easy job to do, but one of the common mistakes that Java programmers make is using the wrong method. Consider this piece of code:
Can you see what is really going on? If you have a look at commons logging's API, there are 2 error methods in the Log interface. All the above code does is it logs e.toString() to the error log, which means the error stack trace will be lost! Here is what you need to do instead:
try {
..
}
catch (Exception e) {
LOG.error(e);
}
Can you see what is really going on? If you have a look at commons logging's API, there are 2 error methods in the Log interface. All the above code does is it logs e.toString() to the error log, which means the error stack trace will be lost! Here is what you need to do instead:
try {
..
}
catch (Exception e) {
LOG.error("problem...", e);
}
Labels:
java
Wednesday, 13 February 2008
EJB 3.0 LazyInitializationException In Unit Tests
I have to say that unit testing in EJB is very challenging. All I want is doing unit tests on a local session bean that someone else created, so here is what I did:
- Create a remote interface
- Create a base interface from the current local session bean interface
- Delete all abstract methods on the local interface and extend the base interface
- Update the remote interface to extend the base interface
- Add the methods that I want to unit test in the remote interface
- Change the methods that I want to test in the implementation to public
- Edit the implementation class so that it extends both the local and remote interface
Gosh, if that is not time consuming, tell me what is! After all the effort, finally I wrote the actual unit test class, wrote the code to get the remote home that I created earlier using JNDI in the setUp() method, wrote my test, compile the whole project, and then start my JBoss.To my surprise, I got LazyInitializationException, so I thought, all the effort that I did earlier was useless! I tried googling and found some ways to avoid this exception. There are actually 4 ways to do this:
- Change the session bean to be stateful, and change the persistence context type to EXTENDED. Do I really need to do this just to get the test working?
- Run the session from within another session bean. Do I really need to create another one just to get the test working?
- Make fetch type EAGER (obviously). Impossible! There are lots of data, and therefore the laziness
- Create another method and use Hibernate's JOIN FETCH strategy. This one seems to be the cleanest and the least destructive solution
Honestly, why is it so hard to unit test a Session Bean? If the project had been done in Spring, there are Spring tools that can be utilised and therefore unit testing would have been much easier! See my earlier post to work around this Exception in Spring.
Subscribe to:
Posts (Atom)