JAVA How to JAVA Development tutorials and how to

24Aug/101

JavaZone Java 4-ever trailer

I readed a little bit about JavaZone that will be in September's 8-9th, but some days ago a friend shared me the link to "official" trailer of JavaZone, about a movie called "Java 4-Ever" that's so funny XD . Check the video ;) .



Source: http://jz10.java.no/java-4-ever-trailer.html

Tagged as: , 1 Comment
20Jul/100

How to set ARITHABORT from JAVA – SQL Server

I had a problem yesterday. I was developing a RESTful web service where i have to run an UPDATE to SQL Server 2005 table, but when i do that i have the next problem:

UPDATE failed because the following SET options have incorrect settings: 'ARIHABORT'

Damn! What the hell is that? Googling i found this:

http://j2eeframeworks.blogspot.com/2008/10/insert-failed-because-following-set.html

And i understood that the table that i want to update is related to indexed views so the UPDATE or INSERT proccess isn't as simple because i had to set the parameter ARIHABORT = ON to do my operations.

So, how to do that?

25Jun/100

How to validate through annotations: Struts 2

Struts 2 validation - JAVA How to

Hi to all. I've studied some stuff about struts 2 those days so i've learn a lot of new things like this post topic. Normally, what do you do when you want to implement a basic validation on Struts 2? The steps about how to do that are:

  • Assure that you're using defaultStack interceptor stack because inside it are workflow and validation interceptors that are responsible of execute validation logic and redirect to appropiate result when validation triggers.
  • Define a result named "input" in action's declaration on struts.xml . This is the result where validation must redirect automatically if exists validation errors. If input result is not defined it will give an error of result not found.
  • Override validate() method on your action.
  • Write your own validation logic inside it, that must add error messages when it fails to properly validation mechanism. For example, if i validate that a field must be a number and greater than 1000, if it doesn't pass the validation it must add a error message using addActionError() or addFieldError() (To follow standards you should use addFieldError() ), like this:
    if (fieldOne == null || fieldOne.equals("")) {
     addFieldError("fieldOne", "Field one must not be empty.");
     }
     if (fieldTwo == null || Integer.valueOf(fieldTwo) < 30) {
     addFieldError("fieldTwo", "Field two must be greater or equal than 30.");
     }
  • (Optional) in your jsp you can define <s:fielderror> or <s:actionerror> tags to print your validation messages. As you can guess, <s:fielderror> prints validation errors added with addFieldError() and <s:actionerror> to print action error messages added with addActionError(). To print validation errors from fieldOne and fieldTwo you have to define <s:fielderror> like this:
    <s:fielderror cssClass="cssClassForUllistwithLi" >
     <s:param>fieldOne</s:param>
     <s:param>fieldTwo</s:param>
     </s:fielderror>
  • Run your app :P

This is the basic way. But if you want to validate through annotations is easier and faster, you have to do this:

4Jun/103

How to avoid validation on Action call – Struts 2

As you know, like Struts 1, Struts 2 allow us to define server side validations when you call an action. This is very useful because sometimes javascript client side validation is not enought when we want to validate input entries against data from DB or do complex validations.

How to define validations in JAVA Struts 2? First your action must extend ActionSupport class, and override it's method validate that has te following signature:

public void validate() {}

Inside validate() you define your validations and, if you add messages to ActionErrors or FieldErrors, Struts 2 automatically detects that it must redirect to input result defined in action's declaration in struts.xml, like this:

 <action name="login">
            <interceptor-ref name="defaultStack" />

            <result name="homePage">/login/login.jsp</result>
            <result name="input">/login/login.jsp</result>
...
            <result name="backToLoginPer">/login/login.jsp</result>
        </action>

The problem is that sometimes you want that validation applies only on certain action calls, that is, avoid validation on certain action calls. How to do this?

2May/100

JAVA Singleton Pattern

Singleton Pattern - JAVA How to

Hello again, after 3 weeks of posts absense, i'm back 8-) . Back with JAVA design patterns stuff, this time about How to apply Singleton Pattern, basically a pattern that allows you to restrict to instantiate more than one instance of a class in your application. The requirements that you satisfy with Singleton Pattern are:

  • Only one instance of a class per application
  • If you try to instantiate a second object from singleton class, you'll get the original instance

I decided to write about it because i had a requirement in a project where i'm working right now that involves to handle an object to mantain the user state and other data in a single object, without possibility of instantiate another one and access easily to current object, so i decided to implement the pattern. First, you need to restrict the constructor of the class to avoid to instantiate object in the usual way so we have to declare the constructor as private. next you have to declare a method that, if an object isn't created yet, instantiate a new object and returns it, or, if object is already created, return a reference to that object...

4Mar/100

How to solve “cannot find javac” with JAVA SDK App Engine

Google App Engine Logo - JAVA How to

Recently i decided to try Google App Engine, a service where you can host your applications built in different languages like JAVA, Ruby, Python and so on, using Google's infraestructure. Now is enough for me because i see that you can get this for free:

  • 500MB storage
  • Enough CPU and bandwidth to serve your applications to 5 million visits per month

So i want to test what kind of JAVA technologies it supports (I don't know, Struts2, Spring, Hibernate JPA) . The proccess to join this is very simple, the steps are the next:

3Mar/100

How to save JAVA Exception printStackTrace on String

Probably you've used sometines the Exception object in try/catch block to print the exception stack trace that help us to find where the line of code where the exception is thrown, but more than once i wanted to get that stack trace in some String variable for example, maybe to save in some auditory table or something like that. I read a little bit about the method getStackTrace but really it doesn't give me the full stack trace.

Well, to do that, first you have to understand that when you call ex.printStackTrace() you print a characters stream on screen, so the way to get that characters stream is using the overloaded version of printStackTrace(PrintWriter objWriter) that receives a PrintWriter object to transfer that characters stream to the PrintWriter object, then you can use that writer to "write" it's stream on something like a file or a simple String.

Check this sample code:

import java.io.File;
import java.io.IOException;
class MyClass {
	public static void main(String[] arguments)
	{
		try
		{
			(new MyClass()).readInexistentFile();
		}
		catch(IOException ex)
		{
			//Catch the stack trace?
		}
	}

	public void readInexistentFile() throws IOException
	{
		File myFile = new File("hi6.txt");
			FileReader myReader = new FileReader(myFile);
			myReader.read();
	}
}

...

1Mar/100

How to sort JAVA collection elements (part 2)

JAVA List Comparator ordering - JAVA How to
Continuing with "How to sort JAVA collection elements", i want to share with you another way to sort collections that have it's differences to the first way (using Comparable interface) and enables you to have different sort options, i'm talking about use the Comparator interface.

class Employee implements Comparable<Employee> {
	private String completeName;
	private int age;
	private boolean sex;
	private String position;

	public Employee(String completeName, int age, boolean sex, String position) {
			setCompleteName(completeName);
			setAge(age);
			setSex(sex);
			setPosition(position);
	}

	@Override
	public String toString()
	{
		return getCompleteName() + ", " + getAge() + " years, " +
				(isSex()?"male, ":"female, ") + getPosition();
	}

	public String getCompleteName() {
		return completeName;
	}

	public void setCompleteName(String completeName) {
		this.completeName = completeName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public boolean isSex() {
		return sex;
	}

	public void setSex(boolean sex) {
		this.sex = sex;
	}

	public String getPosition() {
		return position;
	}

	public void setPosition(String position) {
		this.position = position;
	}

	public int compareTo(Employee o) {
		return getCompleteName().compareTo(o.getCompleteName());
	}
}

Wait... Comparable and Comparator? Yes, you read well. The comparator interface is slightly similar to comparable, because it defines a method called compare() that works like compareTo() of Comparable interface, but it has the difference that you don't need to implement Comparator in the collection's class type. To explain that a little bit well, i'm going to resume the example of the last post. I have my Employee class implementing Comparable interface and it's method compareTo() that orders in ascending order based on completeName field (if you haven't read the first post you can download the sample code >>HERE<<).

Now, additional to it, i wan to have the option of order an Employee list based on age field descending or position ascending. How to do that in JAVA?? Continue reading :D

24Feb/100

How to sort JAVA collection elements

JAVA List ordering - JAVA How to

Probably you've worked with List in a moment of your JAVA developer life, and we can say that using a List instead an array is more beautiful because the list grows automatically, you can add elements easily (only objects, but if you want to add primitives use wrapper classes) and so on. But, How to sort the elements of a list?

Suppose that you have a list of employees. Those employees have the next data:

 complete name
 age
 sex
 position

So, you have your JAVA bean Employeee, like this: (Continue reading the post)

18Feb/104

Dynamic mime type on stream result – Struts 2

Hi to all. A reader (Staci) asks about how to dinamically define the mime type of stream result type on Struts 2, for example define that the stream result will serve a pdf file or excel file. Well, as i see, that can bea achieved in 2 ways:

  • Defining a stream result for each mime type that you want to return in the struts.xml
  • Using wildcards to define the mime type and file extension in struts.xml
  • Using parameters on struts.xml

Both options are viable, but the first extendes more and more the more kind of mime types that you want to support, because you have to define a result for each mime type and then send a parameter or something like that to define the result that you want to get.

But i'm going to write about the second and third options. First: Using wildcards. FIrst, imagine that you have a simple html to call the action method that gives us a file:

<html>
 <head>
 <title>Name Collector</title>
 </head>
 <body>
 <a href="/demoStruts2/pdf_pdf_WildCardRaw!giveMeMyFile.action">Get PDF file</a><br />
 <a href="/demoStruts2/vnd.ms-excel_xls_WildCardRaw!giveMeMyFile.action">Get XLS file</a>
 </body>
</html>