JSON post encoding in Elasticsearch through maven - java

I want to make insert in java.Maven with http post to Elasticsearch server.
My code is:
package com.server.java.Webping;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ReadAndWrite extends Server {
public static void main(String[] args) throws IOException {
try {
URL url = new URL("http://192.168.1.126:9200/shakespeare/_bulk?pretty' --data-binary #shakespeare.json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
File file = new File("shakespeare.json");
FileReader reader = new FileReader(file);
#SuppressWarnings("resource")
BufferedReader br = new BufferedReader(reader);
String input = null;
StringBuilder builder = new StringBuilder();
while(br.readLine( ) != null)
{
String txt = br.readLine( );
builder.append(txt);
}
input = builder.toString();
OutputStream os = (OutputStream) conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br1 = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br1.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
However when I execute the post method, java return me an error:
java.io.IOException: Error writing to server
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:699)
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:711)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1567)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at com.server.java.Webping.ReadAndWrite.main(ReadAndWrite.java:38)
I have also checked my server connection with pinging socket request and its working .
code for pinging request:
package com.server.java.Webping;
import java.net.InetAddress;
import java.net.Socket;
public class WebPing {
public static void main(String[] args) {
try {
InetAddress addr;
Socket sock = new Socket("192.168.1.126", 9200); // elastic search - 9200 , kibana - 5601
addr = sock.getInetAddress();
System.out.println("Connected to " + addr);
sock.close();
} catch (java.io.IOException e) {
System.out.println("Can't connect to " + args[0]);
System.out.println(e);
}
}
}
and output returns as :
Connected to /192.168.1.126
Can anyone help me out that what is wrong in my code ?

Related

I just tried to build a simple server and client

Both ran successfully, but they skipped some parts, I don't know why. Here are the codes
Client:
package echoapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class SimpleEchoClient {
public static void main(String[] args) throws IOException{
System.out.println("Simple Echo Client");
try {
System.out.println("Waiting for connection.....");
InetAddress localAddress = InetAddress.getLocalHost();
try (Socket clientSocket = new Socket(localAddress, 6000);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))){
System.out.println("Connected to server");
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter text: ");
String inputLine = scanner.nextLine();
if ("quit".equalsIgnoreCase(inputLine)) {
break;
}
out.println(inputLine);
String response = br.readLine();
System.out.println("Server response: " + response);
}
}
} catch (IOException ex) {
// Handle exceptions
}
}
}
Server:
package echoapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleEchoServer {
public static void main(String[] args)throws IOException {
System.out.println("Simple Echo Server");
try (ServerSocket serverSocket = new ServerSocket(6000)){
System.out.println("Waiting for connection.....");
Socket clientSocket = serverSocket.accept();
System.out.println("Connected to client");
try (BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String inputLine;
while((inputLine = br.readLine()) != null) {
System.out.println("Server: " + inputLine);
out.println(inputLine);
}
}
} catch (IOException ex) {
// Handle exceptions
}
}
}
I should be able to type something in the client and get the response from the server. Like echo. I don't know why how to fix the try block to make all the codes ran through. The parts where the second try has a problem, and I couldn't make the second try block work.

How to fix javax.net.ssl.SSLHandShakeException accessing JIRA

I want to match issues in JIRA with other datasource.
I can use curl:
curl -u myname:mypassword
https://jira.myorganization.com/rest/api/latest/issue/TR-1234
This will return info about the issue, for exampel TR-1234, that I want to check some data for.
In java I want to do the same thing but I get javax.net.ssl.SSLHandShakeException
The program I try to run:
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
URL url = null;
try {
url = new URL("https://jira.myorganization.com/rest/api/latest/issue/TR-1234");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String userpass = "myusername:mypassword";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
System.out.println("Resp="+ con.getResponseCode()+" "+con.getResponseMessage());
String contentType = con.getHeaderField("Content-Type");
BufferedReader br = new BufferedReader(new InputStreamReader(
(con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can I somehow pass userid and password to the URL. The application is a tool and it would be ok to let the user input his name and password.

How to use geonames api to validate zip code / postal code against a country?

The requirement is to validate whether zip code really exists or not in a specific country??
Country = US
State = California
I wants to know how to call geonames API using REST to get country code by zip code? I would prefer an output in a JSON format over XML.
Answer :
Refer
http://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientGet {
// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) {
try {
URL url = new URL("http://api.geonames.org/postalCodeSearchJSON?postalcode=94536&maxRows=1&username=demo&country=US");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
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();
}
}
}
Thanks Mkyong!
They have a file a country info file,There are regexes for about 150 countries.
You need to create GeoNames model. This model will handle creating, storing, and returning the value of our GeoNames WebServices request.
For more info - http://www.geonames.org/export/web-services.html

To write the response of servlet into pdf using httpurlconnection

I am trying to hit a url through URL Connection in servlet. The response of the request (which is a pdf) needs to be displayed on the browser as pdf. Here I do not have any temporary pdf file kept on the server which means i want my code to generate the url response as a pdf on the fly. Currently my webservice returns pdf if I hit the webservice url(REST) directly in the browser.
Here is my code
I am getting a blank output
code:
package com.mm;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class testServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\""+ "dummy" + "\"");
byte[] pdfData = servicecall().getBytes("UTF-8");
System.out.println(pdfData.length);
response.setContentLength(pdfData.length);
OutputStream output = response.getOutputStream();
output.write(pdfData);
output.flush();
output.close();
}
public String servicecall()
{
String output = "";
BufferedReader reader = null;
StringBuilder stringBuilder;
try
{
URL url = new URL("http://hardik/Wecs/External/private/document.aspx?prd=1042737~~PDF~~MTR~~IPDS~~EN~~2014-01-10%2014:00:41~~SOLEST%20120~~");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/pdf");
conn.connect();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
reader = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
output = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println( output);
return output;
}
}
I get a blank pdf output

server make a txt file and client write it

I have a project that has a server which creates an empty text file.
Once my client stops writing to this file, the server should read and display the results.
My problem is that the client is connecting to the server, but whatever text the client is sending is not being written on the server side. In addition, when I exit, the server doesn't quit.
This is what I have so far:
The Server
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String args[]) throws IOException {
BufferedWriter out;// = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
ServerSocket echoServer = null;
String line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(55);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
while (true) {
line = is.readUTF();
os.println(line);
os.flush();
out.write(line);
out.flush();
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
Here is my client:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class client {
public static void main(String[] args) {
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
String strout;
Scanner in = new Scanner(System.in);
try {
smtpSocket = new Socket("localhost", 55);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
}
if (smtpSocket != null && os != null && is != null) {
try {
do{
System.out.print("Write what the client will send: ");
strout = in.nextLine();
os.writeBytes(strout);}
while(!strout.equals("exit"));
os.close();
is.close();
smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
};
Try this.
In your server
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
while (true) {
line = br.readLine();
System.out.println(line);
os.println(line);
os.flush();
if( line != null ){
out.write(line + '\n');
out.flush();
}
}
}
And about the 'exit' part of your client try after changing
while(!strout.equals("exit"));
to
while(!strout.equalsIgnoreCase("exit"));
Hope this helps !!
Today my teacher is upload a new project because he has make a false , the project i have to make is similar which the old but the client is reading or writing a txt with number from 0-911, The client is choice randomly what is make read o write if choice read show the numbers of txt if choice write he write randomly a number from 0-911 and stop if choice the 100.
i make it but nothing show me is stack.
sever
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String args[]) throws IOException {
BufferedWriter out;// = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
ServerSocket echoServer = null;
int line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(55);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
boolean ch=true;
{
line =(Integer) br.read();
// System.out.println(line);
os.println(line);
os.flush();
out.write(line+"\n");
out.flush();
} while (line != 100);
os.close();
out.close();
br.close();
clientSocket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
client
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.Scanner;
public class client {
public static void main(String[] args) throws IOException {
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
String strout;
int number=0;
Random rand = new Random(System.currentTimeMillis());
Scanner in = new Scanner(System.in);
try {
smtpSocket = new Socket("localhost", 55);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost");
}
int choice=2;//rand.nextInt(2);
if(choice==1){
int num=is.read();
System.out.println(num);
}
else if(choice==2){
try {
do{
number=rand.nextInt(911);
// System.out.println(number);
os.writeInt(number);
}while(number!=100);
os.close();
is.close();
smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
}

Categories