Has anyone used this twitter api - http://www.twapime.com/ - java

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;
}
}

Related

Problem with getting JSON to android app, propably problem with url

I think i did something wrong with string named "url", but im not sure what should i change, what am i doing wrong?
I didn't want to share my api key, normally it is there.
I use no commercial version of flickr.
Main activity:
FlickrFetchr flickrFetchr = new FlickrFetchr();
Log.d("HTTP_JSON",flickrFetchr.getJSONString());
JsonString is always "sth went wrong"
FlickrFetchr class:
public class FlickrFetchr {
String API_KEY = "MY_API";
HttpsURLConnection connection;
public byte[] getUrlBytes(String urlSpec)
{
try {
URL url = new URL(urlSpec);
connection = (HttpsURLConnection) url.openConnection();
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream imput = connection.getInputStream();
if(connection.getResponseCode() != HttpsURLConnection.HTTP_OK) {
throw new Exception();
}
int bytesRead;
byte [] buffer = new byte[1024] ;
do {
bytesRead = imput.read(buffer);
out.write(buffer,0,bytesRead);
}while (imput.read(buffer)>0);
out.close();
return out.toByteArray();
}catch (Exception e) {
Log.e("HTTPeerpr", e.getMessage());
byte[] emptyArray = new byte[0];
return emptyArray;
}
finally {
connection.disconnect();
}
}
public String getURLString(String urlSpec)
{
return getUrlBytes(urlSpec).toString();
}
public String getJSONString()
{
String jsonString = "sth went wrong";
try {
String url = Uri.parse("https://api.flickr.com/services/rest/")
.buildUpon()
.appendQueryParameter("method", "flickr.photos.getRecent")
.appendQueryParameter("api key", API_KEY)
.appendQueryParameter("format", "json")
.appendQueryParameter("nojsoncallback", "1")
.appendQueryParameter("extras", "url_s")
.build().toString();
jsonString = getURLString(url);
}catch (Exception je)
{
Log.e("JSON_ERROR", je.getMessage());
}
return jsonString;
}
}
Thanks for your help.

How to Save "Data.Json" file from assets to internal Storage and then use it for read/write

Currently i am fetching a package details(Onnet Minutes, Offnet Minutes, etc) from a Json file "Data.json" from assets but i know we cannot change values from assets. So my Question is how to copy Data.json to internal storage and then Load it for read/Write.
I am using this to load Data.Json from Assets
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("Data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
Toast.makeText(jazz_sim_lagao_offer_details.this, "JSON Loaded", Toast.LENGTH_SHORT).show();
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and using this code to update data
private void UpdateData() {
JSONObject JSONobj = null;
try {
loadJSONFromAsset();
//get JSONObject from JSON file
JSONobj = new JSONObject(loadJSONFromAsset());
//fetch JSONObject named
JSONObject Jazz_SimLagaoOffer = JSONobj.getJSONObject("packages").getJSONObject("jazz_packages").getJSONObject("call_packages").getJSONObject("sim_lagao_offer");
String Jazz_SimLagaoOffer_ONNET = Jazz_SimLagaoOffer.getString("onnet");
Jazz_SimLagaoOffer_OnNet_TextView.setText(Jazz_SimLagaoOffer_ONNET);
String Jazz_SimLagaoOffer_OFFNET = Jazz_SimLagaoOffer.getString("offnet");
Jazz_SimLagaoOffer_OffNet_TextView.setText(Jazz_SimLagaoOffer_OFFNET);
String Jazz_SimLagaoOffer_MBs = Jazz_SimLagaoOffer.getString("mbs");
Jazz_SimLagaoOffer_Mb_TextView.setText(Jazz_SimLagaoOffer_MBs);
String Jazz_SimLagaoOffer_SMS = Jazz_SimLagaoOffer.getString("sms");
Jazz_SimLagaoOffer_Sms_TextView.setText(Jazz_SimLagaoOffer_SMS);
String Jazz_SimLagaoOffer_SUBCODE = Jazz_SimLagaoOffer.getString("sub_code");
Jazz_SimLagaoOffer_Sub_Code_TextView.setText(Jazz_SimLagaoOffer_SUBCODE);
String Jazz_SimLagaoOffer_CHECKCODE = Jazz_SimLagaoOffer.getString("check_code");
Jazz_SimLagaoOffer_Check_Code_TextView.setText(Jazz_SimLagaoOffer_CHECKCODE);
String Jazz_SimLagaoOffer_UNSUBCODE = Jazz_SimLagaoOffer.getString("unsub_code");
Jazz_SimLagaoOffer_Unsub_Code_TextView.setText(Jazz_SimLagaoOffer_UNSUBCODE);
Jazz_SimLagaoOffer_Charges = Jazz_SimLagaoOffer.getString("charges");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), JSONobj + "", Toast.LENGTH_SHORT).show();
}
}
How to Get Json Object?
Here is My Data.Json
{
"packages" : {
"jazz_packages" : {
"call_packages" : {
"sim_lagao_offer" : {
"charges" : "0.01",
"check_code" : "*551*2#",
"mbs" : "1500",
"offnet" : "5000",
"onnet" : "3000",
"sms" : "3000",
"sub_code" : "*551#",
"unsub_code" : "*551*3#"
}
}
}
}
}
Try this
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(YOUR_ASSETS_FILE); // if files resides inside the "Files" directory itself
out = new FileOutputStream(STORAGE_PATH).toString() +"/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
e.printStackTrace();
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Use below code to read from storage
String jsongString = readFromFile();
JSONObject mainJsonObject = new JSONObject(jsongString);
JSONObject Jazz_SimLagaoOffer = mainJsonObject.getJSONObject("packages").getJSONObject("jazz_packages").getJSONObject("call_packages").getJSONObject("sim_lagao_offer");
Use below method to read data from internal storage file and return as String.
private String readFromFile() {
String ret = "";
InputStream inputStream = null;
try {
inputStream = openFileInput("names.json");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
Hope this work :)
I Got Answer my own Question after 1 Day Research and Thanks to #pratik vekariya
helped me a lot.
CopyAssets() works perfect as defined #pratik vekariya in his answer and to readfromfile see my Question loadJSONFromAssets()
and i Just replaced line
InputStream is = getAssets().open("Data.json");
with this
InputStream is = new FileInputStream(getFilesDir().toString() +"/" + "Data.json");
to to load .json file from files and get json object from inputStrem

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”)

Extract value from Json using Gson

I am trying to extract values from JSON from the URL provided below using GSON java library:
http://api.wunderground.com/api/b28d047ca410515a/forecast/q/-33.912,151.013.json
I have successfully used the code provided below to extract data from URL below:
http://api.wunderground.com/api/b28d047ca410515a/conditions/q/-33.912,151.013.json
Code:
String url = "http://api.wunderground.com/api/b28d047ca410515a/conditions/q/-33.912,151.013.json";
String url2 = "http://api.wunderground.com/api/b28d047ca410515a/forecast/q/-33.912,151.013.json";
InputStream is = null;
try {
is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JsonElement je = new JsonParser().parse(jsonText);
System.out.println("Current Temperature:" + getAtPath(je, "current_observation/temp_c").getAsString() );
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
However I am getting exception trying to extract from url2 as per code below , it seems to be a more complicated json to get values from, any help please?
// below code not working
weather_icon_url = getAtPath(je, "current_observation/icon_url").getAsString();
is = new URL(url2).openStream();
BufferedReader rd2 = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText2 = readAll(rd2);
JsonElement je2 = new JsonParser().parse(jsonText2);
System.out.println("max Temperature:" + getAtPath(je2, "forecast/simpleforecast/forecastday/high/celsius").getAsString() );
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
getAtPath code:
private static JsonElement getAtPath(JsonElement e, String path) {
JsonElement current = e;
String ss[] = path.split("/");
for (int i = 0; i < ss.length; i++) {
current = current.getAsJsonObject().get(ss[i]);
}
return current;
}
The problem you are facing is because there is an issue with the getAtPath implementation.
[{"date":{"epoch":"1459152000"... represents a JSONArray which the method is trying to access as JSONObject. Hence the IllegalStateException.
JsonObject com.google.gson.JsonElement.getAsJsonObject()
convenience method to get this element as a JsonObject. If the element
is of some other type, a IllegalStateException will result. Hence it
is best to use this method after ensuring that this element is of the
desired type by calling isJsonObject() first.
You can update and use something like below, as of now it returns only the first element.
private static JsonElement getAtPath(JsonElement e, String path) {
JsonElement current = e;
String ss[] = path.split("/");
for (int i = 0; i < ss.length; i++) {
if(current instanceof JsonObject){
current = current.getAsJsonObject().get(ss[i]);
} else if(current instanceof JsonArray){
JsonElement jsonElement = current.getAsJsonArray().get(0);
current = jsonElement.getAsJsonObject().get(ss[i]);
}
}
return current;
}
This should work:
System.out.println("max Temperature:" + getAtPath(je2, "forecast/simpleforecast/forecastday/high/celsius").getAsString() );

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.

Categories

Resources