Tuesday, February 14. 2017
Had an interesting discussion today in which a few points on Java came up. My primary focus has never been Java exclusively, so I am far from an expert, but I have been working with Java more extensively in the last few years with the Hadoop stack.
Explore the variety of Map implementations. I usually reach for HashMap when sometimes I should be thinking about the other Map types. Lots of other goodies to review there, when doing development with a 'get a project done' focus it's easy to forget these basics, there's a bunch of other interesting Java collections topics in the sidebar there too.
There are different reference types in Java which affect garbage collection. Many Java implementations make heavy use of object and object factories, let garbage collection throw away some of the extra stuff you may not need in your implementation.
In the fun with threads category, the volatile keyword. As the author at the link succinctly puts "poorly documented, poorly understood, and rarely used." Avoid reliance on a changing global variable when using threads, use immutable types. Related to this is Java's Atomic classes, another construct to allow simultaneous access among threads to common values. These can provide efficiency gains in advanced use cases, but in general really think, read about, and consider safer alternative patterns before using.
Tuesday, March 6. 2012
I get a lot of use out of Java 5 enums:
enum Galaxies { MilkyWay, Andromeda, NGC4414 }
But here's a nice trick; as enum members are actually classes, you can override the member functions they contain. I find this most useful overriding toString:
enum Galaxies {
MilkyWay {
@Override
public String toString() {
return "Milky Way";
},
Andromeda,
NGC4414 {
@Override
public String toString() {
return "NGC 4414";
}
}
Tuesday, March 22. 2011
When using Spring annotation based controllers, @RequestMapping must be applied to a method as well as the class or it will not work. For example:
@Controller
@RequestMapping("/blah.html")
public MyController {
@ModelAttribute("session")
public InventorySession getSession() {
return session;
}
}
Will result in No mapping found for HTTP request with URI [/[contextpath]/blah.html] errors. Request methods (or sub-pages) must be mapped to controller methods, i.e.:
. . .
@RequestMapping(method={RequestMethod.GET})
public String getForm() {
return "formView.jsp";
}
. . .
This mistake is particularly easy to make when migrating older code to the newer annotation based model, where mappings on legacy code may make it (erroneously) appear such linking is done in the xml file already.
Friday, March 4. 2011
Spring, my favorite Java application framework, doesn't provide an easy way to bind Spring-managed session beans to JSP pages. I have had success doing this by binding the bean to the request at creation time. When doing it this way, be sure to call the session bean somewhere in your dispatch servlet configuration or it will never be initialized when individual requests are created.
Note that for most applications, session beans are better left as plain objects managed independently of Spring for less overhead and to keep them as simple as possible. Each of these is going to take up space for each user. However, I have found some cases where accessing Spring objects from within a session bean is desirable; if you have as well or curiosity prevails, details are below.
Continue reading "Spring Session Bind to JSP"
Monday, October 25. 2010
I was recently asked how to do custom date parsing in Perl, specifically for a date in the format mmddyyyy. I work with dates frequently in Java, so I am familiar with using SimpleDateFormat objects to parse dates in this manner. The Perl equivalent is Date::Manip::Date.
Continue reading "Perl Custom Date Parsing"
Wednesday, March 3. 2010
Upgrading an old Java Swing application using Substance LAF to 5.3, the old method of instantiating org.jvnet.substance.SubstanceLookAndFeel fails as this class is now abstract. This is documented in the release notes; however instantiating a concrete skin using:
UIManager.setLookAndFeel(new SubstanceBusinessBlueSteelLookAndFeel());
Causes the following error for most of them on OS X:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: com.apple.laf.AquaRootPaneUI cannot be cast to org.jvnet.substance.SubstanceRootPaneUI
Use the third recommended option instead:
SubstanceLookAndFeel.setSkin(new SubstanceBusinessBlueSteelSkin());
This usage resolves the issue for every skin I've tested.
Tuesday, November 17. 2009
When working with automatic id's in Grails, sequence generation uses a less than useful default sequence name of hibernate_sequence . Use the following syntax as part of the GORM mapping to set the sequence name to something sane:
static mapping = {
id generator:sequence,params:[name:'mytable_id_seq']
}
Wednesday, November 11. 2009
Working on a Spring application using Hibernate recently I encountered the dreaded org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions error. Fixes for this vary widely; it can be caused by problems ranging from bad session handling in your framework configuration, bad cascade settings, incorrect persistence settings, to forgetting initialization of an array stored in a @ManyToOne database relation.
Make sure to check thoroughly for the latter before wasting hours changing the transaction handling, trying various cascade settings, or mucking with persistence annotations.
Wednesday, October 28. 2009
When using the FCKeditor plugin for Grails, if the data is loaded into the view this way:
<fckeditor:editor name="detail">
${fieldValue(bean:itemInstance,field:'detail')}
</fckeditor:editor>
The raw html being retrieved from the data source will not be parsed as expected. This will display as html source in the editor, and if saved will result in the html tags being placed into the data source as escaped text. For correct handling, add .decodeHTML() to the JSTL retrieval:
<fckeditor:editor name="detail">
${fieldValue(bean:itemInstance,field:'detail').decodeHTML()}
</fckeditor:editor>
Tuesday, June 9. 2009
Every programmer I know has played Dungeons and Dragons at some point. The C++ Lands Map is a beautiful merging of the two worlds. There are some amusing comments on the map at boing boing too.
I would love to have a poster print of this on some good quality parchment-like stock. Perhaps the author will do a commercial printing of it in the future.
Thursday, February 5. 2009
When building Spring controllers, it is often useful to access a DAO instance which has been set up in applicationContext.xml . To do so, add a variable in the controller for the DAO as well as a setter for it. Once this is done, wire it up by reference in dispatcher-servlet.xml .
Continue reading "Injecting DAO Objects Into Spring Controllers "
Often when working with Spring Web MVC mappings I want all calls to a certain extension handled by a generic resolver, i.e. mapping "*.html" to corresponding "*.jsp" entries in WEB-INF. This is easily done using UrlFilenameViewController which automatically passes the parsed filename to the view resolver.
Continue reading "Spring Generic URL Handling"
Monday, October 20. 2008
A Java Swing user interface I am working on which makes extensive use of a custom JTableModel implementation was failing. In certain instances when my data structure changes, it purges empty cells. If the cursor was left in these cells while this was taking place, the table would become unresponsive, often requiring an application restart to fix.
Watch for issues with setValueAt , which in some cases can be called with invalid values. In particular if the cursor is editing a field, the table is not refreshed until the edit focus leaves the widget even if you try to force it with validate() calls. In my instance the ideal fix was to add checks and do nothing instead of throwing exceptions.
With getValueAt , some table widget types choked on my default of null, which I was returning for invalid cells. Using an empty string instead of null for these invalid cells fixed this problem.
Wednesday, September 17. 2008
Firefox 3 introduces a new behavior when your doctype is XHTML Strict; certain tags that do not allow minimization as per the spec no longer close anyway. For example, if you use a <script src="blah.js" /> tag in your heading, Firefox 3 will take the whole rest of the page as a script, which will result in a blank page. This is good as it enforces standards compliance, however jspx minimizes tags, so you may have <script src="blah.js"></script> on your page, but the actual rendered page will minimize it.
There are many ways to fix this issue by playing tricks on jspx, I recommend:
<script src="blah.js"><!-- //prevent jspx minimization --></script>
This reminds me when I'm working on the code why that comment is there. Hopefully this will be fixed in the jspx spec at some point.
Thursday, June 5. 2008
A project I am working on requires binary image files and form data to be submitted simultaneously. This is rather easy to do with Spring, following the directions available in the latest documentation to handle file uploads in a form. It does not mention there that you can mix form fields as well as file upload fields when doing this, but it works as expected.
Continue reading "Spring Binary and Text Forms"
|