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();
}
Related
I just wrote this code here:
package SpellcheckerClient;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
BorderPane root = FXMLLoader.load(getClass().getResource("/controller/gui.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.setTitle("Spellchecker Client");
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
And this is the corresponding controller.
package controller;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import spellchecker.remote.SpellcheckerRemoteAdapter;
public class Controller {
#FXML
TextField input;
#FXML
Button send;
#FXML
TextArea area;
#FXML
Button connect;
private SpellcheckerRemoteAdapter adapter;
#FXML
private void send() throws RemoteException{
String toCheck = input.getText();
this.area.appendText(toCheck + "\n");
this.area.appendText(checkRoutine(toCheck, this.adapter) + "\n\n");
this.input.clear();
}
public void initiateConnection() {
try {
Registry registry = LocateRegistry.getRegistry(1088);
this.adapter = (SpellcheckerRemoteAdapter) registry.lookup(SpellcheckerRemoteAdapter.NAME);
this.area.appendText("Verbindung erfolgreich aufgebaut!\n");
connect.setDisable(true);
} catch (Exception e) {
if(this.adapter == null) {
this.area.appendText("Server nicht gefunden!\n");
}
}
}
private static String checkRoutine(String input, SpellcheckerRemoteAdapter adapter) throws RemoteException {
if (input == null || input.isEmpty()) {
return "Bitte etwas eingeben!";
}
String[] words = input.split(" ");
boolean control = true;
String output = "";
for(String word : words) {
if(!adapter.check(word)) {
control = false;
output += word + ":\t" + adapter.getProposal(word) + "\n";
}
}
if(control) {
return "Alles Okay!\n";
}
return output;
}
}
If I run this code on my Laptop, where I wrote it, it runs perfectly fine in Eclipse and as runnable Jar. However, if I try to run the JAR on another computer i receive this error message:
Exception in thread "WindowsNativeRunloopThread" java.lang.NoSuchMethodError: <init>
at javafx.graphics/com.sun.glass.ui.win.WinApplication.staticScreen_getScreens(Native Method)
at javafx.graphics/com.sun.glass.ui.Screen.initScreens(Unknown Source)
at javafx.graphics/com.sun.glass.ui.Application.lambda$run$1(Unknown Source)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Exception in thread "WindowsNativeRunloopThread" java.lang.NoSuchMethodError: <init>
at javafx.graphics/com.sun.glass.ui.win.WinApplication.staticScreen_getScreens(Native Method)
at javafx.graphics/com.sun.glass.ui.Screen.initScreens(Unknown Source)
at javafx.graphics/com.sun.glass.ui.Application.lambda$run$1(Unknown Source)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at javafx.graphics/com.sun.prism.d3d.D3DPipeline.getAdapterOrdinal(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.assignScreensAdapters(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runToolkit(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$startup$10(Unknown Source)
at javafx.graphics/com.sun.glass.ui.Application.lambda$run$1(Unknown Source)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
On my Laptop and my Computer are the same Versions of the JDK/JRE installed.
I don't really get what the error message is telling me.
Hello I have the same issue on my Eclipse environnement (Windows 10 OS),
adding in VM option -Djava.library.path="C:\WINDOWS\Sun\Java\bin" solved my problem
That means that javafx-graphics-[version]-win.jar call some native dll. And You have to found were those dll is stored.
I found the path, thanks to jvisualvm and showing the VM option for the case where it's the application run correctly.
Hoping that it will solve your problem.
Which JDk you have installed?? I have the same issue and i use JDK 8 instead of JDK 9. Which helped me.Sample Image of Exception
This is because jar which i created it was created on JDK 8 through a different system.
Where as when it was executing on another system which has JDK9. So it is version incompatible.
After keeping single JDK 8 and mapped it to system environment when i try to run my jar it worked for me.
Good Luck :)
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.
i am new in java... i am trying to read on modbus. PLC is slave device and it is configured well. my java file is unable to read modbus values.here is the code..given below. error is coming at master.init(); method. please help me in this case.
package com.mod4j;
import java.io.File;
import gnu.io.SerialPort;
import com.serotonin.io.serial.SerialParameters;
import com.serotonin.*;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.code.DataType;
import com.serotonin.modbus4j.code.RegisterRange;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.locator.BaseLocator;
import com.serotonin.modbus4j.locator.NumericLocator;
import com.serotonin.modbus4j.msg.ReadCoilsRequest;
import com.serotonin.modbus4j.msg.ReadCoilsResponse;
import com.serotonin.modbus4j.msg.ReadDiscreteInputsRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;
import com.serotonin.modbus4j.msg.ReadInputRegistersRequest;
import com.serotonin.modbus4j.msg.ReadInputRegistersResponse;
import com.serotonin.modbus4j.msg.WriteCoilRequest;
import com.serotonin.modbus4j.msg.WriteCoilResponse;
import com.serotonin.modbus4j.msg.WriteRegistersRequest;
import com.serotonin.modbus4j.msg.WriteRegistersResponse;
import gnu.io.*;
public class Modbus4JTest
{
public static void main(String[] args) throws Exception
{
try
{
SerialParameters params = new SerialParameters();
params.setCommPortId("COM1");
params.setBaudRate(9600);
params.setDataBits(8);
params.setStopBits(1);
params.setParity(0);
ModbusFactory modbusFactory = new ModbusFactory();
ModbusMaster master = modbusFactory.createRtuMaster(params);
master.setTimeout(100);
master.setRetries(3);
byte [] RIR,RHR,RDI,RCR;
int slaveId=1;
int startOffset=0;
int numberOfRegisters=10;
int numberOfBits=10;
try
{
master.init();
while (true)
{
ReadInputRegistersRequest reqRIR = new ReadInputRegistersRequest(slaveId, startOffset, numberOfRegisters);
System.out.println("ReadInputRegistersRequest reqRIR =" +reqRIR);
ReadInputRegistersResponse resRIR = (ReadInputRegistersResponse) master.send(reqRIR);
RIR = resRIR.getData();
System.out.println("InputRegisters :" + RIR);
ReadHoldingRegistersRequest reqRHR = new ReadHoldingRegistersRequest(slaveId, startOffset, numberOfRegisters);
ReadHoldingRegistersResponse resRHR = (ReadHoldingRegistersResponse) master.send(reqRHR);
RHR=resRHR.getData();
System.out.println("HoldingRegister :" + RHR);
ReadDiscreteInputsRequest reqRDI= new ReadDiscreteInputsRequest(slaveId, startOffset, numberOfBits);
ReadCoilsResponse resRDI = (ReadCoilsResponse) master.send(reqRDI);
RDI=resRDI.getData();
System.out.println("DiscreteInput :" + RDI);
ReadCoilsRequest reqRCR = new ReadCoilsRequest(slaveId, startOffset, numberOfBits);
ReadCoilsResponse resRCR = (ReadCoilsResponse) master.send(reqRCR);
RCR=resRCR.getData();
System.out.println("CoilResponce :" + RCR);
short[] sdata = null;
WriteRegistersRequest reqWR = new WriteRegistersRequest(slaveId, startOffset, sdata);
WriteRegistersResponse resWR = (WriteRegistersResponse) master.send(reqWR);
int writeOffset = 0;
boolean writeValue = true;
WriteCoilRequest reqWC = new WriteCoilRequest(slaveId, writeOffset, writeValue);
WriteCoilResponse resWC = (WriteCoilResponse) master.send(reqWC);
Thread.sleep(1000);
}//end while
}//end try
catch (Exception e)
{
e.printStackTrace();
}//end catch
finally
{
master.destroy();
}//end finally
}//end try
catch (Exception e)
{
e.printStackTrace();
}//end catch
}// end main
}//end class Modbus4JTest
this is java file i am running.
and here are the error i have got after compiling..
please suggest what went wrong and please correct me at ...
is there any step by step tutorial or any demo video please give me link at
ayyaz.nadaf#gmail.com
Exception in thread "main" java.lang.NoClassDefFoundError:
jssc/SerialPortException
at com.serotonin.io.serial.SerialUtils.openSerialPort(SerialUtils.java:94)
at com.serotonin.modbus4j.serial.SerialMaster.init(SerialMaster.java:58)
at com.serotonin.modbus4j.serial.rtu.RtuMaster.init(RtuMaster.java:45)
at com.mod4j.Modbus4JTest.main(Modbus4JTest.java:58)
Caused by: java.lang.ClassNotFoundException: jssc.SerialPortException
at java.net.URLClassLoader$1.run(Unknown Source)
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)
... 4 more
It appears you're using Modbus4J. It is based on jSSC (Java Simple Serial Connector) for serial communication, so make sure that jSSC is found while compiling (you may need to download it separately, since you're getting a ClassNotFoundException related to a jSSC class).
I don't know about any tutorial but I may suggest you to take a look at the Modbus4J forum archive. Here's a simple Modbus RTU example.
I don't know why my code java is not compiled.
I need to index my database with solr.
I launch my server with line commande .
>cd C:\Solr\solr-4.10.0\solr-4.10.0\example\solr
>java -jar start.jar
After that i create a new project that contain my class to index database with solr.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
//import org.apache.lucene.index.IndexWriter;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;// CommonsHttpSolrServer;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest.ACTION;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
public class IndexFiles {
public static void main(String[] args) {
HttpSolrServer server = new HttpSolrServer("http://localhost:8983/solr/");
// i use SolrServer but it generate same error like this from httpSolrServer
//SolrServer solr = new HttpSolrServer("http://localhost:8983/solr");
/*
// TODO Auto-generated method stub
String urlString = "http://localhost:8989/solr";
if (args != null & args.length > 1) {
urlString = args[1];
}
SolrServer solr = new HttpSolrServer("http://localhost:8983/solr"); //CommonsHttpSolrServer(urlString);
try {
indexDocs(solr, new File(args[0]));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
}
I get this error :
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/NoHttpResponseException
at IndexFiles.main(IndexFiles.java:23)
Caused by: java.lang.ClassNotFoundException: org.apache.http.NoHttpResponseException
at java.net.URLClassLoader$1.run(Unknown Source)
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)
... 1 more
How to resolve this problem?
Sounds like you haven't added the httpclient jar (from dist/solrj-lib) to your classpath.
See the Solrj wiki page topic about: Setting the Classpath
I have downloaded the google data API plugin for eclipse. While dealing with the Contacts template (Demo.java)
/* INSTRUCTION: This is a command line application. So please execute this template with the following arguments:
arg[0] = username
arg[1] = password
*/
/**
* #author (Your Name Here)
*
*/
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
/**
* This is a test template
*/
public class Contacts {
public static void main(String[] args) {
try {
// Create a new Contacts service
ContactsService myService = new ContactsService("My Application");
myService.setUserCredentials(args[0],args[1]);
// Get a list of all entries
URL metafeedUrl = new URL("http://www.google.com/m8/feeds/contacts/"+args[0]+"#gmail.com/base");
System.out.println("Getting Contacts entries...\n");
ContactFeed resultFeed = myService.getFeed(metafeedUrl, ContactFeed.class);
List<ContactEntry> entries = resultFeed.getEntries();
for(int i=0; i<entries.size(); i++) {
ContactEntry entry = entries.get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
System.out.println("\nTotal Entries: "+entries.size());
}
catch(AuthenticationException e) {
e.printStackTrace();
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(ServiceException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
it is getting compiled successfully, but throwing this runtime exception (i am providing correct required credentials as arguments).
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/collect/Maps
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:118)
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:100)
at com.google.gdata.client.Service.<clinit>(Service.java:532)
at Contacts.main(Contacts.java:36)
Caused by: java.lang.ClassNotFoundException: com.google.common.collect.Maps
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)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 4 more
I am sure, i am missing something, but enable to resolve it.
You seem to be missing a dependency. Download this google-collections and add the jar to your build-path.