I'm writing a java program whose operation is summarized as follows:
The subfolder with the specified name is selected in the source
folder.
All the pdfs are taken and converted into txt files in
the target folder.
The name of an item is searched inside the
txt.
If the name is found then the pdf from source to target is
copied.
All the txt from the target folder are deleted, in this
way all the pdfs containing the searched word remain.
"It all works", the problem is that the txt files are not deleted from target and I can not understand why. Thanks in advance, best regards.
Launcher.java:
import java.lang.String;
import java.util.Scanner;
import java.io.File;
public class Launcher {
// campi
int status = 1;
static String source = "C:\\Users\\MyUser\\Desktop\\source\\";
static String target = "C:\\Users\\MyUser\\Desktop\\target\\";
public static void main(String [] args) {
// strings
String src = source;
String item = "";
// init
Scanner scan = new Scanner(System.in);
System.out.print("\nFornitore: ");
src += scan.nextLine().toUpperCase() + "\\";
System.out.print("Item: ");
item = scan.nextLine();
// notifier
Launcher launcher = new Launcher();
// threads
MakerThread maker = new MakerThread(launcher, src, target);
SearcherThread searcher = new SearcherThread(launcher, src, target, item);
CleanupThread cleaner = new CleanupThread(launcher, target);
// run
maker.start();
searcher.start();
cleaner.start();
}
}
MakerThread.java:
import java.io.File;
public class MakerThread extends Thread {
// campi
String src = "";
String target = "";
Launcher launcher;
// costruttore
public MakerThread(Launcher launcher, String src, String target) {
this.src = src;
this.target = target;
this.launcher = launcher;
}
// metodi
#Override
public void run() {
try{
synchronized (launcher) {
File folder = new File(this.src);
for (File f : folder.listFiles()) {
// spin-lock
while (launcher.status != 1){
launcher.wait();
}
if(f.isFile() && f.getName().endsWith("pdf")) {
System.out.println("PDF TROVATO: " + f.getName());
// input
String input = win_str(src + f.getName());
// output
String output = target;
output += f.getName().replaceAll(".pdf", ".txt");
output = win_str(output);
// command
String command = "cmd /C java -jar ./pdfbox-app-2.0.11.jar ExtractText ";
command += input + " " + output;
Process p1 = Runtime.getRuntime().exec(command);
p1.waitFor();
}
}
// set status, awake other threads
launcher.status = 2;
launcher.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}
private String win_str(String str) {
return "\"" + str + "\"";
}
}
SearcherThread.java:
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
public class SearcherThread extends Thread {
// campi
String src = "";
String target = "";
String item = "";
Launcher launcher;
// costruttore
public SearcherThread(Launcher launcher, String src, String target, String item) {
this.target = target;
this.src = src;
this.item = item;
this.launcher = launcher;
}
// metodi
#Override
public void run() {
try{
synchronized (launcher) {
File folder = new File(this.target);
for(File f : folder.listFiles()) {
// spin-lock
while (launcher.status != 2){
launcher.wait();
}
if(f.isFile() && f.getName().endsWith("txt")) {
System.out.println("SEARCHING IN: " + f.getName());
// init
String line;
BufferedReader br = new BufferedReader(new FileReader(new File(target+f.getName())));
// txt search
while((line = br.readLine()) != null) {
if(line.contains(item)) {
System.out.println(" [" + item + "]" + " trovato in " + f.getName() + "\n");
// input
String pdf = f.getName().replaceAll(".txt", ".pdf");
String input = win_str(src+pdf);
// output
String output = win_str(target);
// command
String command = "cmd /C copy " + input + " " + output;
Process p1 = Runtime.getRuntime().exec(command);
p1.waitFor();
break;
}
}
}
}
// set status, awake other threads
launcher.status = 3;
launcher.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}
private String win_str(String str) {
return "\"" + str + "\"";
}
}
CleanupThread.java:
import java.io.File;
public class CleanupThread extends Thread {
// campi
String target = "";
Launcher launcher;
// costruttore
public CleanupThread(Launcher launcher, String target) {
this.target = target;
this.launcher = launcher;
}
// metodi
#Override
public void run() {
try{
synchronized (launcher) {
File folder = new File(this.target);
for (File f : folder.listFiles()) {
// spin-lock
while (launcher.status != 3){
launcher.wait();
}
if(f.isFile() && f.getName().endsWith("txt")) {
System.out.println("CLEANING UP: " + f.getName());
// input
String input = win_str(target + f.getName());
// command
String command = "cmd /C del " + input;
Process p1 = Runtime.getRuntime().exec(command);
p1.waitFor();
}
}
// set status, awake other threads
launcher.status = 1;
launcher.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}
private String win_str(String str) {
return "\"" + str + "\"";
}
}
Related
I have a small program that attempts to allow plugins via class files copied to a specific ext directory.
The program is derived from https://javaranch.com/journal/200607/Plugins.html and I have attempted to simplify it and add on a directory scanning ability to scan packages and directories that the original code lacks.
When running the original code, it works. When I add on my directory and package scanning capability and test it on a demo package, it fails. Below are the samples.
The directory layout of the system accepting dynamically loaded class files as plugins:
testpack-+
|
+---PluginDemo.java
|
+---PluginFunction.java
The test plugin's directory layout:
b-+
|
+---Fibonacci.java
testpack-+
|
+---PluginFunction.java
The PluginDemo code with custom class loader:
package testpack;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;
public class PluginDemo extends ClassLoader {
static String pluginsDir = "ext";
static File basePluginDir = null;
File directory;
static List plugins;
public static void main(String args[]) {
PluginDemo demo = new PluginDemo();
basePluginDir = new File(System.getProperty("user.dir") + File.separator + pluginsDir);
demo.getPlugins(pluginsDir, "");
}
PluginDemo() {
plugins = new ArrayList();
}
protected void getPlugins(String directory, String parent) {
File dir = new File(System.getProperty("user.dir") + File.separator + directory);
if (dir.exists() && dir.isDirectory()) {
String[] files = dir.list();
for (int i = 0; i < files.length; i++) {
try {
// Allows recursive targetting of nested directories
String newTargetFile = System.getProperty("user.dir") + File.separator + directory + File.separator
+ files[i];
System.out.println("Targetting: " + newTargetFile);
File currentTarget = new File(newTargetFile);
if (currentTarget.isDirectory()) {
String newDirectoryTarget = directory + File.separator + files[i];
getPlugins(newDirectoryTarget, files[i]);
}
if (!files[i].endsWith(".class"))
continue;
String childFile = parent + File.separator + files[i].substring(0, files[i].indexOf("."));
Class c = loadClass(childFile);
Class[] intf = c.getInterfaces();
for (int j = 0; j < intf.length; j++) {
if (intf[j].getName().equals("PluginFunction")) {
PluginFunction pf = (PluginFunction) c.newInstance();
plugins.add(pf);
continue;
}
}
} catch (Exception ex) {
System.err.println("File " + files[i] + " does not contain a valid PluginFunction class.");
ex.printStackTrace();
}
}
}
}
public Class loadClass(String name) throws ClassNotFoundException {
return loadClass(name, true);
}
public Class loadClass(String classname, boolean resolve) throws ClassNotFoundException {
try {
Class c = findLoadedClass(classname);
if (c == null) {
try {
c = findSystemClass(classname);
} catch (Exception ex) {
}
}
if (c == null) {
String filename = classname.replace('.', File.separatorChar) + ".class";
// Create a File object. Interpret the filename relative to the
// directory specified for this ClassLoader.
File baseDir = new File(System.getProperty("user.dir"));
File f = new File(baseDir, PluginDemo.pluginsDir + File.separator + filename);
int length = (int) f.length();
byte[] classbytes = new byte[length];
DataInputStream in = new DataInputStream(new FileInputStream(f));
in.readFully(classbytes);
in.close();
c = defineClass(classname, classbytes, 0, length);
}
if (resolve)
resolveClass(c);
return c;
} catch (Exception ex) {
throw new ClassNotFoundException(ex.toString());
}
}
}
The PluginFunction interface code:
package testpack;
public interface PluginFunction {
// let the application pass in a parameter
public void setParameter (int param);
// retrieve a result from the plugin
public int getResult();
// return the name of this plugin
public String getPluginName();
// can be called to determine whether the plugin
// aborted execution due to an error condition
public boolean hasError();
}
The Fibonacci.java code:
package b;
import testpack.PluginFunction;
public class Fibonacci implements PluginFunction {
int parameter = 0;
boolean hasError = false;
public boolean hasError() {
return hasError;
}
public void setParameter (int param) {
parameter = param;
}
public int getResult() {
hasError = false;
return fib(parameter);
}
protected int fib (int n) {
if (n < 0) {
hasError = true;
return 0;
}
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fib(n-1) + fib(n-2);
}
public String getPluginName() {
return "Fibonacci";
}
}
The output with errors:
Targetting: C:\Users\Administrator\eclipse-workspace\TestPluginSystem\ext\b\Fibonacci.class
Exception in thread "main" java.lang.NoClassDefFoundError: b\Fibonacci (wrong name: b/Fibonacci)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
at testpack.PluginDemo.loadClass(PluginDemo.java:89)
at testpack.PluginDemo.loadClass(PluginDemo.java:65)
at testpack.PluginDemo.getPlugins(PluginDemo.java:47)
at testpack.PluginDemo.getPlugins(PluginDemo.java:40)
at testpack.PluginDemo.main(PluginDemo.java:19)
I would need help to get this package and directory scanning capable classloader working. Thanks.
Looking at the error and method ClassLoader.defineClass, I think the name parameter must have . as package separators, not / or \.
In your code in getPlugins the childFile is constructed using File.separator
String childFile = parent + File.separator + files[i].substring(0, files[i].indexOf("."));
Class c = loadClass(childFile);
I've tried to create a program that will read multiple text files in a certain directory and then produce a frequency of the words that appear in all the text files.
Example
text file 1: hello my name is john hello my
text file 2: the weather is nice the weather is
The output would show
hello 2
my 2
name 1
is 3
john 1
the 2
weather 2
nice 1
The issue i'm having is that my program just terminates as soon as it's ran, no output is shown at all.
Here's my class
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class WordCountstackquestion implements Runnable {
public String filename;
public WordCountstackquestion(String filename) {
this.filename = filename;
}
public void run() {
File file = new File("C:\\Users\\User\\Desktop\\files\\1.txt");
if (file.isDirectory()) {
Scanner in = null;
for (File files : file.listFiles()) {
int count = 0;
try {
HashMap<String, Integer> map = new HashMap<String, Integer>();
in = new Scanner(file);
while (in.hasNext()) {
String word = in.next();
if (map.containsKey(word)) {
map.put(word, map.get(word) + 1);
}
else {
map.put(word, 1);
}
count++;
}
System.out.println(file + " : " + count);
for (String word : map.keySet()) {
System.out.println(word + " " + map.get(word));
}
} catch (FileNotFoundException e) {
System.out.println(file + " was not found.");
}
}
}
//in.close();
}
}
Here's my class to run them
public class Mainstackquestion {
public static void main(String args[]) {
if (args.length > 0) {
for (String filename : args) {
CheckFile(filename);
}
}
else {
CheckFile("C:\\Users\\User\\Desktop\\files\\1.txt");
}
}
private static void CheckFile(String file) {
Runnable tester = new WordCountstackquestion(file);
Thread t = new Thread(tester);
t.start();
}
}
UPDATED answer. I was wrong on the original cause of the problem. The problem was more an algorithm problem than a thread-related problem.
Code for Mainstackquestion class:
public class Mainstackquestion {
public static void main(String args[])
{
List<Thread> allThreads = new ArrayList<>();
if(args.length > 0) {
for (String filename : args) {
Thread t = CheckFile(filename);
allThreads.add(t); // We save this thread for later retrieval
t.start(); // We start the thread
}
}
else {
Thread t = CheckFile("C:\\Users\\User\\Desktop\\files");
allThreads.add(t);
t.start();
}
try {
for (Thread t : allThreads) {
t.join(); // We wait for the completion of ALL threads
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static Thread CheckFile(String file) {
Runnable tester = new WordCountstackquestion(file);
return new Thread(tester);
}
}
Code for WordCountstackquestion:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class WordCountstackquestion implements Runnable {
public String filename;
public WordCountstackquestion(String filename) {
this.filename = filename;
}
public void run() {
File dir = new File(filename);
if (dir.exists() && dir.isDirectory()) {
Scanner in = null;
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (File file : dir.listFiles()) {
if (file.exists() && !file.isDirectory()) {
int count = 0;
try {
in = new Scanner(file);
while (in.hasNextLine()) {
String line = in.nextLine();
String[] words = line.split(" ");
for (String w : words) {
if (map.containsKey(w)) {
map.put(w, map.get(w) + 1);
} else {
map.put(w, 1);
}
}
count++;
}
//System.out.println(file + " : " + count);
} catch (FileNotFoundException e) {
System.out.println(file + " was not found.");
} finally {
if (in != null) {
in.close();
}
}
}
}
for (String word : map.keySet()) {
System.out.println(word + " " + map.get(word));
}
}
}
}
Tested with the same 2 files that you gave as example.
Obtained result:
the 2
name 1
weather 2
is 3
john 1
hello 2
my 2
nice 1
I have a huge CSV file ~800 K records and using that data I have to form a POST request and make a rest call.
Initially I tried WITHOUT using threads but it is taking very long time to process it.
So I thought of using threads to speed up the process and followed below approach.
divided file into relatively smaller files (Tried with 3 files with approx ~5K data each file). (I Did this Manually Before passing to application)
Created 3 threads (traditional way by extending Thread class)
Reads each file with each thread and form HashMap with details required to form request and added it to ArrayList of POST Request
Send Post request to in loop
List item
Get the Response and add it to Response List
Both above approach takes too long to even complete half (>3 hrs). Might be one of them would not be good approach.
Could anyone please provide suggestion which helps me speeding up the process ? It is NOT mandatory to use threading.
Just to add that my code is at the consumer end and does not have much control on producer end.
MultiThreadedFileRead (Main class that Extends Thread)
class MultiThreadedFileRead extends Thread
{
public static final String EMPTY = "";
public static Logger logger = Logger.getLogger(MultiThreadedFileRead.class);
BufferedReader bReader = null;
String filename = null;
int Request_Num = 0;
HashMap<Integer, String> filteredSrcDataMap = null;
List<BrandRQ> brandRQList = null;
List<BrandRS> brandRSList = null;
ReadDLShipFile readDLShipFile = new ReadDLShipFile();
GenerateAndProcessPostBrandAPI generateAndProcessPostBrandAPI = new GenerateAndProcessPostBrandAPI();
MultiThreadedFileRead()
{
}
MultiThreadedFileRead(String fname) throws Exception
{
filename = fname;
Request_Num = 0;
List<BrandRQ> brandRQList = new ArrayList<BrandRQ>();
List<BrandRS> brandRSList = new ArrayList<BrandRS>();
this.start();
}
public void run()
{
logger.debug("File *** : " + this.filename);
//Generate Source Data Map
HashMap<Integer, String> filteredSrcDataMap = (HashMap<Integer, String>) readDLShipFile.readSourceFileData(this.filename);
generateAndProcessPostBrandAPI.generateAndProcessPostRequest(filteredSrcDataMap, this);
}
public static void main(String args[]) throws Exception
{
String environment = ""; // TO BE UNCOMMENTED
String outPutfileName = ""; // TO BE UNCOMMENTED
BrandRetrivalProperties brProps = BrandRetrivalProperties.getInstance();
if(args != null && args.length == 2 && DLPremiumUtil.isNotEmpty(args[0]) && DLPremiumUtil.isNotEmpty(args[1])) // TO BE UNCOMMENTED
{
environment = args[0].trim();
outPutfileName = args[1].trim();
ApplicationInitializer applicationInitializer = new ApplicationInitializer(environment);
applicationInitializer.initializeParams();
logger.debug("Environment : " + environment);
logger.debug("Filename : " + outPutfileName);
// TO BE UNCOMMENTED - START
}else{
System.out.println("Invalid parameters passed. Expected paramenters: Environment");
System.out.println("Sample Request: java -jar BrandRetrival.jar [prd|int] brand.dat");
System.exit(1);
}
MultiThreadedFileRead multiThreadedFileRead = new MultiThreadedFileRead();
List<String> listOfFileNames = multiThreadedFileRead.getFileNames(brProps);
logger.debug("List : " + listOfFileNames);
int totalFileSize = listOfFileNames.size();
logger.debug("totalFileSize : " + totalFileSize);
MultiThreadedFileRead fr[]=new MultiThreadedFileRead[totalFileSize];
logger.debug("Size of Array : " + fr.length);
for(int i = 0; i < totalFileSize; i++)
{
logger.debug("\nFile Getting Added to Array : " + brProps.getCountFilePath()+listOfFileNames.get(i));
fr[i]=new MultiThreadedFileRead(brProps.getCountFilePath()+listOfFileNames.get(i));
}
}
public List<String> getFileNames(BrandRetrivalProperties brProps)
{
MultiThreadedFileRead multiThreadedFileRead1 = new MultiThreadedFileRead();
BufferedReader br = null;
String line = "";
String filename = multiThreadedFileRead1.getCounterFileName(brProps.getCountFilePath(), brProps.getCountFilePathStartsWith());
List<String> fileNameList = null;
logger.debug("filename : " + filename);
if(filename != null)
{
fileNameList = new ArrayList<String>();
try{
br = new BufferedReader(new FileReader(brProps.getCountFilePath()+filename));
while ((line = br.readLine()) != null)
{
fileNameList.add(line);
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block ;
e2.printStackTrace();
} catch (Exception e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
} finally
{
if (br != null)
{
try
{
br.close();
} catch (IOException e4)
{
e4.printStackTrace();
} catch (Exception e5)
{
e5.printStackTrace();
}
}
}
}
return fileNameList;
}
// Get the Name of the file which has name of individual CSV files to read to form the request
public String getCounterFileName(String sourceFilePath, String sourceFileNameStartsWith)
{
String fileName = null;
if(sourceFilePath != null && !sourceFilePath.equals(EMPTY) &&
sourceFileNameStartsWith != null && !sourceFileNameStartsWith.equals(EMPTY))
{
File filePath = new File(sourceFilePath);
File[] listOfFiles = filePath.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile() && listOfFiles[i].getName().startsWith(sourceFileNameStartsWith)) {
fileName = listOfFiles[i].getName();
} else if (listOfFiles[i].isDirectory()) {
fileName = null;
}
}
}
return fileName;
}
}
GenerateAndProcessPostBrandAPI
public class GenerateAndProcessPostBrandAPI {
public static Logger logger = Logger.getLogger(GenerateAndProcessPostBrandAPI.class);
List<BrandRQ> brandRQList = new ArrayList<BrandRQ>();
List<BrandRS> brandRSList = new ArrayList<BrandRS>();
DLPremiumClientPost dlPremiumclientPost = new DLPremiumClientPost();
JSONRequestGenerator jsonRequestGenerator = new JSONRequestGenerator();
public List<BrandRQ> getBrandRequstList(Map<Integer, String> filteredSrcDataMap)
{
if(filteredSrcDataMap != null)
{
brandRQList = jsonRequestGenerator.getBrandRQList(filteredSrcDataMap, brandRQList);
}
return brandRQList;
}
public void generateAndProcessPostRequest(Map<Integer, String> filteredSrcDataMap, MultiThreadedFileRead multiThreadedFileRead)
{
if(filteredSrcDataMap != null)
{
brandRQList = jsonRequestGenerator.getBrandRQList(filteredSrcDataMap, brandRQList);
if(brandRQList != null && brandRQList.size() > 0)
{
BrandRetrivalProperties brProps = BrandRetrivalProperties.getInstance();
String postBrandsEndpoint = brProps.getPostBrandsEndPoint();
for (BrandRQ brandRQ : brandRQList)
{
multiThreadedFileRead.Request_Num = multiThreadedFileRead.Request_Num + 1;
logger.debug("Brand Request - " + multiThreadedFileRead.Request_Num + " : " + ObjectToJSONCovertor.converToJSON(brandRQ));
BrandRS brandResponse = dlPremiumclientPost.loadBrandApiResponseJSON(brandRQ, postBrandsEndpoint, DLPremiumUtil.getTransactionID(), BrandConstants.AUTH_TOKEN);
logger.debug("Response - " + multiThreadedFileRead.Request_Num + " : " + ObjectToJSONCovertor.converToJSON(brandResponse));
brandRSList.add(brandResponse);
}
}
}
}
}
RMIclient,
THIS IS THE CLIENT
package rmiclient;
import java.rmi.RMISecurityManager;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.*;
public class RMIClient {
public static void main(String[] args) {
RMIClient client = new RMIClient();
System.setSecurityManager(new RMISecurityManager());
if(args.length == 0)
{
System.out.println("Please enter the correct server, exiting.");
System.exit(0);
}
client.runMenu(args);
}//end Main()
public void runMenu(String[] args) {
while (true) {
int commandToRun = 0;
int numberOfThreads;
Scanner commandScanner = new Scanner(System.in);
Scanner threadScanner = new Scanner(System.in);
System.out.println();
System.out.println("Enter the number for the command that you wish to execute.");
System.out.println("1. Date & Time \n"
+ "2. Server Uptime \n"
+ "3. Memory Usage \n"
+ "4. Netstat \n"
+ "5. Current Users \n"
+ "6. Running processes \n"
+ "7. Exit");
commandToRun = commandScanner.nextInt();
System.out.println();
if (commandToRun == 7) {
System.out.println("Exiting");
System.exit(0);
} else if(commandToRun > 7 || commandToRun < 1) {
System.out.println("Enter a valid command");
}
/* else {
if(commandToRun == 1 || commandToRun == 4)
{
System.out.println("Enter number of threads to run");
numberOfThreads = threadScanner.nextInt();
clientThreads thread[] = new clientThreads[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++) {
thread[i] = new clientThreads(args, commandToRun);
}
for (int i = 0; i < numberOfThreads; i++) {
thread[i].start();
try{
thread[i].join();
}
catch(Exception e){}
}
}
else{
numberOfThreads = 1;
clientThreads thread[] = new clientThreads[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++) {
thread[i] = new clientThreads(args, commandToRun);
}
for (int i = 0; i < numberOfThreads; i++) {
thread[i].start();
try{
thread[i].join();
}
catch(Exception e){}}
}*/
}
}
}
class clientThreads extends Thread {
int commandToRun;
String host;
public clientThreads(String[] args, int commandToRun) {
this.commandToRun = commandToRun;
this.host = args[0];
}
public void run() {
String serverResponse = "";
try {
Registry registry = LocateRegistry.getRegistry(1225);
RMIInterface stub = (RMIInterface)registry.lookup("runCommand");
serverResponse = stub.runCommand(commandToRun);
} catch (Exception e) {
System.out.println(e);
}
System.out.println();
System.out.println(serverResponse);
}
}
RMIINTERFACE, Interface
package rmiclient;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RMIInterface extends Remote {
String runCommand(int commandToRun) throws RemoteException;
}
RMIserver, this is the server
package rmiserver;
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
//import java.rmi.RMISecurityManager;
import java.io.*;
public class RMIServer implements RMIInterface {
public RMIServer() {}
public static void main(String[] args) {
try {
RMIServer obj = new RMIServer();
// System.setSecurityManager(new RMISecurityManager());
RMIInterface stub = (RMIInterface) UnicastRemoteObject.exportObject(obj, 0);
Registry registry = LocateRegistry.getRegistry(1225);
registry.rebind("runCommand", stub);
System.out.println("Server starting");
} catch (Exception e) {
System.out.println(e);
}
}
public String runCommand(int commandToRun) throws RemoteException {
Runtime runtime = null;
Process process = null;
String command = "";
String output = "";
String newLine = "";
BufferedReader inp = null;
try {
if (commandToRun == 1) {
System.out.println("Running command: Date and Time");
runtime = Runtime.getRuntime();
command = "date";
process = runtime.exec(command);
inp = new BufferedReader(new InputStreamReader(process.getInputStream()));
output = inp.readLine();
} else if (commandToRun == 2) {
System.out.println("Running command: Uptime");
runtime = Runtime.getRuntime();
command = "uptime";
process = runtime.exec(command);
inp = new BufferedReader(new InputStreamReader(process.getInputStream()));
output = inp.readLine();
} else if (commandToRun == 3) {
System.out.println("Running command: Memory Use");
runtime = Runtime.getRuntime();
command = "free";
process = runtime.exec(command);
inp = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((newLine = inp.readLine()) != null) {
output = output + "\n" + newLine;
}
} else if (commandToRun == 4) {
System.out.println("Running command: Netstat");
runtime = Runtime.getRuntime();
command = "netstat";
process = runtime.exec(command);
inp = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((newLine = inp.readLine()) != null) {
output = output + "\n" + newLine;
}
} else if (commandToRun == 5) {
System.out.println("Running command: Current Users");
runtime = Runtime.getRuntime();
command = "who";
process = runtime.exec(command);
inp = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((newLine = inp.readLine()) != null) {
output = output + "\n" + newLine;
}
} else if (commandToRun == 6) {
System.out.println("Running command: Running Processes");
runtime = Runtime.getRuntime();
command = "ps -e";
process = runtime.exec(command);
inp = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((newLine = inp.readLine()) != null) {
output = output + "\n" + newLine;
}
}
} catch (Exception e) {
System.out.println(e);
}
return output;
}
}
Please help, i feel like i'm pretty close to getting the client and server. were pretty close to getting them connected utilizing the SSH secure shell.
after the client and server start communicating it should be easy to finish this program, when finished it will be able to take input from client (a number 1-10) and based off that number give the response from the server.
I am writing Java application and I want to write some simple plugin system. I want to have base class Plugin. Other classes extends Plugin, these files are in some other directory out of class path.
public class Plugin {
public Plugin() {
//code
}
public void proc() {
//code
}
}
and class loader:
public class PluginLoader {
private static final FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return Pattern.matches("^.*[a-zA-Z]*[.]class$", name);
}
};
public static final String removeExtension(String str) {
if (str == null)
return null;
int pos = str.lastIndexOf(".");
if (pos == -1)
return str;
return str.substring(0, pos);
}
#SuppressWarnings("unchecked")
public static LinkedList<Plugin> loadEffects(String path) {
LinkedList<Plugin> result = new LinkedList<Plugin>();
Plugin instance = null;
File[] classesList = null;
System.out.println("Searching in " + path);
try {
File classDir = new File(path);
URL[] url = { classDir.toURI().toURL() };
URLClassLoader urlLoader = new URLClassLoader(url);
String filename;
classesList = classDir.listFiles(filter);
System.out.println(classesList.length + " class files found:");
for (File file : classesList) {
System.out.println("- " + file.getName());
}
for (File file : classesList) {
filename = removeExtension(file.getName());
if (filename.equals(".") || filename.equals("..") || filename.startsWith("."))
continue;
if (filename.equals("Plugin")) {
System.err.println("File name is Plugin");
continue;
}
System.out.println("Reading " + filename);
instance = (Plugin) urlLoader.findClass(filename).getConstructor().newInstance();
System.out.println("Adding: " + url + ", " + filename);
result.push(instance);
}
urlLoader.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
This code causes java.lang.NoClassDefFoundError: D:\test\PluginImpl/class (wrong name: test/PluginImpl). Plugin class is in D:\test.
You are calling File#getAbsolutePath() which will include the entire path and the drive letter (D:\). The class name stored in the class does not match with the class name you provided so Java throws an error.
Try calling findClass with just the class name and it should work