Authorize.net Java example - java

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

Related

looking for a sample code to read parameter value from aws parameter store

looking for a sample java code to read parameter store values like RDS connection string from aws parameter store. appreicate code or any reference links. thanks.
Here is the V2 (not V1) example to read a specific parameter value from the AWS parameter store:
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.GetParameterRequest;
import software.amazon.awssdk.services.ssm.model.GetParameterResponse;
import software.amazon.awssdk.services.ssm.model.SsmException;
public class GetParameter {
public static void main(String[] args) {
final String USAGE = "\n" +
"Usage:\n" +
" GetParameter <paraName>\n\n" +
"Where:\n" +
" paraName - the name of the parameter\n";
if (args.length < 1) {
System.out.println(USAGE);
System.exit(1);
}
// Get args
String paraName = args[0];
Region region = Region.US_EAST_1;
SsmClient ssmClient = SsmClient.builder()
.region(region)
.build();
try {
GetParameterRequest parameterRequest = GetParameterRequest.builder()
.name(paraName)
.build();
GetParameterResponse parameterResponse = ssmClient.getParameter(parameterRequest);
System.out.println("The parameter value is "+parameterResponse.parameter().value());
} catch (SsmException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
}
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement;
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagementClientBuilder;
import com.amazonaws.services.simplesystemsmanagement.model.GetParametersRequest;
import com.amazonaws.services.simplesystemsmanagement.model.GetParametersResult;
...
private static AWSSimpleSystemsManagement ssmclient = AWSSimpleSystemsManagementClientBuilder
.standard().withRegion(System.getProperty("SystemsManagerRegion")).build();
...
GetParametersRequest paramRequest = new GetParametersRequest()
.withNames(parameterName).withWithDecryption(encrypted);
GetParametersResult paramResult = new GetParametersResult();
paramResult = ssmclient.getParameters(paramRequest);
I think GitHub may be of help. I searched for SsmClient getParameter language:java and some of the results seem promising.
This one for example:
public static String getDiscordToken(SsmClient ssmClient) {
GetParameterRequest request = GetParameterRequest.builder().
name("/discord/token").
withDecryption(Boolean.TRUE).
build();
GetParameterResponse response = ssmClient.getParameter(request);
return response.parameter().value();
}

Controlling events of a Twilio call

In the next sample code, Twilio puts in conversation OPERATOR_PHONE_NUMBER to CLIENT_PHONE_NUMBER, and records the call.
But I don't know what should be the code to control some things, one or both of the phones...:
does not exist.
exists but communicates.
exists, does not communicate but does not pick up.
exists, does not communicate, picks up and the conversation takes place.
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Call;
import com.twilio.rest.api.v2010.account.CallCreator;
import com.twilio.type.PhoneNumber;
import com.twilio.type.Twiml;
public class SimpleCallWithRecording2 {
private static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private static final String AUTH_TOKEN = "9ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ";
private static final String ASSIGNED_PHONE_NUMBER = "+15999999999999";
//Must be verified numbers in trial account
private static final String OPERATOR_PHONE_NUMBER = "+34888888888";
private static final String CLIENT_PHONE_NUMBER = "+34777777777";
public static void main(String[] args) throws Exception {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
PhoneNumber to = new PhoneNumber(OPERATOR_PHONE_NUMBER);
PhoneNumber from = new PhoneNumber(ASSIGNED_PHONE_NUMBER);
Twiml twiml = new Twiml(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?> " +
"<Response> " +
" <Say voice=\"woman\">This is said by a robotic woman</Say> " +
" <Dial> " +
" <Number> " + CLIENT_PHONE_NUMBER + "</Number> " +
" </Dial> " +
"</Response> " );
CallCreator callCreator = Call.creator(to, from, twiml);
callCreator.setRecord(true);
Call call = callCreator.create();
System.out.println(call);
}
}
In the doc I see something could be done with callCreator.setStatusCallback(URI.create("https://www.myapp.com/events")), and some clasification of events: "initiated", "ringing", "answered", "completed". BUT I havent find the code "on the other side", I mean in https://www.myapp.com/events extreme ¿?
You need to setup a that rest endpoint and set it as status callback url.
The url will recieve events from twilio.
Refer this
edit: if you also need events from the nested verb, define attribute 'action' to it.
ie
<Dial action="//callbackURL">
<Number> CLIENT_PHONE_NUMBER </Number>
</Dial>
that way you'll know your cases 1 ,2 ,3 ,4.
and to "control" the call, you just respond with the desired TwiML to the callback request. Hope this clarifies.
edit2: You need to do something like:
//handles callback url
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
{ //...
TwiMLResponse twiml = new TwiMLResponse();
String callSid = request.getParameter("CallSid");
//handle call specific data
switch(request.getParameter("CallStatus")){
case "no-answer": //construct twiML
case "ringing" ://...
}
//...
response.setContentType("application/xml");
response.getWriter().print(twiml.toXML());
}
See: IVR - Example

Errors when using Intent Detection with Dialogflow in JHIPSTER

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.

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

Categories