DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Coding Topics

article thumbnail
Spring 3 WebMVC - Optional Path Variables
Introduction To bind requests to controller methods via request pattern, Spring WebMVC's REST-feature is a perfect choice. Take a request like http://example.domain/houses/213234 and you can easily bind it to a controller method via annotation and bind path variables: ... @RequestMapping("/houses/{id}") public String handleHouse(@PathVariable long id) { return "viewHouse"; } Problem But the problem was, I needed optional path segments small and preview. That means, it would like to handle requests like /houses/preview/small/213234, /houses/small/213234, /houses/preview/213234 and the original /houses/213234. Why can't I use only one @RequestMapping for that. Ok, I could introduce three new methods with request mappings: ... @RequestMapping("/houses/{id}") public String handleHouse(@PathVariable long id) { return "viewHouse"; } @RequestMapping("/houses/preview/{id}") ... @RequestMapping("/houses/preview/small/{id}") ... @RequestMapping("/houses/small/{id}") ... But imagine I have 3 or 4 optional path segments. I would had 8 or 16 methods to handle all request. So, there must be another option. Browsing through the source code, I found an org.springframework.util.AntPathMatcher which is reponsable for parsing the request uri and extract variables. It seems to be the right place for an extension. Here is, how I would like to write my handler method: @RequestMapping("/houses/[preview/][small/]{id}") public String handlePreview(@PathVariable long id, @PathVariable("preview/") boolean preview, @PathVariable("small/") boolean small) { return "view"; } Solution Let's do the extension: package de.herold.spring3; import java.util.HashMap; import java.util.Map; import org.springframework.util.AntPathMatcher; /** * Extends {@link AntPathMatcher} to introduce the feature of optional path * variables. It's supports request mappings like: * * * @RequestMapping("/houses/[preview/][small/]{id}") * public String handlePreview(@PathVariable long id, @PathVariable("preview/") boolean preview, @PathVariable("small/") boolean small) { * ... * } * * */ public class OptionalPathMatcher extends AntPathMatcher { public static final String ESCAPE_BEGIN = "["; public static final String ESCAPE_END = "]"; /** * stores a request mapping pattern and corresponding variable * configuration. */ protected static class PatternVariant { private final String pattern; private Map variables; public Map getVariables() { return variables; } public PatternVariant(String pattern) { super(); this.pattern = pattern; } public PatternVariant(PatternVariant parent, int startPos, int endPos, boolean include) { final String p = parent.getPattern(); final String varName = p.substring(startPos + 1, endPos); this.pattern = p.substring(0, startPos) + (include ? varName : "") + p.substring(endPos + 1); this.variables = new HashMap(); if (parent.getVariables() != null) { this.variables.putAll(parent.getVariables()); } this.variables.put(varName, Boolean.toString(include)); } public String getPattern() { return pattern; } } /** * here we use {@link AntPathMatcher#doMatch(String, String, boolean, Map)} * to do the real match against the * {@link #getPatternVariants(PatternVariant) calculated patters}. If * needed, template variables are set. */ @Override protected boolean doMatch(String pattern, String path, boolean fullMatch, Map uriTemplateVariables) { for (PatternVariant patternVariant : getPatternVariants(new PatternVariant(pattern))) { if (super.doMatch(patternVariant.getPattern(), path, fullMatch, uriTemplateVariables)) { if (uriTemplateVariables != null && patternVariant.getVariables() != null) { uriTemplateVariables.putAll(patternVariant.getVariables()); } return true; } } return false; } /** * build recursicly all possible request pattern for the given request * pattern. For pattern: /houses/[preview/][small/]{id}, it * generates all combinations: /houses/preview/small/{id}, * /houses/preview/{id} /houses/small/{id} * /houses/{id} */ protected PatternVariant[] getPatternVariants(PatternVariant variant) { final String pattern = variant.getPattern(); if (!pattern.contains(ESCAPE_BEGIN)) { return new PatternVariant[] { variant }; } else { int startPos = pattern.indexOf(ESCAPE_BEGIN); int endPos = pattern.indexOf(ESCAPE_END, startPos + 1); PatternVariant[] withOptionalParam = getPatternVariants(new PatternVariant(variant, startPos, endPos, true)); PatternVariant[] withOutOptionalParam = getPatternVariants(new PatternVariant(variant, startPos, endPos, false)); return concat(withOptionalParam, withOutOptionalParam); } } /** * utility function for array concatenation */ private static PatternVariant[] concat(PatternVariant[] A, PatternVariant[] B) { PatternVariant[] C = new PatternVariant[A.length + B.length]; System.arraycopy(A, 0, C, 0, A.length); System.arraycopy(B, 0, C, A.length, B.length); return C; } } Now let Spring use our new path matcher. Here you have the Spring application context: That's it. Just set the pathMatcher property of AnnotationMethodHandlerAdapter. Fazit I know this implementation is far from being elegant or effective. My intention was to show an extension of the AntPathMatcher. Maybe someone gets inspired and provides an extension to handle pattern like: @RequestMapping("/houses/{**}/{id}") public String handleHouse(@PathVariable long id, @PathVariable("**") String inBetween) { return "viewHouse"; } to get the "**" as a concrete value. The sources for a little prove of concept are attached.
October 19, 2010
by Sebastian Herold
· 51,780 Views · 1 Like
article thumbnail
Step-by-Step Instructions for Integrating DJ Native Swing into NetBeans RCP
Here's how to integrate DJ Native Swing into a NetBeans RCP application. We will create multiple operating-system specific modules, each with the JARs and supporting classes needed for the relevant operating system. Then, in a module installer, we will enable only the module that is relevant for the operating system in question. I.e., if the user is on Windows, only the Windows module will be enabled, while all other modules will be disabled. Many thanks to Aljoscha Rittner for all of the code and each of the steps below. Any errors are my own, his instructions are perfect. 1. Download DJ Native Swing. 2. Go to download.eclipse.org/eclipse/downloads/drops/R-3.6-201006080911/. There, under the heading "SWT Binary and Source", download and extract the os-specific ZIPs that you want to support. 3. Unzip your downloaded ZIPs. Rename your swt.jar in the unzipped files to the full name of the zip. For example, instead of multiple "swt.jar" files, you'll now have JAR names such as "swt-3.6-gtk-linux-x86_64.jar" and "swt-3.6-win32-win32-x86_64.jar". Because these JARs will be in the same cluster folder in the NetBeans Platform application, they will need to have different names. 4. Let's start with Linux. Put the two DJ Native Swing JARs ("DJNativeSwing.jar" and "DJNativeSwing-SWT.jar") into a NetBeans library wrapper module named "com.myapp.nativeswing.linux64". Also put the "swt-3.6-gtk-linux-x86_64.jar" into the library wrapper module, while checking the "project.xml" and making sure there's a classpath extension entry for each of the three JARs in your library wrapper module. 5. Do the same for all the operating systems you're supporting, i.e., create a new library wrapper module like the above, with the operating-system specific SWT Jar, together with the two DJ Native Swing JARs. 6. Create a new module named "DJNativeSwingAPI", with code name base "com.myapp.nativeswing.api". 7. In the above main package, create a subpackage "browser", where you'll create an API to access the different implementations: public interface Browser { public JComponent getBrowserComponent(); public void browseTo (URL url); public void dispose(); } public interface BrowserProvider { public Browser createBrowser(); } 8. Make the "browser" package public and let all the operating-system specific library wrapper modules depend on the API module. 9. In each of the operating-system specific modules, create an "impl" subpackage with the following content, here specifically for Windows 64 bit: package com.myapp.nativeswing.windows64.impl; import chrriis.dj.nativeswing.swtimpl.NativeInterface; import com.myapp.nativeswing.api.browser.Browser; import com.myapp.nativeswing.api.browser.BrowserProvider; import org.openide.util.lookup.ServiceProvider; @ServiceProvider(service = BrowserProvider.class) public class Win64BrowserProvider implements BrowserProvider { private boolean isInitialized; @Override public Browser createBrowser() { initialize(); return new Win64Browser(); } private synchronized void initialize() { if (!isInitialized) { NativeInterface.open(); isInitialized = true; } } } import chrriis.dj.nativeswing.NSComponentOptions; import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser; import com.myapp.nativeswing.api.browser.Browser; import java.net.URL; import javax.swing.JComponent; class Win64Browser implements Browser { private JWebBrowser webBrowser; public Win64Browser() { //If not this, browser component creates exceptions when you move it around, //this flag is for the native peers to recreate in the new place: webBrowser = new JWebBrowser(NSComponentOptions.destroyOnFinalization()); } public JComponent getBrowserComponent() { return webBrowser; } public void browseTo(URL url) { webBrowser.navigate(url.toString()); } public void dispose() { webBrowser.disposeNativePeer(); webBrowser = null; } } 10. Copy the above two classes into all your other operating-system specific library wrapper modules. Rename the classes accordingly. 11. In the DJ Native Swing API module, create a new subpackage named "utils", with this class, which programmatically enables/disables modules using the NetBeans AutoUpdate API: import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.netbeans.api.autoupdate.OperationContainer; import org.netbeans.api.autoupdate.OperationContainer.OperationInfo; import org.netbeans.api.autoupdate.OperationException; import org.netbeans.api.autoupdate.OperationSupport; import org.netbeans.api.autoupdate.OperationSupport.Restarter; import org.netbeans.api.autoupdate.UpdateElement; import org.netbeans.api.autoupdate.UpdateManager; import org.netbeans.api.autoupdate.UpdateUnit; import org.openide.LifecycleManager; import org.openide.modules.ModuleInfo; import org.openide.util.Exceptions; import org.openide.util.Lookup; /** * Der ModuleHandler ist eine Hilfsklasse zum programatischen (de)aktivieren * von Modulen und der Analyse von installierten aktiven Modulen. * @author rittner */ public class ModuleHandler { private boolean restart = false; private OperationContainer oc; private Restarter restarter; private final boolean directMode; public ModuleHandler() { this (false); } public ModuleHandler(boolean directMode) { this.directMode = directMode; } /** * Gibt eine sortierte Liste der Codename-Base aller aktiven installierten * Module zurück. * * Es handelt sich dabei explizit um einen aktuellen Zwischenstand, der sich * jeder Zeit verändern kann. * @param startFilter Es werden nur die Module zurückgegeben, die mit dem Startfilter-Namen anfangen (oder null für alle) * @param includeDisabled Wenn true, werden auch alle inaktiven Module ermittelt. * @return Sortierte Liste der Codename-Base */ public List getModules(String startFilter, boolean includeDisabled) { List activatedModules = new ArrayList(); Collection lookupAll = Lookup.getDefault().lookupAll(ModuleInfo.class); for (ModuleInfo moduleInfo : lookupAll) { if (includeDisabled || moduleInfo.isEnabled()) { if (startFilter == null || moduleInfo.getCodeNameBase().startsWith(startFilter)) { activatedModules.add(moduleInfo.getCodeNameBase()); } } } Collections.sort(activatedModules); return activatedModules; } /** * Führt einen Neustart der Anwendung durch, wenn der vorherige setModulesState * ein Flag dafür gesetzt hat. mit force, kann der Restart erzwungen werden. * * Man sollte nicht davon ausgehen, dass nach dem Aufruf der Methode * zurückgekehrt wird. * @param force */ public void doRestart(boolean force) { if (force || restart) { if (oc != null && restarter != null) { try { oc.getSupport().doRestart(restarter, null); } catch (OperationException ex) { Exceptions.printStackTrace(ex); } } else { LifecycleManager.getDefault().markForRestart(); LifecycleManager.getDefault().exit(); } } } /** * Aktiviert oder deaktivert die Liste der Module * @param enable * @param codeNames * @return true, wenn ein Neustart zwingend erforderlich ist */ public boolean setModulesState (boolean enable, Set codeNames) { boolean restartFlag; if (enable) { restartFlag = setModulesEnabled(codeNames); } else { restartFlag = setModulesDisabled(codeNames); } return restart = restart || restartFlag; } private boolean setModulesDisabled(Set codeNames) { Collection toDisable = new HashSet(); List allUpdateUnits = UpdateManager.getDefault().getUpdateUnits(UpdateManager.TYPE.MODULE); for (UpdateUnit unit : allUpdateUnits) { if (unit.getInstalled() != null) { UpdateElement el = unit.getInstalled(); if (el.isEnabled()) { if (codeNames.contains(el.getCodeName())) { toDisable.add(el); } } } } if (!toDisable.isEmpty()) { oc = directMode ? OperationContainer.createForDirectDisable() : OperationContainer.createForDisable(); for (UpdateElement module : toDisable) { if (oc.canBeAdded(module.getUpdateUnit(), module)) { OperationInfo operationInfo = oc.add(module); if (operationInfo == null) { continue; } // get all module depending on this module Set requiredElements = operationInfo.getRequiredElements(); // add all of them between modules for disable oc.add(requiredElements); } } try { // get operation support for complete the disable operation OperationSupport support = oc.getSupport(); // If support is null, no element can be disabled. if ( support != null ) { restarter = support.doOperation(null); } } catch (OperationException ex) { Exceptions.printStackTrace(ex); } } return restarter != null; } private boolean setModulesEnabled(Set codeNames) { Collection toEnable = new HashSet(); List allUpdateUnits = UpdateManager.getDefault().getUpdateUnits(UpdateManager.TYPE.MODULE); for (UpdateUnit unit : allUpdateUnits) { if (unit.getInstalled() != null) { UpdateElement el = unit.getInstalled(); if (!el.isEnabled()) { if (codeNames.contains(el.getCodeName())) { toEnable.add(el); } } } } if (!toEnable.isEmpty()) { oc = OperationContainer.createForEnable(); for (UpdateElement module : toEnable) { if (oc.canBeAdded(module.getUpdateUnit(), module)) { OperationInfo operationInfo = oc.add(module); if (operationInfo == null) { continue; } // get all module depending on this module Set requiredElements = operationInfo.getRequiredElements(); // add all of them between modules for disable oc.add(requiredElements); } } try { // get operation support for complete the enable operation OperationSupport support = oc.getSupport(); if (support != null) { restarter = support.doOperation(null); } return true; } catch (OperationException ex) { Exceptions.printStackTrace(ex); } } return false; } } 12. Create a ModuleInstall class in the API module. In this class, we need to create a map, connecting all the operating systems to the related code name base of the module relevant to the specific operating system. For this, we use "os.arch" and "os.name". Then we create an enable list and a disable list for the code name base. We create two handlers, one to disable everything, the other to enable just the relevant module. public class Installer extends ModuleInstall { @Override public void restored() { Map modelMap = new HashMap(); modelMap.put("Windows.64", "com.myapp.nativeswing.windows64"); modelMap.put("Linux.64", "com.myapp.nativeswing.linux64"); String osArch = System.getProperty("os.arch"); if ("amd64".equals(osArch)) { osArch = "64"; } else { osArch = "32"; } String osName = System.getProperty("os.name"); if (osName.startsWith("Windows")) { osName = "Windows"; } if (osName.startsWith("Mac")) { osName = "Mac"; } Map osNameMap = new HashMap(); osNameMap.put("Windows", "Windows"); osNameMap.put("Linux", "Linux"); osNameMap.put("Mac", "Mac"); String toEnable = modelMap.get(osNameMap.get(osName) + "." + osArch); Set toDisable = new HashSet(modelMap.values()); if (toEnable != null) { toDisable.remove(toEnable); } ModuleHandler disabler = new ModuleHandler(true); disabler.setModulesState(false, toDisable); ModuleHandler enabler = new ModuleHandler(true); enabler.setModulesState(true, Collections.singleton(toEnable)); } } 13. Finally, create yet another module, where the TopComponent will be found that will host the browser from DJ Native Swing. So, create a new module, add a window where the browser will appear, and set a dependency on the DJ Native Swing API module. In the constructor of the window add the following: setLayout(new BorderLayout()); BrowserProvider bp = Lookup.getDefault().lookup(BrowserProvider.class); if (bp!=null){ Browser createBrowser = bp.createBrowser(); add(createBrowser.getBrowserComponent(), BorderLayout.CENTER); } 14. By default, library wrapper modules are set to "1.4" source code level and to "autoload". You will need to change "1.4" to "1.6" (since you're using annotations above). You will also need to change "autoload" to "regular", otherwise they will never be loaded, since no module depends on them. 15. On Linux, at least on Ubuntu, make sure you have done something like this: export MOZILLA_FIVE_HOME=/usr/lib/mozilla export LD_LIBRARY_PATH=$MOZILLA_FIVE_HOME On Linux (at least on Ubuntu), you also need to set an impl dependency on the "JNA" module. 16. In "platform.properties", add this line: run.args.extra=-J-Dsun.awt.disableMixing=true Hurray, you're done, once you run the application: Note: above I followed these instructions to remove the tab in the browser window.
October 18, 2010
by Geertjan Wielenga
· 52,063 Views
article thumbnail
Practical PHP Patterns: Record Set
This is the last article from the Practical PHP Patterns series. Stay tuned on css.dzone.com for the new series, Practical PHP Testing Patterns. The RecordSet pattern's goal is to represent a set of relational database rows, with the main purpose of giving access to their values (a data structure), sometimes with the possibility of modification (via single Row Data Gateway instances). Despite the term set, the rows have usually a defined order. The intent is ultimately representing a result from an SQL query with an object, to gain the usual advantages of objects over scalars and functions: it can be passed around but maintain its encapsulated behavior, injected, mocked, wrapped and so on. A Record Set is usually not mocked if it is provided by an external extension or library, because instancing a real one working on a lightweight database such as Sqlite is used in substitution for the real one. Especially in the PHP world, this solution is fast enough to become a standard. Today, Record Set is less used on the client side to favor Object-Relational Mapping approaches, which make some kind of translation over the raw rows (what an horrible pun). Record Set instead maintains by definition a one-to-one relationship with the table rows, and it is still diffused in ORM internals (such as Doctrine's own code) or in applications that call PDO directly. It is a fairly basic pattern, but given that a vast part of legacy PHP applications still uses mysql_query()... Interesting things happen when... Interesting leverages of this pattern happen when someone stays in the middle between the Record Set creation and the user interface, with the goal of modifying or decorating it. The UI can then explore the RecordSet and automatically generate itself, in a form of scaffolding. Continuing on this line of thought, UI components can edit the RecordSet without knowing the model which it refers to, via building forms driven by the Record Set metadata. This solution is diffused, but it does not scale to Domain Models with a level of complexity greater than plain arrays. Of course, the Record Set may also encapsulate business logic as a low-cost form of Domain Model. In this case, the ability to unlink it from the database connection is important to its serializability and ease of testing. Examples PDOStatement represents both a SQL query and a RecordSet implementation, after it has been executed. When fetching all the results, it returns an array. In other languages Record Sets are more evolved and can for example be used to navigate a table and modify only certain records (via their annexed Row Data Gateway). PDOStatement is used only for reading. If you want further functionalities (which obviously depends on your domain), you should create your own Record Set accordingly. It is probably best to wrap the PDOStatement because extending it is out of question due to the instantiation not being under our control. connection = $connection; } public function getTweetsRecordSet($username) { /** * @var PDOStatement this is a Record Set */ $stmt = $this->connection->prepare('SELECT * FROM tweets WHERE username = :username'); $stmt->bindValue(':username', $username, PDO::PARAM_STR); $stmt->execute(); return $stmt; } } $pdo = new PDO('sqlite::memory:'); $pdo->exec('CREATE TABLE tweets (id INT NOT NULL, username VARCHAR(255) NOT NULL, text VARCHAR(255) NOT NULL, PRIMARY KEY(id))'); $pdo->exec('INSERT INTO tweets (id, username, text) VALUES (42, "giorgiosironi", "Practical PHP Patterns has come to an end")'); $pdo->exec('INSERT INTO tweets (id, username, text) VALUES (43, "giorgiosironi", "Cool series: will continue as Practical PHP Testing Patterns")'); // client code $table = new TweetsTable($pdo); $recordSet = $table->getTweetsRecordSet('giorgiosironi'); while ($row = $recordSet->fetch()) { var_dump($row['text']); }
October 18, 2010
by Giorgio Sironi
· 3,369 Views
article thumbnail
Enum Tricks: Customized valueOf
When I am writing enumerations I very often found myself implementing a static method similar to the standard enum’s valueOf() but based on field rather than name: public static TestOne valueOfDescription(String description) { for (TestOne v : values()) { if (v.description.equals(description)) { return v; } } throw new IllegalArgumentException( "No enum const " + TestOne.class + "@description." + description); } Where “description” is yet another String field in my enum. And I am not alone. See this article for example. Obviously this method is very ineffective. Every time it is invoked it iterates over all members of the enum. Here is the improved version that uses a cache: private static Map map = null; public static TestTwo valueOfDescription(String description) { synchronized(TestTwo.class) { if (map == null) { map = new HashMap(); for (TestTwo v : values()) { map.put(v.description, v); } } } TestTwo result = map.get(description); if (result == null) { throw new IllegalArgumentException( "No enum const " + TestTwo.class + "@description." + description); } return result; } It is fine if we have only one enum and only one custom field that we use to find the enum value. But if we have 20 enums, and each has 3 such fields, then the code will be very verbose. As I dislike copy/paste programming I have implemented a utility that helps to create such methods. I called this utility class ValueOf. It has 2 public methods: public static , V> T valueOf(Class enumType, String fieldName, V value); which finds the required field in specified enum. It is implemented utilizing reflection and uses a hash table initialized during the first call for better performance. The other overridden valueOf() looks like: public static > T valueOf(Class enumType, Comparable comparable); This method does not cache results, so it iterates over enum members on each invocation. But it is more universal: you can implement comparable as you want, so this method may find enum members using more complicated criteria. Full code with examples and JUnit test case are available here. Conclusions Java Enums provide the ability to locate enum members by name. This article describes a utility that makes it easy to locate enum members by any other field.
October 16, 2010
by Alexander Radzin
· 80,208 Views
article thumbnail
Reduce Boilerplate Code for DAO's -- Hades Introduction
Most web applications will have DAO's for accessing the database layer. A DAO provides an interface for some type of database or persistence mechanism, providing CRUD and finders operations without exposing any database details. So, in your application you will have different DAO's for different entities. Most of the time, code that you have written in one DAO will get duplicated in other DAO's because much of the functionality in DAO's is same (like CRUD and finder methods). One of way of avoiding this problem is to have generic DAO and have your domain classes inherit this generic DAO implementation. You can also add finders using Spring AOP; this approach is explained Per Mellqvist in this article. There is a problem with the approach: this boiler plate code becomes part of your application source code and you will have to maintain it. The more code you write, there are more chances of new bugs getting introduced in your application. So, to avoid writing this code in an application, we can use an open source framework called Hades. Hades is a utility library to work with Data Access Objects implemented with Spring and JPA. The main goal is to ease the development and operation of a data access layer in applications. In this article, I will show you how easy it is write DAO's using Hades without writing any boiler plate code. In order to introduce you to Hades, I will show you how we can manage an entity like Book. Before we write any code we need to add the following dependencies to pom.xml. org.synyx.hades org.synyx.hades 2.0.0.RC3 org.hibernate hibernate-entitymanager 3.5.5-Final So, lets start by creating a Book Entity import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(unique = true) private String title; private String author; private String isbn; private double price; // setters and getters } This is a very simple JPA entity without any relationships. Now that we have modeled our entity we need to add a DAO interface for handling persistence operations. You need to create a BookDao interface which will extend GenericDao interface provided by Hades. GenericDao is an interface for generic CRUD operations on a DAO for a specific type. So, we passed the type parameters Book for entity and Long for id. import org.synyx.hades.dao.GenericDao; public interface BookDao extends GenericDao { } GenericDao has an default implementation called GenericJpaDao which provides implementation of all its operations. Now that we have created a BookDao interface, we will configure it in the Spring application context xml. Hades provides a factory bean which will provide the DAO instance for the given interface (in our case BookDao). In the xml shown above I have used a new feature introduced in Spring 3 Embedded Databases to give me the instance of HSQL database datasource. You can refer to my earlier post on Embedded databases in case you are not aware of it. I have used Hibernate as my JPA provider so you need to configure it in persistence.xml as shown below org.hibernate.ejb.HibernatePersistence Next we will write a JUnit test for testing this code. @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @Transactional public class BookDaoTest { @Autowired private BookDao bookDao; private Book book; @Before public void setUp() throws Exception { book = new Book(); book.setAuthor("shekhar"); book.setTitle("Effective Java"); book.setPrice(500); book.setIsbn("1234567890123"); } @Test public void shouldCreateABook() throws Exception { Book persistedBook = bookDao.save(book); assertBook(persistedBook); } @Test public void shouldReadAPersistedBook() throws Exception { Book persistedBook = bookDao.save(book); Book bookReadByPrimaryKey = bookDao.readByPrimaryKey(persistedBook.getId()); assertBook(bookReadByPrimaryKey); } @Test public void shouldDeleteBook() throws Exception { Book persistedBook = bookDao.save(book); bookDao.delete(persistedBook); Book bookReadByPrimaryKey = bookDao.readByPrimaryKey(persistedBook.getId()); assertNull(bookReadByPrimaryKey); } private void assertBook(Book persistedBook) { assertThat(persistedBook, is(notNullValue())); assertThat(persistedBook.getId(), is(not(equalTo(null)))); assertThat(persistedBook.getAuthor(), equalTo(book.getAuthor())); } } Auto Configuration Using Spring Namespaces The way that we have configured the DAO can become quite cumbersome if the number of DAO's increases. To overcome this we can make use of namespaces to configure daos. This configuration will trigger the auto detection mechanism of DAOs that extend GenericDAO or Extended-GenericDAO. It will create DAO instances for all the DAO interfaces found in this package. You can use or for including or excluding interfaces from getting their beans created. Adding Finders and Query Methods So far we have used the inbuilt operations provided by GenericDao but most of the time we need to add our own finders methods like findByAuthorAndTitle, findWithPriceLessThan . Hades makes it very easy for you to add such methods in your domain dao interface like BookDao. Hades provides 3 strategies for creating JPA query at runtime. These are :- CREATE : This will create a JPA query from method name. This strategy ties you with the method name so you have to think twice before changing the method name. public interface BookDao extends GenericDao { public Book findByAuthorAndTitle(String author, String title); } // test code @Test public void shouldFindByAuthorAndTitle() throws Exception { Book persistedBook = bookDao.save(book); Book bookByAuthorAndTitle = bookDao.findByAuthorAndTitle("shekhar", "Effective Java"); assertBook(bookByAuthorAndTitle); } USE DECLARED QUERY : This lets you define query using JPA @NamedQuery or Hades @Query annotation. If no query is found exception will be thrown. @Query("FROM Book b WHERE b.author = ?1") public Book findBookByAuthorName(String author); // test code public void shouldFindBookByAuthorName() { Book persistedBook = bookDao.save(book); Book bookByAuthor = bookDao.findBookByAuthorName("shekhar"); assertBook(bookByAuthor); } CREATE IF NOT FOUND : It is the combination of both the strategies mentioned above. It will first lookup for the declared query and if it is not found will lookup for method name. This is by default option and you can change it by changing query-lookup-strategy attribute in hades:dao-config element. Hades queries also has the support for pagination and sorting. You can pass the instance of Pageable and Sort to the finder methods create above. public Page findByAuthor(String author, Pageable pageable); public List findByAuthor(String author, Sort sort); Hades is not limited to just limited to CRUD and adding custom finder methods. There are some other features like auditing ,Specifications,etc that I will discuss in second part of this article.
October 15, 2010
by Shekhar Gulati
· 21,230 Views
article thumbnail
Asynchronous (non-blocking) Execution in JDBC, Hibernate or Spring?
There is no so-called asynchronous execution support in JDBC mainly because most of the time you want to wait for the result of your DML or DDL, or because there is too much complexity involved between the back-end database and the front end JDBC driver. Some database vendors do provide such support in their native drives. For example Oracle supports non-blocking calls in its native OCI driver. Unfortunately it is based on polling instead of callback or interrupt. Neither Hibernate or Spring supports this feature. But sometimes you do need such a feature. For example some business logic is still implemented using legacy Oracle PL/SQL stored procedures and they run pretty long. The front-end UI doesn't want to wait for its finish and it just needs to check the running result later in a database logging table into which the store procedure will write the execution status. In other cases your front-end application really cares about low latency and doesn't care too much about how individual DML is executed. So you just fire a DML into the database and forget the running status. Nothing can stop you from making asynchronous DB calls using multi-threading in your application. (Actually even Oracle recommends to use multi-thread instead of polling OCI for efficiency). However you must think about how to handle transaction and connection (or Hibernate Session) in threads. Before continuing, let's assume we are only handling local transaction instead of JTA. 1. JDBC It is straightforward. You just create another thread (DB thread hereafter) from the calling thread to make the actual JDBC call. If such a call is frequent, you call use ThreadPoolExecutor to reduce thread's creation and destroy overhead. 2. Hibernate You usually use session context policy "thread" for Hibernate to automatically handle your session and transaction. With this policy, you get one session and transaction per thread. When you commit the transaction, Hibernate automatically closes the session. Again you need to create a DB thread for the actual stored procedure call. Some developer may be wondering whether the new DB thread inherits its parent calling thread's session and transaction. This is an important question. First of all, you usually don't want to share the same transaction between the calling thread and its spawned DB thread because you want to return immediately from the calling thread and if both threads share the same session and transaction, the calling thread can't commit the transaction and long running transaction should be avoided. Secondly Hibernate's "thread" policy doesn't support such inheritance because if you look at Hibernate's corresponding ThreadLocalSessionContext, it is using ThreadLocal class instead of InheritableThreadLocal. Here is a sample code in the DB thread: // Non-managed environment and "thread" policy is in place // gets a session first Session sess = factory.getCurrentSession(); Transaction tx = null; try { tx = sess.beginTransaction(); // call the long running DB stored procedure //Hibernate automatically closes the session tx.commit(); } catch (RuntimeException e) { if (tx != null) tx.rollback(); throw e; } 3.Spring's Declarative Transaction Let's suppose your stored procedure call is included in method: @Transactional(readOnly=false) public void callDBStoredProcedure(); The calling thread has the following method to call the above method asynchronously using Spring's TaskExecutor: @Transactional(readOnly=false) public void asynchCallDBStoredProcedure() { //creates a DB thread pool this.taskExecutor.execute(new Runnable() { @Override public void run() { //call callDBStoredProcedure() } }); } You usually configure Spring's HibernateTransactionManager and the default proxy mode (aspectj is another mode) for declarative transactions. This class binds a transaction and a Hibernate session to each thread and doesn't Inheritance either just like Hibernate's "thread" policy. Where you put the above method callDBStoredProcedure() makes a huge difference. If you put the method in the same class as the calling thread, the declared transaction for callDBStoredProcedure() doesn't take place because in the proxy mode only external or remote method calls coming in through the AOP proxy (an object created by the AOP framework in order to implement the transaction aspect. This object supports your calling thread's class by composing an instance of your calling thread class) will be intercepted. This meas that "self-invocation", i.e. a method within the target object (the composed instance of your calling thread class in the AOP proxy) calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with @Transactional! So you must put callDBStoredProcedure() in a different class as a Spring's bean so that the DB thread in method asynchCallDBStoredProcedure() can load that bean's AOP proxy and call callDBStoredProcedure() through that proxy. About The Author Yongjun Jiao is a technical manager with SunGard Consulting Services. He has been a professional software developer for the past 10 years. His expertise covers Java SE, Java EE, Oracle, application tuning and high performance and low latency computing.
October 15, 2010
by Yongjun Jiao
· 98,347 Views · 6 Likes
article thumbnail
Mockito - Pros, Cons, and Best Practices
It's been almost 4 years since I wrote a blog post called "EasyMock - Pros, Cons, and Best Practices, and a lot has happened since. You don't hear about EasyMock much any more, and Mockito seems to have replaced it in mindshare. And for good reason: it is better. A Good Humane Interface for Stubbing Just like EasyMock, Mockito allows you to chain method calls together to produce less imperative looking code. Here's how you can make a Stub for the canonical Warehouse object: Warehouse mock = Mockito.mock(Warehouse.class); Mockito.when(mock.hasInventory(TALISKER, 50)). thenReturn(true); I know, I like a crazy formatting. Regardless, giving your System Under Test (SUT) indirect input couldn't be easier. There is no big advantage over EasyMock for stubbing behavior and passing a stub off to the SUT. Giving indirect input with mocks and then using standard JUnit asserts afterwards is simple with both tools, and both support the standard Hamcrest matchers. Class (not just Interface) Mocks Mockito allows you to mock out classes as well as interfaces. I know the EasyMock ClassExtensions allowed you to do this as well, but it is a little nicer to have it all in one package with Mockito. Supports Test Spies, not just Mocks There is a difference between spies and mocks. Stubs allow you to give indirect input to a test (the values are read but never written), Spies allow you to gather indirect output from a test (the mock is written to and verified, but does not give the test input), and Mocks are both (your object gives indirect input to your test through Stubbing and gathers indirect output through spying). The difference is illustrated between two code examples. In EasyMock, you only have mocks. You must set all input and output expectations before running the test, then verify afterwards. // arrange Warehouse mock = EasyMock.createMock(Warehouse.class); EasyMock.expect( mock.hasInventory(TALISKER, 50)). andReturn(true).once(); EasyMock.expect( mock.remove(TALISKER, 50)). andReturn(true).once(); EasyMock.replay(mock); //act Order order = new Order(TALISKER, 50); order.fill(warehouse); // assert EasyMock.verify(mock); That's a lot of code, and not all of it is needed. The arrange section is setting up a stub (the warehouse has inventory) and setting up a mock expectation (the remove method will be called later). The assertion in all this is actually the little verify() method at the end. The main point of this test is that remove() was called, but that information is buried in a nest of expectations. Mockito improves on this by throwing out both the record/playback mode and a generic verify() method. It is shorter and clearer this way: // arrange Warehouse mock = Mockito.mock(Warehouse.class); Mockito.when(mock.hasInventory(TALISKER, 50)). thenReturn(true); //act Order order = new Order(TALISKER, 50); order.fill(warehouse); // assert Mockito.verify(warehouse).remove(TALISKER, 50); The verify step with Mockito is spying on the results of the test, not recording and verifying. Less code and a clearer picture of what really is expected. Update: There is a separate Spy API you can use in Mockito as well: http://mockito.googlecode.com/svn/branches/1.8.3/javadoc/org/mockito/Mockito.html#13 Better Void Method Handling Mockito handles void methods better than EasyMock. The fluent API works fine with a void method, but in EasyMock there were some special methods you had to write. First, the Mockito code is fairly simple to read: // arrange Warehouse mock = Mockito.mock(Warehouse.class); //act Order order = new Order(TALISKER, 50); order.fill(warehouse); // assert Mockito.verify(warehouse).remove(TALISKER, 50); Here is the same in EasyMock. Not as good: // arrange Warehouse mock = EasyMock.createMock(Warehouse.class); mock.remove(TALISKER, 50); EasyMock.expectLastMethodCall().once(); EasyMock.replay(mock); //act Order order = new Order(TALISKER, 50); order.fill(warehouse); // assert EasyMock.verify(mock); Mock Object Organization Patterns Both Mockito and EasyMock suffer from difficult maintenance. What I said in my original EasyMock post holds true for Mockito: The method chaining style interface is easy to write, but I find it difficult to read. When a test other than the one I'm working on fails, it's often very difficult to determine what exactly is going on. I end up having to examine the production code and the test expectation code to diagnose the issue. Hand-rolled mock objects are much easier to diagnose when something breaks... This problem is especially nasty after refactoring expectation code to reduce duplication. For the life of me, I cannot follow expectation code that has been refactored into shared methods. Now, four years later, I have a solution that works well for me. With a little care you can make your mocks reusable, maintainable, and readable. This approach was battle tested over many months in an Enterprise Environment(tm). Create a private static method the first time you need a mock. Any important data needs to be passed in as a parameter. Using constants or "magic" fields hides important information and obfuscates tests. For example: User user = createMockUser("userID", "name"); ... assertEquals("userID", result.id()); assertEquals("name", result.name(); Everything important is visible and in the test, nothing important is hidden. You need to completely hide the replay state behind this factory method if you're still on EasyMock. The Mock framework in use is an implementation detail and try not to let it leak. Next, as your dependencies grow, be sure to always pass them in as factory method parameters. If you need a User and a Role object, then don't create one method that creates both mocks. One method instantiates one object, otherwise it is a parameter and compose your mock objects in the test method: User user = createMockUser( "userID", "name", createMockRole("role1"), createMockRole("role2") ); When each object type has a factory method, then it makes it much easier to compose the different types of objects together. Reuse. But you can only reuse the methods when they are simple and with few dependencies, otherwise they become too specific and difficult to understand. The first time you need to reuse one of these methods, then move the method to a utility class called "*Mocker", like UserMocker or RoleMocker. Follow a naming convention so that they are always easy to find. If you remembered to make the private factory methods static then moving them should be very simple. Your client code ends up looking like this, but you can use static imports to fix that: User user = UserMocker.createMockUser( "userID", "name", RoleMocker.createMockRole("role1"), RoleMocker.createMockRole("role2") ); User overloaded methods liberally. Don't create one giant method with every possible parameter in the parameter list. There are good reasons to avoid overloading in production, but this is test. Use overloading so that the test methods only display data relevant to that test and nothing more. Using Varargs can also help keep a clean test. Lastly, don't use constants. Constants hide the important information out of sight, at the top of the file where you can't see it or in a Mocker class. It's OK to use constants within the test case, but don't define constants in the Mockers, it just hides relevant information and makes the test harder to read later. Avoid Abstract Test Cases Managing mock objects within abstract test cases has been very difficult for me, especially when managing replay and record states. I've given up mixing mock objects and abstract TestCase objects. When something breaks it simply takes too long to diagnose. An alternative is to create custom assertion methods that can be reused. Beyond that, I've given up on Abstract TestCase objects anyway, on the grounds of preferring composition of inheritance. Don't Replace Asserts with Verify My original comments about EasyMock are still relevant for Mockito: The easiest methods to understand and test are methods that perform some sort of work. You run the method and then use asserts to make sure everything worked. In contrast, mock objects make it easy to test delegation, which is when some object other than the SUT is doing work. Delegation means the method's purpose is to produce a side-effect, not actually perform work. Side-effect code is sometimes needed, but often more difficult to understand and debug. In fact, some languages don't even allow it! If you're test code contains assert methods then you have a good test. If you're code doesn't contain asserts, and instead contains a long list of verify() calls, then you're relying on side effects. This is a unit-test bad smell, especially if there are several objects than need to be verified. Verifying several objects at the end of a unit test is like saying, "My test method needs to do several things: x, y, and z." The charter and responsibility of the method is no longer clear. This is a candidate for refactoring. No More All or Nothing Testing Mockito's verify() methods are much more flexible than EasyMock's. You can verify that only one or two methods on the mock were called, while EasyMock had just one coarse verify() method. With EasyMock I ended up littering the code with meaningless expectations, but not so in Mockito. This alone is reason enough to switch. Failure: Expected X received X For the most part, Mockito error messages are better than EasyMock's. However, you still sometimes see a failure that reads "Failure. Got X Expected X." Basically, this means that your toString() methods produce the same results but equals() does not. Every user who starts out gets confused by this message at some point. Be Warned. Don't Stop Handrolling Mocks Don't throw out hand-rolled mock objects. They have their place. Subclass and Override is a very useful technique for creating a testing seam, use it. Learn to Write an ArgumentMatcher Learn to write an ArgumentMatcher. There is a learning curve but it's over quickly. This post is long enough, so I won't give an example. That's it. See you again in 4 years when the next framework comes out! From http://hamletdarcy.blogspot.com/2010/09/mockito-pros-cons-and-best-practices.html
October 14, 2010
by Hamlet D'Arcy
· 57,184 Views
article thumbnail
IntelliJ IDEA Shortcut Wallpaper
The fastest developers use the keyboard almost exclusively. To help you learn the IntelliJ IDEA shortcuts, I created a desktop wallpaper that lists the most common ones for Linux, Mac and Windows users. Can't remember the command? Just pop up the desktop and check it out. Bored while waiting for a compile? Ditto. There are a few resolutions: IntelliJ IDEA Linux/Windows 1440x900 IntelliJ IDEA Macintosh 1440x900 IntelliJ IDEA Linux/Windows 1680x1050 IntelliJ IDEA Macintosh 1680x1050 IntelliJ IDEA Linux/Windows 1920x1200 IntelliJ IDEA Macintosh 1920x1200 The shortcuts are based on the great JetBrains "Key Map" Document plus a few more that I like. As an alternative, print out the JetBrains Key Map Doc and tape it to the sides of your monitor. If neither of these look good on your resolution then leave a comment and I'll scale one just for you. On a Mac? Send me the shortcuts in a text file and I will convert it for you. Not on IDEA? You can download the Eclipse Desktop wallpaper from us, or the vim quick reference from our friend Ted Naleid. doce ut discas - Teach, that you yourself may learn.
October 13, 2010
by Hamlet D'Arcy
· 35,549 Views
article thumbnail
Practical PHP Patterns: Plugin
The Separated Interface pattern can often be used to provide hook points to client code, in the form of interfaces to implement or classes to extend with client code. The right implementation to use in a part of the system can then be chosen via configuration: the Factory or Dependency Injection container with the largest scope would process the configuration and execute conditionals only one time, and inject the right Plugin as a collaborator of a standard object. This pattern is a evolution of the Separated Interface one, where the implementor package is not even under your maintenance, but it is provided by some external developer that links his code to your work. Implementation In PHP the concept of compile time does not exist, apart from the just-in-time cached compilation of the scripts to operation codes, a phrase which you can peacefully ignore if you are not into caching. By the way, even if some checks are performed while loading and parsing the PHP code, PHP is by design a dynamic language where you can write nearly everything and it will not explode until executed. This design leaves open many possibilities for inserting plugins, but due to the lack of compile there is often a lack of a clean separation between code and configuration. For example, database credentials are embedded in PHP code more often than in other languages. Think now of a framework or a library: you cannot change the code but you must adapt or create a configuration to make it work. To implement a Plugin pattern, your application should strive towards the flexibility of a library: think of your production code as external and untouchable, and try to deploy a particular configuration to make it work and to modify a functionality. For example, extract it in a temporary working copy with svn checkout or git clone and hook in the necessary extensions. When you succeed, and your svn diff or git diff is clean, you'll have implemented a Plugin system. Modification of vendor code (and you are the vendor here) is out of the question. Future changes Kent Beck says in Implementation Patterns that providing hooks via implementation and inheritance is one of the most effective ways to tie a framework down from future evolution. For example, once you have published an interface, you cannot add methods to it without breaking all the implementors. You can publish versioned interfaces, but this adds complexity to your application. With a published abstract class instead, you can include a default implementation for new methods, but you can't remove methods or refactor protected members without breaking Plugin implementators. This is the specular situation of providing an interface. Zend Framework includes both an interface and an abstract class for most of its components, but it does not get right the management of extension points (at least in the 1.x branch). When including the possibility of Plugins in your application, default as much as possible to private visibility and hide the internals of your Plugin hook point. What is left to protected is a seam that screams "extend me", and the interfaces not marked as internal will be implemented by someone else. There is no built-in language mechanism to protect interfaces,m so you'll have to rely on some kind of convention (like a particular prefix or namespace), but for private methods left to protected scope we can only blame ourselves. Configuration The configuration of your Plugin system can be managed with solution of different levels of complexity, each more powerful than the previous ones. Of course, you shouldn't provide a needlessly complex system when all you need is a class name. The first solution is indeed to insert class names into configuration files. This is a totally declarative approach, which uses simple INI files. This is commonly done in Zend Framework, for example with bootstrap resources, and in some cases can even manage dependencies of the Plugins. Bootstrap resources can request other object of the same kind, but cannot pull in arbitrary collaborators (unless they create them by themselves... ugly if you know what DI is). A second, widely applicable solution is to request Factory objects. this solution still involves writing PHP code, but it is one step towards textual configuration. However, a Factory object can fetch and inject all the dependencies into a Plugin without cluttering it with this kind glue code (only a constructor or some setters). The problem with Factories is that they tend to contain all the same boilerplate code. A third solution can be used to provide quick construction of objects: Dependency Injection containers, which have recently been introduced even in PHP. A DI container is configured textually, via an XML or INI file containing parameters like the collaborators each object requires, its lifetime, and so on. DI containers are probably the future of flexible PHP applications, but beware of growing too dependent on them: they are a library like every other open source component, and should be isolated from your code as much as possible like you would do with your models and Doctrine 2, or your services and Zend Framework. Example The code sample shows hot to predispose a class for receiving an injected simple Factory that manages user-defined plugins. // plugin_view.php formatDate(time()), ".\n"; factory = $factory; } public function render($script) { include $script; } /** * Forwards the call to the View Helper invoked. */ public function __call($name, $args) { $callback = $this->factory->getHelper($name); return call_user_func_array($callback, $args); } } /** * Extension code. */ class UserDefinedFactory implements ViewHelperFactory { private $helpers; /** * In this example, we only define a simple Plugin for * formatting dates using PHP's internal function. */ public function __construct() { $this->helpers = array( 'formatDate' => function($time) { return date('Y-m-d', $time); } ); } public function getHelper($name) { return $this->helpers[$name]; } } // client code $view = new View(new UserDefinedFactory); $view->render('plugin_view.php');
October 11, 2010
by Giorgio Sironi
· 5,224 Views
article thumbnail
Practical PHP Patterns: Special Case
The Special Case pattern is a very simple base pattern that describes a subclass representing, as the name suggests, a special case of the computation made by your program. Don't think that the technical simplicity of the solution means that this pattern is very diffused. If vs. polymorphism The idea of the pattern is to implements two classes with the same interface or base superclass, and rely on polymorphism to target the special case, instead that inserting if and switch statements in the original class. The extracted piece of functionality can be a method to override (specialization in the Template Method pattern) or an independent collaborator injected into the client code (Strategy pattern and many others). Dispatching a method call instead of inserting if statements is simpler to read and understand, as the code of the class has a lower cyclomatic complexity overall (few possible execution paths). If you ever tried to debug Doctrine 1 or a similar piece of software where the methods contain many nested ifs, you have been probably forced to insert echo statements to reveal the actually executed path, even when a single, isolated unit test was exercising the code. The alternative to some ifs is to introduce a Special Case. A rule of thumb for discovering if the substitution is possible is to check if the condition of the if is based on a state that is longer lived with respect to the parameters of the method that it resides in. Ifs that depend only on the state of the object fields or on collaborators are the simplest to replace. Null Object The Null Object pattern is a specialized version of Special Case (what a pun), and probably the most famous one. Instead of returning false or null when a computation fails to provide a result, you return an object that as a matter of fact, does nothing: an User subclass AnonymousUser with authorize() that always return false an empty array (it can be thought of as a Null Object, even if it is a primitive value) an empty ArrayObject. When a Null Object is returned, it effectively removes the checks for the null value or empty result from the client code. The client class object can call methods on the return value without worrying (calling methods on NULL is a fatal error in PHP and would crash a test suite). Or it can execute foreach() over a returned array and skip the cycle altogether if the array is empty. Since null can be dispatched, we may in fact use it as a Test Double in our test code to ensure a collaborator is never called in a particular scenario. If you have a method that shouldn't refer to a collaborator, you can inject null in the constructor or via a setter. PHP is different from Java in the type hinting behavior: in Java you can pass null to this constructor: public MyClass(Collaborator c) { ... while in PHP you have to resort to this: public function __construct(Collaborator $c = null) { ... Implementation The Special Case can be a Flyweight or an object with, since it has usually no internal state: the behavior depending on state is encapsulate in the code itself. You can also have more than one Special Case for each superclass or interface: Fowler makes the example of a MissingCustomer and AnonymousCustomer as special cases for the Customer class. By the way, every method of a Null Object should return a plain scalar value or another Special Case object. Note that with more than one level of Special Case objects, you may be violating the Law of Demeter: your client code access the first Special Case and then the other contained one, navigating the object graph instead of asking for its dependencies or sending a message. Examples In this example we apply the pattern to go from this situation: type = $type; } /** * This if() is based only on the object state * and can probably be modelled differently. * You'll need two tests for this method. */ public function accelerate() { if ($this->type == 'Ferrari') { $this->speed += 2; } else { $this->speed++; } } public function brake() { $this->speed--; } public function __toString() { return $this->type; } } // client code $car = new Car('Fiat'); $ferrari = new Car('Ferrari'); $car->accelerate(); $ferrari->accelerate(); var_dump($car, $ferrari); to this one: speed--; } public function __toString() { return $this->type; } } /** * One Special Case: a car with $type parametrized in the constructor * and ordinary acceleration properties. */ class OrdinaryCar extends Car { public function __construct($type) { $this->type = $type; } public function accelerate() { $this->speed++; } } /** * Another Special Case: a car with fixed $type and greater acceleration. */ class FerrariCar extends Car { /** * This is state encapsulate in code: you don't have to set up * it in tests or with configuration, only to instantiate this class. */ protected $type = 'Ferrari'; public function accelerate() { $this->speed += 2; } } // client code $car = new OrdinaryCar('Fiat'); $ferrari = new FerrariCar(); $car->accelerate(); $ferrari->accelerate(); var_dump($car, $ferrari);
October 7, 2010
by Giorgio Sironi
· 3,066 Views
article thumbnail
5 Maven Tips
I have been working with Maven for 3 years now and over that time I have learned some tips and tricks that help me work faster with Maven. In this article, I am going to talk about 5 of those tips. Maven rf option Most of us work in a multi-module environment and it happens very often that a build fails at some module. It's a big pain to rerun the entire the build. To save you from going through this pain, Maven has an option called rf (i.e. resume) from which you can resume your build from the module where it failed. So, if your build failed at myproject-commons you can run the build from this module by typing: mvn -rf myproject-commons clean install Maven pl option This next Maven option helps you build specified reactor projects instead of building all projects. For example, if you need to build only two of your modules myproject-commons and myproject-service, you can type: mvn -pl myproject-commons,myproject-service clean install This command will only build commons and service projects. Maven Classpath ordering In Maven, dependencies are loaded in the order in which they are declared in the pom.xml. As of version 2.0.9, Maven introduced deterministic ordering of dependencies on the classpath. The ordering is now preserved from your pom, with dependencies added by inheritence added last. Knowing this can really help you while debugging NoClassDefFoundError. Recently, I faced NoClassDefFoundError: org/objectweb/asm/CodeVisitor while working on a story where cglib-2.1_3.jar was getting loaded before cglib-nodep-2.1_3.jar. And as cglib-2.1_3.jar does not have this CodeVisitor class I was getting the error. Maven Classifiers We all know about qualifiers groupId, artifactId, version that we use to describe a dependency but there is fourth qualifier called classifier. It allows distinguishing two artifacts that belong to the same POM but were built differently, and is appended to the filename after the version. For example, if you want to build two separate jars, one for Java 5 and another for Java 6, you can use classifier. It lets you locate your dependencies with the further level of granularity. junitjunittestjdk16 Dependency Version Ranges Have you ever worked with a library that releases too often when you want that you should always work with the latest without changing the pom. It can be done using dependency version changes. So, if you want to specify that you should always work with the version above a specified version, you will write: [1.1.0,) This line means that the version should always be greater than or equal to 1.1.0. You can read more about dependency version ranges at this link. These are my five tips. If you have any tips please share.
October 5, 2010
by Shekhar Gulati
· 66,123 Views · 5 Likes
article thumbnail
Disable Javascript error in WPF WebBrowser control
I work with WebBrowser control in WPF, and one of the most annoying problems I have with it, is that sometimes you browse sites that raise a lot of javascript errors and the control becomes unusable. Thanks to my friend Marco Campi, yesterday I solved the problem. Marco pointed me a link that does not deal with WebBrowser control, but uses a simple javascript script to disable error handling in a web page. This solution is really simple, and seems to me the right way to solve the problem. The key to the solution is handle the Navigated event raised from the WebBrowser control. First of all I have my WebBrowser control wrapped in a custom class to add functionalities, in that class I declare this constant. private const string DisableScriptError = @"function noError() { return true; } window.onerror = noError;"; This is the very same script of the previous article, then I handle the Navigated event. void browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { InjectDisableScript(); Actually I’m doing a lot of other things inside the Navigated event handler, but the very first one is injecting into the page the script that disable javascript error. private void InjectDisableScript() { HTMLDocumentClass doc = Browser.Document as HTMLDocumentClass; HTMLDocument doc2 = Browser.Document as HTMLDocument; //Questo crea lo script per la soprressione degli errori IHTMLScriptElement scriptErrorSuppressed = (IHTMLScriptElement)doc2.createElement("SCRIPT"); scriptErrorSuppressed.type = "text/javascript"; scriptErrorSuppressed.text = DisableScriptError; IHTMLElementCollection nodes = doc.getElementsByTagName("head"); foreach (IHTMLElement elem in nodes) { //Appendo lo script all'head cosi è attivo HTMLHeadElementClass head = (HTMLHeadElementClass)elem; head.appendChild((IHTMLDOMNode)scriptErrorSuppressed); } } This is the code that really solves the problem, the key is creating a IHTMLScriptElement with the script and injecting into the Head of the page, this effectively disables the javascript errors. I’ve not fully tested with a lot of sites to verify that is able to intercept all errors, but it seems to work very well with a lot of links that gave us a lot of problems in the past. Alk.
October 5, 2010
by Ricci Gian Maria
· 20,980 Views
article thumbnail
Practical PHP Patterns: Value Object
Today comes a pattern that I have wanted to write about for a long time: the Value Object. A Value Object is conceptually a small simple object, but a fundamental piece of Domain-Driven Design and of object-oriented programming. Identity vs. equality The definition of a Value Object, that establishes if we can apply the pattern to a class, is the following: the equality of two Value Objects is not based on identity (them being the same object, checked with the operator ===), but on their content. An example of PHP built-in Value Object is the ArrayObject class, which is the object-oriented equivalent of an array. Two ArrayObjects are equal if they contain the same elements, not if they are the same identical object. Even if they were created in different places, as long as the contained scalars are equals (==) and the contained objects are identical (===), they are effectively "identical" for every purpose. In PHP, the == operator is used for equality testing, while the === for identity testing. Also custom equals() method can be created. Basically, the == operator checks that two scalars, like strings or integers, have the same value. When used on objects, it checks that their corresponding fields are equals. The === operator, when used between objects, returns true only if the two objects are actually the same (they refer to the same memory location and one reflects the changes made to another.) Scalars, as objects Other languages provide Value Objects also for basic values like strings and integers, while PHP limits itself to the ArrayObject and Date classes. Another example of a typical Value Object implementation is the Money class. Continuing with the Date example, we usually don't care if two Date objects are the same, but we care instead to know if they had the exact identical timestamp in their internals (which means they are effectively the same date.) On the contrary, if two Users are the same, they should be the same object (in the memory graph) which resides in a single memory location, or they should have an identity field (in databases) that allow us to distinguish univocally between two users. If you and I have the same name and address in the database, we are still not the same User. But if two Dates have the same day, month, and year, they are the same Date for us. This second kind of objects, whose equality is not based on an Identity Field, are Value Objects. For simplicity, ORMs automatically enforce the identity rules via an Identity Map. When you retrieve your own User object via Doctrine 2, you can be sure that only one instance would be created and handed to you, even if you ask for it a thousand times (obviously other instances would be created for different User objects, like mine or the Pope's one). In Domain-Driven Design The Value Object pattern is also a building block of Domain-Driven Design. In practice, it represents an object which is similar to a primitive type, but should be modelled after the domain's business rules. A Date cannot really be a primitive type: Date objects like Feb 31, 2010 or 2010-67-89 cannot exists and their creation should never be allowed. This is a reason why we may use objects even if we already have basic, old procedural types. Another advantage of objects if that they can add (or prohibit) behavior: we can add traits like immutability, or type hinting. There's no reason to modelling a string as a class in PHP, due to the lack of support from the str*() functions; however, if those strings are all Addresses or Phonenumbers... In fact, Value Objects are almost always immutable (not ArrayObject's case) so that they can be shared between other domain objects. The immutability solves the issues named aliasing bugs: if an User changes its date of birth, whose object is shared between other two users, they will reflect the change incorrectly. But if the Date is a Value Object, it is immutable and the User cannot simply change a field. Mutating a Value Object means creating a new one, often with a Factory Method on the Value Object itself, and place it in the reference field that pointed to the old object. In a sense, if transitions are required, they can be modelled with a mechanism similar to the State pattern, where the Value Object returns other instances of its class that can be substituted to the original reference. Garbage collecting will take care of abandoned Value Objects. To a certain extent, we can say that Value Objects are "passed by value" even if the object reference is passed by handler/reference/pointer like for everything else. No method can write over a Value Object you pass to it. The issues of using Value Objects extensively is that there is no support from database mapping tools yet. Maybe we will be able to hack some support with the custom types of Doctrine 2, which comprehend the native Date class, but real support (based on the JPA metadata schema) would come in further releases. Examples An example of Value object is presented here, and my choice fell onto the Paint class, an example treated in the Domain-Driven Design book in discussions about other patterns. On this Value Object we have little but useful behavior (methods such as equals(), and mix()), and of course immutability. red = $red; $this->green = $green; $this->blue = $blue; } /** * Getters expose the field of the Value Object we want to leave * accessible (often all). * There are no setters: once built, the Value Object is immutable. * @return integer */ public function getRed() { return $red; } public function getGreen() { return $green; } public function getBlue() { return $blue; } /** * Actually, confronting two objects with == would suffice. * @return boolean true if the two Paints are equal */ public function equals($object) { return get_class($object) == 'Paint' and $this->red == $object->red and $this->green == $object->green and $this->blue == $object->blue; } /** * Every kind of algorithm, just to expanding this example. * Since the objects are immutable, the resulting Paint is a brand * new object, which is returned. * @return Paint */ public function mix(Paint $another) { return new Paint($this->integerAverage($this->red, $another->red), $this->integerAverage($this->green, $another->green), $this->integerAverage($this->blue, $another->blue)); } private function integerAverage($a, $b) { return (int) (($a + $b) / 2); } } // client code $blue = new Paint(0, 0, 255); $red = new Paint(255, 0, 0); var_dump($blue->equals($red)); var_dump($violet = $blue->mix($red));
September 29, 2010
by Giorgio Sironi
· 24,424 Views · 1 Like
article thumbnail
Java Barcode API
Originally Barcodes were 1D representation of data using width and spacing of bars. Common bar code types are UPC barcodes which are seen on product packages. There are 2D barcodes as well (they are still called Barcodes even though they don’t use bars). A common example of 2D bar code is QR code (shown on right) which is commonly used by mobile phone apps. You can read history and more info about Barcodes on Wikipedia. There is an open source Java library called ‘zxing’ (Zebra Crossing) which can read and write many differently types of bar codes formats. I tested zxing and it was able to read a barcode embedded in the middle of a 100 dpi grayscale busy text document! This article demonstrates how to use zxing to read and write bar codes from a Java program. Getting the library It would be nice if the jars where hosted in a maven repo somewhere, but there is no plan to do that (see Issue 88). Since I could not find the binaries available for download, I decided to download the source code and build the binaries, which was actually quite easy. The source code of the library is available on Google Code. At the time of writing, 1.6 is the latest version of zxing. 1. Download the release file ZXing-1.6.zip (which contains of mostly source files) from here. 2. Unzip the file in a local directory 3. You will need to build 2 jar files from the downloaded source: core.jar, javase.jar Building core.jar cd zxing-1.6/core mvn install cd zxing-1.6/core mvn install This will install the jar in your local maven repo. Though not required, you can also deploy it to your company’s private repo by using mvn:deploy or by manually uploading it to your maven repository. There is an ant script to build the jar as well. Building javase.jar Repeat the same procedure to get javase.jar cd zxing-1.6/javase mvn install cd zxing-1.6/javase mvn install Including the libraries in your project If you are using ant, add the core.jar and javase.jar to your project’s classpath. If you are using maven, add the following to your pom.xml. com.google.zxing core 1.6-SNAPSHOT com.google.zxing javase 1.6-SNAPSHOT com.google.zxing core 1.6-SNAPSHOT com.google.zxing javase 1.6-SNAPSHOT Once you have the jars included in your project’s classpath, you are now ready to read and write barcodes from java! Reading a Bar Code from Java You can read the bar code by first loading the image as an input stream and then calling this utility method. InputStream barCodeInputStream = new FileInputStream("file.jpg"); BufferedImage barCodeBufferedImage = ImageIO.read(barCodeInputStream); LuminanceSource source = new BufferedImageLuminanceSource(barCodeBufferedImage); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Reader reader = new MultiFormatReader(); Result result = reader.decode(bitmap); System.out.println("Barcode text is " + result.getText()); InputStream barCodeInputStream = new FileInputStream("file.jpg"); BufferedImage barCodeBufferedImage = ImageIO.read(barCodeInputStream); LuminanceSource source = new BufferedImageLuminanceSource(barCodeBufferedImage); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Reader reader = new MultiFormatReader(); Result result = reader.decode(bitmap); System.out.println("Barcode text is " + result.getText()); Writing a Bar Code from Java You can encode a small text string as follows: String text = "98376373783"; // this is the text that we want to encode int width = 400; int height = 300; // change the height and width as per your requirement // (ImageIO.getWriterFormatNames() returns a list of supported formats) String imageFormat = "png"; // could be "gif", "tiff", "jpeg" BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height); MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, new FileOutputStream(new File("qrcode_97802017507991.png"))); String text = "98376373783"; // this is the text that we want to encode int width = 400; int height = 300; // change the height and width as per your requirement // (ImageIO.getWriterFormatNames() returns a list of supported formats) String imageFormat = "png"; // could be "gif", "tiff", "jpeg" BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height); MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, new FileOutputStream(new File("qrcode_97802017507991.png"))); In the above example, the bar code for “97802017507991″ is written to the file “qrcode_97802017507991.png” (click to see the output). JavaDocs and Documentation The Javadocs are part of the downloaded zip file. You can find a list of supported bar code formats in the Javadocs. Open the following file to see the javadocs. zxing-1.6/docs/javadoc/index.html zxing-1.6/docs/javadoc/index.html From http://www.vineetmanohar.com/2010/09/java-barcode-api/
September 27, 2010
by Vineet Manohar
· 112,469 Views · 2 Likes
article thumbnail
How to Create JavaHelp in a Mavenized NetBeans Platform Application
There isn't a JavaHelp template for Maven-based NetBeans Platform modules, hence you need to set up JavaHelp yourself. It's a bit tricky, involving several different parts that can go wrong easily (which is why a JavaHelp template is so handy). Here's instructions on how to set up JavaHelp in your Maven-based NetBeans Platform modules. Do the following: In each module that needs to provide a JavaHelp set, add this line to the manifest: OpenIDE-Module-Requires: org.netbeans.api.javahelp.Help In the POM of the container project (i.e., NOT the application project and NOT a functionality module project), add the "dependencies" section in the definition of the "org.codehaus.mojo", while setting the "version" to 3.0: org.codehaus.mojo nbm-maven-plugin 3.0 true javax.help javahelp 2.0.02 ${brandingToken} foobar Note that the "version" is set to 3.0. I could not get JavaHelp to work for 3.1 or 3.2 (the default in 6.9+) and had to revert to 3.0. Maybe someone can correct me on this point somehow. Make sure that the POMs in the other projects (i.e., application project and functionality module projects) do not have their own definition of "org.codehaus.mojo". I.e., the container project should handle this definition for the whole application. You have now configured the application to use JavaHelp and have indicated each module that will provide JavaHelp. In each of those modules, you now need to provide JavaHelp content. The simplest approach for this is to create an Ant-based NetBeans Platform module. Then, use the wizard available for Ant-based NetBeans Platform projects for the creation of JavaHelp sets. Then copy the files that are generated into your Maven-based NetBeans Platform project: Note the following in the screenshot above. The "resources" folder contains the "module1-helpset.xml" file, which references the files in the "src/main/javahelp" folder by means of having the following content: And note that the "layer.xml" file above has this folder added: The folder "src/main/javahelp" is new, I created that myself, by copying that folder from the Ant-based NetBeans Platform module. That's the place where you will now create all your help topics within the Mavenized application. The Map file lists the identifying keys of the help topics, the TOC lists those keys that define the table of contents, and the Index does the same to define the index of the helpset. That's all you need. Now you have JavaHelp working in your Mavenized NetBeans Platform application:
September 25, 2010
by Geertjan Wielenga
· 13,486 Views
article thumbnail
How to Create a Custom Project Type in a Mavenized NetBeans Platform Application
Let's take the NetBeans Project Type Module Tutorial and port it to a Maven-based NetBeans Platform application. In contrast to the Hello World Maven NetBeans RCP article, we'll now use the NetBeans IDE's tooling, since the aforementioned article has laid the foundation that we need for using the NetBeans IDE's Maven tooling intelligently. Take the following steps: Create the project as follows: Right-click on the node with the orange icon ("NetBeans Platform based application"), which is the application node, and choose "Build with Dependencies". Right-click the application node and choose Run. Here's your application: Copy the three Java classes from the "NetBeans Project Type Module Tutorial" into "TextAnalyzerProjectType NetBeans Module", which is the functionality module. Specifically, put them into the main package within "Source Packages", which is "com.text.analyzer". Copy the two icons into "Other Sources", specifically into "src/main/resources/com.text.analyzer". Make sure that you change the location of the icons in the two Java classes where they are used, otherwise they will not be found when you run the application. In the POM file of the functionality module, define the "dependencies" section as follows: org.netbeans.api org-openide-util ${netbeans.version} org.netbeans.api org-netbeans-modules-projectuiapi RELEASE691 org.netbeans.api org-openide-util-lookup RELEASE691 org.netbeans.api org-netbeans-modules-projectapi RELEASE691 org.netbeans.api org-openide-filesystems RELEASE691 org.netbeans.api org-openide-loaders RELEASE691 org.netbeans.api org-openide-nodes RELEASE691 In the POM file of the application node, add this dependency: org.netbeans.modules org-netbeans-modules-projectui RELEASE691 The above is needed because we're depending on the Project UI API (see step 5 above). In that particular API, the "OpenIDE-Module-Needs" key is used in the manifest to specify that "ActionsFactory", "OpenProjectsTrampoline", and "ProjectChooserFactory" are needed by this module. Therefore, a module that implements and provides those classes is required, which is the Project UI module, which implements Project UI API. To ensure that that module will be available at runtime, you specify the dependency above as described, in the POM file of the application node. For details, go here. Repeat steps 2 and 3 above. Then open the Favorites window and browse to a folder that has a subfolder named "texts". Right-click on the folder that has a subfolder named "texts" and then click "Open Project". Here's your application, with the project opened: Congrats, you've now ported the sample to a Maven based NetBeans Platform application.
September 24, 2010
by Geertjan Wielenga
· 15,480 Views
article thumbnail
How to Display Maven Project Version in Your Webapp Overview
sometimes it is useful to display the version of your web application, typically in the footer area of the web page. by displaying the version information, one can quickly determine which version of the app is running or users can use it for error reporting purposes. displaying the version is also useful when there are frequent automated releases using the maven release plugin and it is hard to track which version is actually deployed on a server. here’s an illustration of how version can be displayed in the footer. this article describes how to display the version of your maven project in your web application. step 1: create a view file to display the version first we will create a view file which will display the version. the view file could be a jsp, html, xhtml, a facelet or any format depending on your stack. in this example, we will create a jsp file which will print the version somewhere in the page. however, instead of the hardcoding an actual version, we put a special token ‘project_version’. we don’t want to hard code the version information as it will change from release to release. the special token will be replaced with actual maven project version when the app is packaged. create the following jsp. src/main/webapp/version.jsp here’s a simple file which displays the version information. project version is project_version step 2: add snippet to pom.xml the maven replacer plugin is a simple and useful plugin which can replaces tokens in file of your choice. add the following snippet of code to your pom.xml. com.google.code.maven-replacer-plugin maven-replacer-plugin 1.3.2 prepare-package replace target/myproject/version.jsp false project_version ${project.version} to test the above setup, you can run the following command: mvn prepare-package navigate to the following file. target/myproject/version.jsp the contents of this file will look something like this (assuming that your project version is 1.0-snapshot): project version is 1.0-snapshot when your application ships, the version.jsp file will always have the correct version. you can see the version by invoking the version.jsp page. http://localhost:8080/myproject/version.jsp note: your view file does not have to be a jsp, it can be any a view file suitable to your stack. it could be part of your footer which could be included at the bottom in each page. the special token can be changed from project_version to another value of your choice, just change it in the view file as well as the pom.xml instead of having the version contained in a view file, you could have the version in a properties file or a message bundle and then display a message from the message bundle on the view references maven replace plugin on google code from http://www.vineetmanohar.com/2010/09/how-to-display-maven-project-version-in-your-webapp
September 23, 2010
by Vineet Manohar
· 36,931 Views · 1 Like
article thumbnail
Practical PHP Patterns: Registry
Fowler's definition for the Registry pattern is this one: A well known object that other ones can use to find related objects or service. This vague definition leaves open the possibility of abuse. Implementation The idea of a Registry is simple: providing a dynamic possibility for discovering collaborator objects, so that we not hardcode static calls to global objects like Singletons in each of them. In the testing environment, we can fill the Registry with mocks. However, the problem is that then we hardcode static calls to the Registry, which is an effective sinkhole for dependencies in the case of a general purpose implementation. You can't limit which objects of a Registry are accessed by a client, so depending on the Registry may mean depending on each stored component. In this scenario, the Registry becomes a Service Locator, the poor man's version of Dependency Injection. Fixing it My suggestion before implementing this pattern is thinking about how many of the registered objects would the ordinary client object actually need; maybe you can inject them directly. A constraint I'd like to set for Registry implementations is that all the contained objects should be of the same type (or of a Layer Supertype). With this limitation, incarnations of the Registry become very useful as they can be injected and passed around as a virtual collection of object, even if they do not exist/currently are in persistence/are not all in memory at the same time. If this reminds you of the Repository, you're right; the Repository pattern is a specialization of the Registry one, with this limitation written with blood in its contract in a night of full moon. This is what a Registry is supposed to be: not an hidden blackboard like Zend_Registry where you can practice accumulate and fire, and setup time-ticking bombs that will explode later. Here's an example from our test suite, which used Zend_Registry to set up the locale. One day, uncommenting a test would make another one fail (it used Zend_Registry, and the uncommented one messed with some keys). Fixing it takes some minutes (but it should have taken seconds). Scale that to a test suite with one thousands tests and you can easily destroy your tests isolation. Shortly, one test would pass when executed alone, but explode when the whole test suite (which maybe takes 15 minutes to run) because a previous test, whose identity you do not know, modified some global state. Good luck fixing that and grepping for 'Zend_Registry::'. Instead, a Registry can be a first-class citizen, an object that can be injected, by itself or hidden behind an interface of a composer, into any client object that sincerely needs access to the whole encapsulated collection. Why you now feel a generic Registry could be handy Lifecycle problems can create the need for a generic Registry. How do you access an object A from a client object B if A do not exist when B is created? Use a Registry. Of course, this solution does not go a long way: you're never sure that A would be created in time, and you should revise your design to discover why a long-lived object should hold a reference to a short-lived one. In fact, higher-level or injected Factories ara a similar, but more powerful solution. If B needs A, and A has the same lifecycle, simply inject it via a request-wide Factory. If B and A have a shorter lifecycle than the one of the request (for example they are view helpers that may not be used at all in certain requests, so they are instantiated only when needed in the presentation layer), provide a Factory that craates both and inject the Factory in the right scope. However, never inject a generic registry: it is a false solution. The Registry becomes a Service Locator, which is depended on by every piece of your application, and depends again on every piece of it. This is a benignuos form of what I call "hiding dependencies under the carpet", which can be solved by injecting the direct dependency instead of a provider. Examples Our code sample is the infamous Zend_Registry component from Zend Framework 1. It is a Singleton, and when testing controllers it is a typical resource that the testing harness must remember to reset between each test. My comments are in italic. offsetExists($index)) { require_once 'Zend/Exception.php'; throw new Zend_Exception("No entry is registered for key '$index'"); } return $instance->offsetGet($index); } /** * setter method, basically same as offsetSet(). * * This method can be called from an object of type Zend_Registry, or it * can be called statically. In the latter case, it uses the default * static instance stored in the class. * * @param string $index The location in the ArrayObject in which to store * the value. * @param mixed $value The object to store in the ArrayObject. * @return void */ public static function set($index, $value) { $instance = self::getInstance(); $instance->offsetSet($index, $value); } /** * Returns TRUE if the $index is a named value in the registry, * or FALSE if $index was not found in the registry. * * @param string $index * @return boolean */ public static function isRegistered($index) { if (self::$_registry === null) { return false; } return self::$_registry->offsetExists($index); } /** * Constructs a parent ArrayObject with default * ARRAY_AS_PROPS to allow acces as an object * * @param array $array data array * @param integer $flags ArrayObject flags */ public function __construct($array = array(), $flags = parent::ARRAY_AS_PROPS) { parent::__construct($array, $flags); } }
September 22, 2010
by Giorgio Sironi
· 8,244 Views · 1 Like
article thumbnail
CheckThread - A Static Analysis Tool For Catching Java Concurrency Bugs
a few days back, i was browsing the web and found an interesting open source framework called checkthread . it is a static analysis tool for catching java concurrency bugs at compile time. static analysis tools are used to find out programming error in the code by analyzing their byte code. to me a tool aiming to catch concurrency bugs at compile time was worth spending time on. so, i decided to play with checkthread to find out its capabilities. checkthread requires developers to specify the thread policy in either xml or annotations. thread policy defines whether the piece of code (i.e. a method) is thread safe, not thread safe, or thread confined. thread confined means that this method is confined to a specific runtime thread. for example, the swing api must be invoked on the event-dispatch thread. prerequisite before you start: download eclipse plugin . put plugin in jar in eclipse plugins folder and restart eclipse. for more information refer here . download checkthread annotation jar . this jar is not present in any maven repository, so manually install the jar in your maven repository. mvn install:install-file -dfile=checkthread-annotations-1.0.9.jar -dgroupid=org.checkthread -dartifactid=checkthread-annotations -dversion=1.0.9 -dpackaging=jar checkthread capabilities let's look at an example: public class threadsafetyexample { final map helpermap = new hashmap(); public void addelementtomap() { helpermap.put("name", "shekhar"); } } this is a simple class which puts a key value pair in a map. is this code thread safe? no. lets test this class using multiple threads. in the unit test i am using countdownlatch for producing maximum parallelism. i talked about countdownlatch in an earlier article . @test public void regressiontest() throws exception{ for (int i = 1; i <= 100; i++) { system.out.println("runing "+i); addelementtomapwhenaccessedbymultiplethread(); } } public void addelementtomapwhenaccessedbymultiplethread() throws exception { final countdownlatch latch = new countdownlatch(1); final threadsafetyexample helper = new threadsafetyexample(); class mythread extends thread { @override public void run() { try { latch.await(); } catch (interruptedexception e) { } helper.addelementtomap(); } } int threadcount = 2000; mythread[] mythreads = new mythread[threadcount]; for (int i = 0; i < mythreads.length; i++) { mythreads[i] = new mythread(); mythreads[i].start(); } latch.countdown(); for (mythread mythread : mythreads) { mythread.join(); } assertequals(1, helper.helpermap.size()); } i am calling the method addelementtomapwhenaccessedbymultiplethread in a for loop because if you run the test only once it might not fail (thread timing). so, how can these types of errors be detected at compile time if most of the unit-tests and integration tests that we write do not test the code in multi-threaded environments? checkthread can help you out in such situations. checkthread can only help you if you annotate your method with threadsafe annotation. for example, lets apply @threadsafe annotation to the threadsafetyexample class: public class threadsafetyexample { final map helpermap = new hashmap(); @threadsafe public void addelementtomap() { helpermap.put("name", "shekhar"); } } now when you run the checkthread by pressing the button you will see a compile time error as shown below: as you can see in the above image, the tool shows the code where problems exist and descriptions of errors in the problems section. this can come in handy while writing multi threaded code. you just need to think about your contract, whether the method you have written should be thread safe or not. this was just a simple use case but it can also help you detect race conditions . have a look at this tool, maybe it can help you detect concurrency bugs.
September 21, 2010
by Shekhar Gulati
· 27,850 Views
article thumbnail
Naming Conventions for Parameterized Types
Parameterized types - the <> expressions that can be used in Java as of JDK 5 are not just for collections. I find myself frequently using them in APIs I design. They really do let you write things which are more generic in the non-Java sense of the word - and the result is more reusable code, which means less code overall, which means fewer bugs and things to test. The verbosity, and some of the weirdness of type-erasure are less than ideal, but used right, the benefits are worth the complexity. The standard (and somewhere recommended) naming convention for parameterized types is to use a single-letter name. That works fine in signatures that have only one such type. But in practice, single-letter names make code less self-describing, and if you're defining a class with more than one parameterized type, it can be confusing and hard to read. People other than me will have to call, understand and maintain my code - the more self-describing I can make it, the better. So I am looking for a naming convention that makes it obvious that something is a parameterized type, but allows for descriptive names. I am wondering if anybody else has run into this problem, and if there is any emerging consensus on naming generics. Do you work on a project that uses generics a lot? If so, what do you do? Here's an example. At the moment, I'm writing a generic (in both senses) class which simply limits the number of threads which can access some resource. It's basically a wrapper around a Semaphore which uses a Runnable-like object to ensure that the Semaphore is accessed correctly, and does some non-blocking statistic gathering about thread contention. So to access the scarce resource, you pass in a ResourceAccessor: public interface ResourceAccessor { public Result run (ProtectedResource resource, Argument argument); } The problem is that, when somebody looks at this interface, they will instantly get the idea that there are really classes they need to go find, which are called ProtectedResource, Argument and Result - and of course, no such classes exist - these are just names for generic types. The standard-naming-convention is worse: public interface ResourceAccessor { public S run (T resource, R argument); } Here, nobody could possibly figure out what on earth this class is for without extensive documentation - this is a really horrible idea. So I've concluded that the standard recommendations for generic type names are simply wrong for any non-trivial usage (I.e. Collection is fine, since there is one type and Collections are well-understood). You simply can't do this on a non-collection code structure you have invented, or people will just be confused and not use it. The best suggestion I've heard thus far is using $ as a prefix: public interface ResourceAccessor <$ProtectedResource, $Argument, $Result> { public $Result run ($ProtectedResource resource, $Argument argument); } I don't find this pretty, but I don't have any better ideas, and at least it makes it crystal-clear that there is something different about these names. Any thoughts? What do you do in this situation?
September 20, 2010
by Tim Boudreau
· 17,922 Views
  • Previous
  • ...
  • 872
  • 873
  • 874
  • 875
  • 876
  • 877
  • 878
  • 879
  • 880
  • 881
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×