Make a folder hidden using java 6 in Windows, but it failed - java

I run my class in the command line, it's ok, but When I package my project as the service of Windows, it's failed. Anyone get the reason?
My service run as the System user, the tempFolder was created as System user.
There is my code, and I didn't get any exception and error.
(!tempFolder.exists()){
if(tempFolder.mkdirs()){
String operatingSystemName = System.getProperty("os.name");
if (operatingSystemName != null
&& operatingSystemName.startsWith(WINDOWS_FAMILY)) {
String string = " attrib " + tempFolder.getAbsolutePath()+ " +h";
try {
Runtime.getRuntime().exec(string);
} catch (Exception e) {
e.printStackTrace();
}
}
}else {
throw new Exception("Can't create temp folder - " + tempFolder.toString());
}

Add parameter +s
String string = " attrib " + tempFolder.getAbsolutePath()+ " +s +h";
+s : Used to set the file attribute as a system file.
Parameters of attrib command
+r : Used to set the file attribute as read-only.
-r : Used to clear the read-only file attribute.
+a : Used to set the file attribute as archive.
-a : Used to clear the archive file attribute.
+s : Used to set the file attribute as a system file.
-s : Used to clear the system file attribute.
+h : Used to make the file attribute as hidden not visible to the user.
-h : Used to clear the hidden file attribute.

Related

RServe: control pipe to master process is closed/broken

I have this R script:
palindrome <- function(p) {
for(i in 1:floor(nchar(p)/2) ) {
r <- nchar(p) - i + 1
if ( substr(p, i, i) != substr(p, r, r) ) return(FALSE)
}
return(TRUE)
}
that I am calling from Java using the following code:
connection.serverSource("C:\\Users\\x\\Desktop\\R Script\\Palindrome.R");
the connection is of type RConnection is created as follows:
public void startConnection() {
PATH_TO_R = SystemUtils.IS_OS_UNIX ? "R" : "C:\\Program Files\\R\\R-3.6.1\\bin\\x64\\R.exe";
try {
String cmd = PATH_TO_R + " -e " + "\"library(Rserve);Rserve(port=" + 6311+ ")\"";
Runtime.getRuntime().exec(cmd);
RConnection connection = new RConnection("localhost", 6311);
} catch (IOException | RserveException e) {
e.printStackTrace();
}
}
The problem is I am having this error thrown and have no idea how to fix it:
org.rosuda.REngine.Rserve.RserveException: serverSource failed, request status: control pipe to master process is closed/broken
any help will be much appreciated!
The function serverSource (just like serverEval and serverShutdown) directly works on the main R+Rserve process, this feature is off by default. You can enable it in /etc/Rserv.conf adding the line control enabled (config reference).
If you don't already use an Rserve config file, you can simply create it in the default location /etc/Rserv.conf (linux/macOS) or create it anywhere (also windows) and pass the location as parameter when starting Rserve: R CMD Rserve --RS-conf <your path here> (command line arguments at the bottom of the page).

Java - how to create a file under unknown/variable path?

I have a directory: <dir>\Report\<env>\Log_XXX\Logs
where XXX is randomly created at run time, so I have to create a file inside Logs folder.
Following is what I tried to generate the Logs folder:
new File(System.getProperty("user.dir") + "/Report/" + System.getProperty("env") + "/" + Pattern.compile("^Log_") + "/Logs").mkdirs();
Based on your comments, it appears you are trying to locate the one and only subdirectory whose base name starts with Log_. You can accomplish this with Files.list:
Path logParent = Paths.get(
System.getProperty("user.dir"),
"Report",
System.getProperty("env"));
Path logDir;
try (Stream<Path> listing = Files.list(logParent)) {
Optional<Path> match = listing.filter(p -> Files.isDirectory(p) &&
p.getFilename().toString().startsWith("Log_")).findFirst();
logDir = match.orElseThrow(() -> new RuntimeException(
"No log directory found in " + logParent));
}

Process does not exit when launched from Java

I am launching WebTorrent-CLI from within my Java application as a separate process. I am using zt-exec for managing the process. When WebTorrent is launched with the following command, it is supposed to exit after the file at given index (value of --select) has been downloaded.
"D:\downloadmanager\node\webtorrent.cmd" download "magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel" --select 0 --out "D://nf/"
As expected, webtorrent-cli does exit after downloading 0th file when the command above is used to launch it from command line. But when I try the same from within my Java app, it completely ignores the --select option and continues downloading other files in the torrent.
Basically, when launched as a process from Java, webtorrent ignores all the options set (--select, --out or whatever). I should mention that there is nothing wrong with the library because recently I've tried replacing it with commons-exec and that solved nothing. Also, to make sure that the right command is passed while starting the process, I'm printing the command right before calling executor.start(). The command above is copied from the output retrieved from printing the command before the process starts.
This is how the process is started:
#Override
public synchronized void start() throws IOException {
if (mWasDownloadStarted || mWasDownloadFinished) return;
mExec.getCommand().listIterator().forEachRemaining(s -> {
System.out.print(s + " ");
});
mExec.start();
setProcessId();
mWasDownloadStarted = true;
mWasDownloadStopped = false;
}
This is how the command is prepared:
private String buildCommand() {
List <String> command = new ArrayList<>();
command.add("\"" + mManager.mWTLocation + "\"");
command.add("download");
command.add("\"" + mManager.mMagnetUrl + "\"");
if (mManager.mFileIndex >= 0) {
command.add("--select " + mManager.mFileIndex);
}
if (mManager.mSaveTo != null) {
command.add("--out \"" + mManager.mSaveTo + "\"");
}
mManager.mExec.command(command);
String cmdStr = "";
for (String s : command) {
cmdStr = cmdStr.concat(s + " ");
}
return cmdStr.trim();
}
What might be wrong?
Okay, so I was able to fix this issue.
The / character following the path specified as value of --out was causing the problem. In order to fix this, I added a line in node_modules/webtorrent-cli/bin/cmd.js to print the arguments passed to webtorrent:
console.log(process.argv)
With the /, output of this line was something like the following:
[ 'D:\\downloadmanager\\node\\node.exe',
'D:\\downloadmanager\\node\\node_modules\\webtorrent-cli\\bin\\cmd.js',
'download',
'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel',
'--select',
'0',
'--out',
'D:\\nf"' ]
Note the " that is included in the path after D:\\nf. When / is removed from the path, the quote disappears and webtorrent behaves as expected.
I doubt that this is a bug in webtorrent. I think zt-exec (or maybe I) was doing something stupid.
Somewhat unrelated, but I think I should also mention that I had to enclose every value for each option with quotes, even the index, to get rid of other nasty errors (e.g.: Error 87, the parameter is incorrect)

Ensure Install4j Uses only its bundled jre and never Java found by path

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());
}

how to use property=value in CLI commons Library

I am trying to use the OptionBuilder.withArgName( "property=value" )
If my Option is called status and my command line was:
--status p=11 s=22
It only succeeds to identify the first argument which is 11 and it fails to identify the second argument...
Option status = OptionBuilder.withLongOpt("status")
.withArgName( "property=value" )
.hasArgs(2)
.withValueSeparator()
.withDescription("Get the status")
.create('s');
options.addOption(status);
Thanks for help in advance
You can access to passed properties using simple modification of passed command line options
--status p=11 --status s=22
or with your short syntax
-s p=11 -s s=22
In this case you can access to your properties simply with code
if (cmd.hasOption("status")) {
Properties props = cmd.getOptionProperties("status");
System.out.println(props.getProperty("p"));
System.out.println(props.getProperty("t"));
}
If you need to use your syntax strictly, you can manually parse your property=value pairs.
In this case you should remove .withValueSeparator() call, and then use
String [] propvalues = cmd.getOptionValues("status");
for (String propvalue : propvalues) {
String [] values = propvalue.split("=");
System.out.println(values[0] + " : " + values[1]);
}

Categories