I have following code that outputs my and my users twitter time line messages in java.
I followed this tutorial to get the code below
http://namingexception.wordpress.com/2011/09/12/how-easy-to-make-your-own-twitter-client-using-java/
import java.io.IOException;
import java.util.List;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
public class SimpleTweet {
List<Status> statuses;
private final static String CONSUMER_KEY = "XXXXXX";
private final static String CONSUMER_KEY_SECRET = "XXXXXXX-123";
public void start() throws TwitterException, IOException {
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
String accessToken = getSavedAccessToken();
String accessTokenSecret = getSavedAccessTokenSecret();
AccessToken oathAccessToken = new AccessToken(accessToken,accessTokenSecret);
twitter.setOAuthAccessToken(oathAccessToken);
twitter.updateStatus("Hello world :).");
statuses = twitter.getHomeTimeline();
for (Status each : statuses) {
System.out.println("Sent by: #" + each.getUser().getScreenName()
+ " - " + each.getUser().getName() + "\n" + each.getText()
+ "\n");
}
}// start method ends here
private String getSavedAccessTokenSecret() {
return "vxcvvxcvxcvx";
}
private String getSavedAccessToken() {
return "eweweqweqweqwe";
}
public static void main(String[] args) throws Exception {
new SimpleTweet().start();
}
}
And I get following output
Sent by: #tweetrr - rr
Hello to all :).
Sent by: #addthis - AddThis
Just in time for #wordcampnyc, we have updated the AddThis WordPress plugin! Check it:
http://t.co/cgOgRwyl
Now I want the output to be in XML format. I would like to know if there are API's that does this work. Thanks in advance
You can use betwixt from apache (Bitwix example), using which you can convert either bean or hashmap to XML format easily. So, you create bean called UserStatusBean with fields like sentBy, status, message etc, populate the bean and output as XML using [BeanWriter][2].
Related
I am making a Discord JDA bot that can when a user sends the message: Prefix("$") + hastebin + their code, the bot will create a request to hastebin and paste their code, after that he will take the paste URL and print it to the console(I will send it as a message after I solve the problem).
This is my HastebinCommand class:
package events;
import main.Hastebin;
import Info.Info;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import java.lang.*;
public class HastebinCommand extends ListenerAdapter
{
Info info;
Hastebin hastebin;
#Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event)
{
String[] message = event.getMessage().getContentRaw().split(" ");
if (message[0].equalsIgnoreCase(info.prefix + "hastebin") || message[0].equalsIgnoreCase(info.prefix + "haste"))
{
if (message.length == 1)
{
//Send an error message
}
else
{
String code = "";
for (int i = 1; i < message.length; i++)
{
code = code + "" + message[i];
}
System.out.println(hastebin.paste(code));
}
}
}
}
This is my Hastebin request class:
package main;
import org.json.JSONObject;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Hastebin
{
public static String paste(String content) throws Exception{
final HttpClient client = HttpClient.newHttpClient();
final HttpRequest request = HttpRequest.newBuilder(URI.create("https://hastebin.com/documents"))
.POST(HttpRequest.BodyPublishers.ofString(content)).build();
final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
final String responseContent = response.body();
final JSONObject responseJson = new JSONObject(responseContent);
final String key = responseJson.getString("key");
return "https://hastebin.com/" + key;
}
}
My error:
C:\Users\user\Documents\Java\Java Projects\DiscordJDA\SpoonfeedingBot\src\events\HastebinCommand.java
Error:(32, 50) java: unreported exception java.lang.Exception; must be caught or declared to be thrown
I would really appreciate getting help after trying to solve my problem for so long.
Some function you're using is throwing an exception that must be dealt with (checked exception). Whenever you have a problem with an exception you should google the exception first. For example, in this case, you could paste "unreported exception java.lang.Exception; must be caught or declared to be thrown" in google search engine and you'd get your explanation.
Here's a tutorial on Exceptions: https://www.tutorialspoint.com/java/java_exceptions.htm
Also, your StackOverflow post should be about the error itself, in other words "unreported exception java.lang.Exception".
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;
}
}
I am new to the Authorize.net using Java SDK. I am trying to create the Customer Profile using CreateCustomerPaymentProfile API.
The following error is coming:
06/24/16 21:24:36,362: INFO [pool-1-thread-1] (net.authorize.util.LogHelper:24) - Use Proxy: 'false'
Failed to create customer payment profile: ERROR
~~~~ Details Are ~~~~
Message Code : E00040
Message Text : The record cannot be found.
The following API:
import java.util.List;
import net.authorize.Environment;
import net.authorize.api.contract.v1.CreateCustomerPaymentProfileRequest;
import net.authorize.api.contract.v1.CreateCustomerPaymentProfileResponse;
import net.authorize.api.contract.v1.CreditCardType;
import net.authorize.api.contract.v1.CustomerAddressType;
import net.authorize.api.contract.v1.CustomerPaymentProfileType;
import net.authorize.api.contract.v1.MerchantAuthenticationType;
import net.authorize.api.contract.v1.MessageTypeEnum;
import net.authorize.api.contract.v1.MessagesType.Message;
import net.authorize.api.contract.v1.PaymentType;
import net.authorize.api.controller.CreateCustomerPaymentProfileController;
import net.authorize.api.controller.base.ApiOperationBase;
public class CreateCustomerPaymentProfile {
public static final String apiLoginID= "72mNC7gyq";
public static final String transactionKey= "**";
private static final String customerProfileId = "36731856";
public static void main(String[] args) {
ApiOperationBase.setEnvironment(Environment.SANDBOX);
MerchantAuthenticationType merchantAuthenticationType = new MerchantAuthenticationType() ;
merchantAuthenticationType.setName(apiLoginID);
merchantAuthenticationType.setTransactionKey(transactionKey);
ApiOperationBase.setMerchantAuthentication(merchantAuthenticationType);
//private String getPaymentDetails(MerchantAuthenticationType merchantAuthentication, String customerprofileId, ValidationModeEnum validationMode) {
CreateCustomerPaymentProfileRequest apiRequest = new CreateCustomerPaymentProfileRequest();
apiRequest.setMerchantAuthentication(merchantAuthenticationType);
apiRequest.setCustomerProfileId(customerProfileId);
//customer address
CustomerAddressType customerAddress = new CustomerAddressType();
customerAddress.setFirstName("test");
customerAddress.setLastName("scenario");
customerAddress.setAddress("123 Main Street");
customerAddress.setCity("Bellevue");
customerAddress.setState("WA");
customerAddress.setZip("98004");
customerAddress.setCountry("USA");
customerAddress.setPhoneNumber("000-000-0000");
//credit card details
CreditCardType creditCard = new CreditCardType();
creditCard.setCardNumber("4111111111111111");
creditCard.setExpirationDate("2023-12");
creditCard.setCardCode("122");
CustomerPaymentProfileType profile = new CustomerPaymentProfileType();
profile.setBillTo(customerAddress);
PaymentType payment = new PaymentType();
payment.setCreditCard(creditCard);
profile.setPayment(payment);
apiRequest.setPaymentProfile(profile);
CreateCustomerPaymentProfileController controller = new CreateCustomerPaymentProfileController(apiRequest);
controller.execute();
CreateCustomerPaymentProfileResponse response = new CreateCustomerPaymentProfileResponse();
response = controller.getApiResponse();
if (response != null) {
if (response.getMessages().getResultCode() == MessageTypeEnum.OK) {
System.out.println(response.getCustomerPaymentProfileId());
System.out.println(response.getMessages().getMessage().get(0).getCode());
System.out.println(response.getMessages().getMessage().get(0).getText());
if(response.getValidationDirectResponse() != null)
System.out.println(response.getValidationDirectResponse());
}
else {
System.out.println("Failed to create customer payment profile: " + response.getMessages().getResultCode());
System.out.println("~~~~ Details Are ~~~~");
List<Message> messages = response.getMessages().getMessage();
for (Message message : messages) {
System.out.println("Message Code : "+message.getCode());
System.out.println("Message Text : "+message.getText());
}
}
}
}
}
You cannot create a customer payment profile without a customer profile.
In the code you have given String customerProfileId = "36731856";, you are getting error E00040 as the Customer profile with id 36731856 doesn't exist.
You are unclear on what you want.
If you want to create a customer profile, use CreateCustomerProfile API
Here, is the GitHub sample code for it : https://github.com/AuthorizeNet/sample-code-java/blob/master/src/main/java/net/authorize/sample/CustomerProfiles/CreateCustomerProfile.java
I am working with the ETrade Java API. I was able to use most of the functions but I am having trouble with the previewEquityOrder and the previewOptionOrder functions. Here are the error messages/ exceptions I get when I call these functions:
URL : https://etwssandbox.etrade.com/order/sandbox/rest/previewequityorder
? Java exception occurred:
com.etrade.etws.sdk.common.ETWSException
at com.etrade.etws.sdk.common.ETWSUtil.constructException(ETWSUtil.java:9)
at com.etrade.etws.sdk.core.ConnectionUtils.invoke(ConnectionUtils.java:90)
at com.etrade.etws.sdk.core.ConnectionUtils.invoke(ConnectionUtils.java:32)
at com.etrade.etws.sdk.client.OrderClient.previewEquityOrder(OrderClient.java:145)
For the previewOptionOrder:
URL : https://etwssandbox.etrade.com/order/sandbox/rest/previewoptionorder
? Java exception occurred:
com.etrade.etws.sdk.common.ETWSException
at com.etrade.etws.sdk.common.ETWSUtil.constructException(ETWSUtil.java:9)
at com.etrade.etws.sdk.core.ConnectionUtils.invoke(ConnectionUtils.java:90)
at com.etrade.etws.sdk.core.ConnectionUtils.invoke(ConnectionUtils.java:32)
at com.etrade.etws.sdk.client.OrderClient.previewOptionOrder(OrderClient.java:167)
The following Java code can reproduce the problem. You can compile this code on a Mac using the following command. On windows machine, replace the " : " with " ; " as the separator.
javac -classpath "./commons-codec-1.3.jar:./commons-httpclient-3.1.jar:./commons-httpclient-contrib-ssl-3.1.jar:./commons-lang-2.4-javadoc.jar:./commons-lang-2.4-sources.jar:./commons-lang-2.4.jar:./commons-logging-api.jar:./commons-logging.jar:./etws-accounts-sdk-1.0.jar:./etws-common-connections-1.0.jar:./etws-market-sdk-1.0.jar:./etws-oauth-sdk-1.0.jar:./etws-order-sdk-1.0.jar:./log4j-1.2.15.jar:./xstream-1.3.1.jar:" test.java
You can run the compiled class from command line using the following command:
java -classpath "./commons-codec-1.3.jar:./commons-httpclient-3.1.jar:./commons-httpclient-contrib-ssl-3.1.jar:./commons-lang-2.4-javadoc.jar:./commons-lang-2.4-sources.jar:./commons-lang-2.4.jar:./commons-logging-api.jar:./commons-logging.jar:./etws-accounts-sdk-1.0.jar:./etws-common-connections-1.0.jar:./etws-market-sdk-1.0.jar:./etws-oauth-sdk-1.0.jar:./etws-order-sdk-1.0.jar:./log4j-1.2.15.jar:./xstream-1.3.1.jar:" test <consumer_key> <consumer_secret>
You will need to pass in the ETrade consumer key and consumer secret as command line arguments to run this.
Notice that the authentication part works which is verified by getting the accounts list.
import com.etrade.etws.account.Account;
import com.etrade.etws.account.AccountListResponse;
import com.etrade.etws.oauth.sdk.client.IOAuthClient;
import com.etrade.etws.oauth.sdk.client.OAuthClientImpl;
import com.etrade.etws.oauth.sdk.common.Token;
import com.etrade.etws.sdk.client.ClientRequest;
import com.etrade.etws.sdk.client.Environment;
import com.etrade.etws.sdk.common.ETWSException;
import com.etrade.etws.sdk.client.AccountsClient;
import com.etrade.*;
import com.etrade.etws.order.PreviewEquityOrder;
import com.etrade.etws.order.PreviewEquityOrderResponse;
import com.etrade.etws.order.EquityOrderRequest;
import com.etrade.etws.order.EquityOrderTerm;
import com.etrade.etws.order.EquityOrderAction;
import com.etrade.etws.order.MarketSession;
import com.etrade.etws.order.EquityPriceType;
import com.etrade.etws.order.EquityOrderRoutingDestination;
import com.etrade.etws.sdk.client.OrderClient;
import java.math.BigInteger;
import java.awt.Desktop;
import java.net.URI;
import java.*;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class test
{
public static void main(String[] args) throws IOException, ETWSException
{
//Variables
if(args.length<2){
System.out.println("Class test needs two input argument as follows:");
System.out.println("test <consumer_key> <consumer_secret>");
return;
}
String oauth_consumer_key = args[0]; // Your consumer key
String oauth_consumer_secret = args[1]; // Your consumer secret
String oauth_request_token = null; // Request token
String oauth_request_token_secret = null; // Request token secret
String oauth_verify_code = null;
String oauth_access_token = null;
String oauth_access_token_secret = null;
ClientRequest request = new ClientRequest();
System.out.println("HERE");
IOAuthClient client = OAuthClientImpl.getInstance(); // Instantiate IOAUthClient
// Instantiate ClientRequest
request.setEnv(Environment.SANDBOX); // Use sandbox environment
request.setConsumerKey(oauth_consumer_key); //Set consumer key
request.setConsumerSecret(oauth_consumer_secret);
Token token = client.getRequestToken(request); // Get request-token object
oauth_request_token = token.getToken(); // Get token string
oauth_request_token_secret = token.getSecret(); // Get token secret
request.setToken(oauth_request_token);
request.setTokenSecret(oauth_request_token_secret);
String authorizeURL = null;
authorizeURL = client.getAuthorizeUrl(request);
System.out.println(authorizeURL);
System.out.println("Copy the URL into your browser. Get the verification code and type here");
oauth_verify_code = get_verification_code();
//oauth_verify_code = Verification(client,request);
request.setVerifierCode(oauth_verify_code);
token = client.getAccessToken(request);
oauth_access_token = token.getToken();
oauth_access_token_secret = token.getSecret();
request.setToken(oauth_access_token);
request.setTokenSecret(oauth_access_token_secret);
// Get Account List
AccountsClient account_client = new AccountsClient(request);
AccountListResponse response = account_client.getAccountList();
List<Account> alist = response.getResponse();
Iterator<Account> al = alist.iterator();
while (al.hasNext()) {
Account a = al.next();
System.out.println("===================");
System.out.println("Account: " + a.getAccountId());
System.out.println("===================");
}
// Preview Equity Order
OrderClient order_client = new OrderClient(request);
PreviewEquityOrder orderRequest = new PreviewEquityOrder();
EquityOrderRequest eor = new EquityOrderRequest();
eor.setAccountId("83405188"); // sample values
eor.setSymbol("AAPL");
eor.setAllOrNone("FALSE");
eor.setClientOrderId("asdf1234");
eor.setOrderTerm(EquityOrderTerm.GOOD_FOR_DAY);
eor.setOrderAction(EquityOrderAction.BUY);
eor.setMarketSession(MarketSession.REGULAR);
eor.setPriceType(EquityPriceType.MARKET);
eor.setQuantity(new BigInteger("100"));
eor.setRoutingDestination(EquityOrderRoutingDestination.AUTO.value());
eor.setReserveOrder("TRUE");
orderRequest.setEquityOrderRequest(eor);
PreviewEquityOrderResponse order_response = order_client.previewEquityOrder(orderRequest);
}
public static String get_verification_code() {
try{
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
String input;
input=br.readLine();
return input;
}catch(IOException io){
io.printStackTrace();
return "";
}
}
}
I posted this on the ETrade community forum but that forum is not very active. I also sent a request to ETrade and haven't gotten a reply yet. If I get a solution from them, I will come back and post it here. In the mean time any help is greatly appreciated.
After debugging my above code, I figured out that the problem is that I was setting the ReserveOrder to TRUE but I wasn't providing the required ReserveOrderQuantity. I got the above code from the Java code snippet in the ETrade Developer Platform Guide. This is clearly a bug in their documentation.
I'm trying to programmatic-ally add pages to my Google Site using Java.
This is the code:
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gdata.client.sites.*;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.XhtmlTextConstruct;
import com.google.gdata.data.sites.*;
import com.google.gdata.util.ServiceException;
import com.google.gdata.util.XmlBlob;
public class PageCreate {
public static void main(String args[]) throws Exception {
WebPageEntry createdEntry = createWebPage("New Webpage Title", "<b>HTML content</b>");
System.out.println("Created! View at " + createdEntry.getHtmlLink().getHref());
}
private static void setContentBlob(BaseContentEntry<?> entry, String pageContent) {
XmlBlob xml = new XmlBlob();
xml.setBlob(pageContent);
entry.setContent(new XhtmlTextConstruct());
}
public static WebPageEntry createWebPage(String title, String content)
throws ServiceException, IOException, MalformedURLException {
SitesService client = new SitesService("*****-pagecreate-v1");
client.setUserCredentials("***********", "*********");
client.site = "intratrial2"; -> ***SYNTAX ERROR REPORTED***
//ContentFeed contentFeed = client.getFeed(new URL(buildContentFeedUrl()), ContentFeed.class);
WebPageEntry entry = new WebPageEntry();
entry.setTitle(new PlainTextConstruct(title));
setContentBlob(entry, content); // Entry's HTML content
return client.insert(new URL(buildContentFeedUrl()), entry);
}
public static String buildContentFeedUrl() {
String domain = "*****"; // OR if the Site is hosted on Google Apps, your domain (e.g. example.com)
String siteName = "intratrial2";
return "https://sites.google.com/feeds/content/" + domain + "/" + siteName + "/";
}
}
If i comment out the line with syntax error i get the following error report on running:
Exception in thread "main" com.google.gdata.util.ServiceException: Internal Server Error
Internal Error
I'm not sure what I'm doing wrong here and I'd really appreciate some help. Thanks.