[java]Add the jar fail,I can't ues the class - java

I have added the jar to Build path and the Reference Libraries also have the jar.IDE is the eclipse2019.9. Can you see my image?I can't sure whether it was posted
package com.itranswarp.learnjava;
import java.io.UnsupportedEncodingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Main {
static final Log log = LogFactory.getLog(Main.class);
public static void main(String[] args) {
log.info("Start process...");
try {
"".getBytes("invalidCharsetName");
} catch (UnsupportedEncodingException e) {
}
log.info("Process end.");
}
}
screenshot:This is my project structure

Please add build path.. refer image

Related

Why doesn't my external Java file get compiled by the main program, when it imports a class that I've built, even if it's in the same package?

I'm building a program that needs to compile a Java file saved in an external package and execute it. The issue that I'm having is that the external file needs to import a class that I've built, but whenever I specify the import at the beginning of the code, the main class doesn't compile the external Java file.
However, if I remove the import from the external file, it compiles without issues.
This is the code:
Main class
package zhrfrd.jrobots;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class JRobots {
public static void main(String[] args) throws IOException {
// Compile and execute external java program
try {
Process processCompilation = Runtime.getRuntime().exec("javac -d /Users/faridzouheir/eclipse-workspace/JRobots/src/ /Users/faridzouheir/eclipse-workspace/JRobots/src/zhrfrd/testjrobots/Test.java"); // Compile Test.java
processCompilation.waitFor(); // Wait until the process is terminated before starting the following process (to avoid the second process not working properly)
Process processExecution = Runtime.getRuntime().exec("java -cp /Users/faridzouheir/eclipse-workspace/JRobots/src/ zhrfrd.testjrobots.Test"); // Execute java (-cp is class path)
BufferedReader in = new BufferedReader(new InputStreamReader(processExecution.getInputStream())); // Get result of the execution of the external file
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Execution error.");
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Interrupted exception.");
}
}
}
External file to be executed (Test)
package zhrfrd.testjrobots;
import java.io.IOException;
import zhrfrd.jrobots.Robot; //This is the import that doesn't allow the compilation
public class Test{
private static final long serialVersionUID = 1L;
static Robot rob;
public static void main(String[] args) throws IOException {
Robot rob;
int a = 300;
int b = 23;
int res = doSum(a, b);
System.out.println(res);
// boom();
rob = new Robot();
rob.boom();
}
public static int doSum(int a, int b) {
return a + b;
}
}
Robot class
package zhrfrd.jrobots;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class Robot extends JLabel implements Runnable{
protected static final long serialVersionUID = 1L;
protected int life, direction, speed, posX, posY;
protected Thread threadRobot;
private Random random;
private Dimension size;
// Constructor
public Robot() throws IOException {
this.life = 100;
threadRobot = new Thread(this, "My thread");
}
// Methods
//Set robot position
public void setPosition() {
random = new Random();
posX = random.nextInt(500);
posY = random.nextInt(500);
size = this.getPreferredSize();
this.setBounds(posX, posY, size.width, size.height);
System.out.println(posX);
}
//TEST METHOD
public void boom() {
System.out.println("BOOM BOOM!!");
}
#Override
public void run () {
System.out.println(threadRobot.getName());
setPosition();
}
}
Note: I tried to move the Robot class inside the same package of the Test file but it still doesn't work. Also, in case I want to remove the main method from the Test file and make it as a subclass of Robot, is it still possible to compile it and execute it.
I finally managed to fix the issue. Inside the main class when I run the command to compile the Test class, I didn't specified the path for the Robot class (imported by the Test class):
Process processCompilation = Runtime.getRuntime().exec("javac -d /Users/faridzouheir/eclipse-workspace/JRobots/src/ /Users/faridzouheir/eclipse-workspace/JRobots/src/zhrfrd/testjrobots/Test.java");
In order to fix it I simply add it to the command:
Process processCompilation = Runtime.getRuntime().exec("javac -d /Users/faridzouheir/eclipse-workspace/JRobots/src/ /Users/faridzouheir/eclipse-workspace/JRobots/src/zhrfrd/testjrobots/Test.java");

why isn't my config file modifying my servers motd?

So as the title says I need my config file to modify my servers motd, I feel like I've done everything the right way but obviously something is wrong, so let me show you what I'm working with
me.zavage.motd.Main
package me.zavage.motd;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
#Override
public void onEnable() {
saveDefaultConfig();
}
}
me.zavage.motd.listeners.PingListener
package me.zavage.motd.listeners;
import java.io.File;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.ServerListPingEvent;
import me.zavage.motd.Main;
import me.zavage.motd.utils.Utils;
public class PingListener implements Listener {
private Main plugin;
#EventHandler
public void onPing(ServerListPingEvent e) {
e.setMaxPlayers(plugin.getConfig().getInt("maxplayers"));
e.setMotd(Utils.chat(plugin.getConfig().getString("motd" + "\n" + (Utils.chat(plugin.getConfig().getString("motd_line_2"))))));
try {
e.setServerIcon(Bukkit.loadServerIcon(new File(plugin.getConfig().getString("server_icon_path"))));
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
Then we have the config.yml
#can only be a NUMBER with NO DECIMALS!
maxplayers: ''
motd: ''
#next line on motd
motd_line_2:
#create a folder inside the first page of your server files, call it "icon" and drop you server icon in there
#server icon MUST be 64 x 64 pixels
# #NameOfIcon#
#path example "C:\Users\user\Desktop\minecraft test server\icon\icon.png
server_icon_path: ''
If the code that you show if everything that you are using, there is few issues.
You don't register the listener
package me.zavage.motd;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
#Override
public void onEnable() {
saveDefaultConfig();
getServer().getPluginManager().registerEvents(new PingListener(this), this);
}
}
You don't set the plugin variable in the listener, and you don't have constructor
public class PingListener implements Listener {
private Main plugin;
public PingListener(Main plugin) {
this.plugin = plugin;
}
}
Finally, you are searching for the motd\n motd_line_2 message. You have to use this in your ServerListPingEvent listener :
e.setMaxPlayers(plugin.getConfig().getInt("maxplayers"));
e.setMotd(Utils.chat(plugin.getConfig().getString("motd") + "\n" + plugin.getConfig().getString("motd_line_2")));
try {
e.setServerIcon(Bukkit.loadServerIcon(new File(plugin.getConfig().getString("server_icon_path"))));
} catch (Exception exc) {
exc.printStackTrace();
}

How to solve error given by eclipse on running runClient?

I am trying to make a basic mod for minecraft and am following a tutorial for the same. When I run runClient, it gives me the following error
Reference to undefined variable MC_VERSION
Here is my main.java for reference:
package rattandeep.basicmod;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import rattandeep.basicmod.proxy.CommonProxy;
import rattandeep.basicmod.util.Reference;
#Mod(modid = Reference.MOD_ID, name = Reference.NAME, version = Reference.VERSION)
public class Main {
#Instance
public static Main instance;
#SidedProxy(clientSide = Reference.CLIENT_PROXY_CLASS, serverSide = Reference.COMMON_PROXY_CLASS)
public static CommonProxy proxy;
#EventHandler
public static void PreInit(FMLPreInitializationEvent event) {
}
#EventHandler
public static void init(FMLInitializationEvent event) {
}
#EventHandler
public static void Postinit(FMLPostInitializationEvent event) {
}
}
I have searched for a solution but found none. How do I solve this?
I found out how to solve it. I just needed to change the variable value of MC_VERSION in my runClient launch file to my minecraft version.

Using Windows Task Scheduler to automate execution of WAR file

My application is written with Spring, Hibernate (JPA), JBOSS 9.0.0.GA & JBOSS EAP 6.4. In POM.xml I have specified the packaging to WAR.
I have 2 functions which I'd like to automate:
a. CSV reader - Read from CSV file and update table in DB
package com.fwd.pmap.memberInterfaceFile;
/* all imports */
public class CsvReader
{
public void importInterfaceFile() throws Exception
{
// do processing here
}
}
b. CSV Writer - Read from DB and output to CSV file
package com.fwd.pmap.memberInterfaceFile;
/* all imports */
public class CsvWriter
{
public void generateInterfaceFile() throws Exception
{
// do processing here
}
}
How can I automate both functions above to run on a specific time every day? For example:
CSV Reader to run daily # 05:00 AM
CSV Writer to run daily # 07:00 AM
Project Structure
Finally decided to use Spring Scheduling as it does not involve lots of coding as well as XML.
This is the bean class where I schedule 2 jobs to run at 5AM & 6AM daily:
package com.fwd.pmap.scheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.fwd.pmap.memberInterfaceFile.CsvReader;
import com.fwd.pmap.memberInterfaceFile.CsvWriter;;
#Component
public class MyBean {
#Scheduled(cron="0 0 5 * * *")
public void importInterfaceFile()
{
CsvReader reader = new CsvReader();
try {
reader.importInterfaceFile();
} catch (Exception e) {
e.printStackTrace();
}
}
#Scheduled(cron="0 0 6 * * *")
public void generateInterfaceFile()
{
CsvWriter writer = new CsvWriter();
try {
writer.generateInterfaceFile();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here's the config class:
package com.fwd.pmap.scheduler;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import com.fwd.pmap.scheduler.MyBean;
#Configuration
#EnableScheduling
public class SchedulerConfig implements SchedulingConfigurer {
#Bean
public MyBean bean() {
return new MyBean();
}
#Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
#Bean(destroyMethod="shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(4);
}
}
And the main class to execute the above:
package main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import com.fwd.pmap.scheduler.SchedulerConfig;
public class Main {
static Logger LOGGER = LoggerFactory.getLogger(Main.class);
#SuppressWarnings({ "unused", "resource" })
public static void main(String[] args) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(SchedulerConfig.class);
}
}

java program not able to access another class from same package when compiled from command prompt

I have two classes in a package. One class contained two methods. I am calling these methods in second class. On compiling from command prompt its showing error on first class name. Its running fine on Intellij though.
package with 2 classes - test2.java, test1.java
on compiling test1.java on cmd i m getting below error:
root#a TagPackage]# javac -classpath "/home/admin/TagAPI/lib/*" Test1.java
Test1.java:9: cannot find symbol
symbol : class Test2
location: class TagPackage.Test2
Test2 s= newTest2();
Any suggestions will be helpful.
package TagPackage;
import java.io.IOException;
public class Test2 {
public String getControlBlock(String url) throws IOException {
xcv...
}
public void validate(String url, String ResponseCB) throws
IOException, JSONException {
xzq...
}
}
package TagPackage;
import org.json.JSONException;
import java.io.IOException;
public class Test1 {
Test2 s = new Test2();
public static void main (String[] args) {
Test1 a = new Test1();
try {
a.testMethod();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Testmethod 1 out");
}
public void testMethod()throws IOException, JSONException {
String url = "dsadas";
String ResponseCB = s.getControlBlock(url);
s.validateurl, ResponseCB);
System.out.println("Testmethod 1 reached here123");
System.out.println("Testmethod 1 out");
}
You need to run the compiler from the directory that contains TestPackage, and you therefore also need to specify TestPackage/Test1.java as the file to compile.
This is all documented.
I recommend you to create a new project with default package and save your class in it.It worked for me :)

Categories