I have to make an application which is able to use Bing Search API ( SOAP Services) with java.It must do a specific search for a word.Here is my code :
import com.google.code.bing.search.client.BingSearchClient;
import com.google.code.bing.search.client.BingSearchServiceClientFactory;
import com.google.code.bing.search.client.BingSearchClient.SearchRequestBuilder;
import com.google.code.bing.search.schema.AdultOption;
import com.google.code.bing.search.schema.SearchOption;
import com.google.code.bing.search.schema.SearchRequest;
import com.google.code.bing.search.schema.SearchResponse;
import com.google.code.bing.search.schema.SourceType;
import com.google.code.bing.search.schema.web.WebResult;
import com.google.code.bing.search.schema.web.WebSearchOption;
public class MyApp {
String apikey = "****************";
String searchword="google";
public static void main(String[] args){
BingSearchServiceClientFactory factory = BingSearchServiceClientFactory.newInstance();
BingSearchClient client = factory.createBingSearchClient();
SearchRequestBuilder builder = client.newSearchRequestBuilder();
builder.withAppId(apikey);
builder.withQuery(searchword);
builder.withSourceType(SourceType.WEB);
builder.withVersion("2.0");
builder.withMarket("en-us");
builder.withAdultOption(AdultOption.MODERATE);
builder.withSearchOption(SearchOption.ENABLE_HIGHLIGHTING);
builder.withWebRequestCount(10L);
builder.withWebRequestOffset(0L);
builder.withWebRequestSearchOption(WebSearchOption.DISABLE_HOST_COLLAPSING);
builder.withWebRequestSearchOption(WebSearchOption.DISABLE_QUERY_ALTERATIONS);
SearchResponse response = client.search(builder.getResult());
for (WebResult result : response.getWeb().getResults()) {
System.out.println(result.getTitle());
System.out.println(result.getDescription());
System.out.println(result.getUrl());
System.out.println(result.getDateTime());
}
}
}
I found this http://code.google.com/p/bing-search-java-sdk/ site.
I get my appkey from Azure MarketPlace. I get an error : java.lang.NullPointerException at the line for loop that will show response. That means response is null.
I don't understand what I am missing .
bing is changing their license system at the moment. this API was created using the "old" version 2 license. MS had done some changes when migrating to Azzure market place:
https://datamarket.azure.com/dataset/5BA839F1-12CE-4CCE-BF57-A49D98D29A44
migration guide:
http://go.microsoft.com/fwlink/?LinkID=248077
I don't think that this is covered by this Java-API wrapper you use already.
Related
On the server side, I develop a REST API with Java and Jersey / Jackson, and this API makes calls to the Stripe API.
The Stripe API returns all objects with properties names in snake case, such as client_secret for class PaymentIntent.
The JSON returned by my REST API using Jersey automatically converts these properties to camel case, with names such as clientSecret.
On the client side, I use the Stripe JS library, which also expects properties names in snake case, and therefore I get errors when I try to read properties of objects returned by my REST API.
I have seen many posts about configuring Jersey to use snake case instead of camel case, but I have not been able to apply what I found to my use case, which is using camel case for my own classes, and snake case for Stripe classes I have no control on.
Here is my current code on the server site:
package com.knowledgeplaces.metalmsapi.resources;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.knowledgeplaces.metalmsapi.records.PaymentIntentArgsRec;
import com.knowledgeplaces.metalmsapi.records.PaymentIntentResponseRec;
import com.knowledgeplaces.metalmsapi.utils.MetaLmsConstants;
import com.stripe.Stripe;
import com.stripe.model.PaymentIntent;
import com.stripe.exception.StripeException;
import com.stripe.net.ApiResource;
#Path("/eShops/{eShopId}/stripePaymentIntent")
public class StripePaymentIntentRest {
// request one Payment Intent
#POST
#Produces({ MediaType.APPLICATION_JSON })
public PaymentIntentResponseRec createService(
#Context HttpServletRequest req,
#PathParam("eShopId") Integer eShopId,
PaymentIntentArgsRec paymentIntentArgs) {
PaymentIntent paymentIntent;
PaymentIntentResponseRec paymentIntentResponse;
// get Stripe API secret key
if (paymentIntentArgs.stripeTestMode()) {
Stripe.apiKey = "***********************";
} else {
Stripe.apiKey = "***********************";
}
// create Payment Intent
List<Object> paymentMethodTypes = new ArrayList<>();
paymentMethodTypes.add("card");
Map<String, Object> params = new HashMap<>();
params.put("amount", paymentIntentArgs.amount());
params.put("currency", paymentIntentArgs.currency());
params.put(
"payment_method_types",
paymentMethodTypes);
try {
// paymentIntent = PaymentIntent.create(params);
paymentIntent = ApiResource.GSON.fromJson(PaymentIntent.create(params).toJson(), PaymentIntent.class);
paymentIntentResponse = new PaymentIntentResponseRec(null, paymentIntent);
} catch (StripeException ex) {
paymentIntentResponse = new PaymentIntentResponseRec(MetaLmsConstants.StripeApiError, null);
}
return paymentIntentResponse;
}
}
With this code, I get a Payment Intent object with properties in camel case.
If I uncomment the line
paymentIntent = PaymentIntent.create(params);
And comment the line
paymentIntent = ApiResource.GSON.fromJson(PaymentIntent.create(params).toJson(), PaymentIntent.class);
Then I get the following error:
No serializer found for class com.stripe.net.StripeResponse and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.knowledgeplaces.metalmsapi.records.PaymentIntentResponseRec["paymentIntent"]->com.stripe.model.PaymentIntent["lastResponse"])
Please advise on how to get rid off this error.
I have reviewed my code and here is a working solution:
try {
paymentIntent = PaymentIntent.create(params);
String paymentIntentJson = paymentIntent.toJson();
stringResponse = new StringResponseRec(null, paymentIntentJson);
} catch (StripeException ex) {
stringResponse = new StringResponseRec(ex.getMessage(), null);
}
return stringResponse;
The problem was related to snake case support in Jersey Jackson or records in Java 16, I don't know.
So, instead of loading a record of type PaymentIntentResponseRec which has a Stripe PaymentIntent object as a property, I load a record of type StringResponseRec which has a property of type string, and I load that string from the paymentIntent.toJson() provided by the Stripe API.
On the client side, my Angular app which uses the Stripe JS library gets my PaymentIntent object fine.
It works, but if you think there is a more elegant solution, feel free to comment.
I'm attempting to follow this AWS tutorial. But I'm having trouble at "You can run GreeterWorker successfully at this point." as I'm getting an UnknownResourceException.
Exception in thread "main" com.amazonaws.services.simpleworkflow.model.UnknownResourceException: Unknown domain: helloWorldWalkthrough (Service: AmazonSimpleWorkflow; Status Code: 400; Error Code: UnknownResourceFault; Request ID: xxxxx)
Steps taken
Resolved permission exception by attaching the SimpleWorkflowFullAccess IAM Policy to my AWS user.
Verified that the helloWorldWalkthrough is registered on the SWF dashboard
registered new helloWorldWalkthrough2 domain, same error occured
The tutorial didn't cover the step about attaching the SimpleWorkflowFullAccess policy to the AWS user, so I'm wondering if there is a similar undocumented step to allow my user to find this domain.
My code is copy/pasted from the GreeterWorker class in the tutorial.
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflowClient;
import com.amazonaws.services.simpleworkflow.flow.ActivityWorker;
import com.amazonaws.services.simpleworkflow.flow.WorkflowWorker;
public class GreeterWorker {
public static void main(String[] args) throws Exception {
ClientConfiguration config = new ClientConfiguration().withSocketTimeout(70*1000);
String swfAccessId = System.getenv("AWS_ACCESS_KEY_ID");
String swfSecretKey = System.getenv("AWS_SECRET_KEY");
AWSCredentials awsCredentials = new BasicAWSCredentials(swfAccessId, swfSecretKey);
AmazonSimpleWorkflow service = new AmazonSimpleWorkflowClient(awsCredentials, config);
service.setEndpoint("https://swf.us-east-1.amazonaws.com");
String domain = "helloWorldWalkthrough";
String taskListToPoll = "HelloWorldList";
ActivityWorker aw = new ActivityWorker(service, domain, taskListToPoll);
aw.addActivitiesImplementation(new GreeterActivitiesImpl());
aw.start();
WorkflowWorker wfw = new WorkflowWorker(service, domain, taskListToPoll);
wfw.addWorkflowImplementationType(GreeterWorkflowImpl.class);
wfw.start();
}
}
You need to create the domain using the console or through an api call. Domain is not created automatically.
I was also facing the same issue and then I found that the region is hard coded in the main method inside GreeterWorker class as shown below:
service.setEndpoint("https://swf.us-east-1.amazonaws.com");
However my SWF account was in west-2 region.
I was also faving same problem. region is hard coded in tutorial.
I changed code as flllows
service.setEndpoint("https://swf.us-west-2.amazonaws.com");
I introduced myself to Twitter4j yesterday, and are now testing out features for an upcoming program of mine. As the title suggests, I am trying to upload an image to twitter, without any luck. Here's my code:
import static java.awt.Toolkit.getDefaultToolkit;
import static javax.swing.JOptionPane.ERROR_MESSAGE;
import static javax.swing.JOptionPane.showMessageDialog;
import java.awt.Image;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.examples.tweets.UploadMultipleImages;
import twitter4j.media.ImageUpload;
import twitter4j.media.ImageUploadFactory;
public final class UpdateStatus {
static File file = new File("/images/Done.jpg");
public static void main(String[] args) {
for(int i=0;i<2;i++){
Twitter twitter = new TwitterFactory().getInstance();
Status status=null;
try {
ImageUpload.upload(file,"22");
} catch (TwitterException e) {
System.err.println("Shit...");
System.exit(3);
}
}
System.out.println("Done");
}
}
The image I'm trying to upload is Done.jpg, and is in a folder in the package. I've used this method for images in other programs, so I am pretty sure it works. Though, this gives me an error message before I run the code, saying "Cannot make a static reference to the non-static method upload(File, String) from the type ImageUpload". Any ideas that could help me? :D
You need to ensure following before testing your code -
Register your app at https://apps.twitter.com/ and get Oauth tokens to be able to connect your app to Twitter and perform desired action.
You will get a consumerKey,consumerAccessToken, accessKey and accessToken.
If you want to post updates, please ensure you configure your app
permissions to have a Read and Write access, deafult access is Read
Only.
After you have the required access tokens, you need to instantiate a Twitter instance using those tokens. This instance can then be used to perform requisite action. See sample code below to upload an image -
ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
twitterConfigBuilder.setDebugEnabled(true);
twitterConfigBuilder.setOAuthConsumerKey("consumerkey");
twitterConfigBuilder.setOAuthConsumerSecret("consumersecret");
twitterConfigBuilder.setOAuthAccessToken("accesstoken");
twitterConfigBuilder.setOAuthAccessTokenSecret("accesstokensecret");
Twitter twitter = new TwitterFactory(twitterConfigBuilder.build()).getInstance();
String statusMessage = "Watch out this interesting offer I came across today";
File file = new File("/images/Done.jpg");
StatusUpdate status = new StatusUpdate(statusMessage);
status.setMedia(file); // set the image to be uploaded here.
twitter.updateStatus(status);
Hope this helps.
ImageUpload.upload is not a static method, but an instance method.
You need to create an instance of ImageUpload, and call the method from the instance.
Checking the documentation of ImageUpload, it is an interface. So you'll need to instantiate a class that implements ImageUpload.
I am following this source:
Elastic Search Example
and I created the piece of code:
import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.elasticsearch.client.Client;
import org.elasticsearch.node.Node;
public class ElasticSearchAPI {
public static void main(String[] args) {
Node node = nodeBuilder().clusterName("yourclustername").node();
Client client = node.client();
client.prepareIndex("kodcucom", "article", "1")
.setSource(
putJsonDocument(
"ElasticSearch: Java API",
"ElasticSearch provides the Java API, all operations "
+ "can be executed asynchronously using a client object.",
new Date(), new String[] { "elasticsearch" },
"Huseyin Akdogan")).execute().actionGet();
node.close();
}
public static Map<String, Object> putJsonDocument(String title,
String content, Date postDate, String[] tags, String author) {
Map<String, Object> jsonDocument = new HashMap<String, Object>();
jsonDocument.put("title", title);
jsonDocument.put("conten", content);
jsonDocument.put("postDate", postDate);
jsonDocument.put("tags", tags);
jsonDocument.put("author", author);
return jsonDocument;
}
}
I run ElasticSearch with command line:
elasticsearch.bat
and it runs correctly:
After that, I run my Java code and here is a log from Eclipse and server:
Should I configure something? I saw few tutorials like this and everytime is really similar code which never works for me.
Thanks
Your jsonDocument has a typo:
jsonDocument.put("conten", content);
Should be
jsonDocument.put("content", content);
I presume
Ok, I solved this problem. In fact, the problem was with the versions of ElasticSearch Client and ES Java API.
Upgrade ES Java API to the same version as ES Client solved this problem.
More info here:
Java API 1.x Client
Important:
Please note that you are encouraged to use the same version on client
and cluster sides. You may hit some incompatibilities issues when
mixing major versions.
I am coding for consuming Sharepoint 2010 web services in Java using Netbeans. I am able to creating the web service client from WSDL using the provided wizard. When I call the following code I get the Microsoft.SharePoint.SoapServer.SoapServerException
import java.net.Authenticator;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import proxy.webs.GetWebCollectionResponse;
import proxy.webs.GetWebResponse;
import proxy.webs.Webs;
import proxy.webs.WebsSoap;
public class AccessLists {
public static void main(String[] args) throws Exception {
String username = "domain\\Administrator";
char[] password = "password".toCharArray();
NtlmAuthenticator ntlmAuth = new NtlmAuthenticator(username, password);
Authenticator.setDefault(ntlmAuth);
Webs websService = new Webs(new URL("http://servername:7766/_vti_bin/Webs.asmx?wsdl"));
WebsSoap webPort = websService.getWebsSoap();
GetWebResponse.GetWebResult webRes = webPort.getWeb("http://servername/sites/Test1");
System.out.println(webRes);
}
}
The site http://servername/sites/Test1 exists and I can open it in the browser.
Update 1: Similar thing happens for C# code, which I run on the same machine as Sharepoint 2010:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Webs webService = new Webs();
webService.Credentials = System.Net.CredentialCache.DefaultCredentials;
Object o = webService.GetWeb("http://servername/sites/Test1");
Console.WriteLine(o.ToString());
}
}
}
I guess this is the problem with the set up and not with the code.
I was using the wrong endpoint for the web service. For the Sharepoint site http://servername/sites/Test1 the endpoint should also be http://servername/sites/Test1/_vti_bin/Webs.asmx?wsdl