How to perform Amazon Cloud Search with .net code? - java

I am learning Amazon Cloud Search but I couldn't find any code in either C# or Java (though I am creating in C# but if I can get code in Java then I can try converting in C#).
This is just 1 code I found in C#: https://github.com/Sitefinity-SDK/amazon-cloud-search-sample/tree/master/SitefinityWebApp.
This is 1 method i found in this code:
public IResultSet Search(ISearchQuery query)
{
AmazonCloudSearchDomainConfig config = new AmazonCloudSearchDomainConfig();
config.ServiceURL = "http://search-index2-cdduimbipgk3rpnfgny6posyzy.eu-west-1.cloudsearch.amazonaws.com/";
AmazonCloudSearchDomainClient domainClient = new AmazonCloudSearchDomainClient("AKIAJ6MPIX37TLIXW7HQ", "DnrFrw9ZEr7g4Svh0rh6z+s3PxMaypl607eEUehQ", config);
SearchRequest searchRequest = new SearchRequest();
List<string> suggestions = new List<string>();
StringBuilder highlights = new StringBuilder();
highlights.Append("{\'");
if (query == null)
throw new ArgumentNullException("query");
foreach (var field in query.HighlightedFields)
{
if (highlights.Length > 2)
{
highlights.Append(", \'");
}
highlights.Append(field.ToUpperInvariant());
highlights.Append("\':{} ");
SuggestRequest suggestRequest = new SuggestRequest();
Suggester suggester = new Suggester();
suggester.SuggesterName = field.ToUpperInvariant() + "_suggester";
suggestRequest.Suggester = suggester.SuggesterName;
suggestRequest.Size = query.Take;
suggestRequest.Query = query.Text;
SuggestResponse suggestion = domainClient.Suggest(suggestRequest);
foreach (var suggest in suggestion.Suggest.Suggestions)
{
suggestions.Add(suggest.Suggestion);
}
}
highlights.Append("}");
if (query.Filter != null)
{
searchRequest.FilterQuery = this.BuildQueryFilter(query.Filter);
}
if (query.OrderBy != null)
{
searchRequest.Sort = string.Join(",", query.OrderBy);
}
if (query.Take > 0)
{
searchRequest.Size = query.Take;
}
if (query.Skip > 0)
{
searchRequest.Start = query.Skip;
}
searchRequest.Highlight = highlights.ToString();
searchRequest.Query = query.Text;
searchRequest.QueryParser = QueryParser.Simple;
var result = domainClient.Search(searchRequest).SearchResult;
//var result = domainClient.Search(searchRequest).SearchResult;
return new AmazonResultSet(result, suggestions);
}
I have already created domain in Amazon Cloud Search using AWS console and uploaded document using Amazon predefine configuration option that is movie Imdb json file provided by Amazon for demo.
But in this method I am not getting how to use this method, like if I want to search Director name then how do I pass in this method as because this method parameter is of type ISearchQuery?

I'd suggest using the official AWS CloudSearch .NET SDK. The library you were looking at seems fine (although I haven't look at it any detail) but the official version is more likely to expose new CloudSearch features as soon as they're released, will be supported if you need to talk to AWS support, etc, etc.
Specifically, take a look at the SearchRequest class -- all its params are strings so I think that obviates your question about ISearchQuery.
I wasn't able to find an example of a query in .NET but this shows someone uploading docs using the AWS .NET SDK. It's essentially the same procedure as querying: creating and configuring a Request object and passing it to the client.
EDIT:
Since you're still having a hard time, here's an example. Bear in mind that I am unfamiliar with C# and have not attempted to run or even compile this but I think it should at least be close to working. It's based off looking at the docs at http://docs.aws.amazon.com/sdkfornet/v3/apidocs/
// Configure the Client that you'll use to make search requests
string queryUrl = #"http://search-<domainname>-xxxxxxxxxxxxxxxxxxxxxxxxxx.us-east-1.cloudsearch.amazonaws.com";
AmazonCloudSearchDomainClient searchClient = new AmazonCloudSearchDomainClient(queryUrl);
// Configure a search request with your query
SearchRequest searchRequest = new SearchRequest();
searchRequest.Query = "potato";
// TODO Set your other params like parser, suggester, etc
// Submit your request via the client and get back a response containing search results
SearchResponse searchResponse = searchClient.Search(searchRequest);

Related

How to send Entity in API DELETE with HTTP-CLIENT

I have to call a DELETE Method inside one of the APIS of a client.
This shouldn´t be a problem but I am struggling with the framework that my company currently uses and I hope I can get some info that hopefully will help me solve the problem:
First thing first.
1: The api doesn´t work if I do the call sending the params as URL:
2: It works completely OK if I send the params inside the body as x-www-form-urlencoded but not form-data or raw
The documentation of the method inside the API told us the following: (Important to Look to IDEtapa)
I have to do this call in JAVA (JAVA 8)
currently my company uses HTTP_CLIENT as the main framework for APICalls.
My code:
The build of the Data (Currently I build both, as Entity and as Params for you to view I´ve tried with each one of them indepently):
Map datosApi = new HashMap<>();
datosApi.put(Constants.URL, anular_cita);
Map headers = new HashMap<>();
headers.put(Constants.AUTHORIZATION, params.get("token_autorizacion"));
headers.put("Content-Type", "application/json");
headers.put("entity_charset", "UTF-8");
datosApi.put(Constants.HEADERS, headers);
JSONObject entity = new JSONObject();
Map param = new HashMap();
param.put(Constants.ID_CENTRO, consul);
param.put("IdAsistencia", propiedades[0]);
param.put("IdCapitulo", propiedades[1]);
param.put("IdEtapa", Integer.valueOf(propiedades[2]));
entity.put(Constants.ID_CENTRO, consul);
entity.put("IdAsistencia", propiedades[0]);
entity.put("IdCapitulo", propiedades[1]);
entity.put("IdEtapa", Integer.valueOf(propiedades[2]));
datosApi.put("entity", entity.toString());
datosApi.put("entity_mime_type", "application/json");
datosApi.put("entity_charset", "UTF-8");
datosApi.put("params", param);
String anularCita = APIDao.callAPIDelete(datosApi);
The preparation for my call to the framework:
public static String callAPIDelete(Map in) {
String contentString = "";
Map res = new HashMap<>();
try {
res = XWM.execute("delete#http_client", in);
byte[] content = (byte[]) res.get("content");
contentString = new String(content, StandardCharsets.UTF_8);
And inside our framework we have this:
if (StringUtils.equals(StringUtils.trim(method), "delete"))
{
StringBuilder requestUrl = new StringBuilder(url);
if (formparams != null)
{
if (requestUrl.indexOf("?")==-1) requestUrl.append("?");
else requestUrl.append("&");
requestUrl.append(URLEncodedUtils.format(formparams, charset));
}
if (entityRequest != null)
{
log.error("Param 'entity' no puede usarse en get (se ignora)");
}
HttpDelete delete = new HttpDelete(requestUrl.toString());
delete.setConfig(requestConfig);
uriRequest = delete;
}
}
}
}
// Headers
if (headers != null)
{
for (String h: headers.keySet()) uriRequest.addHeader(h, headers.get(h));
}
// Ejecutamos método
log.info("Executing request " + uriRequest.getRequestLine());
CloseableHttpResponse response = null;
if (!preemtiveAuth || credsProvider == null)
{
response = httpclient.execute(uriRequest);
}
As you can see, in the delete method, we ignore the entity that i´ve built in the first patch of code.
The HTTPDelete Class is APACHE, the url with info of the class is the following:
https://www.javadoc.io/doc/org.apache.httpcomponents/httpclient/4.5.2/org/apache/http/client/methods/HttpDelete.html
The question can be divided in two:
1: Can we send the Entity in a Delete Call? I have found a few info about this in the following places:
Is an entity body allowed for an HTTP DELETE request?
https://web.archive.org/web/20090213142728/http://msdn.microsoft.com:80/en-us/library/cc716657.aspx
https://peterdaugaardrasmussen.com/2020/11/14/rest-should-you-use-a-body-for-your-http-delete-requests/
I assume that in order to do it, i would need a new HttpDelete that would allow us to use entity, if possible, could you give me some examples of this?
2: For what i understand of the links i posted above, while using entity in Delete calls is not forbidden is something that is not encouraged, Should I just talk with the people who made the API and ask them to change their configuration to allow us to send the info by params? (It is not personal or sensible info, just a bunch of IDs)
Thank you so much for your attention and my apologies for any typo or format mistake, still learning how to make good posts.
EDIT: i have found this answer setEntity in HttpDelete that more or less solve the first issue about if its, posible to send an Entity in a Delete call, but still, don´t now if it should be better to ask them to change their method
As told in the coments by Ewramner and VoiceOfUnreason and in the edits:
1: The answer about how to make this was found in an older post of StackOverflow: setEntity in HttpDelete
2: The answer about "Should I just talk with the people who made the API and ask them to change their configuration to allow us to send the info by params?" was answered by both of them. While it´s not forbidden, it´s something thats not recommended.
My course of action will be:
1: Talk with the people responsible for the API to give them info about this situation.
2: Ask our Architecture team to create a new method that will allow us to do HttpDelete calls with an entity body, just in case that we have to make more API calls like this one.
With this i think all my answers are solved.
Again, Thank you.

Adding reviewers to pull request using github-java sdk

I am trying to use https://github.com/eclipse/egit-github/tree/master/org.eclipse.egit.github.core to create a pull request, but I can't find a way to add reviews to the pull request. The V3 Github API supports adding reviewers as mentioned here, https://developer.github.com/v3/pulls/review_requests/#create-a-review-request. I am trying to create the pull request as follows.
private void createPullRequest(
String repositoryName,
String repositoryOwner,
String pullRequestTitle,
String pullRequestBody,
String branchSource,
String branchDestination
) throws IOException {
logger.info("starting to create pull request");
var gitHubClient = new GitHubClient();
gitHubClient.setCredentials("x", "y");
var repositoryService = new RepositoryService(gitHubClient);
var repository = repositoryService.getRepository(repositoryOwner, repositoryName);
var pullRequestService = new PullRequestService(gitHubClient);
var pullRequest = new PullRequest();
pullRequest.setTitle(pullRequestTitle);
pullRequest.setBody(pullRequestBody);
pullRequest.setHead(
new PullRequestMarker().setRef(branchSource).setLabel(branchSource)
);
pullRequest.setBase(
new PullRequestMarker().setRef(branchDestination).setLabel(branchDestination)
);
logger.info("Finally starting to push PR");
pullRequestService.createPullRequest(repository, pullRequest);
logger.info("PR should be created now");
}
From the documentation it says, it supports 100% of Github V3 API. But I am unable to find any reference in code & online for adding reviewers.
Thanks!

How to get the API Endpoint of a SoapUI TestStep using Java

I would like to know how to get the API end point of a TestStep in SoapUI Xml using Java.
I have used the following,
for (int i=0; i<numberOfTestSteps; i++) {
WsdlTestStep testStep = testCase.getTestStepAt(i);
WsdlTestCaseRunner runner = new WsdlTestCaseRunner(testCase, new StringToObjectMap());
runner.runTestStep(testStep);
List<TestStepResult> resultList = runner.getResults();
for (TestStepResult result : resultList) {
String endPoint = ((MessageExchange)result).getEndpoint();
System.out.println("End Point = " + endPoint);
}
}
It only gives "www.test.com:8080". But I need the API end point as in the image.
Please someone help me to solve this.
Below should give you what you are looking for:
String resourcePath = ((MessageExchange)result).getResource().getFullPath();
System.out.println("Resource Path = " + resourcePath);
You may look at respective SoapUI's API
There is very simply way too if you wish to show that value from with SoapUI Project itself.
In the test case, there might be a REST Request Test step type. Add a Script Assertion as shown below:
log.info messageExchange.endpoint

Get Existing Key-pair from AWS server using aws sdk for java

i am trying to create EC2 instances on AWS using the aws sdk for java..
here is the runinstance method
public static RunInstancesResult createInstaince() {
RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
runInstancesRequest.withImageId("ami-ca381398")
.withInstanceType("t2.micro")
.withMinCount(1)
.withMaxCount(1)
.withKeyName("java-sdk")
.withSubnetId("subnet-8eca36f9")
.withSecurityGroupIds("sg-3f00a25a");
RunInstancesResult runInstancesResult = amazonEC2Client
.runInstances(runInstancesRequest);
return runInstancesResult;
}
here i have explicitly specified java-sdk as the key-pair,but now i want the user to be able to choose the key-pair available on the aws server..i saw a function getAMI that gets the AMI from the aws server.can anyone tell me if a function like getKey-pair is possible?
DescribeKeyPairs is what you are looking for. The link is for EC2 API documentation. You may want to look for aws-java sdk method which calls this API.
public static List<String> getKeyName() {
DescribeKeyPairsRequest dkpr = new DescribeKeyPairsRequest();
DescribeKeyPairsResult dkpresult =
amazonEC2Client.describeKeyPairs(dkpr);
List<KeyPairInfo> keyPairs = dkpresult.getKeyPairs();
List<String> keyPairNameList = new ArrayList<String>();
for (KeyPairInfo keyPairInfo : keyPairs) {
keyPairNameList.add(keyPairInfo.getKeyName());
}
for (int i = 0; i < keyPairs.size(); i++) {
System.out.println(keyPairNameList.get(i));
}
return keyPairNameList;
}
this is the code it will return an arraylist of keynames.

How do I get all the calendar entries for a particular time range using Google Calendar API

I want to view events over specific time range for a specific calendar, but am having trouble using the API, It is a generic API, and it reminds me of using the DOM. The problem is that it seems difficult to work with because much of the information is in generic base classes.
How do I get the events for a calendar using Groovy or Java?
Does anybody have an example of passing credentials using curl?
Example code would be appreciated.
This document has examples for most of the common use cases. For example, here's the code for retrieving events for a specific time range
URL feedUrl = new URL("http://www.google.com/calendar/feeds/default/private/full");
CalendarQuery myQuery = new CalendarQuery(feedUrl);
myQuery.setMinimumStartTime(DateTime.parseDateTime("2006-03-16T00:00:00"));
myQuery.setMaximumStartTime(DateTime.parseDateTime("2006-03-24T23:59:59"));
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("jo#gmail.com", "mypassword");
// Send the request and receive the response:
CalendarEventFeed resultFeed = myService.query(myQuery, Feed.class);
You could make this a bit Groovier, using something like:
def myQuery = new CalendarQuery("http://www.google.com/calendar/feeds/default/private/full".toURL()).with {
minimumStartTime = DateTime.parseDateTime("2006-03-16T00:00:00");
maximumStartTime = DateTime.parseDateTime("2006-03-24T23:59:59");
it
}
def myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("jo#gmail.com", "mypassword");
// Send the request and receive the response:
def resultFeed = myService.query(myQuery, Feed);
If you do not need to alter the calendar, you only need to get the calendars private feed url, and you can use something like this (taken from the http://eu.gr8conf.org/agenda page). It uses the ICal4J library.
def url = "http://www.google.com/calendar/ical/_SOME_URL_/basic.ics".toURL()
def cal = Calendars.load(url)
def result = cal.components.sort { it.startDate.date }.collect {
def e = new Expando()
e.startDate = it.startDate.date
e.endDate = it.endDate.date
e.title = it.summary.value
if (it.location) {
e.presentation = Presentation.findByName(it.location.value, [fetch:"join"])
}
e.toString = {
"$startDate: $title"
}
return e
}
result
Happy hacking.

Categories