Passing a table to client - jdbc

I have to build a client/server database; the server builds the database that contains a single table. It has to pass the table to
the client which will display it in a TableView.
The server retrieves the SQL commands from a txt file.
The question is how do I (Server) pass the table that I've created to the client?
I thought of ArrayList but it gets really complicated and hard to handle.
The server code:
//Load driver, connect to JDBC..
private void DBSetup()
{
try
{
statement = connection.createStatement();
FileInputStream fstream = new FileInputStream("mysql.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
System.out.println(strLine);
//INSERT PLATFORM->RUNLATER
status.appendText(strLine+"\n");
if (strLine != null && !strLine.equals(""))
statement.execute(strLine);
}
br.close();
}catch (java.lang.Exception ex)
{
Platform.runLater(()->
{
status.setText(ex.toString());
});
}
}
My program supports multiple clients, so I have a hashTable that holds the socket and the outputStream of each client.
P.S.: I'm working with javaFX.

Related

Generating pdf in a web API (ItextSharp 5.5.13)

I need to create a PDF file in memory within a web API and send it. I do create the PDF and the web API sends it, but I can't open it once received.
I do create the PDF as a byte array with this:
private byte[] createPDF()
{
MemoryStream memStream = new MemoryStream();
byte[] pdfBytes;
Document doc = new Document(iTextSharp.text.PageSize.LETTER);
PdfWriter wri = PdfWriter.GetInstance(doc, memStream);
doc.AddTitle("test");
doc.AddCreator("I am");
doc.Open();//Open Document to write
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse = new Phrase("This is my second line using Pharse.");
Chunk chunk = new Chunk(" This is my third line using Chunk.");
doc.Add(paragraph);
doc.Add(pharse);
doc.Add(chunk);
pdfBytes = memStream.ToArray();
doc.Close(); //Close
return pdfBytes;
}
This method is called by the method in the web API which sends the PDF, and it is this one:
[HttpGet]
public HttpResponseMessage GetFiniquitopdf()
{
try
{
byte[] buffer = createPDF();
response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(new MemoryStream(buffer));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentLength = buffer.Length;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "myFirstPDF.pdf"
};
}
catch (Exception e)
{
response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
return response;
}
The problem is when the PDF is downloaded it is useless, can't be opened, I don't understand why the PDF can't be opened, I thought it was the security of the Windows 10, so once downloaded I do check it as a secure file, but it doesn't open anyway.
I guess there is something wrong in the way I send it or maybe I lack of something in the creation of the PDF file
thanks in advance
You retrieve the bytes from the memory stream before closing the document:
pdfBytes = memStream.ToArray();
doc.Close(); //Close
return pdfBytes;
But the pdf in the memory stream is not complete before the document is closed. Thus, simply switch the order of instructions:
doc.Close(); //Close
pdfBytes = memStream.ToArray();
return pdfBytes;

ElasticSearch Rest API in JAVA

I am trying to write a simple JAVA REST Client through which I want to PUT/GET elasticsearch document information.
PUT is working fine, my json data got added into index.
But the problem is GET, Response Code is 200, but it is not returning any data.
Can anyone please help.
public static String httpGet(String resturl){
String output = null;
try {
URL url = new URL(resturl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
//System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
I am calling as
RestClient.httpGet("http://localhost:9200/gabsindex/employee/_search")
You println call is currently commented out. If you uncomment it, you'll get the response from the server on one single line, something like
{"took":50,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":7056,"max_score":1.0,"hits":[...]}}
If you are trying to follow this approach educationally, this can be ok. Remember, nonetheless, that there are a number of libraries that can be used exactly for this use. You should check out the clients page.

InputStreamReader throws NPE on second iteration of for loop

InputStreamReader throws an NPE as follows when I execute this code on the second iteration of the for loop. The code works perfectly for the first iteration and returns the following NPE on the second iteration. I am using the code snippet to read contents of specific file from an FTP location and display them. Please note all the lines till the new InputStreamReader work perfectly even on second iteration. Any ideas why?
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:61)
at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
at com.test.txtweb.server.task.CallBackRetryTask.main(CallBackRetryTask.java:229)
Here is the source code:
public static void main(String[] args){
String strDate = "20130805";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(host);
String pathToFiles = "/path/to/File";
String ftpFileName = "";
List<String> ftpFileNames = null;
InputStream iStream;
if(ftpClient.login(username, password)){
ftpClient.enterLocalPassiveMode();
FTPFile[] ftpFiles = ftpClient.listFiles();
ftpFileNames = new ArrayList<String>();
for (FTPFile ftpFile : ftpFiles) {
ftpFileName = ftpFile.getName();
if(ftpFileName.contains(strDate)){
iStream = ftpClient.retrieveFileStream(pathToFiles + ftpFileName);
System.out.println(ftpClient.getReplyString());
InputStreamReader isr = new InputStreamReader(iStream); //Error on this line on second iteration
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
}
Figured out the issue after quite a lot of debugging. I was not calling the completePendingCommand() after transferring the file to check the status of the transfer.
The API for FTPClient.retrieveFileStream() states that to finalize the file transfer you must call FTPClient.completePendingCommand() and check its return value to verify success. After correcting this issue, everything started working fine.

Sending Image with Exif info from Windows Phone to Java Server

I'm new in programming in Windows Phone (and StackOverflow tbh). Currently, I'm working on a task that concerns with sending images stored in the Windows Phone's storage (with Exif info) to a Java server. So far I have successfully send the byte stream from the Windows Phone client and construct the image on the Java side, however, the Exif information is somehow lost. I believe it's just the way I send it on Windows Phone that's causing the problem. Very much appreciated for any help or guidance !
Here's my code on the Windows Phone client:
// Windows Phone Client code (MainPage.xaml.cs)
// This function is called when an image is selected from
// the task PhotoChooserTask ptask, which brings
// a popup that allows the user to choose an image
// from the phone's storage
void ptask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK && e.ChosenPhoto != null)
{
//Take JPEG stream and decode into a WriteableBitmap object
App.CapturedImage = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
// Attempt to send the image
WriteableBitmap pic = new WriteableBitmap(App.CapturedImage);
MemoryStream stream = new MemoryStream();
pic.SaveJpeg(stream, App.CapturedImage.PixelHeight, App.CapturedImage.PixelWidth, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
client.Send(stream);
// Close the socket connection explicitly
client.Close();
}
}
Here's the code in the SocketClient.cs
public string Send(MemoryStream data)
{
byte[] msData = data.ToArray();
if (_socket != null)
{
// Create SocketAsyncEventArgs context object
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
// Set properties on context object
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
socketEventArg.UserToken = null;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
_clientDone.Set();
});
// Add the data to be sent into the buffer
socketEventArg.SetBuffer(msData, 0, msData.Length);
// Sets the state of the event to nonsignaled, causing threads to block
_clientDone.Reset();
// Make an asynchronous Send request over the socket
_socket.SendAsync(socketEventArg);
}
else
{
response = "Socket is not initialized";
}
return response;
}
On the Java Server,
public static void main(String[] args) {
ServerSocket serverSocket;
Socket client;
try {
serverSocket = new ServerSocket(PORT_NUMBER);
while (true) {
client = serverSocket.accept();
// Extract exif info
InputStream inputStream = client.getInputStream();
InputStream stream = new BufferedInputStream(inputStream);
// Create file from the inputStream
File file = new File("image.jpg");
try {
OutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[4096];
for (int n; (n = stream.read(buffer)) != -1;) {
os.write(buffer, 0, n);
}
}
The output image is identical to the one sent from the windows phone, just without any Exif information whatsoever. Anyone could point out what I did wrong that causes the information to be lost? I'm guessing because I called the SaveJpeg function in the windows phone code, rewriting the image file, and losing all information there, but I don't know how else to convert the image to byte and stream it.
Much help is appreciated ! Thank you.
I found the answer to my own problem. For those of you who might have a problem with this. I simply use:
Byte[] imageData = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Position = 0;
e.ChosenPhoto.Read(imageData, 0, imageData.Length);
Then send the byte array in my send function:
socketEventArg.SetBuffer(imageData, 0, imageData.Length);

Windows Phone 7 client server implementation

I'm trying to create an application for windows phone 7 which acts as a client and which sends requests to a server which is written in Java. The client supposed to send a request, and wait for an answer from the server.
My problem is that I can't seem to communicate with the server properly. When I tried testing it in a simple .NET C# program and used blocking calls such as socket.send() and socket.receive() it works but the Windows Phone application doesn't have blocking calls.
This is what the server (Java) does once it detects a connection:
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));
String message = reader.readLine();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"));
writer.println("hiBack");
writer.close();
and this is how the client(C#) is implemented:
public void sendRequest()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var connectionOperation = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint(server, serverPort) };
connectionOperation.Completed += new EventHandler<SocketAsyncEventArgs>(onConnectCompleted);
socket.ConnectAsync(connectionOperation);
}
private void onConnectCompleted(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError != SocketError.Success)
{
System.Console.WriteLine("Error! " + e.SocketError);
return;
}
var sendListener = new SocketAsyncEventArgs();
string msg = "hi";
var buffer = new System.Text.UTF8Encoding().GetBytes(msg + Environment.NewLine);
sendListener.SetBuffer(buffer, 0, buffer.Length);
sendListener = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint(server, serverPort) };
sendListener.Completed += new EventHandler<SocketAsyncEventArgs>(onSendCompleted);
socket.SendToAsync(sendListener);
}
private void onSendCompleted(object sender, SocketAsyncEventArgs e)
{
socket.ReceiveAsync(e);
}
I've got a problem with the line: socket.SendToAsync(sendListener); on the C# side which end the program without doing anything (exit with return code 0).
the Java server starts it's work instantly when it detects the connection so it might also cause a problem?
What can I do to make the communication work?

Resources