How to configure Apache camel with Eclipse - java

i am trying to start apache camel for integration purpose
can you tell what i need to do for camel configuration run this class
Error for running class
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.apache.camel.support.ServiceSupport.<clinit>(ServiceSupport.java:39)
at MainExample.boot(MainExample.java:21)
at MainExample.main(MainExample.java:16)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 3 more
And we use camel-core-2.11.0.jar
Here is my calss
MainExample.java
import java.util.Date;
import javax.annotation.processing.Processor;
import org.apache.camel.Exchange;
import org.apache.camel.Main;
import org.apache.camel.builder.RouteBuilder;
#SuppressWarnings("deprecation")
public class MainExample {
private Main main;
public static void main(String[] args) throws Exception {
MainExample example = new MainExample();
example.boot();
}
public void boot() throws Exception {
// create a Main instance
main = new Main();
// enable hangup support so you can press ctrl + c to terminate the JVM
main.enableHangupSupport();
// bind MyBean into the registery
main.bind("foo", new MyBean());
// add routes
main.addRouteBuilder(new MyRouteBuilder());
// run until you terminate the JVM
System.out.println("Starting Camel. Use ctrl + c to terminate the JVM.\n");
main.run();
}
private static class MyRouteBuilder extends RouteBuilder {
#Override
public void configure() throws Exception {
from("timer:foo?delay=2000")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
System.out.println("Invoked timer at " + new Date());
}
})
.beanRef("foo");
}
}
public static class MyBean {
public void callMe() {
System.out.println("MyBean.calleMe method has been called");
}
}
}

Just add SLF4J libraries to your CLASSPATH. Normally your need SLF4J API (slf4j-api-version.jar) and one implementation e.g. slf4j-log4j-version.jar

Related

Error 'java.lang.IllegalArgumentException: Plugin already initialized!' found

I'm trying to use a simple socket server to receive some commands(bukkit api).
With the thread, the plugin can receive commands and send it to the main server, so that i can control the server.
But when i tried to use a use a thread to solve the problem, an error happened:
CODE:
package tiance.auroracore;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import tiance.auroracore.metrics.Metrics;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public final class AuroraCore extends JavaPlugin {
private int port;// 默认服务器端口
private String AcceptCommand;
public AuroraCore() {
this.port=9028;
this.AcceptCommand=new String();
}
// 创建指定端口的服务器
public AuroraCore(int port) {//构造方法
this.port = port;//将方法参数赋值给类参数
this.AcceptCommand=new String();
}
// 提供服务
public void service() {//创建service方法
ServerSocket server;
try {
server = new ServerSocket(port);//创建 ServerSocket类
}
catch (IOException e) {
System.out.println("Error! Cannot start the server! Is the port already used?");
return;
}
while (true) {
try {// 建立服务器连接
Socket socket = server.accept();// 等待客户连接
try {
DataInputStream in = new DataInputStream(socket
.getInputStream());// 读取客户端传过来信息的DataInputStream
DataOutputStream out = new DataOutputStream(socket
.getOutputStream());// 向客户端发送信息的DataOutputStream
while (true) {
String accept = in.readUTF();// 读取来自客户端的信息
AcceptCommand = accept;
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), AcceptCommand);
}
} finally {// 建立连接失败的话不会执行socket.close();
socket.close();//关闭连接
server.close();//关闭
}
} catch (IOException e) {//捕获异常
e.printStackTrace();
}
}
}
#Override
public void onEnable() {
new BukkitRunnable(){
public void run(){
new AuroraCore().service();//调用service方法
}
}.runTaskAsynchronously(this);
int pluginId = 13929;
Metrics metrics = new Metrics(this, pluginId);
saveDefaultConfig();
}
#Override
public void onDisable() {
}
}
ERROR
[12:45:28 WARN]: [AuroraCore] Plugin AuroraCore v1.0.0 generated an exception while executing task 2
java.lang.IllegalArgumentException: Plugin already initialized!
at org.bukkit.plugin.java.PluginClassLoader.initialize(PluginClassLoader.java:218) ~[craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
at org.bukkit.plugin.java.JavaPlugin.<init>(JavaPlugin.java:52) ~[craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
at tiance.auroracore.AuroraCore.<init>(AuroraCore.java:19) ~[?:?]
at tiance.auroracore.AuroraCore$1.run(AuroraCore.java:69) ~[?:?]
at org.bukkit.craftbukkit.v1_16_R3.scheduler.CraftTask.run(CraftTask.java:76) ~[craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
at org.bukkit.craftbukkit.v1_16_R3.scheduler.CraftAsyncTask.run(CraftAsyncTask.java:54) [craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_281]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_281]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_281]
Caused by: java.lang.IllegalStateException: Initial initialization
at org.bukkit.plugin.java.PluginClassLoader.initialize(PluginClassLoader.java:221) ~[craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
at org.bukkit.plugin.java.JavaPlugin.<init>(JavaPlugin.java:52) ~[craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
at tiance.auroracore.AuroraCore.<init>(AuroraCore.java:19) ~[?:?]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_281]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_281]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_281]
at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[?:1.8.0_281]
at java.lang.Class.newInstance(Unknown Source) ~[?:1.8.0_281]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:79) ~[craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:143) ~[craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:393) ~[craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:301) ~[craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
at org.bukkit.craftbukkit.v1_16_R3.CraftServer.loadPlugins(CraftServer.java:379) ~[craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
at net.minecraft.server.v1_16_R3.DedicatedServer.init(DedicatedServer.java:218) ~[craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
at net.minecraft.server.v1_16_R3.MinecraftServer.w(MinecraftServer.java:905) ~[craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
at net.minecraft.server.v1_16_R3.MinecraftServer.lambda$0(MinecraftServer.java:263) ~[craftbukkit-1.16.5.jar:3096a-Bukkit-af1a232]
... 1 more
I've edited the code again and again,but didn't found any solution. I've also seen some questions on the website, but none of them could solve my problem.I didn't found any repeat main class .I really don't know what to do! If someone can help, i will be very glad and thankful to him or her.
Replace new AuroraCore() with AuroraCore.this.
You have to replace new AuroraCore() with AuroraCore.this to initialize service() void
#Override
public void onEnable() {
new BukkitRunnable(){
public void run(){
AuroraCore.this.service();//调用service方法
}
}.runTaskAsynchronously(this);
int pluginId = 13929;
Metrics metrics = new Metrics(this, pluginId);
saveDefaultConfig();
}

Launcher crashes when running mod in Eclipse

I'm trying to make my first block in Eclipse, but the launcher crashes whenever I try to run it. I'm not sure what I'm doing wrong. I've created a new instance of the block, registered it, gave the constructor all the necessary fields, triple-checked the run methods, and I still haven't found the problem. I am running Minecraft 1.7.10.
Here are the classes:
Creates a BasicBlock object and registers it:
package com.mrcrayfish.tutorial.blocks;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
public final class ModBlocks {
public static Block tutorialBlock;
public static final void init() {
tutorialBlock = new BasicBlock("tutorialBlock", Material.wood);
GameRegistry.registerBlock(tutorialBlock, "tutorialBlock");
}
}
BasicBlock class:
package com.mrcrayfish.tutorial.blocks;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import com.mrcrayfish.tutorial.Reference;
public class BasicBlock extends Block {
public BasicBlock(String unlocalizedName, Material material) {
super(material);
this.setBlockName(unlocalizedName);
this.setBlockTextureName(Reference.MOD_ID + ":" + unlocalizedName);
this.setCreativeTab(CreativeTabs.tabBlock);
this.setHardness(2.0F);
this.setResistance(6.0F);
this.setLightLevel(20.0F);
this.setHarvestLevel("shovel", 3);
this.setStepSound(soundTypeMetal);
}
}
Proxy with runtime methods:
package com.mrcrayfish.tutorial.proxy;
import cpw.mods.fml.common.event.*;
import com.mrcrayfish.tutorial.blocks.ModBlocks;
import com.mrcrayfish.tutorial.init.ModItems;
public class CommonProxy {
public void preInit(FMLPreInitializationEvent e) {
ModItems.init();
ModItems.register();
ModBlocks.init();
}
public void init(FMLInitializationEvent e) {
}
public void postInit(FMLPostInitializationEvent e) {
}
}
Main runtime class:
package com.mrcrayfish.tutorial;
import com.mrcrayfish.tutorial.init.ModItems;
import com.mrcrayfish.tutorial.proxy.CommonProxy;
import com.mrcrayfish.tutorial.blocks.ModBlocks;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.*;
import cpw.mods.fml.common.Mod.EventHandler;
#Mod(modid = Reference.MOD_ID, name = Reference.NAME, version = Reference.VERSION)
public class Tutorial {
#Instance
public static Tutorial instance;
#SidedProxy(clientSide = Reference.CLIENT_PROXY_CLASS, serverSide = Reference.SERVER_PROXY_CLASS)
public static CommonProxy proxy;
#EventHandler
public void preInit(FMLPreInitializationEvent event) {
ModItems.init();
ModItems.register();
ModBlocks.init();
proxy.preInit(event);
}
#EventHandler
public void init(FMLInitializationEvent event) {
System.out.println("init");
proxy.init(event);
}
#EventHandler
public void postInit(FMLPostInitializationEvent event) {
System.out.println("postinit");
proxy.postInit(event);
}
}
Reference class with final variables/enums:
package com.mrcrayfish.tutorial;
import net.minecraft.block.material.Material;
public class Reference {
public static final String MOD_ID = "ctm";
public static final String NAME = "MrCrayfish's Tutorial Mod";
public static final String VERSION = "1.0";
public static final String CLIENT_PROXY_CLASS = "com.mrcrayfish.tutorial.proxy.ClientProxy";
public static final String SERVER_PROXY_CLASS = "com.mrcrayfish.tutorial.proxy.ServerProxy";
public enum TutorialItems {
CHEESE("cheese", "ItemCheese");
public String unlocalizedName;
public String registryName;
TutorialItems(String unlocalizedName, String registryName) {
this.unlocalizedName = unlocalizedName;
this.registryName = registryName;
}
public String getUnlocalizedName() {
return unlocalizedName;
}
public String getRegistryName() {
return registryName;
}
}
public enum EBlock {
TUTORIALBLOCK("tutorialBlock", Material.wood);
String BlockName;
Material material;
EBlock(String BlockName, Material material) {
this.BlockName = BlockName;
this.material = material;
}
}
}
ClientProxy class:
package com.mrcrayfish.tutorial.proxy;
import cpw.mods.fml.common.event.*;
public class ClientProxy extends CommonProxy
{
public void preInit(FMLPreInitializationEvent h)
{
super.preInit(h);
}
public void init(FMLInitializationEvent h)
{
super.init(h);
}
public void postInit(FMLPostInitializationEvent h)
{
super.postInit(h);
}
}
ServerProxy class:
package com.mrcrayfish.tutorial.proxy;
import cpw.mods.fml.common.event.*;
public class ServerProxy extends CommonProxy
{
public void preInit(FMLPreInitializationEvent h)
{
super.preInit(h);
}
public void init(FMLInitializationEvent h)
{
super.init(h);
}
public void postInit(FMLPostInitializationEvent h)
{
super.postInit(h);
}
}
The most I could get out of the debug report is that there is an issue with the "preInit" method in "Tutorial.java". Here's the crash report:
at cpw.mods.fml.common.registry.FMLControlledNamespacedRegistry.add(FMLControlledNamespacedRegistry.java:410)
at cpw.mods.fml.common.registry.GameData.registerItem(GameData.java:849)
at cpw.mods.fml.common.registry.GameData.registerItem(GameData.java:812)
at cpw.mods.fml.common.registry.GameRegistry.registerItem(GameRegistry.java:149)
at cpw.mods.fml.common.registry.GameRegistry.registerItem(GameRegistry.java:137)
at com.mrcrayfish.tutorial.init.ModItems.register(ModItems.java:23)
at com.mrcrayfish.tutorial.proxy.CommonProxy.preInit(CommonProxy.java:10)
at com.mrcrayfish.tutorial.proxy.ClientProxy.preInit(ClientProxy.java:8)
at com.mrcrayfish.tutorial.Tutorial.preInit(Tutorial.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at cpw.mods.fml.common.FMLModContainer.handleModStateEvent(FMLModContainer.java:532)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.common.eventbus.EventSubscriber.handleEvent(EventSubscriber.java:74)
at com.google.common.eventbus.SynchronizedEventSubscriber.handleEvent(SynchronizedEventSubscriber.java:47)
at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322)
at com.google.common.eventbus.EventBus.dispatchQueuedEvents(EventBus.java:304)
at com.google.common.eventbus.EventBus.post(EventBus.java:275)
at cpw.mods.fml.common.LoadController.sendEventToModContainer(LoadController.java:212)
at cpw.mods.fml.common.LoadController.propogateStateMessage(LoadController.java:190)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.common.eventbus.EventSubscriber.handleEvent(EventSubscriber.java:74)
at com.google.common.eventbus.SynchronizedEventSubscriber.handleEvent(SynchronizedEventSubscriber.java:47)
at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322)
at com.google.common.eventbus.EventBus.dispatchQueuedEvents(EventBus.java:304)
at com.google.common.eventbus.EventBus.post(EventBus.java:275)
at cpw.mods.fml.common.LoadController.distributeStateMessage(LoadController.java:119)
at cpw.mods.fml.common.Loader.preinitializeMods(Loader.java:556)
at cpw.mods.fml.client.FMLClientHandler.beginMinecraftLoading(FMLClientHandler.java:243)
at net.minecraft.client.Minecraft.startGame(Minecraft.java:522)
at net.minecraft.client.Minecraft.run(Minecraft.java:942)
at net.minecraft.client.main.Main.main(Main.java:164)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at net.minecraft.launchwrapper.Launch.launch(Launch.java:135)
at net.minecraft.launchwrapper.Launch.main(Launch.java:28)
at net.minecraftforge.gradle.GradleStartCommon.launch(Unknown Source)
at GradleStart.main(Unknown Source)
After looking through eclipse's console output, I think I can narrow down the issue:
[09:12:27] [Client thread/INFO] [MinecraftForge]: Attempting early MinecraftForge initialization
[09:12:27] [Client thread/INFO] [FML]: MinecraftForge v10.13.4.1558 Initialized
[09:12:27] [Client thread/INFO] [FML]: Replaced 183 ore recipies
[09:12:27] [Client thread/INFO] [MinecraftForge]: Completed early MinecraftForge initialization
[09:12:28] [Client thread/INFO] [FML]: Found 0 mods from the command line. Injecting into mod discoverer
[09:12:28] [Client thread/INFO] [FML]: Searching C:\Users\Chris\Desktop\Forge\eclipse\mods for mods
[09:12:44] [Client thread/INFO] [FML]: Forge Mod Loader has identified 4 mods to load
[09:12:45] [Client thread/INFO] [FML]: Attempting connection with missing mods [mcp, FML, Forge, ctm] at CLIENT
[09:12:45] [Client thread/INFO] [FML]: Attempting connection with missing mods [mcp, FML, Forge, ctm] at SERVER
Seems to be an issue with the proxy classes I created.
When the preInit Event occures you run the following lines
ModItems.init();
ModItems.register();
ModBlocks.init();
and then you run your Proxies preInit Methode
since bothe the ClientProxy and ServerProxy just call super.preInit
both call CommonProxy's preInit Methode which also does
ModItems.init();
ModItems.register();
ModBlocks.init();
this means you are trying to register everything twich wich probably causes the error.

Twitter4j streaming api call throwing class not found exception

I am writing a utility class using twitter4j for multiple purpose. I am able to search tweets based on Hashtags, location etc but Streaming API is not working for me.
I have written a class with main method after following a blog as follows but I am getting class not found error.I am new to java.
package mytweetapp;
import twitter4j.FilterQuery;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterException;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.conf.ConfigurationBuilder;
public class Stream {
public static void main(String[] args) throws TwitterException {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("*****")
.setOAuthConsumerSecret(
"*******")
.setOAuthAccessToken(
"*****")
.setOAuthAccessTokenSecret(
"*****");
TwitterStreamFactory tf = new TwitterStreamFactory(cb.build());
TwitterStream twitter = tf.getInstance();
StatusListener listener = new StatusListener() {
public void onStatus(Status status) {
System.out
.println("#" + status.getUser().getScreenName() + " - " + status
.getText());
}
public void onDeletionNotice(
StatusDeletionNotice statusDeletionNotice) {
System.out
.println("Got a status deletion notice id:" + statusDeletionNotice
.getStatusId());
}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out
.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
public void onScrubGeo(long userId, long upToStatusId) {
System.out
.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
public void onException(Exception ex) {
ex.printStackTrace();
}
#Override
public void onStallWarning(StallWarning arg0) {
// TODO Auto-generated method stub
}
};
FilterQuery fq = new FilterQuery();
String keywords[] = { "Mango", "Banana" };
fq.track(keywords);
twitter.addListener(listener);
twitter.filter(fq);
}
Error
Exception in thread "main" java.lang.NoClassDefFoundError: twitter4j/internal/http/HttpClientWrapperConfiguration
at twitter4j.TwitterStreamFactory.<clinit>(TwitterStreamFactory.java:40)
at mytweetapp.Stream.main(Stream.java:23)
Caused by: java.lang.ClassNotFoundException: twitter4j.internal.http.HttpClientWrapperConfiguration
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 2 more
My current hypothesis is that the problem is because of mixing core and stream jars of different versions (so e.g. TwitterStreamFactory from stream-3.0.3 expects HttpClientWrapperConfiguration to be available on your classpath but in 4.0.4 it is no longer included. Please try having those of the same version included (and only one version of lib, so stream-3 and stream-4 being included together is no-no). If that won't work - share the whole project somewhere for more context.
As for what classpath is you can google, or read up e.g. here What is a classpath?

Netty 4.0.x Correctly catch a ConnectException

I'm developing an application with Netty and I need to handle the ConnectException on the client side thrown in case, for example, of a connect timeout.
Here's the code
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
public class ConnectTest {
public static void main(String[] args) throws Exception {
Bootstrap b = new Bootstrap();
b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
}
});
final ChannelFuture f = b.connect("0.0.0.0", 8080);
f.addListener(new FutureListener<Void>() {
#Override
public void operationComplete(Future<Void> future) throws Exception {
if (!f.isSuccess())
System.out.println("Test Connection failed");
}
});
f.sync();
}
}
And this is the result:
Test Connection failed
Exception in thread "main"
java.net.ConnectException: Connection refused: no further information: /0.0.0.0:8080
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(Unknown Source)
at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:208)
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:287)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:524)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:464)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:378)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:350)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
at java.lang.Thread.run(Unknown Source)
As you can see the listener works fine, but i still get an ugly stacktrace printed out and I can't figure out where to intercept it.
Any hints?
the culprit is
f.sync()
You could handle ConnectExceptions in the listener :
final ChannelFuture f = b.connect("0.0.0.0", 8080);
f.addListener(new FutureListener<Void>() {
#Override
public void operationComplete(Future<Void> future) throws Exception {
if (!f.isSuccess()) {
System.out.println("Test Connection failed");
handleException(future.cause());
}
}
});
//f.sync();

Getting NotBoundException while writing a Java RMI chat application :-/

I have written a Java RMI chat application. There are four classes and two interfaces. Here they are:
ChatClient
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;
com.za.tutorial.rmi.server.ChatServerIF;
public class ChatClient extends UnicastRemoteObject implements ChatClientIF,Runnable {
private ChatServerIF chatServer;
private String name = null;
protected ChatClient(String name, ChatServerIF chatServer) throws RemoteException {
this.name = name;
this.chatServer = chatServer;
chatServer.registerChatClient(this);
}
public void retrieveMessage(String message) throws RemoteException {
// TODO Auto-generated method stub
System.out.println(message);
}
public void run() {
Scanner scanner = new Scanner(System.in);
String message;
while(true){
message = scanner.nextLine();
try {
chatServer.broadcastMessage(name + " : " + message);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
ChatClientDriver
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import com.za.tutorial.rmi.server.ChatServerIF;
public class ChatClientDriver {
public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException {
String chatServerURL = "rmi://localhost/RMIChatServer";
ChatServerIF chatServer = (ChatServerIF) Naming.lookup(chatServerURL);
new Thread(new ChatClient(args[0],chatServer)).start();
}
}
ChatClientInterface
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface ChatClientIF extends Remote {
void retrieveMessage(String message) throws RemoteException;
}
ChatServer
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import com.za.tutorial.rmi.client.ChatClientIF;
public class ChatServer extends UnicastRemoteObject implements ChatServerIF {
private ArrayList<ChatClientIF> chatClients;
protected ChatServer() throws RemoteException {
chatClients = new ArrayList<ChatClientIF>();
}
public synchronized void registerChatClient(ChatClientIF chatClient)
throws RemoteException {
this.chatClients.add(chatClient);
}
public synchronized void broadcastMessage(String message) throws RemoteException {
int i = 0;
while(i < chatClients.size()){
chatClients.get(i++).retrieveMessage(message);
}
}
}
ChatServerDriver
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
public class ChatServerDriver {
public static void main(String[] args) throws RemoteException, MalformedURLException {
Naming.rebind("RMIChatServer", new ChatServer());
}
}
ChatServerInterface
import java.rmi.Remote;
import java.rmi.RemoteException;
import com.za.tutorial.rmi.client.ChatClientIF;
public interface ChatServerIF extends Remote {
void registerChatClient(ChatClientIF chatClient) throws RemoteException;
void broadcastMessage(String message) throws RemoteException;
}
When I run it on Commando, first of all I run rmic ChatClient and ChatServer, then rmiregistry. Then i run chatServerDriver which works completely fine. after that, when I run chatClientDriver with a name, I get the following error, I dont understand why :/ Can I get any solution for this?
Thanks :)
Exception in thread "main" java.rmi.NotBoundException: RMIChatServer
at sun.rmi.registry.RegistryImpl.lookup(RegistryImpl.java:136)
at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source)
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:409)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:267)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at java.rmi.Naming.lookup(Unknown Source)
at com.za.tutorial.rmi.client.ChatClientDriver.main(ChatClientDriver.java:15)
It also looks like you have a different address in Rebind to what is being used by the client to connect.
Naming.rebind("//localhost/RMIChatServer", new ChatServer());
There's an example implementation on the following Wikipedia page which may be worth comparing against your code.
http://en.wikipedia.org/wiki/Java_remote_method_invocation
Note that using Java 1.5+ you don't need to use rmic anymore see Do we really need to create Stub in java RMI?

Categories

Resources