Errors when using Intent Detection with Dialogflow in JHIPSTER - java

I'm setting up a chat bot in JHIPSTER & Dialogflow. but I keep getting errors when I execute my code.
I have created a class called DetectIntent with the code for DetectIntent provided by DialogFlow v2, and a REST api that receives messages from users and then I call the DetectIntent class to understand what the user wants to say.
NOTE: I am behind a proxy of the company I work at.
import com.google.api.client.util.Maps;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;
import com.google.cloud.dialogflow.v2.SessionName;
import com.google.cloud.dialogflow.v2.SessionsClient;
import com.google.cloud.dialogflow.v2.TextInput;
import com.google.cloud.dialogflow.v2.TextInput.Builder;
import java.util.List;
import java.util.Map;
/**
* DialogFlow API Detect Intent sample with text inputs.
*/
public class DetectIntent {
public static Map<String, QueryResult> detectIntentTexts(
String projectId,
List<String> texts,
String sessionId,
String languageCode) throws Exception {
Map<String, QueryResult> queryResults = Maps.newHashMap();
// Instantiates a client
try (SessionsClient sessionsClient = SessionsClient.create()) {
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
SessionName session = SessionName.of(projectId, sessionId);
System.out.println("Session Path: " + session.toString());
// Detect intents for each text input
for (String text : texts) {
// Set the text (hello) and language code (en-US) for the query
TextInput.Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode);
// Build the query with the TextInput
QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
// Performs the detect intent request
DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);
// Display the query result
QueryResult queryResult = response.getQueryResult();
System.out.println("====================");
System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
System.out.format("Detected Intent: %s (confidence: %f)\n",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
queryResults.put(text, queryResult);
}
}
return queryResults;
}
}
#RestController
#RequestMapping("/api")
public class ConversationExchange {
public ConversationExchange()
{
}
// Receive Messages Web Hook
#PostMapping(path="/whatsapp/hook")
public void TwilioWebHook(#RequestParam Map<String, String> map) throws Exception {
System.out.println("************************************************");
System.out.println("************************************************");
System.out.println("- DATA : " + map );
System.out.println("- SMS ID : " + map.get("SmsSid").toString());
System.out.println("- SENDER : " + map.get("From").toString());
System.out.println("- RECEIVER : " + map.get("To").toString());
System.out.println("- MESSAGE : " + map.get("Body").toString());
System.out.println("- STATUS : " + map.get("SmsStatus").toString());
System.out.println("- MESSAGE SID : " + map.get("MessageSid").toString());
System.out.println("- Account SID : " + map.get("AccountSid").toString());
System.out.println("************************************************");
System.out.println("************************************************");
List<String> list = new ArrayList<String>(Arrays.asList(map.get("Body").split(" ")));
// Detect Intent From Message
String session = UUID.randomUUID().toString();
DetectIntent detectIntent = new DetectIntent();
String response = detectIntentTexts("agent...", list, session,"fr-FR").toString();
System.out.println("----> INTENT DETECTED : " + response );
// SEND RESPONSE
}
}
I excepted to get the intent detected but what I get multiple errors in the console.
i.g.n.s.io.grpc.netty.GrpcSslContexts : Conscrypt class not found. Not using Conscrypt
i.g.n.s.i.n.u.i.NativeLibraryLoader : Unable to load the library 'io_grpc_netty_shaded_netty_tcnative_windows_x86_64', trying other loading mechanism.
i.g.n.s.i.n.u.i.NativeLibraryLoader : io_grpc_netty_shaded_netty_tcnative_windows_x86_64 cannot be loaded from java.libary.path, now trying export to -Dio.netty.native.workdir:..
Couldn't load full implementation for TagsComponent, now trying to load lite implementation.
io.opencensus.tags.Tags : Couldn't load lite implementation for TagsComponent, now using default implementation for TagsComponent.
io.opencensus.stats.Stats : Couldn't load full implementation for StatsComponent, now trying to load lite implementation.
io.opencensus.stats.Stats : Couldn't load lite implementation for StatsComponent, now using default implementation for StatsComponent.
io.opencensus.trace.Tracing : Couldn't load full implementation for TraceComponent, now trying to load lite implementation.
io.opencensus.trace.Tracing : Couldn't load lite implementation for TraceComponent, now using default implementation for TraceComponent.
io.grpc.Context : Storage override doesn't exist. Using default

Fixed it, the issue was the proxy, I had to set system variables to support the proxy.

Related

Unable to connect dialogflow using environment variable in local env

I created a simple dialogflow intent.
I want to consume it from java application in local environment (Linux).
I get the error :
The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials.
I set environment variable like this :
export GOOGLE_APPLICATION_CREDENTIALS="/home/me/******.json"
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-dialogflow</artifactId>
<version>0.99.0-alpha</version>
</dependency>
public class App {
public static void main(String[] args) throws Exception {
String projectId = "my-project-id";
String sessionId = "fake_session_for_testing";
String languageCode = "fr-FR";
List<String> texts = Arrays.asList("hello", "Qui tu es");
Map<String, QueryResult> result = detectIntentTexts(projectId, texts, sessionId, languageCode);
result.forEach((s, q) -> System.out.println(s + " " + q));
}
public static Map<String, QueryResult> detectIntentTexts(
String projectId,
List<String> texts,
String sessionId,
String languageCode) throws Exception {
Map<String, QueryResult> queryResults = new HashMap<>();
// Instantiates a client
try (SessionsClient sessionsClient = SessionsClient.create()) {
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
SessionName session = SessionName.of(projectId, sessionId);
System.out.println("Session Path: " + session.toString());
// Detect intents for each text input
for (String text : texts) {
// Set the text (hello) and language code (en-US) for the query
TextInput.Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode);
// Build the query with the TextInput
QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
// Performs the detect intent request
DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);
// Display the query result
QueryResult queryResult = response.getQueryResult();
System.out.println("====================");
System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
System.out.format("Detected Intent: %s (confidence: %f)\n",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
queryResults.put(text, queryResult);
}
}
return queryResults;
}
}

How to assign roles with a Discord bot made in Java?

I'm trying to get my Meeseeks bot to assign and remove roles on discord for my personal server. I'm not all too familiar with the special methods and commands, and I've had no luck looking for it!
This is my code right now;
package discord.meeseeksBot;
import discord.meeseeksBot.Ref2;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.MessageChannel;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
public class App extends ListenerAdapter
{
public static void main(String[] args) throws Exception
{
JDA jda = new
JDABuilder(AccountType.BOT).setToken(Ref2.token).buildBlocking();
jda.addEventListener(new App());
}
#Override
public void onMessageReceived(MessageReceivedEvent evt)
{
User objUser = evt.getAuthor();
MessageChannel objMsgCh = evt.getChannel();
Message objMsg = evt.getMessage();
//the prefix to which the bot responds to is "Mr.Meeseeks, "
if(objMsg.getContentRaw().equalsIgnoreCase(Ref2.prefix+"I need
help"))
{
objMsgCh.sendMessage("Hi, " + objUser.getAsMention() + ", " + "
I'm Mr.Meeseeks! Look at me! How can I help?").queue();
objMsgCh.sendMessage("You can tell me to **ADD** you to a role,
or **REMOVE** you from a role!").queue();
}
}
}
I'm working to get the bot to where he'll reply to "Mr.Meeseeks, I need help"
with a list of title roles (these roles serve no hierarchical purpose, nor do they appear separately from online members!) you can choose from, and apply to yourself. I'd also like him to be able to remove yourself from a role.
And example for what I had in mind was a role for gender pronouns, (i.e. "she/her" or "he/him") so that when a profile is clicked on in the server, you'd be able to see what they'd be called.
So you could say, "Mr.Meeseeks, add me to "she/her" pronouns!" and he'd do that for you, or "Mr.Meeseeks, remove me from "she/her" pronouns!".
I can't seem to figure it out for Java.
I am not too familiar with JDA, as Discord4J is better, but I can point you in the right direction.
You want to use regex to test for "Mr", "Meeseeks", "add", and "me" all in the same message. Then you can test for the gender pronouns:
#Override
public void onMessageReceived(MessageReceivedEvent evt) {
User objUser = evt.getAuthor();
MessageChannel objMsgCh = evt.getChannel();
Message objMsg = evt.getMessage();
String content = objMsg.getContentRaw();
Guild guild = evt.getGuild();
//the prefix to which the bot responds to is "Mr.Meeseeks, "
if (objMsg.getContentRaw().equalsIgnoreCase(Ref2.prefix + "I need help")) {
objMsgCh.sendMessage("Hi, " + objUser.getAsMention() + ", " + " I'm Mr.Meeseeks! Look at me! How can I help?").queue();
objMsgCh.sendMessage("You can tell me to **ADD** you to a role, or **REMOVE** you from a role!").queue();
// Test for "Mr", "Meeseeks", "add", and "me".
} else if (content.matches("^(?=.*\\badd\\b)(?=.*\\bme\\b)(?=.*\\bto\\b)(?=.*\\bMr\\b)(?=.*\\bMeeseeks\\b).+")) {
// Test for pronouns (Assuming your roles names are "he/him" and "she/her")
Role group = content.matches("((she)|(her))") ? guild.getRolesByName("she/her", true).get(0) :
content.matches("((he)|(him))") ? guild.getRolesByName("he/him", true).get(0) : null;
if (group == null) {
// Let the user know if they used an invalid pronoun.
objMsgCh.sendMessage("Sorry " + objUser.getAsMention() + ", I can't find that role!").queue();
} else {
// Assign the role.
guild.getController().addRolesToMember​(guild.getMember(objUser), group);
objMsgCh.sendMessage("Added " + objUser.getAsMention() + " to " + group.getName() + "!").queue();
}
}
}

Hello Analytics API: Java quickstart errors

I'm trying to access data from the Google analytics reporting API using Java.
I was following the "Hello Analytics API: Java quickstart for installed applications" tutorial, and i did everything it tells you, and i get following issues:
com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\<user>\.store\hello_analytics
com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\timst\.store\hello_analytics
java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at com.example.demo.HelloAnalytics.initializeAnalytics(HelloAnalytics.java:60)
at com.example.demo.HelloAnalytics.main(HelloAnalytics.java:44)
I tried using the full path for the client_secret.json.
tried using different methods i found online, but none seem to work.
After getting frustrated by this error i tried the "Hello Analytics API: Java quickstart for service accounts" tutorial.
But here i have the issue that i can't add users to the account, property or view for the accounts i can access.
I have access to other peoples analytics accounts and I can only remove myself from the accounts.
All code I'm using is from the tutorials, using Intellij and gradle.
tl;dr; All I want to do is access the analytics data for all my
accounts, using the reporting API so i can put all this data in my own
database and use this database for my other projects.
the Tutorials google provides doesn't work for me. (the data is mostly Google Adwords data.)
So the Warning is not the problem, it's a known issue with it not working properly on windows.
The java.lang.NullPointerException is because the profile I call to has no rows of data for the given metric. so the return value of the call doesn't have a .getRows() methode because there isn't a row value.
you should check for the row's first,
GaData results;
if (null != results) {
if(results.get("rows") != null){
if (!results.getRows().isEmpty()){
//do something with the rows exp.
for (List<String> row : results.getRows()) {
for (int i=0; i<results.getColumnHeaders().size();i++) {
List<GaData.ColumnHeaders> headers = results.getColumnHeaders();
System.out.println( headers.get(i).getName()+": " + row.get(i));
}
}
}
}
}
In the example I also use the ColumnHeaders, wich you should also check first.
It was also easier to check every single account i had access to and every webProperty and Profile and not just the first value of each of those.
Also, the query explorer is really useful. you should use it to check out which metrics you can use and which dimensions.
Here is my full HelloAnalytics class i just print everything that might be usefull to the console i also use multiple metrics and a dimension from Google AdWords in the getResults methode:
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.AnalyticsScopes;
import com.google.api.services.analytics.model.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* A simple example of how to access the Google Analytics API.
*/
public class HelloAnalytics {
// Path to client_secrets.json file downloaded from the Developer's Console.
// The path is relative to HelloAnalytics.java.
private static final String CLIENT_SECRET_JSON_RESOURCE = "/client_secret.json";
// The directory where the user's credentials will be stored.
private static final File DATA_STORE_DIR = new File("out/DataStore/hello_analytics");
private static final File OUTPUT_FILE = new File("out/DataStore/output.text");
private static final String APPLICATION_NAME = "Online Marketing Buddy";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static NetHttpTransport httpTransport;
private static FileDataStoreFactory dataStoreFactory;
public static void main(String[] args) {
try {
Analytics analytics = initializeAnalytics();
getProfileIds(analytics);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Analytics initializeAnalytics() throws Exception {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
// Load client secrets.
InputStream in =
HelloAnalytics.class.getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE);
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Set up authorization code flow for all auth scopes.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
.Builder(httpTransport, JSON_FACTORY, clientSecrets,AnalyticsScopes.all())
.setDataStoreFactory(dataStoreFactory)
.build();
// Authorize.
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
.authorize("user");
// Construct the Analytics service object.
Analytics response = new Analytics
.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
return response;
}
private static void getProfileIds(Analytics analytics) throws IOException {
// Get the all view (profile) IDs for the authorized user.
List<String> profileIds = new ArrayList<>();
// Query for the list of all accounts associated with the service account.
Accounts accounts = analytics.management().accounts().list().execute();
if (accounts.getItems().isEmpty()) {
System.err.println("No accounts found");
} else {
for (Account account : accounts.getItems()) {
System.out.println("account: " + account.getName());
String accountId = account.getId();
// Query for the list of properties associated with the each account.
Webproperties properties = analytics.management().webproperties()
.list(accountId).execute();
if (properties.getItems().isEmpty()) {
System.err.println("No properties found for accountId: " + accountId);
} else {
for (Webproperty webproperty : properties.getItems()) {
System.out.println("\nwebproperty: " + webproperty.getName());
String webpropertyId = webproperty.getId();
// Query for the list views (profiles) associated with the property.
Profiles profiles = analytics.management().profiles()
.list(accountId, webpropertyId).execute();
if (profiles.getItems().isEmpty()) {
System.err.println("No views (profiles) found for accoundId: " + accountId + "and webpropertyId: " + webpropertyId);
} else {
// Return the first (view) profile associated with the property.
for (Profile profile : profiles.getItems()) {
System.out.println("\nprofileId added for profile: " + profile.getName());
profileIds.add(profile.getId());
printResults(getResults(analytics,profile.getId()), profile.getId());
}
}
System.out.println("---------- ---------- end webproperty: " + webproperty.getName() + "---------- ----------");
}
}
System.out.println("---------- ---------- end account: " + account.getName() + "---------- ----------");
}
}
}
private static GaData getResults(Analytics analytics, String profileId) throws IOException {
// Query the Core Reporting API for the number of sessions
// in the past 30 days.
GaData data = analytics.data().ga()
.get("ga:" + profileId, "30daysAgo", "yesterday", "ga:adClicks, ga:adCost, ga:transactions, ga:transactionRevenue, ga:users, ga:sessions")
.setDimensions("ga:adwordsCampaignID")
.execute();
return data;
}
private static void printResults(GaData results, String profile) {
// Parse the response from the Core Reporting API for
// the profile name and number of sessions.
if (null != results) {
System.out.println("View (Profile: " + profile + ") Name: "
+ results.getProfileInfo().getProfileName() + "\n");
if (results.get("rows") != null && results.get("columnHeaders") != null) {
if (!results.getRows().isEmpty() && !results.getColumnHeaders().isEmpty()) {
for (List<String> row : results.getRows()) {
for (int i=0; i<results.getColumnHeaders().size();i++) {
List<GaData.ColumnHeaders> headers = results.getColumnHeaders();
System.out.println( headers.get(i).getName()+": " + row.get(i) + "\n");
}
System.out.println("---------- ---------- ----------\n");
}
} else {
System.out.println("No rows or columHeaders empty\n");
}
} else {
System.out.println("No rows or columHeaders\n");
}
}
}
}

How can I update custom properties in alfresco workflow task using only Java?

First, I want to say thanks to everyone that took their time to help me figure this out because I was searching for more than a week for a solution to my problem. Here it is:
My goal is to start a custom workflow in Alfresco Community 5.2 and to set some custom properties in the first task trough a web script using only the Public Java API. My class is extending AbstractWebScript. Currently I have success with starting the workflow and setting properties like bpm:workflowDescription, but I'm not able to set my custom properties in the tasks.
Here is the code:
public class StartWorkflow extends AbstractWebScript {
/**
* The Alfresco Service Registry that gives access to all public content services in Alfresco.
*/
private ServiceRegistry serviceRegistry;
public void setServiceRegistry(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
#Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
// Create JSON object for the response
JSONObject obj = new JSONObject();
try {
// Check if parameter defName is present in the request
String wfDefFromReq = req.getParameter("defName");
if (wfDefFromReq == null) {
obj.put("resultCode", "1 (Error)");
obj.put("errorMessage", "Parameter defName not found.");
return;
}
// Get the WFL Service
WorkflowService workflowService = serviceRegistry.getWorkflowService();
// Build WFL Definition name
String wfDefName = "activiti$" + wfDefFromReq;
// Get WorkflowDefinition object
WorkflowDefinition wfDef = workflowService.getDefinitionByName(wfDefName);
// Check if such WorkflowDefinition exists
if (wfDef == null) {
obj.put("resultCode", "1 (Error)");
obj.put("errorMessage", "No workflow definition found for defName = " + wfDefName);
return;
}
// Get parameters from the request
Content reqContent = req.getContent();
if (reqContent == null) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Missing request body.");
}
String content;
content = reqContent.getContent();
if (content.isEmpty()) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Content is empty");
}
JSONTokener jsonTokener = new JSONTokener(content);
JSONObject json = new JSONObject(jsonTokener);
// Set the workflow description
Map<QName, Serializable> params = new HashMap();
params.put(WorkflowModel.PROP_WORKFLOW_DESCRIPTION, "Workflow started from JAVA API");
// Start the workflow
WorkflowPath wfPath = workflowService.startWorkflow(wfDef.getId(), params);
// Get params from the POST request
Map<QName, Serializable> reqParams = new HashMap();
Iterator<String> i = json.keys();
while (i.hasNext()) {
String paramName = i.next();
QName qName = QName.createQName(paramName);
String value = json.getString(qName.getLocalName());
reqParams.put(qName, value);
}
// Try to update the task properties
// Get the next active task which contains the properties to update
WorkflowTask wfTask = workflowService.getTasksForWorkflowPath(wfPath.getId()).get(0);
// Update properties
WorkflowTask updatedTask = workflowService.updateTask(wfTask.getId(), reqParams, null, null);
obj.put("resultCode", "0 (Success)");
obj.put("workflowId", wfPath.getId());
} catch (JSONException e) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST,
e.getLocalizedMessage());
} catch (IOException ioe) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST,
"Error when parsing the request.",
ioe);
} finally {
// build a JSON string and send it back
String jsonString = obj.toString();
res.getWriter().write(jsonString);
}
}
}
Here is how I call the webscript:
curl -v -uadmin:admin -X POST -d #postParams.json localhost:8080/alfresco/s/workflow/startJava?defName=nameOfTheWFLDefinition -H "Content-Type:application/json"
In postParams.json file I have the required pairs for property/value which I need to update:
{
"cmprop:propOne" : "Value 1",
"cmprop:propTwo" : "Value 2",
"cmprop:propThree" : "Value 3"
}
The workflow is started, bpm:workflowDescription is set correctly, but the properties in the task are not visible to be set.
I made a JS script which I call when the workflow is started:
execution.setVariable('bpm_workflowDescription', 'Some String ' + execution.getVariable('cmprop:propOne'));
And actually the value for cmprop:propOne is used and the description is properly updated - which means that those properties are updated somewhere (on execution level maybe?) but I cannot figure out why they are not visible when I open the task.
I had success with starting the workflow and updating the properties using the JavaScript API with:
if (wfdef) {
// Get the params
wfparams = {};
if (jsonRequest) {
for ( var prop in jsonRequest) {
wfparams[prop] = jsonRequest[prop];
}
}
wfpackage = workflow.createPackage();
wfpath = wfdef.startWorkflow(wfpackage, wfparams);
The problem is that I only want to use the public Java API, please help.
Thanks!
Do you set your variables locally in your tasks? From what I see, it seems that you define your variables at the execution level, but not at the state level. If you take a look at the ootb adhoc.bpmn20.xml file (https://github.com/Activiti/Activiti-Designer/blob/master/org.activiti.designer.eclipse/src/main/resources/templates/adhoc.bpmn20.xml), you can notice an event listener that sets the variable locally:
<extensionElements>
<activiti:taskListener event="create" class="org.alfresco.repo.workflow.activiti.tasklistener.ScriptTaskListener">
<activiti:field name="script">
<activiti:string>
if (typeof bpm_workflowDueDate != 'undefined') task.setVariableLocal('bpm_dueDate', bpm_workflowDueDate);
if (typeof bpm_workflowPriority != 'undefined') task.priority = bpm_workflowPriority;
</activiti:string>
</activiti:field>
</activiti:taskListener>
</extensionElements>
Usually, I just try to import all tasks for my custom model prefix. So for you, it should look like that:
import java.util.Set;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.apache.log4j.Logger;
public class ImportVariables extends AbstractTaskListener {
private Logger logger = Logger.getLogger(ImportVariables.class);
#Override
public void notify(DelegateTask task) {
logger.debug("Inside ImportVariables.notify()");
logger.debug("Task ID:" + task.getId());
logger.debug("Task name:" + task.getName());
logger.debug("Task proc ID:" + task.getProcessInstanceId());
logger.debug("Task def key:" + task.getTaskDefinitionKey());
DelegateExecution execution = task.getExecution();
Set<String> executionVariables = execution.getVariableNamesLocal();
for (String variableName : executionVariables) {
// If the variable starts by "cmprop_"
if (variableName.startsWith("cmprop_")) {
// Publish it at the task level
task.setVariableLocal(variableName, execution.getVariableLocal(variableName));
}
}
}
}

Authorize.net Java example

I am looking to develop simple Java program which will be sending a request and get response from "Authorize.net" say for Authorization, Capture, Void, Refund Transactions etc. I have created my test account in authorized.net - https://sandbox.authorize.net/. I did goggled lots of week and didn't find any sample example for reference.
I am using AIM for my development, let's say I've code for AuthTransaction
GenericValue cc = (GenericValue) params.get("creditCard");
String currency = (String) params.get("currency");
String amount = ((BigDecimal)params.get("processAmount")).toString();
String number = UtilFormatOut.checkNull(cc.getString("cardNumber"));
String expDate = UtilFormatOut.checkNull(cc.getString("expireDate"));
String cardSecurityCode = (String) params.get("cardSecurityCode");
AIMRequest.put("x_Amount", amount);
AIMRequest.put("x_Currency_Code", currency);
AIMRequest.put("x_Method", props.getProperty("method"));
AIMRequest.put("x_Type", props.getProperty("transType"));
AIMRequest.put("x_Card_Num", number);
AIMRequest.put("x_Exp_Date", expDate);
if (UtilValidate.isNotEmpty(cardSecurityCode)) {
AIMRequest.put("x_card_code", cardSecurityCode);
}
if (AIMRequest.get("x_market_type") != null) {
AIMRequest.put("x_card_type", getCardType(UtilFormatOut.checkNull(cc.getString("cardType"))));
}
But I don't know how to make a request call and get a response back. Any one please guide me / provide me sample code ?
Yes, Authorize.net does provide Java SDK and maven dependency from http://mvnrepository.com/artifact/net.authorize/anet-java-sdk.
Authorize.Net SDK includes standard payments, recurring billing, and customer profiles.
I've perform the simple AuthCapture Transaction through following Java code
package com.auth.net;
import java.math.BigDecimal;
import net.authorize.Environment;
import net.authorize.Merchant;
import net.authorize.TransactionType;
import net.authorize.aim.Result;
import net.authorize.aim.Transaction;
import net.authorize.data.creditcard.CreditCard;
public class AIMauthCaptureTransactionDemo {
public static final String apiLoginID= "Your Sandbox API Login ID";
public static final String transactionKey= "Your Sandbox API Transaction Key";
public static void main(String[] args) {
Merchant merchant = Merchant.createMerchant(Environment.SANDBOX, apiLoginID, transactionKey);
// create credit card
CreditCard creditCard = CreditCard.createCreditCard();
creditCard.setCreditCardNumber("4111 1111 1111 1111");
creditCard.setExpirationMonth("12");
creditCard.setExpirationYear("2018");
// create transaction
Transaction authCaptureTransaction = merchant.createAIMTransaction
(TransactionType.AUTH_CAPTURE, new BigDecimal("5.00"));
authCaptureTransaction.setCreditCard(creditCard);
#SuppressWarnings("unchecked")
Result<Transaction> result = (Result<Transaction>)merchant.postTransaction(authCaptureTransaction);
if(result.isApproved()) {
System.out.println("Response Code : "+ result.getReasonResponseCode());
System.out.println("Response Text : " + result.getResponseText());
System.out.println("Transaction Id: " + result.getTarget().getTransactionId());
System.out.println("AuthorizationCode : "+result.getTarget().getAuthorizationCode());
}
else if (result.isDeclined()) {
System.out.println(result.getReasonResponseCode() + " : " + result.getResponseText());
}
else {
System.out.println(result.getReasonResponseCode() + " : " + result.getResponseText());
}
}
}
Here, Please refer first transaction which I performed some time before in below screen shot

Categories