How to do remote JNLP error reporting? - java

I have a JNLP downloader application deployed on remote user machines that downloads files.
I need to get some error feedback mailed to me. Not so much exceptions, just things getting stuck, or stalled or in infinite loops.
Currently I have a basic handler:
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class javaerrorlog {
private static Logger l = Logger.getLogger("");
public static void main(String args[]) throws Exception{
FileHandler handler = new FileHandler("log.txt");
l.addHandler(handler);
l.setLevel(Level.ALL);
l.info("Error logs");
try {
} catch (Error ex) {
l.log(Level.INFO, "", ex);
}
l.fine("");
}
}
Also, should I prompt for the client's permission to send error reporting data?

If you just need notifications you could use something like SMTPHandler. If you need it more fancy you could use JMS with an MDB.

Related

I'm using JDA 4.4.0_352 and my Discord Bot is unable to send message in the channel

Here's my code in Bot.java.
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import javax.security.auth.login.LoginException;
public class Bot {
private JDA api;
public Bot() throws LoginException, InterruptedException {
api = JDABuilder.createDefault("token")
.addEventListeners(new search()).build()
.awaitReady();
}
public static void main(String[] args) throws LoginException, InterruptedException {
new Bot();
}
}
token is replaced with an actual token in my code :)
And here's my code in search.java
package core;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
public class search extends ListenerAdapter {
#Override
public void onMessageReceived(MessageReceivedEvent event) {
String msg = event.getMessage().getContentRaw();
if (event.getAuthor().isBot())
return;
if (msg.equalsIgnoreCase("!search")) {
event.getPrivateChannel()
.sendMessage("Please enter the course name: ").queue();
}
}
}
I'm not sure why my bot doesn't send the appropriate message when I put search to my discord channel (tried both private and guild).
Please let me know if you know where the problem is, thank you!
The Bot's intents/permissions need to be set in the createDefault method (and possibly inside the discord developer portal). For direct messages it'd be:
JDABuilder.createDefault("token", GatewayIntent.DIRECT_MESSAGES)
To handle messages in your guild, I think it'd require Message Content Intent enabled in the discord developer portal; and it'd be:
JDABuilder.createDefault("token", GatewayIntent.GUILD_MESSAGES)
The GatewayIntent parameter inside the createDefault method uses varargs, so you can tack on any number of intents:
JDABuilder.createDefault("token", GatewayIntent.DIRECT_MESSAGES, GatewayIntent.GUILD_MESSAGES)
Also, event.getPrivateChannel() will throw an IllegalStateException in the event that the message is not from a private channel; I'd recommend first checking if event.getChannelType() == ChannelType.PRIVATE, or a try/catch.

Intelij IDEA 2022.1 Cannot debug Runtime.getRuntime().addShutdownHook();

I've tried to debug Runtime.getRuntime().addShutdownHook(unfortunateHook); in sample tapestry application created with Maven quickstart, but it seems that it doesn't work - Debugger doesn't stop at trap set to line set at LOGGER.debug("In the main hook!!!");
Example code:
package org.example.spring;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication
public class App extends SpringBootServletInitializer {
private static final Logger LOGGER= LoggerFactory.getLogger(App.class);
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(AppConfiguration.class);
}
public static void main(String[] args) throws Exception {
Thread unfortunateHook = new Thread(() -> {
LOGGER.debug("In the main hook!!!");
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
});
Runtime.getRuntime().addShutdownHook(unfortunateHook);
LOGGER.debug("Simple log statement with inputs {}, {} and {}", 1,2,3);
SpringApplication application = new SpringApplication(App.class);
SpringApplication.run(App.class, args);
}
}
Is it possible to debug code inside shutdown hook thread? I'm using InteliJ Idea 2022.01. Killing application with standard Intelij Idea way (red square).
Ok, after some more digging I have found this: https://youtrack.jetbrains.com/issue/IDEA-170313/Breakpoints-not-working-after-stop-signal and many more simmilar threads.
In short, Idea is disconnecting debugger in a moment that you click red square and sends signal to app to kill itself. Because of these, traps are not working any more.
Workaround to this is to send kill signal from external source. In Linux it's pretty easy but in windows (which is I'm using) you should:
Put a break point any place in your code that will be executed
When code stops at your trap, you go to "evaulate expression" (alt+f8 or from degug acctions) and write System.exit(0)
You breakpoint may need to be set up as a thread one - to do that, click right button on it and switch to "Thread"
Then breakpoint should work.

How to send OSC to QLab with Java?

I am trying to send OSC (Open Sound Control) to Figure 53's QLab. So far I have come up with this code.
import com.illposed.osc.transport.udp.OSCPortOut;
import com.illposed.osc.OSCMessage;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class controller {
public static void main(String[] args) throws UnknownHostException, IOException {
OSCPortOut sender = new OSCPortOut(InetAddress.getByName("10.67.192.113"), 53000);
OSCMessage msg = new OSCMessage("/cue/1");
try {
sender.send(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have successfully added Illposed's JavaOSC library to my code, but then it says I need SLF4J, and when I try to add slf4j-api-1.7.30.jar it says Failed to load class "org.slf4j.impl.StaticLoggerBinder". When I try to run the above code with both libraries SLF4J and JavaOSC.
You will need to use Maven to handle the dependencies JavaOSC needs.
Here's a good tutorial for Eclipse. Just use a simple project, you do not need to do archetype selection.
Then add the following at the end of your new projects pom.xml file, before
</project>
but after everything else.
`<dependency>`
<groupId>com.illposed.osc</groupId>
<artifactId>javaosc-core</artifactId>
<version>0.7</version>
</dependency>

Adding REST route to an existing Jetty endpoint in Camel at runtime

I have been inventing a way how to work around the problem of adding consumers to a jetty endpoint (it does not allow multiple consumers). The way we do it in our company is to build our own router and a broadcasting endpoint which consumes from jetty and routes requests to underlying "subscriptions". Only one of them will eventually process the request. It kind of works but it's not completely ok, since recently when updating to latest Camel we have found our custom built component to leak memory and in general I consider using built-in functionality over custom hacks.
I started investigating the Camel REST API and found it very nice and pretty much replacing our home-grown component apart from one thing - you cannot re-configure it at runtime - you have to stop the context basically for this to work. Below I include my unit test with a happy path and the path that fails. Frankly I think is a bug, but if there is a legitimate way to achieve what I want, I'd like to hear sound advice:
package com.anydoby.camel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
/**
* Test tries to add/remove routes at runtime.
*/
public class RoutesTest {
private DefaultCamelContext ctx;
#Before
public void pre() throws Exception {
ctx = new DefaultCamelContext();
new RouteBuilder(ctx) {
#Override
public void configure() throws Exception {
restConfiguration("jetty").host("localhost").port(8080);
rest("/")
.get("/issues/{isin}").route().id("issues")
.process(e -> e.getOut().setBody("Here's your issue " + e.getIn().getHeader("isin"))).endRest()
.get("/listings").route().id("listings").process(e -> e.getOut().setBody("some listings"));
}
}.addRoutesToCamelContext(ctx);
ctx.start();
}
#Test
public void test() throws IOException {
{
InputStream stream = new URL("http://localhost:8080/issues/35").openStream();
assertEquals("Here's your issue 35", IOUtils.toString(stream));
}
{
InputStream stream = new URL("http://localhost:8080/listings").openStream();
assertEquals("some listings", IOUtils.toString(stream));
}
}
#Test
public void disableRoute() throws Exception {
ctx.stopRoute("issues");
ctx.removeRoute("issues");
try (InputStream stream = new URL("http://localhost:8080/issues/35").openStream()) {
fail();
} catch (Exception e) {
}
new RouteBuilder(ctx) {
#Override
public void configure() throws Exception {
rest().get("/issues/{isin}/{sedol}").route().id("issues")
.process(e -> e.getOut()
.setBody("Here's your issue " + e.getIn().getHeader("isin") + ":" + e.getIn().getHeader("sedol")))
.endRest();
}
}.addRoutesToCamelContext(ctx);
{
InputStream stream = new URL("http://localhost:8080/issues/35/65").openStream();
assertEquals("Here's your issue 35:65", IOUtils.toString(stream));
}
}
}
The disableRoute() test fails since I cannot add another consumer to an existing endpoint.
So my question is - "is there a way to add a new URL mapping to a restful camel-jetty endpoint"? If you do it during first configuration it works fine, but when later you want to reconfigure one of the routes the error is:
org.apache.camel.FailedToStartRouteException: Failed to start route because of Multiple consumers for the same endpoint is not allowed: jetty:http://localhost:8080/issues/%7Bisin%7D/%7Bsedol%7D?httpMethodRestrict=GET

Start, stop, restart Glassfish Server from java desktop application

I am developing a project that needs booth a web and desktop application. The web app receives the tasks from my clients and stores them (in database). The desktop application gets the tasks (from database) and execute them one by one. In my web application i am using java servlets, web services ...
Sometimes my glassfish server (v 3.1.2) freezes or he becomes blocked and needs to be restarted so he can continue work properly. I can detect this kind of error by monitoring him and find out when he freezes (by calling simple web service method that throws exception, simple http request that also throws exception etc).
I want my desktop application get the Glassfish server status and if
"Everything is ok" then "Do nothing"
"Server is down" then "Start Glassfish Server"
"I detect an error" then "Restart Glassfish Server"
"Application quit" then "Shutdown Glassfish Server"
Does anyone had this problem and has any solution. I am tired of manually restarting the glassfish server.
I run Glassfish 3.1.2 in production for months at a time without issue. I would suspect the freezing your are seeing is a problem with the application you have deployed to it.
I think you would be best served spending time investigating and remediating your hanging issue. Have you tried taking a thread dump of the Glassfish java process when this happens?
I found my own solution that i want to share.
When i detect that something is wrong with my Glassfish server, i restart it. This solutions only works on Linux (i will edit this answer if i find simular for windows users). Also u might have to add this line for your user in "/etc/sudoers" under root user, adrian is my username.
adrian ALL=(ALL:ALL) ALL
GlassFish Class: (U will need to change glassfishPath and domainName with yours)
package es.web.glassfish;
import es.os.linux.Konsole;
import java.io.IOException;
/**
*
* #author adrian
*/
public class Glassfish {
private final static String glassfishPath = "/home/adrian/glassfish-4.0/";
private final static String domainName = "domain1";
public static String startGlassfishServer() throws IOException, InterruptedException {
String command = glassfishPath + "bin/asadmin start-domain "+domainName;
return Konsole.executeCommand(command);
}
public static String stopGlassfishServer() throws IOException, InterruptedException {
String command = glassfishPath + "bin/asadmin stop-domain "+domainName;
return Konsole.executeCommand(command);
}
public static String restrartGlassfishServer() throws IOException, InterruptedException {
String command = glassfishPath + "bin/asadmin restart-domain "+domainName;
return Konsole.executeCommand(command);
}
}
Konsole Class:
package es.os.linux;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* #author adrian
*/
public class Konsole {
static Process process;
static BufferedReader reader;
public static String executeCommand(String command) throws IOException, InterruptedException {
String rez = "";
process = Runtime.getRuntime().exec(command);
process.waitFor();
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
rez += line + "#";
}
return rez;
}
}
Test Class:
public class test {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
try {
System.out.println("START");
System.out.println(Glassfish.startGlassfishServer());
System.out.println("RESTART");
System.out.println(Glassfish.restrartGlassfishServer());
System.out.println("STOP");
System.out.println(Glassfish.stopGlassfishServer());
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
Test class output:
START
Waiting for domain1 to start ............#Successfully started the domain : domain1#domain Location: /home/adrian/glassfish-4.0/glassfish/domains/domain1#Log File: /home/adrian/glassfish-4.0/glassfish/domains/domain1/logs/server.log#Admin Port: 4848#Command start-domain executed successfully.#
RESTART
Successfully restarted the domain#Command restart-domain executed successfully.#
STOP
Waiting for the domain to stop #Command stop-domain executed successfully.#

Categories

Resources