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”)
Related
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());
}
I am a beginner in the android studio. I will successfully connect the database but I don't know how to read a data 5 seconds once in an android studio.
I want to how to read data from the database every 5 seconds once
#Override
protected String doInBackground(String... voids) {
String result = "";
String name = voids[0];
String word = voids[1];
Log.d("myTag", "This is my test");
String connstr ="http://192.168.43.123/suruthi/login.php";
try {
URL url = new URL(connstr);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream ops = http.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ops, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8")+"="+URLEncoder.encode(name, "UTF-8")
+"&&"+ URLEncoder.encode("pass", "UTF-8")+"="+URLEncoder.encode(word, "UTF-8");
writer.write(data);
writer.flush();
writer.close();
ops.close();
InputStream ips = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ips, "ISO-8859-1"));
String line ="";
while ((line = reader.readLine()) != null)
{
result += line;
}
reader.close();
ips.close();
http.disconnect();
return result;
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
}
}
The below timer function is working only image changes but it is not suitable for reading a database ever 5 sec once
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
#Override
public void run()
{
/* iv.setImageResource(mThumbIds[i]);
i++;
if(i >= mThumbIds.length)
{
i=0;
}*/
doInBackground();
}
});}}
catch (InterruptedException e)
{
}}};
}
I tried above the timer function to read a database but it is not working..please guide me to resolve the issues..
When I'm trying to download html using this method:
public class DownloadHtml extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection connection = null;
try {
url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
char currentChar = (char) data;
result += currentChar;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
}
And logging a result
DownloadHtml downloadHtml = new DownloadHtml();
String result = null;
try {
result = downloadHtml.execute("http://stackoverflow.com").get();
} catch (Exception e) {
e.printStackTrace();
}
Log.i("Html", result);
I am gettin only small part of it.
Is there a way to get whole HTML of webpage?
Solution was simple. Looks like Log.i doesn't print everything in one go.
When I have tried to get all the links from HTML they were successfully printed.
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.
Has anyone tried this api ? I'm having some trouble implementing it on BlackBerry. Tweets do not always send and I cannot access posted tweets.
Here is my code -
private void twitterSetup(){
HttpRequest req = new HttpRequest("https://api.twitter.com/oauth/access_token");
req.setMethod(HttpConnection.POST);
XAuthSigner signer = new XAuthSigner("", "");
signer.signForAccessToken(req, "", "");
try {
HttpResponse resp = req.send();
if (resp.getCode() == HttpConnection.HTTP_OK)
{
Token accessToken = Token.parse(resp.getBodyContent());
req.close();
req = new HttpRequest("http://api.twitter.com/1/statuses/update.xml");
req.setMethod(HttpConnection.POST);
req.setBodyParameter("status", "new message");
req.setSigner(signer, accessToken);
resp = req.send();
Tweet[] twts = null;
try {
Credential c = new Credential("","","","");
UserAccountManager uam = UserAccountManager.getInstance(c);
List[] lists = null;
ListManager ter = null;
if (uam.verifyCredential()) {
ter = ListManager.getInstance(uam); //pode ser pela classe Timeline tambem.
ListManager listMngr = ListManager.getInstance(uam);
lists = listMngr.getLists();
}
ter.startGetListTweets(lists[0], null, new SearchDeviceListener() {
public void searchCompleted() {}
public void searchFailed(Throwable cause) {}
public void tweetFound(Tweet tweet) {
System.out.println(tweet);
}
});
}
catch(Exception e){
e.printStackTrace();
}
}
else { }
} catch (IOException e) {
e.printStackTrace();
}
catch(Exception e){
}finally {
try {
req.close();
} catch (IOException e) {}
}
}
Thanks for any help.
Ok,
Here is the class im using to get the twitter content based on type and tag. method getContent is not the most elegant but it works. It just downloads and parses a json file.
Look at http://search.twitter.com/api/
public class GetTwitterContent implements Runnable {
private String tag;
private String type;
public GetTwitterContent(String type, String tag) {
this.type = type;
this.tag = tag;
}
public void run() {
try {
Hashtable twitterValuesHashtable = new Hashtable();
String serviceUrl = "";
if (type.equalsIgnoreCase(Constants.TWITTER_CONTENT_TYPE_HASHTAG)) {
serviceUrl = Constants.TWITTER_CONTENT_HASHTAG_CONTENT;
} else if (type.equalsIgnoreCase(Constants.TWITTER_CONTENT_TYPE_USER)) {
serviceUrl = Constants.TWITTER_CONTENT_USER_CONTENT;
}
ByteArrayOutputStream baos = getContent(serviceUrl + this.tag);
JSONObject jsonObject = new JSONObject(new String(baos.toByteArray(), 0, baos.size(), "utf-8"));
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int counter = 0; counter < jsonArray.length(); ++counter) {
JSONObject thisJsonObject = (JSONObject) jsonArray.get(counter);
TwitterResponse twitterResponse = new TwitterResponse();
twitterResponse.setCreatedAt(thisJsonObject.optString("created_at", "na"));
twitterResponse.setTweetText(thisJsonObject.optString("text","na"));
twitterResponse.setFromUser(thisJsonObject.optString("from_user", "na"));
twitterValuesHashtable.put(new Integer(counter),twitterResponse);
}
ServerContent.future.addContent(Constants.TWITTER_KEY, twitterValuesHashtable);
} catch (Exception e) {
e.printStackTrace();
}
}
private ByteArrayOutputStream getContent(String url) {
ByteArrayOutputStream baos = null;
// len = 0;
try {
javax.microedition.io.HttpConnection connection = (javax.microedition.io.HttpConnection) Connector
.open(url);
connection.setRequestMethod(HttpConnection.GET);
// connection.setRequestProperty("Connection", "close");
java.io.InputStream inputStream = connection.openDataInputStream();
// inputStream = getClass().getResourceAsStream(url);
baos = new ByteArrayOutputStream();
int c;
while (true) {
c = inputStream.read();
if (c == -1)
break;
// ++len;
baos.write(c);
}
} catch (Exception e) {
e.printStackTrace();
}
return baos;
}
}