save UDP socket data into file - file

I have a code to send and receive UDP socket
Send UDP code:
public static void main(String args[]) throws Exception
{
try
{
FileOutputStream fo = new FileOutputStream("OUTFILE.txt");
PrintStream ps = new PrintStream(fo);
DatagramSocket Socket = new DatagramSocket(4555);
byte[] receiveData = new byte[1000000];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
while(true)
{
receivePacket.setLength(receiveData.length);
Socket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.printf("RECEIVED: %s " , new String(receivePacket.getData()));
ps.println(sentence);
ps.println();
ps.close();
fo.close();
}
File file = new File("OUTFILE.txt");
FileInputStream fis = new FileInputStream(file);
byte[] fsize = new byte[(int) file.length()];
int size = fis.read(fsize);
System.out.println("Received Size = " + size);
}
catch (Exception e) {
System.err.println(e);
}
}
}
I want to write the value of each received data packet into file then get the size of the whole file.
In my code I just got the first received value written in the file.
Could you please tell me how can I write the whole received value in the file.

At the end of the first loop, you're closing the streams so additional lines can not be written. You need to move the ps.close(); and fs.close() calls to be outside of the loop. In addition, you have an indefinite loop which guarantees that the code reading from the file can not be called--you need to have some mechanism to determine when to stop looping.

Related

Java - Load file as Template + append content in memory and manage byte[]

Im trying load a file in memory with a base information, append lines and include the result into a Zip file. In C# existes MemoryStream but, in java not.
the context of my application is load a stylesheet.css files with a pre-defined styles for add other styles that i get dinamically. Later i want add this content to a zip entry, and i need a byte[] that represent this content.
For the moment, i have the next lines, but i dont know as convert this to byte[]:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
File file = new File(classLoader.getResource("style.css").getFile());
OutputStreamWriter osw = new OutputStreamWriter( new FileOutputStream( file ) );
BufferedWriter writer = new BufferedWriter(osw);
I tried, with ByteArrayOutputStream but i can't completed all my requirements.
Any idea? im opne to other ideas for get my goal. I looking for CSSParser too, but i didn't see as I can append content and get a File document (byte[]) for to add to my zip file.
Finnaly, i didn't find other solution for my problem that convert the InputStream to ByteArrayOutputStream byte to byte.
I created the following methods:
Load template file into Input Stream and convert.
private ByteArrayOutputStream getByteArrayOutputStreamFor(String templateName) {
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inStream = classLoader.getResourceAsStream( templateName ); //file into resources directory
ByteArrayOutputStream baos = Utils.toOutputStream(inStream);
return baos;
} catch (Exception e) {
String msg = String.format("erro to loaf filetemplate {%s}: %s", templateName, e.getMessage());
throw new RuntimeException( msg, e.getCause() );
}
}
Copy the inputStream into a ByteArrayOutputStream byte to byte
public static final ByteArrayOutputStream toOutputStream(InputStream inStream) {
try {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
int byteReads;
while ((byteReads = inStream.read()) != -1) {
outStream.write(byteReads);
}
outStream.flush();
inStream.close();
return outStream;
} catch (Exception e) {
throw new RuntimeException("error message");
}
}
Finally, I append text to ByteArrayOutputStream
ByteArrayOutputStream baosCSS = getByteArrayOutputStreamFor( "templateName.css" );
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( baosCSS ) );
writer.append( "any text" );
writer.flush();
writer.close();
byte[] bytes = baosCSS.toByteArray()

Windows IoT TcpClient

I want to send a command to my Sonos speaker. With my Windows application that is easy. I just use the TcpClient example provided on Microsoft website (shown below).
public void Connect(String server, String message)
{
try
{
TcpClient client = new TcpClient(server, 1400);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
//Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
//Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
//Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
// Console.WriteLine("SocketException: {0}", e);
}
//Console.WriteLine("\n Press Enter to continue...");
//Console.Read();
}
Now, how would I go about doing this with Windows 10 IoT on a Raspberry Pi 3?
With UWP, you may need to reference the "System.Net.Sockets" Nuget package in order to use TcpClient. You probably end up with something like below snippet,
async void FunctionName()
{
try
{
using (var client = new TcpClient())
{
await client.ConnectAsync(server, 1400);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
//Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
//Console.WriteLine("Received: {0}", responseData);
}
}
catch (ArgumentNullException e)
{
//Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
// Console.WriteLine("SocketException: {0}", e);
}
//Console.WriteLine("\n Press Enter to continue...");
//Console.Read();
}
Note that you need to declare the Internet client capability in your project manifest file.
PS: There's also an alternative an alternative called StreamSocket.
Refer to an complete code sample from Microsoft github repository.
Also, if you're new to UWP programming, you should get yourself familar with the async/await pattern.

Using Database as Alfresco ContentStore

I'm working with Alfresco 4.2 and I need to use a table in my database as document content store.
Collecting some information hither and thither over the internet, I read that I have to just implement my custom DBContentStore DBContentWriter and DBContentReader classes. Someone told me to take as reference the FileContentStore class.
I need some help to mapping the FileContentStore in order to match my new class.
For example;
The DBContentWriter has to extend AbstractContentWriter and in the API docs I read that the only methods I have to overwrite are:
getReader() to create a reader to the underlying content
getDirectWritableChannel() to write content to the repository.
What about the second method?
protected WritableByteChannel getDirectWritableChannel()
This is called by getContentOutputStream():
public OutputStream getContentOutputStream() throws ContentIOException
{
try
{
WritableByteChannel channel = getWritableChannel();
OutputStream is = new BufferedOutputStream(Channels.newOutputStream(channel));
// done
return is;
}
The main method is the putContent(InputStream is) which wants to write content into a DB table.
public final void putContent(InputStream is) throws ContentIOException
{
try
{
OutputStream os = getContentOutputStream();
copyStreams(is, os);
Where copyStreams does something like this:
public final int copyStreams(InputStream in, OutputStream out, long sizeLimit) throws IOException
{
int byteCount = 0;
IOException error = null;
long totalBytesRead = 0;
try
{
byte[] buffer = new byte[BYTE_BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1)
{
// We are able to abort the copy immediately upon limit violation.
totalBytesRead += bytesRead;
if (sizeLimit > 0 && totalBytesRead > sizeLimit)
{
StringBuilder msg = new StringBuilder();
msg.append("Content size violation, limit = ")
.append(sizeLimit);
throw new ContentLimitViolationException(msg.toString());
}
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
out.flush();
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
error = e;
logger.error("Failed to close output stream: " + this, e);
}
try
{
out.close();
}
catch (IOException e)
{
error = e;
logger.error("Failed to close output stream: " + this, e);
}
}
if (error != null)
{
throw error;
}
return byteCount;
}
}
The main target is to write some code in order to write and read from the DB using these methods.
When the out.flush() is called i should have to write into the BLOB field.
thanks
Without looking at the example implementation in FileContentStore it is difficult to determine everything that getDirectWritableChennel() needs to do. Needless to say actually creating a WritableByteChannel to your database should be relatively easy.
Assuming you are using the BLOB type and you are using JDBC to get at your database then you just need to set a stream for your BLOB and turn it in to a channel.
OutputStream stream = myBlob.setBinaryStream(1);
WritableByteChannel channel = Channels.newChannel(stream);
Will you need to overwrite other methods? Maybe. If you have specific issues with those feel free to raise them.

Apache Camel - protocol buffer endpoint

I am trying to create a camel endpoint that listens on a tcp port to receive a message encoded using protocol buffers. [https://code.google.com/p/protobuf/]
I am trying to use netty to open the tcp port but I cannot get it to work.
My camel route builder is:
from("netty:tcp://localhost:9000?sync=false").to("direct:start");
from("direct:start").unmarshal(format)
.to("log:protocolbuffers?level=DEBUG")
.to("mock:result");
I have tried the textline code, but this just causes the error com.google.protobuf.InvalidProtocolBufferException: While parsing a protocol message, the input ended unexpectedly in the middle of a field. This could mean either than the input has been truncated or that an embedded message misreported its own length.
I think I need to use a byte array codec rather than a String, but I can't see a way to do it. I think I could write a custom endpoint to do it, but I'd rather not. Any pointers would be much appreciated.
I sent the message to the camel endpoint using the code below:
public static void main(String[] args) {
try {
TestProtos.Person me = TestProtos.Person.newBuilder().setId(2).setName("Alan").build();
//set up socket
SocketChannel serverSocket;
serverSocket = SocketChannel.open();
serverSocket.socket()
.setReuseAddress(true);
serverSocket.connect(new InetSocketAddress("127.0.0.1", 9000));
serverSocket.configureBlocking(true);
//create BAOS for protobuf
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//mClientDetails is a protobuf message object, dump it to the BAOS
me.writeDelimitedTo(baos);
//copy the message to a bytebuffer
ByteBuffer socketBuffer = ByteBuffer.wrap(baos.toByteArray());
//keep sending until the buffer is empty
while (socketBuffer.hasRemaining()) {
serverSocket.write(socketBuffer);
}
serverSocket.close();
} catch (Exception e) {
System.out.println("error....");
}
}
}
I also ran a test using a file endpoint which worked as expected. I created the file
with:
#Test
public void fileTest() throws Exception {
TestProtos.Person me = TestProtos.Person.newBuilder().setId(2).setName("Chris").build();
File file = new File("/tmp/test.txt");
FileOutputStream out = new FileOutputStream(file);
me.writeTo(out);
out.close();
};

how to read ZipInputStream into CharArrayReader

Right now i am developing an application using Google App Engine (GAE). GAE doesnt allow me to create temp folder for me to store my zipfile and read from it. The only way is to read it from memory. The zipfile contains 6 CSV files which i need to read it into CSVReader.
//part of the code
MultipartFormDataRequest multiPartRequest = null;
Hashtable files = multiPartRequest.getFiles();
UploadFile userFile = (UploadFile)files.get("bootstrap_file");
InputStream input = userFile.getInpuStream();
ZipInputStream zin = new ZipInputStream(input);
How do i read ZipInputStream into char[] which is needed to create CharArrayReader for my CSVReader object.
CSVReader reader = new CSVReader(CharArrayRead(char[] buf));
Wrap the ZipInputStream with an InputStreamReader to convert from bytes to chars; then call inputStreamReader.read(char[] buf, int offset, int length) to fill your char[] buffer, like this:
//part of the code
MultipartFormDataRequest multiPartRequest = null;
Hashtable files = multiPartRequest.getFiles();
UploadFile userFile = (UploadFile)files.get("bootstrap_file");
InputStream input = userFile.getInpuStream();
ZipInputStream zin = new ZipInputStream(input);
// wrap the ZipInputStream with an InputStreamReader
InputStreamReader isr = new InputStreamReader(zin);
ZipEntry ze;
// ZipEntry ze gives you access to the filename etc of the entry in the zipfile you are currently handling
while ((ze = zin.getNextEntry()) != null) {
// create a buffer to hold the entire contents of this entry
char[] buf = new char[(int)ze.getSize()];
// read the contents into the buffer
isr.read(buf);
// feed the char[] to CSVReader
CSVReader reader = new CSVReader(CharArrayRead(buf));
}
if your CharArrayRead is actually a java.io.CharArrayReader, then there is no need to load it into a char[] and you'd be better off with code like this:
InputStreamReader isr = new InputStreamReader(zin);
BufferedReader br = new BufferedReader(isr);
ZipEntry ze;
while ((ze = zin.getNextEntry()) != null) {
CSVReader reader = new CSVReader(br);
}
If you just have a single zipped file (trying to get around the 1MB limitation) then this will work:
InputStreamReader isr = new InputStreamReader(zin);
zip.getNextEntry();
CSVReader reader = new CSVReader(isr, ...);

Resources