Java - Improve method (try/catch) - java

I have a method for retrieving some coordinates from a very slow page.
My method works fine but i cant help to feel like it can be greatly improved, specially the try/catch clauses.
The method looks like this:
public void getCoordinates(){
EventQueue.invokeLater(() -> loadingLabel.updateCoordinates(true));
consolePanel.getConsole().append("\nRetrieving coordinates from server\n");
shapes.clear();
URL url = null;
try {
url = new URL("http://TestServlet/");
} catch (MalformedURLException e) {
e.printStackTrace();
consolePanel.getConsole().append(e.toString());
}
try {
URLConnection connection = url.openConnection();
connection.setConnectTimeout(1000);
try (InputStream dataSource = url.openStream()) {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(
dataSource, StandardCharsets.ISO_8859_1));
double xCoordinate;
double yCoordinate;
String line;
while ((line = inputStream.readLine()) != null) {
if(!line.startsWith("#")) {
consolePanel.getConsole().append(line + "\n");
String[] text = line.split(",");
xCoordinate = Double.parseDouble(text[0]);
yCoordinate = Double.parseDouble(text[1]);
xCoordinate = Math.abs(xCoordinate)/4;
yCoordinate = Math.abs(yCoordinate)/4;
String name = text[2];
shapes.add(this.mapPanelState.getNewShape(xCoordinate, yCoordinate, 10, name));
}
}
}
} catch (IOException e) {
e.printStackTrace();
consolePanel.getConsole().append(e.toString());
}
EventQueue.invokeLater(this::repaint);
EventQueue.invokeLater(() -> loadingLabel.updateCoordinates(false));
}
Any help to improve on it would be much appreciated.

Your error handling is the same for both catch clauses. So you may easily merge those.
public void getCoordinates() {
try {
URL url = new URL("http://TestServlet/");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(1000);
try (InputStream dataSource = url.openStream()) {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(dataSource, StandardCharsets.ISO_8859_1));
double xCoordinate;
double yCoordinate;
String line;
while ((line = inputStream.readLine()) != null) {
if (!line.startsWith("#")) {
consolePanel.getConsole().append(line + "\n");
String[] text = line.split(",");
xCoordinate = Double.parseDouble(text[0]);
yCoordinate = Double.parseDouble(text[1]);
xCoordinate = Math.abs(xCoordinate) / 4;
yCoordinate = Math.abs(yCoordinate) / 4;
String name = text[2];
shapes.add(this.mapPanelState.getNewShape(xCoordinate, yCoordinate, 10, name));
}
}
}
} catch (Exception e) {
e.printStackTrace();
consolePanel.getConsole().append(e.toString());
}
EventQueue.invokeLater(this::repaint);
EventQueue.invokeLater(() -> loadingLabel.updateCoordinates(false));
}

Here is my improvement:
try {
URL url = new URL("http://TestServlet/");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(1000);
try (InputStream dataSource = url.openStream()) {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(
dataSource, StandardCharsets.ISO_8859_1));
/*
your logic here
*/
}
} catch (MalformedURLException e) {
e.printStackTrace();
//consolePanel.getConsole().append("URL is malformed! Try with a valid one");
} catch (IOException e) {
e.printStackTrace();
//consolePanel.getConsole().append("....");
} catch (Exception e) {
// runtime exceptions
}
If your action does not change whether it's a MalformedURLException, IOException etc., the following catch block is enough:
catch (Exception e) {
e.printStackTrace();
//consolePanel.getConsole().append(e.toString());
}

Related

How to create a folder structure in URL using java?

I want to create a folder structure to connected URL location. I am able read file from connected URL location, but note able to create a folder. Here is my code to read file from URL.
public class ReadFromURL {
public static void main(String[] args) {
// TODO Auto-generated method stub
String urlToConnect = "http://11.111.111.2/UploadedFiles/test/";
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
URLConnection connection = null;
URL url = null;
try {
url= new URL("http://11.111.111.2/UploadedFiles/test");
connection = url.openConnection();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection.setDoOutput(true); // This sets request method to POST.
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
int responseCode = 0;
try {
responseCode = ((HttpURLConnection) connection).getResponseCode();
URL url1 = new URL("http://11.111.111.2/UploadedFiles/test/test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(url1.openStream()));
String FILENAME = "D:\\test\\filename.txt";
// write the output to stdout
String line;
while ((line = reader.readLine()) != null)
{
write_to_file(FILENAME,line);
System.out.println(line);
}
// close our reader
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(responseCode);
}
public static void write_to_file(String filename,String line)
{
BufferedWriter bw = null;
FileWriter fw = null;
try {
//String content = "This is the content to write into file\n";
fw = new FileWriter(filename);
bw = new BufferedWriter(fw);
bw.write(line);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

Java connection with Threads

I want to create an App, it can show the newest movies datas, with trailers from Movie Database
I try to connect url, with threads to search the trailers. But its load only the first 38 connect succes, but i need 60. I have no idea why.
Is anyone has?
P.S.: I am sorry my English
private Thread loadTrailers = new Thread(){
#Override
public void run(){
int counter = 0;
String str = new String("");
BufferedReader br = null;
try { // try open source site
URL url = new URL("https://api.themoviedb.org/3/movie/"+id+"/videos?api_key="+myApikey);
br = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream())); // problem with openConnection()
if(br != null){
if((str = br.readLine()) != null){
String[] moviedatas = str.split("\"id\"");
for(int i = 1; i < moviedatas.length && counter < 3;++i){
Pattern isTrailer = Pattern.compile(".*Trailer.*");
Matcher matc_tr = isTrailer.matcher(moviedatas[i]);
if(matc_tr.matches()){
Pattern getKey = Pattern.compile(".*key\":\"(.*)\",\"name.*");
Matcher key = getKey.matcher(moviedatas[i]);
if(key.matches()){
links.add("https://www.youtube.com/watch?v="+key.group(1));
counter++;
}
}
}
}
}
} catch (MalformedURLException e) {
System.err.println("Invalid URL!");
} catch (IOException e) {
System.err.println("Connection failed from trailers.");
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
System.err.println("File close not success.");
}
}
}
};

How can i create vertex and edge with HTTP in Orientdb?

Here is my code. I did a "GET" method for have a response of my DB.
Then I read my own file csv. All is ok in this point, but... I have not idea how can i do a "POST" method. i know that i need to use "addRequestProperty"method.
Any idea for create vertex and edge?
public void run() throws MalformedURLException, JSONException, IOException {
String viaURl = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxx/mydb";
URL url = new URL(viaURl);
HttpURLConnection conexion = null;
String texto = null;
String json;
BufferedReader in = null, in2 = null;
int numDump = 5;
String dato;
String csvSplitBy = ";";
int numApps = 0;
OutputStreamWriter out;
try {
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxx", "xxxxxxxxxxxxx.".toCharArray());
}
});
conexion = (HttpURLConnection) url.openConnection();
conexion.setRequestMethod("GET");
conexion.connect();
System.out.println("¡¡¡Conectado!!!");
in = new BufferedReader(new InputStreamReader(conexion.getInputStream()));
out = new OutputStreamWriter(conexion.getOutputStream());
json = "";
while ((texto = in.readLine()) != null) {
json += texto;
}
in.close();
System.out.println(json);
conexion.setDoOutput(true);
try {
for (int i = 0; i < numDump; i++) {
String csvFile = "/home/danicroque/dump/dump_" + i;
try {
in2 = new BufferedReader(new FileReader(csvFile));
while ((dato = in2.readLine()) != null) {
numApps++;
String[] datos = dato.split(csvSplitBy, 15);
conexion.setRequestMethod("POST");
conexion.addRequestProperty("_id0" , datos[0]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("Fin");
}
}
}
Thank in advance.
You can use this POST methods to create class:
http://your_host:2480/class/mydb/className
to add property to a class
http://your_host:2480/property/mydb/className/propertyName
You can fine more detailed information here.
Hope it helps,
Alex.
UPDATE:
To insert use this POST method:
http://your_host:2480/command/mydb/sql/insert into className(propertyName) values(“yourValue”)

How can I call a WebMethod in Java Applet

How can I call a C# WebMethod in my Java Applet ?
The method called EnrollClient in C#
My Try
public void enroll(String teste) {
URL u;
InputStream is = null;
try {
u = new URL("http://localhost:5154/lb.ashx?pwd=abci/EnrollClient");
is = u.openStream();
BufferedReader d = new BufferedReader(new InputStreamReader(is));
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ioe) {
}
}
C# WebMethod
public class lb : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
strings pwd = context.Request["pwd"].ToString();
business.Client.lb cli = new business.Client.lb();
JavaScriptSerializer jss = new JavaScriptSerializer();
StringBuilder sbRes = new StringBuilder();
jss.Serialize(cli.ReturnJSon(), sbRes);
context.Response.Write(sbRes.ToString());
}
[WebMethod]
public void EnrollClient()
{
string template = string.Empty;
string client = string.Empty;
try
{
business.Client.lb cli = new business.Client.lb();
cli.EnrollClient(template, client);
}
catch (Exception e)
{
}
}
If I do the same code but with the code
u = new URL("http://localhost:5154/lb.ashx?pwd=abci");
it will access the ProcessRequest of my C# code.

Retry a connection on timeout in Java

I have a method (below) that pulls down and returns the source of a webpage as a String. It all works fine and dandy, but when the connection times out, the program throws an exception and exits. Is there a better method to do this that would allow it to try again on timeout, or is there a way to do it within this method?
public static String getPage(String theURL) {
URL url = null;
try {
url = new URL(theURL);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
exitprint();
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
exitprint();
}
int ptr = 0;
StringBuffer buffer = new StringBuffer();
try {
while ((ptr = is.read()) != -1) {
buffer.append((char)ptr);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
exitprint();
}
return buffer.toString();
}
Here's a refactoring of your code that should retry the download N times. Haven't tested it though, but it should kick you off in the right direction.
public static String getPage(String theURL) {
URL url = null;
try {
url = new URL(theURL);
} catch (MalformedURLException e) {
e.printStackTrace();
exitprint();
}
for (int i = 0; i < N; i++) {
try {
InputStream is = url.openStream();
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while ((ptr = is.read()) != -1)
buffer.append((char)ptr);
} catch (IOException e) {
continue;
}
return buffer.toString();
}
throw new SomeException("Failed to download after " + N + " attepmts");
}
I think AOP and Java annotations is a good option. I would recommend to use a read-made mechanism from jcabi-aspects:
#RetryOnFailure(attempts = 2, delay = 10)
public String load(URL url) {
return url.openConnection().getContent();
}
Write a wrapper function around it and allow the connect exception to propogate out. Then you can loop calling your existing function while you receive connect exception upto some max retries.
This is better than embedding a for loop in your existing function because it logically separates retry logic from mainline code. And it's easier to read and understand as a result.
Instead of
try {
is = url.openStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
exitprint();
}
you can try set longer timeout and you can still handle timeout exception by catching it
try {
URLConnection con= url.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(50000);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
} catch (SocketTimeoutException e) {
//here you can still handle timeout like try again under certain conditions
}
You could put the whole thing in a while loop:
while (true) {
try {
...
} catch (IOException e) {
continue;
}
return buffer.toString();
}
The return statement will break you out of the loop. You might also want to keep track of the number of attempts and stop after 5-10, for politeness, but that's the basic shape of it.
Edit
The better version, based on comments:
int retries = 10;
for (int i = 0 ; i < retries ; i++) {
try {
...
} catch (IOException e) {
continue;
}
return buffer.toString();
}

Categories

Resources