Archive | Java RSS feed for this section

How to test Applications using Eclipse ? (Introducing my new book)

16 May

Application testing plays very important role in any development process.  After spending numerous hours on it, I have decided to put what I felt was important in to a short book, which is intended to help developers  to get  started with  application testing using Eclipse.

918Y5X8TILL._AA1500_

The book is very practical, there is almost no theory, just recipes that introduce essential concepts of testing such as Breakpoints and JUnit tests.It is short and strict to the point. You can read it and do all the recipes in one day, and in the end, you will have deep understanding of how to debug your application using Eclipse.

The book is available in paperback as well as ebook formats.

Java Helper Class: BMI calculator, lb to kg converter, kg to lb converter, feet to cm converter, cm to feet converter

22 Mar

Hey Guy’s,

Long time no seen. Today I want to share with you Java helper class that I have designed for one  of the projects I am working on. This class will be useful for you, if your application works with height and weight conversions, also if you need to calculate Body Mass Index.

My helper class has following functionality:

- Kg to Lb Converter
- Lb to Kg Converter
- BMI (Body Mass Index) Calculator and “Classificator
- Feet to Cm Converter
- Cm to Feet Converter

Here is the class:

import java.text.DecimalFormat;

/**
* This class is used for any calculations connected with Weight and Height
*  - KG to LB converter (and vice versa)
*  - Feet to Cm converter (and vice versa)
*  - BMI Calculation
*
*/
public class HeightWeightHelper {

/**
*
* @param value double that is formatted
* @return double that has 1 decimal place
*/
private double format ( double value) {
  if ( value != 0){
   DecimalFormat df = new DecimalFormat("###.#");
   return Double.valueOf(df.format(value));
 } else {
   return -1;
 }
}

/**
*
* @param lb - pounds
* @return kg rounded to 1 decimal place
*/
public double lbToKgConverter(double lb) {
  return format(lb * 0.45359237 );
}

/**
*
* @param kg - kilograms
* @return lb rounded to 1 decimal place
*/
public double kgToLbConverter(double kg) {
  return format(kg * 2.20462262);
}

/**
*
* @param cm - centimeters
* @return feet rounded to 1 decimal place
*/
public double cmToFeetConverter(double cm) {
  return format(cm * 0.032808399 );
}

/**
*
* @param feet - feet
* @return centimeters rounded to 1 decimal place
*/
public double feetToCmConverter(double feet) {
  return format(feet * 30.48 );
}

/**
*
* @param height in <b>cm</b>
* @param weight in <b>kilograms</b>
* @return BMI index with 1 decimal place
*/
public double getBMIKg (double height, double weight) {
  double meters = height/100;
  return format( weight / Math.pow(meters,2));
}

/**
*
* @param height in <b>feet</b>
* @param weight in <b>pounds</b>
* @return BMI index with 1 decimal place
*/
public double getBMILb (double height, double weight) {
  int inch = (int)(height *12);
  return format((weight*703) / Math.pow(inch, 2));
}

/**
*
* @param bmi (Body Mass Index)
* @return BMI classification based on the bmi number
*/
public String getBMIClassification (double bmi) {

 if (bmi <= 0) return "unknown";
 String classification;

 if (bmi < 18.5) {
  classification = "underweight";
 } else if (bmi < 25) {
  classification = "normal";
 } else if (bmi < 30) {
  classification = "overweight";
 } else {
  classification = "obese";
 }

 return classification;
}

}//end of class

P.S If you want to have JUnit tests for this class let me know, I have them too :)

Regards,

Anatoly

SWT migration to GTK+ 3.x: Use Cairo Instead GDK : First Patch – Tracker Widget

7 Jun

I am continuing series of posts about   SWT migration to GTK+ 3.x . Today, I will  write about patch for SWT Tracker Widget, that omits some of GTK+ 3.x deprecated methods.

When I started working on patch for Tracker, it was very important for me understand what Tracker Widget is intended to do. I found very good implementation of  SWT Tracker widget   here 

Actual code is:


import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tracker;

public class Tracker_test {

public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
shell.open();
shell.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
Tracker tracker = new Tracker(shell, SWT.NONE);
tracker.setRectangles(new Rectangle[] { new Rectangle(e.x, e.y, 100, 100), });
tracker.open();
}
});
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}

When you run this code, you see small rectangle. It appears when you  right-mouse click and disappears when you  release right-mouse click. It looks like this:

From this example, we can see that Tracker is intended to track mouse movements and mouse clicks. It works great, the only problem is that some code in Tracker Widget is outdated, and it won’t built with GTK+ 3.x. I am talking about code in drawRectangles() method inside Tracker.java.

Let’s look at this code:


void drawRectangles (Rectangle [] rects) {
int   window = OS.gdk_get_default_root_window();
if (parent != null) {
window = OS.GTK_WIDGET_WINDOW (parent.paintHandle());
}
if (window == 0) return;
//TODO: Use Cairo
int gc = OS.gdk_gc_new (window);
if (gc == 0) return;
int /*long*/ colormap = OS.gdk_colormap_get_system ();
GdkColor color = new GdkColor ();
OS.gdk_color_white (colormap, color);
OS.gdk_gc_set_foreground (gc, color);
OS.gdk_gc_set_subwindow (gc, OS.GDK_INCLUDE_INFERIORS);
OS.gdk_gc_set_function (gc, OS.GDK_XOR);
for (int i=0; i
Rectangle rect = rects [i];
int x = rect.x;
if (parent != null && (parent.style & SWT.MIRRORED) != 0) x = parent.getClientWidth () - rect.width - x;
OS.gdk_draw_rectangle (window, gc, 0, x, rect.y, rect.width, rect.height);
}
OS.g_object_unref (gc);
}

If we take a look at  GDK documentation , we will find out that gdk_gc_newgdk_color_white gdk_gc_set_foreground, gdk_gc_set_subwindow, gdk_gc_set_function and even  gdk_draw_rectangle are all deprecated since GTK version 2.22 and should not be used in newly written code. And as a hint, there is ‘ // TODO: Use Cairo’.

So I here is some of the changes I made to this code:

1. I replaced gdk_gc_new  with  gdk_cairo_create

2. OS.gdk_gc_set_function (gc, OS.GDK_XOR)  was replaced with equivalent function  Cairo.cairo_set_operator(cairo,Cairo.CAIRO_OPERATOR_DIFFERENCE)  (this function is responsible for rectangle to disappear on mouse release)

3. gdk_draw_rectangle was replaced with cairo_rectangle, as cairo saves everything to buffer first, you need to release changes. In my case I used cairo_stroke. ( it fills just contour of rectangle)

4. gdk_color_white was replaced with  cairo_set_source_rgb(cairo, 1, 1, 1);

5. I also had to add line width,  and antialising (without antialising  line width didn’t work)

So my code looks like this:

if(OS.USE_CAIRO){
int /*long*/ cairo = OS.gdk_cairo_create(window);
if (cairo == 0) error (SWT.ERROR_NO_HANDLES);

Cairo.cairo_set_source_rgb(cairo, 1, 1, 1);
Cairo.cairo_set_line_width(cairo, 1);
Cairo.cairo_set_operator(cairo,Cairo.CAIRO_OPERATOR_DIFFERENCE);
Cairo.cairo_set_antialias(cairo, Cairo.CAIRO_ANTIALIAS_NONE);

for (int i=0; i<rects.length; i++) {
Rectangle rect = rects [i];
Cairo.cairo_rectangle (cairo, rect.x, rect.y, rect.width, rect.height);
Cairo.cairo_stroke(cairo);
}
Cairo.cairo_destroy(cairo);
return;
}

After run with Cairo, I have the same output as GTK version does.

I have posted bug report with my patch here:  https://bugs.eclipse.org/bugs/show_bug.cgi?id=380287  ( As for June 7, patch is not reviewed yet, as Eclipse reviewers are extra-busy with new version of Eclipse coming out very soon)
I have coded couple of other patches, and I will definitely do some posts on them after this first patch is reviewed.

Regards,

Anatoly

Update:

Unfortunately there is one case where current patch does not work properly, as it supposed to. This case is when you pass “display” to the Tracker constructor. In GDK version it is supposed to use GDK_INCLUDE_INFERIORS that puts rectangle on top of all other windows, however Cairo does not have this luxury, and all my attempts to put in on top is clipped by child windows.

I keep on working on it, and I will keep you updated!

 

Check out more posts on “SWT migration From GTK+ 2 to GTK+ 3″

What is Standard Widget Toolkit for Eclipse (SWT) ?

15 May

Here I am at my new workplace. Next 8 months I will be working in Eclipse team, on migration of SWT  from GTK2 to GTK3.

If these words does not tell you much, don’t worry, I am pretty much in the same situation, but what I am going to do in the next couple of days is to explore this issue as much as I can, and  write down my findings here.

Let’s start with SWT.  My first stop in finding info about SWT was here: http://www.eclipsepluginsite.com/swt.html

After reading  introductory chapter,  I have  found out that SWT stands for   Standard Widget Toolkit.  As I have understood from the reading, SWT is a collection of tools, intended for creating stand alone java applications or eclipse plugins  with basic UI components (such as buttons, trees etc). What is  special about SWT, is that it uses native OS components, so when you build application with SWT it feels like this application is intended for the particular OS.

I decided to build a simple application using one of the examples provided in the reading.

Simple SWT Application

/*
 *  Name: BlogButton.java
 *  Description:  SWT  button on click changes text and background color
 *
 *  Author: Anatoly Spektor
 *  Date: May 14,2012
 * */

import org.eclipse.swt.events.SelectionAdapter;
 import org.eclipse.swt.events.SelectionEvent;
 import org.eclipse.swt.layout.FillLayout;
 import org.eclipse.swt.widgets.Button;
 import org.eclipse.swt.widgets.Display;
 import org.eclipse.swt.widgets.Shell;
 import org.eclipse.swt.*;

public class BlogButton {

public static void main(String[] args) {
 // creating new object of Display myDisplay
 //in SWT Display manages connection between app and OS
 final Display myDisplay = new Display();
 // creating instance of shell - which is actual window
 Shell myShell = new Shell(myDisplay);

// setting window title
 myShell.setText("Window Title");
 //setting size
 myShell.setSize(400,400);
 // setting layout
 myShell.setLayout(new FillLayout());
 // creating button object in myShell
 // passing PUSH behaviour
 final Button button = new Button(myShell, SWT.PUSH);
 // passing button label
 button.setText("Show Blog URL");

// adding event listener to button
 button.addSelectionListener(new SelectionAdapter() {
 public void widgetSelected(SelectionEvent event) {
 //on selected change button label
 button.setText("myprogrammingblog.com");
 // set text color to red
 button.setForeground(myDisplay.getSystemColor(SWT.COLOR_RED));

}
 });

// open - pushes shell on the top of drawing order and makes it visible
 myShell.open();

// checking if shell is Disposed or not
 while (!myShell.isDisposed()) {
 // check if there is work to do for this shell and if not
 // put it in sleep mode so no CPU is consumed
 if (!myDisplay.readAndDispatch()) myDisplay.sleep();
 }
 // disposing an object
 myDisplay.dispose();
 }
 }

Output:

Before Click:
SWT button before click

After Click:

SWT button after click snapshot

 

Check out more posts on “SWT migration From GTK+ 2 to GTK+ 3″

Java – How to format string using SampleDateFormat ?

6 Apr

One of the blog readers asked me this question, how to format string using SampleDateFormat to mm/dd/yyy.

Here is a small piece of code, I hope some of you will find it useful.

a. Frist – import 2 libraries:


import java.text.SimpleDateFormat;
import java.util.Date;

b. Here is code:


Date date = new Date(); // creating date object
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy hh:mm a");
// creating SampleDate object and passing the pattern to constructor ("a" means show AM or PM)
System.out.println( "Here is today's date: " +  formatter.format(date) + ");

//The output: Here is today's date: 04/06/12 10:52 AM

Regards,

Anatoly Spektor

Java: How to split Java String with delimeter comma, space, new line, tab ? [SOLVED]

20 Feb

Sometimes it is very important to split a string on a comma \n \t etc. This piece of code will help you with it.


import java.util.*;

 public class split{

  public  static void main ( String args[]) {
       // this is my string
	String s = "Java,	Programming	is ,,, fun do you agree? ."; split
	String regexp = "[\\s,;\\n\\t]+"; // these are my delimiters
	String [] tokens; // here i will save tokens
	// length is 7 because i know that my string will consist of 7 tokens
	for(int i=0;i<7;i++){
		tokens = s.split(regexp);
		System.out.println(tokens[i]);
	}
   }
}

 // tokens are: Java Programming is fun do you agree?

Check out more posts on “Useful Java Functions and Tutorials”

Java: How to find Longest String in ArrayList ? [FUNCTION]

19 Feb

While I was playing with Java code, I have coded a class that has method that finds longest String in the ArrayList. Method is very simple, but I am sure that some of you will find it useful.

So here it is:

 // I have a class attribute:
private ArrayList wordsList = new ArrayList();

// here is method itself:
public String longest_word(){
	String longest_word="";
	int maxLength=0;
		for(int i=0; i

			if(wordsList.get(i).length() > maxLength){
			  maxLength = wordsList.get(i).length();
			  longest_word = wordsList.get(i);
			}
		}
	return longest_word;
	}

Check out more posts on “Useful Java Functions and Tutorials”

Java : How to swap two objects [Problem Solved]

12 Jan

As you might knowJava does not support pointers, thus swapping things around could create problems.  In this post I will show an example of swapping two objects.

We have Employee class that holds information about Employees and SwapDemo3 class that will actually swap two employees inside a swap() method.

Swap() method will be using set and get methods of Employee class to get the private data from it.

So here is Employee Class we will be working with:

Continue reading 

Follow

Get every new post delivered to your Inbox.

Join 274 other followers

%d bloggers like this: