I am trying to get multiple arguments passed to a java program. The Apache Commons CLI interface has been set up correctly and works. However, when I try to use
setArgs(Option.UNLIMITED_VALUES), it gives me an error
The method setArgs(int) is undefined for the type Options.
My code looks like this:
import java.io.Console;
import java.util.Arrays;
import java.io.IOException;
import org.apache.commons.cli.*;
public class main {
public static void main(String[] args) {
#SuppressWarnings("deprecation")
CommandLineParser parser = new BasicParser();
Options options = new Options();
options.setArgs(Option.UNLIMITED_VALUES);
options.addOption("p", true, "Program under test");
options.addOption("o", true, "Oracle");
options.addOption("n", true, "Number of test cases");
try {
CommandLine commandline = parser.parse(options, args);
System.out.println(commandline.getOptionValue("p"));
} catch (ParseException e) {
System.out.println("Command line failed.");
e.printStackTrace();
}
}
}
setArgs is a method related to Option not Options
Related
I am trying to develop a camunda process, but I don't know how to implement a multi insntance subprocess to iterate through a collection.
For example:
SubProcess subProcess = modelInstance.getModelElementById("elementVersionId-" + element.getId().toString());
subProcess.builder().multiInstance().multiInstanceDone() //Cant add a start event after multinstance done
After add a multiInstanceDone to the subprocess i cant start the subprocess with startEvent.
Does anyone have an idea, example to help me?
Hope this helps:
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.builder.MultiInstanceLoopCharacteristicsBuilder;
import org.camunda.bpm.model.bpmn.instance.*;
import java.io.File;
#Slf4j
public class MultiInstanceSubprocess {
public static final String MULTI_INSTANCE_PROCESS = "myMultiInstanceProcess";
// #see https://docs.camunda.org/manual/latest/user-guide/model-api/bpmn-model-api/fluent-builder-api/
public static void main(String[] args) {
BpmnModelInstance modelInst;
try {
File file = new File("./src/main/resources/multiInstance.bpmn");
modelInst = Bpmn.createProcess()
.id("MyParentProcess")
.executable()
.startEvent("ProcessStarted")
.subProcess(MULTI_INSTANCE_PROCESS)
//first create sub process content
.embeddedSubProcess()
.startEvent("subProcessStartEvent")
.userTask("UserTask1")
.endEvent("subProcessEndEvent")
.subProcessDone()
.endEvent("ParentEnded").done();
// Add multi-instance loop characteristics to embedded sub process
SubProcess subProcess = modelInst.getModelElementById(MULTI_INSTANCE_PROCESS);
subProcess.builder()
.multiInstance()
.camundaCollection("myCollection")
.camundaElementVariable("myVar")
.multiInstanceDone();
log.info("Flow Elements - Name : Id : Type Name");
modelInst.getModelElementsByType(FlowNode.class).forEach(e -> log.info("{} : {} : {}", e.getName(), e.getId(), e.getElementType().getTypeName()));
Bpmn.writeModelToFile(file, modelInst);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Executor;
import com.jacob.com.LibraryLoader;
import autoitx4java.AutoItX;
public class SilentInstallation {
public static void main(String[] args) throws IOException, InterruptedException {
String[] cmd = { "C:\\WINDOWS\\system32\\cmd.exe", "/c", "start" };
try {
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec(cmd);
}
catch (java.io.IOException exception) {
System.out.println("Caught IOException: " + exception.getMessage());
}
}
}
Here is my code in which I am running command prompt using java. But the problem here I am facing is I can't be able to change the path in command prompt using java code.
Since this code is using in Automation, so is there any command or method in java that can be used to change the path in the command prompt.
I have also used ProcessBuilder to change the directory path.
Any Recommendations.....
This should be enough:
Process p = ...
p.getOutputStream().write("cd d:\\/r/n".getBytes());
I'm trying to run a java class without saving to a file and i use javax.tools.JavaCompiler for this.
here i found a answer on so question about java memory compile.
but when i run this code i got two different outputs .java version in both ide and cmd is 1.8.0_31
this is in netbeans IDE version-8.0.2
this is the line 50
Class.forName("HelloWorld").getDeclaredMethod("main", new Class[]{String[].class})
this is cmd output
line 33 is
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
i want to know the reason for getting two different output .
this is the code i used .this is almost same as above answer's code .but i removed multiple catch blocks in to one.
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.Arrays;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject.Kind;
public class CompileSourceInMemory {
public static void main(String args[]) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("public class HelloWorld {");
out.println(" public static void main(String args[]) {");
out.println(" System.out.println(\"This is in another java file\");");
out.println(" }");
out.println("}");
out.close();
JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
boolean success = task.call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
System.out.println(diagnostic.getCode());
System.out.println(diagnostic.getKind());
System.out.println(diagnostic.getPosition());
System.out.println(diagnostic.getStartPosition());
System.out.println(diagnostic.getEndPosition());
System.out.println(diagnostic.getSource());
System.out.println(diagnostic.getMessage(null));
}
System.out.println("Success: " + success);
if (success) {
try {
Class.forName("HelloWorld").getDeclaredMethod("main", new Class[]{String[].class})
.invoke(null, new Object[]{null});
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class JavaSourceFromString extends SimpleJavaFileObject {
final String code;
JavaSourceFromString(String name, String code) {
super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.code = code;
}
#Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
thanks.
I couldn't reproduce your first error:
$ ~/jdk1.8.0_25/bin/java CompileSourceInMemory
Success: true
This is in another java file
Try finding out which java was called from terminal or command line in your case.
The second problem is related to where NetBeans/compiler outputs compiled class. It is root of project, so class path needs adjustment:
if (success) {
try {
URL[] classpathExt = {new File("/home/[your name]/NetBeansProjects/JavaApplication2/").toURI().toURL()};
URLClassLoader loader = new URLClassLoader(classpathExt, null);
Class.forName("HelloWorld", true, loader).getDeclaredMethod("main", new Class[]{String[].class})
.invoke(null, new Object[]{null});
} catch (Exception e) {
e.printStackTrace();
}
}
Interesting that ~/NetBeansProjects/JavaApplication2/ won't work, full path must be specified. For Windows you will use C:\\User\\and so on\\
The cmd problem at line 33 is probably because tools.jar is not present in your command line classpath (and thus compiler is null). The compiler returned by ToolProvider.getSystemJavaCompiler() comes from this jar, so if tools.jar isn't on your classpath it will return null. This is then being dereferenced at line 33 to cause the NPE.
Perhaps the compiler that you run from the command line was installed with only the JRE present, and not the JDK? I imagine that NetBeans IDE is automatically including JDK libraries for you.
However its classloader seems not to be capable of loading your java source, as Filip Bulovic mentioned: you can create a new URLClassLoader adding to it the directory where the compiler returned by ToolProvider.getSystemJavaCompiler() put your compiled code. Or you can use the class loader provided by ToolProvider.getSystemToolClassLoader() to load the HelloWorld class.
I implemented the example from docs of this plugin, but I have an exception stating that a parameter Initiator is missed. I don't see this parameter at all.
My code is:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.emitter.csv.CSVRenderOption;
public class RunExport {
static void runReport() throws FileNotFoundException, BirtException {
String resourcePath = "C:\\Users\\hpsa\\workspace\\My Reports\\";
FileInputStream fs = new FileInputStream(resourcePath + "new_report_1.rptdesign");
IReportEngine engine = null;
EngineConfig config = new EngineConfig();
config.setLogConfig("C:\\birtre\\", Level.FINE);
config.setResourcePath(resourcePath);
Platform.startup(config);
IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
engine = factory.createReportEngine(config);
engine.changeLogLevel(Level.FINE);
IReportRunnable design = engine.openReportDesign(fs);
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
CSVRenderOption csvOption = new CSVRenderOption();
String format = CSVRenderOption.OUTPUT_FORMAT_CSV;
csvOption.setOutputFormat(format);
csvOption.setOutputFileName("newBIRTcsv.csv");
csvOption.setShowDatatypeInSecondRow(true);
csvOption.setExportTableByName("SecondTable");
csvOption.setDelimiter("\t");
csvOption.setReplaceDelimiterInsideTextWith("-");
task.setRenderOption(csvOption);
task.setEmitterID("org.eclipse.birt.report.engine.emitter.csv");
task.run();
task.close();
Platform.shutdown();
System.out.println("Report Generated Successfully!!");
}
public static void main(String[] args) {
try {
runReport();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have an exception:
org.eclipse.birt.report.engine.api.impl.ParameterValidationException: Required parameter Initiator is not set.
at org.eclipse.birt.report.engine.api.impl.EngineTask.validateAbstractScalarParameter(EngineTask.java:803)
at org.eclipse.birt.report.engine.api.impl.EngineTask.access$0(EngineTask.java:789)
at org.eclipse.birt.report.engine.api.impl.EngineTask$ParameterValidationVisitor.visitScalarParameter(EngineTask.java:706)
at org.eclipse.birt.report.engine.api.impl.EngineTask$ParameterVisitor.visit(EngineTask.java:1531)
at org.eclipse.birt.report.engine.api.impl.EngineTask.doValidateParameters(EngineTask.java:692)
at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.doRun(RunAndRenderTask.java:95)
at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.run(RunAndRenderTask.java:77)
at com.demshin.RunExport.runReport(RunExport.java:44)
at com.demshin.RunExport.main(RunExport.java:54)
[1]: https://code.google.com/a/eclipselabs.org/p/csv-emitter-birt-plugin/
I tried to find this parameter in csvOption, but there is nothing like that.
What am I doing wrong?
It is not a parameter of the emitter. This exception means a report parameter named "Initiator" is defined in the report "new_report_1.rptdesign", and its property "required" is checked.
For example edit the report design, disable "required" for this parameter and set a default value instead.
I have this java program, which executes a pig script in MapReduce mode. Here is the code:
import java.io.IOException;
import java.util.Properties;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.backend.executionengine.ExecException;
public class pigCV {
public static void main(String args[]){
PigServer pigServer;
try {
Properties props = new Properties();
props.setProperty("fs.default.name", "hdfs://hdfs://localhost:8022");
props.setProperty("mapred.job.tracker", "localhost:8021");
pigServer = new PigServer(ExecType.MAPREDUCE, props);
pigServer.registerScript("Desktop/text_v3.pig");
}
catch (ExecException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
}
Via the linux command line, I'm able to pass arguments to the pig script with a command like this:
pig -f "Desktop/text_v3.pig" -param param1=value1 -param2=value2
But with PigServer, I did not find how to do it.
Do you know how to resolve the problem ?
Thank you.
You can use this version of the registerScript method:
public void registerScript(String fileName, Map<String,String> params)
The java docs explanation is the following: "Register a pig script file. The parameters in the file will be substituted with the values in params."