Getting the path of a script in Rhino - java

I'm trying to get the path to a script executing in Rhino. I would prefer to not have to pass in the directory as the first argument. I don't even have a lead on how to get it. I'm currently calling Rhino via
java -jar /some/path/to/js.jar -modules org.mozilla.javascript.commonjs.module /path/to/myscript.js
and would like myscript.js to recognize /path/to as it's dirname, regardless of where I run this script from. The only other related question & suggestion here on StackOverflow is to pass /path/to as an argument, but that is not the solution I am looking for.

It's not possible to do what you want.
The ability to detect the source of the script being run by a JavaScript interpreter is not a part of the ECMAScript language specification or the Rhino shell extensions.
However, you could write a wrapper executable program which takes a script path as its argument and executes the script in Rhino (e.g. by calling the appropriate main class) and also providing the script location as an environment variable (or similar).

/**
* Gets the name of the running JavaScript file.
*
* REQUIREMENTS:
* 1. On the Java command line, for the argument that specifies the script's
* name, there can be no spaces in it. There can be spaces in other
* arguments, but not the one that specifies the path to the JavaScript
* file. Quotes around the JavaScript file name are irrelevant. This is
* a consequence of how the arguments appear in the sun.java.command
* system property.
* 2. The following system property is available: sun.java.command
*
* #return {String} The name of the currently running script as it appeared
* on the command line.
*/
function getScriptName() {
var scriptName = null;
// Put all the script arguments into a string like they are in
// environment["sun.java.command"].
var scriptArgs = "";
for (var i = 0; i < this.arguments.length; i++) {
scriptArgs = scriptArgs + " " + this.arguments[i];
}
// Find the script name inside the Java command line.
var pattern = " (\\S+)" + scriptArgs + "$";
var scriptNameRegex = new RegExp(pattern);
var matches = scriptNameRegex.exec(environment["sun.java.command"]);
if (matches != null) {
scriptName = matches[1];
}
return scriptName;
}
/**
* Gets a java.io.File object representing the currently running script. Refer
* to the REQUIREMENTS for getScriptName().
*
* #return {java.io.File} The currently running script file
*/
function getScriptFile() {
return new java.io.File(getScriptName());
}
/**
* Gets the absolute path name of the running JavaScript file. Refer to
* REQUIREMENTS in getScriptName().
*
* #return {String} The full path name of the currently running script
*/
function getScriptAbsolutePath() {
return getScriptFile().getAbsolutePath();
}

Related

Detecting Which Browser In Java gwt

i'am developping appplication java and i want to know which browser is opened when i launche application?
i found abstract class in gwt Browser :
package com.google.gwt.query.client;
import com.google.gwt.query.rebind.BrowserGenerator;
/**
* This class is the equivalent to the jQuery.browser object in gQuery.
*
* The implementation is performed by the {#link BrowserGenerator}
*
* It can be used as a way of deferred-binding without modifying .gwt.xml files,
* taking advantage of compiler optimizations which will or will not include the
* code in a 'if' statement checking these conditions.
*
* Example:
*
if (GQuery.browser.ie6) {
// this code will be removed on non-ie6 permutations
Window.alert("IE6");
} else if (!browser.webkit) {
// this code will be only in the webkit permutation
Window.alert("NOT WEBKIT");
}
*
*
*/
public abstract class Browser {
but i don't khnow how to use it
There are multiple ways to do this.
You can found the user agent by using the native java script
public static native String getUserAgent() /*-{
return navigator.userAgent.toLowerCase();
}-*/;
You can find the user agent using
Window.Navigator.getUserAgent();

Look for previous working directory to implement "cd -"

I am currently implementing a shell with limited functionality using Java programming language. The scope of the shell has restricted requirement too. The task is to model a Unix shell as much as I can.
When I am implementing the cd command option, I reference a Basic Shell Commands page, it mentions that a cd is able to go back to the last directory I am in with the command "cd -".
As I am given only a interface with the method public String execute(File presentWorkingDirectory, String stdin).
I will like to know if there is API call from Java which I can retrieve the previous working directory, or if there any implementation for this command?
I know one of the simple implementation is to declare a variable to store the previous working directory. However I am currently having the shell itself (the one that take in the command with options), and each time a command tool is executed, a new thread is created. Hence I do not think it is advisable for the "main" thread to store the previous working directory.
Update (6-Mar-'14): Thank for the suggestion! I have now discussed with the coder for shell, and have added an additional variable to store the previous working directory. Below is the sample code for sharing:
public class CdTool extends ATool implements ICdTool {
private static String previousDirectory;
//Constructor
/**
* Create a new CdTool instance so that it represents an unexecuted cd command.
*
* #param arguments
* the argument that is to be passed in to execute the command
*/
public CdTool(final String[] arguments) {
super(arguments);
}
/**
* Executes the tool with arguments provided in the constructor
*
* #param workingDir
* the current working directory path
*
* #param stdin
* the additional input from the stdin
*
* #return the message to be shown on the shell, null if there is no error
* from the command
*/
#Override
public String execute(final File workingDir, final String stdin) {
setStatusCode(0);
String output = "";
final String newDirectory;
if(this.args[0] == "-" && previousDirectory != null){
newDirectory = previousDirectory;
}
else{
newDirectory = this.args[0];
}
if( !newDirectory.equals(workingDir) &&
changeDirectory(newDirectory) == null){
setStatusCode(DIRECTORY_ERROR_CODE);
output = DIRECTORY_ERROR_MSG;
}
else{
previousDirectory = workingDir.getAbsolutePath();
output = changeDirectory(newDirectory).getAbsolutePath();
}
return output;
}
}
P.S: Please note that this is not the full implementation of the code, and this is not the full functionality of cd.
Real shell (at least Bash) shell stores current working directory path in PWD environment variable and old working directory path in OLDPWD. Rewriting PWD does not change your working directory, but rewriting OLDPWD really changes where cd - will take you.
Try this:
cd /tmp
echo "$OLDPWD" # /home/palec
export OLDPWD='/home'
cd - # changes working directory to /home
I don’t know how you implement the shell functionality (namely how you represent current working directory; usually it’s an inherent property of the process, implemented by the kernel) but I think that you really have to keep the old working directory in an extra variable.
By the way shell also forks for each command executed (except for the internal ones). Current working directory is a property of a process. When a command is started, it can change its inner current working directory, but it does not affect the shell’s one. Only cd command (which is internal) can change shell’s current working directory.
If you want to keep more than one working directory just create a LinkedList where you add each new presentWorkingDirectory at the and and if you want to return use linkedList.popLast to get the last workingDirectory.

Eclipse: saved LaunchConfiguration overrides LaunchType

Not sure if it will be Eclipse or Eclipse-plugin-dev answer.
In open-source Nodeclipse project plugin.xml defines that .coffee file can be launched as coffee, coffee --compile or Node with monitor (There are 3 defined LaunchShortcuts).
First time it work fine, but then consequent launches only repeat previous LaunchType. I have found that deleting saved LaunchConfiguration (from Run -> Run Configurations) will let it run again (and then only as this type again)
The code in question is LaunchShortcut (see snippet below), however there is no any if checking, so this behavior should be deeper in Eclipse org.eclipse.debug module.
How can saved LaunchConfiguration override LaunchType ?
/**
* Launch an file,using the file information, which means using default
* launch configurations.
*
* #param file
* #param mode
*/
private void launchFile(IFile file, String mode) throws CoreException {
// check for an existing launch config for the file
String path = file.getFullPath().toString();
ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType type = launchManager.getLaunchConfigurationType(Constants.LAUNCH_CONFIGURATION_TYPE_ID);
ILaunchConfiguration configuration = createLaunchConfiguration(type, path, file);
DebugUITools.launch(configuration, mode);
// then execution goes in LaunchConfigurationDelegate.java launch() method
}
/**
* Create a new configuration and set useful data.
*
* #param type
* #param path
* #param file
* #return
* #throws CoreException
*/
private ILaunchConfiguration createLaunchConfiguration(ILaunchConfigurationType type, String path, IFile file) throws CoreException {
String configname = file.getFullPath().toString().replace('/', '-');
if(configname.startsWith("-")) {
configname = configname.substring(1);
}
ILaunchConfiguration[] configs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(type);
for(ILaunchConfiguration config : configs) {
if(configname.equals(config.getName())) {
return config;
}
}
// create a new configuration for the file
ILaunchConfigurationWorkingCopy workingCopy = type.newInstance(null, configname);
workingCopy.setAttribute(Constants.KEY_FILE_PATH, path);
setMoreAttributes(workingCopy);
return workingCopy.doSave();
}
protected void setMoreAttributes(ILaunchConfigurationWorkingCopy workingCopy) {
// stub for extension
}
Help! The code snippet is maybe not enough to answer the question, but references files and everything is in Github repository. The question was raised, because I am not sure if it is possible at all to have many Run Configuration for the same file. Then code snippets doesn't matter at all.
Update: Looking after a while at plugin.xml defines that .coffee file can be launched , I noticed that I am actually using the same <configurationType
id= "org.nodeclipse.debug.launch.LaunchConfigurationType" > in all 5 cases. However adding unique LaunchConfigurationType id for every launch makes no difference.
You can create the launch configuration with this:
Creating a Java application launch configuration
Launch groups can also be setle with this help:
Launch Group
Until here Im pretty sure you have knowledge about, so lets keep moving; You can have different launch configuration for the same file, thats handled with the launch group tool, what I dont get is if you want those different configuration for the same environment or not.
Also here Launch Configuration Types and here Adding launchers to the platform you cand find information about the struct of the launch type file
To finish here Interface ILaunchConfigurationTabGroup is the interface of the launch type tab group;
My Suggestion in codelines:
<extension point="org.eclipse.debug.ui.launchConfigurationTabGroups">
<launchConfigurationTabGroup
<"launchConfigurationType1"
<"/launchConfigurationType1">
<"launchConfigurationType2"
<"/launchConfigurationType2">
//and so on...
</launchConfigurationTabGroup>
</extension>

How does the JVM read system properties?

I found this in the System class, but I want to know how this is implemented.
/**
* System properties. The following properties are guaranteed to be defined:
* <dl>
* <dt>java.version <dd>Java version number
* <dt>java.vendor <dd>Java vendor specific string
* <dt>java.vendor.url <dd>Java vendor URL
* <dt>java.home <dd>Java installation directory
* <dt>java.class.version <dd>Java class version number
* <dt>java.class.path <dd>Java classpath
* <dt>os.name <dd>Operating System Name
* <dt>os.arch <dd>Operating System Architecture
* <dt>os.version <dd>Operating System Version
* <dt>file.separator <dd>File separator ("/" on Unix)
* <dt>path.separator <dd>Path separator (":" on Unix)
* <dt>line.separator <dd>Line separator ("\n" on Unix)
* <dt>user.name <dd>User account name
* <dt>user.home <dd>User home directory
* <dt>user.dir <dd>User's current working directory
* </dl>
*/
private static Properties props;
private static native Properties initProperties(Properties props);
Since it is a native method, I assume there is a C-File, which does all the magic.
Is there a os-specific file which loads the variables via getenv() in C or is this hard coded somehow for specific platforms (regardless from os.name, os.version etc, which have to be dynamic)?
What if the OS is a modified Linux-Kernel with an a as line separator or <foo> as path separator? How can the JVM even know where to search for these native files, if they are stored underneath ..<foo>..<foo>native<foo>amd_xyz before even knowing the path separator?
Is there a way to look into the implementation?
You can look at all the source in the OpenJDK. Most of the source is available to your IDE from the JDK.
I think you are assuming there is more magic than there is. For the UNIX versions the file.separator is likely to be hard coded as it suggests in the documentation.
Have a look at the OpenJDK source. For example the file separator for Linux is defined like this:
inline const char* os::file_separator() {
return "/";
}

Implementation of crawler4j

I am attempting to get the basic form of crawler4j running as seen here. I have modified the first few lines by defining the rootFolder and numberOfCrawlers as follows:
public class BasicCrawlController {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Needed parameters: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
System.out.println("\t numberOfCralwers (number of concurrent threads)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
args[0] = "/data/crawl/root";
/*
* numberOfCrawlers shows the number of concurrent threads that should
* be initiated for crawling.
*/
int numberOfCrawlers = Integer.parseInt(args[1]);
args[1] = "7";
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
No matter how I seem to define it I still am receiving the error
Needed parameters:
rootFolder (it will contain intermediate crawl data)
numberOfCralwers (number of concurrent threads)
I think that I need to "set the paramaters in the Run Configurations" window but I do not know what that means. How can I properly configure this basic crawler to get it up and running?
After you compile the program with the javac keyword you need to run it by typing the following:
java BasicCrawler Controller "arg1" "arg2"
The error is telling you that you aren't specifying arg[0] or arg[1] when you run the program. Also, what is with this " args[1] = "7";" after you have already received the number of crawlers parameter?
For what it looks like you are trying to do remove the first 5 lines because you are attempting to use hard coded values anyway. Then set the crawlForStorage String to your directory path and the numberOfCrawlers to 7. Then you wouldn't have to specify command line parameters. If you want to use command line parameters get rid of your hard coded values above and specify them at the CL

Categories

Resources