google search in Java - google-search-api

Here's some code I found on StackExchange:
public static void main(String[] args) throws Exception {
String key="YOUR KEY";
String qry="Android";
URL url = new URL(
"https://www.googleapis.com/customsearch/v1?key="+key+ "&cx=013036536707430787589:_pqjad5hr1a&q="+ qry + "&alt=json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
if(output.contains("\"link\": \"")){
String link=output.substring(output.indexOf("\"link\": \"")+("\"link\": \"").length(), output.indexOf("\","));
System.out.println(link); //Will print the google search links
}
}
conn.disconnect();
}
My question is: how do I restrict the search using filetype:pdf ?

Use :<file-extension in the query> of the search item.
For example
GET https://www.googleapis.com/customsearch/v1?
key=INSERT-YOUR-KEY&cx=013036536707430787589:_pqjad5hr1a&q=flowers:pdf&alt=json
For other parameters applicable visit
https://developers.google.com/custom-search/v1/using_rest

Related

I got notification from FCM of google, but my messageBody was garbled. How to resolve it?

Post was successful, but the message body was garbled.
{"data":{"data_content":"測試","data_title":"Joyce"},"notification":{"body":"測試","title":"test"},"to":"myDeviceId"}
this.is my post code , is there any wrong? Thanks.
<pre><code>
public class HttpConnection {
public void startConnection(final String apiUrl, final String jsonStr, final OnPostNotificationListener listener) {
new Thread(new Runnable() {
#Override
public void run() {
HttpURLConnection conn = null;
StringBuilder response = new StringBuilder();
try {
URL url = new URL(apiUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization","key=Key");
conn.setRequestProperty("Content-Type","application/json");
conn.setRequestMethod("POST");
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
OutputStream os = conn.getOutputStream();
DataOutputStream writer = new DataOutputStream(os);
writer.writeBytes(jsonStr);
writer.flush();
writer.close();
os.close();
//Get Response
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
response.append('\r');
}
listener.onSuccessful(response.toString());
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
listener.onFail(ex.toString());
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}).start();
}
public interface OnPostNotificationListener{
void onSuccessful(String result);
void onFail(String exception);
}
}
</code></pre>
Thank you for your help.The picture of the phone
The problem comes from writeBytes method and the representation of kanjis (or other non ISO-8859-1 characters). You should use writeUTF method instead :
writer.writeUTF(jsonStr);
You can take a look at this post explaning the difference between writeBytes and writeUTF. Basically, you should always use writeUTF when writing strings.

Rally: How to Map test cases with user stories using REST API?

I am writing code to create new test cases using rally restAPI.
Able to create the test cases under Test Plan & Test folder.
Now, want to map those test cases to Rally user stories.
Work product is the field to map it. But how to get the reference of user story using restAPI?
Please let me know if anyone has done in past.
In WS API user story is HierarchicalRequirement object. Query on the story, which you want to be a workproduct, and get its _ref. Then update the test case, e.g.
testCaseUpdate.addProperty("WorkProduct", storyRef);
Here is a Java example using Rally Rest toolkit for Java, but the approach is the same regardless of your choice of language or toolkit:
public class UpdateTestCase {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123";
String workspaceRef = "/workspace/123456";
String applicationName = "RestExample_updateWorkProductOnTestCase";
RallyRestApi restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
try {
String testid = "TC12";
String storyid = "US34";
QueryRequest testCaseRequest = new QueryRequest("TestCase");
testCaseRequest.setWorkspace(workspaceRef);
testCaseRequest.setFetch(new Fetch("FormattedID", "Name", "WorkProduct"));
testCaseRequest.setQueryFilter(new QueryFilter("FormattedID", "=", testid));
QueryResponse testCaseQueryResponse = restApi.query(testCaseRequest);;
if (testCaseQueryResponse.getTotalResultCount() == 0) {
System.out.println("Cannot find test case : " + testid);
return;
}
JsonObject testCaseJsonObject = testCaseQueryResponse.getResults().get(0).getAsJsonObject();
String testCaseRef = testCaseJsonObject.get("_ref").getAsString();
System.out.println(testCaseRef);
QueryRequest storyRequest = new QueryRequest("HierarchicalRequirement");
storyRequest.setWorkspace(workspaceRef);
storyRequest.setFetch(new Fetch("FormattedID", "Name"));
storyRequest.setQueryFilter(new QueryFilter("FormattedID", "=", storyid));
QueryResponse storyQueryResponse = restApi.query(storyRequest);;
if (storyQueryResponse.getTotalResultCount() == 0) {
System.out.println("Cannot find test story : " + storyid);
return;
}
JsonObject storyJsonObject = storyQueryResponse.getResults().get(0).getAsJsonObject();
String storyRef = storyJsonObject.get("_ref").getAsString();
System.out.println(storyRef);
JsonObject testCaseUpdate = new JsonObject();
testCaseUpdate.addProperty("WorkProduct", storyRef);
UpdateRequest updateTestCaseRequest = new UpdateRequest(testCaseRef,testCaseUpdate);
UpdateResponse updateTestCaseResponse = restApi.update(updateTestCaseRequest);
if (updateTestCaseResponse.wasSuccessful()) {
System.out.println("Successfully updated : " + testid + " WorkProduct after update: " + testCaseUpdate.get("WorkProduct"));
}
} finally {
restApi.close();
}
}
}

HTTP Requests in Glass GDK

I am implementing a GDK application and need to do in my application some HTTP Post requests. Do I send the HTTP requests the same way as on android phone or there is some other way of doing it? (I have tried the code that I am using on my phone and it's not working for glass.)
thanks for your help in advance.
You can make any post request like in smartphones, but ensure you make the requests using an AsyncTask.
For example:
private class SendPostTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Make your request POST here. Example:
myRequestPost();
return null;
}
protected void onPostExecute(Void result) {
// Do something when finished.
}
}
And you can call that asynctask anywhere with:
new SendPostTask().execute();
And example of myRequestPost() may be:
private int myRequestPost() {
int resultCode = 0;
String url = "http://your-url-here";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add headers you want, example:
// post.setHeader("Authorization", "YOUR-TOKEN");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", "111111"));
nameValuePairs.add(new BasicNameValuePair("otherField", "your-other-data"));
try {
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
resultCode = response.getStatusLine().getStatusCode();
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
} catch (Exception e) {
Log.e("POST", e.getMessage());
}
return resultCode;
}

How to create HMACSHA256 api signature in Salesforce Apex

Can somebody help in creating HMACSHA256 api signature in apex using crypto class. Corresponding java code is given below :-
public static void main(String[] args) throws GeneralSecurityException, IOException {
String secretKey = "secretKey";
String salt = "0123456789";
String generateHmacSHA256Signature = generateHmacSHA256Signature(salt, secretKey);
System.out.println("Signature: " + generateHmacSHA256Signature);
String urlEncodedSign = URLEncoder.encode(generateHmacSHA256Signature, "UTF-8");
System.out.println("Url encoded value: " + urlEncodedSign);
}
public static String generateHmacSHA256Signature(String data, String key) throws GeneralSecurityException {
byte[] hmacData = null;
try {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(secretKey);
hmacData = mac.doFinal(data.getBytes("UTF-8"));
return new Base64Encoder().encode(hmacData);
} catch (UnsupportedEncodingException e) {
throw new GeneralSecurityException(e);
}
}
Thanks in advance
http://boards.developerforce.com/t5/Apex-Code-Development/How-to-create-HMACSHA256-api-signature/td-p/551055
I think that'll do it for you?
Copied here for posterity (in case the link dies)
AKK's answer:
"Re: How to create HMACSHA256 api signature
‎12-28-2012 02:58 AM
Sorry for unformatted code, actually I was looking into how to format but didn't find anything in mozilla and when login through chrome editor appeared.
I got the signature right using below code maybe this helps someone :-
public void genrateSignature() {
String salt = String.valueOf(Crypto.getRandomInteger());
String secretKey = 'secret_key';
String signature = generateHmacSHA256Signature(salt, secretKey);
System.debug('Signature : '+signature);
}
private static String generateHmacSHA256Signature(String saltValue, String secretKeyValue) {
String algorithmName = 'HmacSHA256';
Blob hmacData = Crypto.generateMac(algorithmName, Blob.valueOf(saltValue), Blob.valueOf(secretKeyValue));
return EncodingUtil.base64Encode(hmacData);
}
Thanks"

How to login Gmail with Apache's HttpClient?

I want to login my gmail and get the contact list automatically with httpClient,
I've tryed the method described in the page below:
Android: How to login into webpage programmatically, using HttpsURLConnection
but once it ran to:
String cookie = response.getFirstHeader("Set-Cookie").getValue();
a java.lang.NullPointerException was catched.
I thought it was because the page was moved temporarily, then I coded my code like this:
private static String uriLogin = "https://mail.google.com";
private static String uriContacts = "https://mail.google.com/mail/shva=1#contacts";
// the account was registered just for test:
private static String myAcc = "httpclient.test";
private static String myPwd = "testpassword";
public static void main(String[] args) throws ClientProtocolException,
IOException, InterruptedException {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(uriLogin);
List<NameValuePair> params = new ArrayList<NameValuePair>(3);
params.add(new BasicNameValuePair("Email", myAcc));
params.add(new BasicNameValuePair("Passwd", myPwd));
params.add(new BasicNameValuePair("signIn", "Sign in"));
post.setEntity(new UrlEncodedFormEntity(params));
redp("url is:: ", post.getEntity());
HttpResponse rsp = client.execute(post);
if (rsp.getStatusLine().getStatusCode() >= 400) {// returns 302 if
// success
System.err.println("failed to get the web page!!!");
System.err.println("status: " + rsp.getStatusLine());
System.exit(-1);
}
redp("status is:: ", rsp.getStatusLine());
redp("heads of rsp :: ", "");
pHeads(rsp);
redp("content is:: ", EntityUtils.toString(rsp.getEntity()));
String redirect = rsp.getLastHeader("Location").getValue();
HttpGet get = new HttpGet(redirect);
rsp = client.execute(get);
String cookie = rsp.getFirstHeader("Set-Cookie").getValue();
redp("cookie is:: ", cookie);
HttpGet getContacts = new HttpGet(uriContacts);
getContacts.setHeader("Cookie", cookie);
redp("heads of get [contacts]:: ", "");
pHeads(getContacts);
client.getConnectionManager().shutdown();
client = new DefaultHttpClient(); // without these 2 lines,
// "java.lang.IllegalStateException"
// will be catched
rsp = client.execute(getContacts);
redp("heads of rsp (new) ::", "");
pHeads(rsp);
InputStream istream = rsp.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
istream));
String line;
p("联系人列表: ");
while ((line = reader.readLine()) != null) {
p(line);
}
reader.close();
istream.close();
}// main
public static void pHeads(HttpMessage msg) {
Header[] headers = msg.getAllHeaders();
for (int i = 0; i < headers.length; i++)
p(headers[i].getName() + ": " + headers[i].getValue());
}
public static void p(Object o) {
System.out.println(o);
}
public static void redp(String head, Object o) throws InterruptedException {
System.err.println(head);
if (o.equals("") || o.equals(null))
return;
Thread.sleep(100);
System.out.println(o);
}
}
`
but it still doesn't work... Any help would be great~~
[BTW, I saw a some people says on the Internet that httpClient was not very acceptable for this kind of job, could you tell me in what kind of project HttpClient is most used?]
From what I've seen, You receive the nullPointerEception when you get to response.getLastHeader("Location").getValue();
it looks like there is no "Location" tag in the GMail html header. When Java fails to find this, it just throws "I can't find it"
What you want is the redirect after the POST occurs.
At a quick glance, its something like:
https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=http://mail.google.com/mail/&scc=1&ltmpl=default&ltmplcache=2
but you should double check this.
Hope this helps.