I would like to get current app path in the app.
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current config file path is: " + s);
It seems working well, BUT when I use like below.
> pwd
> /usr/local/
> java -jar app/getapppath.jar // executed app inside app folder
> Current config file path is : /usr/local // I want /usr/local/app
I can executed my app after 'cd app', but I want to fix it fundamentally. Any idea of this?
You can use classloader to get that information. Here is a example, which you can adopt to your needs:
package test;
import java.net.URL;
public class a {
public static void main(String[] args) {
URL u = ClassLoader.getSystemResource("test/a.class");
System.out.println(u);
}
}
In my case it works as:
$ cd /tmp
$ java -cp /home/me a
file:/home/me/a.class
$
Related
question
How can I ensure my install4j installer always finds only its java?
Can I create a top level installer which installs JRE to tmp, sets env variables and then starts the actual installer?
Can I load a vm file during installation?
problem
Install4j finds java 1.7 during install which impacts custom code preventing successful installation. I see found java7 prior to file deployment - ok expected given the JRE hasn't yet been unpacked.
evidence
I created a simple installer and see the following:
BEFORE
PATH=/opt/tools/Java/jdk1.7.0_79/bin:...
JAVA_HOME=/opt/tools/Java/jdk1.7.0_79
...
ENV [JAVA_HOME] /opt/tools/Java/jdk1.7.0_79
ENV [PATH] /opt/tools/Java/jdk1.7.0_79/bin:...
installer details
envTest.install4j
Optional customer install script reporting found java prior at execution start
echo BEFORE
echo PATH=$PATH
echo JAVA_HOME=$JAVA_HOME
echo Version: java -version
Run script reporting env after installer deployed jre
`
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
Map<String, String> envMap = System.getenv();
SortedMap<String, String> sortedEnvMap = new TreeMap<String, String>(envMap);
Set<String> keySet = sortedEnvMap.keySet();
for (String key : keySet) {
String value = envMap.get(key);
Util.logInfo(this,"ENV [" + key + "] " + value);
}
return true;
Actually, this turned our to be a problem with my custom code. The custom code launches an install4j generated executable via java. When launched on command line with wrong java found first, the launcher uses only its own java. When launched from my extension it fails.
Solution - set java in my extension:
private File getInstalledJREDir() {
return new File(installationDir, "jre");
}
private String addJREToFrontOfPathVar() {
File jreBinDir = new File(getInstalledJREDir(), "bin");
String path = System.getenv().get("PATH");
if (null == path) {
path = jreBinDir.getAbsolutePath();
} else {
path = jreBinDir.getAbsolutePath() + File.pathSeparator + path;
}
return path;
}
/**
* Start Laucnher and block until it starts or timeout reached
* #throws AutoRunException
*/
public void run() throws AutoRunException, IOException, InterruptedException {
notifier.setPhase("Starting Agent");
// Set Directories
File dataDir = new File(installationDir.getParentFile(), "data-agent");
File agentLog = new File(logDir,"agent.log");
if (! isWindows()) {
File agent = new File(installationDir, "bin/launcherExecutable");
CmdExecutor ce = new CmdExecutor(agent, agentLog);
// Ensure our installed JRE found 1st - PLAT-38833
ce.updateEnvironmentVariable("JAVA_HOME", getInstalledJREDir().getAbsolutePath());
ce.updateEnvironmentVariable("PATH", addJREToFrontOfPathVar());
ce.setWorkingDir(installationDir);
ce.setArgLine(String.format("--datadir %s", dataDir.getAbsolutePath()));
notifier.logInfo("Starting " + agent + " with " + ce.getArgLine());
if (! ce.run(true) ) {
throw new AutoRunException("Agent failed to start " + ce.getOutput());
}
I have a child java project which has groovy files added in classpath using eclipse. Parent java project triggers some functionality in child which uses Groovy library to run the scripts. So import works fine in eclipse environment with opened child project but if I run it from command line or if I close child project then I get groovy compilation error at import statement. How can I resolve this ? I want to avoid using evaluate() method.
Following is my master groovy:
package strides_business_script
abstract class Business_Script extends Script {
//some stuff
}
Following is the another groovy:
import static strides_business_script.StridesBusiness_Script.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
String Key = Part_Product_PartDetails
boolean containsData = checkIncomingMessage(Key)
if(containsData) {
def edgeKeyList = [PPR]
JSONArray partDetails = appendEdgeValueToMsg(edgeKeyList,Key,vertex,messageIterator);
//deleteMessages(Key);
JSONObject jsonObject = constructInfoWithPropertyJSON("NAME,PRODUCTTYPE,FGTYPE,UOM,ITEMCLASSIFICATIONBYMARKET");
jsonObject.put("PARTS",partDetails);
send(Product_AggPO_ProductDetails,convertJSONToString(jsonObject));
}
Edit:
My master script Business_Script.groovy resides in scripts/strides_business_script/ folder. All other scripts are in scripts/StridesComputationScripts/ folder and they import the Business_Script.groovy.
I run the application with remote debugging enabled like this:
java -cp "./lib/*:./scripts/strides_business_script/Business_Script.groovy" -Xdebug -Xrunjdwp:transport=dt_socket,address=6969,server=y -Dhibernate.cfg.xml.path=./conf/hibernate.cfg.xml -Dlog4j.configuration=file:./conf/log4j.properties com.biglabs.dataExtractor.dataDump.DataDumpDriver 7
and here I am trying to parse all computation scripts.
for (String scriptName : files) {
Script script = groovyShell.parse(new File(
SCRIPT_PLACED_AT + Constants.SLASH
+ SCRIPT_FILE_FOLDER + Constants.SLASH
+ scriptName));
scriptMping.put(scriptName, script);
}
It throws following exception while parsing using groovy shell:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/home/manoj/strides/release/strides/scripts/StridesComputationScripts/PRODUCT-script.groovy: 2: unable to resolve class strides_business_script.StridesBusiness_Script
# line 2, column 1.
import static strides_business_script.Business_Script.*;
^
/home/manoj/strides/release/strides/scripts/StridesComputationScripts/PRODUCT-script.groovy: 2: unable to resolve class strides_business_script.StridesBusiness_Script
# line 2, column 1.
import static strides_business_script.Business_Script.*;
^
2 errors
Fixed it by adding script path in comiler configuration:
CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
String path = SCRIPT_PLACED_AT;
if(!SCRIPT_PLACED_AT.endsWith("/")){
path = path+ "/";
}
compilerConfiguration.setClasspath(path);
GroovyShell groovyShell = new GroovyShell(
compilerConfiguration);
for (String scriptName : files) {
Script script = groovyShell.parse(new File(
SCRIPT_PLACED_AT + Constants.SLASH
+ SCRIPT_FILE_FOLDER + Constants.SLASH
+ scriptName));
scriptMping.put(scriptName, script);
}
i em trying to fetch some query from an url and then pass them to a java program for further execution. The problem i am facing is that my php code is calling my java program but is not passing the values.
till now i have worked on these codes,
PHP PROGRAM:
<?php
$phonecode= $_GET['phonecode'];
$keyword= $_GET['keyword'];
$location= $_GET['location'];
exec("C:\Users\Abc\Documents\NetBeansProjects\JavaApplication11\src\javaapplication11\main.java -jar jar/name.jar hello" . $phonecode . ' ' . $keyword . ' ' . $location, $output);
print_r($output);
?>
JAVA PROGRAM:
public class Main
{
public static void main(String args[])
{
try
{
String phonecode = args[];
System.out.println(args[]);
System.out.println(phonecode);// i have only tried to print phonecode for now
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Ok, a couple of issues with the Java code you've posted, here's a working version of what you posted:
class Main
{
public static void main(String[] args)//String[] args, not String args[]
{
if (args.length == 0)
{//check to see if we received arguments
System.out.println("No arguments");
return;
}
if ( args.length < 3)
{//and make sure that there are enough args to continue
System.out.println("To few arguments");
return;
}
try
{//this try-catch block can be left out
String phonecode = args[0];//first arg
String keyword = args[1];//second
String location = args[2];//third
//print out the values
System.out.print("Phonecode: ");
System.out.println(phonecode);
System.out.print("keyword: ");
System.out.println(keyword);
System.out.print("location: ");
System.out.println(location);
}
catch(Exception e)
{
System.out.println(e.getMessage());//get the exception MESSAGE
}
}
}
Now, save that as a .java file, and compile it, it should churn out a Main.class file. I compiled it from the command-line:
javac main.java
I don't have netbeans installed, but I suspect the .class file will be written to a different directory, something like:
C:\Users\Abc\Documents\NetBeansProjects\JavaApplication11\bin\javaapplication11\Main.class
// note the BIN
Then, to execute, you need to run the java command, and pass it the path to this Main.class file, leaving out the .class extension. Thus, we end up with:
java /path/to/Main 123 keywrd loc
Should result in the output:
Phonecode: 123
keyword: keywrd
location: loc
In your PHP code:
exec('java /path/to/Main '.escapeshellarg($phonecode). ' '.escapeshellarg($keyword).' '.escapeshellarg($location), $output, $status);
if ($status === 0)
{//always check exit code, 0 indicates success
var_dump($output);
}
else
exit('Error: java exec failed: '.$status);
There are a couple of other issues, too: like $phonecode = $_GET['phonecode']; doesn't check if that $_GET param exists. If it doesn't your code will emit notices. To fix:
$phonecode = isset($_GET['phonecode']) ? $_GET['phonecode'] : '';
Other niggles include: the backslash is a special char in strings, it is used in escape sequences: \n is a newline char. PHP can deal with the *NIX directory separator /, even on windows. Use that, or escape the backslashes (C:\\Users\\Abc\\ and so on).
A file that only contains PHP code doesn't require the closing ?> tag. In fact: it is recommended you leave it out.
your java code should look like
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
Note String[] args, not String args[]
Also on PHP side in exec you need space between string hello, and variable $phonecode if you want those to be looked as a 2 separate arguments.
I got error While running the jess in java program like
error: package jess does not exist
I don't know what and all packages to be included.
I have written code like this:
import jess.*;
public class ExQuery {
public static void main(String[] argv) throws JessException {
Rete engine = new Rete();
engine.batch("query.clp");
engine.reset();
QueryResult result =
engine.runQueryStar("search-by-name", new ValueVector().add("Smith"));
while (result.next()) {
System.out.println(result.getString("fn") + " " + result.getString("ln")
+ ", age" + result.getInt("age"));
}
}
}
Make sure you've imported the jess.jar librairy into your project.
Right click on project -> Properties -> Into Java Build Path -> Add external JARs
you need to select the jess.jar file into your Jess71p2 (or other version..) -> lib -> jess.jar
I have two file.
Hello.java
Index.php
Hello.java
class Hello
{
public static void main(String args[])
{
System.out.println("HelloWorld");
}
}
Index.php
$file="Hello.java";
exec('javac'.$file,$output,$resultCode);
if ($resultCode===0)
{
echo "Result: " . $resultCode . "\n";
}
else
{
echo "fail";
}
It give "Fail" output i want to get "HelloWorld" output on browser.
please help me.
You have not provided a space between your command and arguments.
exec('javac'.$file,$output,$resultCode);
should be
exec('javac '.$file,$output,$resultCode);
This part just completed the compiling then you need another exec statement to completed the execution of the program. As suggested by mthmulders
exec("java -cp . Hello", $output,$resultCode);