I am trying to use microsoft cognitive search api for web results - api

final String accountKey = "***********************";
final String bingUrlPattern ="https://api.cognitive.microsoft.com/bing/v5.0/search?q=bill gates";
String query = URLEncoder.encode("'what is omonoia'", Charset.defaultCharset().name());
String bingUrl = String.format(bingUrlPattern, query);
String accountKeyEnc = Base64.getEncoder().encodeToString((accountKey + ":" + accountKey).getBytes());
URL url = new URL(bingUrl);
URLConnection connection = url.openConnection();
connection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
JSONObject json = new JSONObject(response.toString());
JSONObject d = json.getJSONObject("d");
JSONArray results = d.getJSONArray("results");
int resultsLength = results.length();
for (int i = 0; i < resultsLength; i++) {
final JSONObject aResult = results.getJSONObject(i);
System.out.println(aResult.get("Url"));
}
}
}
Code returns 400 error code while execution.
It seems format of url pattern is wrong. Please suggest.
Also how can can specify format to be in JSON.

You are specifying your auth incorrectly. You'll want the following instead:
connection.setRequestProperty("Ocp-Apim-Subscription-Key", accountKey);
You'll also want to change how the URL is constructed, since you've hard-coded the query to 'bill gates'.
final String bingUrlPattern ="https://api.cognitive.microsoft.com/bing/v5.0/search?q=%s";
You may find the API console helpful.

Related

Insert line breaks in VariableReplace in docx4j

I have been trying to fill up a word template(.docx) file which has placeholders which needs to be replaced.
I was able to rewrite the template but the text does not come with line breaks
I understand that carriage return or new line (\r\n) does not work in .docx files. I used the VariableReplace method to convert but I was unable to place br or factory.createBr() while using the variable replace.
Any suggestions would be really helpful. Below is the piece of code what i tried
Map<String,String> variableReplaceMap = new HashMap<>();
Map<String, String> textContent = readTextContentAfterDBExtractionToFillUpTemplate();
ObjectFactory factory = Context.getWmlObjectFactory();
P para = factory.createP();
R rspc = factory.createR();
String power= textContent.get("Power & Energy");
String[] powerWithNewLine = skills.split("\\\\n");
for (String eachLineOfPower : powerWithNewLine) {
Text eachLineOfPowerTxt = factory.createText();
eachLineOfPowerTxt .setValue( eachLineOfPower );
rspc.getContent().add( eachLineOfPowerTxt );
Br br = factory.createBr();
rspc.getContent().add(br);
para.getParagraphContent().add(rspc);
documentPart.addObject(para);
}
String str = "";
for (Object eachLineOfPgrph : para.getParagraphContent()) {
str = str + eachLineOfPgrph;
}
variableReplaceMap.put("POWER", str);
return variableReplaceMap;
The link from Jason is dead.
Here is the current link: https://github.com/plutext/docx4j/blob/master/docx4j-samples-docx4j/src/main/java/org/docx4j/samples/VariableReplace.java
In case it gets changed in the future, simply use the following function and apply it to your string, that contains linebreaks:
/**
* Hack to convert a new line character into w:br.
* If you need this sort of thing, consider using
* OpenDoPE content control data binding instead.
*
* #param r
* #return
*/
private static String newlineToBreakHack(String r) {
StringTokenizer st = new StringTokenizer(r, "\n\r\f"); // tokenize on the newline character, the carriage-return character, and the form-feed character
StringBuilder sb = new StringBuilder();
boolean firsttoken = true;
while (st.hasMoreTokens()) {
String line = (String) st.nextToken();
if (firsttoken) {
firsttoken = false;
} else {
sb.append("</w:t><w:br/><w:t>");
}
sb.append(line);
}
return sb.toString();
}
See newlineToBreakHack method at https://github.com/plutext/docx4j/blob/master/src/samples/docx4j/org/docx4j/samples/VariableReplace.java#L122

CloudStack: Unable to verify user credentials and/or request signature

I am working on CloudStack API now and I have the problem about making the API request. I always got "{ "listtemplatesresponse" : {"errorcode":401,"errortext":"unable to verify user credentials and/or request signature"} }" even though I change the parameter.
This error occurs in some commands that require the parameter and this is the command that I use:
command=listTemplates&templatefilter=featured
I don't know what I did wrong since it works with others. Here is the code I use to make the API request:
try {
String encodedApiKey = URLEncoder.encode(apiKey.toLowerCase(), "UTF-8");
ArrayList<String> sortedParams = new ArrayList<String>();
sortedParams.add("apikey="+encodedApiKey);
StringTokenizer st = new StringTokenizer(apiUrl, "&");
while (st.hasMoreTokens()) {
String paramValue = st.nextToken().toLowerCase();
String param = paramValue.substring(0, paramValue.indexOf("="));
String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=")+1, paramValue.length()), "UTF-8");
sortedParams.add(param + "=" + value);
}
Collections.sort(sortedParams);
System.out.println("Sorted Parameters: " + sortedParams);
String sortedUrl = null;
boolean first = true;
for (String param : sortedParams) {
if (first) {
sortedUrl = param;
first = false;
} else {
sortedUrl = sortedUrl + "&" + param;
}
}
sortedUrl += "&response=json";
System.out.println("sorted URL : " + sortedUrl);
String encodedSignature = signRequest(sortedUrl, secretKey);
String finalUrl = host + "?" + apiUrl + "&response=json&apiKey=" + apiKey + "&signature=" + encodedSignature;
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(finalUrl);
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
System.out.println("str: "+str);
result = str.toString();
System.out.println("result: "+str);
}
else
System.out.println("Error response!!");
} catch (Throwable t) {
System.out.println(t);
}
And this is signRequest function:
public static String signRequest(String request, String key) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
mac.init(keySpec);
mac.update(request.getBytes());
byte[] encryptedBytes = mac.doFinal();
return URLEncoder.encode(Base64.encodeBytes(encryptedBytes), "UTF-8");
} catch (Exception ex) {
System.out.println(ex);
}
return null;
}
Please feel free to ask me if you need more information. All comments and advice are welcome!
Have you tried sorting after you've added "&response=json" to the list of parameters?
E.g.
try {
String encodedApiKey = URLEncoder.encode(apiKey.toLowerCase(), "UTF-8");
ArrayList<String> sortedParams = new ArrayList<String>();
sortedParams.add("apikey="+encodedApiKey);
sortedParams.add("response=json");
StringTokenizer st = new StringTokenizer(apiUrl, "&");
while (st.hasMoreTokens()) {
String paramValue = st.nextToken().toLowerCase();
String param = paramValue.substring(0, paramValue.indexOf("="));
String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=")+1, paramValue.length()), "UTF-8");
sortedParams.add(param + "=" + value);
}
Collections.sort(sortedParams);
System.out.println("Sorted Parameters: " + sortedParams);
String sortedUrl = null;
boolean first = true;
for (String param : sortedParams) {
if (first) {
sortedUrl = param;
first = false;
} else {
sortedUrl = sortedUrl + "&" + param;
}
}
System.out.println("sorted URL : " + sortedUrl);
String encodedSignature = signRequest(sortedUrl, secretKey);
String finalUrl = host + "?" + apiUrl + "&response=json&apiKey=" + apiKey + "&signature=" + encodedSignature;
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(finalUrl);
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
System.out.println("str: "+str);
result = str.toString();
System.out.println("result: "+str);
}
else
System.out.println("Error response!!");
} catch (Throwable t) {
System.out.println(t);
}
Your API Key and Response parameters need to be part of the sorted Url used when signing, which they appear to be.
try changing
return URLEncoder.encode(Base64.encodeBytes(encryptedBytes), "UTF-8");
to
return URLEncoder.encode(Base64.encodeAsString(encryptedBytes), "UTF-8");

NameValueCollection in Windows Phone 8

I want to use NameValueCollection in windows phone 8, but I can not see this option in WP8 SDK. Can you help me please?
This function has been removed.
But a query can be manipulated using parsing and a SortedDictionary. i.e. This snippet sorts a query string:
public string sortQuery(string myUrl)
{
string url = myUrl.Substring(0, myUrl.IndexOf("?") + 1);
string q = myUrl.Substring(myUrl.IndexOf("?") + 1);
string[] pr = q.Split('&');
SortedDictionary<string,string> d = new SortedDictionary<string,string>();
foreach (string s in pr)
{
string[] prm = s.Split('=');
string key = prm[0];
string value = "";
if (prm.Length > 1) { value = "=" + prm[1]; }
d.Add(key, value);
}
string result = "";
foreach (var k in d.Keys)
{
result += k + d[k] + "&";
}
result = result.Substring(0, result.Length - 1);
return url + result;
}

Rally SOAP API - How do I add an attachment to a Hierarchical Requirement?

I have followed this code to add attachment to a HierarchicalRequirement.
I get the following error:
validation error: Attachment.attachments[0] should not be null
How do I add an attachment to a Hierarchical Requirement?
Can you post a code excerpt that illustrates the problem? If you followed the approach in Rally SOAP API - How do I add an attachment to a TestCaseResult you're on the right track. Following is a quick code sample that works for me when adding an attachment to a story:
// issue query for target story
QueryResult queryResult = service.query(workspace, objectType, queryString, orderString, fetchFullObjects, start, pageSize);
// look at the object returned from query()
Console.WriteLine("Query returned " + queryResult.TotalResultCount + " objects");
// Grab the resulting story
DomainObject rallyObject = queryResult.Results.First();
HierarchicalRequirement queryStory = (HierarchicalRequirement)rallyObject;
// Read In Image Content
String imageFilePath = "C:\\Users\\username\\";
String imageFileName = "image1.png";
String fullImageFile = imageFilePath + imageFileName;
var imageFileLength = new FileInfo(fullImageFile).Length;
Image myImage = Image.FromFile(fullImageFile);
Console.WriteLine("Image File Length: " + imageFileLength);
// Convert Image to Byte Array format
byte[] imageByteArray = ImageToByteArray(myImage, System.Drawing.Imaging.ImageFormat.Png);
var imageNumberBytes = imageByteArray.Length;
// Create the Attachment Content
AttachmentContent attachmentContent = new AttachmentContent();
attachmentContent.Content = imageByteArray;
attachmentContent.Workspace = workspace;
CreateResult result = service.create(attachmentContent);
attachmentContent = (AttachmentContent)result.Object;
// Create the Attachment Container, wire it up to the AttachmentContent
Attachment myAttachment = new Attachment();
myAttachment.ContentType = "image/png";
myAttachment.Content = attachmentContent;
myAttachment.Name = "image1.png";
myAttachment.Size = imageNumberBytes ;
myAttachment.SizeSpecified = true;
myAttachment.User = user;
myAttachment.Artifact = queryStory;
myAttachment.Workspace = workspace;
// Create the attachment in Rally
result = service.create(myAttachment);
Console.WriteLine(result.Object);
}
public static byte[] ImageToByteArray (Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
return imageBytes;
}
}
}

How to get the list of unsubscribers emails from mailchimp

I want to get the emails of unsubscribers the code below returning the count that how many of it are there but how could i get the List of unsubscribers from output variable...
Here is my full code::
private List<campaignUnsubscribesResults.Unsubscribes> Unsubscribers = new List<campaignUnsubscribesResults.Unsubscribes>();
private void GetUnsubscribers(string apikey, string MailChimpCampaignID)
{
campaignUnsubscribesInput input = new campaignUnsubscribesInput();
input.api_AccessType = PerceptiveMCAPI.EnumValues.AccessType.Serial;
input.api_CustomErrorMessages = true;
input.api_MethodType = PerceptiveMCAPI.EnumValues.MethodType.POST;
input.api_Validate = true;
input.api_OutputType = PerceptiveMCAPI.EnumValues.OutputType.XML;
input.parms.apikey = apikey;
input.parms.cid = MailChimpCampaignID;
//input.parms.start = PageIndex;
//input.parms.limit = PageSize;
campaignUnsubscribes unsubscribe = new campaignUnsubscribes();
campaignUnsubscribesOutput output = unsubscribe.Execute(input);
Unsubscribers.AddRange(output.result.data);
string unsubscriber = "0";
//ArrayList a = new ArrayList();
//a[0] = output.result.data.ToString();
//List<MCItem> lst = new List<MCItem>();
// foreach (listBatchUnsubscribeResults order in myArrayList)
//{
// orders.add(order);
//}
string[] unsubs;
//ArrayList [] list = new ArrayList [0];
foreach (listMembers list1 in output.result)
{
unsubscriber = list1.ToString();
}
string unsubscribers = Unsubscribers.Count.ToString();
Page.ClientScript.RegisterStartupScript(typeof(Page), "alert", "<script language=JavaScript>alert('Unsubscribers:: '+ ' " + unsubscribers + " ');</script>");
//Unsubscribers.Reverse();
//dlUnsubscribes.DataSource = Unsubscribers.Take(10);
//dlUnsubscribes.DataBind();
//dlUnsubscribes.Visible = (Unsubscribers.Count > 0);
}
I would use Mailchimp Webhooks. You setup a page/script on your website which will get called by Mailchimp every time a particular event occurs. When it's an unsubscribe event, you can log the info you want to store to a database, file, etc.