How to use Dialog Directives with Alexa's java SDK - java

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.

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);

"Unsupported protocol element" when creating Interactions programmatically

I am attempting to create new Interactions programmatically on Genesys Platform SDK 8.5 for Java.
I use the example on the API reference
public void createInteraction(String ixnType, String ixnSubtype, String queue) throws Exception
{
RequestSubmit req = RequestSubmit.create();
req.setInteractionType(ixnType);
req.setInteractionSubtype(ixnSubtype);
req.setQueue(queue);
req.setMediaType("email");
Message response = mPMService.getProtocol("IxnSrv").request(req);
if(response == null || response.messageId() != EventAck.ID) {
// For this sample, no error handling is implemented
return;
}
EventAck event = (EventAck)response;
mInteractionId = event.getExtension().getString("InteractionId");
}
However, this gives me an Unsupported protocol element error.
'EventError' (126) attributes:
attr_error_desc [str] = "Unsupported protocol element"
attr_ref_id [int] = 2
attr_error_code [int] = 4
How do I create a new Interaction programmatically?
Interaction server should be connected with ClientType as either MediaServer or AgentApplication for this request(RequestSubmit).
First of all, you must open your protocol as Media Server. After that you must submit your interaction to interaction server.
Firstly your protocol config must be like this;
interactionServerConfiguration.ClientName = "TestClient";
interactionServerConfiguration.ClientType = InteractionClient.MediaServer;
// Register this connection configuration with Protocol Manager
protocolManagementService.Register(interactionServerConfiguration);
Note : You must have MediaServer type application definition on your Configuration Env., you must see it in CME.
After open you connection to ixn server. You can submit your interaction what you like. Even you can create new type interaction just like i do. I did for our coopate sms system. Its name is not important. We defined it on our bussiness attribute, so our agent can send coopate 3rd party sms system from their agent desktop. Without new extension or new license :) Just tricked it system. Also genesys allows it. i know it because we are genesys official support team in our country :) (But agent seat license may be required depends on agent head count).
RequestSubmit request = RequestSubmit.Create();
request.TenantId = 1;
request.MediaType = "email";
request.Queue = c_inboundQueue;
request.InteractionType = "Inbound";
request.InteractionSubtype = "InboundNew";
// Prepare the message to send. It is inserted in the request as UserData
KeyValueCollection userData =
new KeyValueCollection();
// Prepare the message to send
userData.Add("Subject", "subject goes here");
request.UserData = userData; protocolManagementService[c_interactionServerConfigurationIdentifier].Send(request);
Turns out I needed to set ClientType to InteractionClient.ReportingEngine.

Creating Meeting lotus Meeting using ICall

In a eclipse plugin for the Lotus Notes client I need to create a meeting in a user's mailfile. I have created successfully an appointment in my own mailfile using the NotesCalendar object. (see code below ). What I don't seem to get right is to create a meeting instead of an appointment. On the database level the difference is made by a field called appointmenttype which is set to 3 in the case of a meeting and 0 in the case of a appointment.
According to resources I found I need to add the xProperty "X-LOTUS-APPTTYPE" with a value of "3" to my Ical4j object but for some reason this is not being processed by the NotesCalendar.createEntry() method.
Does someone have any idea how to create a Meeting in a mailfile using the NotesCalendar notes classes and Ical4j?
(the reason I have added the xPages tag is that I hope someone in the xPages community ever has used the notescalendar objects before )
Code that creates an appointment:
DateTime meetingStart = new DateTime(c.getStartTime().getTime());
DateTime meetingEnd = new DateTime(c.getEndTime().getTime());
VEvent meeting = new VEvent(meetingStart, meetingEnd, c.getSubject());
// Add chair
Attendee chairAttendee = new Attendee(URI.create("mailto:j.somhorst#development.acuity.nl"));
chairAttendee.getParameters().add(Role.CHAIR);
// Add invitees
for(User invitee : c.getUserParticipants()){
Attendee attendee = new Attendee(URI.create("mailto:"+invitee.getEmail()));
attendee.getParameters().add(Role.REQ_PARTICIPANT);
meeting.getProperties().add(attendee);
}
// create calendar for ics export
Calendar call = new Calendar();
call.getProperties().add(new ProdId("-//Lotus Development Corporation//NONSGML Notes 9.0.1//EN_API_C"));
call.getComponents().add(meeting);
// notes specific fields
meeting.getProperties().add(new XProperty("X-LOTUS-NOTESVERSION","2"));
meeting.getProperties().add(new XProperty("X-LOTUS-APPTTYPE","3"));
NotesCalendar notesCalendar = NotesUtil.getNotesCalendar(s);
if(notesCalendar!=null){
notesCalendar.setAutoSendNotices(false);
NotesCalendarEntry entry = notesCalendar.createEntry(call.toString());
String icallvalue = entry.read();
System.out.println(icallvalue);
}

how to retrieve orders from ordertools component in atg or how to test orderlookup droplet api

iam trying to orderlookup droplet API by passing some parameters.I assume that the parameters which are mandatory is userId and organisationIds which i have passed and additionally i have also passed "state" parameter.All these params are passed thru request and then the service method of droplet is invoked.But the service method returns nothing.My goal is to check whether this droplet this retrieving the expected set of orders or not.We can use droplet invoker but i tried that way but it didnt work may be i missed something.Please help me out!!
this is my code when i tried to use OrderLookUp API
DynamoHttpServletRequest request = ServletUtil.getCurrentRequest();
mTestService.setCurrentRequest(request);
if (request == null) {
mTestService.vlogError("Request is null.");
Assert.fail("Request is null ");
}
else
{
Object droplet = mTestService
.getRequestScopedComponent("OrderLookupDroplet");
OrderLookupDroplet=(OrderLookup) droplet;
request.setParameter("state", "submitted");
request.setParameter("organisationIds", organizationIds);
request.setParameter("userId", userId);
ByteBuffer buffer = ByteBuffer.allocate(1024);
DynamoHttpServletRequest dynRequest = (DynamoHttpServletRequest) request;
TestingDynamoHttpServletRequest wrappedRequest = new TestingDynamoHttpServletRequest(
dynRequest, buffer);
TestingDynamoHttpServletResponse wrappedResponce = new TestingDynamoHttpServletResponse(
dynRequest.getResponse());
OrderLookupDroplet.service(wrappedRequest, wrappedResponce);
}
the above sample is only part of the code..
this is the code when i tried using droplet invoker
DropletInvoker invoker = new DropletInvoker(mNucleus);
invoker.getRequest().setParameter("state", "submitted");
// String [] siteIds = {"siteA", "siteB"};
// invoker.getRequest().setParameter("siteIds", Arrays.asList(siteIds));
String [] organizationIds = {"OrgA", "OrgB"};
invoker.getRequest().setParameter("organizationIds", organizationIds);
String [] orderIds = {"orderautouser001OrgA" , "orderautouser001OrgB"};
invokeDroplet(invoker, "autouser001", orderIds);
......
protected void invokeDroplet(DropletInvoker pInvoker, String pUserId, String[] pOrderIds) throws Exception
{
Map<String, Object> localParams = new HashMap();
localParams.put("userId", pUserId);
DropletResult result = pInvoker.invokeDroplet("/atg/commerce/order/OrderLookup", localParams);
RenderedOutputParameter oparam = result.getRenderedOutputParameter("output", 0);
assertNotNull("'output' oparam was not rendered", oparam);
assertEquals("Check totalCount.", pOrderIds.length, oparam.getFrameParameter("totalCount"));
List<Order> orders = (List<Order>)oparam.getFrameParameter("result");
assertEquals("Check order array length.", pOrderIds.length, orders.size());
for (int index = 0; index < pOrderIds.length; index++) {
boolean found = false;
for (Order order: orders) {
if (pOrderIds[index].equals(order.getId())) {
found = true;
break;
}
}
assertTrue("Expected orderId " + pOrderIds[index] + " not found in result array", found);
}
in first case i donno how to retrieve the orders by directly using orderlookup api....and in second case though i know how to use it ,iam still failing!! please help me out..thanks in advance
You should't use droplets in java classes they should be used only inside jsp pages. Documentation of OrderLookup with example hot to use it on jsp page is here.
If you want to get orders or any other data stored in a repository you should use repository API with RQL (Repository Query Language). Example how to get data from repository you can find here and RQL grammar here.
Thanks for giving your opinions.Good news is we can invoke droplets from any other API
OrderLookup droplet = (OrderLookup) sNucleus.resolveName("/atg/commerce/order/OrderLookup");
ServletTestUtils utils = new ServletTestUtils();
mRequest = utils.createDynamoHttpServletRequestForSession(sNucleus, null, null);
ServletUtil.setCurrentRequest(mRequest);
mResponse = new DynamoHttpServletResponse();
mRequest.setResponse(mResponse);
mResponse.setRequest(mRequest);
mResponse.setResponse(new GenericHttpServletResponse());
mRequest.setParameter("userId", "publishing");
droplet.setSearchByUserId(true);
droplet.service(mRequest, mResponse);
ArrayList<Order> orders = (ArrayList<Order>) mRequest.getObjectParameter("result");
here the "result" param is output param which this droplet sets.and the userId i have hardcoded as "publishing" which i have created.Ignore servletTestUtils class that is created by me which has not much to do with droplet theory here :)
I assume from your code example, and the fact that you mention DropletInvoker that you are writing a unit test, and that this is not functional code.
If it is functional code, you really, really, should not invoke a droplet from another Nucleus component. A droplet exists solely to be used in a JSP page. If you need the functionality of the droplet in Java code, you should refactor the droplet into a service that holds the main logic, and a droplet that simply acts as a façade to the service to allow it to be invoked from a page.
In the case of the OrderLookup look droplet, you don't need to refactor anything. The service to use should be OrderManager or OrderTools depending on what you need. Note, there is a difference between Order objects and Order repository items, and you should prefer to use order objects - so only use the Order Repository directly if you really need to.

how to create a lotus notes meeting using java in domino designer

Hi i am trying to create meeting in lotus notes using java.i am able to send a meeting invite to the recipients.But when i send a meeting the options available to the chair and the recipients are the same.(options like accept,decline).But the options for the chair and the recipients should be different.can anyone please tell how to do this?
public DocumentKey save(final Session session, final Database db, boolean send,
String moveToFolder) throws NotesException, Io Exception {
//setBody(null);
Document doc = null;
RichTextItem rti = null;
try {
doc = db.createDocument();
db.getView(ServiceConstants.MEETINGS);
// Here i am setting all the properties for that document.
// I cant post that code as it has
// over 100 properties, so more than 100 lines of code
rti = doc.createRichTextItem(ServiceConstants.BODY);
rti.appendText(getBody());
if ((attachment != null) && (attachment.length > 0)) {
for (int i = 0; i < attachment.length; i++) {
attachment[i].save(rti);
}
}
doc.save(true, true, true);
if (send) {
doc.send();
}
if (!isBlank(moveToFolder)) {
doc.putInFolder(moveToFolder, true);
}
setKey(new DocumentKey(doc.getNoteID()));
} finally {
Helper.cleanupIfNeeded(rti);
Helper.cleanupIfNeeded(doc);
}
return getKey();
}
To successfully schedule a meeting, you need to follow the calendaring and scheduling schema
In short: A meeting has to be created in the chair's mail file and the invitations have to be responses (doc.MakeResponse(...)) to that main document and sent via mail. The "ApptUnid"- item ties them all together.
Read the documentation in the link, it is very good
If you are using Notes / Domino 9.0 or greater, you should consider using the lotus.domino.NotesCalendar interface and its related interfaces. These relatively new interfaces let you create, read and update calendar entries using iCalendar format.
Here's some sample code:
// Get the NotesCalendar object from the database
NotesCalendar notesCalendar = session.getCalendar(database);
if ( notesCalendar == null ) {
throw new Exception("Cannot open calendar.");
}
// Create a meeting in iCalendar format
String ical = iCalendarMeeting();
// Create the meeting on the Notes calendar
NotesCalendarEntry entry = notesCalendar.createEntry(ical);
This code creates an instance of NotesCalendar from an instance of Database. Then it gets the representation of a meeting in iCalendar format (the iCalendarMeeting method is not shown). Finally, it calls NotesCalendar.createEntry() to create the meeting. The createEntry method places the meeting on the organizer's calender and sends an invitation to all attendees.

Categories

Resources