Android Programming - Post Google Form/Spreedsheet (REQUIRED FIELD) - java

So I have successfully post data onto a Google Spreadsheet using the Google Form source. Everything works perfect UNTIL I make the field (in the Google Form) "required." When I do that, the Android Emulator still responds as if the information sent was properly saved. But on the Google spreadsheet it isn't there.
Am I missing something?
This is my AsyncTask:
new BackgroundTask().execute(
"https://docs.google.com/forms/d/10QStmb9Nr-hcfv889FMSNTZdA_hNUErxeK7vISzkx0E/formResponse",
student.FirstName, "entry_2030274183=",
student.LastName, "entry_1558758483=",
student.Age, "entry_1871336861=",
student.Gender, "entry.2013677542=",
student.Grade, "entry_1921311866=");
This is my Background.
protected String doInBackground(String... params) {
HttpRequest reg = new HttpRequest();
String URL = params[0];
String FirstName = params[1];
String FirstNameEntry = params[2];
String LastName = params[3];
String LastNameEntry = params[4];
String Age = params[5];
String AgeEntry = params[6];
String Gender = params[7];
String GenderEntry = params[8];
String Grade = params[9];
String GradeEntry = params[10];
#SuppressWarnings("deprecation")
String data =
FirstNameEntry + URLEncoder.encode(FirstName) + "&" +
LastNameEntry + URLEncoder.encode(LastName) + "&" +
AgeEntry + URLEncoder.encode(Gender) + "&" +
GenderEntry + URLEncoder.encode(Age) + "&" +
GradeEntry + URLEncoder.encode(Grade);
String response = reg.sendPost(URL, data);
return response;
}
Do I need to put something in the entries if it is a required field?
If you want to look at the HttpRequest class go here (Not My Code):
Secure HTTP Post in Android
Much Appreciated

The only way I can immediately think of is by processing the response and then making your app behave accordingly.
For instance - I tried one test form and if the request send had some required field empty, then the HTTPResponse contains "Looks like you have a question or two that still need attention".
Another way would be to validate if the save was actually successful by searching for the text you gave in the "Confirmation Page".
In both cases, you should be able to differentiate between a successful post and a failed one.

Related

Twilio URL on different servers

how can i parse into url of my current application URI.create(String) when trying to call a number? I would like to parse on the test server http://localhost:8089 etc, but address on the production will be different.
I have tried to get the url
((ServletRequestAttributes) RequestContextHolder.
currentRequestAttributes()).getRequest();
String baseEnvLinkURL = "http://" + currentRequest.getLocalName();
if(currentRequest.getLocalPort() != 80) {
baseEnvLinkURL += ":" + currentRequest.getLocalPort();
}
if(!StringUtils.isEmpty(currentRequest.getContextPath())) {
baseEnvLinkURL += currentRequest.getContextPath();
}
but that returns http://0:0:0:0:...:8089/
Is it possible to somehow do it without getting it from different URL? Just parsing some kind of instance of something?
Thanks.

Error using DocuSign AuthenticationApi.login() for Legacy Authentication - Missing grant_type/code

I'm trying to use the Authentication::login() API call in the DocuSign Java SDK and am receiving an error. Here's some code:
#Component
public class TestClass {
private ApiClient apiClient;
public void authenticate() {
this.apiClient = new ApiClient("account-d.docusign.com", "docusignAccessCode",
"mySecretIntegratorKey", "myClientSecret");
final AuthenticationApi authenticationApi = new AuthenticationApi(this.apiClient);
try {
// ERROR ON THE LINE BELOW
final LoginInformation loginInformation = authenticationApi.login();
} catch (final ApiException e) {
// do something appropriate
}
}
}
The mySecretIntegratorKey and myClientSecret values are not the real values I'm sending in obviously, but the other ones are.
Here is the error I am receiving when making the login() call:
Caused by: org.apache.oltu.oauth2.common.exception.OAuthSystemException: Missing grant_type/code
at com.docusign.esign.client.auth.OAuth$OAuthJerseyClient.execute(OAuth.java:184)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:65)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:55)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:71)
at com.docusign.esign.client.auth.OAuth.updateAccessToken(OAuth.java:92)
... 123 common frames omitted
I realize that this is using the older legacy authentication, however I have a limitation that won't allow me to upgrade to the newer method of authentication until the first of the year. So for now I need to use this legacy method using SDK Version 2.2.1.
Any ideas what I'm doing wrong here? I'm sure it is something simple...
Thank you for your time.
You want to use Legacy authentication?
In that case you need to make a number of updates to your code.
Only call new ApiClient(base_url)
Set the X-DocuSign-Authentication header--
From an old Readme:
String authHeader = "{\"Username\":\"" + username +
"\",\"Password\":\"" + password +
"\",\"IntegratorKey\":\"" + integratorKey + "\"}";
apiClient.addDefaultHeader("X-DocuSign-Authentication", authHeader);
Then use the authenticationApi.login to look up the user's Account ID(s) and matching base urls.
The authenticationApi.login doe not actually log you in. (!)
Rather, that method just gives you information about the current user.
There is no login with the API since it does not use sessions. Instead, credentials are passed with every API call. The credentials can be an Access Token (preferred), or via Legacy Authentication, a name / password / integration key triplet.
When using Legacy Authentication, the client secret is not used.
More information: see the Readme section for using username/password in this old version of the repo.
Just in case someone was looking for complete legacy code that works! The below C# code snippet works. This is production ready code. I've tested it and it works. You will have to create an EnvelopeDefinition separately as this code is not included. However, the piece below will authenticate the user and will successfully send an envelope and get back the Envelope ID:
string username = "john.bunce#mail.com";
string password = "your_password";
string integratorKey = "your_integration_key";
ApiClient apiClient = new ApiClient("https://www.docusign.net/restapi");
string authHeader = "{\"Username\":\"" + username + "\", \"Password\":\"" + password + "\", \"IntegratorKey\":\"" + integratorKey + "\"}";
apiClient.Configuration.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
AuthenticationApi authApi = new AuthenticationApi(apiClient.Configuration);
LoginInformation loginInfo = authApi.Login();
string accountId = loginInfo.LoginAccounts[0].AccountId;
string baseURL = loginInfo.LoginAccounts[0].BaseUrl;
string[] baseUrlArray= Regex.Split(baseURL, "/v2");
ApiClient apiClient2 = new ApiClient(baseUrlArray[0]);
string authHeader2 = "{\"Username\":\"" + username + "\", \"Password\":\"" + password + "\", \"IntegratorKey\":\"" + integratorKey + "\"}";
apiClient2.Configuration.AddDefaultHeader("X-DocuSign-Authentication", authHeader2);
EnvelopesApi envelopesApi = new EnvelopesApi(apiClient2.Configuration);
EnvelopeSummary results = envelopesApi.CreateEnvelope(accountId, envelopeDefinition);
string envelopeID = results.EnvelopeId;

reading two variable values after decrypting

I am working on "Forgot Password". I am trying to create a reset token with email + current_time. email is user login whilst code will check if time >= 5 minutes then this link will not work. Here is my code:
// preparing token email + time
Date now = new Date();
String prepareToken = "?email="+email+"&tokenTime="+now.getTime();
// encrypt prepareToken value
Encryptor enc = new Encryptor();
resetToken = enc.encrypt(resetToken);
The token will be sent as for example as http://domainname.com/ForgotPassword?resetToken=adj23498ljj238809802340823
Problem:
When user click it then I got as request parameter and obviously decrypt this parameter but how can I get email in one String + time as another String
Please advise
If your issue is simply parsing the decoded String to get some sort of Map of your parameters, I'd suggest you to read Parse a URI String into Name-Value Collection .
Hope it helps.
EDIT :
Assuming you have the splitQuery(URL url) method from the previous link and that you successfully decoded the token :
public String getEmailFromToken(String decodedToken) {
// if you decoded your token it will looks like the prepareToken String
String stubUrl = "http://localhost"+decodedToken;
Map<String,String> map = splitQuery(new URL(stubUrl));
return map.get("timeToken");
}
I created a properly formed URL to respect the URL syntax.
With little tweak, you should be able to implement splitQuery for a String. I hope you can manage that.

Passing parameters to YQL using Java

I am using the following code:
String zip = "75227";
String str = "http://query.yahooapis.com/v1/public/yql?q=select%20Title%2C%20Address%2C%20" +
"City%2C%20State%2C%20Phone%2C%20Distance%20from%20local.search%20where%20query%3D%22" +
"food%20pantries%22%20and%20zip%3D%22" + zip +"%22%20and%20(category%3D%2296927050%22%20or" +
"%20category%3D%2296934498%22)%20%7C%20sort(field%3D%22Distance%22)";
Document doc = Jsoup.connect(str).get();
and it is producing the results I want by replacing the zip code value. I would like to also change the location. I tried doing the same I did with the zip code by doing this:
String zip = "32207";
String service = "food pantry";
String testOne = "http://query.yahooapis.com/v1/public/yql?q=select%20Title%2C%20Address%2C%20" +
"City%2C%20State%2C%20Phone%2C%20Distance%20from%20local.search%20where%20query%3D%22" +
service + "%22%20and%20zip%3D%22" + zip +"%22%20and%20(category%3D%2296927050%22%20or" +
"%20category%3D%2296934498%22)%20%7C%20sort(field%3D%22Distance%22)";
When used this way the variable "service" gave me an error.
I initially tried to use the yql table like this:
String search = "http://query.yahooapis.com/v1/public/yql?q=";
String table = "select Title, Address, City, State, Phone, Distance from local.search where " +
"query=\"food pantries\" and zip=\"75227\" and (category=\"96927050\" or category=" +
"\"96934498\") | sort(field=\"Distance\")";
String searchText = search + table;
UPDATE:
Here is the error I am getting:
Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=505, URL=http://query.yahooapis.com/v1/public/yql?q=select%20Title%2C%20Address%2C%20City%2C%20State%2C%20Phone%2C%20Distance%20from%20local.search%20where%20query%3D%22food pantry%22%20and%20zip%3D%2232207%22%20and%20(category%3D%2296927050%22%20or%20category%3D%2296934498%22)%20%7C%20sort(field%3D%22Distance%22)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:418)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:393)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:159)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:148)
at org.jsoup.examples.HtmlToPlainText.main(HtmlToPlainText.java:86)
However, this did not work either. Any ideas on how I can do this search and provide the service and zip code as variables?
Have you tried replacing String service = "food pantry"; with String service = "food%20pantry"; ?
EDIT:
and it is "food pantry" or "food pantries"... ?

Access to Facebook API using REST and HttpClient

I am going to use RESTful Web Services and HttpClient to access Facebook API REST Server.
Am somewhat of a newbie to REST and Facebook APIs...
Question(s):
Verification / Authorization
(1) If I have a session key sent by a client app, how do I verify and authenticate that the user exists and then query for his / her friends on the server side?
How can I be access these Facebook RESTful end points:
http://wiki.developers.facebook.com/index.php/Users.getInfo
and
http://wiki.developers.facebook.com/index.php/Friends.getLists
via a HTTP GET Request? Meaning, what does the full URL look like including parameters?
(2) What would the full RESTful URL look like to grab the APIs (which I have listed above)?
Posting to a Friend's Wall
(3) After verification / authorization, querying users friends, how (which API) would I use to a post to a Friend's Wall?
(4) Is there any additional parameters that I need to append to the Facebook RESTful Server's URL?
HTTP Client
(5) Do I include the RESTful web service calls to these Facebook APIs inside my Java program through HttpClient?
Happy programming and thank you for taking the time to read this...
I can't answer all your questions but the method calls are made via http://api.facebook.com/restserver.php so a call to users.getInfo looks like this
http://api.facebook.com/restserver.php?method=users.getinfo
You also need to pass in your api key and any other parameters the method needs. But rather than make the http calls yourself there must be some Java library that abstracts all this away for you.
As for this being a REST API - there's one web service endpoint with method scoping in the URL and all calls are made via HTTP GET or POST.
Frankly, this is RPC over HTTP and about as far from REST as you can get (no pun intended!). Facebook should change their API documentation, it's just plain wrong.
In terms of creating the URL, I've used this code which seems to work pretty well...
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
// Written by Stuart Davidson, www.spedge.com
public class JSONComm
{
private final String JSON_URL = "http://api.facebook.com/restserver.php";
private final String fbSecretKey = "xxx";
private final String fbApiKey = "xxx";
private final String fbApiId = "xxx";
private int callId = 0;
public int getNextCall() { callId++; return callId; }
public String getApiKey() { return fbApiKey; }
public String getApiId() { return fbApiId; }
public String getRestURL(HashMap<String, String> args)
{
String url = JSON_URL + "?";
for(String arg : args.keySet()) { url = url + arg + "=" + args.get(arg) + "&"; }
String sig = getMD5Hash(args);
url = url + "sig=" + sig;
return url;
}
public String getMD5Hash(HashMap<String, String> args)
{
String message = "";
Vector<String> v = new Vector<String>(args.keySet());
Collections.sort(v);
Iterator<String> it = v.iterator();
while(it.hasNext())
{
String tmp = it.next();
message = message + tmp + "=" + args.get(tmp);
}
message = message + fbSecretKey;
try{
MessageDigest m = MessageDigest.getInstance("MD5");
byte[] data = message.getBytes();
m.update(data,0,data.length);
BigInteger i = new BigInteger(1,m.digest());
return String.format("%1$032X", i).toLowerCase();
}
catch(NoSuchAlgorithmException nsae){ return ""; }
}
}
Make sure you see the critical components - the fact that the arguments are alphabetically sorted, and that the whole thing is encrypted using MD5, but the string that is encrypted is slightly different than the URL string.
Also note that the API keys need to be filled in!
So, to get the URL for the method User.getInfo and return the first and last names, I'd do the following...
public String getFbURL(String callback, Long playerId)
{
HashMap<String, String> args = new HashMap<String, String>();
args.put("api_key", jsonComm.getApiKey());
args.put("call_id", "" + jsonComm.getNextCall());
args.put("v", "1.0");
args.put("uids", "" + playerId);
args.put("fields", "first_name,last_name");
args.put("format", "JSON");
args.put("method", "Users.getInfo");
args.put("callback", "" + callback);
return jsonComm.getRestURL(args);
}
Hope this helps :)

Categories