Archive for 'Java'

1. Java Class TheTime.java

import java.awt.*;
import javax.swing.*;

public class TheTime {
  public static void main(String args[]) {
    JFrame frame =  new JFrame("Time Check");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel label = new JLabel();
    Container content = frame.getContentPane();
    content.add(label, BorderLayout.CENTER);
    String message = "missing";
    message = "foo";
    label.setText(message);
    frame.pack();
    frame.show();
  }

javac TheTime.java
java TheTime

2. Create a JAR

jar cf JNLPTime.jar TheTime.class
3. Sign the JAR
keytool -genkey -keystore myKeys -alias jdc
jarsigner -keystore myKeys JNLPTime.jar jdc

4. Create JNLP file:

< ?xml version="1.0" encoding="UTF-8"?>
< jnlp spec="1.0+" codebase="file:///var/www/JavaWebStart/jnlp/" >
< information>
  < title>Time Check
  < vendor>nf
  < homepage href="http://www.google.de" />
  < description>desc
< /information>
< offline-allowed/>
< security>
  < j2ee-application-client-permissions/>
< /security>
< resources>
  < j2se version="1.5+" />
  < jar href="JNLPTime.jar"/>
< /resources>
< application-desc main-class="TheTime" />
< /jnlp>

5. Create HTML link

 < a href=time.jnlp>Launch the application< /a>

Tagged with , .

1. Create Connection Factory and Destination Resource in GlassFish admin console:

Resources / JMS Resources / Connection Factory -> New
JNDI-Name: jms/myFactory
Resource-Type: javax.jms.ConnectionFactory
Additional Properties: Remove username and password

Resources / JMS Resources / Destination Resources -> New
JNDI-Name: jms/myQueue
Physical Destination Name: myQueue
Resource Type: javax.jms.Queue

2. Create a new web application in NetBeans, edit index.jsp:

        < title>Send Message to JMS-Queue< /title>
        < form action="sendMessage">
            < table  cellspacing="20" >
                < tbody>
                    < tr>
                        < td>Message:< /td>
                        < td>< input type="text" name="message" value="" width="30" />< /td>
                    < /tr>
                < /tbody>
            < /table>
                < input type="submit" value="Send The message" name="send" />
        < /form>

3. Create new Servlet sendMessage in web application:

package dummy;
import java.io.*;
import javax.jms.*;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class sendMessage extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try{
            Context ctx = new InitialContext();
            ConnectionFactory connectionFactory = (ConnectionFactory)ctx.lookup("jms/myFactory");
            Queue queue = (Queue)ctx.lookup("jms/myQueue");
            javax.jms.Connection connection = connectionFactory.createConnection();
            javax.jms.Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(queue);
            TextMessage message = session.createTextMessage();
            message.setText(request.getParameter("message"));
            messageProducer.send(message);
            out.println("");
            out.println("");
            out.println("");
            out.println("");
            out.println("");
            out.println("
"); out.print("Message " + request.getParameter("message") + " sent to Queue " + queue.getQueueName() +"."); out.println("
"); out.println(""); out.println(""); } catch(Exception ex){ ex.printStackTrace(); } out.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }

Tagged with , , .

1. viPlugin
Name: viPlugin
Site: viplugin.com

2. GlassFish
Plugin Site: http://ajax.dev.java.net/eclipse
GlassFish download: https://glassfish.dev.java.net/downloads/v3-final.html
Servers / New Server / GlassFish v3
Preferences / GlassFish -> start Derby with GlassFish

3. Derby
http://db.apache.org/derby/derby_downloads.html (core & ui) into eclipse/plugins
Data Source Explorer / Database Connections -> New -> Derby
New Driver Definition / Derby Client JDBC Driver

Tagged with , , , .

try {
  BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt", true));  // true defines append to file instead of overwrite
  writer.write("text into file" + "\n");
  writer.close();
} catch (Exception e) {
  System.out.println(e.getMessage());
}

Tagged with , , , , .

Date and Time in Java (0)

January 12th, 2010 by Frank Niedermann, under Java.


import java.util.*;
import java.text.*;

// actual date and time
Date d = new Date();
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String now = f.format(d));

// other time zone
df.setTimeZone(TimeZone.getTimeZone("America/New_York");
String nowNY = f.format(d));

Tagged with , , , .

XML: SAX or DOM? (0)

September 22nd, 2009 by Frank Niedermann, under Java.

There are some differences between the SAX and DOM XML parser. The main difference in one sentence are:

1. SAX reads the XML document once and can react on events but it won’t save the XML structure in memory.

2. DOM reads the XML document and stores it in a tree which allows manipulation or to extract information from the XML document more than once.

SAX is easy and fast, DOM builds a tree and allows manipulation.

Tagged with , , , .

This is how the type of a file can be determined using the extension of the file:

1
2
3
4
5
6
7
8
9
10
public class FileType {
	public static void main(String[] args) {
		String fileName = "foo.pdf";
		String extension = fileName.substring(fileName.lastIndexOf("."));
		System.out.println("Extension: " + extension);
		if (fileName.equalsIgnoreCase(".pdf")) {
			System.out.println("It is a PDF-File.");
		}
	}
}

Tagged with , , , .

1. Generating a key pair (public key + private key) for the server and store those as certificate in the keystore “ServerKeystore”

keytool -genkey -keystore ServerKeystore -alias SSLCertificate -keyalg RSA -validity 360

2. Export the public key of the server and import it into the keystore “ClientKeystore”

keytool -keystore ServerKeystore -export -alias ServerKeystore -file ServerCertificate.crt
keytool -keystore ClientKeystore -import -file ServerCertificate.cer

3. List the contents of the two keystores

keytool -list -keystore ServerKeystore -v
keytool -list -keystore ClientKeystore -v

4. Generate the Java class for the SSLServer

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
 
public class SSLServer implements Runnable {
 
	public static void main(String[] args) {
		ExecutorService executor = Executors.newSingleThreadExecutor();
		executor.execute(new SSLServer());
		System.out.println("Server started on port 7777");
		executor.shutdown();
	}
 
	@Override
	public void run() {
		try {
			// create a server socket and listen on it
			SSLServerSocket serverSocket = (SSLServerSocket) SSLServerSocketFactory
					.getDefault().createServerSocket(7777);
			SSLSocket server = (SSLSocket) serverSocket.accept();
 
			// input and output stream
			InputStream in = server.getInputStream();
			OutputStream out = server.getOutputStream();
 
			// receive data from client and echo it back
			Scanner scanner = new Scanner(in);
			PrintWriter printWriter = new PrintWriter(out);
			String line = null;
			while (scanner.hasNextLine()) {
				line = scanner.nextLine();
				System.out.println("Server received: " + line);
				printWriter.println(line);
				printWriter.flush();
			}
			scanner.close();
			server.close();
			serverSocket.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

5. Generate the Java class for the SSLClient

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
 
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
 
public class SSLClient {
 
	public static void main(String[] args) {
 
		try {
			// create a client socket and connect to server
			SSLSocket client = (SSLSocket) SSLSocketFactory.getDefault()
					.createSocket("localhost", 7777);
 
			// output stream to server
			OutputStream out = client.getOutputStream();
 
			// input stream for user input
			InputStream in = System.in;
			InputStreamReader reader = new InputStreamReader(in);
			BufferedReader breader = new BufferedReader(reader);
 
			// send data to server
			PrintWriter printWriter = new PrintWriter(out);
			String line = null;
			while ((line = breader.readLine()) != null) {
				printWriter.println(line);
				printWriter.flush();
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

6. Run the SSLServer and SSLClient classes with the following JRE parameters

SSLServer: -Djavax.net.debug=all -Djavax.net.ssl.keyStore="/path/to/ServerKeystore"  -Djavax.net.ssl.keyStorePassword=serverKeystorePassword
SSLClient: -Djavax.net.debug=all -Djavax.net.ssl.trustStore="/path/to/ClientKeystore" -Djavax.net.ssl.trustStorePassword=clientKeystorePassword

Using -Djavax.net.debug=all as additional JRE parameter will print some debug information.

Tagged with , , , , , .

WebService with Java 6 (0)

March 23rd, 2009 by Frank Niedermann, under Java.

It is possible to create a WebService and a WebClient with Java 6. This is a Hello World example how to do so.

There will be the following Java Classes:

WebService:
– Hello.java: This is the Class which contains the logic that will serve as WebService
– HelloServer.java: This is the Class which will start a server and publish the WebService

WebClient:
– Hello.java: This Class will automatically be created by the wsimport tool
– HelloService.java: This Class will also automatically be created by the wsimport tool
– HelloClient.java: This is the Class which will act as WebClient connecting to the WebService

Creating the WebService

1. Declare a Java Class as WebService using Annotation @WebService:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package webservice;
 
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
 
@WebService
@SOAPBinding(style=Style.RPC)
public class Hello {
	public String returnHello(String name) {
		System.out.println("Service: generating response String");
		return "Hello " + name + "!";
	}
}

2. Create the Java Class that publishes the WebService as server:

1
2
3
4
5
6
7
8
9
10
11
package webservice;
 
import webservice.Hello;
import javax.xml.ws.Endpoint;
 
public class HelloServer {
	public static void main(String[] args) {
		Hello server = new Hello();
		Endpoint endpoint = Endpoint.publish("http://localhost:8080/hello", server);
	}
}

After starting this server it’s possible to view the WSDL: http://localhost:8080/hello?wsdl

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
33
34
<?xml version="1.0" encoding="UTF-8"?>
<!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.1 in JDK 6. -->
<!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.1 in JDK 6. --><definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://webservice/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://webservice/" name="HelloService">
<types></types>
<message name="returnHello">
<part name="arg0" type="xsd:string"></part>
</message>
<message name="returnHelloResponse">
<part name="return" type="xsd:string"></part>
</message>
<portType name="Hello">
<operation name="returnHello" parameterOrder="arg0">
<input message="tns:returnHello"></input>
<output message="tns:returnHelloResponse"></output>
</operation>
</portType>
<binding name="HelloPortBinding" type="tns:Hello">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"></soap:binding>
<operation name="returnHello">
<soap:operation soapAction=""></soap:operation>
<input>
<soap:body use="literal" namespace="http://webservice/"></soap:body>
</input>
<output>
<soap:body use="literal" namespace="http://webservice/"></soap:body>
</output>
</operation>
</binding>
<service name="HelloService">
<port name="HelloPort" binding="tns:HelloPortBinding">
<soap:address location="http://localhost:8080/hello"></soap:address>
</port>
</service>
</definitions>

That’s it – the WebService is running.

Creating a WebClient

1. Automatic generation of the necessary files for the WebClient
To tool wsimport will generate the necessary Class files for the WebClient according to a given WSDL file:

1
wsimport -keep http://localhost:8080/hello?wsdl

The -keep parameter will tell wsimport to keep the Java sourcecode files and not only the binary code.

2. Create the Java Class that will act as WebClient and connect to the WebService:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package webclient;
 
import webclient.Hello;
import webclient.HelloService;
 
public class HelloClient {
 
	public static void main(String[] args) {
		HelloService service = new HelloService();
		Hello hello = service.getHelloPort();
		System.out.println("Response: " + hello.returnHello("Joe"));
	}
 
}

Running this Class will connect to the WebService which can be seen on the console:
WebService: Service: generating response String
WebClient: Response: Hello Joe!

Tagged with , , , , .

Of course it’s possible to use Apache Derby as database for Java apps without Eclipse:

1. Download and extract Apache Derby

http://apache.atviraskodas.com/db/derby/db-derby-10.4.2.0/db-derby-10.4.2.0-bin.zip

2. Start Apache Derby database: bin/startNetworkServer.bat

3. Create database: bin/ij.bat

1
connect 'jdbc:derby://localhost:1527/myDB;create=true;user=user1;password=user1';

4. Insert some values into database:

1
2
3
4
5
CREATE TABLE restaurants(id integer, name varchar(20), city varchar(50));
INSERT INTO restaurants VALUES (1, 'Irifunes', 'San Mateo');
INSERT INTO restaurants VALUES (2, 'Estradas', 'Daly City');
INSERT INTO restaurants VALUES (3, 'Prime Rib House', 'San Francisco');
SELECT * FROM restaurants;

5. Create new Java Class, example code:

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
33
34
35
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
 
public class Restaurants {
  private static String url = "jdbc:derby://localhost:1527/myDB;create=true;user=user1;password=user1";
  private static String table = "restaurants";
  private static Connection con = null;
  private static Statement stmt = null;
 
  public static void main(String[] args) {
    try {
      Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
      con = DriverManager.getConnection(url);
      stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("select * from " + table);
      ResultSetMetaData rsmd = rs.getMetaData();
      int cols = rsmd.getColumnCount();
      for (int i=1; i<=cols; i++) {
      System.out.print(rsmd.getColumnLabel(i) + "\t\t");
    }
    System.out.println("\n----------------------------------------");
    while (rs.next()) {
      System.out.println(rs.getInt("ID") + "\t\t" +  rs.getString("NAME") + "\t\t" + rs.getString("CITY"));
    }
    rs.close();
    stmt.close();
    con.close();
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
    }
  }
}

6. Compile Java Class:
javac.exe -classpath .;derby.jar;derbyclient.jar;derbynet.jar;derbytools.jar Restaurants.java

7. Run Java Class:
java.exe -classpath .;derby.jar;derbyclient.jar;derbynet.jar;derbytools.jar Restaurants
ID NAME CITY
—————————————-
1 Irifunes San Mateo
2 Estradas Daly City
3 Prime Rib House San Francisco

That’s it.

It’s also possible with Derby to share a database. After creation and inserting data just copy the file bin/myDB (myDB is the name of the database) to another Derby bin directory – done.

Tagged with , , , .