sending mailchimp campaign with maleorang v3.0 java api - java

I have gotten so far that I can create a new campaign in my campaign list in mailchimp using a java class, however, I am not getting there to send it, see code, does anyone have suggestions?
it executes the creation of the campaign (and i see it in mailchimp), and I receive back the campaignInfo object, but from the point to send this campaign, I cant figure it out
package mailingapp2;
import com.ecwid.maleorang.MailchimpClient;
import com.ecwid.maleorang.method.v3_0.campaigns.CampaignActionMethod;
import com.ecwid.maleorang.method.v3_0.campaigns.CampaignInfo;
import com.ecwid.maleorang.method.v3_0.campaigns.CampaignInfo.SettingsInfo;
import static com.ecwid.maleorang.method.v3_0.campaigns.CampaignInfo.Type.PLAINTEXT;
import com.ecwid.maleorang.method.v3_0.campaigns.EditCampaignMethod;
public class SendMailchimpCampaign {
public void SendCampaign() throws Exception {
String apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
String listId = "d069f8c902";
String Email ="test#test.be";
String firstName = "test";
String lastName = "test";
MailchimpClient client = new MailchimpClient(apiKey);
try{
EditCampaignMethod.Create method = new EditCampaignMethod.Create();
method.type = PLAINTEXT;
method.settings = new SettingsInfo();
method.settings.mapping.put("title", "test2");
method.settings.mapping.put("subject_line", "test");
method.settings.mapping.put("from_name", "test");
method.settings.mapping.put("reply_to", "info#test.be");
CampaignInfo campaign = client.execute(method); //until here it works, //it executes, and I receive back the campaignInfo object, but from here I can't //figure it out how to move on to send this campaign.
CampaignActionMethod.Send send = new CampaignActionMethod.Send(listId);
System.out.println("info" + campaign);
}catch (Exception e) {
System.err.println("Caught IOException: " + e.getMessage());
}
}
}

It seems you should add
client.execute(send);
right after
CampaignActionMethod.Send send = new CampaignActionMethod.Send(listId);

Related

AWS Email Template usage using java (bulk email)

Can some one give me a direction how can I implement this aws email template tutorial by a java code? Through java code I want to set this AWS Email Template and through java only I want to set the parameter values to the template and through java only I want to send the email.
I cant find any tutorial or direction from which I can translate above requests in java code.
The "code" in your link is actually just some JSON templates for sending and formatting email, and a few calls to an AWS command line tool. If you need to make AWS send email calls from a Java process then you need to take a look at:
The SES API
The Javadoc for the Java client lib
I am able to code it successfully. Pasting the example code here.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
import com.amazonaws.services.simpleemail.model.BulkEmailDestination;
import com.amazonaws.services.simpleemail.model.BulkEmailDestinationStatus;
import com.amazonaws.services.simpleemail.model.Destination;
import com.amazonaws.services.simpleemail.model.SendBulkTemplatedEmailRequest;
import com.amazonaws.services.simpleemail.model.SendBulkTemplatedEmailResult;
public class AmazonSESSample2 {
public static void main(String[] args) throws IOException {
String accessKeyId = "accessKeyId";
String secretKeyId = "secretKeyId";
String region = "us-east-1";
List<BulkEmailDestination> listBulkEmailDestination = null;
SendBulkTemplatedEmailRequest sendBulkTemplatedEmailRequest = null;
try {
AmazonSimpleEmailService client = getAmazonSESClient(accessKeyId, secretKeyId, region);
listBulkEmailDestination = new ArrayList<>();
for(String email : getRecievers()) {
String replacementData="{"
+ "\"FULL_NAME\":\"AAA BBB\","
+ "\"USERNAME\":\""+email+"\","
+ "}";
BulkEmailDestination bulkEmailDestination = new BulkEmailDestination();
bulkEmailDestination.setDestination(new Destination(Arrays.asList(email)));
bulkEmailDestination.setReplacementTemplateData(replacementData);
listBulkEmailDestination.add(bulkEmailDestination);
}
sendBulkTemplatedEmailRequest = new SendBulkTemplatedEmailRequest();
sendBulkTemplatedEmailRequest.setSource("noreply#mydomain.com");
sendBulkTemplatedEmailRequest.setTemplate("welcome-email-en_GB-v1");
sendBulkTemplatedEmailRequest.setDefaultTemplateData("{\"FULL_NAME\":\"friend\", \"USERNAME\":\"unknown\"}");
sendBulkTemplatedEmailRequest.setDestinations(listBulkEmailDestination);
SendBulkTemplatedEmailResult res = client.sendBulkTemplatedEmail(sendBulkTemplatedEmailRequest);
System.out.println("======================================");
System.out.println(res.getSdkResponseMetadata());
System.out.println("======================================");
for(BulkEmailDestinationStatus status : res.getStatus()) {
System.out.println(status.getStatus());
System.out.println(status.getError());
System.out.println(status.getMessageId());
}
} catch (Exception ex) {
System.out.println("The email was not sent. Error message: " + ex.getMessage());
ex.printStackTrace();
}
}
public static List<String> getRecievers() {
ArrayList<String> list = new ArrayList<>();
list.add("aaa+1#gmail.com");
list.add("aaa+2#gmail.com");
list.add("aaa+3#gmail.com");
list.add("aaa+4#gmail.com");
return list;
}
public static AmazonSimpleEmailService getAmazonSESClient(String accessKeyId, String secretKeyId, String region) {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKeyId, secretKeyId);
AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.withRegion(region)
.build();
return client;
}
}

How to create the version and get the details of any version of specific project using JIRA REST CLIENT JAVA in groovy?

I am trying to create the version in JIRA for specific project.Below is my code.I am able to connect the JIRA successfully through JIRA REST CLIENT JAVA java libraries but now want to achieve the get the information of any version,createversion few more actions.
import com.atlassian.jira.rest.client.api.JiraRestClient
import com.atlassian.jira.rest.client.api.JiraRestClientFactory
//import com.atlassian.jira.rest.client.api.domain.User
import com.atlassian.jira.rest.client.api.domain.Version
//import com.atlassian.jira.rest.client.api.domain.input.VersionInput
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory
import com.atlassian.util.concurrent.Promise
class Jira {
private static final String JIRA_URL = "https://jira.test.com"
private static final String JIRA_ADMIN_USERNAME = "ABCDE"
private static final String JIRA_ADMIN_PASSWORD = "xxxxxx"
static void main(String[] args) throws Exception
{
// Construct the JRJC client
System.out.println(String.format("Logging in to %s with username '%s' and password '%s'", JIRA_URL, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD))
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory()
URI uri = new URI(JIRA_URL)
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD)
// client.withCloseable {
// it.projectClient.getProject("ABCD").claim().versions.each { println it }
// }
// Invoke the JRJC Client
//Promise<User> promise = client.getUserClient().getUser(JIRA_ADMIN_USERNAME)
//User user = promise.claim()
Promise<Version> promise = client.getVersionRestClient().getVersion(1234)
//Version version = promise.claim()
// Print the result
System.out.println(String.format("Your user's email address is: %s\r\n", user.getEmailAddress()))
}
}
I am able to do some task like to get the email address of any userid.I am trying this in groovy
package com.temp.jira
import com.atlassian.jira.rest.client.api.JiraRestClient
import com.atlassian.jira.rest.client.api.JiraRestClientFactory
import com.atlassian.jira.rest.client.api.domain.BasicProject
import com.atlassian.jira.rest.client.api.domain.Issue
import com.atlassian.jira.rest.client.api.domain.SearchResult
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory
import com.atlassian.util.concurrent.Promise
/**
* Created on 7/21/2017.
*/
class Test {
private static final String JIRA_URL = "https://jira.test.com"
private static final String JIRA_ADMIN_USERNAME = "ABCDEF"
private static final String JIRA_ADMIN_PASSWORD = "*****"
private static final String JIRA_PROJECT = "ABCD"
static void main(String[] args) throws Exception
{
// Construct the JRJC client
System.out.println(String.format("Logging in to %s with username '%s' and password '%s'", JIRA_URL, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD))
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory()
URI uri = new URI(JIRA_URL)
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD)
for (BasicProject project : client.getProjectClient().getProject(JIRA_PROJECT).claim()) {
System.out.println(project.getKey() + ": " + project.getName())
}
Promise<SearchResult> searchJqlPromise = client.getSearchClient().searchJql("project = $JIRA_PROJECT AND status in (Closed, Completed, Resolved) ORDER BY assignee, resolutiondate");
for (Issue issue : searchJqlPromise.claim().getIssues()) {
System.out.println(issue.getId())
}
// Done
System.out.println("Example complete. Now exiting.")
System.exit(0)
}
}
Stick to the jira rest client api, since you have a typed access provided from the creator o fJira.
Excerpt from my working Groovy code:
/**
* Retrieves the latest unreleased version for the given project.
* #param projectId Given project
* #return latest unreleased version
*/
private Version getVersion(String projectId)
{
def project = restClient.projectClient.getProject(projectId).claim()
def unreleasedVersions = project
.getVersions()
.findAll { version ->
version.released == false
}
if (unreleasedVersions.size() != 1) {
throw new RuntimeException('There are zero or more unreleased versions.')
}
unreleasedVersions.get(0)
}
/**
* Creates a new, undeployed version for the given project.
* #param projectId Given project
*/
private void createVersion(String projectId)
{
def versionInputBuilder = new VersionInputBuilder(projectId)
versionInputBuilder.released = false
versionInputBuilder.name = incrementVersion(capturedVersion.name)
versionInputBuilder.description = 'Bugfixing'
versionInputBuilder.startDate = DateTime.now()
def promise = restClient.versionRestClient.createVersion(versionInputBuilder.build())
trackCompletion(promise)
}
What I don't have in my code is get a certain version, but your commented code should work when you change the data type of the version to string.
I created the script in below way and able to create,update and delete the version
import com.atlassian.jira.rest.client.api.JiraRestClient
import com.atlassian.jira.rest.client.api.VersionRestClient
import com.atlassian.jira.rest.client.api.domain.Version
import com.atlassian.jira.rest.client.api.domain.input.VersionInput
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory
import com.atlassian.util.concurrent.Promise
import org.codehaus.jettison.json.JSONException
import org.joda.time.DateTime
import java.util.concurrent.ExecutionException
class VersionClient {
private static final String JIRA_URL = "https://jira.test.com"
private static final String JIRA_ADMIN_USERNAME = "ABCDEF"
private static final String JIRA_ADMIN_PASSWORD = "******"
private static final String JIRA_PROJECT = "TEST"
static void main(String[] args)
throws URISyntaxException, InterruptedException, ExecutionException, JSONException {
// Initialize REST Client
final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory()
final URI uri = new URI("$JIRA_URL")
final JiraRestClient jiraRestClient = factory.createWithBasicHttpAuthentication(uri, "$JIRA_ADMIN_USERNAME", "$JIRA_ADMIN_PASSWORD")
// Get specific client instances
VersionRestClient versionClient = jiraRestClient.getVersionRestClient()
// Create Version
VersionInput versionInput = new VersionInput("$JIRA_PROJECT", "TEST 1.2.8", "Test Version", new DateTime(), false, false)
Promise<Version> version = versionClient.createVersion(versionInput)
Version versionObj = version.get()
System.out.println("Created Version:" + versionObj.getName())
// Invoke the JRJC Client
Promise<Version> promise = versionClient.getVersion(versionObj.getSelf())
Version versionid = promise.claim()
// Print the result
System.out.println(String.format("Version id is: %s\r\n", versionid.getId() + " and URI:" + versionid.getSelf()))
// Release Version using Update
versionClient.updateVersion(versionid.getSelf(),new VersionInput("$JIRA_PROJECT", "TEST 1.2.8", "Test Version", new DateTime(), false, true))
// Delete the Version
versionClient.removeVersion(versionid.getSelf(), null, null).claim()
System.out.println("Deleted Version")
}
}

Error in inserting a string parameter to a cypher query in a java code

I want to insert a string parameter to a cypher query in Java. Below is the code I used and I have a person node named 'piyumi' and I want to make relationship with an activity node. The name of the activity node is 'walking'. When I execute the code I get http status code 400. Can anyone help me to modify the cypher query so that I can insert the string variable s without error.
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import javax.ws.rs.core.MediaType;
public class NeoAPIClass {
private final String baseUri = "http://localhost:7474/db/data/cypher";
private final String user = "neo4j";
private final String password = "12345";
public static void main(String args[]) throws JSONException {
NeoAPIClass n=new NeoAPIClass();
n.runQuery();
}
void runQuery() throws JSONException {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter(user, password));
WebResource cypherResource = client.resource(baseUri);
String s="walking";
JSONObject obj = new JSONObject();
obj.put("query", "Match(piyumi : Person{name:\"Piyumi\"}) create (piyumi)-[:doing{timestamp:4789}]->(n:activity) WHERE n.name=s");
String st = obj.toString();
ClientResponse cypherResponse = cypherResource.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON_TYPE).entity(st).post(ClientResponse.class);
System.out.println("Output from Server .... "+ cypherResponse.getStatus());
}
}
It is impossible to combine the create and where. You need first match person and activity, and then create a relationship.
And also recommend to simplify the transfer parameters in a separate part of the request (https://neo4j.com/docs/rest-docs/current/#rest-api-use-parameters):
JSONObject request = new JSONObject();
JSONObject params = new JSONObject();
String query = "MATCH (P:Person { name:{personName} }) \n";
query = query + "MATCH (A:activity { name:{activityName} }) \n";
query = query + "CREATE (P)-[rel:doing { timestamp:{activityTimestamp} }]->(A) \n";
query = query + "RETURN P, A, rel";
request.put("query", query);
params.put("personName", "Piyumi");
params.put("activityName", "walking");
params.put("activityTimestamp", 4789);
request.put("params", params);
ClientResponse cypherResponse = cypherResource.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(request.toString())
.post(ClientResponse.class);
System.out.println("Response: " + cypherResponse.getEntity(String.class));
Your problem is that the cypher server can't see the variable s from your Java code. You need to pass a cypher query that has the String itself, rather than the name of a Java variable.
You could change the line with obj.put to this.
obj.put("query", "Match(piyumi : Person{name:\"Piyumi\"}) create (piyumi)-[:doing{timestamp:4789}]->(n:activity) WHERE n.name=\"" + s + "\"");
Problem occurs when you try to retrieve existing node.
So, go to http://localhost:7474/browser/ and execute below query,
MATCH (n:activity)
WHERE n.name="walking"
CREATE (piyumi:Person{name:"Piyumi"}) - [r1:doing{timestamp:4789}]-> (n)
If it works fine, then retrieve it.
MATCH (piyumi:Person)-[r1:doing]->(n:activity)
RETURN r1
So your query code should looks like this,
"MATCH (n:activity)\nWHERE n.name=\"walking\"\nCREATE (piyumi:Person{name:\"Piyumi\"}) - [r1:doing{timestamp:4789}]-> (n)"

Sonar-ws-client returning 401 error even though I can perform a search in the UI

I have the following source code:
package com.sample.sonar.report;
import org.sonar.wsclient.Host;
import org.sonar.wsclient.Sonar;
import org.sonar.wsclient.SonarClient;
import org.sonar.wsclient.connectors.HttpClient4Connector;
import org.sonar.wsclient.services.*;
import org.sonar.wsclient.issue.*;
import java.util.List;
public class App {
public static void main(String args[]) {
try {
String url = "http://sample.url.com:9000";
String login = "userid";
String password = "password";
SonarClient client = SonarClient.create(url);
client.builder().login(login);
client.builder().password(password);
IssueQuery query = IssueQuery.create();
query.rules("S1081");
query.languages("c");
IssueClient issueClient = client.issueClient();
System.out.println("About to Run query\n");
Issues issues = issueClient.find(query);
System.out.println("Ran query\n");
List<Issue> issueList = issues.list();
for (int i = 0; i < issueList.size(); i++) {
System.out.println(issueList.get(i).projectKey() + " " +
issueList.get(i).componentKey() + " " +
issueList.get(i).line() + " " +
issueList.get(i).ruleKey() + " " +
issueList.get(i).severity() + " " +
issueList.get(i).message());
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
Although I can log into Sonar and search the results I am getting the following runtime error
org.sonar.wsclient.base.HttpException: Error 401 on http://sample.url.com:9000/api/issues/search?languages=c&rules=S1081
I believe this is a 401 error which maps to Unauthorized. Am I missing some sort of authentication beyond what I am doing? Thanks in advance.
SonarClient#builder() is a static method which returns a new builder instance each time it is called. So basically, when you write:
SonarClient client = SonarClient.create(url);
client.builder().login(login);
client.builder().password(password);
your are setting the login on one Builder object, setting the password on another and doing nothing from any of them.
The object you are using is the SonarClient create by the method SonarClient#create(String url) which, indeed, has no login nor password, hence the 401 HTTP error.
What you should write is:
SonarClient client = SonarClient.builder()
.url(url)
.login(login)
.password(password)
.build();

Jacob Fatal Error

I am trying to build a Java Drag and Drop that works with Outlook emails. I've been using Jacob because of an inability to transfer data from Outlook to Java using standard AWT Event stuff. That said, all of the solutions I've pulled from here or other sites have been causing a fatal crash in Java. Here's the code:
import java.awt.dnd.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.*;
import java.util.List;
import sun.awt.datatransfer.*;
import com.jacob.com.*;
import com.jacob.activeX.*;
public class D2 extends JFrame
{
private static final String DIR = "FILES";
private static void saveSelectedOutlookMails(String directory) {
Dispatch xl = new Dispatch("Outlook.Application");
//Dispatch selection = Dispatch.get(xl, "Selection").toDispatch();
System.out.println(xl);
System.out.println(xl==null);
//PROGRAM CRASHES AFTER THIS LINE
Dispatch explorer = Dispatch.get(xl,"ActiveExplorer").toDispatch();
System.out.println("explorer");
Object selection = Dispatch.get(explorer, "Selection").toDispatch();
Variant count = Dispatch.get(selection, "Count");
for (int mailIndex = 1; mailIndex <= count.toInt(); mailIndex++ ) {
Object mailItem = Dispatch.call(selection, "Item", new Variant(mailIndex)).toDispatch();
Variant senderName = Dispatch.get(mailItem, "SenderName");
Variant subject = Dispatch.get(mailItem, "Subject");
Variant body = Dispatch.get(mailItem, "Body");
String emailFileName = subject.toString() +".txt";
String fullPath = directory + "/" + emailFileName;
try {
File email = new File(fullPath);
PrintWriter writer = new PrintWriter( new FileWriter(email) );
writer.println("From: "+ senderName );
writer.println("Subject: "+ subject);
writer.println("");
writer.print( body );
writer.close();
}
catch (IOException e) {
System.out.println(e.getMessage());
//logger.error("IOException writing e-mail with subject: '"+ subject +"'", e);
continue;
}
Object attachments = Dispatch.get(mailItem, "Attachments").toDispatch();
Variant attachmentCount = Dispatch.get(attachments, "Count");
if ( attachmentCount.toInt() > 0 ) {
for( int attachmentIndex = 1; attachmentIndex<=attachmentCount.toInt(); attachmentIndex++ ) {
Object attachment = Dispatch.call(attachments, "Item", new Variant(attachmentIndex)).toDispatch();
Variant fileNameVariant = Dispatch.get(attachment, "FileName");
String fileName = fileNameVariant.toString();
Variant saveResult = Dispatch.call(attachment, "SaveAsFile", directory, "/", fileName);
}
}
}
}
public D2() throws Exception
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(0,0,300,300);
this.setVisible(true);
DropTarget dropTarget=new DropTarget();
dropTarget.setComponent(this);
dropTarget.addDropTargetListener(new DropTargetAdapter()
{
public void drop(DropTargetDropEvent dtde){
saveSelectedOutlookMails(DIR);
}
});
}
public static void main(String[] args)
{
try{
new D2();
}catch(Exception e){
e.printStackTrace();
}
}
}
Ok, firstly, you are creating Outlook.Application in a way I've never seen before - I've only ever seen the Active X Component way:
e.g.
ActiveXComponent xl = new ActiveXComponent("Outlook.Application");
Dispatch explorer = Dispatch.get(xl,"ActiveExplorer").toDispatch();
Dispatch selection = Dispatch.get(explorer, "Selection").toDispatch();
Variant count = Dispatch.get(selection, "Count");
// loop over selected mail items.
for (int mailIndex = 1; mailIndex <= count.getInt(); mailIndex++ ) {
Dispatch mailItem = Dispatch.call(selection, "Item", new Variant(mailIndex)).toDispatch();
Variant subject = Dispatch.get(mailItem, "Subject");
// .... and so on
}
Secondly, your code is not saving the mail, its pulling out all the fields and attachments and trying to recreate the mail, which seems inaccurate at best and will only be an approximation of what the message was.
Why don't you just use the COM objects to SaveAs the whole .msg file to disk? Then if you need to access it again you can use something like JDIC to launch Outlook and pop up the message in its original glory, including all attachments?
My guess is that you are trying to get PROPERTY with name "ActiveExplorer", but it is a method! Here is documentation of that particuliar method https://msdn.microsoft.com/en-us/library/office/ff870017.aspx . Try to use .call() Jacob method to invoke METHODS on MS objects.

Categories

Resources