Author Archive

Serializing an Object in Java

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.


//Employee class

class Employee implements java.io.Serializable
{
public String name;
public String address;
public String city;
public int id;
}

import java.io.*;

public class SerializeDemo
{
public static void main(String [] args)
{
Employee emp = new Employee();
emp.name = "Rajeev Pillai";
emp.address = "292, PTP Nagar";
emp.city = "Trivandrum";
emp.id = 1000;

//Serialize
try {
ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("employee.ser"));
out.writeObject(emp);
out.close();
System.out.printf("Serialized data is saved");

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

In this example we are using ListUtils.union() function to join two lists

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.ListUtils;

public class JoinListsExample2 {

public static void main(String[] args) {

List<String> listA = new ArrayList<String>();
listA.add("One");
listA.add("two");
listA.add("three");
listA.add("four");
listA.add("five");

List<String> listB = new ArrayList<String>();
listB.add("Six");
listB.add("Seven");
listB.add("eight");
listB.add("nine");
listB.add("ten");

List<String> listAB = ListUtils.union(listA, listB);

System.out.println("listA : "  + listA);
System.out.println("listB : "  + listB);
System.out.println("listAB : " + listAB);

}

}

How to convert String to InputStream in Java

A simple Java program to convert a String to InputStream, and use BufferedReader to read and display the converted InputStream.

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StringToInputStreamExample {
public static void main(String[] args) throws IOException {

String line;
String str = "Welcome to Schogini Systems";

// convert String into InputStream
InputStream is = new ByteArrayInputStream(str.getBytes());

// read it with BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(is));

while ((line = br.readLine()) != null) {
System.out.println(line);
}

br.close();
}
}

How to convert array of bytes into File in Java

The Java.io.FileOutputStream can used to convert an array of bytes into a file. In this example, you read a file from “C:\\myfile1.txt”, and convert it into an array of bytes, and write it into another file “C:\\myfile2.txt”.
package com.schogini.arrayByteToFile

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ArrayOfBytesToFile
{
public static void main ( String[] args )
{
FileInputStream fileInputStream = null;

File file = new File ( "C:\\myfile1.txt" );

byte[] bFile = new byte [ (int) file.length() ];

try {
//convert file into array of bytes
fileInputStream = new FileInputStream ( file );
fileInputStream.read ( bFile );
fileInputStream.close();

//convert array of bytes into file
FileOutputStream fileOuputStream =
new FileOutputStream ( "C:\\myfile2.txt" );
fileOuputStream.write ( bFile );
fileOuputStream.close();

System.out.println ( "Completed" );
} catch ( Exception e ) {
e.printStackTrace();
}
}
}

BufferedReader example in JDK 7

In JDK 7, can use new feature try-with-resources to close file automatically.

package com.schogini.bufferedReaderExample;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {

public static void main(String[] args) {

try (BufferedReader br = new BufferedReader(new FileReader("C:\\myfile.txt")))
{

String sCurrentLine;

while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}

} catch (IOException e) {
e.printStackTrace();
}

}
}

To draws a quadratic Bezier curve from one point to another in HTML5, the quadraticCurveTo() is used. The quadraticCurveTo() function draws a quadratic Bezier curve from one point to another. The curve is controlled by a single control point. Example:

context.lineWidth = 5;

var fromX = 50;
var fromY = 50;
var toX   = 100;
var toY   = 50;
var cpX   = 75;
var cpY   = 100;

context.beginPath();
context.moveTo(fromX, fromY);
context.quadraticCurveTo(cpX, cpY, toX, toY);
context.stroke();
context.closePath();

Beginning and Closing a Path in HTML5

An HTML5 Canvas path is a series of points with drawing instructions between those points. For instance, a series of points with lines between them, or with arcs between them. Paths are used to draw many types of shapes such as lines, circles, polygons etc. on an HTML5 canvas.

The following example will draw two triangles:


context.beginPath();
context.moveTo(10,10);
context.lineTo(60,50);
context.lineTo(110,50);
context.lineTo(10,10);
context.stroke();
context.closePath();

context.beginPath();
context.moveTo(100,10);
context.lineTo(150,50);
context.lineTo(200,50);
context.lineTo(100,10);
context.fill();
context.closePath();

Drawing shapes with OpenGL ES in Android

In our next example, you’ll use OpenGL ES to create a simple drawing, a rectangle, using OpenGL primitives, which are pixels, polygons, and triangles. When you draw the square, you’ll use a primitive called the GL_Triangle_Strip, which takes three vertices (the x, y, and z points in an array of vertices) and draws a triangle. The last two vertices become the first two vertices for the next triangle, with the next vertex in the array being the final point. This process repeats for as many vertices as there are in the array, where two triangles are drawn. OpenGL supports a small set of primitives, that allow you to build anything using simple geometric shapes, from a rectangle to 3D models of animated characters.

OpenGL primitives and their descriptions:
GL_LINE_LOOP: Draws a continuous set of lines. After the first vertex, it draws a line between every successive vertex and the vertex before it. Then it connects the start and end vertices.
GL_LINE_STRIP: Draws a continuous set of lines. After the first vertex, it draws a line between every successive vertex and the vertex before it.
GL_LINES: Draws a line for every pair of vertices given.
GL_POINTS: Places a point at each vertex.
GL_TRIANGLE_FAN: After the first two vertices, every successive vertex uses the previous vertex and the first vertex to draw a triangle. This flag is used to draw cone-like shapes.
GL_TRIANGLE_STRIP: After the first two vertices, every successive vertex uses the previous two vertices to draw a triangle.
GL_TRIANGLES: For every triplet of vertices, it draws a triangle with corners specified by the coordinates of the vertices.

In the next listing, we use an array of vertices to define a square to paint on our surface. To use the code, insert it directly into the code for immediately below the commented line:

// do whatever drawing here

gl.glClear(GL10.GL_COLOR_BUFFER_BIT |
GL10.GL_DEPTH_BUFFER_BIT);
float[] square = new float[] {
0.25f, 0.25f, 0.0f,
0.75f, 0.25f, 0.0f,
0.25f, 0.75f, 0.0f,
0.75f, 0.75f, 0.0f };
FloatBuffer squareBuff;
ByteBuffer bb =
ByteBuffer.allocateDirect(square.length*4);
bb.order(ByteOrder.nativeOrder());
squareBuff = bb.asFloatBuffer();
squareBuff.put(square);
squareBuff.position(0);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluOrtho2D(gl, 0.0f,1.2f,0.0f,1.0f);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, squareBuff);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glColor4f(0,1,1,1);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

This code is dense with OpenGL commands. The first thing we do is clear the screen using glClear, which you want to do before every drawing. Then we build the array that’ll represent the set of vertices that make up our square. As we explained before, we’ll be using the OpenGL primitive GL_TRANGLE_STRIP to create the rectangle, where the first set of three vertices (points 1, 2, and 3) represent the first triangle. The last vertex represents the third vertex (point 4) in the second triangle, which reuses vertices 2 and 3 from the first triangle as its first two to make the triangle described by points 2, 3, and 4. To put it more succinctly, Open GL takes one triangle and flips it over on its third side (in this case, the hypotenuse). We then create a buffer to hold that same square data. We also tell the system that we’ll be using a GL_PROJECTION for our matrix mode, which is a type of matrix transformation that’s applied to every point in the matrix stack. The next things we do are more related to setup. We load the identity matrix and then use the gluOrtho2D(GL10 gl, float left, float right, float bottom, float top) command to set the clipping planes that are mapped to the lower-left and upperright corners of the window.

Now we’re ready to start drawing our image. First, we use the glVertex-Pointer(int size, int type, int stride, pointer to array) method, which indicates the location of vertices for our triangle strip. The method has four attributes: size, type, stride, and pointer. The size attribute specifies the number of coordinates per vertex (for example, a 2D shape might ignore the z axis and use only two coordinates per vertex), type defines the data type to be used (GL_BYTE, GL_SHORT, GL_FLOAT, and so on). stride specifies the offset between consecutive vertices (how many unused values exist between the end of the current vertex and the beginning of the next), and pointer is a reference to the array. Though most drawing in OpenGL ES is performed by using various forms of arrays such as the vertex array, they’re all disabled by default to save system resources. To enable them, we use the OpenGL command glEnableClientState(array type), which accepts an array type; in our case the type is GL_VERTEX_ARRAY. Finally, we use the glDrawArrays function to render our arrays into the OpenGL primitives and create our simple drawing. The glDrawArrays (mode, first, count) function has three attributes:
mode indicates which primitive to render, such as GL_TRIANGLE_STRIP; first is the starting index of the array, which we set to 0 because we
want it to render all the vertices in the array; and count specifies the number of indices to be rendered, which for us is 4.

 

A secure oracle database connection application example
import java.sql.*;
import java.util.*;
public class TestDataEncryptionIntegrity {
public static void main ( String[] argv )
throws Exception {
DriverManager.registerDriver ( new oracle.jdbc.driver.OracleDriver( ) );
Properties prop = new Properties( );
prop.setProperty ( “user”, “scott” );
prop.setProperty ( “password”, “tiger” );
prop.setProperty ( “oracle.net.encryption_client”, “REQUIRED” );
prop.setProperty ( “oracle.net.encryption_types_client”, “( RC4_40 )” );
prop.setProperty ( “oracle.net.crypto_checksum_client”, “REQUIRED” );
prop.setProperty ( “oracle.net.crypto_checksum_types_client”, “( MD5)” );
Connection conn = DriverManager.getConnection(“jdbc:oracle:thin:@dssw2k01:1521:orcl”, prop);
Statement stmt = conn.createStatement( );
ResultSet rset = stmt.executeQuery(“select ‘Hello Thin driver Encryption & Integrity ” + “tester ‘||USER||’!’ result from dual”);
while(rset.next( ))
System.out.println(rset.getString(1));
rset.close( );
stmt.close( );
conn.close( );
}
}

First, the program loads the Oracle Thin driver using the DriverManager.registerDriver() method. This method is chosen because the use of encryption and integrity is definitely an Oracle extension, and therefore not portable. So why be concerned about using the Class.forName( ) method, along with the extra coding that it requires, when portability is no longer a concern?
Second, the program creates a Properties object named prop and then adds the required
properties. It adds the user and password properties because the form of getConnection( ) used with a Properties object does not take them as separate parameters. The program then adds the oracle.net.encryption_client and
oracle.net.encryption_types_client properties to require 40-bit encryption. Next, the program adds oracle.net.crypto_checksum_client and
oracle.net.crypto_checksum_types_client properties to require that MD5 message digests be added to each packet.

Third, the program calls the getConnection(String url, Properties info) form of the getConnection( ) method. Then it finishes up in a manner similar to our previous connection examples by querying the database. This is the kind of secured connection you would most likely make for an applet. Alternatively, if you use an application or servlet, you would most likely use the OCI driver, in which case, all these settings would be transparent to the program because
they would be set in the Oracle Client’s sqlnet.ora file.

Cached connection example in Java

The following Java code will show you how to implement cached connection:

import java.sql.*;
public class CachedConnection {
private boolean inUse;
private Connection conn;
private long lastUsed;
private String baseName;
public CachedConnection ( )  {
conn = null;
inUse = false;
lastUsed = System.currentTimeMillis ( );
baseName = “Database”;
}
public CachedConnection ( Connection conn, boolean inUse )  {
this.conn = conn;
this.inUse = inUse;
this.lastUsed = System.currentTimeMillis ( );
this.baseName = “Database”;
}
public CachedConnection ( Connection conn, boolean inUse, String
baseName )  {
this.conn = conn;
this.inUse = inUse;
this.lastUsed = System.currentTimeMillis ( );
this.baseName = baseName;
}
public Connection getConnection ( )  {
return conn;
}
public void setConnection ( Connection conn ) {
this.conn = conn;
}
public boolean getInUse ( )  {
return inUse;
}
public boolean isInUse ( ) {
return inUse;
}
public void setInUse ( boolean inUse )  {
if ( !inUse )
lastUsed = System.currentTimeMillis ( );
this.inUse = inUse;
}
public String getBaseName ( )  {
return baseName;
}
public void setBaseName ( String baseName )  {
this.baseName = baseName;
}
public long getLastUsed ( )  {
return lastUsed;
}
}

A CachedConnection object has the following four attributes:
inUse A boolean that keeps track of whether the connection is in use. A value of true indicates that the connection has been checked out by a servlet. A value of false indicates that the connection is available.
conn A JDBC Connection object that is cached in the pool.
lastUsed A long that holds the time the connection was last checked out. This is used by the management class to determine when to close and remove from the cache connections that have not been used in a predetermined period of time.
baseName A String object that holds the name of the pool to which this connection belongs. This allows you to manage several different connection pools simultaneously. The CachedConnection class’s isInUse( ) method is a function you can use in a logical statement to check if the connection is in use. The rest of the methods are getter-setter methods for the class.

Page 2 of 5512345...102030...Last »
We Can Build Your App for You. Lets Get Started !