Archive

Posts Tagged ‘Java’

Spring MVC + Tiles

December 13th, 2009 No comments

1. create web.xml
<?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>action</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

2. create action-servlet.xml
<?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-2.5.xsd">

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="message" />
</bean>

<bean id="testController" class="com.bluewiseinc.erp.common.web.TestController">
<property name="methodNameResolver" ref="methodNameResolver" />
</bean>

<bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName">
<value>med</value>
</property>
<property name="defaultMethodName">
<value>userMain</value>
</property>
</bean>

<!--
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="cache" value="false" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<bean class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location">
<value>/WEB-INF/UrlMap.properties</value>
</property>
</bean>
</property>
</bean>

<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles-def.xml</value>
</list>
</property>
</bean>

<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>
</beans>

3. create TestController
package com.bluewiseinc.erp.common.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class TestController extends MultiActionController {
public ModelAndView testMain(HttpServletRequest request, HttpServletResponse response) throws Exception {
return new ModelAndView("test/test_main", "testMain", null);
}
}

4. UrlMap.properties
## test module mapping
/test/index.do=testController

5. tiles-def.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">

<tiles-definitions>
<definition name="defaultTemplate" template="/WEB-INF/view/tiles/default.jsp">
<put-attribute name="header" value="/WEB-INF/view/tiles/def_header.jsp" />
<put-attribute name="menu" value="/WEB-INF/view/tiles/def_menu.jsp" />
<put-attribute name="footer" value="/WEB-INF/view/tiles/def_footer.jsp" />
</definition>
<definition name="test_main" extends="defaultTemplate">
<put-attribute name="content" value="/WEB-INF/view/test/test_main.jsp"/>
</definition>
</tiles-definitions>

6. message.properties
# Page titles
index.title=Test Spring MVC + Tiles

7. default.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><fmt:message key="index.title"/></title>
<link rel=stylesheet href="${pageContext.request.contextPath}/css/global.css" type="text/css">
<script type="text/javascript" src="${pageContext.request.contextPath}/scripts/global.js"></script>
</head>
<body>
<div id="header">
<div id="headerTitle"><tiles:insertAttribute name="header" /></div>
</div>
<div id="menu">
<tiles:insertAttribute name="menu" />
</div>
<div id="content">
<tiles:insertAttribute name="content" />
</div>
<div id="footer">
<tiles:insertAttribute name="footer" />
</div>
</body>
</html>

SwingWorker not on Java 6.0

April 24th, 2008 4 comments

SwingWorker is useful when a time-consuming task has to be performed following a user-interaction event (for example, parsing a huge XML File, on pressing a Button). The most straightforward way to do it is :

[sourcecode language='java']
private Document doc;

JButton button = new JButton(“Open XML”);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doc = loadXML();
}
});
[/sourcecode]

This will work, but unfortunately, the loadXML() method will be called in the same thread as the main Swing thread, so if the method needs time to perform, the GUI will freeze during this time.

[sourcecode language='java']
package com.wsjoung.demo;
import javax.swing.SwingUtilities;

public abstract class SwingWorker {
// see getValue(), setValue()
private Object value;
private Thread thread;

private static class ThreadVar {
private Thread thread;
ThreadVar(Thread t) { thread = t; }
synchronized Thread get() { return thread; }
synchronized void clear() { thread = null; }
}

private ThreadVar threadVar;

protected synchronized Object getValue() {
return value;
}

private synchronized void setValue(Object x) {
value = x;
}

public abstract Object construct();

public void finished() {
}

public void interrupt() {
Thread t = threadVar.get();
if (t != null) {
t.interrupt();
}
threadVar.clear();
}

public Object get() {
while (true) {
Thread t = threadVar.get();
if (t == null) {
return getValue();
}
try {
t.join();
}
catch (InterruptedException e) {
// propagate
Thread.currentThread().interrupt();
return null;
}
}
}

public SwingWorker() {
final Runnable doFinished = new Runnable() {
public void run() { finished(); }
};

Runnable doConstruct = new Runnable() {
public void run() {
try {
setValue(construct());
}
finally {
threadVar.clear();
}

SwingUtilities.invokeLater(doFinished);
}
};

Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
t.start();
}
}
[/sourcecode]

SwingWorker.java

[sourcecode language='java']
public class Task{
public void go() {
current = 0;
final SwingWorker worker = new SwingWorker() {
public Object construct() {
return new ActualTask();
}
};
}

class ActualTask {
ActualTask() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}
[/sourcecode]

Task.java

Categories: Java, Programming Tags: ,

what's static?

April 14th, 2008 1 comment

First of all, the meaning of static in java is embedded or belong to a specific class not to its instance, and therefore there is no such static class.

  • There is no such static class
  • Embedded or belong to a specific class
  • Global variable
  • No need to load and create its instance

Most of methods and variables in Math class are static, because those are not need to be instanced in most of cases. we just use return value of PI or max(int a, int b).

class Bicycle {

private static int numberOfBicycles = 0;
private int id;

public Bicycle() {
id = ++numberOfBicycles;
}

public static int getNumberOfBicycles() {
return numberOfBicycles;
}
public int getID() {
return id;
}

public static void main(String[] args) {
Bicycle b1 = new Bicycle();
Bicycle b2 = new Bicycle();

System.out.println(“static result : “+getNumberOfBicycles());
System.out.println(“static result : “+numberOfBicycles);
System.out.println(“instance result : “+b1.getID());
System.out.println(“instance result : “+b2.getID());
}
}

Another characteristic of static is that even if we create instance of a class, jvm does not create instance variables for static resources. in above source code, there is no difference calling b1.getNumberOfBicycles(), b2.getNumberOfBicycles() and just getNumberOfBicycles() or directly numberOfBicycles
that mean we should call static variable with its class name because it’s belong to it. just like Bicycle.numberOfBicycles or in this example, getNumberOfBicycles() because we have a getter.
otherwise get confused.

Categories: Programming Tags: , ,

DataSource setup on Tomcat

September 21st, 2007 Comments off

1. create META-INF/context.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<Context docBase=”e-sports” path=”/e-sports” debug=”0″ reloadable=”true”
source=”org.eclipse.jst.j2ee.server:e-sports”>
<Logger className=”org.apache.catalina.logger.FileLogger”
prefix=”e-sports_log.” suffix=”.txt” timestamp=”true” />
<Resource name=”jdbc/myoracle”
auth=”Container”
type=”javax.sql.DataSource”
driverClassName=”oracle.jdbc.driver.OracleDriver”
factory=”org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory”
url=”jdbc:oracle:thin:@127.0.0.1:1521:ORA92″
username=”scott”
password=”tiger”
maxActive=”20″
maxIdle=”10″
maxWait=”-1″ />
</Context>

2. test.jsp
<%@ page import=”java.sql.Connection” %>
<%@ page import=”java.sql.ResultSet” %>
<%@ page import=”java.sql.SQLException” %>
<%@ page import=”java.sql.Statement” %>
<%@ page import=”javax.naming.Context” %>
<%@ page import=”javax.naming.InitialContext” %>
<%@ page import=”javax.naming.NamingException” %>
<%@ page import=”javax.sql.DataSource” %>

<%
Context ctx = null;
DataSource source = null;
Connection con = null;

try {
ctx = new InitialContext();
ctx = (Context) ctx.lookup(“java:comp/env”);
source = (DataSource) ctx.lookup(“jdbc/myoracle”);

System.out.println(“DataSource ===========================”+ source);

con = source.getConnection();
System.out.println(“Connection ============================”+ con);
} catch (NamingException ne) {
ne.printStackTrace();
}
%>

Categories: Server Tags: , , ,

Signed java applet

May 15th, 2007 No comments

Applet Security Basics

Below are the basic facts regarding applet security and Java Plug-in. More detail can be found in the next chapter, How RSA Signed Applet Verification Works in Java Plug-in.

  • All unsigned applets are run under the standard applet security model.
  • If usePolicy IS NOT DEFINED in the java.policy file, then a signed applet has the AllPermission permission if:
    Java Plug-in can verify the signers, and the user, when prompted, agrees to granting the AllPermission permission.
  • If usePolicy IS DEFINED, then a signed applet has only the permissions defined in java.policy and no prompting occurs.

Moreover, note that Java Plug-in now handles certificate management; i.e., the certificate verification task is no longer passed off to the browser.

keytool -genkey -keyalg rsa -alias MyCert
keytool -certreq -alias MyCert
keytool -import -alias MyCert -file VSSStanleyNew.cer

or

keytool -selfcert

and

jarsigner AppletName.jar MyCert
jarsigner -verify -verbose -certs AppletName.jar

Categories: Programming Tags: , , ,

Eclipse web.xml validation problem

February 7th, 2007 No comments

The problem is because of “http://java.sun.com/xml/ns/j2ee/j2ee_1_4.xsd” fil, it points ibm’s schema instead of Sun’s

Window -> Preferences… -> Web and XML -> XML Catalog

URI : http://java.sun.com/xml/ns/j2ee/j2ee_web_services_client_1_1.xsd
Key Type : Schema Location
Key : http://www.ibm.com/webservices/xsd/j2ee_web_services_client_1_1.xsd

Thanks Carey Evans

Categories: Software Tags: , , ,

Java SE 6 Key Features

December 13th, 2006 No comments

New Security Features and Enhancements

  • Native platform Security (GSS/Kerberos) integration.
  • Java Authentication and Authorization Service (JAAS) login module that employs LDAP authentication
  • New Smart Card I/O API
    » Find out more


Integrated Web Services

  • New API for XML digital signature services for secure web services
  • New Client and Core Java Architecture for XML-Web Services (JAX-WS) 2.0 APIs
  • New support for Java Architecture for XML Binding (JAXB) 2.0
    » Find out more


Scripting Language Support (JSR 223)

  • New framework and API for scripting languages
  • Mozilla Rhino engine for JavaScript built into the platform
    » Find out more


Enhanced Management and Serviceability

  • Improved JMX Monitoring API
  • Runtime Support for dTrace (Solaris 10 and future Solaris OS releases only)
  • Improved memory usage analysis and leak detection
    » Find out more


Increased Developer Productivity

  • JDBC 4.0 support (JSR 221)
  • Significant library improvements
  • Improvements to the Java Platform Debug Architecture (JPDA) & JVM Tool Interface


Improved User Experience

  • look-and-feel updates to better match underlying operating system
  • Improved desktop performance and integration
  • Enhanced internationalization support
Categories: Java Tags: ,

String constant pool

November 26th, 2006 17 comments

Everybody knows about String constant pool which is for efficient memory management in java. Basically most of objects are managed on heap area but String object. In most of ordinary application, programmers use String object quite often and this String object quite frequently need to be changed or it occupies large amounts of memory. Therefore instead of managing String object on heap area, they introduced String constant pool.

One of important characteristic of String constant pool is that it doesn’t create same String object if there is already String constant in the pool.

String var1 = “This is String Literal”;
String var2 = “This is String Literal”;

For above two String objects, JVM creates only one object in the String constant pool and for the second string reference variable (var2), it points the string object which is created for var1. In this case, (var1 == var2) is true.

But one thing, people make confused is that. It works only when it encounter on String Literal with double quote.

String var3 = new String(“This is String Literal”);

In this case, a regular object will be created by new keyword on heap area and it will be placed in the String constant pool. Finally it will be assigned to the reference variable, var3. This process is just by passing from String constant pool management. Therefore, (var1 == var3) is false.

Categories: Programming Tags: , ,

"null", is this Object or not?

November 26th, 2006 1 comment

In java, some people say null is Object and they also use “null object” term when they try to explain something related in null like NullPointerException.

And some people simply show “null instanceof Object” result to prove that null is not Object. Of course it returns false for “null instanceof Object”. Because null is technically not Object.

The reason why people keep regarding null as a kind of Object is that they are confused those two terms, Object itself and Reference variable which points an object. Whenever they say “null object”, which means actually reference variable, and that reference variable assigned for a specific bit pattern which is for null.

Categories: Java Tags: , ,

Read all files in a directory

November 17th, 2006 No comments

int fileCount = 0;
File dir = new File(inputDirName);
File[] strFilesDirs = dir.listFiles();

if (strFilesDirs == null) {
System.err.println(inputDirName +” is not valid directory name or there is no pdb file”);
System.exit(1);
}
for (int i=0; i
if (strFilesDirs[i].isDirectory()) {
//System.out.println(“Directory: “+strFilesDirs[i]);
} else if (strFilesDirs[i].isFile()) {
//System.out.println(“File: “+strFilesDirs[i]+”(“+strFilesDirs[i].length()+”)”);
fileCount = fileCount + 1;
}
}

beside, there is no such method which is changing directory.

Categories: Programming Tags: , , ,