This is a very simple card memory game I wrote for Android platform.
I’ve attached it complete with source code and resources.
Enjoy.


zip  Download Game

zip  Download Source code


Screen shots:





 

HtmlUnit – A quick introduction

On 16/05/2010, in HtmlUnit, by admin
  • HtmlUnit is an open source java library for creating HTTP calls which imitate the browser functionality.
  • HtmlUnit is mostly used for integration testing upon Unit test frameworks such as JUnit or TestNG. This is done by requesting web pages and asserting the results.


Simple Example


@Test
public void testGoogle(){
	WebClient webClient = new WebClient();
	HtmlPage currentPage = webClient.getPage("http://www.google.com/");
	assertEquals("Google", currentPage.getTitleText());
}


WebClient


  • As you can see in the example, the WebClient is the starting point. It is the browser simulator.
  • WebClient.getPage() is just like typing an address in the browser. It returns an HtmlPage object.


HtmlPage


  • HtmlPage represents a single web page along with all of it’s client’s data (HTML, JavaScript, CSS …).
  • The HtmlPage lets you access to many of a web page content:


Page source

  • You can receive the page source as text or as XML.
HtmlPage currentPage =
		webClient.getPage("http://www.google.com/");
String textSource = currentPage.asText();
String xmlSource = currentPage.asXml();


HTML Elements

  • HtmlPage lets you ability to access any of the page HTML elements and all of their attributes and sub elements. This includes tables, images, input fields, divs or any other Html element you may imagine.
  • Use the function getHtmlElementById() to get any of the page elements.
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
HtmlImage imgElement = (HtmlImage)currentPage.getHtmlElementById("logo");
System.out.println(imgElement.getAttribute("src"));


Anchors

  • Anchor is the representation of the Html tag <a href=”…” >link</a>.
  • Use the functions getAnchorByName(), getAnchorByHref() and getAnchorByText() to easily access any of the anchors in the page.
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
HtmlAnchor advancedSearchAn =
		currentPage.getAnchorByText("Advanced Search");
currentPage = advancedSearchAn.click();
assertEquals("Google Advanced Search",currentPage.getTitleText());


Dom elements by XPath

  • You can access any of the page elements by using XPath.
WebClient webClient = new WebClient();
HtmlPage currentPage =
	webClient.getPage("http://www.google.com/search?q=avi");

//Using XPath to get the first result in Google query
HtmlElement element = (HtmlElement)currentPage.getByXPath("//h3").get(0);
DomNode result = element.getChildNodes().get(0);


Form control

  • A large part of controlling your HTML page is to control the form elements:

    • HtmlForm
    • HtmlTextInput
    • HtmlSubmitInput
    • HtmlCheckBoxInput
    • HtmlHiddenInput
    • HtmlPasswordInput
    • HtmlRadioButtonInput
    • HtmlFileInput
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");

//Get the query input text
HtmlInput queryInput = currentPage.getElementByName("q");
queryInput.setValueAttribute("aviyehuda");

//Submit the form by pressing the submit button
HtmlSubmitInput submitBtn = currentPage.getElementByName("btnG");
currentPage = submitBtn.click();


Tables

currentPage = webClient.getPage("http://www.google.com/search?q=htmlunit");
final HtmlTable table = currentPage.getHtmlElementById("nav");
for (final HtmlTableRow row : table.getRows()) {
System.out.println("Found row");
    for (final HtmlTableCell cell : row.getCells()) {
       System.out.println("   Found cell: " + cell.asText());
    }
}


JavaScript support


  • HtmlUnit uses the Mozilla Rhino JavaScript engine.
  • This lets you the ability to run pages with JavaScript or even run JavaScript code by command.
ScriptResult result = currentPage.executeJavaScript(JavaScriptCode);
  • By default JavaScript exceptions will crash your tests. If you wish to ignore JavaScript exceptions use this:
webClient().setThrowExceptionOnScriptError(false);
  • If you would like to turn off the JavaScript all together, use this:
currentPage.getWebClient().setJavaScriptEnabled(false);


HTTP elements



URL

WebClient webClient = new WebClient();
HtmlPage currentPage =
	webClient.getPage("http://www.google.co.uk/search?q=htmlunit");
URL url = currentPage.getWebResponse().getRequestSettings().getUrl()


Response status

WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
assertEquals(200,currentPage.getWebResponse().getStatusCode());
assertEquals("OK",currentPage.getWebResponse().getStatusMessage());


Cookies

Set<Cookie> cookies = webClient.getCookieManager().getCookies();
for (Cookie cookie : cookies) {
	System.out.println(cookie.getName() + " = " + cookie.getValue());
}


Response headers

WebClient webClient = new WebClient();
HtmlPage currentPage =
	webClient.getPage("http://www.google.com/search?q=htmlunit");

List<NameValuePair> headers =
	currentPage.getWebResponse().getResponseHeaders();
for (NameValuePair header : headers) {
	System.out.println(header.getName() + " = " + header.getValue());
}


Request parameters

List<NameValuePair> parameters =
	currentPage.getWebResponse().getRequestSettings().getRequestParameters();
for (NameValuePair parameter : parameters) {
	System.out.println(parameter.getName() + " = " + parameter.getValue());
}


Making assertions


  • HtmlUnit comes with a set of assetions:
   assertTitleEquals(HtmlPage, String)
   assertTitleContains(HtmlPage, String)
   assertTitleMatches(HtmlPage, String)
   assertElementPresent(HtmlPage, String)
   assertElementPresentByXPath(HtmlPage, String)
   assertElementNotPresent(HtmlPage, String)
   assertElementNotPresentByXPath(HtmlPage, String)
   assertTextPresent(HtmlPage, String)
   assertTextPresentInElement(HtmlPage, String, String)
   assertTextNotPresent(HtmlPage, String)
   assertTextNotPresentInElement(HtmlPage, String, String)
   assertLinkPresent(HtmlPage, String)
   assertLinkNotPresent(HtmlPage, String)
   assertLinkPresentWithText(HtmlPage, String)
   assertLinkNotPresentWithText(HtmlPage, String)
   assertFormPresent(HtmlPage, String)
   assertFormNotPresent(HtmlPage, String)
   assertInputPresent(HtmlPage, String)
   assertInputNotPresent(HtmlPage, String)
   assertInputContainsValue(HtmlPage, String, String)
   assertInputDoesNotContainValue(HtmlPage, String, String)


  • You can still of course use the framework’s assertions. For example, if you are using JUnit, you can still use assertTrue() and so on.
  • Here are a few examples:
WebClient webClient = new WebClient();
HtmlPage currentPage =
      webClient.getPage("http://www.google.com/search?q=htmlunit");

assertEquals(200,currentPage.getWebResponse().getStatusCode());
assertEquals("OK",currentPage.getWebResponse().getStatusMessage());
WebAssert.assertTextPresent(currentPage, "htmlunit");
WebAssert.assertTitleContains(currentPage, "htmlunit");
WebAssert.assertLinkPresentWithText(currentPage, "Advanced search");
assertTrue(currentPage.getByXPath("//h3").size()>0); //result number
assertNotNull(webClient.getCookieManager().getCookie("NID"));


See also



 Download example

Tagged with:
 

Freeware for generating UMLs

On 29/04/2010, in software, by admin

I was looking for a simple freeware for generating UMLs and class diagrams spesifclly.

Here is some of the better ones I have found:



ArgoUML

open source UML modeling tool.



StarUml

Another cool open source UML modeling tool.



hierarchy

A freeware by white magic software.



AmaterasUML

AmaterasUML is an Eclipse plug-in for drawing UML class-diagram, and UML sequence-diagram.



ObjectAid

The ObjectAid UML Explorer is a UML plugin for Eclipse. It provides a graphical view on your Java source code.



Umlet

UMLet is an open-source UML tool with a simple user interface



fujaba



NetBeans

Of course NetBeans itself comes with a very good UML tool built in.

 

Recently I had to choose a validation framework or write one by my own. First I thought, no big deal, validation is not that a complicated issue.
But the more you think of it, the more you come to the conclusion it is not as shallow as you think – you need to validate different types, you have different groups and much more issues… In short, writing a validation framework by yourself demands a lot of work.

Luckily, JSR 303 comes to solve exactly that and the hibernate implementation of this 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 a 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 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:
<constraint-mappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd"
                     xmlns="http://jboss.org/xml/ns/javax/validation/mapping">
    <default-package>com.mytest</default-package>
    <bean class="MyBean"  >
        <field name="x"  >
            <constraint annotation="javax.validation.constraints.NotNull"/>
        </field>
        <field name="y"  >
            <constraint annotation="javax.validation.constraints.Min">
                  <element name="value">2</element>
            </constraint>
        </field>
      </bean>
</constraint-mappings>
  • 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 “<default-package>”. 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{
	@NotNull
	String 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:
<constraint-mappings
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd"
    xmlns="http://jboss.org/xml/ns/javax/validation/mapping">
    <default-package>com.mytest.beans</default-package>

    <!--  ignore-annotations default is true. After changing to 'false',
                      by default, annotations will be stronger -->
    <bean class="MyBean" ignore-annotations="false"    > 

         <field name="x1"  > <!-- ignore-annotations default is false,
                                                      annotation is stronger -->
            <constraint annotation="javax.validation.constraints.Min">
                 <element name="value">2</element>
            </constraint>
        </field>
         <field name="x2"  ignore-annotations="true"    >  <!-- XML is stronger -->
            <constraint annotation="javax.validation.constraints.Min">
                 <element name="value">2</element>
            </constraint>
        </field>
    </bean>
 

  • 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 constrains

  • 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:
<constraint-mappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd"
                     xmlns="http://jboss.org/xml/ns/javax/validation/mapping">
    <default-package>com.mytest.beans</default-package>

    <bean class="MyBean" ignore-annotations="false"    >
         <field name="innerBean">
           <valid/>   <!-- validation for an inner object -->
        </field>
      </bean>

    <bean class="InnerBean" ignore-annotations="false">
        <field name="xx">
            <constraint annotation="javax.validation.constraints.NotNull"/>
        </field>
    </bean>

</constraint-mappings>
  • Annotation example:
public class MyBean{

	@Valid  //inner bean to be validated separately
	private InnerBean innerBean; 

	public InnerBean getInnerBean() {
		return innerBean;
	}

	public void setInnerBean(InnerBean innerBean) {
		this.innerBean = innerBean;
	}

}

public class InnerBean {

        @NotNull
	String 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<ConstraintViolation<MyBean>> 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<ConstraintViolation<MyBean>> constraintViolations =
               validator.validate(bean);

//printing the results
for (ConstraintViolation<MyBean> 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)
@Documented
public @interface MyConstraint{

	// These next parameters exist in every constraint
	String message() default "{com.mytest.MyConstraint.message}";
	Class<?>[] groups() default {};
	Class<? extends Payload>[] payload() default {};

	// These next parameters are added
	// They are the constraint's attributes
	String myOptionalValue() default ""; //this parameter has a default value
	String 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
@NotNull
public @interface MyConstraint{
	String message() default "{com.mytest.MyConstraint.message}";
	Class<?>[] groups() default {};
	Class<? extends Payload>[] payload() default {};
}
  • In the example, notice the @NotNull annotation.



Creating the validator class

  • Here is an example of a simple validator:
public class MyValidator
implements ConstraintValidator<MyConstraint, String> {

	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 user
		return 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:

<bean class="MyBean" ignore-annotations="false"    >
        <field name="x"  ignore-annotations="true"    >
            <constraint annotation="javax.validation.constraints.Min">
                <message>x is too small</message> <!-- message can appear inside the XML -->
                 <element name="value">2</element>
            </constraint>
        </field>
    </bean>

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 messages
FileInputStream in =
          new FileInputStream(new File("resources/messages.properties"));

ResourceBundleMessageInterpolator messageInterpolator =
			new ResourceBundleMessageInterpolator(
                                                  new PropertyResourceBundle(in));

// Setting a messages properties file
config.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 bellow



1. Create a group

  • To create a group you simply create a new interface.

example:

public interface MyBeanGroup{
}



2. Create a constraint for the group

  • XML example:
<bean class="MyBean" ignore-annotations="false"    >
        <field name="x"  >
            <constraint annotation="javax.validation.constraints.NotNull">
            	<groups><value>com.mytest.groups.MyBeanGroup</value></groups>
            </constraint>
        </field>
 </bean>
  • 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;
	}
}



3. Validate an object using the group

Set<ConstraintViolation<MyBean>> 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 MyBeanGroup
extends javax.validation.groups.Default{

}
  • All the constraint that are defined for that group will apply to it.
  • But also all the constraint which are 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


 Download demo project

  • EasyImage lets you do all the basic image operations – converting, cropping, resizing, rotating, flipping…
  • Plus it let’s you do some really cool affects.
  • All is done super easily.
  • Combining operations can produce some very cool results.



  • Download

    JavaDoc
    Click here to see full java doc.

    Operations

    • Open image.
    • Save image
    • Convert image
    • Re-size image
    • Crop image
    • Convert to black and white image
    • Rotate image
    • Flip image
    • Add color to image
    • Create image with multiple instance of the original
    • Combining 2 images together
    • Emphasize parts of the image
    • Affine transform image

    Examples

    Combining 2 pictures

    Image image  = new Image("c:/pics/p1.jpg");
    image.combineWithPicture("c:/pics/p2.jpg");
    image.saveAs("c:/pics/p1combinedWithp2.jpg");
    



    Emphasizing parts of the image

            Image image  = new Image("c:/pics/p1.jpg");
            image.emphasize(250, 200, 2300, 500);
            image.saveAs("c:/pics/p1Emphesized.jpg");
    



    Affine transform + combine

            Image image  = new Image("c:/pics/p1.jpg");
            Image image2  = new Image("c:/pics/p2.jpg");
            image.affineTransform(0.5, 0.0);
            image2.affineTransform(-0.5, 0.0);
            image2.combineWithPicture(image,Color.black);
            image2.saveAs("c:/pics/affineTransformAndCombine.jpg");
    




    Add color to image

            Image image  = new Image("c:/pics/p1.jpg");
            image.addColorToImage(Color.red, 5);
            image.saveAs("c:/pics/addColorToImage.jpg");
    




    Add to pixel color

            Image image  = new Image("c:/pics/y2.jpg");
            image.addPixelColor(111111);
            image.resize(40);
            image.crop(100, 0, -1, -1);
            image.saveAs("c:/pics/addPixelColor.jpg");
    




    Image resizing + multiplying with pixel color enhancement

            Image image  = new Image("c:/pics/p1.jpg");
            image.resize(10);
            image.multiply(5, 5, 11111);
            image.saveAs("c:/pics/multiply+color.jpg");
    




    Combine image with image without background

            Image image  = new Image("c:/pics/heart.gif");
            image.multiply(20, 20);
            Image image2  = new Image("c:/pics/p6.jpg");
            image2.crop(400, 0, -1, -1);
            image2.combineWithPicture(image,3,Color.white);
            image2.saveAs("c:/pics/combineWithPictureWithoutBackground.jpg");
    




    Emphasize trick

    Image image  = new Image("c:/pics/p1.jpg");
            int width = image.getWidth();
            int height = image.getHeight();
            for(int i=0,c=0;i<height;c++,i+=50){
                int x = width/2  - i;
                int y = height/2 - i;
    
                image.emphasize(x, y, width-1-x, height-1-y,
                            Color.BLACK, 12 - c/4);
            }
            image.saveAs("c:/pics/emphesizeTrick.jpg");
    

Tagged with:
 

HTML image maker

On 13/02/2010, in Image Manipulation, projects, by admin

From time to time I like to make small projects that are good for nothing. This weekend I have created a small project that I call “HTML image maker”.


Description

  • It’s purpose is to take existing images and to generate HTML table where each pixel is replaced by a table cell.
  • It is also possible to insert text inside the cells where the color of the cell is at the background of the text or in the foreground.
  • If you won’t insert input image than the program will simply create a screen shot image instead.


Used technologies

  • The image manipulation is done using java’s ImageIO object.
  • The user interface was built using Apache Pivot.


Screen shots

Click to enlarge.









Downloads

download Download the software

download Download the sources (eclipse project)


Instructions

  • No need to install.
  • To start the program execute Html image maker.bat.
  • Optional – Insert input image path. If you won’t insert input image than the image will be generated from the screen shot.
  • Insert an output path for the Html file.
  • Optional – You can enter text to be inserted inside the image. Select foreground if you would like to color the text itself instead of the background.
  • Press ‘Generate HTML image’.


Warning

  • This software consumes a lot of memory. You should use it on not so big images.
Tagged with:
 

Getting ready for job interviews

On 06/02/2010, in Job searching, by admin

Searching for a job can be a rather discouraging experience. In a few occasions in the past I found myself looking for a job as a java developer. During these occasions I have managed to gather a few principles that have helped me along the way. Perhaps you will find them useful.

Who is this post for?
Even though this post is mainly for java developers, there is no reason why other kinds of developers won’t benefit from it as well.

This post is obviously not for developers with 10+ years experience, it is for the lesser experienced.

Why even prepar for an interview?
Many would say that you don’t need special training for interviews, but rather show what you really know in the interview so you will get the job that is right for you.
There is much truth in that, but I still think there is much that can be done in order to improve your chances in finding a job, and not just any job – the right job for you. I do not suggest you lie in your interview, quite the opposite, you need to show your real self. For some people it comes naturally but others (like me) need to practice to be able to display that. At first, whenever I went to a job interview I said the things the interviewer would want to hear and even though it sometimes worked and I did got the job, these weren’t necessarily the right jobs for me.
More over, I feel that the periods in which I searched for a job have actually made me a better developer. Job hunting pushed me to study new stuff and made me understand the companies perspectives and the common technologies that are being used. There is no reason not to use the motivation job hunting gives you to improve.

An interview structure
Even though software development interviews may differ, you can still find a clear distinction between different parts of the interview.

  • Tell about yourself and your experiences
  • General riddles
  • Java riddles and syntax
  • Specific technologies questions
  • Java short design questions
  • General Design questions – classes design and DB design

Probably most interviews will not include all of these parts, but surely most of them.



Tell about yourself, your current job and your experiences
This is the part I probably hate the most. It always makes me uncomfortable talking about myself as if I am trying to sell something. But there is nothing much to do about it, it is important.

Don’t get me wrong, the professional parts of the interview are no doubt more important, but still, this part may be the one extra point you need to be chosen over another guy.

Advice:

  • Never ever trash your current or past employers. Your interviewer may assume that you are a difficult person.
  • I have found that many of the interviewers love the fact that I have other interests besides programming. I guess a part of being a good programmer is to be curious, and that can be acknowledged by having diverse interests.

How to practice?

  • practice how to define yourself
    • What are you really good at?
    • What are you looking for?
    • Why do you want to quit your job or how did you lose it?
  • practice describing what you did in your last job/current job (This is a very important part)
    You have to know:

    • The general design of the product you worked on.
    • What would you change in that design?
    • Class diagram – why did you designed it like that?
    • Which design patterns did you use?
    • What problems did you solve?
  • Practice while talking out loud. Don’t feel stupid, doing it will make you sound more conformable and confident in the real interview.
  • Work on your confidence. The way you sit, the way you walk and the way you talk, should all show you are a confident person.



General riddles
Some of the work places want to see the way you think by answering general riddles that don’t necessarily have something to do with programming. This is in order to establish if you are a creative person and are able to think “out of the box” .

How to practice?
Search the internet for riddles. Even though you can’t learn every one of them by heart, you can certainly adjust yourself to think in certain ways. There are repeating tricks in many of them. Who knows you might even like it and it can actually help you develop a way to think outside of the box. I like to search riddles like that from time to time, just for fun and to keep my mind fresh.


Java riddles and syntax
Probably all of the interviews I have been in perform this part in one way or another. In this part you will not be asked to design anything or answer hard programming questions. You will simply be asked to show your plain knowledge in java syntax, objects and main principles of Java. For example: this question or what is the difference between ArrayList and Vector. You may also be asked some short java riddles, like what is the best way to sort an array or to find loops in a linked list.

How to practice?

  • Search the internet and collect questions, copy them to a document and go over them every day.
  • Search the internet for java code examples. Copy them and experience with them.
  • Acknowledge repeating tricks like going over a list with 2 iterators instead of 1 is a principle that I ran into in many java riddles regarding lists.

Specific technologies questions
In this part you will probably be asked about specific technologies according to your resume. Like Spring framework, Hibernate, Struts and so on.

Advices

  • It’s always a good idea to keep track on the current trends. Read the java magazines and experience with the most popular technologies out there.
  • If you don’t know a certain technology, don’t say that you do. If you fixed a bug one time in Hibernate that does not mean you are a Hibernate expert. Believe me, an interviewer will probably see that after one question and then your chances to pass the interview are next to nothing.
  • It may be a good idea to also strengthen your knowledge in technologies you already know. It may be that you worked with Struts for years but you never had the chance to build a project using it from scratch or you never thought about the life cycle of it. This is the time to open books and learn just that. This is the time to open your IDE and start a project from scratch. This will make you realize things you have’nt realized until that point. This will make the difference between a struts developer and a struts expert.

Java short design questions
This part also requires java knowledge, but it’s not questions of syntax. In this part you will be asked to answer harder programming questions like how to write reader’s/writer’s lock, what is the best way to create a singleton or how to create a thread pool or a caching system.

  • Search the internet for java code examples. Copy them and experience with them.
  • Also here there are many repeating tricks like multi-threading problems many times include the use of wait/notify.
  • Learn Design patterns. Although I am not a big fan of design patterns, it is something that can’t be overlooked in the world of software programming. I suggest you go over them and take 2-3 and study just them really good.

General Design questions / DB tables designs
As opposed to the last part, here your java knowledge doesn’t matter, only your design abilities. These are pure design questions. Like designing a game of chess, design a book store DB or a tickets web site.

  • The internet is full with design question, but you actually don’t have to search, you can just look around. Look at the system around you. Choose a system (like a computer game) and design for yourself. When you finish look at it again and try to improve on it. I assure you that your first design can be improved, you just need to find how. If you repeat this step you will most certainly see improvement in your designing skills.
  • Design patterns – read previous section.
  • There are patterns that repeat a lot:
    • Many times a use of layers is a good idea. If you are asked to design a large system, than you probably need to create a data layer, business layer, user interface layer and so on.
    • DECOUPLE- every time you have a piece of code that is doing something unique, you should take it out and add also an interface so you could change the implementation easily. Almost always there is an interface or an abstract class, even if no inheritance is needed.
    • Almost always there is a factory or a singleton or both.
    • Many times there is a worker – a Daemon thread
    • Many times a use of cache is required to improve performance.
    • Multi-threading problems many times should include the use of wait/notify.
    • Multi-threading problems many times should include a thread pool.



General tips

  • Ask questions
    Remember – you are not just being interviewed, you are also the interviewer yourself.
    In the past I had a different approach, I tried to pass the interview no matter what, this was my only goal during the interview. This approach is no good. Even though you don’t have to decide during the interview if this job could be right for you you still need to gather as much information that will help you make the decision later on. Do that by asking questions: about the product, about the business, about the way the company works and about anything else.
    This will not only help you decide whether to work there or not but will actually improve your chances of getting the job. Asking questions shows that you won’t settle for any job, that you have standards, it also shows that you are curious and that is great.
  • Most important – show interest in the company and in the job you are interviewing for. This can help you in many ways.
  • Click with your interviewer.
  • If you don’t know something just say “I don’t know”, it is a lot better than mumbling. if you find yourself saying “I don’t know” too many times, maybe this is not the place for you but don’t give up, there were many times I aced interviews which I was sure I failed.

If you didn’t get the job

  • Perhaps it wasn’t meant to be. It sounds corny but it’s true – perhaps they didn’t take you for the job because they truly believe it’s not the right place for you. Maybe they are right.
  • Learn from your mistakes. Go over the interview in your head, try to see the interviewer’s point of view. In which part did you fail?
  • See your improvement. Every failed interview makes you smarter. In fact, the periods in my life in which I was unemployed were the times I probably learned the most, and not just professionally, I actually learned about myself and how to define myself better, as well as focus more on what kind of job I was looking for.



All I have written here demands a lot of work on your part. You certainly can not do it all, but let me tell you, you can really truly improve.
Hope it will help. Good luck.

Tagged with:
 

Trivia question – “Finally”

On 30/01/2010, in Pure Java, Trivia, by admin

Here is a confusing question – what does the next code prints?

	public static void doStam() {
		try {
			doExcption();
			return;
		}
		finally {
			System.out.println("Finally");
		}
	}

	public static void main(String[] args) {
		doStam();
	}

	public static void doExcption() {
		String [] stam = new String[0];
		//purpose exception
		stam[1].toString();
	}




Answer:
Finally
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: …

Tagged with:
 

Apache Pivot. Making Java GUI is easy.

On 22/01/2010, in Pivot, by admin

I just got to know to Pivot and I have to say, I love it.

Pivot is a technology to create Java applets for RIA or desktop applications with the use of XML and/or code.

When I write applications at home I don’t want waste time writing swing or applets myself. Pivot helps me designing the GUI with use of XML. It is that simple and the cool thing is that you can run it as a web page and a desktop application.



An example of a Pivot XML (WTKX):

<Window title="Hello" maximized="true"
    xmlns:wtkx="http://pivot.apache.org/wtkx"
    xmlns="org.apache.pivot.wtk">
    <content>
    	<BoxPane styles="{padding:4, horizontalAlignment:'center', verticalAlignment:'center'}">
       		 <Label wtkx:id="label1" text="Please enter your name"
          	  styles="{font:'Arial 20', color:'#ff0000',
              	  horizontalAlignment:'center', verticalAlignment:'center'}"/>
              <TextInput wtkx:id="text1"  />
               <PushButton wtkx:id="button1" buttonData="Enter"/>
         </BoxPane>
    </content>
</Window>



After creating the XML, you can refer to the GUI components from the code.


import org.apache.pivot.collections.Map;
import org.apache.pivot.wtk.Alert;
import org.apache.pivot.wtk.Application;
import org.apache.pivot.wtk.Button;
import org.apache.pivot.wtk.ButtonPressListener;
import org.apache.pivot.wtk.DesktopApplicationContext;
import org.apache.pivot.wtk.Display;
import org.apache.pivot.wtk.Label;
import org.apache.pivot.wtk.MessageType;
import org.apache.pivot.wtk.PushButton;
import org.apache.pivot.wtk.TextInput;
import org.apache.pivot.wtk.Window;
import org.apache.pivot.wtkx.WTKXSerializer;

public class HelloWTKX implements Application {
    private Window window = null;
    private Label label;
    private PushButton button1;
    private TextInput text1;

    @Override
    public void startup(Display display, Map<String, String> properties)
        throws Exception {
        WTKXSerializer wtkxSerializer = new WTKXSerializer();
        window = (Window)wtkxSerializer.readObject(this, "hello.wtkx");
        label = (Label)wtkxSerializer.get("label1");
        button1 = (PushButton)wtkxSerializer.get("button1");
        text1 = (TextInput)wtkxSerializer.get("text1");

        button1.getButtonPressListeners().add(new ButtonPressListener() {
                          @Override
                          public void buttonPressed(Button button) {
                             Alert.alert(MessageType.INFO, "Hello " + text1.getText(),
                                     window);
                         }
                     });
        window.open(display);
    }

    @Override
    public boolean shutdown(boolean optional) {
        if (window != null) {
            window.close();
        }

        return false;
    }

    @Override
    public void suspend() {
    }

    @Override
    public void resume() {
    }

    public static void main(String[] args) {
        DesktopApplicationContext.main(HelloWTKX.class, args);
    }
}



Actually the entire GUI can be built just from the code, but I like the XML way better.

The application can be run from the IDE or can be referred from a web page as an applet.
All you have to do is refer to the Pivot jars + your jar and give the full name of your application class you have created.


<applet code="org.apache.pivot.wtk.BrowserApplicationContext$HostApplet"
    archive="lib/test.jar,lib/pivot-core-1.4.jar,lib/pivot-wtk-1.4.jar,lib/pivot-wtk-terra-1.4.jar,lib/pivot-tutorials-1.4.jar"
    width="500" height="400">
    <param name="application_class_name" value="HelloWTKX"> <!-- your application class package -->
</applet>




The result:

The Pivot web site contains loads of examples with the use of their components.



Pivot website

downloaddownload sample project for Eclipse but don’t forget also to download Pivot jars.

Tagged with:
 

Java Interface rules

On 15/01/2010, in Pure Java, Trivia, by admin

Let’s start with a short Java question:

Bellow you can see the interface ‘Test’.
Which lines in that interface will be rejected by the compiler?


public interface Test{

	//1
	public static final int x1 = 3; 

	//2
	public static int x2 = 3; 

	//3
	static int x3 = 3; 

	//4
	int x4 = 3; 

	//5
	public int f5();

	//6
	int f6(); 

	//7
	public static int f7();

	//8
	private void f8();

	//9
	public final void f9();

	//10
	private static final int x5 = 3;
}

The answer is:

lines: 7,8,9,10

I am sure that even many of the experienced java developers will not have a 100% success answering this question because it can be confusing.

1, 2, 3 and 4 are actually all the same – only constants are allowed and by default they are. For that reason, 10 is not allowed.
5, 6 are the same – only public and protected methods are allowed. By default they are public.

In short these are the rules for interfaces:
Member variables
Can be only public and are by default.
By default are static and always static
By default are final and always final

Methods
Can be only public and are by default.
Can NOT be static
Can Not be Final

Tagged with: