Printing PCX images on Zebra Printers using CPCL - java

I spent really a lot of time to understand how to print a PCX image using CPCL on a Zebra Printer (via network) without downloading the image to the printer.
The sample on the documentation, in my opinion, is quite obscure.
I attach a sample class to show how to simply print an image.
It requires a "zebra.pcx" image on your classpath.
Hope it helps.

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class PrintZebraPCXImage {
public static void main(String[] args) throws Exception {
PrintZebraPCXImage instance = new PrintZebraPCXImage();
instance.print("192.168.1.133", 6101);
}
public void print(String address, int port) throws Exception {
Socket socket = null;
DataOutputStream stream = null;
socket = new Socket(address, port);
try {
stream = new DataOutputStream(socket.getOutputStream());
ByteArrayOutputStream bos = readFileToString(this.getClass().getClassLoader().getResourceAsStream("zebra.pcx"));
stream.writeBytes("! 0 200 200 300 1\r\n");
stream.writeBytes("PCX 20 0\r\n");
stream.write(bos.toByteArray());
stream.writeBytes("PRINT\r\n");
} finally {
if (stream != null) {
stream.close();
}
if (socket != null) {
socket.close();
}
}
}
public ByteArrayOutputStream readFileToString(InputStream is) {
InputStreamReader isr = null;
ByteArrayOutputStream bos = null;
try {
isr = new InputStreamReader(is);
bos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int n = 0;
while (-1 != (n = is.read(buffer))) {
bos.write(buffer, 0, n);
}
return bos;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}
}

Related

How to tell the Browser that the data that its getting is html and not regular text?

I wrote a Java server application that returns a file when it is requested by a browser. The browser makes a GET request to my socket and the socket returns the file. But the browser (firefox in my case) treats the html file as a regular text file and does not render the actual page. So the browser shows the whole html source code. How can I fix that?
Here the Code:
package ml.mindlabor.networking;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
static final int PORT = 9806;
static final int MAX_BYTES_PER_STREAM = 10_000; // 10 kB
static final String FILE_SYSTEM_PATH = "C:\\Users\\SBrau\\eclipse-workspace\\Networking\\src\\ml\\mindlabor\\networking\\Files\\public_html";
static boolean running = true;
ServerSocket ss = null;
Socket soc = null;
public static void main(String[] args) {
Server server = new Server();
// When the connection could not be established
System.out.println("Waiting for connection ...");
if (!server.connect()) return;
server.listenForResponse();
}
public Server() {
try {
ss = new ServerSocket(PORT);
} catch (IOException e) {
System.err.println("Could not create ServerSocket on Port " + PORT);
shutdown();
}
}
boolean respond(String response) {
try {
PrintWriter out = new PrintWriter(soc.getOutputStream(), true);
out.println(response);
return true;
} catch (IOException e) {
System.err.println("Could not send to Port " + PORT);
}
return false;
}
boolean respond(byte[] response) {
try {
soc.getOutputStream().write(response);
return true;
} catch (IOException e) {
System.err.println("Could not send to Port " + PORT);
}
return false;
}
boolean respondFile(String relPath) {
String path = Server.FILE_SYSTEM_PATH + relPath;
File file = new File(path);
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[(int)file.length()]; // or 4096, or more
in.read(buffer, 0, buffer.length);
soc.getOutputStream().write(buffer, 0, buffer.length);
System.out.println("Loaded :D");
in.close();
soc.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
String rawDataToString(byte[] rawData) {
return new String(rawData);
}
void listenForResponse() {
new Thread(() -> {
while (true) {
try {
DataInputStream in = new DataInputStream(soc.getInputStream());
byte[] packetData = new byte[MAX_BYTES_PER_STREAM];
in.read(packetData);
receivedPackage(packetData);
} catch (IOException e) {
System.err.println("Could not get data from port " + PORT);
shutdown();
}
}
}).start();
}
void shutdown() {
Server.running = false;
}
void receivedPackage(byte[] pkg) {
String request = new String(pkg).trim();
// GET Request for file
if (request.contains("GET ")) {
String[] arr = request.split(" ");
respondFile(arr[1].trim());
}
}
boolean connect() {
try {
soc = ss.accept();
//soc.setKeepAlive(true);
System.out.println("Connected!");
return true;
} catch (IOException e) {
System.err.println("Could not wait for connection on port " + PORT);
shutdown();
}
return false;
}
}
Ok. Got it. I solved it by rewriting the following method:
boolean respondFile(String relPath) {
String path = Server.FILE_SYSTEM_PATH + relPath;
File file = new File(path);
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
PrintWriter out = new PrintWriter(soc.getOutputStream());
BufferedOutputStream dataOut = new BufferedOutputStream(soc.getOutputStream());
byte[] fileData = readFileData(file, (int)file.length());
out.println("HTTP/1.1 501 Not Implemented");
out.println("Content-type: text/html");
out.println(); // blank line between headers and content, very important !
out.flush();
dataOut.write(fileData, 0, fileData.length);
dataOut.flush();
System.out.println("Loaded :D");
in.close();
soc.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private byte[] readFileData(File file, int fileLength) throws IOException {
FileInputStream fileIn = null;
byte[] fileData = new byte[fileLength];
try {
fileIn = new FileInputStream(file);
fileIn.read(fileData);
} finally {
if (fileIn != null)
fileIn.close();
}
return fileData;
}

Time factor in Client server program to measure upload and download time of video file

I have completed client server program to download and upload a video(media) file, but I am unable to figure out how to calculate the upload, download time separately and make it run repeatedly to measure improvement in time? I will be running client at one IP and server at different IP.
Source code of the client;
package wdc;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket("127.0.0.1", 3248);
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("C:\\file1.avi");
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
And the source code of the server side;
package wds;
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File("C:\\file2.avi");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}

ObjectInputStream readObject EOFException

I have tried to use this question's answer to get a functioning implementation, but I get various errors and am now down to an EOFException and on debugging, it appears the file does not get written.
The goal is to download an image from a URL, save it to internal cache, then later fetch it from that cache for displaying. Where have I gone wrong? The EOFException is thrown in CachedImage.java on the line which reads byte[] data = (byte[]) ois.readObject();
CachedImage.java
package com.example.droid;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import android.graphics.Bitmap;
public class CachedImage implements Serializable {
private static final long serialVersionUID = -12345678987654321L;
private transient Bitmap _bmp;
public CachedImage(Bitmap bmp) {
this._bmp = bmp;
}
public void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
if (this._bmp != null) {
int bytes = this._bmp.getWidth() * this._bmp.getHeight() * 4;
ByteBuffer buffer = ByteBuffer.allocate(bytes);
this._bmp.copyPixelsToBuffer(buffer);
if (buffer.hasArray()) {
try {
String configName = this._bmp.getConfig().name();
byte[] array = buffer.array();
oos.writeObject(array);
oos.writeInt(this._bmp.getWidth());
oos.writeInt(this._bmp.getHeight());
oos.writeObject(configName);
} catch (BufferUnderflowException e) {
}
}
} else {
oos.writeObject(null);
}
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
byte[] data = (byte[]) ois.readObject();
if (data != null) {
int w = ois.readInt();
int h = ois.readInt();
String configName = (String) ois.readObject();
Bitmap.Config configBmp = Bitmap.Config.valueOf(configName);
Bitmap bitmap_tmp = Bitmap.createBitmap(w, h, configBmp);
ByteBuffer buffer = ByteBuffer.wrap(data);
bitmap_tmp.copyPixelsFromBuffer(buffer);
this._bmp = bitmap_tmp.copy(configBmp, true);
bitmap_tmp.recycle();
} else {
this._bmp = null;
}
}
public Bitmap getBitmap() {
return this._bmp;
}
}
And here are the code segments which trigger the calls:
Async callback function for when the image is fetched from the URL to write the image to internal:
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
FileOutputStream output = null;
ObjectOutputStream oos = null;
try {
output = ICEApplication.getAppContext().openFileOutput(filename, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(output);
CachedImage cachedImage = new CachedImage(result);
oos.writeObject(cachedImage);
} catch (Exception e) {
Log.d("DEBUG", "Exception: " + e.getMessage());
} finally {
if (output != null) {
try {
oos.close();
output.close();
} catch (IOException e) {
}
}
}
}
}
The code to read the image from disk after downloaded and saved:
Bitmap image = null;
FileInputStream input = null;
ObjectInputStream ois = null;
try {
input = ICEApplication.getAppContext().openFileInput(urldisplay);
ois = new ObjectInputStream(input);
CachedImage cachedImage = (CachedImage)ois.readObject();
image = cachedImage.getBitmap();
} catch (Exception e) {
Log.d("DEBUG", "Exception: " + e.getMessage());
return null;
} finally {
if (input != null) {
try {
ois.close();
input.close();
} catch (IOException e) {
}
}
}
I read from
http://www.javablogging.com/what-are-writeobject-and-readobject-customizing-the-serialization-process/
ObjectOutputStream uses reflection to find out if those methods are declared. It uses getPrivateMethod so those methods have to be declared private in order to be used by the ObjectOutputStream
So, change CachedImage's method writeObject to private(because you posted it as public).

Parse a Path from Java program

Have a file on specified path /foo/file-a.txt and that file contains a path of another file
file-a.txt contains: /bar/file-b.txt this path at line one. need to parse the path of file-b.txt and zip that file and move that zipped file to another path /too/ from my Java code.
I been till the below code then i m stuck.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Reader
{
public static void main(String[] args)
{
BufferedReader br = null;
try
{
String CurrentLine;
br = new BufferedReader(new FileReader("/foo/file-a.txt"));
while ((CurrentLine = br.readLine()) != null)
{
System.out.println(CurrentLine);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)br.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
am getting path as text, help would be appreciated. Thanks in advance
For the actual zipping of the file, this page may be of help.
As a general note, this code will replace the current existing zip file.
public class TestZip02 {
public static void main(String[] args) {
try {
zip(new File("TextFiles.zip"), new File("sample.txt"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void zip(File zip, File file) throws IOException {
ZipOutputStream zos = null;
try {
String name = file.getName();
zos = new ZipOutputStream(new FileOutputStream(zip));
ZipEntry entry = new ZipEntry(name);
zos.putNextEntry(entry);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] byteBuffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = fis.read(byteBuffer)) != -1) {
zos.write(byteBuffer, 0, bytesRead);
}
zos.flush();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
zos.closeEntry();
zos.flush();
} finally {
try {
zos.close();
} catch (Exception e) {
}
}
}
}
For moving the file, you can use File.renameTo, here's an example.
Hope this helps!

Java Voice Chat - Mixdown Incoming Data for Single Output

I am trying to write a Java voice chat application, and have achieved echo capabilities, but when trying to connect multiple clients, I am stuck. I understand that you cannot iterate through sockets and send the data to everyone connected without mixing-down the data. (I have tried and it sounds nothing like how it should). I am not quite sure what to do, and I am using a very simple byte-buffered echo server as the server (where I would like to perform the mixdown). I also have a client that takes microphone input, sends it to the server, takes data from the server, and plays that data out of a speaker.
NOTE: The client is composed of 2 classes (Program and SoundReceiver). I am using the javax.sound.sampled library.
Echo Server: http://pastebin.com/c9KiaTpJ
import java.net.*;
import java.io.*;
import java.util.*;
public class Echo
{
public static void main(String[] args) throws Exception
{
ServerSocket serverSocket = new ServerSocket(3000);
while(true){Thread echoThread = new Thread(new EchoThread(serverSocket.accept()));
echoThread.start();}
}
}
class EchoThread implements Runnable
{
public static Collection<Socket> sockets = new ArrayList<Socket>();
Socket connection = null;
DataInputStream dataIn = null;
DataOutputStream dataOut = null;
public EchoThread(Socket conn) throws Exception
{
connection = conn;
dataIn = new DataInputStream(connection.getInputStream());
dataOut = new DataOutputStream(connection.getOutputStream());
sockets.add(connection);
}
public void run()
{
int bytesRead = 0;
byte[] inBytes = new byte[1];
while(bytesRead != -1)
{
try{bytesRead = dataIn.read(inBytes, 0, inBytes.length);}catch (IOException e){}
if(bytesRead >= 0)
{
sendToAll(inBytes, bytesRead);
}
}
sockets.remove(connection);
}
public static void sendToAll(byte[] byteArray, int q)
{
Iterator<Socket> sockIt = sockets.iterator();
while(sockIt.hasNext())
{
Socket temp = sockIt.next();
DataOutputStream tempOut = null;
try
{
tempOut = new DataOutputStream(temp.getOutputStream());
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{tempOut.write(byteArray, 0, q);}catch (IOException e){}
}
}
}
Client Program Class: http://pastebin.com/v24CYwXE
import java.io.DataOutputStream;
import java.net.*;
import javax.sound.sampled.*;
public class Program
{
public static void main(String[] args) throws Exception
{
AudioFormat af = new AudioFormat(8000.0f,8,1,true,false);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, af);
TargetDataLine microphone = (TargetDataLine)AudioSystem.getLine(info);
microphone.open(af);
Socket conn = new Socket("localhost",3000);
microphone.start();
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
int bytesRead = 0;
byte[] soundData = new byte[1];
Thread inThread = new Thread(new SoundReceiver(conn));
inThread.start();
while(bytesRead != -1)
{
bytesRead = microphone.read(soundData, 0, soundData.length);
if(bytesRead >= 0)
{
dos.write(soundData, 0, bytesRead);
}
}
System.out.println("IT IS DONE.");
}
}
Client SoundReceiver Class: http://pastebin.com/2tt0Jucv
import java.net.*;
import java.io.*;
import javax.sound.sampled.*;
public class SoundReceiver implements Runnable
{
Socket connection = null;
DataInputStream soundIn = null;
SourceDataLine inSpeaker = null;
public SoundReceiver(Socket conn) throws Exception
{
connection = conn;
soundIn = new DataInputStream(connection.getInputStream());
AudioFormat af = new AudioFormat(8000.0f,8,1,true,false);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
inSpeaker = (SourceDataLine)AudioSystem.getLine(info);
inSpeaker.open(af);
}
public void run()
{
int bytesRead = 0;
byte[] inSound = new byte[1];
inSpeaker.start();
while(bytesRead != -1)
{
try{bytesRead = soundIn.read(inSound, 0, inSound.length);} catch (Exception e){}
if(bytesRead >= 0)
{
inSpeaker.write(inSound, 0, bytesRead);
}
}
}
}
Basically, I'd like to merge all incoming bytes into one byte array while keeping everyone's voice full (just like a 3-way phone call).
setting the limit to the serverSocket may help, eg new ServerSocket(3000,101); something like backlog or queue length..
It's this line:
try
{
tempOut.write(byteArray, 0, q);
}
catch (IOException e){
}
in server side which i think sends the data back to the client due which there is an echo. I think you should omit the line.
I think you need to create a check in the server side. its like if sendAll is being called from EChoThread that has connection instance just pass this to sendAll and there compare sockIt with connection if they are the same then this is the same socket that is sending the date and there is no need to send data to it self so just skip it and move to the next socket.
the following changes should be made at server side:
public void run()
{
int bytesRead = 0;
byte[] inBytes = new byte[1];
while(bytesRead != -1)
{
try{bytesRead = dataIn.read(inBytes, 0, inBytes.length);}catch (IOException e) {}
if(bytesRead >= 0)
{
sendToAll(connection, inBytes, bytesRead);
}
}
sockets.remove(connection);
}
public static void sendToAll(Socket connection, byte[] byteArray, int q)
{
Iterator<socket> sockIt = sockets.iterator();
while(sockIt.hasNext())
{
Socket temp = sockIt.next();
if(connection == temp){
continue;
}
DataOutputStream tempOut = null;
try
{
tempOut = new DataOutputStream(temp.getOutputStream());
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{tempOut.write(byteArray, 0, q);}catch (IOException e){}
}
}
public void run()
{
int bytesRead = 0;
byte[] inBytes = new byte[1];
while(bytesRead != -1)
{
try{bytesRead = dataIn.read(inBytes, 0, inBytes.length);}catch (IOException e) {}
if(bytesRead >= 0)
{
sendToAll(connection, inBytes, bytesRead);
}
}
sockets.remove(connection);
}
public static void sendToAll(Socket connection, byte[] byteArray, int q)
{
Iterator<socket> sockIt = sockets.iterator();
while(sockIt.hasNext())
{
Socket temp = sockIt.next();
if(connection == temp){
continue;
}
DataOutputStream tempOut = null;
try
{
tempOut = new DataOutputStream(temp.getOutputStream());
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{tempOut.write(byteArray, 0, q);}catch (IOException e){}
}
}

Categories

Resources