Remove Search Protect by Conduit

Hopefully this will help someone else. I think this was installed by foxit reader.

Quick Solution:
1. Click start, type command, right click on the command prompt icon and click run as administrator.
2. In the command prompt type: sc delete CltMngSvc
3. I’d recommend restoring chrome defaults and rebooting your computer
If that is not successful the service name may be different or you may have to manually delete it. To find the service name follow steps 1 and 2 of the Manual solution for Windows 7.

Manual Solution for Windows 7:
First check to see if the service is running on your computer:
1. click start, type msconfig in the search box and press enter. Once the msconfig dialog opens, click on the services tab, then check the box that says hide all Microsoft Services. Uncheck the Search Protect By Conduit box, click Apply and then click Okay. Exit without restarting.
2. Click start, type services.msc in the search box and press enter. Once the services dialog opens up, scroll down and right click on the Search Protect By Conduit. Select properties, then copy the path to executable. For example mine said: C:\PROGRA~2\SearchProtect\Main\bin\CltMngSvc.exe. While in the properties dialog also click stop, to stop the service since it is probably still running.
3. Click start, type regedit and press enter. This will load up the Windows Registry Editor. Inside of the registry editor we will search for all occurences of the Search Protect By Conduit executable found in step 3. For example mine said: CltMngSvc.exe. Delete the registry key that contains that executable name. After that is done, goto the directory we found in step 2 and delete the SearchProtect folder. I.e navgate to C:\PROGRA~2\ and ONLY delete SearchProtect.
4. I’d recommend restoring chrome defaults and rebooting your computer

Comments Trackbacks / Pingbacks (123)

Polymophic messages with Jboss’s Netty and Google’s Protocol Buffers.

First I want to give credit where due to: http://www.indelible.org/ink/protobuf-polymorphism/

I recently restarted working on my client/server architecture for Dunya. I decided to use protobuf to handle message generation since ideally my clients will be open and written in either C++, Java, or [your language here...].

I wanted an Abstract message type that could be extended by more specific types. For more detailed information on how to get this working in protobuf see the link above, or just look at my .proto file below. Now I will show you how to properly setup your pipeline to decode protobuf messages, how to construct and send the polymorphic message, and how to go about handling it in your Channel Handler. This is a great improvement over my previous implementation, because it is now easier to use cross language.
Protobuf definition

 
package request;

option java_package = "com.dunyaonline.communication.messages.requests";
option java_outer_classname = "AbstractRequestProtos";

message AbstractRequest {
	extensions 100 to 115;
	enum Type {
		NewCharRequest = 0;
		CharListRequest = 1;
	}
	required Type type = 1;
}

message CharListRequest {
	extend AbstractRequest {
		required CharListRequest request = 100;
	}
	required int32 userid = 1;
	required int32 world = 2;
}

message NewCharRequest {
        extend AbstractRequest{
		required NewCharRequest request = 101;
	}
	required string name = 1;
	required int32 userid = 2;
}

Client Message Initialization and Send

public void getCharacterList() {
	AbstractRequestProtos.CharListRequest clr = AbstractRequestProtos.CharListRequest
			.newBuilder().setUserid(12345).setWorld(6789).build();
	AbstractRequest ar = AbstractRequest
			.newBuilder()
			.setType(AbstractRequest.Type.CharListRequest)
			.setExtension(AbstractRequestProtos.CharListRequest.request,
					clr).build();
	cmService.sendMessage(ar);
}

public ChannelFuture sendMessage(Object obj) {
		return channel.write(obj);
}

Server Network Initialization

	private void initNetwork() {
		ChannelFactory factory = new NioServerSocketChannelFactory(
				Executors.newCachedThreadPool(),
				Executors.newCachedThreadPool());

		ServerBootstrap bootstrap = new ServerBootstrap(factory);
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline pipeline = Channels.pipeline();
				
				// Decoder
				pipeline.addLast("frameDecoder",
						new ProtobufVarint32FrameDecoder());

				pipeline.addLast(
						"ProtoCharacterListRequestDecoder",
						new ProtobufDecoder(
								AbstractRequestProtos.AbstractRequest
										.getDefaultInstance()));
				// Encoder
				pipeline.addLast("frameEncoder",
						new ProtobufVarint32LengthFieldPrepender());
				pipeline.addLast("protobufEncoder", new ProtobufEncoder());
				pipeline.addLast("handler", new ServerMessageHandler());
				return pipeline;
			}
		});

		bootstrap.setOption("child.tcpNoDelay", true);
		bootstrap.setOption("child.keepAlive", true);
		bootstrap.bind(new InetSocketAddress(PORT));
	}
}

Handler

public class ServerMessageHandler extends SimpleChannelHandler {

	private Logger LOGGER = Logger.getLogger(ServerMessageHandler.class);
	
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		super.messageReceived(ctx, e);
		AbstractRequest r = (AbstractRequest) e.getMessage();
		if(r.getType().getNumber() == AbstractRequest.Type.NewCharRequest_VALUE)
		{
			LOGGER.info(NewCharacterRequest.class.getName() + ": " + e.getMessage());
			
		}else if(r.getType().getNumber() == AbstractRequest.Type.CharListRequest_VALUE)
		{
			LOGGER.info(CharacterListRequest.class.getName() + ": " + e.getMessage());
                        ByteString str = r.getUnknownFields()
					.getField(CharListRequest.REQUEST_FIELD_NUMBER)
					.getLengthDelimitedList().get(0);
			CharListRequest clr = CharListRequest.parseFrom(str);
			
                        // Now you have an instance of CharListRequest and can invoke its getters:
                        getPlayerCharacters(clr.getUserid(), clr.getWorld());
		}else{
			LOGGER.info(ctx.getChannel().getRemoteAddress() + ": " + e.getMessage());
		}
	}
}

Comments Trackbacks / Pingbacks (17)

Google Protocol Buffers + Maven + Eclipse

I had a hard time figuring out just how to “easily” add Google protobuf into my eclipse maven project. Here is a complete pom.xml from my commons project for the Dunya mmo. The only dependencies you will need is com.google.protobuf (see the last entry). I hope this helps someone else who is looking to play with protobuf + maven + eclipse. Running a maven install will build .proto files located in src/main/protobuf.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.dunyaonline.commons</groupId>
    <artifactId>dunya-commons</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <url>http://repository.jboss.org/maven2</url>
    <name>Dunya Commons</name>
    <pluginRepositories>
        <pluginRepository>
            <id>protoc-plugin</id>
            <url>http://sergei-ivanov.github.com/maven-protoc-plugin/repo/releases/</url>
        </pluginRepository>
    </pluginRepositories>
    <build>
        <plugins>
            <plugin>
                <groupId>com.github.igor-petruk.protobuf</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.jboss.netty</groupId>
            <artifactId>netty</artifactId>
            <version>3.2.9.Final</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.28</version>
        </dependency>
        <!-- Hibernate library dependecy start -->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>

        <!-- Hibernate framework -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.2.5.Final</version>
        </dependency>

        <!-- Hibernate library dependecy end -->
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>

        <!--Hibernate JPA Persistence -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Draft-16</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- Google Protocol Buffer -->
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>2.4.1</version>
        </dependency>
    </dependencies>
</project>
</code>

Comments Trackbacks / Pingbacks (7)

Example of writing objects with Netty

I’m developing a simple message passing interface in Java using JBoss’s Netty API. During the design phase I considered two options. The first option is quite primitive and was simply a constants file containing public integers that mapped to a particular message type. This way seemed efficient, but may not scale so well and will be annoying to maintain. The second option was to design a base Message class that will be extended by custom message types. This was the option I chose. Here is a small example of how it works.


package com.dunyaonline.communication.messages;

import java.nio.ByteBuffer;

public abstract class Message {

	protected int clientId;
	
	protected int characterId;

	public abstract int getMessageType();

	public abstract ByteBuffer toByteBuffer();
	
	public static final int CLIENT_ID_OFFSET = 1;
	
	public static final int CHAR_ID_OFFSET = 2;
	
	public Message() {

	}

	public Message(int id) {
		this.clientId = id;
	}
	
	/**
	 * 
	 * @param clientId the id of the remote client.
	 * @param charId the id of the remote clients current selected character
	 */
	public Message(int clientId, int charId) {
		this.clientId = clientId;
		this.characterId = clientId;
	}

	public int getClientId() {
		return clientId;
	}

	public void setClientId(int clientId) {
		this.clientId = clientId;
	}

	public int getCharacterId() {
		return characterId;
	}

	public void setCharacterId(int characterId) {
		this.characterId = characterId;
	}
}

package com.dunyaonline.communication.messages.requests;

import java.io.Serializable;
import java.nio.ByteBuffer;

import com.dunyaonline.communication.MessageTypes;
import com.dunyaonline.communication.messages.Message;

public class LoadCharacterRequest extends Message implements Serializable {

	public static final int TYPE = MessageTypes.CHAR_SELECTION_TYPE;

	private static final long serialVersionUID = -1718878638687805906L;

	public LoadCharacterRequest(int id) {
		super(id);
	}

	/**
	 * 
	 * @param clientId the id of the remote client.
	 * @param charId the id of the remote clients current selected character
	 */
	public LoadCharacterRequest(int clientId, int charId) {
		super(clientId, charId);
	}

	public LoadCharacterRequest(String[] messageArray) {
		clientId = Integer.parseInt(messageArray[CLIENT_ID_OFFSET]);
		characterId = Integer.parseInt(messageArray[CHAR_ID_OFFSET]);
	}

	public int getMessageType() {
		return TYPE;
	}

	/**
	 * Prepare message for custom serialization
	 */
	public ByteBuffer toByteBuffer() {
		StringBuilder outputString = new StringBuilder();
		outputString.append(TYPE + "#" + clientId + "#" + characterId + "\r\n");
		ByteBuffer bb = ByteBuffer.wrap(outputString.toString().getBytes());
		return bb;
	}
}

Once the message is instantiated, it can be sent over an ordinary Channel by invoking the channel.write(Object);. For the sake of brevity I will only demonstrate how the Channel is setup and which pipelines to use (Note: For the sake of simplicity I am using a deprecated Object).


public void initNIOSocketChannel() {
	ChannelFactory factory = new NioClientSocketChannelFactory(
			Executors.newCachedThreadPool(),
			Executors.newCachedThreadPool());
	ClientBootstrap bootStrap = new ClientBootstrap(factory);
	bootStrap.setPipelineFactory(new ClientPipelineFactory());
	ChannelPipeline pipeline = Channels.pipeline();

	pipeline.addLast("encoder", new ObjectEncoder());
	pipeline.addLast("decoder", new ObjectDecoder());
	pipeline.addLast("clientchannelhandler", handler);
	bootStrap.setPipeline(pipeline);
	clientMessageService.setChannel(bootStrap
			.connect(new InetSocketAddress("localhost", 7555))
			.awaitUninterruptibly().getChannel());
}

The ObjectEncoder and ObjectDecoder are provided by Netty and automatically handle serializing and deserializing the object to and from a ChannelBuffer.

The receiving end of the message will also need an identical pipeline setup. In the case of this example, it is a Client/Server relationship.


private void initNetwork() {
	messageService = new MessageService();
	ChannelFactory factory = new NioServerSocketChannelFactory(
			Executors.newCachedThreadPool(),
			Executors.newCachedThreadPool());

	ServerBootstrap bootstrap = new ServerBootstrap(factory);
	zoneServerHandler = new MessageChannelHandler();
	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() throws Exception {
			return Channels.pipeline(new ObjectEncoder(),
					new ObjectDecoder(), zoneServerHandler);
		}
});
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
messageService.addChannel(bootstrap.bind(new InetSocketAddress(PORT)));
messageService.setServerHandler(zoneServerHandler);

Note: I did not include an ObjectEncoder for the Server side, which means that the server will not be writing Objects back out to the client. If you want to add an encoder, simply mimic the client side pipeline setup, or consult Netty’s documentation.

Now that this is complete, I will show you how I handle messages on the server side.


private void processMessages(Queue messageQueue) {
	for (int i = 0; i < messageQueue.size(); ++i) {
		if (messageQueue.peek() == null)
			return;

		MessageEvent e = messageQueue.poll();
		if (e.getMessage() instanceof LoadCharacterRequest) {

		}else if(e.getMessage() instanceof ZoneListRequest)
		{

		}else if(e.getMessage() instanceof ZoneSelectedRequest)
		{

		}
	}
}

Notice, that once a message has been encoded, sent, received and decoded, the receiving end has a POJO and we can use the instanceof operator to determine the message type and direct program flow accordingly. This method leaves the source code in a much more readable and maintainable state.

Comments Trackbacks / Pingbacks (16)

Leptonica: Cosine Similarity for Pix comparison

Lately I have been researching various methods of image comparison and classification. One simple method that is often used for comparing documents is known as cosine similarity. The cosine similarity is simply the dot product of two vectors divided by their euclidean norms multiplied. Wikipedia has more information on the actual definition.


double cosineSimilarity(Pix* pixA, Pix* pixB) {
	double numerator = 0.0;
	double denominator_A = 0.0;
	double denominator_B = 0.0;
	double denominator = 0.0;
	int width = 0;
	int height = 0;
	getSmallestDimensions(pixA, pixB, width, height);

	l_uint8** linePtrs_A = (l_uint8**) pixGetLinePtrs(pixA, NULL);
	l_uint8** linePtrs_B = (l_uint8**) pixGetLinePtrs(pixB, NULL);
	volatile l_uint8 val_A, val_B;

	// sum of A * B
	for (int i = 0; i < height; ++i) {
		l_uint8 *line_A = linePtrs_A[i];
		l_uint8 *line_B = linePtrs_B[i];
		for (int k = 0; k < width; ++k) {
			val_A = line_A[k] & 0x1;
			val_B = line_B[k] & 0x1;
			numerator += val_A * val_B;
		}
	}

	for (int i = 0; i < height; ++i) {
		l_uint8 *line_A = linePtrs_A[i];
		l_uint8 *line_B = linePtrs_B[i];
		for (int k = 0; k < width; ++k) {
			val_A = ((int) (line_A[k] & 0x1), 2);
			val_B = ((int) (line_B[k] & 0x1), 2);
			denominator_A += val_A;
			denominator_B += val_B;
		}
	}
	denominator = sqrt(denominator_A) * sqrt(denominator_B);
	return numerator / denominator;
}

void getSmallestDimensions(Pix* pixA, Pix* pixB, int &width, int &height) {
	int w1 = 0.0;
	int w2 = 0.0;
	int h1 = 0.0;
	int h2 = 0.0;

	pixGetDimensions(pixA, &w1, &h1, NULL);
	pixGetDimensions(pixA, &w2, &h2, NULL);

	if (w1 < w2) {
		width = w1;
	} else {
		width = w2;
	}
	if (h1 < h2) {
		height = h1;
	} else {
		height = h2;
	}
}

Comments Trackbacks / Pingbacks (139)

Weka Arff Generator

Recently I have been playing around with the weka engine. For those who have never heard of weka, it is a collection of algorithms used in various types of analysis including data mining, machine learning, biological research etc.

My purpose for using weka was quite trivial, and simply involved using intraday tick data to observe stock patterns. The hardest part by far was obtaining tick data. Please read the comments in the code for information on how to obtain the stock data.


import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * Author: Ronald Grant  
This file parses the stock data into a arff format. * File does one category at a time. Output has to be * manually copied and pasted into arff file.
*

Usage: This program is designed specifically for parsing tick data obtained from http://hopey.netfonds.no
* Tick data can be downloaded from the following link:
* http://hopey.netfonds.no/tradedump.php?date=201212/05&paper=GOOG.O&csv_format=txt

* The link above is for Google Nasdaq: GOOG for the date 12-05-2012
* Data for the last 5 trading days is usually available for Nasdaq stocks.
* All tick files should be saved as .txt files in a folder specifically designated to hold the tick data files.
* It is recommended that the folder does not contain any other files, other than the txt files to be parsed.

*/ class ArffGenerator { private static String txtDir = "C:/Users/rgrant/school/datamining/projectb/stockdata/"; private static StringBuilder outfileName; private static StringBuilder testOutfileName; private static FileReader fr = null; private static BufferedReader dis = null; private static File outputFile; private static File testOutputFile; private static FileOutputStream fos; private static FileOutputStream testFos; private static OutputStreamWriter out; private static OutputStreamWriter testOut; private static boolean randomValues; public static void main(String[] args) throws IOException { File directory = new File(txtDir); File[] files = directory.listFiles(new Filter()); for (File file : files) { System.out.print("Generating Arff files for: " + file.getName() + "..."); printHeader(file.getName()); fr = new FileReader(file); dis = new BufferedReader(fr); String line; StringBuilder arffData = new StringBuilder(); StringBuilder arffTestData = new StringBuilder(); dis.readLine(); // get rid of header String[] dataArray; while ((line = dis.readLine()) != null) { dataArray = line.replaceAll("\\t", ",").replaceAll(",,,", "").split(","); for (int i = 0; i 0 && i < 2) { arffData.append(dataArray[i] + ","); if (randomValues) { if (Math.random() * 3 = 2) { arffData.append(dataArray[i] + "\n"); if (randomValues) { if (Math.random() * 2 < 1) { arffTestData.append(dataArray[i] + "\n"); } else { arffTestData.append("?\n"); } } else { arffTestData.append("?\n"); } } } } out.write(arffData.toString()); out.flush(); out.close(); testOut.write(arffTestData.toString()); testOut.flush(); testOut.close(); System.out.print("Done\n"); } } public static void printHeader(String filename) throws IOException { outfileName = new StringBuilder(filename); testOutfileName = new StringBuilder(filename); testOutfileName.replace(outfileName.indexOf(".txt"), outfileName.length(), "-Test.arff"); outfileName.replace(outfileName.indexOf(".txt"), outfileName.length(), ".arff"); outputFile = new File(outfileName.toString()); testOutputFile = new File(testOutfileName.toString()); fos = new FileOutputStream(outputFile); testFos = new FileOutputStream(testOutputFile); testOut = new OutputStreamWriter(testFos, "UTF-8"); out = new OutputStreamWriter(fos, "UTF-8"); out.write("@relation " + outfileName + "\n\n"); out.write("@attribute time DATE \"yyyy-MM-dd HH:mm:ss\" \n@attribute price REAL\n@attribute quantity NUMERIC\n\n@data\n"); testOut.write("@relation " + testOutfileName + "\n\n"); testOut .write("@attribute time DATE \"yyyy-MM-dd HH:mm:ss\" \n@attribute price REAL\n@attribute quantity NUMERIC\n\n@data\n"); } public static void generateTestFiles() { } } class Filter implements FileFilter { public boolean accept(File file) { return file.getName().endsWith("txt"); } }

Comments Trackbacks / Pingbacks (11)

Writing Objects to an Input or Output Stream with Java

Serialization in Java is the process by which an application can transmit an entire object (including state) over a communications channel. Prior to being transmitted all data, including primitive types must be marshaled. Marshaling (serializing) is simply the process of breaking data into bytes so that they can be transmitted over a channel. Once the data is transmitted, the receiving end unmarshals (deserializes) the data into its original form.

Object deserialization is more complex than primitive unmarshaling because objects often have references to other objects, and thus it becomes necessary to keep track of referenced objects in order to fully reconstruct the object after serialization. Fortunately there are classes that manage the serialization for us. These are the ObjectInputStream and ObjectOutputStream classes. All you will need to do is ensure that the class you wish to write to a file implements the Serializable interface. Below is an example program that uses the ObjectOutputStream to write an object to a file. It then uses the ObjectInputStream to read the object from a file into a different instance variable.

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * A simple object serialization example
 */
public class ObjectToFile {
	private File file = null;
	private FileOutputStream fos = null;
	private FileInputStream fis = null;
	private ObjectOutputStream oos = null;
	private ObjectInputStream iis = null;
	private TwoPoint tp;
	private TwoPoint tp2;

	public ObjectToFile() {
		tp = new TwoPoint(Math.random(), Math.random());
	}

	public static void main(String[] args) throws IOException,
			ClassNotFoundException {
		ObjectToFile otf = new ObjectToFile();
		if (args.length <= 0) {
			otf.openOutputFile(null); // using default file
		} else {
			otf.openOutputFile(args[0]); // providing filename
		}
		otf.writeInnerClassState();
		otf.openInputFile(null);
		otf.closeFile();

	}

	// open file
	private void openInputFile(String filename) throws IOException,
			ClassNotFoundException {
		if ((filename == null) || filename.trim().equals("")) {
			file = new File("output.txt");
			System.out.println("Reading from:" + file.getAbsolutePath());
		} else {
			file = new File(filename);
			System.out.println("Reading from: " + file.getAbsolutePath());
		}
		fis = new FileInputStream(file);
		iis = new ObjectInputStream(fis);
		tp2 = (TwoPoint) iis.readObject();
		System.out.println("tp2: " + tp2.toString());
	}

	public void openOutputFile(String filename) throws IOException {
		if ((filename == null) || filename.trim().equals("")) {
			file = new File("output.txt");
			System.out.println("Writing to default file:"
					+ file.getAbsolutePath());
		} else {
			file = new File(filename);
			System.out.println("Writing to file: " + file.getAbsolutePath());
		}
		fos = new FileOutputStream(file, false);
		oos = new ObjectOutputStream(fos);
	}

	public void writeInnerClassState() throws IOException {
		oos.writeObject(tp);
		System.out.println("tp: " + tp.toString());
	}

	private void closeFile() {
		if (fos != null) {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (fis != null) {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public TwoPoint getTp() {
		return tp;
	}
}

class TwoPoint implements Serializable {
	private static final long serialVersionUID = -4233775519934013146L;
	private double x;
	private double y;

	public TwoPoint(double x, double y) {
		this.x = x;
		this.y = y;
	}

	public double getX() {
		return x;
	}

	public double getY() {
		return y;
	}

	public void setX(double x) {
		this.x = x;
	}

	public void setY(double y) {
		this.y = y;
	}

	public String toString() {

		return "[TwoPoint:x=" + this.x + ", y=" + y + "]";
	}
}
 

Comments Trackbacks / Pingbacks (15)

Java OutputStream

Java uses streams as the foundation for communication and IO. Two very important abstract classes are InputStream and OutputStream. These two classes  provide a foundation of methods that are called to read and write byte sized data or byte arrays.

A subclass of OutputStream must at least override the write() method to write at least one byte. A commonly used subclass of OutputStream is the FileOutputStream class which provides a platform independent way to write data to a file.

The following code demonstrates a character generator that writes data to a FileOutputStream object.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CharGenerator {
	private File file = null;
	private FileOutputStream fos = null;

	public CharGenerator() {

	}

	public static void main(String[] args) {
		CharGenerator charGenerator = new CharGenerator();
		if (args.length <= 0) {
			charGenerator.openFile(null); // using default file
		} else {
			charGenerator.openFile(args[0]); // providing filename
		}

		// write to file
		try {
			charGenerator.writeAscii();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			charGenerator.closeFile();
		}

	}

	private void closeFile() {
		if(fos != null){
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// open file
	public void openFile(String filename) {
		try {
			if ((filename == null) || filename.trim().equals("")) {
				file = new File("output.txt");
				System.out.println("Writing to default file:"
						+ file.getAbsolutePath());
			} else {
				file = new File(filename);
				System.out
						.println("Writing to file: " + file.getAbsolutePath());
			}
			fos = new FileOutputStream(file, false);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void writeAscii() throws IOException {
		char character = 0x21;
		int charBase = 0x21;
		for (int i = 1; i = 72 && charBase <= 54) {
				System.out.println();
				fos.write((char) '\r'); // carriage return, ms-dos
				fos.write((char) '\n');
				++charBase;
				i = 0;
				character = (char) charBase;
			}
		}
	}
}

[/sourcecode]

Comments Trackbacks / Pingbacks (7)