Trying to add an event to google places - google-maps

I am trying to use the Google Place Actions API, specifically the events and I cannot get a valid post for the life of me.
Here is the URL I am using:
https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=placesApiKey&duration=26000&reference=CjQwAAAAv4TTQ3ySXiGhOElWFNAQ-roLOfgwo215yRTk1Bmhg0jSJ-sAdz9nHgNgnGBAmqP7EhC7K0AjTfFcZgCUh68c2yNtGhRkmynXvE5d4XA5ZfyBqAxlNdsAIg&summary=this is going to be something fun
The reference is to Tempe, AZ. I keep getting a 404 back saying that it is an illegal request. Any help would be great! I really don't know what I am doing wrong.
I have tried three different ways both with the same results:
HttpClient client = new HttpClient();
client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String url = "https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=" + googlePlacesAPIKey;
PostMethod post = new PostMethod(url);
NameValuePair[] data = {
new NameValuePair("duration", Long.toString(duration)),
new NameValuePair("reference", reference),
new NameValuePair("summary", summary)
};
post.setRequestBody(data);
and
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=" + googlePlacesAPIKey);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("duration", Long.toString(duration)));
nameValuePairs.add(new BasicNameValuePair("reference", reference));
nameValuePairs.add(new BasicNameValuePair("summary", summary));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
}
and
URL url = new URL("https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key="+googlePlacesAPIKey+"&duration="+duration+"&reference="+reference+"&summary="+summary);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter( httpCon.getOutputStream());
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage()); out.close();
and
HttpPost post = new HttpPost("https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=" + googlePlacesAPIKey);
post.setHeader("Content-type", "application/json");
JSONObject object = new JSONObject();
object.put("duration", Long.toString(duration));
object.put("reference", reference);
object.put("summary", summary);
String message = object.toString();
post.setEntity(new StringEntity(message));
HttpResponse response = client.execute(post);
Here is the link to the API for those that are curious:
https://developers.google.com/places/documentation/actions#event_add

In python, you can do like this:
#!/usr/bin/python
# coding: utf8
import sys
import urllib
parameters = urllib.urlencode({
'key' : "YOUR_API_KEY",
'sensor' : 'false'
})
url = "https://maps.googleapis.com/maps/api/place/event/add/json?%s" % (parameters)
#The reference
reference = "CoQBdgAAAN4u...YKmgQ"
#Add event
postdata = '''
{
"duration": 86400,
"language": "ja",
"reference": "%s",
"summary": "Event Name!",
"url" : "http://hogehoge.com/test_page"
}
''' % (reference)
f = urllib.urlopen(url, postdata)
print f.read()

Ok, I'm not good for Java though, I created an example code for Android Java.
[MainActivity.java]
package com.example.placeseventtest;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private final String API_KEY = "YOUR_API_KEY";
private PlacesHTTP myUtil;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView resTxtView = (TextView) findViewById(R.id.responseText);
myUtil = new PlacesHTTP(API_KEY, resTxtView);
Button currentPosBtn = (Button) this.findViewById(R.id.currentPosBtn);
currentPosBtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
JSONObject params = new JSONObject();
JSONObject location = new JSONObject();
JSONArray types = new JSONArray();
try {
location.put("lat", 123.4556);
location.put("lng", 123.4556);
params.put("location", location);
params.put("accuracy", 20);
params.put("name", "Event Name");
//only one type is available.
types.put("parking");
params.put("types", types);
params.put("language", "en");
} catch (Exception e) {}
// Show the request JSON data.
TextView reqTxtView = (TextView) findViewById(R.id.requestText);
try {
reqTxtView.setText(params.toString(2));
} catch (Exception e) {}
// POST to Google Server
myUtil.execute(params);
}
});
}
}
[PlacesHTTP.java]
package com.example.placeseventtest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.widget.TextView;
public class PlacesHTTP extends AsyncTask<JSONObject, Void, HttpResponse>{
private HttpPost post;
private HttpClient httpClient;
private String url;
private TextView txtView;
public PlacesHTTP(String api_key, TextView resultView) {
url = String.format("https://maps.googleapis.com/maps/api/place/add/json?sensor=false&key=%s", api_key);
txtView = resultView;
}
protected void onPreExecute() {
httpClient = new DefaultHttpClient();
post = new HttpPost(url);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
}
#Override
protected HttpResponse doInBackground(JSONObject... params) {
//Send data as JSON format
JSONObject opts = params[0];
StringEntity strEntity;
HttpResponse response = null;
try {
strEntity = new StringEntity(opts.toString());
post.setEntity(strEntity);
response = httpClient.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(HttpResponse result) {
if (result != null) {
// Display the result
try {
txtView.setText(EntityUtils.toString(result.getEntity()));
} catch (Exception e) {
e.printStackTrace();
}
} else {
txtView.setText("null");
}
}
}
I got this result:

Related

Can't parse JSON data from URL with only username authentication

I'm using an url in order to read json data but it doesn't work because there is an authentication requested to get access to it using only the username (no login, no password only username). so my code show me the error :
java.io.IOException: Server returned HTTP response code: 401 for URL
My code is working using another URL with no authentication.
Could someone help me or give me and example that do the same thing.
many thanks to you in advance
package javaapplication3;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import org.json.JSONArray;
import org.json.JSONException;
public class JSONREST {
public static String callURL(String myURL) {
System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null) {
urlConn.setReadTimeout(60 * 1000);
}
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:" + myURL, e);
}
return sb.toString();
}
public static void main(String[] args) {
String jsonString = callURL("MY URL");
System.out.println("\n\njsonString: " + jsonString);
try {
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println("\n\njsonArray: " + jsonArray);
}
catch (JSONException e) {
e.printStackTrace();
}
}
}

Register Page Data store but no JSON encode received

I'm sure it's just a minor problem but I can't figure out what I need to change: I have a register page in my app. When the user inserts data, the data is passed to php script and stored in MYSQL database. The connection works as I get a new user in the db, but the json $success doesn't work - I want to make a Toast and change to a new activity if the user could register, but it does nothing when I click on the button.
Here is my Java Code:
package com.example.android.festivalapp;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class JetztRegistrieren extends Startseite {
Button bRegistrierungAbschliessen;
EditText etUserName, etUserMail, etUserPasswort, etUserPasswort2, etGeburtsdatum, etTelefonnummer;
RadioButton rbMaennlich, rbWeiblich;
RadioGroup rgGeschlecht;
protected String enteredname, enteredemail, enteredpassword, enteredpassword2, enteredGeb, enteredTelnr, userGender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jetzt_registrieren);
bRegistrierungAbschliessen = (Button) findViewById(R.id.bRegistrierungAbschliessen);
etUserName = (EditText) findViewById(R.id.etUserName);
etUserMail = (EditText) findViewById(R.id.etUserMail);
etUserPasswort = (EditText) findViewById(R.id.etUserPasswort);
etUserPasswort2 = (EditText) findViewById(R.id.etUserPasswort2);
etGeburtsdatum = (EditText) findViewById(R.id.etGeburtsdatum);
etTelefonnummer = (EditText) findViewById(R.id.etTelefonnummer);
rgGeschlecht = (RadioGroup) findViewById(R.id.rgGeschlecht);
rbMaennlich = (RadioButton) findViewById(R.id.rbMaennlich);
rbWeiblich = (RadioButton) findViewById(R.id.rbWeiblich);
bRegistrierungAbschliessen.setOnClickListener(new View.OnClickListener() {
//testen, ob Mail und Passwort ausgefüllt oder lang genug
#Override
public void onClick(View v) {
enteredname = etUserName.getText().toString();
enteredemail = etUserMail.getText().toString();
enteredpassword = etUserPasswort.getText().toString();
enteredpassword2 = etUserPasswort2.getText().toString();
enteredTelnr = etTelefonnummer.getText().toString();
enteredGeb = etGeburtsdatum.getText().toString();
userGender = ((RadioButton) findViewById(rgGeschlecht.getCheckedRadioButtonId())).getText().toString();
String serverUrl = "http://www.pou-pou.de/stagedriver/android/register.php";
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute(serverUrl, enteredname, enteredemail, enteredpassword, enteredpassword2, enteredTelnr, enteredGeb, userGender);
if (enteredname.equals("") || enteredemail.equals("") || enteredpassword.equals("") || enteredpassword2.equals("") || enteredGeb.equals("")) {
Toast.makeText(JetztRegistrieren.this, "Bitte alle Felder ausfüllen", Toast.LENGTH_LONG).show();
return;
}
}
class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost("http://www.pou-pou.de/stagedriver/android/register.php");
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("enteredname", params[1]));
nameValuePairs.add(new BasicNameValuePair("enteredemail", params[2]));
nameValuePairs.add(new BasicNameValuePair("enteredpassword", params[3]));
nameValuePairs.add(new BasicNameValuePair("enteredpassword2", params[4]));
nameValuePairs.add(new BasicNameValuePair("enteredTelnr", params[5]));
nameValuePairs.add(new BasicNameValuePair("enteredGeb", params[6]));
nameValuePairs.add(new BasicNameValuePair("userGender", params[7]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
int jsonResult = returnParsedJsonObject(result);
if (jsonResult == 0) {
Toast.makeText(JetztRegistrieren.this, "Passwörter stimmen nicht überein", Toast.LENGTH_LONG).show();
return;
}
if (jsonResult == 1) {
Intent intent = new Intent(JetztRegistrieren.this, Startseite.class);
Toast.makeText(JetztRegistrieren.this, "Willkommen bei Stage Driver! Jetzt loslegen.", Toast.LENGTH_LONG).show();
startActivity(intent);
return;
}
System.out.println("Resulted Value: " + result);
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
private int returnParsedJsonObject(String result) {
JSONObject resultObject = null;
int returnedResult = 2;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
});
}
}
And this is the php file:
<?php
include('config.php');
session_start();
$name = $_POST["enteredname"];
$pass = $_POST["enteredpassword"];
$pass2 = $_POST["enteredpassword2"];
$email = $_POST["enteredemail"];
$tel = $_POST["enteredTelnr"];
$geb = $_POST["enteredGeb"];
$gender = $_POST["userGender"];
if($pass != $pass2) {
$success = 0;
}
else {
$hash = md5($pass);
$speichern = "INSERT INTO user (user_name, user_pw, user_mail, user_tel, user_geb, user_geschl)
VALUES('$name', '$hash', '$email', '$tel', '$geb', '$gender');";
mysql_query($speichern) or die(mysql_error());
if($speichern) {
$success = 1;
}
}
echo json_encode($success);
?>
Thanks in advance!
The problem is that you are not returning an HTTP header for the content type you are returning.
Add this to the top of your php script:
header("Content-Type: application/json;charset=utf-8");
So I think I found the error, in the log it says the jsonresult cannot be converted, it's because in the php script I wrote $success = 0; but instead I think it has to be something like $response["success"] = 0;

Using XPages to get data from managed bean

I am trying to create a list of Twitter users, populating it with the number of followers for the user and their profile image. Because of Twitter's API, you need to get an access token for your application prior to using their REST API. I thought the best way to do this was via Java and a managed bean. I posted the code below, which currently works. I get the access token from Twitter, then make the API call to get the user info, which is in JSON.
My question is, what is the best way to parse the JSON and iterate over a list of user names to create a table/grid on the XPage?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.binary.Base64;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class TwitterUser implements Serializable {
private static final String consumerKey = "xxxx";
private static final String consumerSecret = "xxxx";
private static final String twitterApiUrl = "https://api.twitter.com";
private static final long serialVersionUID = -2084825539627902622L;
private static String accessToken;
private String twitUser;
public TwitterUser() {
this.twitUser = null;
}
public String getTwitterUser(String screenName) {
try {
this.requestTwitterUserInfo(screenName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return twitUser;
}
public void setTwitterUser() {
twitUser = twitUser;
}
//Encodes the consumer key and secret to create the basic authorization key
private static String encodeKeys(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret, "UTF-8");
String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes());
return new String(encodedBytes);
}
catch (UnsupportedEncodingException e) {
return new String();
}
}
//Constructs the request for requesting a bearer token and returns that token as a string
private static void requestAccessToken() throws IOException {
HttpsURLConnection connection = null;
String endPointUrl = twitterApiUrl + "/oauth2/token";
String encodedCredentials = encodeKeys(consumerKey,consumerSecret);
String key = "";
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Your Program Name");
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
writeRequest(connection, "grant_type=client_credentials");
// Parse the JSON response into a JSON mapped object to fetch fields from.
JSONObject obj = (JSONObject)JSONValue.parse(readResponse(connection));
if (obj != null) {
String tokenType = (String)obj.get("token_type");
String token = (String)obj.get("access_token");
accessToken = ((tokenType.equals("bearer")) && (token != null)) ? token : "";
}
else {
accessToken = null;
}
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
private void requestTwitterUserInfo(String sn) throws IOException {
HttpsURLConnection connection = null;
if (accessToken == null) {
requestAccessToken();
}
String count = "";
try {
URL url = new URL(twitterApiUrl + "/1.1/users/show.json?screen_name=" + sn);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Your Program Name");
connection.setRequestProperty("Authorization", "Bearer " + accessToken);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setUseCaches(false);
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
twitUser = readResponse(connection);
}
//Writes a request to a connection
private static boolean writeRequest(HttpsURLConnection connection, String textBody) {
try {
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
wr.write(textBody);
wr.flush();
wr.close();
return true;
}
catch (IOException e) { return false; }
}
// Reads a response for a given connection and returns it as a string.
private static String readResponse(HttpsURLConnection connection) {
try {
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while((line = br.readLine()) != null) {
str.append(line + System.getProperty("line.separator"));
}
return str.toString();
}
catch (IOException e) { return new String(); }
}
}
A few pointers:
Domino has the Apache HTTP client classes. They tend to be more robust than raw HTTP connections
Define a new class as a bean that contains all values that you want to see per row. You only need the getters public
add a method to your managed bean Collection getAllData()
bind that to a repeat control
you then can use repeatvar.someProperty in column values in EL
use better names than I just used

Google docs api for Java (exception)

I have a problem with google docs. I want to retrieve all your files by using OAuth 2.0. The problem is that once you do, and authorization when trying to download a file gives me this error:
Exception in thread "main" java.lang.NullPointerException
at GoogleBlack.readUrl(GoogleBlack.java:95)
at GoogleBlack.getDocument(GoogleBlack.java:87)
at GoogleBlack.go(GoogleBlack.java:187)
at GoogleBlack.main(GoogleBlack.java:222)
Here's the code I use
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.GoogleAuthTokenFactory.UserToken;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.util.ServiceException;
public class GoogleBlack {
private static final String APPLICATION_NAME = "Homework";
public DocsService service;
public GoogleService spreadsheetsService;
static String CLIENT_ID = "***********";
static String CLIENT_SECRET = "**************";
static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
static List<String> SCOPES = Arrays.asList("https://docs.google.com/feeds");
public void getSpreadSheet(String id, String i, String ids, String type) throws Exception {
UserToken docsToken = (UserToken) service.getAuthTokenFactory()
.getAuthToken();
UserToken spreadsheetsToken = (UserToken) spreadsheetsService
.getAuthTokenFactory().getAuthToken();
service.setUserToken(spreadsheetsToken.getValue());
URL url = null;
if(type.equals("doc"))
{
url = new URL("https://docs.google.com/feeds/download/documents/Export?id="+ ids);
}
else
{
url = new URL("https://docs.google.com/feeds/download/spreadsheets/Export?key="+ ids +"&exportFormat="+ type + "&gid=0");
i += ".xls";
}
System.out.println("Spred = " + url.toString());
readUrl1(url.toString(), i, type);
service.setUserToken(docsToken.getValue());
}
public void readUrl1(String url, String i, String type) throws IOException, ServiceException
{
MediaContent mc = new MediaContent();
mc.setUri(url);
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
}
public void getDocument(String id, String i) throws Exception {
URL url = new URL(id);
readUrl(url,i);
}
public void readUrl(URL url, String i) throws Exception {
MediaContent mc = new MediaContent();
mc.setUri(url.toString());
System.out.println("Url "+ url.toString());
System.out.println("MC: " + mc.toString());
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
// FileOutputStream fout = null;
// fout = new FileOutputStream(i);
// fout.write(cbuf.);
// fout.close();
}
static Credential getCredentials() {
HttpTransport transport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
// Step 1: Authorize -->
String authorizationUrl =
new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).build();
// Point or redirect your user to the authorizationUrl.
System.out.println("Go to the following link in your browser:");
System.out.println(authorizationUrl);
// Read the authorization code from the standard input stream.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is the authorization code?");
String code = null;
try {
code = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 1 <--
// Step 2: Exchange -->
GoogleTokenResponse response = null;
try {
response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
code, REDIRECT_URI).execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 2 <--
// Build a new GoogleCredential instance and return it.
return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.setJsonFactory(jsonFactory).setTransport(transport).build()
.setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken());
}
public void go() throws Exception {
DocsService service = new DocsService(APPLICATION_NAME);
service.setOAuth2Credentials(getCredentials());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentListFeed feed = service.getFeed(feedUrl, DocumentListFeed.class);
System.out.println("Feed " + feed.getEntries().size());
for(int i = 0; i < feed.getEntries().size(); i++)
{
DocumentListEntry entry = feed.getEntries().get(i);
if(entry.getType().equals("file"))
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
System.out.println("URL "+ UrlForDownload);
getDocument(UrlForDownload, entry.getFilename());
}
else
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("URL "+ UrlForDownload);
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
if(entry.getTitle().getPlainText().equals("Web Design 2011/2012 - Материали"))
{
continue;
}
if(entry.getType().equals("spreadsheet"))
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"xls");
}
else
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"doc");
}
}
}
}
public static void main(String[] args) throws Exception {
new GoogleBlack().go();
}
}
95 row - MediaSource ms = service.getMedia(mc);
87 row - readUrl(url,i);
187 row - getDocument(UrlForDownload, entry.getFilename());
222 row - new GoogleBlack().go();
I apologize if I am not well explained!!!
You never initialized the "public DocsService service;" member of your GoogleBlack class, so when you call "service.getMedia(mc);" you're getting a NullPointerException.

MySQL db connection

I have been searching the web for a connection between my Android simulator and a MySQL db.
I've found that you can't connect directly but can via a web server. The web server will handle my request from my Android.
I found the following code on Hello Android, but I don't understand. If I run this code on the simulator, nothing happens; the screen stays black.
Where does Log.i land, in the Android screen, the error log, or somewhere else?
Can somebody help me with this code?
package app.android.ticket;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class fetchData extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//call the method to run the data retreival
getServerData();
}
public static final String KEY_121 = "http://www.jorisdek.nl/android/getAllPeopleBornAfter.php";
public fetchData() {
Log.e("fetchData", "Initialized ServerLink ");
}
private void getServerData() {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Logging messages go in the Log cat. You could also use LogCat Reader.