Netbeans Run->Stop Build does not stop the running java processes - netbeans

I'm using Netbeans 7.1.2 on Mac OS X Lion 10.7.3.
I have a simple java server (using netty) project and after I build and run the project then try to stop the running by Run->Stop Build it does not terminate the java server process.
For example, my server app uses port 8080 and even after I stop running from the netbeans the port 8080 is in use and the app keeps running. I have to manually kill the java process from activity monitor.
What's the correct procedure to end the running app started by Netbeans?
Greatly appreciate your help. Thanks in advanced.

Have a look at the documentation: http://netty.io/docs/stable/guide/html/. Scroll down to section 9. Shutting Down Your Application.
Your main app ahs to look something like:
package org.jboss.netty.example.time;
public class TimeServer {
static final ChannelGroup allChannels = new DefaultChannelGroup("time-server"(35));
public static void main(String[] args) throws Exception {
...
ChannelFactory factory = ...;
ServerBootstrap bootstrap = ...;
...
Channel channel = bootstrap.bind(...);
allChannels.add(channel);
...
// Shutdown code
ChannelGroupFuture future = allChannels.close();
future.awaitUninterruptibly();
factory.releaseExternalResources();
}
}
You handler needs:
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
TimeServer.allChannels.add(e.getChannel());
}
You have to:
1. Store all your channels in a ChannelGroup
2. When shutting down, close all channel and release resources.
Hope this helps.

Related

How to add custom shutdown hook to Kafka Connect?

Is there a way to add custom shutdown hook to kafka connect which I can put in the classpath using the plugins.path property?
Use Case:
The Kafka Connect cluster tries to connect to Kafka Cluster.
If it fails it logs and shutsdown immediately
The error logs does not reach to the remote log server like Splunk
I need to delay the shutdown so that the log collector agent can push the logs to the target log server.
I am using Confluent Platform v 6.1
The best way to accomplish what you are looking for is write the log file to a location that outlives the container. This could be a persistent volume like #OneCricketeer mentioned previously, or a network based logging service.
If for some reason you can't do that, you can create a JVM shutdown hook using a Java Agent. This hook could delay the JVM's shutdown long enough (risky) or it could force a flush of the logging library, or any other cleanup. Since the agent is configured as a JVM command line argument, it should work for your kafka-connect workers. You just need to modify the command line that runs the workers.
There are good instructions for creating a Java Agent here and an example for setting up a shutdown hook here: Java shutdown hook
Here is a super simple example class that has both the applications main() method and the Agent's premain() in the same class:
public class App
{
public static void main( String[] args ) throws InterruptedException {
System.out.println( System.currentTimeMillis() + ": Main Started!" );
Thread.sleep(1000);
System.out.println( System.currentTimeMillis() + ": Main Ended!" );
}
public static void premain(String agentArgs, Instrumentation inst) {
System.out.println(System.currentTimeMillis() + ": Agent Started");
Runtime.getRuntime()
.addShutdownHook(
new Thread() {
#Override
public void run() {
System.out.println(System.currentTimeMillis() + ": Shutdown Hook is running!");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// do nothing
}
System.out.println(System.currentTimeMillis() + ": Shutdown hook is completed");
}
});
}
}
Note that in your case, you only need the premain method, as the main method is implemented by the connect worker.
Running the above class with the following command line:
java -javaagent:<MY_AGENT_FILE>.jar -classpath <MY_APP_FILE>.jar
org.example.App
generates the following output:
1630187996652: Agent Started
1630187996672: Main Started!
1630187997672: Main Ended!
1630187997673: Shutdown Hook is running!
1630188002675: Shutdown hook is completed
So you have your delay.

Embedded Jetty Server giving Same response for different urls , without restarting its not working,

I have developed the embedded jetty server to implement the rest service.
I have setup the eclipse project in the eclipse.
I have written the sample program which returns some details through rest url,
I was successfully compiled the program and created a Runnable jar.
I was successfully able to run the Jar files and the server started and running on the port which i gave ,
I have the testing url
http://localhost:1234/getuser/1
it gave me the user details in the response
<username>test1</username>
I ran the same url with different id no
http://localhost:1234/getuser/2
Again it gave me the same result,
`<username>test1</username>`
So i have restarted the server and then it got me the proper details,
<username>test2</username>
public static void main(String[] args) {
// TODO Auto-generated method stub
ServletContextHandler context = new
ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(1234);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", org.test.test.getuser.class.getCanonicalName());
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
e.printStackTrace();
} finally{
jettyServer.destroy();
}
}
Without restarting the jetty web server how to get the proper results.
Is there any thing i need to add in the code to get it worked.
or any settings i need to do for this auto refresh?
I have found the answer, jetty server was able to refresh automatically, there was a object refresh didnt happened in the back end, resolved it from myside and it worked

Erlang Jinterface node nameserver problems on windows

I am trying to implement an interface for my erlang program using jinterface. When I call the command OtpNode otpNode = new OtpNode(nodeName, cookie); java throws an IOException with
java.io.IOException: Nameserver not responding on DESKTOP-GIR29G3 when publishing javanode.
It doesn't seem to be common problem for people as I couldn't find anything similar online. It's a local node with the node name being "javanode" with no fullstops or dashes. Why would there be a DNS issue on a local node?
I have tried starting an erlang node in the directory the java program is started as well as starting the erlang console on my pc, but I'm very new to erlang so those were just wild guesses that some erlang VM must be running.
Here is the code that may help:
public Erlterface()
{
Thread t = new Thread(new Runnable() {
public void run() {
setupMBox();
}
});
t.start();
}
private void setupMBox()
{
try {
String nodeName = "javanode";
String cookie = "jinterface";
//String[] names = OtpEpmd.lookupNames();
OtpNode otpNode = new OtpNode(nodeName, cookie); //CRASH HAPPENS HERE
OtpMbox Mbox = otpNode.createMbox("javaserver");
The error from the console:
Connected to the target VM, address: '127.0.0.1:54025', transport: 'socket'
java.io.IOException: Nameserver not responding on DESKTOP-GIR29G3 when publishing javanode
at com.stellar.base.schedule.com.ericsson.otp.erlang.OtpEpmd.r4_publish(OtpEpmd.java:344)
at com.stellar.base.schedule.com.ericsson.otp.erlang.OtpEpmd.publishPort(OtpEpmd.java:141)
at com.stellar.base.schedule.com.ericsson.otp.erlang.OtpNode$Acceptor.publishPort(OtpNode.java:784)
at com.stellar.base.schedule.com.ericsson.otp.erlang.OtpNode$Acceptor.<init>(OtpNode.java:776)
at com.stellar.base.schedule.com.ericsson.otp.erlang.OtpNode.init(OtpNode.java:232)
at com.stellar.base.schedule.com.ericsson.otp.erlang.OtpNode.<init>(OtpNode.java:196)
at com.stellar.base.schedule.com.ericsson.otp.erlang.OtpNode.<init>(OtpNode.java:149)
at com.stellar.base.schedule.Erlterface.setupMBox(Erlterface.java:40)
at com.stellar.base.schedule.Erlterface.access$000(Erlterface.java:16)
at com.stellar.base.schedule.Erlterface$1.run(Erlterface.java:26)
at java.lang.Thread.run(Thread.java:745)
Thanks in advance
Dale
UPDATE ADDITIONAL INFORMATION:
I went into a dive to try and figure out where exactly the train leaves the rails but I'm taking wild guesses as to what I should flag as potential issues. I just want to add some additional information here to help:
In OptEpmd the following is caught before the io exception is thrown
java.net.ConnectException: Connection refused: connect
The final source is the native DeulSocketImpl class that I suppose calls on windows to do the final connection thingamabob ad it fails:
static native int connect0(int var0, InetAddress var1, int var2) throws IOException;
Am I missing something in setting up the erlang node? I surely don't have to start it manually? I've diabled my firewall completely to test it. How do I figure out why the connection was refused?

Unable to download embedded MongoDB, behind proxy, using automatic configuration script

I have a Spring Boot project, built using Maven, where I intend to use embedded mongo db. I am using Eclipse on Windows 7.
I am behind a proxy that uses automatic configuration script, as I have observed in the Connection tab of Internet Options.
I am getting the following exception when I try to run the application.
java.io.IOException: Could not open inputStream for https://downloads.mongodb.org/win32/mongodb-win32-i386-3.2.2.zip
at de.flapdoodle.embed.process.store.Downloader.downloadInputStream(Downloader.java:131) ~[de.flapdoodle.embed.process-2.0.1.jar:na]
at de.flapdoodle.embed.process.store.Downloader.download(Downloader.java:69) ~[de.flapdoodle.embed.process-2.0.1.jar:na]
....
MongoDB gets downloaded just fine, when I hit the following URL in my web browser:
https://downloads.mongodb.org/win32/mongodb-win32-i386-3.2.2.zip
This leads me to believe that probably I'm missing some configuration in my Eclipse or may be the maven project itself.
Please help me to find the right configuration.
What worked for me on a windows machine:
Download the zip file (https://downloads.mongodb.org/win32/mongodb-win32-i386-3.2.2.zip)
manually and put it (not unpack) into this folder:
C:\Users\<Username>\.embedmongo\win32\
Indeed the problem is about your proxy (a corporate one I guess).
If the proxy do not require authentication, you can solve your problem easily just by adding the appropriate -Dhttp.proxyHost=... and -Dhttp.proxyPort=... (or/and the same with "https.[...]") as JVM arguments in your eclipse junit Runner, as suggested here : https://github.com/learning-spring-boot/learning-spring-boot-2nd-edition-code/issues/2
One solution to your problem is to do the following.
Download MongoDB and place it on a ftp server which is inside your corporate network (for which you would not need proxy).
Then write a configuration in your project like this
#Bean
#ConditionalOnProperty("mongo.proxy")
public IRuntimeConfig embeddedMongoRuntimeConfig() {
final Command command = Command.MongoD;
final IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder()
.defaults(command)
.artifactStore(new ExtractedArtifactStoreBuilder()
.defaults(command)
.download(new DownloadConfigBuilder()
.defaultsForCommand(command)
.downloadPath("your-ftp-path")
.build())
.build())
.build();
return runtimeConfig;
}
With the property mongo.proxy you can control whether Spring Boot downloads MongoDB from your ftp server or from outside. If it is set to true then it downloads from the ftp server. If not then it tries to download from the internet.
The easiest way seems to me to customize the default configuration:
#Bean
DownloadConfigBuilderCustomizer mongoProxyCustomizer() {
return configBuilder -> {
configBuilder.proxyFactory(new HttpProxyFactory(host, port));
};
}
Got the same issue (with Spring Boot 2.6.1 the spring.mongodb.embedded.version property is mandatory).
To configure the proxy, I've added the configuration bean by myself:
#Value("${spring.mongodb.embedded.proxy.domain}")
private String proxyDomain;
#Value("${spring.mongodb.embedded.proxy.port}")
private Integer proxyPort;
#Bean
RuntimeConfig embeddedMongoRuntimeConfig(ObjectProvider<DownloadConfigBuilderCustomizer> downloadConfigBuilderCustomizers) {
Logger logger = LoggerFactory.getLogger(this.getClass().getPackage().getName() + ".EmbeddedMongo");
ProcessOutput processOutput = new ProcessOutput(Processors.logTo(logger, Slf4jLevel.INFO), Processors.logTo(logger, Slf4jLevel.ERROR), Processors.named("[console>]", Processors.logTo(logger, Slf4jLevel.DEBUG)));
return Defaults.runtimeConfigFor(Command.MongoD, logger).processOutput(processOutput).artifactStore(this.getArtifactStore(logger, downloadConfigBuilderCustomizers.orderedStream())).isDaemonProcess(false).build();
}
private ExtractedArtifactStore getArtifactStore(Logger logger, Stream<DownloadConfigBuilderCustomizer> downloadConfigBuilderCustomizers) {
de.flapdoodle.embed.process.config.store.ImmutableDownloadConfig.Builder downloadConfigBuilder = Defaults.downloadConfigFor(Command.MongoD);
downloadConfigBuilder.progressListener(new Slf4jProgressListener(logger));
downloadConfigBuilderCustomizers.forEach((customizer) -> {
customizer.customize(downloadConfigBuilder);
});
DownloadConfig downloadConfig = downloadConfigBuilder
.proxyFactory(new HttpProxyFactory(proxyDomain, proxyPort)) // <--- HERE
.build();
return Defaults.extractedArtifactStoreFor(Command.MongoD).withDownloadConfig(downloadConfig);
}
In my case, I had to add the HTTPS corporate proxy to Intellij Run Configuration.
Https because it was trying to download:
https://downloads.mongodb.org/win32/mongodb-win32-x86_64-4.0.2.zip
application.properties:
spring.data.mongodb.database=test
spring.data.mongodb.port=27017
spring.mongodb.embedded.version=4.0.2
Please keep in mind this is a (DEV) setup.

Has anyone successfully deployed a GWT app on Heroku?

Heroku recently began supporting Java apps. Looking through the docs, it seems to resemble the Java Servlet Standard. Does anyone know of an instance where a GWT app has been successfully deployed on Heroku? If so, are there any limitations?
Yes, I've got a successful deployment using the getting started with Java instructions here:
http://devcenter.heroku.com/articles/java
I use the Maven project with appassembler plugin approach but added gwt-maven-plugin to compile a GWT app during the build.
When you push to heroku you see the GWT compile process running, on one thread only so quite slow but it works fine.
The embedded Jetty instance is configured to serve up static resources at /static from src/main/resources/static and I copy the compiled GWT app to this location during the build and then reference the .nocache.js as normal.
What else do you want to know?
You've got a choice, either build the Javascript representation of your GWT app locally into your Maven project, commit it and the read it from your app, or to generate it inside Heroku via the gwt-maven-plugin as I mentioned.
The code to serve up files from a static location inside your jar via embedded Jetty is something like this inside a Guice ServletModule:
(See my other answer below for a simpler and less Guice-driven way to do this.)
protected void configureServlets() {
bind(DefaultServlet.class).in(Singleton.class);
Map<String, String> initParams = new HashMap<String, String>();
initParams.put("pathInfoOnly", "true");
initParams.put("resourceBase", staticResourceBase());
serve("/static/*").with(DefaultServlet.class, initParams);
}
private String staticResourceBase() {
try {
return WebServletModule.class.getResource("/static").toURI().toString();
}
catch (URISyntaxException e) {
e.printStackTrace();
return "couldn't resolve real path to static/";
}
}
There's a few other tricks to getting embedded Jetty working with guice-servlet, let me know if this isn't enough.
My first answer to this turned out to have problems when GWT tried to read its serialization policy. In the end I went for a simpler approach that was less Guice-based. I had to step through the Jetty code to understand why setBaseResource() was the way to go - it's not immediately obvious from the Javadoc.
Here's my server class - the one with the main() method that you point Heroku at via your app-assembler plugin as per the Heroku docs.
public class MyServer {
public static void main(String[] args) throws Exception {
if (args.length > 0) {
new MyServer().start(Integer.valueOf(args[0]));
}
else {
new MyServer().start(Integer.valueOf(System.getenv("PORT")));
}
}
public void start(int port) throws Exception {
Server server = new Server(port);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setBaseResource(createResourceForStatics());
context.setContextPath("/");
context.addEventListener(new AppConfig());
context.addFilter(GuiceFilter.class, "/*", null);
context.addServlet(DefaultServlet.class, "/");
server.setHandler(context);
server.start();
server.join();
}
private Resource createResourceForStatics() throws MalformedURLException, IOException {
String staticDir = getClass().getClassLoader().getResource("static/").toExternalForm();
Resource staticResource = Resource.newResource(staticDir);
return staticResource;
}
}
AppConfig.java is a GuiceServletContextListener.
You then put your static resources under src/main/resources/static/.
In theory, one should be able to run GWT using the embedded versions of Jetty or Tomcat, and bootstrap the server in main as described in the Heroku Java docs.