Tomcat webapp's file path under multiple OS - java

Java Code :
//Gives the webapp directory
String pythonScriptPath = getServletContext().getRealPath(File.separator);
//Gives OS name
String OS = System.getProperty("os.name").toLowerCase();
if (OS.indexOf("win") >= 0) {
pythonScriptPath = pythonScriptPath + "scripts\\data_parser.py";
} else if ((OS.indexOf("mac") >= 0) {
pythonScriptPath = pythonScriptPath + "scripts/data_parser.py";
}
String[] cmd = new String[3];
cmd[0] = "python";
cmd[1] = pythonScriptPath;
cmd[2] = "2013-09-10T08:00:00-04:00";
// create runtime to execute external command
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmd);
This code runs fine in a Mac machine. The problem is in windows machine. I'm trying to get the python file under "scripts" directory and execute it. My program was able to find the file in Mac, but not in Windows.
File under Windows : C:\Users\Administrator\TEST.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\TEST\scripts\data_parser.py
File under Mac :
/Users/satishjonnala/TEST/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/TEST/scripts/data_parser.py

Have you see the class org.apache.commons.io.FilenameUtils of Apache Commons IO. The method:
public static String separatorsToSystem(String path)
Converts all separators to the system separator.

Related

Java ProcessBuilder not executing git checkout command

I want to execute 4 commands using ProcessBuilder however 2nd command is not working properly.
My code:
public static void main(String[] args) {
String path_prj = "C:\\Users\\asali\\Desktop\\CallRepoCode";
String origBranch = "frontend";
ArrayList<String> paths = new ArrayList<>();
paths.add("server\\src\\main\\java\\org\\classes\\CallManager.java");
paths.add("server\\src\\main\\java\\org\\classes\\CallUtils.java");
paths.add("server\\src\\main\\java\\org\\classes\\Main.java");
String command_1 = "cd " + path_prj;
String command_2 = " & git checkout " + origBranch;
String command_3 = " & mkdir updated_cia_files ";
String command_4 = " ";
for (String path: paths) {
command_4 = command_4 + "& copy " + path + " updated_cia_files ";
}
String[] command = {"cmd.exe", "/C", command_1, command_2, command_3, command_4 };
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.start();
}
Basically, I want to go to the C:\\Users\\asali\\Desktop\\CallRepoCode and checkout to the frontend branch. There is a GitHub repo, so it should work. After checkout, I want to create a folder and copy 3 files to that folder.
I successfully create the folder and copy the files; however local repo does not checkout to the frontend branch.
EDIT
My command works when I run it manually on cmd.
When I remove the command_3 and command_4 on the code, it executes the git checkout command.
Maybe i can suggest you an other solution, You could use jgit and java directly to do these tasks from java directly
For example (not tested)
FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
repositoryBuilder.setMustExist( true );
repositoryBuilder.setGitDir( ... );
Repository repository = repositoryBuilder.build();
Ref ref = repository.checkout().
setCreateBranch(true).
setName("branchName").
setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).
setStartPoint("origin/" + branchName).
call();

Test works on local Windows machine but fails on Linux server

I have this test:
#Test
void testHeader() {
String inputFile = ".\\src\\main\\resources\\binaryFile";
MDHeader addHeader = new MDHeader();
try (
InputStream inputStream = new FileInputStream(inputFile);
) {
long fileSize = new File(inputFile).length();
byte[] allBytes = new byte[(int) fileSize];
inputStream.read(allBytes);
ProducerRecord<String, byte[]> record = new ProducerRecord<String, byte[]>("foo", allBytes);
ProducerRecord<String, byte[]> hdr = addHeader.addMDHeader(record);
for (Header header : hdr.headers()) {
assertEquals("mdpHeader", header.key());
}
}
catch(Exception e) {
assert (false);
}
}
The test succeeds when run locally through Eclipse on my Windows desktop but it fails at com.me.be.HeaderTests.testMDHeader(HeaderTests.java:81) when trying to build the jar on a Linux server. That's the line assert (false). I haven't got any more information on the issue yet but was wondering if it could be the backslashes in inputFile in a Linux environment?
Java on Windows and Linux will both accept / as path separator, whereas Linux does not like \\ as a path separator - so treats the whole string as ONE path component, not 4 parts as you'd expect:
String inputFile = "./src/main/resources/binaryFile";
However for file handling it is better to use java.nio.Path or java.io.File in place of String.
WINDOWS
jshell> Path.of("./src/main/resources/binaryFile")
$2 ==> .\src\main\resources\binaryFile
Linux
jshell> Path.of("./src/main/resources/binaryFile")
$1 ==> ./src/main/resources/binaryFile
You can also use Path.of without any file separator for any OS:
Path p = Path.of("src","main","resources","binaryFile");
The File.separator string is handy to concat into the path string in order to produce an OS independent file path.
String inputFile = "." + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "binaryFile";
Should give you a cross platform compliant file path.

Octave script run through Netbeans 8.2 (Java Project) is not creating files (edit: not running at all)

I ran an Octave script through Java's ProcessBuilder and Process classes. I used Netbeans and the Script file is in resources folder of the Project I am doing.
When run from bash directly the script is working fine. When run from Java, I'm pretty sure the script is working fine.
In the below program,
#!/usr/bin/octave -qf
function ret = manipulateCell(x)
x = x/max(x(:));
x = x.*255;
x = int32(x);
a1 = mean(x(:));
ret = a1<70;
end
img = imread('aaa.png');
imgInd = rgb2ind(img);
imgGray = ind2gray(imgInd,colormap());
sizeVector = 100*ones(1,20);
Cells = mat2cell(imgGray,sizeVector,sizeVector);
ManipCells = cellfun(#manipulateCell,Cells);
file2D = fopen('data.txt','rw+');
dlmwrite(file2D,ManipCells);
Last two lines seem not to run from Netbeans; there is no output (i.e., no output file is created).
Java Code which is used to run this script.
ProcessBuilder pb = new ProcessBuilder("src/resources/ProcessImg.m");
try{
Process p = pb.start();
}
catch(IOException ex){
ex.printStackTrace();
}
--
Edit:
I have just tried imshow(img) in between the above code. It didn't work either.
Edit:
How I verified that ProcessBuilder and Process work fine? and How do I know which directory I am in.
String command = "pwd";
ProcessBuilder pb = new ProcessBuilder(command);
//pb.directory(new File("./"));
try{
Process p = pb.start();
//Debug Code
pb.redirectErrorStream(true);
BufferedReader bf = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
while((s=bf.readLine())!=null){
System.out.println(s);
}
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();
}
catch(IOException ex){
ex.printStackTrace();
}
If the command string is pwd, the output is
/home/user/NetBeansProjects/Project
If the command string is ls, the output is
build
build.xml
manifest.mf
nbproject
src
test
I want to say that commands are being executed.
Also, process builder is identifying shebang notation.
The problem is NetBeans is not allowing ProcessImg.m to create files in it's directory by an external process probably.
#!/usr/bin/octave -qf
function ret = manipulateCell(x)
x = x/max(x(:));
x = x.*255;
x = int32(x);
a1 = mean(x(:));
ret = a1<70;
end
img = imread('~/Desktop/aaa.png');
imgInd = rgb2ind(img);
imgGray = ind2gray(imgInd,colormap());
sizeVector = 100*ones(1,20);
Cells = mat2cell(imgGray,sizeVector,sizeVector);
ManipCells = cellfun(#manipulateCell,Cells);
file2D = fopen('~/Desktop/data.txt','rw+');
dlmwrite(file2D,ManipCells);
I have put absolute path (from home) as suggested and it didn't work. Not only in NetBeans did the file hasn't been created but also on desktop.
I'm pretty sure that "ProcessBuilder" doesn't understand the Shebang in your script (or you haven't set it executable) and you have to call it like
ProcessBuilder pb = new ProcessBuilder("/usr/bin/octave",
"src/resources/ProcessImg.m");
But this looks like a common problem so I suggest searching for "ProcessBuilder execute bash script" (or perl script) which gives many hits.
Also try an absolute path to your script and explicitely close your file on exit.

Java - Get JVM memory settings at runtime

I have a Java 7 program which launches other Java processes. I would like for memory settings for the original program to be passed along to the child processes.
The processes are launched as follows:
//https://stackoverflow.com/questions/636367/executing-a-java-application-in-a-separate-process
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = MyClass.class.getCanonicalName();
ProcessBuilder pb = new ProcessBuilder(javaBin, "-cp", classpath, "-Djava.ext.dirs=" + System.getProperty("java.ext.dirs"), className, arg1, arg2);
logger.debug("Running as {}", new Object[]{pb.command()});
pb.start();
The process works correctly, except in the cases where the program needs it's children to have additional memory.
I've iterated over System.getProperties() to look for any of the memory settings, but none seem present.
Specifically, the three memory configurations I need are -Xms, -Xmx, and -XX:MaxPermSize
In order to get all JVM parameters including Xmx etc
You have to use
java.lang.management.RuntimeMXBean;
Following example lists all jvm parameters available :
public void runtimeParameters() {
RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
List<String> aList = bean.getInputArguments();
for (int i = 0; i < aList.size(); i++) {
System.out.println(aList.get(i));
}
}

ImageMagick's Convert for EPS to JPEG not being called properly

M primary goal is to take in a series of .eps files and convert them to .jpg using ImageMagick and GhostScript. I have both ImageMagick and GhostScript installed in a Windows environment. I am referencing ImageMagick's convert command using Process in java with no luck. Using Window's cmd tool, I successfully converted an EPS to JPEG by navigating to C:\Program Files\ImageMagick-6.8.9-Q16 and using the following command:
convert Raw\R_GiftcardSizeNew3x5.eps Converted\R_GiftcardSizeNew3x5.jpg
In Java, I use almost the exact same command in the following code:
public void convertEPStoJPG()
{ //commands
ArrayList<String> cmds = new ArrayList<String>();
//absolute file paths of eps files retrieved using a helper method
ArrayList<String> filePaths = this.getFilePaths();
//beginning cmd line calls
cmds.add("cmd.exe");
cmds.add("/c");
cmds.add("cd C:\\Program Files\\ImageMagick-6.8.9-Q16\\");
for (int i = 0; i < filePaths.size(); i++)
{
//conversion calls
String tempPath = filePaths.get(i);
//shortening path name
tempPath = tempPath.substring(tempPath.lastIndexOf("\\") + 1, tempPath.length());
//adding command of "convert Raw\\image.eps Converted\\image.jpg"
cmds.add("convert \\Naked Wines\\Raw\\" + tempPath + " \\Naked Wines\\Converted\\" +
tempPath.substring(0,tempPath.length() - 3) + "jpg");
}
//building process with commands
ProcessBuilder pb = new ProcessBuilder(cmds);
Process process;
try {
pb.redirectErrorStream(true);
//executing commands
process = pb.start();
BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
//print output from command execution
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
where my files im trying to grab are C:\Program Files\ImageMagick-6.8.9-Q16\Naked Wines\Raw
and the destination I am converting to is C:\Program Files\ImageMagick-6.8.9-Q16\Naked Wines\Converted.
I get an error stating "The system cannot find the path specified". Looking at previously answered questions such as How to override Windows' convert command by ImageMagick's one?, people suggest you have to override Windows convert command. Would this be the cause of error, or is there something I am missing? I'm fairly new to ImageMagick and might have missed or misunderstood something.
I ended up approaching this problem in a different way using Im4Java, a pure-java interface to the ImageMagick commandline. I installed the libraries via http://im4java.sourceforge.net/#download. Here is my code for converting eps to jpg:
public void convertESPtoJPG()
{
//initialize ImageMagick operation
IMOperation op = new IMOperation();
//setting my path allows us to use ImageMagicks "convert" vs. Windows "convert"
String myPath="C:\\Program Files\\ImageMagick-6.8.9-Q16";
ProcessStarter.setGlobalSearchPath(myPath);
op.addImage(); //in
op.addImage(); //out
ConvertCmd cmd = new ConvertCmd();
//filter out files for eps files, and load the files using included FilenameLoader
ExtensionFilter filter = new ExtensionFilter("eps");
FilenameLoader loader = new FilenameLoader(filter);
List<String> files = loader.loadFilenames("C:\\Program Files\\ImageMagick-6.8.9-
Q16\\NakedWines\\Raw\\");
//what we plan on converting our eps files to
FilenamePatternResolver resolver = new FilenamePatternResolver("%P/%f.jpg");
//iterate through loaded files
for (String img: files)
{
try {
//execute our convert commands
cmd.run(op,img,resolver.createName(img));
} catch (Exception e) {
e.printStackTrace();
}
}
}
I found this method to be much easier to understand and more forward as well.

Categories

Resources