I'm trying to parse the start args in my application, but apache cli do not recognize them:
public static void main(String[] args) {
logger.debug(Arrays.toString(args)); // prints
CommandLine cmdLine = null;
HelpFormatter formatter = new HelpFormatter();
CommandLineParser parser = new BasicParser();
Options options = new Options();
options.addOption("k", true, "bla");
try {
cmdLine = parser.parse(options, args);
logger.debug("main - {}", cmdLine.hasOption("k")); // prints false
} catch (ParseException e) {
e.printStackTrace();
}
}
In Eclispe (Runconfiguration -> Arguments) I'm starting the application with k=hello
My output:
2016-07-08 15:39:34,840 DEBUG [main] (Main.java:27) - [k=hello]
2016-07-08 15:39:34,862 DEBUG [main] (Main.java:53) - main - false
The argument should be "-k hello"
Related
so i have problem where i am trying to open a file through my own written virtual machine object in java but the problem is that the virtual machine is not running and causing an error.
Error: Could not find or load main class C:\Users\dell\Trace\Main.java
we also tried modifying the CLASSPATH & PATH with no success
below is the code of the main
import com.sun.jdi.Bootstrap;
import com.sun.jdi.connect.*;
import java.util.Map;
import java.util.List;
import java.util.Iterator;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Trace {
// Running remote VM
private final VirtualMachine vm;
// Thread transferring remote error stream to our error stream
private Thread errThread = null;
// Thread transferring remote output stream to our output stream
private Thread outThread = null;
// Mode for tracing the Trace program (default= 0 off)
private int debugTraceMode = 0;
// Do we want to watch assignments to fields
private boolean watchFields = false;
// Class patterns for which we don't want events
private String[] excludes = {"java.*", "javax.*", "sun.*",
"com.sun.*"};
/**
* main
*/
public static void main(String[] args) {
new Trace(args);
}
/**
* Parse the command line arguments.
* Launch target VM.
* Generate the trace.
*/
Trace(String[] args) {
PrintWriter writer = new PrintWriter(System.out);
int inx;
for (inx = 0; inx < args.length; ++inx) {
String arg = args[inx];
if (arg.charAt(0) != '-') {
break;
}
if (arg.equals("-output")) {
try {
writer = new PrintWriter(new FileWriter(args[++inx]));
} catch (IOException exc) {
System.err.println("Cannot open output file: " + args[inx]
+ " - " + exc);
System.exit(1);
}
} else if (arg.equals("-all")) {
excludes = new String[0];
} else if (arg.equals("-fields")) {
watchFields = true;
} else if (arg.equals("-dbgtrace")) {
debugTraceMode = Integer.parseInt(args[++inx]);
} else if (arg.equals("-help")) {
usage();
System.exit(0);
} else {
System.err.println("No option: " + arg);
usage();
System.exit(1);
}
}
if (inx >= args.length) {
System.err.println("<class> missing");
usage();
System.exit(1);
}
StringBuffer sb = new StringBuffer();
sb.append(args[inx]);
for (++inx; inx < args.length; ++inx) {
sb.append(' ');
sb.append(args[inx]);
}
vm = launchTarget(sb.toString());
generateTrace(writer);
}
/**
* Generate the trace.
* Enable events, start thread to display events,
* start threads to forward remote error and output streams,
* resume the remote VM, wait for the final event, and shutdown.
*/
void generateTrace(PrintWriter writer) {
vm.setDebugTraceMode(debugTraceMode);
EventThread eventThread = new EventThread(vm, excludes, writer);
eventThread.setEventRequests(watchFields);
eventThread.start();
redirectOutput();
vm.resume();
// Shutdown begins when event thread terminates
try {
eventThread.join();
errThread.join(); // Make sure output is forwarded
outThread.join(); // before we exit
} catch (InterruptedException exc) {
// we don't interrupt
}
writer.close();
}
/**
* Launch target VM.
* Forward target's output and error.
*/
VirtualMachine launchTarget(String mainArgs) {
LaunchingConnector connector = findLaunchingConnector();
Map arguments = connectorArguments(connector, mainArgs);
try {
return connector.launch(arguments);
} catch (IOException exc) {
throw new Error("Unable to launch target VM: " + exc);
} catch (IllegalConnectorArgumentsException exc) {
throw new Error("Internal error: " + exc);
} catch (VMStartException exc) {
throw new Error("Target VM failed to initialize: " +
exc.getMessage());
}
}
void redirectOutput() {
Process process = vm.process();
// Copy target's output and error to our output and error.
errThread = new StreamRedirectThread("error reader",
process.getErrorStream(),
System.err);
outThread = new StreamRedirectThread("output reader",
process.getInputStream(),
System.out);
errThread.start();
outThread.start();
}
/**
* Find a com.sun.jdi.CommandLineLaunch connector
*/
LaunchingConnector findLaunchingConnector() {
List connectors = Bootstrap.virtualMachineManager().allConnectors();
Iterator iter = connectors.iterator();
while (iter.hasNext()) {
Connector connector = (Connector)iter.next();
if (connector.name().equals("com.sun.jdi.CommandLineLaunch")) {
return (LaunchingConnector)connector;
}
}
throw new Error("No launching connector");
}
/**
* Return the launching connector's arguments.
*/
Map connectorArguments(LaunchingConnector connector, String mainArgs) {
Map arguments = connector.defaultArguments();
Connector.Argument mainArg =
(Connector.Argument)arguments.get("main");
if (mainArg == null) {
throw new Error("Bad launching connector");
}
mainArg.setValue(mainArgs);
if (watchFields) {
// We need a VM that supports watchpoints
Connector.Argument optionArg =
(Connector.Argument)arguments.get("options");
if (optionArg == null) {
throw new Error("Bad launching connector");
}
optionArg.setValue("-classic");
}
return arguments;
}
/**
* Print command line usage help
*/
void usage() {
System.err.println("Usage: java Trace <options> <class> <args>");
System.err.println("<options> are:");
System.err.println(
" -output <filename> Output trace to <filename>");
System.err.println(
" -all Include system classes in output");
System.err.println(
" -help Print this help message");
System.err.println("<class> is the program to trace");
System.err.println("<args> are the arguments to <class>");
}
}
HI Can you tell me please where do I put the logger code in the constructor file?
Logger logger = Logger.getLogger("MyLog");
// This block configures the logger with handler and formatter
FileHandler fh = new FileHandler("C:/temp/test/MyLogFile.log");
logger.addHandler(fh);
Project is failing in the read here:
_internal_parameter_table.clear();
_internal_parameter_table.put("OPOPTT", 2);
_internal_parameter_table.put("OPOPID", templateName);
srbopt.read(_internal_parameter_table, 1);
defaultNameSrbnax01 = defaultNameSrbnax01.set(srbopt
.getBy("OPDF01"));
defaultNameSrbnox02 = defaultNameSrbnox02.set(srbopt
.getBy("OPDF02"));
defaultNameSrbcmx06 = defaultNameSrbcmx06.set(srbopt
.getBy("OPDF06"));
defaultNameSrbtpdx15 = defaultNameSrbtpdx15.set(srbopt
.getBy("OPDF15"));
defaultNameSrbnax01 = defaultNameSrbnax01.set(defaultNameSrbnax01
.trimBlanks(true, true, false, false, false));
defaultNameSrbnox02 = defaultNameSrbnox02.set(defaultNameSrbnox02
.trimBlanks(true, true, false, false, false));
defaultNameSrbcmx06 = defaultNameSrbcmx06.set(defaultNameSrbcmx06
.trimBlanks(true, true, false, false, false));
defaultNameSrbtpdx15 = defaultNameSrbtpdx15
.set(defaultNameSrbtpdx15.trimBlanks(true, true, false,
false, false));
Try this sample. It works for me.
public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("C:/temp/test/MyLogFile.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.info("My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Hi How r u?");
}
Produces the output at MyLogFile.log
Jan 2, 2016 9:57:08 AM testing.MyLogger main
INFO: My first log
Jan 2, 2016 9:57:08 AM testing.MyLogger main
INFO: Hi How r u?
To remove the console handler, use
logger.setUseParentHandlers(false);
since the ConsoleHandler is registered with the parent logger from which all the loggers derive.
I am trying to do a chaning Job.
So to some point I want to access the args (public static void main(String[] args)).
say args[0] in mapper.
Is there a way to access those values in mapper rather than sending them to function and accessing?
Alternative Solution
conf.set("args", args[1]);
job1.setJarByClass(BinningDriver.class);
FileSystem fs1 = FileSystem.get(conf);
job1.setOutputKeyClass(Text.class);
job1.setOutputValueClass(Text.class);
job1.setMapperClass(BinningInput.class);
job1.setInputFormatClass(TextInputFormat.class);
job1.setOutputFormatClass(TextOutputFormat.class);
Path out = new Path(args[1]+"/Indexing"); //Output goes to user output location/indexing
if(fs1.exists(out)){
fs1.delete(out,true);
}
FileInputFormat.addInputPath(job1, new Path(args[0]));
FileOutputFormat.setOutputPath(job1, out);
}
Mapper
public void setup(Context context){
Configuration conf = context.getConfiguration();
String param = conf.get("args");
System.out.println("args:"+param);
}
This Works
Args[] is the input parameter of the main function of the Driver class. The only way to access this parameter is from within the Driver (the scope of this parameter is only the main function). So, if you want to pass these to the mapper, you will need to pass them as parameters (e.g. add this information to the Distributed Cache and get it from the configuration of the mappers).
If you simply want to pass some parameters, check this article, and replace "123" with args[2], or whatever arg you are interested in.
If you want to pass a whole file for processing, do the following:
Example:
main method in the Driver class:
public static void main(String[] args) {
...
FileInputFormat.setInputPaths(conf, new Path(args[0]));
FileOutputFormat.setOutputPath(conf, new Path(args[1]));
...
try {
DistributedCache.addCacheFile(new URI(args[2]), conf);
} catch (URISyntaxException e) {
System.err.println(e.toString());
}
....
}
In the Mapper, before the map() method, define the configure method (I am using hadoop 1.2.0):
Set<String> lines;
public void configure(JobConf job){
lines = new HashSet<>();
BufferedReader SW;
try {
localFiles = DistributedCache.getLocalCacheFiles(job);
SW = new BufferedReader(new FileReader(localFiles[0].toString()));
lines.add(SW.readLine());
SW.close();
} catch (FileNotFoundException e) {
System.err.println(e.toString());
} catch (IOException e) {
System.err.println(e.toString());
}
}
For more information on how to use the Distributed Cache, see the API:
http://hadoop.apache.org/docs/stable/api/org/apache/hadoop/filecache/DistributedCache.html
Alright, i'm trying to Xbootclasspath a jar from within my project. Currently I have to load my application through command-line with the follow command:
java -Xbootclasspath/p:canvas.jar -jar application.jar
This works perfectly fine but I want to do this without having to enter command line, is there I way I can Xbootclasspath from within the jar?
Thanks.
The most clear solution is to have two main classes.
Your first class, named Boot or similar, will be the outside entry point into the application, as set in the jar's manifest. This class will form the necessary runtime command to start your actual main class (named Application or similar), with the Xboot parameter.
public class Boot {
public static void main(String[] args) {
String location = Boot.class.getProtectionDomain().getCodeSource().getLocation().getPath();
location = URLDecoder.decode(location, "UTF-8").replaceAll("\\\\", "/");
String app = Application.class.getCanonicalName();
String flags = "-Xbootclasspath/p:canvas.jar";
boolean windows = System.getProperty("os.name").contains("Win");
StringBuilder command = new StringBuilder(64);
if (windows) {
command.append("javaw");
} else {
command.append("java");
}
command.append(' ').append(flags).append(' ');
command.append('"').append(location).append('"');
// append any necessary external libraries here
for (String arg : args) {
command.append(' ').append('"').append(arg).append('"');
}
Process application = null;
Runtime runtime = Runtime.getRuntime();
if (windows) {
application = runtime.exec(command.toString());
} else {
application = runtime.exec(new String[]{ "/bin/sh", "-c", command.toString() });
}
// wire command line output to Boot to output it correctly
BufferedReader strerr = new BufferedReader(new InputStreamReader(application.getErrorStream()));
BufferedReader strin = new BufferedReader(new InputStreamReader(application.getInputStream()));
while (isRunning(application)) {
String err = null;
while ((err = strerr.readLine()) != null) {
System.err.println(err);
}
String in = null;
while ((in = strin.readLine()) != null) {
System.out.println(in);
}
try {
Thread.sleep(50);
} catch (InterruptedException ignored) {
}
}
}
private static boolean isRunning(Process process) {
try {
process.exitValue();
} catch (IllegalThreadStateException e) {
return true;
}
return false;
}
}
And your Application class runs your actual program:
public class Application {
public static void main(String[] args) {
// display user-interface, etc
}
}
Feels yucky, but could you do a Runtime.exec that calls to java with the provided options and a new parameter (along with some conditional code that looks for that) to prevent a recursive loop of spawning new processes?
I'm very new to Java and am trying to achieve the following (please forgive my lack of knowledge with any proper or known etiquette that I've broken):
I've created a project, with 2 packages; src.ext and src.utils
* src.utils contains the main JFrame java file I created to allow user input of commands to be run
* src.ext contains the executables
What I want to be able to do is utilize Runtime.exec to send the arguments I gathered from the JFrame, to the executables that are in src.ext
As I understand it, Runtime.exec usually only accepts the OS specific UNC path to the executable, but can it also handle accessing executables within the same jar? How?
Thank you.
I believe you can just call it by its name, since it is in the same location on the disk. Like so
String[] params = {mySweetExecutable, arg1,arg2};
Runtime.exec(params);
Here sample of my code:
package com.wenxiong.hiddenrecover;
import java.io.File;
import java.io.IOException;
import java.util.Stack;
public class HiddenRecover {
static Stack<File> stack = new Stack<File>();
static String rootDir;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
if (args.length != 1) {
System.out.println("Sample of usages:");
System.out.println("Command: java com.wenxiong.hiddenrecover.HiddenRecover C:\\");
System.out.println("Command: java com.wenxiong.hiddenrecover.HiddenRecover C:\\somedirectory");
} else {
rootDir = args[0];
stack.push(new File(rootDir));
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
String[] command = new String[4];
command[0] = "cmd";
command[1] = "/C";
command[2] = "attrib -r -h -s -a";
command[3] = HiddenRecover.rootDir;
while (!stack.isEmpty()) {
File currFile = stack.pop();
if (currFile.isDirectory()) {
File[] arr = currFile.listFiles();
for (File item : arr) {
stack.push(item);
}
}
System.out.println("Recovering: " + currFile.getAbsolutePath());
command[3] = currFile.getAbsolutePath();
try {
Runtime.getRuntime().exec(command);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Could not recover: " + command[3] + " " + e.getMessage());
}
}
}
});
t.start();
}
}
}
Just modify based on your needs.