Paypal SDK set billing plan to active - java

I am new to the PayPal SDK and I am trying to create a billing plan and change its status to ACTIVE. I have tried some sample Java code from the SDK tutorial but I can't get that code to work. Status remains CREATED. The code I tried can be found below.
What is missing/wrong?
The output from running the code is
Created plan with id = P-1MT21723NA428154CRJGOTXQ
Plan state = CREATED
Plan state = CREATED
Best regards /Lasse
// Build Plan object
Plan plan = new Plan();
plan.setName("T-Shirt of the Month Club Plan");
plan.setDescription("Template creation.");
plan.setType("fixed");
// Payment_definitions
PaymentDefinition paymentDefinition = new PaymentDefinition();
paymentDefinition.setName("Regular Payments");
paymentDefinition.setType("REGULAR");
paymentDefinition.setFrequency("MONTH");
paymentDefinition.setFrequencyInterval("1");
paymentDefinition.setCycles("12");
// Currency
Currency currency = new Currency();
currency.setCurrency("USD");
currency.setValue("20");
paymentDefinition.setAmount(currency);
// Charge_models
ChargeModels chargeModels = new ChargeModels();
chargeModels.setType("SHIPPING");
chargeModels.setAmount(currency);
List<ChargeModels> chargeModelsList = new ArrayList<>();
chargeModelsList.add(chargeModels);
paymentDefinition.setChargeModels(chargeModelsList);
// Payment_definition
List<PaymentDefinition> paymentDefinitionList = new ArrayList<>();
paymentDefinitionList.add(paymentDefinition);
plan.setPaymentDefinitions(paymentDefinitionList);
// Merchant_preferences
MerchantPreferences merchantPreferences = new MerchantPreferences();
merchantPreferences.setSetupFee(currency);
merchantPreferences.setCancelUrl("https://example.com/cancel");
merchantPreferences.setReturnUrl("https://example.com/return");
merchantPreferences.setMaxFailAttempts("0");
merchantPreferences.setAutoBillAmount("YES");
merchantPreferences.setInitialFailAmountAction("CONTINUE");
plan.setMerchantPreferences(merchantPreferences);
// Create payment
Plan createdPlan = plan.create(apiContext);
System.out.println("Created plan with id = " + createdPlan.getId());
System.out.println("Plan state = " + createdPlan.getState());
// Set up plan activate PATCH request
List<Patch> patchRequestList = new ArrayList<>();
Map<String, String> value = new HashMap<>();
value.put("state", "ACTIVE");
// Create update object to activate plan
Patch patch = new Patch();
patch.setPath("/");
patch.setValue(value);
patch.setOp("replace");
patchRequestList.add(patch);
// Activate plan
createdPlan.update(apiContext, patchRequestList);
System.out.println("Plan state = " + createdPlan.getState());

Got it!
I had to execute Plan.get(context, createdPlan.getId());
to get the latest state of the plan.

Related

How do I use the Grafana client for java to upload dashboards with a time-series filled panel to Grafana?

I am currently comparing time-series. They are stored in InfluxDB. My task is to get two time-series from InfluxDB, compare them and upload a visualization to Grafana. The comparison result would be output to console and the two time-series would be uploaded to Grafana in a dashboard and they should be in the same panel. I am trying to use the grafana-api-java-client found here. My problem is that I can not figure out how to do this with the provided examples and Javadocs. There is not a lot of documentation and the examples don't work properly in my case. I hope that someone has worked with this client and can explain how to properly add two time-series to a panel in a dashboard and upload it.
I will provide what I am doing and then post the examples from the github page of the API.
First of all this is how I am getting my time series:
public List<Double> getTimeSeries(String streetName, String start, String stop) {
//gets the query result
QueryResult queryResult = influxDB.query(new Query(String.format("SELECT value FROM your_measurement WHERE street='%s' " +
"AND time >= '%s' AND time <= '%s'", streetName, start, stop)));
//Gets the values from the query result
List<List<Object>> values = queryResult.getResults().iterator().next().getSeries().iterator().next().getValues();
//Adds the values to a list
List<Double> timeSeries = new ArrayList<>();
for (List<Object> li : values) {
timeSeries.add(Double.valueOf(li.get(1).toString()));
}
return timeSeries;
}
I can convert this list to an array of doubles:
double[] timeSeriesArray = timeSeries.stream().mapToDouble(d -> d).toArray();
The following is the first example. It works properly up until the getDashboard() and deleteDashboard() methods, where I get the error that such a dashboard does not exist, even though it does. I don't know what causes this error. Every new dashboard ends up in the folder "General". The method createDashboard() creates, as expected, an empty dashboard in Grafana.
import com.appnexus.grafana.client.GrafanaClient;
//Setup the client
GrafanaConfiguration grafanaConfiguration =
new GrafanaConfiguration().host("your_grafana_host").apiKey("Bearer your_secret_key");
GrafanaClient grafanaClient = new GrafanaClient(grafanaConfiguration);
//Setup the dashboard
String DASHBOARD_NAME = "new_dashboard";
Dashboard dashboard = new Dashboard()
.title(DASHBOARD_NAME)
.version(0);
GrafanaDashboard grafanaDashboard = new GrafanaDashboard().dashboard(dashboard);
//Make API calls
grafanaClient.createDashboard(grafanaDashboard);
grafanaClient.getDashboard(DASHBOARD_NAME);
grafanaClient.deleteDashboard(DASHBOARD_NAME);
This is the second example. I assume that I have to modify it in order to solve my problem. I had to replace two things to get this example to work, which I will explain with code comments. When executing this code it creates a dashboard with an empty panel. I expected something to be shown on the panel but it is empty and there are no axes.
import com.appnexus.grafana.client.GrafanaClient;
//Setup the client
GrafanaConfiguration grafanaConfiguration =
new GrafanaConfiguration().host("your_grafana_host").apiKey("Bearer your_secret_key");
GrafanaClient grafanaClient = new GrafanaClient(grafanaConfiguration);
//Setup the dashboard
String DASHBOARD_NAME = "new_dashboard";
DashboardPanelTarget dashboardPanelTarget =
new DashboardPanelTarget().refId("getSomeMetric").target("*");
DashboardPanelXAxis dashboardPanelXAxis =
new DashboardPanelXAxis().show(true).mode(DashboardPanelXAxis.Mode.TIME);
DashboardPanelYAxis dashboardPanelYAxis =
new DashboardPanelYAxis().format(DashboardPanelYAxis.Format.SHORT).logBase(1).show(true);
//Datasource is required or alerts cannot be added
DashboardPanel dashboardPanel =
new DashboardPanel()
//This might be where my data has to go but I am not sure.
.targets(new ArrayList<>(Collections.singletonList(dashboardPanelTarget)))
//Had to change DASHBOARD_DATA_SOURCE to a String -> "DASHBOARD_DATA_SOURCE", I assume it's just the name of the datasource.
//.datasource(DASHBOARD_DATA_SOURCE)
.datasource("DASHBOARD_DATA_SOURCE")
.type(DashboardPanel.Type.GRAPH)
.fill(1)
.title(dashboardName)
.linewidth(1)
.lines(true)
.height("300px")
.span(12)
.xaxis(dashboardPanelXAxis)
.yaxes(new ArrayList<>(Arrays.asList(dashboardPanelYAxis, dashboardPanelYAxis)));
DashboardRow dashboardRow =
new DashboardRow()
.collapse(false)
.panels(new ArrayList<>(Collections.singletonList(dashboardPanel)));
Dashboard dashboard =
new Dashboard()
.title(dashboardName)
.schemaVersion(1)
.rows(new ArrayList<>(Collections.singletonList(dashboardRow)));
DashboardMeta dashboardMeta = new DashboardMeta().canSave(true).slug(dashboardName);
GrafanaDashboard grafanaDashboard =
new GrafanaDashboard().meta(dashboardMeta).dashboard(dashboard);
//create new dashboard
//Had to change createDashboardTest() to createDashboard(), because createDashboardTest() doesn't seem to exist
//DashboardMeta createdDashboardMeta = createDashboardTest(grafanaDashboard);
DashboardMeta createdDashboardMeta = createDashboard(grafanaDashboard);

Check for conflict when booking an event on Microsoft calendar

I am using the following code to create events on a microsoft account calendar:
Event event = new Event();
event.subject = meetingType.getName();
event.body = getMicrosoftMeetingBody(meetingType);
event.start = getMicrosoftMeetingStart(timeSlot);
event.end = getMicrosoftMeetingEnd(timeSlot, meetingType);
event.location = getMicrosoftMeetingLocation();
event.attendees = getMicrosoftMeetingAttendeeList(attendeeName, attendeeEmail);
event.isOnlineMeeting = true;
event.onlineMeetingProvider = OnlineMeetingProviderType.TEAMS_FOR_BUSINESS;
event.reminderMinutesBeforeStart = SIXTY_MINUTES;
event.responseRequested = true;
Event createdEvent = graphClient.me().calendars(userCalendar.getCalendarId()).events()
.buildRequest()
.post(event);
The above code works and is creating events on the calendar. However, it double books a slot even if there are pre-existing events on it.
Is it possible to build a request in such a way so as to not do the booking if the slot is already booked?

Pagination on Google Analytics using Java

I'm implementing a data extraction from Google Analytics using Java and I'm following this example: https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-java
I managed to extract the data I need but I can't figure out how to set the start-index using its client. Below you can see the changed I made to the default implementation. I can set the page size but I can't find out how to set the start-index.
public GetReportsResponse getReport(String dateStart, String dateEnd) throws IOException {
String[] metricsArr = {"ga:users", "ga:newUsers", "ga:sessions", "ga:totalEvents"};
String[] dimensionsArr = {"ga:eventLabel","ga:eventCategory","ga:eventAction", "ga:country", "ga:countryIsoCode", "ga:dateHourMinute"};
// Create the DateRange object.
DateRange dateRange = new DateRange();
dateRange.setStartDate(dateStart);
dateRange.setEndDate(dateEnd);
// Create the Metrics object.
ArrayList<Metric> metrics = new ArrayList<Metric>();
for(String item : metricsArr){
Metric m = new Metric().setExpression(item).setAlias(item.replace("ga:", ""));
metrics.add(m);
}
ArrayList<Dimension> dimensions = new ArrayList<Dimension>();
for(String item : dimensionsArr){
Dimension d = new Dimension().setName(item);
dimensions.add(d);
}
// Create the ReportRequest object.
ReportRequest request = new ReportRequest()
.setViewId(this.VIEW_ID)
.setDateRanges(Arrays.asList(dateRange))
.setMetrics(metrics)
.setDimensions(dimensions)
.setFiltersExpression("ga:eventCategory=#NOTICE,ga:eventCategory==Document,ga:eventCategory==Document reader")
.setPageSize(10000);
ArrayList<ReportRequest> requests = new ArrayList<ReportRequest>();
requests.add(request);
// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest().setReportRequests(requests);
// Call the batchGet method.
GetReportsResponse response = service.reports().batchGet(getReport).execute();
// Return the response.
return response;
}
How can I achieve that so I can navigate through all pages and extract all items?
The Reporting API V4 uses page tokens. The reply from the reporting API will return the next page's token, see nextPageToken. Using that you can make the exact same call but updating the pageToken in the request with the nextpagetoken from the previous reply. Note that the first call you make the reporting API will not have a page token attached to the request and the last page will not have the nextpagetoken set.
I hope that helps.

How to use Dialog Directives with Alexa's java SDK

I'm trying to create my own Alexa's skill with the java skill kit, and I would like to use the Dialog Interface. I have created my Dialog model with the skill builder in beta, but now I don't understand what I need to return via my webservice in order to delegate my dialog.
Which class should I use to send Alexa a command to handle the next turn in the dialog ?
Moreover, I don't have the dialogState property in the IntentRequest class...
First of all the dialogState property is in the IntentRequest. I use version 1.3.1 of the following dependency (maven). To get the value use yourIntentRequestObject.getDialogState().
<dependency>
<groupId>com.amazon.alexa</groupId>
<artifactId>alexa-skills-kit</artifactId>
<version>1.3.1</version>
</dependency>
Below you see some sample usage from a Speechlet in the onIntent method:
if ("DoSomethingSpecialIntent".equals(intentName))
{
// If the IntentRequest dialog state is STARTED
// This is where you can pre-fill slot values with defaults
if (dialogueState == IntentRequest.DialogState.STARTED)
{
// 1.
DialogIntent dialogIntent = new DialogIntent(intent);
// 2.
DelegateDirective dd = new DelegateDirective();
dd.setUpdatedIntent(dialogIntent);
List<Directive> directiveList = new ArrayList<Directive>();
directiveList.add(dd);
SpeechletResponse speechletResp = new SpeechletResponse();
speechletResp.setDirectives(directiveList);
// 3.
speechletResp.setShouldEndSession(false);
return speechletResp;
}
else if (dialogueState == IntentRequest.DialogState.COMPLETED)
{
String sampleSlotValue = intent.getSlot("sampleSlotName").getValue();
String speechText = "found " + sampleSlotValue;
// Create the Simple card content.
SimpleCard card = new SimpleCard();
card.setTitle("HelloWorld");
card.setContent(speechText);
// Create the plain text output.
PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
speech.setText(speechText);
return SpeechletResponse.newTellResponse(speech, card);
}
else
{
// This is executed when the dialog is in state e.g. IN_PROGESS. If there is only one slot this shouldn't be called
DelegateDirective dd = new DelegateDirective();
List<Directive> directiveList = new ArrayList<Directive>();
directiveList.add(dd);
SpeechletResponse speechletResp = new SpeechletResponse();
speechletResp.setDirectives(directiveList);
speechletResp.setShouldEndSession(false);
return speechletResp;
}
}
Create a new DialogIntent
Create a DelegateDirectiveand assign it to the updatedIntentproperty
Set the shoulEndSession flag to false, otherwise Alexa terminates the session
Within the SkillBuilder select your Intent, it needs to have at least one slot which is marked as required. Configure utterances and prompts. You can also use {slotNames} within prompts.
-Sal
I think you may want to look at the newly updated working example at https://github.com/amzn/alexa-skills-kit-java/pull/45.

Is it possible using the Java AWS API to update a Route53 record?

I have a hosted domain on AWS Route53. Under that domain I have an 'A' record for a subdomain.
I would like to be able to update the IP address of the 'A' record using the Java API. However, when looking at the setAction method of the com.amazonaws.services.route53.model.Change class, it only accepts the CREATE or DELETE values. This seems to match the allowed values in the XML message that the Java API sends behind the scenes.
Is there any way to just update the IP address, or do I have to delete the original record and then create it again?
Thanks
It worked for me using this piece of code:
ResourceRecord record = new ResourceRecord(loadBalancer);
List<ResourceRecord> records = new ArrayList<ResourceRecord>();
records.add(record);
ResourceRecordSet recordsSet = new ResourceRecordSet();
recordsSet.setResourceRecords(records);
recordsSet.setType(RRType.CNAME);
recordsSet.setTTL(900L);
recordsSet.setName(subdomain + ".");
Change change = new Change(ChangeAction.CREATE, recordsSet);
List<Change> changes = new ArrayList<Change>();
changes.add(change);
ChangeBatch batch = new ChangeBatch(changes);
ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest();
request.setChangeBatch(batch);
request.setHostedZoneId(hostedZoneId);
ChangeResourceRecordSetsResult result = getRoute53Client().changeResourceRecordSets(request);
System.out.println(result);
Just replace the variables I used with proper data. (subdomain, loadBalancer and hostedZoneId). The method getRoute53Client() returns an instance of the AmazonRoute53Client class from the AWS API.
ResourceRecord rr = new ResourceRecord(IPAdress); // IPAddress will be String variable that has IP value
List<ResourceRecord> rrList = new ArrayList<ResourceRecord>();
rrList.add(rr);
// Create a ResourceRecordSet
ResourceRecordSet resourceRecordSet = new ResourceRecordSet();
resourceRecordSet.setName(domainName); //domainName is String value of your domain
resourceRecordSet.setType(RRType.A); //type of ResourceRecordSet
resourceRecordSet.setTTL(new Long(300));
resourceRecordSet.setWeight(new Long(0));
resourceRecordSet.setResourceRecords(rrList);
// Create a change
Change change = new Change(ChangeAction.CREATE, resourceRecordSet);
List<Change> changesList = new ArrayList<Change>();
changesList.add(change);
// Create a change batch
ChangeBatch changeBatch = new ChangeBatch(changesList);
// Create ChangeResourceRecordSetRequest.
ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest(hostedZoneID, changeBatch); //hostedZoneId is variable that is the id of HostedZone
// Send the request and get the response.
ChangeResourceRecordSetsResult result = amazonRoute53Client.changeResourceRecordSets(request);
// Print the result
System.out.println(result.getChangeInfo());
The only way is to use DELETE / CREATE sequence as mentioned here.
Creating a Change Batch Request
To create a change batch request, use the ChangeResourceRecordSets
action ChangeBatch element. You use CREATE and DELETE actions within
the ChangeBatch element for each record that you want to update. If
you are only creating records, then you will only use CREATE actions.
hostedzoneId = "hosted zone id from the route53"
aliasTargetHostedzoneId = "zone id of the connected resource such as loadbalancer, cloudfront etc.."
Route53Client route53Client = Route53Client.builder()
.credentialsProvider(StaticCredentialsProvider.create(awsCreds))
.region(Region.AWS_GLOBAL)
.build();
AliasTarget aliasTarget = AliasTarget.builder()
.dnsName(loadBalancerDomain)
.evaluateTargetHealth(false)
.hostedZoneId(aliasTargetHostedzoneId)
.build();
// Create a ResourceRecordSet
ResourceRecordSet resourceRecordSet = ResourceRecordSet.builder()
.name(fullDomainName+".")
.type(RRType.A)
.aliasTarget(aliasTarget)
.build();
// Create a change
Change change = Change.builder()
.action(ChangeAction.CREATE)
.resourceRecordSet(resourceRecordSet)
.build();
List<Change> changesList = new ArrayList<Change>();
changesList.add(change);
// Create a change batch
ChangeBatch changeBatch = ChangeBatch.builder()
.changes(changesList)
.build();
// Create ChangeResourceRecordSetRequest.
ChangeResourceRecordSetsRequest request = ChangeResourceRecordSetsRequest.builder()
.hostedZoneId(hostedzoneId)
.changeBatch(changeBatch)
.build();
// Send the request and get the response.
ChangeResourceRecordSetsResponse result = route53Client.changeResourceRecordSets(request);

Categories

Resources