NoClassDefFoundError: io/netty/util/Timer - java

Just wanted to try Cassandra Java driver from eclipse and copied a sample code from "Practical Cassandra"
But faced error below output by eclipse:
Exception in thread "main" java.lang.NoClassDefFoundError: io/netty/util/Timer
at com.datastax.driver.core.Configuration$Builder.build(Configuration.java:294)
at com.datastax.driver.core.Cluster$Builder.getConfiguration(Cluster.java:1247)
at com.datastax.driver.core.Cluster.<init>(Cluster.java:116)
at com.datastax.driver.core.Cluster.buildFrom(Cluster.java:181)
at com.datastax.driver.core.Cluster$Builder.build(Cluster.java:1264)
at SampleApp.connect(SampleApp.java:13)
at SampleApp.main(SampleApp.java:64)
Caused by: java.lang.ClassNotFoundException: io.netty.util.Timer
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)
... 7 more
here is the sample code:
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
public class SampleApp {
private Cluster cluster;
private Session session;
public void connect(String node) {
cluster = Cluster.builder().addContactPoint(node).build();
Metadata metadata = cluster.getMetadata();
System.out.printf("Cluster: %s\n", metadata.getClusterName());
for ( Host host : metadata.getAllHosts() ) {
System.out.printf("Host: %s \n",host.getAddress());
}
session = cluster.connect();
}
public void close(){
cluster.close();
}
public void createSchema(){
session.execute("CREATE KEYSPACE IF NOT EXISTS portfolio_demo " +
"WITH REPLICATION 5 { ‘class’: ‘SimpleStrategy’, " +
"'replication_factor’: 1 };");
session.execute("CREATE TABLE IF NOT EXISTS portfolio_demo.portfolio (" +
"portfolio_id UUID, ticker TEXT, " +
"current_price DECIMAL, current_change DECIMAL, " +
"current_change_percent FLOAT, " +
"PRIMARY KEY(portfolio_id, ticker));");
}
public void loadData(){
session.execute("INSERT INTO portfolio_demo.portfolio " +
"(portfolio_id, ticker, current_price, " +
" current_change, current_change_percent) VALUES " +
"(756716f7-2e54-4715-9f00-91dcbea6cf50, ‘GOOG’, " +
" 889.07, -4.00, -0.45);");
session.execute("INSERT INTO portfolio_demo.portfolio " +
"(portfolio_id, ticker, current_price, " +
" current_change, current_change_percent) VALUES " +
"(756716f7-2e54-4715-9f00-91dcbea6cf50, ‘AMZN’, " +
" 297.92, -0.94, -0.31);");
}
public void printResults(){
ResultSet results = session.execute("SELECT * FROM " +
"portfolio_demo.portfolio WHERE portfolio_id 5 " +
"756716f7-2e54-4715-9f00-91dcbea6cf50;");
for (Row row : results) {
System.out.println(String.format("%-7s\t%-7s\t%-7s\t%-7s \n%s",
"Ticker", "Price", "Change", "PCT",
"........1........1........1........"));
System.out.println(String.format("%-7s\t%0.2f\t%0.2f\t%0.2f",
row.getString("ticker"),
row.getDecimal("current_price"),
row.getDecimal("current_change"),
row.getFloat("current_change_percent") ));
}
}
public static void main(String[] args) {
SampleApp client = new SampleApp();
client.connect("127.0.0.1");
client.createSchema();
client.loadData();
client.printResults();
client.close();
}
}
And I also added several external JARs which are downloaded or comes with eclipse:
cassandra-driver-core-3.0.0.jar
guava-18.0.jar
netty-3.10.6.Final-20160303.120156-121.jar
org.apache.log4j_1.2.15.v201012070815.jar (from eclipse plugin)
org.slf4j.api_1.7.2.v20121108-1250.jar (from eclipse plugin)
org.slf4j.impl.log4j12_1.7.2.v20131105-2200.jar (from eclipse plugin)
I saw the same questions about the netty error but still could not figure out what was wrong with my code.
Thanks a lot.

This is the wrong Netty version. Version 3.0.0 of the driver uses 4.0.33.
You can view the driver's dependencies in the POM. The properties such as ${netty.version} are defined in the parent POM.

Related

Why Wildfly does not find the postgresql driver

I am developping a multi-tier software using java. The middle tier is a java ejb accessing the postgresql database. But when I run the client java application, I have the following error messages:
INFO: EJBCLIENT000069: Using legacy jboss-ejb-client.properties security configuration
Exception in thread "main" javax.ejb.EJBException: WFLYEJB0442: Unexpected Error
....
Caused by: java.lang.NoClassDefFoundError: org/postgresql/Driver
...
Caused by: java.lang.ClassNotFoundException: org.postgresql.Driver
The content of the module.xml file is:
<?xml version="1.0" encoding="utf-8" ?>
<module xmlns="urn:jboss:module:1.3" name="org.postgresql">
<resources>
<!--the name of your driver -->
<resource-root path="postgresql-42.2.6.jar"/>
</resources>
<dependencies>
<module name="javax.api"/>
<module name="javax.transaction.api"/>
</dependencies>
</module>
The following lines have been added to the standalone.xml file:
<driver name="postgresql" module="org.postgresql">
<driver-class>org.postgresql.Driver</driver-class>
<xa-datasource-class>org.postgresql.xa.PGXADataSource</xa-datasource-
class>
</driver>
The driver and the module.xml are in folder \modules\org\postgresql\main. I have successfully tested my code by moving it to a single-tier java application. I am using Eclipse jee latest verion, wildfly 16, postgresql 11. the driver is postgresql-42.2.6.jar
I have already spent several days battling with the problem, but no success. Help most welcome.
package loginPackage;
import java.sql.Connection;
import java.sql.DriverManager;
import org.postgresql.Driver;
import java.sql.SQLException;
public class LoginDao {
static String errorMessage;
static String connectionResult;
public static String getConnectionResult() {
return connectionResult;
}
public static void setConnectionResult(String connectResult) {
connectionResult = connectResult;
}
public String getErrorMessage() {
return errorMessage;
}
public static void setErrorMessage(String errorMsg) {
errorMessage = errorMsg;
}
public static void LoginCheck(String userCode, String userPswd) {
setConnectionResult(userConnect(userCode, userPswd));
}
public static String userConnect(String userCode, String userPaswd) {
try {
//Connection conn = null;
setConnectionResult("OK");
setErrorMessage("OK");
Driver driver = new org.postgresql.Driver();
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/TestDb", userCode, userPaswd);
System.out.println("Connected to PostgreSQL database!");
return "SUCCESS";
}
catch (Exception e) {
System.out.println("Failed to create JDBC db connection " + e.toString() + e.getMessage());
setErrorMessage(userCode + ", " + userPaswd + ", " + e.toString() + ", " + e.getMessage() + ", " + e.getStackTrace());
return "FAILURE" ;
}
}
}

My Bukkit plugin command throws an exception

My Bukkit plugin command always throws an exception when I run it.
When I type my command: /config set (it should save info to file/config), I get this error in chat:
An internal error occurred while attemping to perform this command.
Why does this happen?
Console Log:
[13:23:24 INFO]: whispereq issued server command: /config set
[13:23:24 ERROR]: null
org.bukkit.command.CommandException: Unhandled exception executing command 'config' in plugin registyPlayer v1.0
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:175) ~[src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
at org.bukkit.craftbukkit.v1_7_R1.CraftServer.dispatchCommand(CraftServer.java:683) ~[src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
at net.minecraft.server.v1_7_R1.PlayerConnection.handleCommand(PlayerConnection.java:952) [src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
at net.minecraft.server.v1_7_R1.PlayerConnection.a(PlayerConnection.java:814) [src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
at net.minecraft.server.v1_7_R1.PacketPlayInChat.a(PacketPlayInChat.java:28) [src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
at net.minecraft.server.v1_7_R1.PacketPlayInChat.handle(PacketPlayInChat.java:47) [src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
at net.minecraft.server.v1_7_R1.NetworkManager.a(NetworkManager.java:146) [src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
at net.minecraft.server.v1_7_R1.ServerConnection.c(SourceFile:134) [src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
at net.minecraft.server.v1_7_R1.MinecraftServer.u(MinecraftServer.java:655) [src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
at net.minecraft.server.v1_7_R1.DedicatedServer.u(DedicatedServer.java:250) [src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
at net.minecraft.server.v1_7_R1.MinecraftServer.t(MinecraftServer.java:545) [src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
at net.minecraft.server.v1_7_R1.MinecraftServer.run(MinecraftServer.java:457) [src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
at net.minecraft.server.v1_7_R1.ThreadServerApplication.run(SourceFile:617) [src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
Caused by: java.lang.ArrayIndexOutOfBoundsException: 1
at whispereq.saver.onCommand(saver.java:14) ~[?:?]
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[src.jar:git-Bukkit-1.7.2-R0.3-b3020jnks]
... 13 more
My code from the saver class:
package whispereq;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class saver implements CommandExecutor {
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("config")) {
if (sender instanceof Player) {
if (args.length == 1) {
if (args[1].equalsIgnoreCase("set")) {
sender.sendMessage("§6Registering player§c " + args[0] + "§6 to Server....");
Player p = (Player) sender;
String nick = p.getName().toLowerCase();
String uid = p.getUniqueId().toString();
boolean op = p.isOp();
GameMode gm = p.getGameMode();
GameMode dgm = Bukkit.getDefaultGameMode();
float exp = p.getExp();
float explvl = p.getExpToLevel();
Main.getInst().getConfig().set("players." + nick + ".uuid", uid);
Main.getInst().getConfig().set("players." + nick + ".isOpped", op);
Main.getInst().getConfig().set("players." + nick + ".CurrentGameMode", gm);
Main.getInst().getConfig().set("players." + nick + ".DefaultGameMode", dgm);
Main.getInst().getConfig().set("players." + nick + ".Exp", exp);
Main.getInst().getConfig().set("players." + nick + ".ExpLevel", explvl);
Main.getInst().saveConfig();
sender.sendMessage("§6Finished!, yours Current in-game Status was SUccesfully registered to the config.yml File in Plugin's Directory. use §c/registy getMe§6 to view your Property.");
return true;
} else if (args[1].equalsIgnoreCase("get")) {
Player p = (Player) sender;
String nick = p.getName().toLowerCase();
if (Main.getInst().getConfig().get("players." + nick) != null) {
p.sendMessage("§8_____________________________________________________");
p.sendMessage(Main.getInst().getConfig().getString("players." + nick + ".uuid"));
p.sendMessage(Main.getInst().getConfig().getString("players." + nick + ".isOpped"));
p.sendMessage(Main.getInst().getConfig().getString("players." + nick + ".CurrentGameMode"));
p.sendMessage(Main.getInst().getConfig().getString("players." + nick + ".DefaultGameMode"));
p.sendMessage(Main.getInst().getConfig().getString("players." + nick + ".Exp"));
p.sendMessage(Main.getInst().getConfig().getString("players." + nick + "ExpLevel"));
p.sendMessage("§8_____________________________________________________");
}
}
}
}
}
return false;
}
}
Main class:
package whispereq;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
public static Main instance;
public void onEnable() {
instance = this;
System.out.println("Loading RegistyPlayer ..");
getCommand("config").setExecutor(new saver());
saveDefaultConfig();
}
public static Main getInst() {
return instance;
}
}
Config File (empty):
#-----------------------------------------------------------#
plugin.yml:
name: registyPlayer
version: 1.0
main: whispereq.Main
commands:
config:
Craftbukkit: 1.7.2 R03
Bukkit API: 1.7.2 R03
Server Craftbukkit: 1.7.2 R03
Arrays always start at index 0. Therefore, to access whether the player specified "get" or "set" you should replace
args[1].equalsIgnoreCase("set")
args[1].equalsIgnoreCase("get")
with
args[0].equalsIgnoreCase("set")
args[0].equalsIgnoreCase("get")
Also, not sure what you are doing with the line
sender.sendMessage("§6Registering player§c " + args[0] + "§6 to Server....");
args[0] refers to either "get" or "set". Presumably, you should replace it with "nick" and insert the line after
String nick = p.getName().toLowerCase();

JAVA - Access file from shared storage without mount

I have done set up a NAS server using NAS4Free and share a folder at:
\\NAS_SERVER_IP/SHARE_FOLDER_NAME
In SHARE_FOLDER_NAME directory contains resource files need to share to multiple clients
Now ,from clients , can I using Java to access (read/write) directly file from NAS server without mount shared folder to local clients
Copied from here, but changed the api call argument.
connecting to shared folder in windows with java
String url = "smb://[NAS server-IP or hostname]/file-or-directory-path";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("[company network domain]", "user", "password");
SmbFile dir = new SmbFile(url, auth);
for (SmbFile f : dir.listFiles())
{
System.out.println(f.getName());
}
For observing file/dir changes using JDK 6, you could use:
WatchService for Java 6
For JDK 7, WatchService is part of NIO package:
http://java.dzone.com/news/how-watch-file-system-changes
Finally, this one works with JDK6 as well. This way, we could observe file/dir changes in windows shared drivers without mounting/mapping them as a drive.
I've used following jars in classpath: commons-collections-4.4.0, commons-logging-1.1.2, commons-logging-api-1.1.2, commons-net-3.3, commons-vfs2-2.0, httpclient-4.3.1, jackrabbit-standalone-2.6.5, jcifs-1.3.17, jsch-0.1.51
import org.apache.commons.vfs2.FileChangeEvent;
import org.apache.commons.vfs2.FileListener;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.impl.DefaultFileMonitor;
public class NFSChangeObserver
{
public static void main(String[] args) throws FileSystemException
{
/** need a non-daemon thread, because <code>DefaultFileMonitor</code> is internally marked as a daemon thread.
*/
Thread t = new Thread(new Runnable() {
#Override
public synchronized void run()
{
try
{
while(1!=2)
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}});
t.start();
FileSystemManager manager = VFS.getManager();
FileObject file = manager.resolveFile("\\\\[server-hostname]\\[directory-path]");
DefaultFileMonitor fm = new DefaultFileMonitor(new FileListener()
{
#Override
public void fileChanged(final FileChangeEvent fileChangeEvt) throws Exception
{
System.out.println("#" + System.currentTimeMillis() + ": " + fileChangeEvt.getFile().getName() + " changed .." );
}
#Override
public void fileCreated(FileChangeEvent fileChangeEvt) throws Exception
{
System.out.println("#" + System.currentTimeMillis() + ": " + fileChangeEvt.getFile().getName() + " created .." );
}
#Override
public void fileDeleted(FileChangeEvent fileChangeEvt) throws Exception
{
System.out.println("#" + System.currentTimeMillis() + ": " + fileChangeEvt.getFile().getName() + " deleted .." );
}
});
fm.setDelay(5000);
fm.addFile(file);
FileObject[] children = file.getChildren();
for(FileObject child : children)
{
System.out.println(child.getURL());
}
fm.start();
}
}

how to send a sms through a usb modem using smslib

I want to send a sms using a usb modem through my java application. I tried smslib and i couldn't do my task.
I tried using following code..
I did the external configurations as mentioned also..
So can u please help me on using smslib ina 64bit machine.
package sms;
import org.smslib.AGateway;
import org.smslib.IOutboundMessageNotification;
import org.smslib.Library;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.modem.SerialModemGateway;
public class Sms{
public void doIt() throws Exception
{
OutboundNotification outboundNotification = new OutboundNotification();
System.out.println("Example: Send message from a serial gsm modem.");
System.out.println(Library.getLibraryDescription());
System.out.println("Version: " + Library.getLibraryVersion());
SerialModemGateway gateway = new SerialModemGateway("modem.com1", "COM39", 115200, "Huawei", "");
gateway.setInbound(true);
gateway.setOutbound(true);
gateway.setSimPin("0000");
gateway.setSmscNumber("+947100003");
Service.getInstance().setOutboundMessageNotification(outboundNotification);
Service.getInstance().addGateway(gateway);
Service.getInstance().startService();
System.out.println();
System.out.println("Modem Information:");
System.out.println(" Manufacturer: " + gateway.getManufacturer());
System.out.println(" Model: " + gateway.getModel());
System.out.println(" Serial No: " + gateway.getSerialNo());
System.out.println(" SIM IMSI: " + gateway.getImsi());
System.out.println(" Signal Level: " + gateway.getSignalLevel() + " dBm");
System.out.println(" Battery Level: " + gateway.getBatteryLevel() + "%");
System.out.println();
// Send a message synchronously.
OutboundMessage msg = new OutboundMessage("+94755466860", "Hello from SMSLib!");
Service.getInstance().sendMessage(msg);
System.out.println(msg);
System.out.println("Now Sleeping - Hit <enter> to terminate.");
System.in.read();
Service.getInstance().stopService();
}
public class OutboundNotification implements IOutboundMessageNotification{
public void process(AGateway gateway, OutboundMessage msg){
System.out.println("Outbound handler called from Gateway: " + gateway.getGatewayId());
System.out.println(msg);
}
}
public static void main(String args[]){
Sms app = new Sms();
try{
app.doIt();
}
catch (Exception e){
e.printStackTrace();
}
}
}
I get the following error
log4j:WARN No appenders could be found for logger (smslib).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "Thread-3" java.lang.ExceptionInInitializerError
at org.smslib.modem.SerialModemDriver.connectPort(SerialModemDriver.java:69)
at org.smslib.modem.AModemDriver.connect(AModemDriver.java:114)
at org.smslib.modem.ModemGateway.startGateway(ModemGateway.java:189)
at org.smslib.Service$1Starter.run(Service.java:277)
Caused by: java.lang.RuntimeException: CommPortIdentifier class not found
at org.smslib.helper.CommPortIdentifier.<clinit>(CommPortIdentifier.java:76)
... 4 more

Netbeans imported JAR not loading on run

i see this question has been posted many times but it has been solved with adding
-Djava.library.path="./path" to the VM runtime options.
I have to build an app in JAVA which uses the JNotify classes.
this is the sample code:
package test;
import net.contentobjects.jnotify.JNotify;
import net.contentobjects.jnotify.JNotifyListener;
/**
*
* #author
*/
public class Test {
public void jnotifydemo() throws Exception {
// path to watch
String path = System.getProperty("user.home");
// watch mask, specify events you care about,
// or JNotify.FILE_ANY for all events.
int mask = JNotify.FILE_CREATED
| JNotify.FILE_DELETED
| JNotify.FILE_MODIFIED
| JNotify.FILE_RENAMED;
// watch subtree?
boolean watchSubtree = true;
// add actual watch
int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener());
// sleep a little, the application will exit if you
// don't (watching is asynchronous), depending on your
// application, this may not be required
Thread.sleep(1000000);
// to remove watch the watch
boolean res = JNotify.removeWatch(watchID);
if (!res) {
// invalid watch ID specified.
}
}
class Listener implements JNotifyListener {
public void fileRenamed(int wd, String rootPath, String oldName,
String newName) {
print("renamed " + rootPath + " : " + oldName + " -> " + newName);
}
public void fileModified(int wd, String rootPath, String name) {
print("modified " + rootPath + " : " + name);
}
public void fileDeleted(int wd, String rootPath, String name) {
print("deleted " + rootPath + " : " + name);
}
public void fileCreated(int wd, String rootPath, String name) {
print("created " + rootPath + " : " + name);
}
void print(String msg) {
System.err.println(msg);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
System.out.println("Hello World");
new Test().jnotifydemo();
}
}
When i run this i get:
Error loading library, java.library.path=C:\Program Files\Java\jdk1.6.0_26\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;(continues)
Exception in thread "main" java.lang.UnsatisfiedLinkError: no jnotify in java.library.path
I have setup a Netbeans project and added the JAR file to the project so that the JAR is correctly in the lib/ folder of my project and everything is set in NETBEANS.
This correctly works if is setup the -Djava.library.path="./path" argument of the java VM, but if i imported my lib in NETBEANS that should be included in the path automatically.
I am doing something wrong or it is necessary to put every .jar in the classpath system variable? I would like to release this app so it can run on other systems that does not have JNotify in their libs.
Thanks
I am using Netbeans 7.2 on Win 7 32Bit
You are messing java jar files as library which has to be added only in netbeans classpath:
Simply in NetBeans on project properties click and adjust Library having your JAR file.
For the native libraries (so,dll,...) you need to have set: -Djava.library.path. As you did in your question.
So you have 2 steps:
1. from http://sourceforge.net/projects/jnotify/files/jnotify/jnotify-0.94/jnotify-lib-0.94.zip/download add jnotify-0.94.jar to your libraries as in picture above (this will update your classpath automatically)
2. jnotify.dll, or jnotify_64bit.dll for 64-bit windows place is some directory and ad this to your -Djava.library.path - add this to VM option of the projects property

Categories

Resources