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

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones Build AI Agents That Are Ready for Production
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
Build AI Agents That Are Ready for Production

LIVE: “Cognitive Databases, Intelligent Data: Unified Infrastructure for Vector Search, AI-Optimized Queries, & Hybrid Workloads" Report

Live Webinar: Exclusive practitioner summit on AI-powered CDN operations and real-world automation strategies

The Latest Java Topics

article thumbnail
Add Comments and Javadocs in Eclipse With a Single Keystroke
When you want to work with comments in Eclipse, you could use the slow way of moving to the start of the line, pressing // and then repeating this for all the lines you have. Or you could use the quick way of adding a comment with a single keystroke no matter where the cursor’s positioned in the statement. The same goes for Javadocs – there are just too many things to type before you can start commenting the good stuff. That’s why Eclipse also has a shortcut that let’s you add Javadoc to a field, method or class. Keyboard shortcuts for comments and JavaDocs Here are the keyboard shortcuts for manipulating comments. Shortcut Command Description Ctrl+/ Toggle Comment Add/remove line comments (//…) from the current line. The position of the cursor can be anywhere on the line. Works with multiple selected lines as well. Ctrl+Shift+/ Add Block Comment Wrap the selected lines in a block comment (/*… */). Ctrl+Shift+\ Remove Block Comment Remove a block comment (/*… */) surrounding the selected lines. Alt+Shift+J Add Javadoc Comment Add a Javadoc comment to the active field/method/class. See the notes below for more details on where to position the cursor. Bear the following in mind when using Add Javadoc comment (Alt+Shift+J): To add a comment to a field, position the cursor on the field declaration. To add a comment to a method, position the cursor anywhere in the method or on its declaration. To add a comment to a class, the easiest is to position the cursor on the class declaration. Also works if you’re in the class, but not in a method, field or nested type. The Javadoc comment inserted is based on the Code Templates defined under Window > Preferences > Java > Code Style > Code Templates. If you expand the Comments section, you can change the default for Fields, Methods, Types (eg. classes), etc. Here’s a video to give you an idea of how fast and easy it is to add/remove comments using these shortcuts. The video shows toggling of single line comments, block comments and also adding a Javadoc comment to the method and class. Once I’ve commented out lines, I often find myself copying them and moving them around (eg. to try different variations of the code). You can do this faster by moving and copying lines using with a single keystroke. You can also have Eclipse format the comments whenever you save, saving you formatting time. From http://eclipseone.wordpress.com/2010/05/05/add-comments-and-javadocs-in-eclipse-with-a-single-keystroke/
May 6, 2010
by Byron M
· 177,951 Views · 2 Likes
article thumbnail
Mediator Pattern Tutorial with Java Examples
Learn the Mediator Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
April 26, 2010
by James Sugrue
· 113,568 Views · 3 Likes
article thumbnail
Grouping Tests Using JUnit Categories
In a well-organized build process, you want lightning-fast unit tests to run first, and provide whatever feedback they can very quickly. A nice way to do this is to be able to class your tests into different categories. For example, this can make it easier to distinguish between faster running unit tests, and slower tests such as integration, performance, load or acceptance tests. This feature exists in TestNG, but, until recently, not in JUnit. Indeed, this has been missing from the JUnit world for a long time. Using JUnit, I typically use test names (integration tests end in 'IntegrationTest', for example) or packages to identify different types of test. It is easy to configure a build script using Maven or Ant to run different types of test at different points in the build lifecycle. However it would be nice to be able to do this in a more elegant manner. JUnit 4.8 introduced a new feature along these lines, called Categories. However, like most new JUnit features, it is almost entirely undocumented. In this article we'll see how it works and what it can do for you. In JUnit 4.8, you can define your own categories for your tests. Categories are implemented as classes or interfaces. Since they simply act as markers, I prefer to use interfaces. One such category interface might look like this: public interface IntegrationTests {} You can also use inheritance to organize your test categories: public interface SlowTests {} public interface IntegrationTests extends SlowTests {} public interface PerformanceTests extends SlowTests {} So far so good. Now you can use these categories in your tests. In this example we flag a particular test class as containing integration tests: @Category(IntegrationTests.class) public class AccountIntegrationTest { @Test public void thisTestWillTakeSomeTime() { ... } @Test public void thisTestWillTakeEvenLonger() { .... } } You can also flag individual test methods if you prefer: public class AccountTest { @Test @Category(IntegrationTests.class) public void thisTestWillTakeSomeTime() { ... } @Test @Category(IntegrationTests.class) public void thisTestWillTakeEvenLonger() { ... } @Test public void thisOneIsRealFast() { ... } } To run tests in a particular category, you need to set up a test suite. In JUnit 4, a test suite is essentially an empty annotated class. To run only tests in a particular category, you use the @Runwith(Categories.class) annotation, and specify what category you want to run using the @IncludeCategory annotation @RunWith(Categories.class) @IncludeCategory(SlowTests.class) @SuiteClasses( { AccountTest.class, ClientTest.class }) public class LongRunningTestSuite {} You can also ask JUnit not to run tests in a particular category using the @ExcludeCategory annotation @RunWith(Categories.class) @ExcludeCategory(SlowTests.class) @SuiteClasses( { AccountTest.class, ClientTest.class }) public class UnitTestSuite {} Test categories are great if you use JUnit test suites. I haven't used test suites for years: Maven can find all my tests by itself, thank you very much, so I don't have to remember to add my test classes to the right test suite each time a create a new one. However, test suites do give you finer control over what order your tests are executed in, so you might still find them useful in that regard. Once you've done this, it is then easy to run tests in a particular category from within your IDE simply by running the test suite. On the tooling and build automation side of things, JUnit categories are not supported as well as TestNG groups. For example, the Maven surefire plugin lets you specify the TestNG groups you want to run in a particular phase, but no such support exists as yet for JUnit categories. You can of course configure the Surefire plugin to run a particular test suite (or test suites) in a particular phase, but it doesn't dispense you with the need to write and maintain a test suite. So test categories are great, but having to run them via a test suite (and to remember to add new test classes to the test suite) seems a bit clunky in these days of annotations and reflection. From http://weblogs.java.net/blog/johnsmart/archive/2010/04/25/grouping-tests-using-junit-categories-0
April 26, 2010
by John Ferguson Smart
· 22,189 Views
article thumbnail
“When a class with type parameters is not a parameterized class” – a Java Generics Puzzler
while recently fiddling with some more runtime generic type extraction for deployit , i was caught out by some unexpected behaviour by the reflection api. a check of the javadocs quickly revealed that i had once again been too hasty in relying on "common sense". still, the case seems sufficiently unintuitive to merit discussion. in this case, the issue centres on the interplay between class.gettypeparameters and parameterizedtype . the gist of the code looks something like: interface spying {} // small class hierarchy class person {} class professional extends person {} class agent extends professional {} class assassin extends professional {} class bystander extends person {} ... person jbond = new agent(); system.out.println("generic superclass type argument: " + trygetsuperclassgenerictypeparam(jbond)); person joepublic = new bystander(); system.out.println("generic superclass type argument: " + trygetsuperclassgenerictypeparam(joepublic)); person oddjob = new assassin(); system.out.println("generic superclass type argument: " + trygetsuperclassgenerictypeparam(oddjob)); ... type trygetsuperclassgenerictypeparam(object obj) { class clazz = obj.getclass(); class superclass = clazz.getsuperclass(); // elvis would be preferred, but for the sake of clarity... if (superclass.gettypeparameters().length > 0) { return ((parameterizedtype) clazz.getgenericsuperclass()).getactualtypearguments()[0]; } else { return null; } } so...what happens? trygetsuperclassgenerictypeparam is where the action happens. it seems fairly straightforward: see if the object's superclass is generic (i.e. takes type parameters) and, if so, cast its type representation to parameterizedtype to extract the actual value for the type parameter. if the superclass is not generic, simply return null. when this code is run, the first two invocations of trygetsuperclassgenerictypeparam result in the expected: generic superclass type argument: interface spying generic superclass type argument: null what about the third one? well, given the fact that we've omitted to specify a generic type parameter for professional we might assume 1 that we'd also get null. the actual output, however, is: exception in thread "main" java.lang.classcastexception: java.lang.class cannot be cast to java.lang.reflect.parameterizedtype at trygetsuperclassgenerictypeparam(...) huh? in order to figure out what's going on here, let's have a look at the javadoc for class.gettypeparameters: returns an array of typevariable objects that represent the type variables declared by the generic declaration represented by this genericdeclaration object, in declaration order. returns an array of length 0 if the underlying generic declaration declares no type variables. in other words, this is returning class-level information about the declaration of, in our case, the professional class, which of course does have a type parameter. however, if we look at class.getgenericsuperclass 2 , which we invoke next, we find that it: returns the type representing the direct superclass of the entity [...] represented by this class. if the superclass is a parameterized type, the type object returned must accurately reflect the actual type parameters used in the source code. here, the information returned is specific to the actual declaration of the class, which may (or may not, as in our case) specify type paramaters for its superclass. and therein lies the problem: professional.class.gettypearguments looks at the declaration of the professional class, discovering a type argument, whereas assassin.class.getgenericsuperclass looks at the occurrence of professional in the declaration of assassin and discovers no type parameters. hence, it returns a class rather than a parameterizedtype and blows up our code. ergo to cut a long story short: if an object's superclass has type arguments as determined by class.gettypearguments that does not mean that object.getclass().getgenericsuperclass() will be a parameterizedtype. footnotes read "i assumed" it's a pity that class.getgenericsignature , which determines the "generic or not" behaviour of class.getgenericsuperclass, is private, native and undocumented. from http://blog.xebia.com/2010/04/22/when-a-class-with-type-parameters-is-not-a-parameterized-class-a-java-generics-puzzler/
April 22, 2010
by Andrew Phillips
· 28,494 Views
article thumbnail
Memento Pattern Tutorial with Java Examples
Learn the Memento Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
April 21, 2010
by James Sugrue
· 63,301 Views · 2 Likes
article thumbnail
PubSub with Redis and Akka Actors
Redis (the version on the trunk) offers publish/subscribe based messaging. This is quite a big feature compared to the typical data structure oriented services that it had been offering so far. This also opens up lots of possibilities to use Redis as a messaging engine of a different kind. The sender and the receiver of the messages are absolutely decoupled from each other in the sense that senders do not send messages to specific receivers. Publishers publish messages on specific channels. Subscribers who subscribe to those channels get them and can take specific actions on them. As Salvatore notes in his weekly updates on Redis, this specific feature has evolved from lots of user requests who had been asking for a general notification mechanism to trap changes in the key space. Redis already offers BLPOP (Blocking list pop operation) for similar use cases. But still it's not sufficient to satisfy the needs of a general notification scheme. Salvatore explains it in more details in his blog post. I have been working on a Scala client, which I forked from Alejandro Crosa's repository. I implemented pubsub very recently and also have integrated it with Akka actors. The full implementation of the pubsub client in Scala is in my github repository. And if you like to play around with the Akka actor based implementation, have a look at the Akka repository. You define your publishers and subscribers as actors and exchange messages over channels. You can define your own callbacks as to what you would like to do when you receive a particular message. Let's have a look at a sample implementation at the client level .. I will assume that you want to implement your own pub/sub application on top of the Akka actor based pubsub substrate that uses the redis service underneath. Implementing the publisher interface is easy .. here is how you can bootstrap your own publishing service .. object Pub { println("starting publishing service ..") val p = new Publisher(new RedisClient("localhost", 6379)) p.start def publish(channel: String, message: String) = { p ! Publish(channel, message) } } The publish method just sends a Publish message to the Publisher. Publisher is an actor defined in Akka as follows: class Publisher(client: RedisClient) extends Actor { def receive = { case Publish(channel, message) => client.publish(channel, message) reply(true) } } The subscriber implementation is a bit more complex since you need to register your callback as to what you would like to do when you receive a specific type of message. This depends on your use case and it's your responsibility to provide a proper callback function downstream. Here is a sample implementation for the subscriber. We need two methods to subscribe and unsubscribe from channels. Remember in Redis the subscriber cannot publish - hence our Sub cannot do a Pub. object Sub { println("starting subscription service ..") val s = new Subscriber(new RedisClient("localhost", 6379)) s.start s ! Register(callback) def sub(channels: String*) = { s ! Subscribe(channels.toArray) } def unsub(channels: String*) = { s ! Unsubscribe(channels.toArray) } def callback(pubsub: PubSubMessage) = pubsub match { //.. } } I have not yet specified the implementation of the callback. How should it look like ? The callback will be invoked when the subscriber receives a specific type of message. According to Redis specification, the types of messages which a subscriber can receive are: a. subscribe b. unsubscribe c. message Refer to the Redis documentation for details of these message formats. In our case, we model them as case classes as part of the core Redis client implementation .. sealed trait PubSubMessage case class S(channel: String, noSubscribed: Int) extends PubSubMessage case class U(channel: String, noSubscribed: Int) extends PubSubMessage case class M(origChannel: String, message: String) extends PubSubMessage Our callback needs to take appropriate custom action on receipt of any of these types of messages. The following can be one such implementation .. It is customized for a specific application which treats various formats of messages and gives appropriate application dependent semantics .. def callback(pubsub: PubSubMessage) = pubsub match { case S(channel, no) => println("subscribed to " + channel + " and count = " + no) case U(channel, no) => println("unsubscribed from " + channel + " and count = " + no) case M(channel, msg) => msg match { // exit will unsubscribe from all channels and stop subscription service case "exit" => println("unsubscribe all ..") r.unsubscribe // message "+x" will subscribe to channel x case x if x startsWith "+" => val s: Seq[Char] = x s match { case Seq('+', rest @ _*) => r.subscribe(rest.toString){ m => } } // message "-x" will unsubscribe from channel x case x if x startsWith "-" => val s: Seq[Char] = x s match { case Seq('-', rest @ _*) => r.unsubscribe(rest.toString) } // other message receive case x => println("received message on channel " + channel + " as : " + x) } } Note in the above implementation we specialize some of the messages to give additional semantics. e.g. if I receive a message as "+t", I will interpret it as subscribing to the channel "t". Similarly "exit" will unsubscribe me from all channels. How to run this application ? I will assume that you have the Akka master with you. Also you need to have a version of Redis running that implements pubsub. You can start the subscription service using the above implementation and then use any other Redis client to publish messages. Here's a sample recipe for a run .. Prerequisite: Need Redis Server running (the version that supports pubsub) 1. Download redis from http://github.com/antirez/redis 2. build using "make" 3. Run server as ./redis-server For running this sample application :- Starting the Subscription service 1. Open up another shell similarly as the above and set AKKA_HOME 2. cd $AKKA_HOME 3. sbt console 4. scala> import sample.pubsub._ 5. scala> Pub.publish("a", "hello") // the first shell should get the message 6. scala> Pub.publish("c", "hi") // the first shell should NOT get this message Another publishing client using redis-cli Open up a redis-client from where you installed redis and issue a publish command ./redis-cli publish a "hi there" ## the first shell should get the message Have fun with the message formats 1. Go back to the first shell 2. Sub.unsub("a") // should unsubscribe the first shell from channel "a" 3. Study the callback function defined below. It supports many other message formats. 4. In the second shell window do the following: scala> Pub.publish("b", "+c") // will subscribe the first window to channel "c" scala> Pub.publish("b", "+d") // will subscribe the first window to channel "d" scala> Pub.publish("b", "-c") // will unsubscribe the first window from channel "c" scala> Pub.publish("b", "exit") // will unsubscribe the first window from all channels The full implementation of the above is there as a sample project in Akka master. And in case you are not using Akka, I also have a version of the above implemented using Scala actors in the scala-redis distribution. Have fun!
April 20, 2010
by Debasish Ghosh
· 15,573 Views
article thumbnail
Using Hibernate Validator to Cover Your Validation Needs
Recently I had to choose a validation framework or write one by myself. First I thought, no big deal, validation is not a complicated issue. But the more you think about it, the more you come to the conclusion that it is not as shallow as you think – you need to validate different types, you have different groups and many more issues… In short, writing a validation framework by yourself demands a lot of work. Luckily, JSR 303 solves this and the Hibernate implementation of the JSR does a pretty good job. Hibernate Validator is a JSR 303 implementation for bean validation. The way to work with this framework is first, to define constraints for java bean fields, and then, validating the bean. JSR 303 JSR 303 – defines a metadata model and API for entity validation. The default metadata source is annotations, with the ability to override and extend the meta-data through the use of XML. The API is not tied to a specific application tier or programming model. It is specifically not tied to either the web tier or the persistence tier, and is available for both server-side application programming, as well as for rich client Swing application developers. Hibernate Validator features Defining validation data using annotation and/or XML. Full object validation (including inner objects using recursion) Create customized constraints and validators. Customized error messages. Define groups(profiles). Create a Traversable Resolver. Using constraints Using XML Here is a simple example of a constraint using xml: com.mytest 2 In this example the field x can not be null. The field y can not be less than 2. Notice that the “Min” constraint has inner element – “value”. Notice the tag “”. It indicates the root path of all the beans. See also directions on how to load the XML file while using the validator. Using annotations Here is a simple code example: public class MyBean{@NotNullString x;@Min(2)int y;} This example is the equivalent to the previous xml example. Using both Using both annotations and XML constraints is possible. By default if you are using both only the XML is taken, unless you are using the attribute ‘ignore-annotations’ in the XML. Example: com.mytest.beans 2 2 Notice that the attribute ignore-annotations appears twice – for a bean and for a field. The default for a bean is ignore-annotations=”true” – this means that if you have an XML constraint for a bean, it will cancel the attribute constraint, Unless you will indicate that by ignore-annotations=”false” (look at the example). The default for a field is ignore-annotations=”false”. This means that by default annotations for a field are stronger (this is of course after you indicated that that the bean itself wont ignore annotations). If you wont that the XML will be stronger than you have to indicate that by ignore-annotations=”true” (look at the example in the “x2″ constraint). Existing constraints These constraints are a part of the hibernate validation framework: Constraint path Parameters javax.validation.constraints.AssertTrue (none) javax.validation.constraints.AssertFalse (none) javax.validation.constraints.NotNull (none) javax.validation.constraints.Null (none) javax.validation.constraints.Max value(mandatory) javax.validation.constraints.Min value(mandatory) javax.validation.constraints.DecimalMax value(mandatory) javax.validation.constraints.DecimalMin value(mandatory) javax.validation.constraints.Pattern regexp(mandatory) flags(optional) javax.validation.constraints.Past (none) javax.validation.constraints.Future (none) javax.validation.constraints.Size min(optional) max(optional) javax.validation.constraints.Digits integer(mandatory) fraction(mandatory) org.hibernate.constraints.Email (none) org.hibernate.constraints.Length min(optional) max(optional) org.hibernate.constraints.NotEmpty (none) org.hibernate.constraints.Range min(optional) max(optional) Inner objects constraints If you have nested beans (beans which contain other beans) you can easily let the system validate also the inner objects by using the constraint ‘valid’. XML example: com.mytest.beans Annotation example: public class MyBean{@Valid //inner bean to be validated separatelyprivate InnerBean innerBean; public InnerBean getInnerBean() {return innerBean;}public void setInnerBean(InnerBean innerBean) {this.innerBean = innerBean;}public class InnerBean { @NotNullString xx; public String getXx() {return xx;}public void setXx(String xx) {this.xx = xx;} Validating Example of a simple validation: ValidatorFactory factory = Validation.buildDefaultValidatorFactory();Validator validator = factory.getValidator();Set> constraintViolations = validator.validate(bean); Loading a constraints XML file As mentioned, you don’t have to use an XML file for defining constraints, you can just use annotations. But if you do want an XML file, you will have to load the file. Example: Configuration config = Validation.byDefaultProvider().configure();FileInputStream in = new FileInputStream( new File("resources/demo-constraints.xml"));config.addMapping(in);// Building the customized factory// (along with the changed configuration)ValidatorFactory factory = config.buildValidatorFactory();Validator validator = factory.getValidator(); The result The result(as you can see in the example above) is a collection of ConstraintViolation. Each ConstraintViolation holds the problematic field, it’s value and the error message itself. Example of reading the result: Set> constraintViolations = validator.validate(bean);//printing the resultsfor (ConstraintViolation constraintViolation : constraintViolations) {System.out.println(constraintViolation.getPropertyPath() + " -> " +constraintViolation.getMessage());} This object can be easily transformed to a more generic object like ValidationException or CyotaSoapException and so on. Customized constraints and validators If you want to create a new constraint you will have to create the constraint annotation interface and the validator class. Creating the constraint interface Here is a simple constraint example @Target( { METHOD, FIELD, ANNOTATION_TYPE })@Retention(RUNTIME)@Constraint(validatedBy = MyValidator.class)@Documentedpublic @interface MyConstraint{// These next parameters exist in every constraintString message() default "{com.mytest.MyConstraint.message}";Class[] groups() default {};Class[] payload() default {};// These next parameters are added// They are the constraint's attributesString myOptionalValue() default ""; //this parameter has a default valueString myMustValue(); //this parameters need to get input from the user} Notice the @Constraint annotation. It signifies the class that suppose to validates this constraint. Notice the message class member. It holds an error message or, like in this case, an error code. It will later be interpreted as a literal error message. The payload member holds payload objects. These objects carry additional data attached to the constraints that can be fetched when validating. Nested constraints You can also overload constraints very easily. For example, let’s say I want to create a new constraint which also checks that the value is not null. In this case, all I have to do is this: @Target( { METHOD, FIELD, ANNOTATION_TYPE })@Retention(RUNTIME)@Constraint(validatedBy = MyValidator.class)@Documented@NotNullpublic @interface MyConstraint{String message() default "{com.mytest.MyConstraint.message}";Class[] groups() default {};Class[] payload() default {};} In the example, notice the @NotNull annotation. Creating the validator class Here is an example of a simple validator: public class MyValidatorimplements ConstraintValidator {MyConstraint MyConstraint;/** * This function recives the constraint instance * (along with the user values) */public void initialize(MyConstraint MyConstraint) {this.MyConstraint=MyConstraint;}/** * The value is the actual object instance. * */public boolean isValid(String value, ConstraintValidatorContext arg1) { //using input from the userreturn value!=null && value.startsWith(MyConstraint.myMustValue());} The above code shows an example of a validator which validates that the value of the given string starts with a given character. The validator implements the ConstraintValidator interface. Notice that the constraint is given as input to the initialize() function. The value itself is input to the isValid() function Customizing error messages Each error has an error template. The error template is defined in the constraint annotation interface. This error template is later translated into an error message. The actual error message may be defined in 2 places: 1. Inside the constraint deceleration. The error message be defined when defining the constraint, whether it you are using XML or annotations. XML example: x is too small 2 Java example: public class MyBean{@Min(value = 2, message="x is too small")private String x;public String getX() {return x;}public void setX(String x) {this.x = x;} 2. Using a separate properties message. You may want to load a separate properties file containing the error messages according to the error template. loading the messages properties file is done using the validation factory configuration: Configuration config = Validation.byDefaultProvider().configure();// Using a properties file for customized error messagesFileInputStream in = new FileInputStream(new File("resources/messages.properties"));ResourceBundleMessageInterpolator messageInterpolator =new ResourceBundleMessageInterpolator( new PropertyResourceBundle(in));// Setting a messages properties fileconfig.messageInterpolator(messageInterpolator);in = new FileInputStream(new File("resources/demo-constraints.xml"));config.addMapping(in);// Building the customized factory (along with the changed configuration)ValidatorFactory factory = config.buildValidatorFactory();Validator validator = factory.getValidator(); Using groups There may be occasions when you will want to create a single constraint but with different values for different situations. For example, let’s say you want to create a username field and let him a minimum constraint. But, one time it will have minimum of 5 characters and another time it will have minimum of 6 characters. For cases like this you will want to use groups. To do so, you will have to create a group, create constraints for that group and last, validate objects by attaching the group. Please follow the steps below Create a group To create a group you simply create a new interface. example: public interface MyBeanGroup{} Create a constraint for the group XML example: com.mytest.groups.MyBeanGroup Annotations example: public class MyBean{@NotNull(groups = MyBeanGroup.class)private String x; public String getX() {return x;}public void setX(String x) {this.x = x;} Validate an object using the group Set> constraintViolations = validator.validate(bean, MyBeanGroup.class); The default group The default group is javax.validation.groups.Default. If you don’t assign a constraint any group it applies to the default group. If you are validating an object without using any group, it is validated as a part of the default group. Groups inheritance You can also create an group inheritance tree. In this way, if you validate an object using a group it will prefer constraints that are defined to it. But if there are no such constraints, then it will also take the constraints of it’s parents. Example, this is a group which inherits the default group: public interface MyBeanGroupextends javax.validation.groups.Default{} All the constraints that are defined for that group will apply to it. But also all the constraints which do not apply to any group(and by which apply to the default group), will also apply to it, since it exteds the default group. Jar dependency validation-api-1.0.0.GA.jar hibernate-validator-4.0.2.GA slf4j-api-1.4.2.jar slf4j-simple-1.4.2.jar log4j-1.2.15.jar Only for java5 jaxb-xjc-2.1.6.jar jaxb-impl-2.1.6.jar jaxb-api-2.1.jar activation-1.1.jar geronimo-stax-api_1.0_spec-1.0.1.jar References JSR 303 specification- Bean validation Product main page Hibernate Validator documentation Download demo project from http://www.aviyehuda.com/
April 15, 2010
by Avi Yehuda
· 134,340 Views
article thumbnail
Debugging Hibernate Generated SQL
In this article, I will explain how to debug Hibernate’s generated SQL so that unexpected query results be traced faster either to a faulty dataset or a bug in the query. There’s no need to present Hibernate anymore. Yet, for those who lived in a cave for the past years, let’s say that Hibernate is one of the two main ORM frameworks (the second one being TopLink) that dramatically ease database access in Java. One of Hibernate’s main goal is to lessen the amount of SQL you write, to the point that in many cases, you won’t even write one line. However, chances are that one day, Hibernate’s fetching mechanism won’t get you the result you expected and the problems will begin in earnest. From that point and before further investigation, you should determine which is true: either the initial dataset is wrong or the generated query is or both if you’re really unlucky Being able to quickly diagnose the real cause will gain you much time. In order to do this, the greatest step will be viewing the generated SQL: if you can execute it in the right query tool, you could then compare pure SQL results to Hibernate’s results and assert the true cause. There are two solutions for viewing the SQL. Show SQL The first solution is the simplest one. It is part of Hibernate’s configuration and is heavily documented. Just add the following line to your hibernate.cfg.xml file: ... true The previous snippet will likely show something like this in the log: select this_.PER_N_ID as PER1_0_0_, this_.PER_D_BIRTH_DATE as PER2_0_0_, this_.PER_T_FIRST_NAME as PER3_0_0_, this_.PER_T_LAST_NAME as PER4_0_0_ from T_PERSON this_ Not very readable but enough to copy/paste in your favourite query tool. The main drawback of this is that if the query has parameters, they will display as ? and won’t show their values, like in the following output: select this_.PER_N_ID as PER1_0_0_, this_.PER_D_BIRTH_DATE as PER2_0_0_, this_.PER_T_FIRST_NAME as PER3_0_0_, this_.PER_T_LAST_NAME as PER4_0_0_ from T_PERSON this_ where (this_.PER_D_BIRTH_DATE=? and this_.PER_T_FIRST_NAME=? and this_.PER_T_LAST_NAME=?) If they’re are too many parameters, you’re in for a world of pain and replacing each parameter with its value will take too much time. Yet, IMHO, this simple configuration should be enabled in all environments (save production), since it can easily be turned off. Proxy driver The second solution is more intrusive and involves a third party product but is way more powerful. It consists of putting a proxy driver between JDBC and the real driver so that all generated SQL will be logged. It is compatible with all ORM solutions that rely on the JDBC/driver architecture. P6Spy is a driver that does just that. Despite its age (the last release dates from 2003), it is not obsolete and server our purpose just fine. It consists of the proxy driver itself and a properties configuration file (spy.properties), that both should be present on the classpath. In order to leverage P6Spy feature, the only thing you have to do is to tell Hibernate to use a specific driver: com.p6spy.engine.spy.P6SpyDriver ... This is a minimal spy.properties: module.log=com.p6spy.engine.logging.P6LogFactory realdriver=org.hsqldb.jdbcDriver autoflush=true excludecategories=debug,info,batch,result appender=com.p6spy.engine.logging.appender.StdoutLogger Notice the realdriver parameter so that P6Spy knows where to redirect the calls. With just these, the above output becomes: 1270906515233|3|0|statement|select this_.PER_N_ID as PER1_0_0_, this_.PER_D_BIRTH_DATE as PER2_0_0_, this_.PER_T_FIRST_NAME as PER3_0_0_, this_.PER_T_LAST_NAME as PER4_0_0_ from T_PERSON this_ where (this_.PER_D_BIRTH_DATE=? and this_.PER_T_FIRST_NAME=? and this_.PER_T_LAST_NAME=?)|select this_.PER_N_ID as PER1_0_0_, this_.PER_D_BIRTH_DATE as PER2_0_0_, this_.PER_T_FIRST_NAME as PER3_0_0_, this_.PER_T_LAST_NAME as PER4_0_0_ from T_PERSON this_ where (this_.PER_D_BIRTH_DATE=’2010-04-10′ and this_.PER_T_FIRST_NAME=’Johnny’ and this_.PER_T_LAST_NAME=’Be Good’) Of course, the configuration can go further. For example, P6Spy knows how to redirect the logs to a file, or to Log4J (it currently misses a SLF4J adapter but anyone could code one easily). If you need to use P6Spy in an application server, the configuration should be done on the application server itself, at the datasource level. In that case, every single use of this datasource will be traced, be it from Hibernate, TopLink, iBatis or plain old JDBC. In Tomcat, for example, put spy.properties in common/classes and update the datasource configuration to use P6Spy driver. The source code for this article can be found here. To go further: P6Spy official site Log4jdbc, a Google Code contender that aims to offer the same features From http://blog.frankel.ch/debugging-hibernate-generated-sql
April 13, 2010
by Nicolas Fränkel
· 30,748 Views
article thumbnail
Prototype Pattern Tutorial with Java Examples
Learn the Prototype Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
April 9, 2010
by James Sugrue
· 90,830 Views · 14 Likes
article thumbnail
Template Method Pattern Tutorial with Java Examples
Learn the Template Method Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
April 6, 2010
by James Sugrue
· 150,511 Views · 11 Likes
article thumbnail
Command Pattern Tutorial with Java Examples
Learn the Command Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
April 2, 2010
by James Sugrue
· 312,185 Views · 21 Likes
article thumbnail
Complete List of Macro Keywords for the NetBeans Java Editor
In NetBeans IDE's Java editor, you can create macros by clicking the "Start Macro Recording" button, performing some actions you'd like to record, then clicking the "Stop Macro Recording" button. The Macro Editor then pops up and you can finetune the macro and also assign a keyboard shortcut to it. (You can also edit macros in the Options window, in the Editor | Macros tab.) A special macro syntax is used to define these macros. For example, if you want to clear the current line in the editor from the cursor, your macro definition would be as follows: selection-end-line remove-selection Then you could assign "Ctrl+L" as the keyboard shortcut for this macro. Whenever you'd then press that key combination, the whole line, from the position of the cursor, would be deleted. But the only way for the syntax to be useful is for it to be made publicly available. I've seen in various places on-line that people are complaining about a lack of documentation in this area. I asked the developers from the NetBeans Java editor team and their advice was: "it should not be that hard to create an action, which will get EditorKit from the JEditorPane in an opened editor, call EK.getActions() and dump Action.NAME property of each action to System.out". That's what I did (together with Action.SHORT_DESCRIPTION) and here is the result: abbrev-debug-line -- Debug Filename and Line Number adjust-caret-bottom -- Move Insertion Point to Bottom adjust-caret-center -- Move Insertion Point to Center adjust-caret-top -- Move Insertion Point to Top adjust-window-bottom -- Scroll Insertion Point to Bottom adjust-window-center -- Scroll Insertion Point to Center adjust-window-top -- Scroll Insertion Point to Top all-completion-show -- Show All Code Completion Popup annotations-cycling -- Annotations Cycling beep -- Beep build-popup-menu -- Build Popup Menu build-tool-tip -- Build Tool Tip caret-backward -- Insertion Point Backward caret-begin -- Insertion Point to Beginning of Document caret-begin-line -- Insertion Point to Beginning of Text on Line caret-begin-word -- Insertion Point to Beginning of Word caret-down -- Insertion Point Down caret-end -- Insertion Point to End of Document caret-end-line -- Insertion Point to End of Line caret-end-word -- Insertion Point to End of Word caret-forward -- Insertion Point Forward caret-line-first-column -- Insertion Point to Beginning of Line caret-next-word -- caret-next-word caret-previous-word -- caret-previous-word caret-up -- Insertion Point Up collapse-all-code-block-folds -- Collapse All Java Code collapse-all-folds -- Collapse All collapse-all-javadoc-folds -- Collapse All Javadoc collapse-fold -- Collapse Fold comment -- Comment complete-line -- Complete Line complete-line-newline -- Complete Line and Create New Line completion-show -- Show Code Completion Popup copy-selection-else-line-down -- Copy Selection else Line down copy-selection-else-line-up -- Copy Selection else Line up copy-to-clipboard -- Copy cut-to-clipboard -- Cut cut-to-line-begin -- Cut from Insertion Point to Line Begining cut-to-line-end -- Cut from Insertion Point to Line End default-typed -- Default Typed delete-next -- Delete Next Character delete-previous -- Delete Previous Character documentation-show -- Show Documentation Popup dump-view-hierarchy -- Dump View Hierarchy expand-all-code-block-folds -- Expand All Java Code expand-all-folds -- Expand All expand-all-javadoc-folds -- Expand All Javadoc expand-fold -- Expand Fold fast-import -- Fast Import find-next -- Find Next Occurrence find-previous -- Find Previous Occurrence find-selection -- Find Selection first-non-white -- Go to First Non-whitespace Char fix-imports -- Fix Imports format -- Format generate-code -- Insert Code generate-fold-popup -- Generate Fold Popup generate-goto-popup -- Generate Goto Popup generate-gutter-popup -- Margin goto -- Go to Line... goto-declaration -- Go to Declaration goto-help -- Go to Javadoc goto-implementation -- Go to Implementation goto-source -- Go to Source goto-super-implementation -- Go to Super Implementation in-place-refactoring -- Instant Rename incremental-search-backward -- Incremental Search Backward incremental-search-forward -- Incremental Search Forward insert-break -- Insert Newline insert-date-time -- Insert Current Date and Time insert-tab -- Insert Tab introduce-constant -- Introduce Constant... introduce-field -- Introduce Field... introduce-method -- Introduce Method... introduce-variable -- Introduce Variable... java-next-marked-occurrence -- Navigate to Next Occurrence java-prev-marked-occurrence -- Navigate to Previous Occurrence jump-list-last-edit -- Last edit jump-list-next -- Forward jump-list-prev -- Back last-non-white -- Go to Last Non-whitespace Char make-getter -- Replace Variable With its Getter make-is -- Replace Variable With its is* Method make-setter -- Replace Variable With its Setter match-brace -- Insertion Point to Matching Brace move-selection-else-line-down -- Move Selection else Line down move-selection-else-line-up -- Move Selection else Line up org.openide.actions.PopupAction -- Show Popup Menu page-down -- Page Down page-up -- Page Up paste-formated -- Paste Formatted paste-from-clipboard -- Paste redo -- Redo reindent-line -- Re-indent Current Line or Selection remove-line -- Delete Line remove-line-begin -- Delete Preceding Characters in Line remove-selection -- Delete Selection remove-tab -- Delete Tab remove-trailing-spaces -- Remove Trailing Spaces remove-word-next -- remove-word-next remove-word-previous -- remove-word-previous replace -- Replace run-macro -- Run Macro scroll-down -- Scroll Down scroll-up -- Scroll Up select-all -- Select All select-element-next -- Select Next Element select-element-previous -- Select Previous Element select-identifier -- Select Identifier select-line -- Select Line select-next-parameter -- Select Next Parameter select-word -- Select Word selection-backward -- Extend Selection Backward selection-begin -- Extend Selection to Beginning of Document selection-begin-line -- Extend Selection to Beginning of Text on Line selection-begin-word -- Extend Selection to Beginning of Word selection-down -- Extend Selection Down selection-end -- Extend Selection to End of Document selection-end-line -- Extend Selection to End of Line selection-end-word -- Extend Selection to End of Word selection-first-non-white -- Extend Selection to First Non-whitespace Char selection-forward -- Extend Selection Forward selection-last-non-white -- Extend Selection to Last Non-whitespace Char selection-line-first-column -- Extend Selection to Beginning of Line selection-match-brace -- Extend Selection to Matching Brace selection-next-word -- selection-next-word selection-page-down -- Extend Selection to Next Page selection-page-up -- Extend Selection to Previous Page selection-previous-word -- selection-previous-word selection-up -- Extend Selection Up shift-line-left -- Shift Line Left shift-line-right -- Shift Line Right split-line -- Split Line start-macro-recording -- Start Macro Recording start-new-line -- Start New Line stop-macro-recording -- Stop Macro Recording switch-case -- Switch Case to-lower-case -- To Lowercase to-upper-case -- To Uppercase toggle-case-identifier-begin -- Switch Capitalization of Identifier toggle-comment -- Toggle Comment toggle-highlight-search -- Toggle Highlight Search toggle-line-numbers -- Toggle Line Numbers toggle-non-printable-characters -- Toggle Non-printable Characters toggle-toolbar -- Toggle Toolbar toggle-typing-mode -- Toggle Typing Mode tooltip-show -- Show Code Completion Tip Popup uncomment -- Uncomment undo -- Undo word-match-next -- Next Matching Word word-match-prev -- Previous Matching Word Now that this list is public, I am looking forward to many new and interesting (and useful) macros being published (maybe even here on NetBeans Zone).
March 31, 2010
by Geertjan Wielenga
· 21,098 Views
article thumbnail
Chain of Responsibility Pattern Tutorial with Java Examples
Learn the Chain of Responsibility Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
March 30, 2010
by James Sugrue
· 161,717 Views · 4 Likes
article thumbnail
Unrolling Spock: Advanced @Unroll Usages in 0.4
Some of the Spock Framework 0.4 features are starting to see the light of day, with the Data Tables being explained last week in a nice blog post from Peter Niederwieser. One of the new features that I had not seen before is the new advanced @Unroll usage. Mixed with Data Tables, it produces some very cool results, and it can still be used with 0.3 style specs as well. Here's the juice: JUnit Integration and @Unroll Spock is built on JUnit, and has always had good IDE support without any effort from you as a user. For the most part, the IDEs just think Spock is another unit test. Here's the a Spock spec for the new Data Tables feature and how it shows up in an IDE. import spock.lang.* class TableTest extends Specification { def "maximum of two numbers"() { expect: Math.max(a, b) == c where: a | b | c 3 | 7 | 7 5 | 4 | 5 9 | 9 | 9 } } The assertion will be run 3 times: once for each row in the data table. And JUnit faithfully reports the method name correctly, even when the method names has a space in it: The problem with data driven tests and xUnit is poor error location. When a test fails you will receive an error stating which method is the culprit... but what if the method runs an assertion across 50 or 60 pieces of data? The cause of a failure is almost never clear with data driven tests. At it's worst you have to step through several iterations of code waiting for an exception. Good tests have a clear point of failure, but good tests also do not repeat themselves with boilerplate. This is exactly why Spock has the @Unroll annotation. As a test author you get to write one concise unit test, and JUnit does the work of reporting results that help you isolate failures. Consider the same test method with the @Unroll annotation and the accompanying IDE output. @Unroll def "maximum of two numbers"() { expect: Math.max(a, b) == c where: a | b | c 3 | 7 | 7 5 | 4 | 5 9 | 9 | 9 } When executed, JUnit sees three test methods instead of one: one for each row in the data table: The end result for you as a test writer is accurate failure resolution. You can pinpoint exactly which row failed. This feature is available in Spock 0.3 and you can use it today. What is new in 0.4 is the ability to change the test name dynamically. Here is a full @Unroll annotation that changes the method name: @Unroll("maximum of #a and #b is #c") def "maximum of two numbers"() { expect: Math.max(a, b) == c where: a | b | c 3 | 7 | 7 5 | 4 | 5 9 | 9 | 9 } Notice the #variable syntax in the annotation parameter. The # produces a sort of GString-like variable substitution that lets you bind columns from your data table into your test name. The annotation parameter references #a, #b, and #c, which aligns with the data table definition of a | b | c. Check out the IDE output: Previously, the test name was just the iteration number within the test. The new @Unroll parameter allows you to make the test name much more meaningful. Your tests will improve because failures become more descriptive. Unrolled failure messages before simply had the iteration name embedded in them, while now they can have meaningful data that you prescribe. My favorite part of playing with the new @Unroll was to see the default value of the parameter within the Spock source code: java.lang.String value() default "#featureName[#iterationCount]"; Talk about eating your own dog food... the default value is a test name template, just like you could have written in your own test. Makes you wonder what other variables are in scope, huh? Spock snapshot builds for 0.4 are available at: http://m2repo.spockframework.org. Get it before the link breaks. From http://hamletdarcy.blogspot.com
March 24, 2010
by Hamlet D'Arcy
· 36,213 Views · 1 Like
article thumbnail
Distance Calculation Using Latitude And Longitude In Java
private double distance(double lat1, double lon1, double lat2, double lon2, char unit) { double theta = lon1 - lon2; double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta)); dist = Math.acos(dist); dist = rad2deg(dist); dist = dist * 60 * 1.1515; if (unit == "K") { dist = dist * 1.609344; } else if (unit == "N") { dist = dist * 0.8684; } return (dist); } /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ /*:: This function converts decimal degrees to radians :*/ /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ private double deg2rad(double deg) { return (deg * Math.PI / 180.0); } /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ /*:: This function converts radians to decimal degrees :*/ /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ private double rad2deg(double rad) { return (rad * 180.0 / Math.PI); } system.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "M") + " Miles\n"); system.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "K") + " Kilometers\n"); system.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "N") + " Nautical Miles\n");
March 23, 2010
by Snippets Manager
· 50,629 Views · 1 Like
article thumbnail
Aspect Oriented Programming For Eclipse Plug-ins
It seems to me that Aspect Oriented Programming never really took off when it was introduced. However, it's a useful way to intercept, or analyse, methods as they happen, in an independent way. Eclipse has a useful suite of AspectJ tools that you can download for your Eclipse installlation. Paired with the benefits of Eclipse's plug-in system, aspects are a nice way of intercepting your RCP application. The following instructions show how to get up and running with aspects in the Plug-in Development Environment really quickly. Once you have downloaded the Eclipse AspectJ tools, you will also want to include the Equinox Aspect jars in your plug-ins directory. The plug-ins you will need are org.eclipse.equinox.weaving.aspectj and org.eclipse.equinox.weaving.hook Create a new OSGi plug-in: Right click on the project and choose AspectJ Tools/Convert to AspectJ Project Create a new package within the plugin eg. com.dzone.aspects.aspectTest Make a new aspectj Aspect within the package e.g. MyAspect In your manifest.mf export the package created in the previous step Export-Package: com.dzone.aspects A you write your AspectJ code, you will be advising another plug-in (for example org.eclipse.jdt.junit) You'll need to do some extra setup in order to advise other plug-ins, by adding the following to your Aspect plug-in manifest.mf. Eclipse-SupplementBundle: org.eclipse.jdt.junit Note you can only supplement one bundle in an aspect. Therefore, if you want to crosscut another bundle, you’ll need to create a new AspectJ plug-in. It also helps to add the plugin that you are advising (org.eclipse.jdt.junit) to your aspect plugin's dependencies. If you don't do it you will get lint warnings from the AspectJ compiler In your plugins META-INF directory make a file called aop.xml, consisting of content similar to the following When executing use the following VM arguments in your Run Configuration -Dosgi.framework.extensions=org.eclipse.equinox.weaving.hook -Dorg.aspectj.osgi.verbose=true It's as simple as that. Have you any instructions to add to this?
March 23, 2010
by James Sugrue
· 10,787 Views
article thumbnail
What's Happening in the Java World?
this morning at theserverside java symposium i attended james gosling's keynote . below are my notes from his talk. the unifying principle for java is the network - it ties everything together. enterprise, desktop, web, mobile, hpc, media and embedded. the most important thing in the java world is the acquisition of sun by oracle. james is showing a slide of duke in a fish tank with a "snorcle!" title above it. obligatory statistics for java: 15 million jre downloads/week (doesn't count tax season in brazil) 10 billion-ish java enabled devices (more devices than people) 1 billion-ish java enabled desktops 100 million-ish tv devices 2.6 billion-ish mobile devices 5.5 billion-ish smart cards 6.5 million professional java developers java has become "learn once, work anywhere". most college students worldwide have taken a java course in school. james' daughter is in college but isn't interested in java, mostly because her dad's name is all over the textbooks. java ee 6 was approved september 30, 2009. it was many years in the making; the result of large-scale community collaboration. it was built by hardware manufacturers, users, developers and academia. because of all the politics involved, many engineers had to become diplomats. most software engineers are from the wrong myers-brigg quadrant for this type of negotiation. needless to say, the process was interesting . new and updated apis in java ee 6: servlet 3.0, jax-rs 1.1, bean validation 1.0, di 1.0, cdi 1.0, managed beans 1.0, jaspic 1.1, ejb 3.1, jpa 2.0 and many others. also new is the web profile . it's the first java ee profile to be defined. it's a fully-functional, mid-size stack for modern web application development. it's complete, but not the kitchen sink. it's what most people use when building a modern web application in java. java ee 6 adds dependency injection with di (jsr-330) and cdi (jsr-299). @resource is still around, but an @inject annotation has been added for typesafe injection. it has automatic scope management (request, session, etc.) and is extensible via a beanmanager api. glassfish is the world's most downloaded app server (1 million-ish downloads/month). gfv2 was the ee 5 reference implementation. gfv3 is the reference implementation for ee 6. but it's not just a reference implementation, it's a benchmark-winning mission-critical large-scale app server. the fcs was released on december 10, 2009. goals of java ee: ease of use, right-sizing and extensibility. now roberto chinnici (ee 6 spec lead) and another guy are on stage showing a netbeans and glassfish demo. with servlet 3.0, you don't need a web.xml file, you just need a web-inf directory. there's a new @webservlet annotation that lets you specify a "urlpattern" value for the servlet-mapping. a new @ejb annotation allows you to easily inject ejbs into your servlet. roberto wired in an ejb, hit ctrl+s and refreshed his browser and it all worked immediately. in the background, netbeans and glassfish did the redeployment and initialized the ejb container in milliseconds. @managedbeans and @sessionscope and @named are all part of cdi. when using @named, the beans become available to jstl and you can access them using ${beanname.property}. interestingly, the cdi annotations are in difference packages: javax.annotation.managedbean and javax.enterprise.context.requestscoped. as david geary mentions , it's great to see the influence that ruby on rails has had on java ee. long demo of jee6 in netbeans. spent quite a bit of time extolling the virtues of hot deploy. thanks, ror! now roberto is showing us the admin console of glassfish and how modular it is. he's installing a jms module, but it's interesting to see that there's a ruby container installed by default. apache felix is the underlying osgi implementation used by glassfish. you can telnet into it and see the status of all the bundles installed. after installing the full-profile, roberto shows that you can restart the server from the console. isn't the whole point of osgi that you don't have to restart anything!? the glassfish management console is definitely impressive and visually appealing. apparently, it's extensible too, so you could easily write plugins to monitor your application and provide memory statistics. changing topics, one of the things that nice about java is its a two-level spec. the important thing in the java world isn't the language, it's the virtual machine. the magic is in the vm! scala, ruby/rails, groovy/grails, python, php, javascript, javafx and many others. in the same breath of talking about java.next languages, james mentioned javafx script. it's a new declarative scripting language for guis. it's similar to flash or silverlight, but it's much better because it has the java vm under it. at the current rate that we're going with cpus and cores, there's a good chance we'll have 5220 cores on our desktops by 2030. if you find the concurrency libraries scary, get over it. for the rest of talk, james talked about what he's hacking on these days. he's helping build an audi tts for the pikes peak road rally in colorado. the goal is to figure out a way to keep the vehicle above 130 mph for the whole race. sounds like a pretty cool project to me. i don't think there was a whole lot of new information covered in james' talk, but i really do like java ee 6's web profile. however, i think it's something most of the community has been using for many years with tomcat + spring + hibernate. now it's simply been standardized. if you happen to work at one of those companies that frowns on open source and smiles at standards, you've finally caught up with the rest of us. from http://raibledesigns.com/
March 18, 2010
by Matt Raible
· 19,488 Views · 1 Like
article thumbnail
Play! Framework Usability
Perhaps the most striking thing about about the Play! framework is that its biggest advantage over other Java web application development frameworks does not fit into a neat feature list, and is only apparent after you have used it to build something. That advantage is usability. Note that usability is separate from functionality. In what follows, I am not suggesting that you cannot do this in some other framework: I merely claim that it is easier and more pleasant in Play! I need to emphasise this because geeks often have a total blind spot for usability because they enjoying figuring out difficult things, and under-appreciate the value of things that Just Work. Written by web developers for web developers The first hint that something different is going on here is when you first hear that the Play! framework is 'written by web developers for web developers', an unconventional positioning that puts the web's principles and conventions first and Java's second. Specifically, this means that the Play! framework is more in line with the W3C's Architecture of the World Wide Web than it is with Java Enterprise Edition (Java EE) conventions. URLs for perfectionists For example, the Play! framework, like other modern web frameworks, provides first-class support for arbitrary 'clean' URLs, which has always been lacking from the Servlet API. It is no coincidence that at the time of writing, Struts URLs for perfectionists, a set of work-arounds for the Servlet API-based Struts 1.x web framework, remains the third-most popular out of 160 articles on www.lunatech-research.com despite being a 2005 article about a previous-generation Java web technology. In Servlet-based frameworks, the Servlet API does not provide useful URL-routing support; Servlet-based frameworks configure web.xml to forward all requests to a single controller Servlet, and then implement URL routing in the framework, with additional configuration. At this point, it does not matter whether the Servlet API was ever intended to solve the URL-routing problem and failed by not being powerful enough, or whether it was intended to be a lower-level API that you do not build web applications in directly. Either way, the result is the same: web frameworks add an additional layer on top of the Servlet API, itself a layer on top of HTTP. Play! combines the web framework, HTTP API and the HTTP server, which allows it to implement the same thing more directly with fewer layers and a single URL routing configuration. This configuration, like Groovy's and Cake PHP's, reflects the structure of an HTTP request - HTTP method, URL path, and then the mapping: # Play! 'routes' configuration file… # Method URL path Controller GET / Application.index GET /about Application.about POST /item Item.addItem GET /item/{id} Item.getItem GET /item/{id}.pdf Item.getItemPdf In this example, there is more than one controller. We also see the use of an id URL parameter in the last two URLs. HttpServletRequest Another example is Play!'s Http.Request class, which is a far simpler than the Servlet API's HttpServletRequest interface. In addition, Play! uses a class where Java EE 6 uses the Java EE convention of using an interface. This interface is also split between HttpServletRequest and the more generic ServletRequest interface. This separation may be useful if you want to use Servlets for things other than web applications, or if you want to allow for the unlikely possibility of the web changing protocol, but for most of us it is merely irrelevant complexity. In other words, the Servlet API is always used with a framework on top these days because it is sub-optimised for building web applications, which is what all of us actually use it for. Play! fixes that. Better usability is not just for normal people Another way of looking at the idea that Play! is by and for web developers is to consider how a web developer might approach software design differently to a Java EE developer. When you write software, what is the primary interface? If you are a web developer, the primary interface is a web-based user-interface constructed with HTML, CSS and (increasingly) JavaScript. A Java EE developer, on the other hand, may consider their primary interface to be a Java API, or perhaps a web services API, for use by other layers in the system. This difference is a big deal, because a Java interface is intended for use by other programmers, while a web user-interface interface is intended for use by non-programmers. In both cases, good design includes usability, but usability for normal people is not the same as usability for programmers. In a way, usability for everyone is a higher standard than usability for programmers, when it comes to software, because programmers can cope better with poor usability. This is a bit like the Good Grips kitchen utensils: although they were originally designed to have better usability for elderly people with arthritis, it turns out that making tools easier to hold is better for all users. The Play! framework is different because the usability that you want to achieve in your web application is present in the framework itself. For example, the web interface to things like the framework documentation and error messages shown in the browser is just more usable. Along similar lines, the server's console output avoids the pages full of irrelevant logging and pages of stack traces when there is an error, leaving more focused and more usable information for the web developer. $ play run phase ~ _ _ ~ _ __ | | __ _ _ _| | ~ | '_ \| |/ _' | || |_| ~ | __/|_|\____|\__ (_) ~ |_| |__/ ~ ~ play! 1.0, http://www.playframework.org ~ ~ Ctrl+C to stop ~ Listening for transport dt_socket at address: 8000 10:15:58,629 INFO ~ Starting /Users/peter/Documents/work/workspace/phase 10:16:00,007 WARN ~ You're running Play! in DEV mode 10:16:00,424 INFO ~ Listening for HTTP on port 9000 (Waiting a first request to start) ... 10:16:11,847 INFO ~ Connected to jdbc:hsqldb:mem:playembed 10:16:13,448 INFO ~ Application 'phase' is now started ! 10:16:14,825 INFO ~ starting DispatcherThread 10:16:48,168 ERROR ~ @61lagcl6i Internal Server Error (500) for request GET /application/startprocess?account=x Java exception (In /app/controllers/Application.java around line 41) IllegalArgumentException occured : Person not found for account x play.exceptions.JavaExecutionException: Person not found for account x at play.mvc.ActionInvoker.invoke(ActionInvoker.java:200) at Invocation.HTTP Request(Play!) Caused by: java.lang.IllegalArgumentException: Person not found for account x at controllers.Application.startProcess(Application.java:41) at play.utils.Java.invokeStatic(Java.java:129) at play.mvc.ActionInvoker.invoke(ActionInvoker.java:127) ... 1 more Try to imagine a JSF web application producing a stack trace this short. In fact, Play! goes further: instead of showing the stack trace, the web application shows the last line of code within the application that appears in the stack trace. After all, what you really want to know is where things first went wrong in your own code. This kind of usability does not happen by itself; the Play! framework goes to considerable effort to filter out duplicate and irrelevant information, and focus on what is essential. Quality is in the details In the Play! framework, much of the quality turns out to be in the details: they may be small things individually, rather than big important features, but they add up to result in a more comfortable and more productive development experience. The warm feeling you get when building something with Play! is the absence of the frustration that usually results from fighting the framework. We recommend that you go to http://www.playframework.org/, download the latest binary release, and spend half an hour on the tutorial. Peter Hilton is a senior software developer at Lunatech Research.
March 16, 2010
by $$anonymous$$
· 24,648 Views
article thumbnail
Decorator Pattern Tutorial with Java Examples
Learn the Decorator Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
March 15, 2010
by James Sugrue
· 141,517 Views · 5 Likes
article thumbnail
Proxy Pattern Tutorial with Java Examples
Learn the Proxy Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
March 12, 2010
by James Sugrue
· 158,967 Views · 13 Likes
  • Previous
  • ...
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • ...
  • 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
×