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
Organize Imports in Eclipse
Today I learned a neat trick to organize imports in Eclipse. Of course, one can use Ctrl + Shift + O to remove the unused imports at file level. But what if you want to remove the unused imports for several files, may be at package level? Simple – in the Package Explorer window, right click on the package that you want to modify and then select source -> Organize Imports which will analyse all the files inside that package and then remove the unused imports. One more nifty trick is that you can automatically organize the imports when you save the file. To enable this, go to Windows -> Preferences -> Java -> Editor -> Save Actions and then enable Perform the selected action on save -> Organize imports. After this, whenever you save a java file, eclipse will remove the unused imports automatically.
August 28, 2012
by Veera Sundar
· 46,952 Views · 3 Likes
article thumbnail
Convert Any Image to HTML5 Canvas
Even before talking about the technicalities of converting an image to a canvas element, check out the demo! DEMO input any image URL there and hit the convert button! P.S : It also accepts data-uri! The code : function draw() { // Get the canvas element and set the dimensions. var canvas = document.getElementById('canvas'); canvas.height = window.innerHeight; canvas.width = window.innerWidth; // Get a 2D context. var ctx = canvas.getContext('2d'); // create new image object to use as pattern var img = new Image(); img.src = document.getElementById('url').value; img.onload = function(){ // Create pattern and don't repeat! var ptrn = ctx.createPattern(img,'no-repeat'); ctx.fillStyle = ptrn; ctx.fillRect(0,0,canvas.width,canvas.height); } } The Magic Behind : All the credits goes to createPattern() nsIDOMCanvasPattern createPattern(in nsIDOMHTMLElement image, in DOMString repetition); Elobrating : context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat"); Hope this was useful, anyway there are loads of fun with the canvas element, happy hacking! Edit 0 After the interesting question by @pinkham in the comment section, from the page of MDN : Although you can use images without CORS approval in your canvas, doing so taints the canvas. Provided that you have a server hosting images along with appropriate Access-Control-Allow-Origin header, you will be able to save those images to localStorage as if they were served from your domain. var img = new Image, canvas = document.createElement("canvas"), ctx = canvas.getContext("2d"), src = "http://example.com/image"; // insert image url here img.crossOrigin = "Anonymous"; img.onload = function() { canvas.width = img.width; canvas.height = img.height; ctx.drawImage( img, 0, 0 ); localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") ); } img.src = src; // make sure the load event fires for cached images too if ( img.complete || img.complete === undefined ) { img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; img.src = src; }
August 27, 2012
by Hemanth HM
· 21,448 Views
article thumbnail
Handle the Middle of a XML Document with JAXB and StAX
Recently I have come across a lot of people asking how to read data from, or write data to the middle of an XML document. In this post I will demonstrate how this can be done using JAXB with StAX. Note: JAXB (JSR-222) and StAX (JSR-173) implementations are included in the JDK/JRE since Java SE 6. XML (input.xml) We will be using a SOAP message as our sample XML. The outer portions of the XML document represent information relevant to the Web Service and the inner portions (lines 5-8) represent the data we want to convert to our domain model. Jane Doe Java Model Our Java model consists of a single domain class. The concepts in this example also apply to larger domain models. package blog.stax.middle; import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) public class Customer { @XmlAttribute int id; String firstName; String lastName; } Unmarshal Demo To unmarshal from the middle of an XML document all we need to do is the following: Create an XMLStreamReader from the XML input (line 12). Advance the XMLStreamReader to the return element (lines 13-16). Unmarshal an instance of Customer from the XMLStreamReader (line 20) package blog.stax.middle; import javax.xml.bind.*; import javax.xml.stream.*; import javax.xml.transform.stream.StreamSource; public class UnmarshalDemo { public static void main(String[] args) throws Exception { XMLInputFactory xif = XMLInputFactory.newFactory(); StreamSource xml = new StreamSource("src/blog/stax/middle/input.xml"); XMLStreamReader xsr = xif.createXMLStreamReader(xml); xsr.nextTag(); while(!xsr.getLocalName().equals("return")) { xsr.nextTag(); } JAXBContext jc = JAXBContext.newInstance(Customer.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); JAXBElement jb = unmarshaller.unmarshal(xsr, Customer.class); xsr.close(); Customer customer = jb.getValue(); System.out.println(customer.id); System.out.println(customer.firstName); System.out.println(customer.lastName); } } Output Below is the output from running the unmarshal demo. 123 Jane Doe Marshal Demo To marshal to the middle of an XML document all we need to do is the following: Create an XMLStreamWriter for the XML output (line 18). Start the document and write the outer elements (lines 19-22). Set the Marshaller.JAXB_FRAGMENT property on the Marshaller (line 26) to prevent the XML declaration from being written. Marshal an instance of Customer to the XMLStreamWriter (line 27). End the document, this will close any elements that have been opened (line 29). package blog.stax.middle; import javax.xml.bind.*; import javax.xml.namespace.QName; import javax.xml.stream.*; public class MarshalDemo { public static void main(String[] args) throws Exception { Customer customer = new Customer(); customer.id = 123; customer.firstName = "Jane"; customer.lastName = "Doe"; QName root = new QName("response"); JAXBElement je = new JAXBElement(root, Customer.class, customer); XMLOutputFactory xof = XMLOutputFactory.newFactory(); XMLStreamWriter xsw = xof.createXMLStreamWriter(System.out); xsw.writeStartDocument(); xsw.writeStartElement("S", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/"); xsw.writeStartElement("S", "Body", "http://schemas.xmlsoap.org/soap/envelope/"); xsw.writeStartElement("ns0", "findCustomerResponse", "http://service.jaxws.blog/"); JAXBContext jc = JAXBContext.newInstance(Customer.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.marshal(je, xsw); xsw.writeEndDocument(); xsw.close(); } } Output Below is the output from running the marshal demo. Note that the output from running the demo code will appear on a single line, I have formatted the output here to make it easier to read. Jane Doe
August 27, 2012
by Blaise Doughan
· 20,209 Views
article thumbnail
Groovy Closures Do Not Have Access to Private Methods in a Super Class
Recently I came upon a groovy oddity. (At least it is perceived by me to be an oddity). Closures in a groovy class do not have access to a private method if that method is defined in the superclass. This seems odd paired against the fact that regular methods in a super class can access private method defined in the super class Background Groovy closures have the same scope access to class member variables and methods as a regular groovy method. In other words, closures are bound to variables in the scope they are defined. See the codehaus link for the official documentation: http://groovy.codehaus.org/Closures This implies that a closure will play by the rules of Object Orientation in the Java language. However, I found that closures do not have access to private methods that are defined in a super class. The best way to demonstrate is through a short example from Grails. I have used TDD for the example. Note this is a dummy case with no business purpose. Later on I will offer a more reasonable scenario in the business context where I encountered this scenario. Simple Groovy Example Take a class that has a closure, a public method, and a private method. Then extend that class. Try and invoke the closure. We get an error. package closure.access class SendCheckService { def calendarService /** * Closure that invokes a private method */ def closureToSendCheck = { sendPersonalCheck() } def regularMethod() { sendPersonalCheck() } /* * Private method that we want to see executed */ private sendPersonalCheck() { println "Sending Personal Check" } } class FooService extends SendCheckService { } Here are some tests the demonstrate the error. package closure.access import grails.test.* class SendCheckServiceTests extends GrailsUnitTestCase { def sendCheckService protected void setUp() { super.setUp() sendCheckService = new SendCheckService() } /** * Invocation of the closure from the super class prints out the message: * "Sending Personal Check" */ void testClosureToSendCheck() { sendCheckService.closureToSendCheck() } /** * Invocation of the method from the super class prints out the message: * "Sending Personal Check" */ void testRegularMethod() { sendCheckService.regularMethod() } /** * Invocation of the the closure from the subclass yields an error: * groovy.lang.MissingMethodException: No signature of method: closure.access.FooService.sendPersonalCheck() * is applicable for argument types: () values: [] * This essentially means it does not exists. */ void testFoo_ClosureToSendCheck() { def fooService = new FooService() fooService.closureToSendCheck() } /** * Invocation of the method does not yield and error! */ void testFoo_RegularMethod() { def fooService = new FooService() fooService.regularMethod() } } All is Well testClosureToSendCheck() executes fine where the closure can access the private method. This is as expected. It is all well and good because we have not extended class yet. testRegularMethod() just demonstrates regular OO principles. A method is able to invoke private methods. Not as Expected testFoo_ClosureToSendCheck() invokes a subclass of SendCheckService. It calls the same closure, yet we get served up a MissingMethodException. testFoo_RegularMethod() just contrasts testFoo_ClosureToSendCheck(). I invoked this test to show that we should be able to have closures access private methods because other regular methods can! Why Even Try to Have a Closure Call A Private Method This may be a double loop learning question any intelligent developer might ask. It questions why we need to even get into this mess. This is a valid point and should be explained. It is optimal to use closures in an attempt to reuse existing template logic. Let me give a simple business problem. Imagine we need to code a system that sends out various types of checks: personal checks and business checks. We have the stipulation that these two events must NEVER be done together. Only send a personal check at one instance, and send a business check at another time. However, they both need to follow the same logic. They must be sent on a business day (no holidays or weekends). Thus, we have a scenario where they need the same calendar logic, but it is needed separately. Duplicate Logic We could just code the calendar logic twice. (Remember sending business checks and personal checks together in one request cannot occur!) package closure.access class SendCheckService2 { def calendarService def triggerPersonalCheck () { if (calendarService.todayIsBusinessDay()) { sendPersonalCheck() } else { println "DO NOTHING" } } def triggerBusinessCheck() { if (calendarService.todayIsBusinessDay()) { sendBusinessCheck() } else { println "DO NOTHING" } } private sendPersonalCheck() { println "Sending Personal Check" } private sendBusinessCheck() { println "Sending Business Check" } } Use the DRY Principle In order to avoid this and follow DRY, we can use closures. Create a method that accepts a closure, and pass it the code snippets to execute in a closure. As a result we have the calendar logic defined once, but executed separately upon a different code snippet. package closure.access class SendCheckService3 { def calendarService def triggerPersonalCheck() { checkIfBusinessDayAndExecute(sendBusinessCheck) } def triggerBusinessCheck() { checkIfBusinessDayAndExecute(sendBusinessCheck) } def checkIfBusinessDayAndExecute(Closure closure) { if (calendarService.todayIsBusinessDay()) { closure() } else { println "DO NOTHING" } } /** * This is now a closure we can pass around */ def sendPersonalCheck = { println "Sending Personal Check" } /** * This is now a closure we can pass around */ def sendBusinessCheck = { println "Sending Business Check" } } In my real world scenario where I encountered the closure issue, it happened that my closure was trying to execute a private method in an abstract class. This is where I observed the problem. JVM Thoughts I honestly do not know the gory details behind why closures in super classes cannot access private methods, but I have an idea. Groovy creates closures by compiling them as inner classes. Since the subclass extends the superclass and then contains a closure, the inner class does not have access to the super class' methods. The reason why a method has access, is because it is compiled as one instance of the class. The closure implementation is not that way (being a inner class), and thus this is why we see a violation of Object Oriented behavior. If you have a better explanation or futher knowledge of the details behind this issue, please describe them in the comments. Thanks for taking the time to delve in this area. Thanks to Scott Risk for helping with examples.
August 26, 2012
by Nirav Assar
· 12,211 Views
article thumbnail
Adding Hibernate Entity Level Filtering feature to Spring Data JPA Repository
Original Article: http://borislam.blogspot.hk/2012/07/adding-hibernate-entity-level-filter.html Those who have used data filtering features of hibernate should know that it is very powerful. You could define a set of filtering criteria to an entity class or a collection. Spring data JPA is a very handy library but it does not have fitering features. In this post, I will demonstarte how to add the hibernate filter features at entity level. You can use this features when you are using Hibernate Entity Manager. We can just define annotation in your repositoy interface to enable this features. Step 1. Define filter at entity level as usual. Just use hibernate @FilterDef annotation @Entity @Table(name = "STUDENT") @FilterDef(name="filterBySchoolAndClass", parameters={@ParamDef(name="school", type="string"),@ParamDef(name="class", type="integer")}) public class Student extends GenericEntity implements Serializable { // add your properties ... } Step2. Define two custom annotations. These two annotations are to be used in your repository interfaces. You could apply the hibernate filter defined in step 1 to specific query through these annotations. @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface EntityFilter { FilterQuery[] filterQueries() default {}; } @Retention(RetentionPolicy.RUNTIME) public @interface FilterQuery { String name() default ""; String jpql() default ""; } Step3. Add a method to your Spring data JPA base repository. This method will read the annotation you defined (i.e. @FilterQuery) and apply hibernate filter to the query by just simply unwrap the EntityManager. You could specify the parameter in your hibernate filter and also the parameter in you query in this method. If you do not know how to add custom method to your Spring data JPA base repository, please see my previous article for how to customize your Spring data JPA base repository for detail. You can see in previous article that I intentionally expose the repository interface (i.e. the springDataRepositoryInterface property) in the GenericRepositoryImpl. This small tricks enable me to access the annotation in the repository interface easily. public List doQueryWithFilter( String filterName, String filterQueryName, Map inFilterParams, Map inQueryParams){ if (GenericRepository.class.isAssignableFrom(getSpringDataRepositoryInterface())) { Annotation entityFilterAnn = getSpringDataRepositoryInterface().getAnnotation(EntityFilter.class); if(entityFilterAnn != null){ EntityFilter entityFilter = (EntityFilter)entityFilterAnn; FilterQuery[] filterQuerys = entityFilter.filterQueries() ; for (FilterQuery fQuery : filterQuerys) { if (StringUtils.equals(filterQueryName, fQuery.name())) { String jpql = fQuery.jpql(); Filter filter = em.unwrap(Session.class).enableFilter(filterName); //set filter parameter for (Object key: inFilterParams.keySet()) { String filterParamName = key.toString(); Object filterParamValue = inFilterParams.get(key); filter.setParameter(filterParamName, filterParamValue); } //set query parameter Query query= em.createQuery(jpql); for (Object key: inQueryParams.keySet()) { String queryParamName = key.toString(); Object queryParamValue = inQueryParams.get(key); query.setParameter(queryParamName, queryParamValue); } return query.getResultList(); } } } } } return null; } Last Step: example usage In your repositry, define which query you would like to apply hibernate filter through your @EntityFilter and @FilterQuery annotation. @EntityFilter ( filterQueries = { @FilterQuery(name="query1", jpql="SELECT s FROM Student LEFT JOIN FETCH s.Subject where s.subject = :subject" ), @FilterQuery(name="query2", jpql="SELECT s FROM Student LEFT JOIN s.TeacherSubject where s.teacher = :teacher") } ) public interface StudentRepository extends GenericRepository { } In your service or business class that inject your repository, you could just simply call the doQueryWithFilter() method to enable the filtering function. @Service public class StudentService { @Inject private StudentRepository studentRepository; public List searchStudent( String subject, String school, String class) { List studentList; // Prepare parameters for query filter HashMap inFilterParams = new HashMap(); inFilterParams.put("school", "Hong Kong Secondary School"); inFilterParams.put("class", "S5"); // Prepare parameters for query HashMap inParams = new HashMap(); inParams.put("subject", "Physics"); studentList = studentRepository.doQueryWithFilter( "filterBySchoolAndClass", "query1", inFilterParams, inParams); return studentList; } }
August 24, 2012
by Boris Lam
· 56,856 Views · 1 Like
article thumbnail
Installing Maven 3.0.4 on Ubuntu 12.04
To install Apache Maven 3.0.4 on Ubuntu 12.04, take the following steps.
August 24, 2012
by Pavithra Gunasekara
· 43,756 Views
article thumbnail
Advanced Dependency Injection With Guice
The more I use dependency injection (DI) in my code, the more it alters the way I see both my design and implementation. Injection is so convenient and powerful that you end up wanting to make sure you use it as often as you can. And as it turns out, you can use it in many, many places. Let’s cover briefly the most obvious scenarios where DI, and more specifically, Guice, are a good fit: objects created either at class loading time or very early in your application. These two aspects are covered by either direct injection or by providers, which allow you to start building some of your object graph before you can inject more objects. I won’t go too much in details about these two use cases since they are explained in pretty much any Guice tutorial you can find on the net. Once the injector has created your graph of objects, you are pretty much back to normal and instantiating your “runtime objects” (the objects you create during the life time of your application) the normal way, most likely with “new” or factories. However, you will quickly start noticing that you need some runtime information to create these objects, other parts of them could be injected. Let’s take the following example: we have a GeoService interface that provides various geolocation functions, such as telling you if two addresses are close to each other: public interface GeoService { /** * @return true if the two addresses are within @param{miles} * miles of each other. */ boolean isNear(Address address1, Address address2, int miles); } Then you have a Person class which uses this service and also needs a name and an address to be instantiated: public class Person { // Fields omitted public Person(String name, Address address, GeoService gs) { this.name = name; this.address = address; this.geoService = gs; } public boolean livesNear(Person otherPerson) { return geoService.isNear(address, otherPerson.getAddress(), 2 /* miles */); } } Something odd should jump at you right away with this class: while name and address are part of the identity of a Person object, the presence of the GeoService instance in it feels wrong. The service is a singleton that is created on start up, so a perfect candidate to be injected, but how can I achieve the creation of a Person object when some of its information is supplied by Guice and the other part by myself? Guice gives you a very elegant and flexible way to implement this scenario with “assisted injection”. The first step is to define a factory for our objects that represents exactly how we want to create them: public interface PersonFactory { Person create(String name, Address address); } Since only name and address participate in the identity of our Person objects, these are the only parameters we need to construct our objects. The other parameters should be supplied by Guice so we modify our Person constructor to let Guice know: @Inject public Person(@Assisted String name, @Assisted Address address, GeoService geoService) { this.name = name; this.address = address; this.geoService = geoService; } In this code, I have added an @Inject annotation on the constructor and an @Assisted annotation on each parameter that I will be providing. Guice will take care of injecting the rest. Finally, we connect the factory to its objects when creating the module: Module module1 = new FactoryModuleBuilder() .build(PersonFactory.class); The important part here is to realize that we will never instantiate PersonFactory: Guice will. From now on, all we need to do whenever we want to instantiate a Person object is to ask Guice to hand us a factory: @Inject private PersonFactory personFactory; // ... Person p = personFactory.create("Bob", new Address("1 Ocean st")); If you want to find out more, take a look at the main documentation for assisted injection, which explains how to support overloaded constructors and also how to create different kinds of objects within the same factory. Wrapping up Let’s take a look at what we did. First, we started with a suspicious looking constructor: public Person(String name, Address address, GeoService s) { This constructor is suspicious because it accepts parameters that do not participate in the identity of the object (you won’t use the GeoService parameter when calculating the hash code of a Person object). Instead, we replaced this constructor with a factory that only accepts identity fields: public interface PersonFactory { Person create(String name, Address address); } and we let Guice’s assisted injection take care of creating a fully formed object for us. This observation leads us to the Identity Constructor rule: If a constructor accepts parameters that are not used to define the identity of the objects, consider injecting these parameters. Once you start looking at your objects with this rule in mind, you will be surprised to find out how many of them can benefit from assisted injection.
August 23, 2012
by Cedric Beust
· 36,672 Views · 2 Likes
article thumbnail
Spring Tool Suite (STS) and Groovy/Grails Tool Suite (GGTS) 3.0.0 releases
We are proud to announce that the newest major release of our Eclipse-based developer tooling is now available. This is a major release not only in terms of new features but because of other serious changes like project componentization, open-sourcing and the fact that for the first time we are making multiple distributions available, each tailored for a different kind of developer. Check out the release announcement on Martin Lippert's Blog. 100% Open Sourced – All STS features that were previously under a free commercial license, have been donated under the Eclipse Public License (EPL) at GitHub! Intelligent Repackaging - Repackaging the product itself makes identifying what tools you need, and getting started with them much easier. In the past, Groovy/Grails developers had to install several extensions manually into Eclipse to get started. Now there are two full eclipse distributions, one targeted at Spring developers, the other at Groovy/Grails developers – just download, install and go, no assembly required. Componentized projects: Componentizing allows installation and configuration flexibility – developers can install components individually into their existing, plain Eclipse Java EE installations if they wish, preserving their hard work of configuring their Eclipse IDEs just the way they like them. Downloads, more information and FAQ You can find the downloads as well as more information on the project websites for the toolsuites: Spring Tool Suite Groovy/Grails Tool Suite Installation Instructions FAQ Feedback and discussions If you have feedback or questions for us, please do not hesitate to contact us via our SpringSource Tool Suite forum. Bugs and feature requests are always welcome as tickets in our JIRA or, even better, as pull requests on GitHub.
August 22, 2012
by Pieter Humphrey
· 3,497 Views
article thumbnail
Obfuscate Your JavaFX Application
Introduction JavaFX currently has a high momentum and enjoys good adoption in the community. With its rich set of controls, CSS styling, good and free tool chain and, last but not least, its multi-platform availability (with Version 2.2 that was released just a couple of days ago, it is available for Windows, Mac OS and Linux) it is just natural to take it into consideration when thinking about an implementation technology for commercial desktop applications. Java is compiled into a bytecode which can be just as easily decompiled back into human readable source code. If you are thinking about writing a commercial application you might want to protect your intellectual property by implementing some functionality that checks if the user has a proper license - for instance a valid serial number - or something alike. This functionality or the whole application should not be easy to decompile and understand by a third party. A common measure to achieve this, or at least make it harder, is obfuscation. Since the reinvention of Version 2.0, JavaFX is 100% Java, which means you can use any Java obfuscator and just mind some minor differences. There is a whole bunch of free and commercial obfuscation tools out there. One of them you will encounter if you Google java obfuscation, and its proguard (http://proguard.sourceforge.net/). It is free and, although it takes some time to get into it, it's well-documented and ships with an ant task. The following text describes the process of obfuscating a JavaFX application with proguard. It is a complete example that uses the latest tools and features in JavaFX, including FXML. The following tools were used: Netbeans 7.2 Scene Builder 1.0 JDK 7 update 6 with JavaFX 2.2 Proguard version 4.8 The complete example is attached as a netbeans project. The Application The example application is a very simple one. It shows one screen with a textfield for a message and a button. If the user presses the button, the message is encrypted and shown in another non-editable textfield. The screen is implemented using fxml (Sample.fxml) and a controller class (SampleController.java). The code to encrypt the message is implemented in a separate class (EncryptionService.java) and the finally there is an application class with a main method (ObfuscationExample.java) that starts up the whole application. The following screenshot shows the application. Obfuscation Proguard is highly customizable and ships with a gui that let's you edit the configuration file that is specific for your application. I don't want to get too much into details here. As mentioned the proguard documentation is pretty exhaustive. You have to specify the jars that you want to get obfuscated (injars) , the resulting jar (outjars) and all libraries that are referenced from your injars (library jars), in any case the Java runtime (rt.jar) and the JavaFX runtime (jfxrt.jar). Until there it is just like any other java application that you obfuscate. In the case of JavaFX, there are some more things that need to be considered: In the controller class for the fxml file action handler methods and controls are annotated with the @FXML annotation. You want to keep these annotations and achieve this with the -keepattributes option Both controls and action handler methods are connected via the annotation AND their name. Therefore you also want to keep the names of those, which can be achieved with the -keepclassmembernames option that is applied to everything that is annotated with @javafx.fxml.FXML Last but not least, you want to keep your main method(s) that are the entry point to your application. In the case of JavaFX you have to configure this always for two classes: com.javafx.main.Main and your JavaFX application class, in our case: obfuscationexample.ObfuscationExample -injars dist\ObfuscationExample.jar -outjars dist\o_ObfuscationExample.jar -libraryjars /lib/rt.jar -libraryjars /lib/jfxrt.jar -dontshrink -dontoptimize -flattenpackagehierarchy '' -keepattributes Exceptions,InnerClasses,Signature,Deprecated,SourceFile,LineNumberTable,LocalVariable*Table,*Annotation*,Synthetic,EnclosingMethod -adaptresourcefilecontents **.fxml,**.properties,META-INF/MANIFEST.MF -keepclassmembernames class * { @javafx.fxml.FXML *; } # Keep - Applications. Keep all application classes, along with their 'main' # methods. -keepclasseswithmembers public class com.javafx.main.Main, obfuscationexample.ObfuscationExample { public static void main(java.lang.String[]); } The result of the obfuscation can be viewed in a decompiler. I was using JD-GUI (http://java.decompiler.free.fr) which is also free and quite easy to use. Automatically obfuscate during build After we have the obfuscation setup to our needs, we finally want to integrate it in our build-process. The build.xml that is created automatically in Netbeans offers some hooks to call additional tasks during the build-process -post-jfx-jar seems to the right step, as this is called after the jar file was created. As mentioned above proguard ships with an ant task that allows - besides other things - to just simply execute a proguard configuration file. The target below is called during the build process and does the following: Define the proguard ant task Call proguard with our configuration that we have setup before Rename the resulting obfuscated jar to the original name to make for example the original JNLP-file still work. Conclusion Although it took me some time to get everything working especially when using FXML, it is after all not much code to get your JavaFX application at least basically obfuscated in a seamless and automated way. Proguard has much more options to obfuscate in a more sophisticated way and to even shrink and optimize your code. Anyway I leave it up to you to configure it to your special needs.
August 21, 2012
by Thomas Bolz
· 16,131 Views · 2 Likes
article thumbnail
Spring Data, Spring Security and Envers integration
Learn about pros, cons, and basics of Spring security and data, plus Envers integration.
August 20, 2012
by Nicolas Fränkel
· 25,112 Views · 1 Like
article thumbnail
EF Migrations Command Reference
Entity Framework Migrations are handled from the package manager console in Visual Studio. The usage is shown in various tutorials, but I haven’t found a complete list of the commands available and their usage, so I created my own. There are four available commands. Enable-Migrations: Enables Code First Migrations in a project. Add-Migration: Scaffolds a migration script for any pending model changes. Update-Database: Applies any pending migrations to the database. Get-Migrations: Displays the migrations that have been applied to the target database. The information here is the output of running get-help command-name -detailed for each of the commands in the package manager console (running EF 4.3.1). I’ve also added some own comments where I think some information is missing. My own comments are placed under the Additional Information heading. Please note that all commands should be entered on the same line. I’ve added line breaks to avoid vertical scrollbars. Enable-Migrations Enables Code First Migrations in a project. Syntax Enable-Migrations [-EnableAutomaticMigrations] [[-ProjectName] ] [-Force] [] Description Enables Migrations by scaffolding a migrations configuration class in the project. If the target database was created by an initializer, an initial migration will be created (unless automatic migrations are enabled via the EnableAutomaticMigrations parameter). Parameters -EnableAutomaticMigrations Specifies whether automatic migrations will be enabled in the scaffolded migrations configuration. If ommitted, automatic migrations will be disabled. -ProjectName Specifies the project that the scaffolded migrations configuration class will be added to. If omitted, the default project selected in package manager console is used. -Force Specifies that the migrations configuration be overwritten when running more than once for given project. This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type: get-help about_commonparameters. Remarks To see the examples, type: get-help Enable-Migrations -examples. For more information, type: get-help Enable-Migrations -detailed. For technical information, type: get-help Enable-Migrations -full. Additional Information The flag for enabling automatic migrations is saved in the Migrations\Configuration.cs file, in the constructor. To later change the option, just change the assignment in the file. public Configuration() { AutomaticMigrationsEnabled = false; } Add-Migration Scaffolds a migration script for any pending model changes. Syntax Add-Migration [-Name] [-Force] [-ProjectName ] [-StartUpProjectName ] [-ConfigurationTypeName ] [-ConnectionStringName ] [-IgnoreChanges] [] Add-Migration [-Name] [-Force] [-ProjectName ] [-StartUpProjectName ] [-ConfigurationTypeName ] -ConnectionString -ConnectionProviderName [-IgnoreChanges] [] Description Scaffolds a new migration script and adds it to the project. Parameters -Name Specifies the name of the custom script. -Force Specifies that the migration user code be overwritten when re-scaffolding an existing migration. -ProjectName Specifies the project that contains the migration configuration type to be used. If ommitted, the default project selected in package manager console is used. -StartUpProjectName Specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used. -ConfigurationTypeName Specifies the migrations configuration to use. If omitted, migrations will attempt to locate a single migrations configuration type in the target project. -ConnectionStringName Specifies the name of a connection string to use from the application’s configuration file. -ConnectionString Specifies the the connection string to use. If omitted, the context’s default connection will be used. -ConnectionProviderName Specifies the provider invariant name of the connection string. -IgnoreChanges Scaffolds an empty migration ignoring any pending changes detected in the current model. This can be used to create an initial, empty migration to enable Migrations for an existing database. N.B. Doing this assumes that the target database schema is compatible with the current model. This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type: get-help about_commonparameters. Remarks To see the examples, type: get-help Add-Migration -examples. For more information, type: get-help Add-Migration -detailed. For technical information, type: get-help Add-Migration -full. Update-Database Applies any pending migrations to the database. Syntax Update-Database [-SourceMigration ] [-TargetMigration ] [-Script] [-Force] [-ProjectName ] [-StartUpProjectName ] [-ConfigurationTypeName ] [-ConnectionStringName ] [] Update-Database [-SourceMigration ] [-TargetMigration ] [-Script] [-Force] [-ProjectName ] [-StartUpProjectName ] [-ConfigurationTypeName ] -ConnectionString -ConnectionProviderName [] Description Updates the database to the current model by applying pending migrations. Parameters -SourceMigration Only valid with -Script. Specifies the name of a particular migration to use as the update’s starting point. If ommitted, the last applied migration in the database will be used. -TargetMigration Specifies the name of a particular migration to update the database to. If ommitted, the current model will be used. -Script Generate a SQL script rather than executing the pending changes directly. -Force Specifies that data loss is acceptable during automatic migration of the database. -ProjectName Specifies the project that contains the migration configuration type to be used. If ommitted, the default project selected in package manager console is used. -StartUpProjectName Specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used. -ConfigurationTypeName Specifies the migrations configuration to use. If omitted, migrations will attempt to locate a single migrations configuration type in the target project. -ConnectionStringName Specifies the name of a connection string to use from the application’s configuration file. -ConnectionString Specifies the the connection string to use. If omitted, the context’s default connection will be used. -ConnectionProviderName Specifies the provider invariant name of the connection string. This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type: get-help about_commonparameters. Remarks To see the examples, type: get-help Update-Database -examples. For more information, type: get-help Update-Database -detailed. For technical information, type: get-help Update-Database -full. Additional Information The command always runs any pending code-based migrations first. If the database is still incompatible with the model the additional changes required are applied as an separate automatic migration step if automatic migrations are enabled. If automatic migrations are disabled an error message is shown. Get-Migrations Displays the migrations that have been applied to the target database. Syntax Get-Migrations [-ProjectName ] [-StartUpProjectName ] [-ConfigurationTypeName ] [-ConnectionStringName ] [] Get-Migrations [-ProjectName ] [-StartUpProjectName ] [-ConfigurationTypeName ] -ConnectionString -ConnectionProviderName [] Description Displays the migrations that have been applied to the target database. Parameters -ProjectName Specifies the project that contains the migration configuration type to be used. If ommitted, the default project selected in package manager console is used. -StartUpProjectName Specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used. -ConfigurationTypeName Specifies the migrations configuration to use. If omitted, migrations will attempt to locate a single migrations configuration type in the target project. -ConnectionStringName Specifies the name of a connection string to use from the application’s configuration file. -ConnectionString Specifies the the connection string to use. If omitted, the context’s default connection will be used. -ConnectionProviderName Specifies the provider invariant name of the connection string. This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type: get-help about_commonparameters. Remarks To see the examples, type: get-help Get-Migrations -examples. For more information, type: get-help Get-Migrations -detailed. For technical information, type: get-help Get-Migrations -full. Additional Information The powershell commands are complex powershell functions, located in the tools\EntityFramework.psm1 file of the Entity Framework installation. The powershell code is mostly a wrapper around the System.Data.Entity.Migrations.MigrationsCommands found in the tools\EntityFramework\EntityFramework.PowerShell.dll file. First a MigrationsCommands object is instantiated with all configuration parameters. Then there is a public method on the MigrationsCommands object for each of the available commands.
August 20, 2012
by Anders Abel
· 31,405 Views · 1 Like
article thumbnail
8 New & Beefed Up NetBeans Keyboard Shortcuts!
My colleague Tom McGinn recently published 10 Time Savers in NetBeans, an excellent overview of tips that everyone using NetBeans should read. For those of us who are keyboard oriented (i.e., we hate the mouse because it breaks our workflow), here is an appendix to Tom's article, listing the very newest keyboard shortcuts, available in NetBeans IDE 7. Most are new or changed in NetBeans IDE 7.2, while the last one is new but unchanged from NetBeans IDE 7.1. Alt + Scroll Up/Down. Increase/decrease the font size. Font resizing, which was first introduced in NetBeans IDE 7.1, was initially done by holding down the Ctrl key while scrolling. However, this conflicted with other actions, as explained in issue 212484. Following discussions with the NetBeans community, the Ctrl key was changed for the Alt key, and now, when you hold down the Alt key and then scroll up/down, in any file, the font size will increase/decrease. Alt + Shift + Page Up/Down. Quickly move entire code elements, i.e., statements and class members, up or down. Take the following situation. The cursor is on the first line below; if you were to use the standard Alt + Shift + Down, only the line would be moved down, which would immediately create an error in the editor because now the class cannot be compiled anymore. However, if you use Alt + Shift + Page Down instead (i.e., Page Down instead of simply Down), the entire method will move downwards, over the method below that, and will then appear below the method that is currently below it. In other words, the move action now has semantic knowledge of the code being moved, as well as semantic knowledge of the code around it. A similarly semantic-aware keyboard shortcut, though not new in NetBeans IDE 7, is Alt + Shift + Period, which lets you semantically expand the selection from the currently selected word to the next level of semantic knowledge, e.g., method or class, and back again via Alt + Shift + Comma. Alt + Backspace. Quickly remove the enclosing parts of a nested statement. Put the cursor within the word "for", or "if", or "else", for example, then press Alt + Backspace and the popup below is displayed. Mouse down or up in the list and then press Enter to confirm. Ctrl + Shift + M. Add/remove a bookmark to/from the Bookmarks Window. As always, you can set bookmarks in your code. However, now, when you do so, the bookmarks are, in addition to being marked in the file, added to the new Bookmarks Window (available via Window | Navigating | Bookmarks). From the Bookmarks Window, you can now jump across all your files and all your projects so that you can, for example, create a task-oriented track through your projects: In a related change, when you now use Ctrl + Shift + Period or Ctrl + Shift + Comma, to toggle back and forward between bookmarks, this handy popup appears, listing all the bookmarks found within the Bookmarks Window: Alt + Shift + F. The "Reformat" action can now be used across multiple projects, packages, and classes, for the first time. That means that when you use the old Alt + Shift + F while multiple nodes are selected in the Projects window, all files within the selected nodes will be reformatted at the same time. Ctrl + Z. The "Undo" keyboard shortcut now applies to refactorings too, for the first time. In previous releases, you needed to use a separate action especially for undoing refactorings, which was very hidden in the Refactoring menu and therefore hard to find, and therefore not frequently used because typically you wouldn't know it existed. Ctrl + Space. Once you have pressed Ctrl-F or Ctrl-H to open the Find bar or the Search bar at the bottom of any file (not only Java source files, but also HTML files, for example), you can press Ctrl + Space which lets you use code completion within the Find field, which can be very useful to get a quick overview of the items you could be trying to find. In the Debugger, the same is true in the New Breakpoint dialog. Ctrl + Shift + R. Change the cursor to a block selector. Then put the cursor next to the top left of the block and Shift+Click its bottom right corner. You now have a block, which you can manipulate, e.g., move or cut or copy or delete or change all the lines within the block. Start typing while having a block selected and all the lines will change simultaneously. Applies to all file types, not only Java source files, as can be seen here: Note: And, a final tip, if you go to the Help menu in NetBeans IDE, you'll find the updated NetBeans IDE Keyboard Shortcut Card in PDF format, ideal for printing out and hanging in a nice frame in your workspace!
August 19, 2012
by Geertjan Wielenga
· 54,872 Views
article thumbnail
How to Migrate Drupal to Azure Web Sites
DrupalCon Munich is next week, and I am lucky enough to be going. As part of preparing for the conference, I thought it would be worthwhile to see just how easy (or difficult) it would be to migrate an existing Drupal site to Windows Azure Web Sites. So, in this post, I’ll do just that. Fortunately, because Windows Azure Web Sites supports both PHP and MySQL, the migration process is relatively straightforward. And, because Drupal and PHP run on any platform, the process I’ll describe should work for moving Drupal to Windows Azure Web Sites regardless of what platform you are moving from. Of course, Drupal installations can vary widely, so YMMV. I tested the instructions below on relatively small (and simple) Drupal installation running on CentOS 5. (Unfortunately, I won’t be using Drush since it isn’t supported on Windows Azure Websites.) If you are considering moving a large and complex Drupal application, may want to consider moving to Windows Azure Cloud Services (more information about that here: Migrating a Drupal Site from LAMP to Windows Azure). Before getting started, it’s worth noting that Windows Azure Websites lets you run up to 10 Web Sites for free in a multitenant environment. And, you can seamlessly upgrade to private, reserved VM instances as your traffic grows. To sign up, try the Windows Azure 90-day free trial. 1. Create a Windows Azure Web Site and MySQL database There is a step-by-step tutorial on http://www.windowsazure.com that walks you through creating a new website and a MySQL database, so I’ll refer you there to get started: Create a PHP-MySQL Windows Azure web site and deploy using Git. If you intend to use Git to publish your Drupal site, then go ahead and follow the instructions for setting up a Git repository. Make sure to follow the instructions in the Get remote MySQL connection information section as you will need that information later. You can ignore the remainder of the tutorial for the purposes of deploying your Drupal site, but if you are new to Windows Azure Web Sites (and to Git), you might find the additional reading informative. Ok, now you have a new website with a MySQL database, your have your MySQL database connection information, and you have (optionally) created a remote Git repository and made note of the Git deployment instructions. Now you are ready to copy your database to MySQL in Windows Azure Web Sites. 2. Copy database to MySQL in Windows Azure Web Sites I’m sure there is more than one way to copy your Drupal database, but I found the mysqldump tool to be effective and easy to use. To copy from a local machine to Windows Azure Web Sites, here’s the command I used: mysqldump -u local_username --password=local_password drupal | mysql -h remote_host -u remote_username --password=remote_password remote_db_name You will, of course, have to provide the username and password for your existing Drupal database, and you will have to provide the hostname, username, password, and database name for the MySQL database you created in step 1. This information is available in the connection string information that you should have noted in step 1. i.e. You should have a connection string that looks something like this: Database=remote_db_name;Data Source=remote_host;User Id=remote_username;Password=remote_password Depending on the size of your database, the copying process could take several minutes. Now your Drupal database is live in Windows Azure Websites. Before you deploy your Drupal code, you need to modify it so it can connect to the new database. 3. Modify database connection info in settings.php Here, you will again need your new database connection information. Open the /drupal/sites/default/setting.php file in your favorite text editor, and replace the values of ‘database’, ‘username’, ‘password’, and ‘host’ in the $databases array with the correct values for your new database. When you are finished, you should have something similar to this: $databases = array ( 'default' => array ( 'default' => array ( 'database' => 'remote_db_name', 'username' => 'remote_username', 'password' => 'remote_password', 'host' => 'remote_host', 'port' => '', 'driver' => 'mysql', 'prefix' => '', ), ), ); Be sure to save the settings.phpfile, then you are ready to deploy. 4. Deploy Drupal code using Git or FTP The last step is to deploy your code to Windows Azure Web Sites using Git or FTP. If you are using FTP, you can get the FTP hostname and username from you website’s dashboard. Then, use your favorite FTP client to upload your Drupal files to the /site/wwwroot folder of the remote site. If you are using Git, you need to set up a Git repository in Windows Azure Web Sites (steps for this are in the tutorial mentioned earlier). And, you will need Git installed on your local machine. Then, just follow the instructions provided after you created the repository: One note about using Git here: depending on your Git settings, your .gitignore file (a hidden file and a sibling to the .git folder created in your local root directory after you executed git commit), some files in your Drupal application may be ignored. In my case, all the files in the sites directory were ignored. If this happens, you will want to edit the .gitignore file so that these files aren’t ignored and redeploy. After you have deployed Drupal to Windows Azure Web Sites, you can continue to deploy updates via Git or FTP. Related information If you are looking for more information about Windows Azure Web Sites, these posts might be helpful: Windows Azure Websites- A PHP Perspective Windows Azure Websites, Web Roles, and VMs- When to use which- Configuring PHP in Windows Azure Websites with .user.ini Files One last thing you might consider, depending on your site, is using the Windows Azure Integration Module to store and serve your site’s media files.
August 19, 2012
by Brian Swan
· 10,265 Views
article thumbnail
8 Ways to Improve Your Java EE Production Support Skills
This article will provide you with 8 ways to improve your production support skills which may help you better enjoy your IT support job.
August 15, 2012
by Pierre - Hugues Charbonneau
· 32,588 Views · 2 Likes
article thumbnail
Using Spring Profiles in XML Config
Learn how to use spring profiles in an XML config with this great tutorial.
August 14, 2012
by Roger Hughes
· 185,768 Views · 4 Likes
article thumbnail
JaCoCo Jenkins Plugin
In my post about JaCoCo and MavenI wrote about the problems of using the JaCoCo Maven plugin in multimodule Maven projects because of having one report for each module separately instead of one report for all modules, and how it can be fixed using JaCoCo Ant Task. In this post we are going to see how to use the JaCoCo Jenkins plugin to achieve the same goal of Ant Tasks and have overall code coverage statistics for all modules. The first step is installing the JaCoCo Jenkins plugin. Go to Jenkins -> Manage Jenkins -> Plugin Manager -> Available and find JaCoCo Plugin The next step, if it is not done already, is configuring your JaCoCo Maven plugin into parent pom: org.jacoco jacoco-maven-plugin ${jacoco.version} prepare-agent report prepare-package report And finally a post-action must be configured to the job responsible for packaging the application. Note that in previous pom file reports are generated just before the package goal is executed. Go to Configure -> Post-build Actions -> Add post-build action -> Record JaCoCo coverage report. Then we have to set folders or files containing JaCoCoXML reports, which are using the previous pom to **/target/site/jacoco/jacoco*.xml, and also set when we consider that a build is healthy in terms of coverage. Then we can save the job configuration and run the build project. After the project is build, a new report will appear just under the test result trend graph, called code coverage trend, where we can see the code coverage of all project modules. From the left menu, you can enter into Coverage Report and see code coverage of each module separately. Furthermore, visiting the Jenkins main page will give you a nice quick overview of a job when you mouse over the weather icon as shown: Keep in mind that this approach for merging code coverage files will only work if you are using Jenkins as a CI system. Ant Task is a more generic solution and can also be used with the JaCoCo Jenkins plugin. We Keep Learning, Alex.
August 14, 2012
by Alex Soto
· 58,570 Views · 4 Likes
article thumbnail
How to do a Production Hotfix
Situation It’s Thursday/Friday evening, the daily version / master branch was deemed too risky to install, and you decide to wait for Sunday/Monday with the deploy to production. There’s a new critical bug found in production. We do not want to install the bug on top of all the other changes, because of the risk factor. What do we do? Develop the fix on top of the production branch, in our local machine, git push, and deploy the fix, without all the other changes. How can I do this? My example uses a Play Framework service, but that’s immaterial. gitk –all – review the situation Suppose the latest version deployed in prod is 1.2.3, and master has some commits after that. You checkout this version: git checkout 1.2.3 Create a new branch for this hotfix. git checkout -b 1.2.3_hotfix1 Fix the bug locally, and commit. Test it locally. git push On the production machine: git fetch (not pull!) sudo service play stop git checkout 1.2.3_hotfix1 sudo service play start Test on production Merge the fix back to master: git checkout master git merge 1.2.3_hotfix1 git push Clean up the local branch: git branch -d 1.2.3_hotfix1 (Note: the branch will still be saved on origin, you’re not losing any information by deleting it locally)
August 14, 2012
by Ron Gross
· 12,110 Views
article thumbnail
JaCoCo in Maven Multi-Module Projects
Code coverage is an important measurement used during our development that describes the degree to which source code is tested. In this post I am going to explain how to run code coverage using Maven and JaCoCo plugins in multi-module projects. JaCoCo is a code coverage library for Java, which has been created by the EclEmma team. It has a plugin for Eclipse, and can be run with Ant and Maven too. Now we will focus only on a Maven approach. In a project with only one module is as easy as registering a build plugin: org.jacoco jacoco-maven-plugin 0.5.7.201204190339 prepare-agent report prepare-package report And now running mvn package in site/jacoco directory, a coverage report will be present in different formats. But with multimodule projects a new problem arises. How do we merge the metrics of all subprojects into only one file so we can have a quick overview of all subprojects? For now the Maven JaCoCo Plugin does not support it. There are many alternatives and I am going to cite the most common: Sonar. It has the disadvantage that you need to install Sonar (maybe you are already using it, but maybe not). Jenkins. The plugin for JaCoCo is still under development. Moreover you need to run a build job to inspect your coverage. This is good in terms of continuous integration but could be a problem if you are trying to "catch" some piece of code that have not been covered with previously implemented tests. Arquillian JaCoCo Extension. Arquillian is a container test framework that has an extension which during test execution can capture the coverage. It's a good option if you are using Arquillian. The disadvantage is that maybe your project does not require a container. Ant. You can use an Ant task with Maven. JaCoCo Ant tasks can merge results from multiple JaCoCo file results. Note that this is the most generic solution, and this is the chosen approach that we are going to use. The first thing to do is add a JaCoCo plugin to the parent pom so all projects could generate a coverage report. Of course, if there are modules which do not require coverage, the plugin definition should be changed from parent pom to specific projects. org.jacoco jacoco-maven-plugin 0.5.7.201204190339 prepare-agent report prepare-package report The next step is creating a specific submodule for appending all results of the JaCoCo plugin by using an Ant task. I suggest using something like project-name-coverage. Then let's open generated pom.xml and we are going to insert the required plugins to join all coverage information. To append them. As we have already written we are going to use a JaCoCo Ant task which has the ability to open all JaCoCo output files and append all their content into one. So the first thing to do is download the jar which contains the JaCoCo Ant task. To automate the download process, we are going to use maven dependency plugin: org.apache.maven.plugins maven-dependency-plugin jacoco-dependency-ant copy process-test-resources false org.jacoco org.jacoco.ant ${jacoco.version} true ${basedir}/target/jacoco-jars During process-test-resources phase Jacoco Ant artifact will be downloaded and copied to the target directory so it can be registered into the pom without worrying about the jar location. We also need a way to handle Ant tasks from Maven. And this is as simple as using maven antrun plugin, which you can specify any ant command in its configuration section. See next simple example: org.apache.maven.plugins maven-antrun-plugin 1.6 compile run Notice that we can specify any Ant task in the target tag. And now we are ready to start configuring the JaCoCo Ant task. The JaCoCo report plugin requires you set the location of the build directory, class directory, source directory or generated-source directory. For this purpose we are going set them as properties. ../projectA/target ../projectB/target ../projectA/target/classes ../projectB/target/classes ../projectA/src/main/java ../projectB/src/main/java ../projectA/target/generated-sources/annotations ../projectB/target/generated-sources/annotations And now the Ant task part which will go into target tag of the antrun plugin. First we need to define report task. Do you see that org.jacoco.ant.jar file is downloaded by the dependency plugin? You don't need to worry about copying it manually. Then we are going to call report task as defined in taskdef section. Within the executiondata element, we specify locations where JaCoCo execution data files are stored. By default this is the target directory, and for each project we need to add one entry for each submodule. The next element is structure. This element defines the report structure, and can be defined with a hierarchy of group elements. Each group should contain class files and source files of all projects that belongs to that group. In our example only one group is used. And finally we are setting output format using html, xml and csv tags. Complete Code: org.apache.maven.plugins maven-antrun-plugin 1.6 post-integration-test run org.jacoco org.jacoco.ant ${jacoco.version} And now simply run mvn clean verify and in my-project-coverage/target/coverage-report, a report with code coverage of all projects will be presented. Hope you find this post useful. We Keep Learning, Alex.
August 13, 2012
by Alex Soto
· 81,633 Views · 4 Likes
article thumbnail
Installing Oracle Java 6 on Ubuntu
If you have already installed Ubuntu 12.04 you probably have realized that Sun java(oracle java) does not come prepacked with Ubuntu like it used to be , instead OpenJDK comes with it. Here is how you can install Oracle java on Ubuntu 12.04 manually. Download jdk-6u32-linux-x64.bin from this link. If you have used 32-bit Ubuntu installation, download jdk-6u32-linux-x32.bin instead. To make the downloaded bin file executable use the following command chmod +x jdk-6u32-linux-x64.bin To extract the bin file use the following command ./jdk-6u32-linux-x64.bin Using the following command create a folder called "jvm" inside /usr/lib if it is not already existing sudo mkdir /usr/lib/jvm Move the extracted folder into the newly created jvm folder sudo mv jdk1.6.0_32 /usr/lib/jvm/ To install the Java source use following commands sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk1.6.0_32/bin/javac 1 sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk1.6.0_32/bin/java 1 sudo update-alternatives --install /usr/bin/javaws javaws /usr/lib/jvm/jdk1.6.0_32/bin/javaws 1 To make this default java sudo update-alternatives --config javac sudo update-alternatives --config java sudo update-alternatives --config javaws To make symlinks point to the new Java location use the following command ls -la /etc/alternatives/java* To verify Java has installed correctly use this command java -version
August 13, 2012
by Pavithra Gunasekara
· 60,176 Views · 1 Like
article thumbnail
Spring Integration with Gateways
This is the second article of the series on Spring Integration. This article builds on top of the first article where we introduced Spring Integration. Context setting In the first article, we created a simple java application where A message was sent over a channel, It was intercepted by a service i.e. POJO and modified. It was then sent over a different channel The modified message was read from the channel and displayed. However, in doing this - keeping in mind that we were merely introducing the concepts there - we wrote some Spring specific code in our application i.e. the test classes. In this article we will take care of that and make our application code as insulated from Spring Integration api as possible. This is done by, what Spring Integration calls gateways. Gateways exist for the sole purpose of abstracting messaging related "plumbing" code away from "business" code. The business logic might really not care whether a functionality is being achieved be sending a message over a channel or by making a SOAP call. This abstraction - though logical and desirable - have not been very practical, till now. It is probably worth having a quick look at the Spring Integration Reference Manual at this point. However, if you are just getting started with Spring Integration, you are perhaps better off following this article for the moment. I would recommend you get your hands dirty before returning to reference manual, which is very good but also very exhaustive and hence could be overwhelming for a beginner. The gateway could be a POJO with annotations (which is convenient but in my mind beats the whole purpose) or with XML configurations (can very quickly turn into a nightmare in any decent sized application if unchecked). At the end of the day it is really your choice but I like to go the XML route. The configuration options for both styles are detailed out in this section of the reference implementation. Spring Integration with Gateways So, let's create another test with gateway throw in for our HelloWorld service (refer to the first article of this series for more context). Let's start with the Spring configuration for the test. File: src/test/resources/org/academy/integration/HelloWorld1Test-context.xml In this case, all that is different is that we have added a gateway. This is an interface called org.academy.integration.Greetings. It interacts with both "inputChannel" and "outputChannel", to send and read messages respectively. Let's write the interface. File: /src/main/java/org/academy/integration/Greetings.java package org.academy.integration; public interface Greetings { public void send(String message); public String receive(); } And then we add the implementation of this interface. Wait. There is no implementation. And we do not need any implementation. Spring uses something called GatewayProxyFactoryBean to inject some basic code to this gateway which allows it to read the simple string based message, without us needing to do anything at all. That's right. Nothing at all. Note - You will need to add more code for most of your production scenarios - assuming you are not using Spring Integration framework to just push around strings. So, don't get used to free lunches. But, while it is here, let's dig in. Now, lets write a new test class using the gateway (and not interact with the channels and messages at all). File: /src/test/java/org/academy/integration/HelloWorld1Test.java package org.academy.integration; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class HelloWorld1Test { private final static Logger logger = LoggerFactory .getLogger(HelloWorld1Test.class); @Autowired Greetings greetings; @Test public void test() { greetings.send("World"); assertEquals(greetings.receive(), "Hello World"); logger.debug("Spring Integration with gateways."); } } Our test class is much cleaner now. It does not know about channels, or messages or anything related to Spring Integration at all. It only knows about a greetings instance - to which it gave some data by .send() method - and got modified data back by .receive() method. Hence, the business logic is oblivious of the plumbing logic, making for a much cleaner code. Now, simply type "mvn -e clean install" (or use m2e plugin) and you should be able to run the unit test and confirm that given string "World" the HelloWorld service indeed returns "Hello World" over the entire arrangement of channels and messages. Again, something optional but I highly recommend, is to run "mvn -e clean install site". This - assuming you have correctly configured some code coverage tool (cobertura in my case) will give you a nice HTML report showing the code coverage. In this case it would be 100%. I have blogged a series on code quality which deals this subject in more detail, but to cut long story short, it is very important for me to ensure that whatever coding practice / framework I use and recommend use, complies to some basic code quality standards. Being able to unit test and measure that is one such fundamental check that I do. Needless to say, Spring in general (including Spring integration) passes that check with flying colours. Conclusion That's it for this article. Happy coding.
August 13, 2012
by Partha Bhattacharjee
· 60,125 Views
  • Previous
  • ...
  • 845
  • 846
  • 847
  • 848
  • 849
  • 850
  • 851
  • 852
  • 853
  • 854
  • ...
  • 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
×