Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, January 19, 2013

How to set environment variables in Windows 7 for Java

Environmental variables are used by the operating system to save settings (default values, locations of resources) to be used by Windows or by processes launched by users.
There are two types of environmental variables:
  • user variables that are specific to a particular Windows user account;
  • system variables are always visible, regardless of the used user account.

Even if these variables are usually defined and initialized automatically when you install the system or other applications, there are situations in which the user must manually define them to put at the disposal of applications.
The considered scenario is to set environment variables to enable the compilation and execution of Java applications from the command line (command prompt) or by using an IDE like Eclipse. By installing the Java SDK, system variables about the location of executables (compiler, java virtual machine) are not defined or initialized automatically.
Testing is done by opening command prompt (Start -> cmd) and trying to launch the compiler with the command

C:\Users\Catalin>javac.exe
If there is no system variable to indicate where to look for the this executable, the system will give an error like:
'javac' is not recognized as an internal or external command,
operable program or batch file.
The solution to this problem is given by setting the system variables: JAVA_HOME, PATH and CLASSPATH:
  1. Open the Control Panel -> System or Security –> System; the same thing can be done by right-clicking on MyComputer and choosing Properties
System window in Windows 7
System window in Windows 7

2.   Choose Advanced System Settings option
System properties window in Windows
System properties window in Windows

3.   Choose the Environment Variables option
Environment variables in Windows
Environment variables in Windows

4.   In the System variables section it is selected New5.   Define the variable name, JAVA_HOME and its value C:\Program Files\Java\jdk1.6.0_16 (for this example JDK version 1.6.0 was installed in C:\Program Files\Java\jdk1.6.0_16 folder; if needed, modify this value to reflect the real situation)
6. Insert a new system variable named, CLASSPATH and its value %JAVA_HOME%\jre\lib

New system variable
New system variable

7. For PATH, if it already exists, select it and choose the Edit option; in the editor add the value;%JAVA_HOME%\bin (the new values are separated by a semicolon from the existing ones) Testing the system variables is done by opening a new command prompt window (Start -> cmd) and trying to launch the compiler with the command:
C:\Users\Catalin>javac
Usage: javac
where possible options include:
-g Generate all debugging info
...
or, by using next commands
C:\Users\Catalin>echo %CLASSPATH%
C:\Program Files\Java\jdk1.6.0_16\jre\lib
 
C:\Users\Catalin>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.6.0_16
 
C:\Users\Catalin>echo %PATH%
8. Restart the computer in order to make your system aware of these changes (thanks to Ike for reminding me)

Wednesday, December 26, 2012

Android - Function to convert ImageURL to Bitmap object

IMAGE URL TO BITMAP

Use this function “convertURLtoBitmap”

public Bitmap convertURLtoBitmap(String src) {

                try {

                                URL url = new URL(src);
                                                
                                HttpURLConnection connection = (HttpURLConnection) url
                                                .openConnection();

                                connection.setDoInput(true);
                                connection.connect();

                                InputStream input = connection.getInputStream();
                                Bitmap myBitmap = BitmapFactory.decodeStream(input);

                                return myBitmap;

                }

                catch (IOException e) {

                                e.printStackTrace();
                                return null;

                }
}

Searching the elements of a String array, starts with SEARCHTEXT (String)


Searching the elements of a String array, starts with SEARCHTEXT (String)

public static ArrayList<String> searchFromStart(String[] inputArray, String searchText) {

            ArrayList<String> outputArray = new ArrayList<String>();

            for (int i = 0; i < inputArray.length; i++) {

                        if (searchText.compareToIgnoreCase(inputArray[i].substring(0,
                                                searchText.length())) == 0) {

                                    outputArray.add(inputArray[i]);

                        }

            }

            return outputArray;
}

Email Validation Function


public boolean validateEmail(String email) {

Pattern pattern;
Matcher matcher;
String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();

}

Monday, December 24, 2012

Ví dụ cơ bản về Spring Framework web


Tạo một package mới với tên tùy ý bên trong của thư mục src. Class Spring Controller extends đến org.springframework.web.servlet.mvc.AbstractController. Để tạo ra một Class Controller mới kích chuột phải vào thư mục src và tạo ra một lớp java mới, hãy nhập tên Controller class và tên super class và nhấn nút Finish.


Copy đoạn mã sau vào trong lớp HelloWorldController.

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class HelloWorldController extends AbstractController {
       private String message; 

       @Override
       protected ModelAndView handleRequestInternal(HttpServletRequest request,       
              HttpServletResponse response) throws Exception {
              return new ModelAndView("welcomePage","welcomeMessage", message);
       }

        public void setMessage(String message) {
              this.message = message;
        }
}

HelloWorldController class có message property được thiết lập thông qua setter injection. HelloWorldController class sẽ ghi đè lên của phương pháp handleRequestInternal() để xử lý yêu cầu. Sau khi xử lý của yêu cầu handleRequestInternal() phương thức trả về một ModelAndView đối tượng trở về DispatcherServlet.


DispatcherSevlet, như tên cho thấy, là một servlet duy nhất để quản lý quá trình xử lý yêu cầu toàn bộ. Khi yêu cầu được gửi đến của DispatcherServlet nó đại diện công việc bằng cách gọi các bộ điều khiển thích hợp để xử lý yêu cầu. Giống như bất kỳ servlet khác DispatcherServlet cần phải được cấu hình trong mô tả triển khai web như được hiển thị.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
     <servlet-name>dispatcher</servlet-name>
     <url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
     <welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>

Ở đây tên servlet là dispatcher. Theo mặc định các DispatcherServlet sẽ tìm một tên tập tin dispatcher-servlet.xml để nạp cấu hình của Spring MVC. Tên tập tin được tạo thành bởi việc ghép tên servlet ("dispatcher") với "-servlet.xml". Ở đây chúng ta sử dụng của của url-pattern là ". htm" inorder để ẩn công nghệ triển khai cho người sử dụng.

Những redirect.jsp sẽ được gọi đầu tiên khi chúng ta thực thi các ứng dụng web Spring. Đây là file jsp duy nhất bên ngoài thư mục WEB-INF và nó ở đây để cung cấp một chuyển hướng đến của DispatcherServlet. Tất cả của views khác cần được lưu giữ dưới thư mục WEB-INF để họ có thể được gọi chỉ thông qua quy trình controller.

Để tạo một tập tin cấu hình bean kích chuột phải vào thư mục WebContent và chọn New -> Other. Hộp thoại sau xuất hiện.


Chọn cấu hình Spring Bean tập tin và kích Next.


Nhập tên file là "dispatcher-servlet.xml" và nhấn vào nút Finish.

Bây giờ các tập tin cấu hình bean của Spring được tạo ra, chúng ta cần phải cấu hình Controller và các lớp ViewResolver. Những mã sau đây cho thấy làm thế nào để làm điều này.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="viewResolver" class=" org.springframework.web.servlet.view. InternalResourceViewResolver" >
     <property name="prefix">
            <value>/WEB-INF/jsp/</value>
     </property>
     <property name="suffix">
            <value>.jsp</value>
      </property>
</bean>
<bean name="/welcome.htm" class="com.vaannila.HelloWorldController" >
        <property name="message" value="Hello World!" />
</bean>
</beans>

Đầu tiên chúng ta hãy hiểu làm thế nào để cấu hình controller.

<bean name="/welcome.htm" class="...HelloWorldController" >
       <property name="message" value="Hello World!" />
</bean>

Những ViewResolver được cấu hình bằng cách sử dụng đoạn mã sau.

<bean id="viewResolver" class=" org.springframework.web.servlet.view.InternalResourceViewResolver" >
      <property name="prefix">
             <value>/WEB-INF/jsp/</value>
      </property>
      <property name="suffix">
             <value>.jsp</value>
      </property>
</bean>

Các tập tin thư viện sau đây là cần thiết để chạy các ví dụ.

antlr-runtime-3.0
commons-logging-1.0.4
org.springframework.asm-3.0.0.M3
org.springframework.beans-3.0.0.M3
org.springframework.context-3.0.0.M3
org.springframework.context.support-3.0.0.M3
org.springframework.core-3.0.0.M3
org.springframework.expression-3.0.0.M3
org.springframework.web-3.0.0.M3
org.springframework.web.servlet-3.0.0.M3

Để thực hiện ví dụ như chạy các tập tin redirect.jsp. Những trang sau sẽ được hiển thị.


Chúc bạn thành công

Tuesday, December 11, 2012

Handling huge data using ZK


Overview

When your database contains a large amount of data you do not want to load all these items into memory. ZK provides many methods for handling large amounts of data including:

  • Live data scrolling
  • Load on demand Trees
  • Paging components

One of the most convenient ways in which to handle a large amount of data is using a paging mechanism.

Introducing huge data with paging

However, normally the paging mechanism will load all the data into the grid via the model. This Small Talk guides you through a method of handling large amounts (in this case 1,000,000 database entries) of data using a small memory footprint.

The basic premise of the Small Talk is to store a list of users within a database, including their first name, surname and phone number.

Demo


Creating the database

We create a database named livedata and create a table named tblusers. We will provide the following columns, id (INT, AI, PK), first_name (VARCHAR), last_name(VARCHAR) and phone(VARCHAR).
The SQL statement to create the table is provided below

1
2
3
4
5
CREATE TABLE tblusers (id int(10) NOT NULL AUTO_INCREMENT,
                                      first_name varchar(200) NOT NULL,
                                      last_name varchar(200) NOT NULL,
                                      phone varchar(20) NOT NULL, PRIMARY KEY (id) )
                                      ENGINE=InnoDB DEFAULT CHARSET=utf8;

The database screen

We have introduced a database screen which allows you to quickly setup and test your database connection. This is the first page that you arrive at when running the sample, if you have any problems you can manually edit the DatabaseInteraction class and recompile it.

Interacting with the database

Linking the application with the database is the easy part and involves creating a DAO to handle the interaction. The DAO, in this instance, only consists of functions to insert and retrieve news items from the database. Please refer to the UserDAO for more details.
The connection is handled via the MySQL J/Connector with a new connection being made for each operation. Please note that a new connection for each operation is NOT the best method of implementation, a connection pool would be far more efficient so please do not use the code for production level software. Building the model
The model needs to represent our user utilizing Java’s Object Orientated features, hence we implement a Java class named User which includes getters and setters for every field present in the database.

The code within the User class is included below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class User {
 
    private int _id;
    private String _firstName;
    private String _lastName;
    private String _phone;
     
    public String getFirstName() {
        return _firstName;
    }
    public void setFirstName(String firstName) {
        this._firstName = firstName;
    }
    public String getLastName() {
        return _lastName;
    }
    public void setLastName(String lastName) {
        this._lastName = lastName;
    }
    public String getPhone() {
        return _phone;
    }
    public void setPhone(String phone) {
        this._phone = phone;
    }
    public void setId(int id) {
        this._id = id;
    }
    public int getId() {
        return _id;
    }
}
With the User class implemented along with the functions to retrieve them from the database we need to construct the model.

The PagingListModel and the AbstractPagingListModel

To make the implementation of a paging model easier a base class which we can easily extend was created by me.

AbstractPagingListModel

The AbstractPagingListModel was created by myself (it is included in the source zip) to take most of the hard work away when implementing a paging system which limits the memory use. The AbstractPagingListModel extends the AbstractListModel provided by ZK and hence has to override two functions:

1
2
3
public Object getElementAt(int index)
 
public int getSize()

These two functions are used to manipulate an internal list which contains the retrieved items from the database. This is not done all at once but on a page per page basis. For example if a database table had 1,000,000 entries and the pageSize was 20, there would only be 20 items in memory at any given time.

The function getElementAt returns an element from a model at a particular index. The getElementAt function accesses a local List which contains the data retrieved from the data source (in the case of this Small Talk it is a database).

It is tempting to use this function to directly access the database and retrieve items one by one, while this is tempting it not the best practice as it would require multiple queries to database and thus be slower than one query.

The getSize function returns the size of the local model, in the case of the example this is 20. It is important that you do not return the total number of items in the database as this would lead to a large amount of memory being used.

Functions we need to override

The AbstractPagingModel requires us to override two functions, these are:

1
2
3
public abstract int getTotalSize();
 
protected abstract List<T> getPageData(int itemStartNumber, int pageSize);

These two functions provide the model with the data for a given page and retrieve the total amount of items in the database table. This information can come from any data source, the decision is up to us.

The constructor

The constructor takes two integer arguments, startPageNumber and pageSize which are multiplied together to retrieve the item number to start from. This item number is then used in a database query to retrieve the list needed. The database query works by using SQL LIMIT to define the starting point (startPageNumber * pageSize) and the number of Users to retrieve (pageSize).
The constructor code is included below:
1
2
3
4
5
6
7
8
public AbstractPagingListModel(int startPageNumber, int pageSize) {
        super();
        this._startPageNumber = startPageNumber;
        this._pageSize = pageSize;
         
        int itemStartNumber = startPageNumber * pageSize;
        _items = getPageData(_itemStartNumber, _pageSize);
    }

Having retrieved the appropriate number of Users we need to store these in memory, hence the amount of Users in memory will only be your pageSize. This functionality is provided by an internal List.

PagingListModel

The PagingListModel overrides the required functions and provides a constructor as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class PagingListModel extends AbstractPagingListModel<User> {
 
    private static final long serialVersionUID = 4370353438941246687L;
 
     
    public PagingListModel(int startPageNumber, int pageSize) {
        super(startPageNumber, pageSize);
    }
 
    @Override
    protected List<User> getPageData(int itemStartNumber, int pageSize) {
        return DatabaseInformation.dao.selectWithLimit(itemStartNumber, pageSize);
    }
 
    @Override
    public int getTotalSize() {
        return DatabaseInformation.dao.getUserCount();
    }
 
}

Building the UI

The basic GUI is very simple and consists of two parts
  1. The button which generates 1,000,000 database entries
  2. The paging area (including Grid and paging components)

Separation of the Paging component and the Grid

One of the most important features of this small talk is the fact that the Paging and Grid component are separated. The interaction between the two is implemented by ourselves and not automatically done by ZK. It is possible to autowire this functionality however, this would require calling the setPaginal function which we have already established is not a good idea in this case.
The markup below is the ZUL code from our index.zul
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<window title="Huge data demo"  border="normal" apply="org.zkoss.zklargelivelist.controllers.MainUserController">
     
    <label value="If you need to generate 1,000,000 entries please press this button!" />
    <button id="btnGenerate" label="Generate database entries" />
     
    <separator />
     
    <paging id="userPaging"/>
    <grid id="dataGrid">
        <columns>
            <column label="id" width="60px"/>
            <column label="firstName"/>
            <column label="lastName"/>
            <column label="phone"/>
        </columns>
    </grid>
</window>
Please note that the Window component uses the MainUserController to respond to any events fired by the GUI. The controller is discussed in the next section.

Controller functionality

The controller handles two GUI events and overrides the doAfterCompose method. Firstly let us deal with the doAfterCompose method and explain what it does. The method is called after the components have been initialized. This allows us to manipulate the components before the user interacts with them.

doAfterCompose

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
 
        dataGrid.setRowRenderer(new RowRenderer(){
            @SuppressWarnings("unchecked")
            public void render(Row row, Object data) throws Exception {
                User usr = (User) data;
                row.getChildren().add(new Label(usr.getId()+""));
                row.getChildren().add(new Label(usr.getFirstName()));
                row.getChildren().add(new Label(usr.getLastName()));
                row.getChildren().add(new Label(usr.getPhone()));
            }});
         
        refreshModel(_startPageNumber);
    }

We create our own custom row renderer to format the data and then refresh the model. The refresh model function will create a new PagingListModel and attach that model to the grid, hence displaying the first page of users. Notice the speed and low memory usage of this as we only pull the amount of users that we require for one page and hold that in memory!

refreshModel

1
2
3
4
5
6
7
8
9
10
11
12
13
private void refreshModel(int activePage){
        userPaging.setPageSize(_pageSize);
        model = new PagingListModel(activePage, _pageSize);
         
        if(_needsTotalSizeUpdate) {
            _totalSize = model.getTotalSize();
            _needsTotalSizeUpdate = false;
        }
         
        userPaging.setTotalSize(_totalSize);
         
        dataGrid.setModel(model);  
    }
When refreshing the model the first thing we do is set the pageSize of the paging system, this is always set to 20, however in your own custom implementations it can be changed to any value you like. After setting the page size and creating the new PagingListModel we set the total size of the data in the paging system, this is a count of the number of items in the database. Finally the model is attached to the dataGrid using the dataGrid's setModel method.

GUI events

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public void onClick$btnGenerate() {
    int numberOfUsers = DatabaseInformation.dao.getUserCount();
    final int numberOfEntriesRequired = 1000000;
     
    int usersRequired = numberOfEntriesRequired - numberOfUsers;
     
    if(usersRequired > 0) {
        User[] users = new User[usersRequired];
                     
        for(int i=0; i<usersRequired; i++) {
            users[i] = GenerateData.generateUser();
        }
             
        DatabaseInformation.dao.insertUser(users);
         
        _needsTotalSizeUpdate = true;
         
        refreshModel(userPaging.getActivePage());
    }
    else
    {
        try {
            Messagebox.show("There are already 1,000,000 entries in the database!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The other two functions are related to handling GUI events, the first is onClick$btnGenerate which is used to generate 1,000,000 entries in our database. This functionality is self explanatory and not the focus of the Small Talk so we will move onto the second function onPaging$userPaging.
1
2
3
4
5
public void onPaging$userPaging(ForwardEvent event){
        final PagingEvent pe = (PagingEvent) event.getOrigin();
        _startPageNumber = pe.getActivePage();
        refreshModel(_startPageNumber);
    }

The function is small but is essential in regulating the model, the function retrieves the active page from the Paging event and then refreshes the model. Upon refreshing the model as described above the model is recreated and then set to the data grid, thus moving the paging along.

Important information

setPaginal

It is important that you do not set the paging element of your listbox or grid. It is not advisable to have grid controlling a paginal component where the total number of items doesn’t match the number of grid’s list items.

pageSize and totalSize

To retrieve the pageSize you need to use the method getPageSize() of the paging component rather than the grid or listbox. In addition we have to make sure we set the total size of the paging component to that of the total number of items in your database table, or what is returned from the query.

Download

Please download the source here.
You can also download the WAR file here.