Getting Exception In onGuildMessageReceivedEvent - Discord JDA - java

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".

Related

How to solve error: cannot find symbol message.reply(...); Vertx point-to-point

I have two java classes communicating using a vert.x EventBus.
I have a Productor.java class:
package TP1;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonObject;
public class Productor extends AbstractVerticle
{
public void start() throws Exception
{
System.out.println("> Launching Productor...");
EventBus ebReady = vertx.eventBus();
//Send ready message
ebReady.send("canal-ready", "ready", messageReady -> {
//If Consumer received the ready message
if(messageReady.succeeded())
{
//Parse json response
JsonObject jsonObject = new JsonObject(messageReady.result().body().toString());
//Get answer value
int answerValue = Calcul.factorial(jsonObject.getInteger("param"));
String answer = Integer.toString(answerValue);
messageReady.reply(answer);//ERROR HERE
}
else
System.out.println("> No response!");
});
}
}
and a Consumer.java class:
package TP1;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonObject;
public class Consumer extends AbstractVerticle
{
public void start() throws Exception
{
System.out.println("> Launching Consumer...");
String jsonString = "{\"class\":\"Calcul\",\"method\":\"factoriel\",\"param\":5}";
JsonObject jsonObj = new JsonObject(jsonString);
EventBus ebReady = vertx.eventBus();
//Wait for ready message
ebReady.consumer("canal-ready", messageReady -> {
//Parse the ready message
String readyString = messageReady.body().toString();
//Make sure it's the ready message
if(readyString.equals("ready"))
{
//Send json back (messageReady.succeeded())
messageReady.reply(jsonObj, messageReadyReply -> {
System.out.println(messageReadyReply);
});
}
});
}
}
I can't build the Productor class but have no problem with the Consumer one.
What's wrong with the messageReady.reply(answer); part in the Productor.java class?
You were missing a call to result() (see here) before getting the message and executing methods on it. However, you're using methods that have been deprecated in the 3.8 version (example) and are missing from 4.0, so I would advise that you use the other signature instead.

Error when i extend AppCompatActivity in Android studio

Hello my code makes a simple http request and returns a json. My Code works fine but when i try to extend AppCompatActivity (because i want to show the json on device screen) it gaves me multiple errors my code is below
package com.vogella.java.library.okhttp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
public class TestMain extends AppCompatActivity {
OkHttpClient client = new OkHttpClient();
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
String doPostRequest(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public static void main(String[] args) throws IOException, JSONException {
String username = "test";
String password = "123";
TestMain example = new TestMain();
String json = "";
String postResponse = example.doPostRequest("http://86.145.89.53:8080/authentication_service-dev/authenticate?username=" + username + "&password=" + password, json);
int counter = postResponse.length();
if (counter == 14) {
System.out.println("Your username or password is invalid!!");
}
if (counter > 1000) {
System.out.println("HTTP Status 401 – Unauthhorized");
}
if (counter < 1000 && counter > 14) {
System.out.println("Welcome!!");
}
}}
the errors are :
Exception in thread "main" java.lang.RuntimeException: Stub!
at android.content.Context.<init>(Context.java:20)
at android.content.ContextWrapper.<init>(ContextWrapper.java:21)
at android.view.ContextThemeWrapper.<init>(ContextThemeWrapper.java:21)
at android.app.Activity.<init>(Activity.java:22)
at android.support.v4.app.SupportActivity.<init>(SupportActivity.java:31)
at android.support.v4.app.BaseFragmentActivityGingerbread.<init>(BaseFragmentActivityGingerbread.java:37)
at android.support.v4.app.BaseFragmentActivityHoneycomb.<init>(BaseFragmentActivityHoneycomb.java:29)
at android.support.v4.app.BaseFragmentActivityJB.<init>(BaseFragmentActivityJB.java:30)
at android.support.v4.app.FragmentActivity.<init>(FragmentActivity.java:79)
at android.support.v7.app.AppCompatActivity.<init>(AppCompatActivity.java:61)
at com.vogella.java.library.okhttp.TestMain.<init>(TestMain.java:18)
at com.vogella.java.library.okhttp.TestMain.main(TestMain.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
You don't use public static void main in Android dev. In the activity, you use onCreate:
#Override
public void onCreate(Bundle sis){
super.onCreate(sis);
//Move the contents of "public static void main" here
}
And delete public static void main when you have moved the code.
Android activities must have onCreate() method, when you extend any class with AppCompactAcitvity it must implement some methods
Change your code, remove main method, add onCreate() and do stuff there.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acremote);
}
Have a look at activities life cycle Link.

ETrade Java API issue - previewEquityOrder and previewOptionOrder throw an ETWSException

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.

Error while attempting to program page creation on google sites

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.

How to get tweet updates in XML format using java

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].

Categories

Resources