How to asynchronously run JBoss server application from Java - java

In my java application, I need to run a Jboss server with the file standalone.bat.
I tried ProcessBuilder, and though it did start the server, my application is blocked waiting for the server to go down
#RequestMapping(value = "api/project/liststart", method = RequestMethod.POST)
public HttpEntity<Boolean> postListServer(#RequestBody ListStart modules) throws Throwable {
String cmd = "";
Boolean response = false;
ProcessBuilder processBuilder = new ProcessBuilder();
String path = "C:\\jboss-as-7.1.1.Final\\bin\\";
String command = standelone.bat+ " >sometext.txt" ;
processBuilder.command("cmd.exe", "/c", command);
processBuilder.directory(new File(path));
Process process = processBuilder.start();
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String ligne;
while ((ligne = reader.readLine()) != null) {
System.out.println(ligne);
}
int exitCode = process.waitFor();
System.out.println("\nExited with error code : " + exitCode);
String F = path + "\\SomeFile.txt";
System.out.println("------------------------file: " + F);
File file = new File(F);
Scanner scanner = new Scanner(file);
//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (line.contains("Started server")) {
response = true;
System.out.println("-------------------------------------" + response.toString());
}
}
ResponseEntity responseEntity = new ResponseEntity<Boolean>(response, HttpStatus.OK);
return responseEntity;
}
}
I expect the method above to return true value, but it's being blocked before a value can be returned.

It seems like scanner.hasNextLine() can't get out from while cycle, so try like this :
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (line.contains("Started server")) {
response = true;
System.out.println("-------------------------------------" + response.toString());
return new ResponseEntity<Boolean>(response, HttpStatus.OK);
} else {
return new ResponseEntity<Boolean>(response, HttpStatus.OK);
}
}

Related

Command injection attack: tempered input value with &&

Controller:
#PostMapping("/output/")
#ResponseBody
public Object command_injected(#RequestParam String command) {
Map<String, String> response_data = new HashMap<String, String>();
try {
String output = "";
Process p = Runtime.getRuntime().exec("ping -c 3 " + command) ;
String line = "";
BufferedReader inputStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader errorStream = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = inputStream.readLine()) != null) {
output += line + "<br/>";
}
inputStream.close();
while ((line = errorStream.readLine()) != null) {
output += line + "<br/>";
}
errorStream.close();
p.waitFor();
response_data.put("status", "success");
response_data.put("msg", output);
return response_data;
} catch (Exception e) {
e.printStackTrace();
response_data.put("status", "error");
response_data.put("msg", "No output found");
return response_data;
}
}
example input (Linux):
8.8.8.8 && ls && whoami
To show a command injection attack, I want to temper my input using &&. If I enter only IP address, this thing works. If I enter the above example, things are not ok and giving me the following:
ping: whoami: Temporary failure in name resolution
Please help!!

Java: Run main of another class and get the stdout of that class

I am running something like this
String[] reassignCmdArgs =
{ "--reassignment-json-file=" + jsonFile,
"--zookeeper=" + zkConnect,
"--throttle=" + (throttle <= 0 ? "1000000000" : throttle),
"--execute" };
ReassignPartitionsCommand.main(reassignCmdArgs);
The ReassignPartitionsCommand has some println statements and I would like to capture those here.
How can this be done?
EDIT:
My current workaround is below. I'm looking for something that does not start another process
String[] reassignCmdArgs =
{ "--reassignment-json-file=" + jsonFile,
"--zookeeper=" + zkConnect,
"--throttle=" + (throttle <= 0 ? "1000000000" : throttle),
"--execute" };
System.out.println("Calling ReassignPartitionsCommand with args: " +
Arrays.toString(reassignCmdArgs));
StringBuilder result = new StringBuilder();
try {
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader) cl).getURLs();
ProcessBuilder pb = new ProcessBuilder();
pb.redirectErrorStream(true);
String classPath = Arrays.asList(urls)
.stream()
.map(URL::getFile)
.collect(Collectors.joining(";"));
String[] args = new String[4 + reassignCmdArgs.length];
args[0] = "java";
args[1] = "-cp";
args[2] = classPath;
args[3] = ReassignPartitionsCommand.class.getName();
for (int i = 4; i < 4 + reassignCmdArgs.length; i++) {
args[i] = reassignCmdArgs[i - 4];
}
pb.command(args);
System.out.println("Calling process with args: " + Arrays.toString(args));
Process p = pb.start();
p.waitFor(); // wait for process to finish
BufferedReader bri =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = bri.readLine()) != null) {
result.append(line + "\n");
}
} catch (Exception e) {
result = new StringBuilder("Problem running as another process");
ReassignPartitionsCommand.main(reassignCmdArgs);
}
You should look at ProcessBuilder; you can specify where the output goes e.g. pb.redirectOutput(Redirect.appendTo(log)). Then simply read the output from the file you specify.

How can I close a Java application from another Java application?

I am using the following code for running an application:
private void RunApp2() throws IOException
{
StringBuilder sb = new StringBuilder();
String filePath = System.getProperty("user.dir");
String jarfile = filePath + "\\MyAppV2.jar";
File f = new File(jarfile);
if(f.exists() && !f.isDirectory()) {
// do something
}
else
{
AreThereProblem = true;
}
try { // jarname arguments has to be saperated by spaces
Process process = Runtime.getRuntime().exec("cmd.exe start /C java -jar \""+jarfile + "\"");
//.exec("cmd.exe /C start dir java -jar "+jarfile+" "+name+" "+id+" dir");
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream ()));
String line = null;
while ((line = br.readLine()) != null){
sb.append(line).append("\n");
}
System.out.println("Console OUTPUT : \n"+sb.toString());
//process.destroy();
}catch (Exception e){
lblInformation.setText(e.getMessage());
}
}
But how can I close MyAppV2.jar application if it is already running before I'm running it again?

how to pass data between 2 #RequestMapping

i have 2 #RequestMapping; the first uploades a video to my server and the second execute a transcoding linux command.
every #RequestMapping is working but i am tryig from a week to get the filename of the uploaded file from the first #RequestMapping and send it to the second one.
please help me !
this is the first One:
#RequestMapping(value = "/uploadajax", method = RequestMethod.POST)
#ResponseBody
public List<ObjectNode> uploadMultipleFiles(Model model, MultipartHttpServletRequest request, HttpServletResponse response,
Principal principal) throws IOException {
CommonsMultipartFile multipartFile = null;
Iterator<String> iterator = request.getFileNames();
ObjectMapper objectMapper = new ObjectMapper();
FileMeta fileMeta = null;
while (iterator.hasNext()) {
String key = iterator.next();
multipartFile = (CommonsMultipartFile) request.getFile(key);
String uploadedFileName = multipartFile.getOriginalFilename();
try {
List<ObjectNode> listFileNode = new ArrayList<ObjectNode>();
byte[] bytes = multipartFile.getBytes();
String phyPath = request.getSession().getServletContext().getRealPath("/");
String repoUserPath=phyPath+"resources/"+user.getId();
System.out.println("-------------"+user.getId()+"------------------");
System.out.println("####"+repoUserPath);
File repoUSer = new File(repoUserPath);
if (!repoUSer.exists()) {
repoUSer.mkdir();
String filepath =repoUserPath+"/"+multipartFile.getOriginalFilename();
System.out.println("####"+filepath);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(filepath));
stream.write(bytes);
stream.close();
fileMeta = new FileMeta();
fileMeta.setFileName(multipartFile.getOriginalFilename());
fileMeta.setFileSize((multipartFile.getSize()/1024)/1024+" Mb");
fileMeta.setFileType(multipartFile.getContentType());
fileMeta.setPathfile("http://89.40.113.84:8080/ProjectTranscode/resources/"+user.getId()+"/"+multipartFile.getOriginalFilename());
fileMeta.setLinkdelete("/var/lib/tomcat7/webapps/ProjectTranscode/resources/"+user.getId()+"/"+multipartFile.getOriginalFilename());
serviceMangerTranscode.save(fileMeta);
fileMeta.setUser(user);
serviceMangerTranscode.updateFile(fileMeta);
file= fileMeta;
model.addAttribute("Nomf", file.getFileName());
System.out.println("created!!");
String[] cmdArray = {"ffprobe","-show_streams","-i",filepath };
model.addAttribute("filepath",filepath);
System.out.println("ffprobe2........!!");
//String[] cmdArray = {"ping","www.google.com" };
Process process = Runtime.getRuntime().exec(cmdArray);
InputStream processInputStream =process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(processInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
System.out.println("<OUTPUT>");
while ( (line = bufferedReader.readLine()) != null){
ObjectNode node = objectMapper.createObjectNode();
System.out.println(line);
node.put("line",line );
listFileNode.add(node);
}
line ="aaa";
ObjectNode node = objectMapper.createObjectNode();
node.put("line",line );
System.out.println("</OUTPUT>");
return listFileNode;
}else {
long size = FileUtils.sizeOfDirectory(repoUSer);
System.out.println("size 1"+(size/1024)/1024);
if ((size/1024)/1024 >100) {
ObjectNode node = objectMapper.createObjectNode();
node.put("error","Size Not Supported for Your repository !");
listFileNode.add(node);
}else{
System.out.println("choix2!!++");
String filepath =repoUserPath+"//"+multipartFile.getOriginalFilename();
System.out.println("####"+filepath);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(filepath));
stream.write(bytes);
stream.close();
// fileMeta = new FileMeta();
fileMeta.setFileName(multipartFile.getOriginalFilename());
fileMeta.setFileSize((multipartFile.getSize()/1024)/1024+" Mb");
fileMeta.setFileType(multipartFile.getContentType());
fileMeta.setPathfile(filepath);
fileMeta.setLinkdelete("/var/lib/tomcat7/webapps/ProjectTranscode/resources/"+user.getId()+"/"+multipartFile.getOriginalFilename());
serviceMangerTranscode.save(fileMeta);
fileMeta.setUser(user);
serviceMangerTranscode.updateFile(fileMeta);
file= fileMeta;
model.addAttribute("filedetails", fileMeta);
System.out.println("fichier créé!!");
String[] cmdArray = {"ffprobe","-show_streams","-i",filepath };
System.out.println("ffprobe executee........!!");
Process process = Runtime.getRuntime().exec(cmdArray);
InputStream processInputStream =process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(processInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
System.out.println("<OUTPUT>");
while ( (line = bufferedReader.readLine()) != null){
ObjectNode node = objectMapper.createObjectNode();
// if (line.contains("codec_type") || line.contains("duration_ts")){
System.out.println(line);
node.put("line",line );
listFileNode.add(node);
}//}
line ="bbb";
ObjectNode node = objectMapper.createObjectNode();
node.put("line",line );
System.out.println("</OUTPUT>");
System.out.println("size 2"+(size/1024)/1024);
return listFileNode;
}
}
} catch (Exception e) {
return null;
}
}
return null;
}
and this is the second one:
#RequestMapping(value ="/Transcodage", method = RequestMethod.POST)
public String Trascoood(Model model, HttpServletRequest request, HttpServletResponse response
) throws IOException {
//Recuperation des valeurs utilisateur:
String userIDD =request.getParameter("useridd");
String newFileName =request.getParameter("newFileName");
String encolist=request.getParameter("encolist");
String codeclist=request.getParameter("codeclist");
String bitrate=request.getParameter("bitratevideo");
String Nomf= request.getParameter("mapping1Form");
System.out.println("NOMFFFFFFFFFFF: " + Nomf);
int userIDDD = Integer.parseInt(userIDD);
User user = userv.getUserById(userIDDD);
ObjectMapper objectMapper = new ObjectMapper();
org.codehaus.jackson.node.ObjectNode node = objectMapper.createObjectNode();
//file= serviceMangerTranscode.getFileById(idfile);
ModelAndView modelUserHome = new ModelAndView("userhome");
//System.out.println("file path : " + file.getPathfile() +"*************************************************");
System.out.println("userIDD: " + userIDD + "...............................................");
System.out.println("newFileName: " + newFileName + "...............................................");
System.out.println("encolist: " + encolist + "...............................................");
String newFileN = new StringBuilder().append(".").append(newFileName).append(".").append(encolist).toString();
System.out.println("FILE NAME + EXTENTION: " + newFileN + "...............................................");
//node.put("success", "true");
String[] cmdArray = {"sudo", "ssh", "-tt", "root#89.40.113.84", "/root/dved", "-l", "89.40.112.120,89.40.112.248", "you.mp4", "-s",newFileN};
//String[] cmdArray = {"sudo", "/root/dve", "-l", "89.40.112.120,89.40.112.248", "/root/greece.mkv", "-s",".teeeeeeeeeeeeest.avi" };
//String[] cmdArray = {"sudo","/root/dve","-s",".encoded.avi","-l","89.40.112.248","/root/greece.mkv" };
List<ObjectNode> listFileNode = new ArrayList<ObjectNode>();
try{
Runtime rt = Runtime.getRuntime();
ProcessBuilder pb = new ProcessBuilder(cmdArray);
Process proc = pb.start();
//Process proc = rt.exec(cmdArray);
int rc =0;
rc = proc.waitFor(); // Wait for the process to finish.
System.out.printf("Script executed successfully in ", rc);
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR___EXEC>");
while ( (line = br.readLine()) != null){
System.out.println(line);
node.put("line",line );
listFileNode.add(node);
}
System.out.println("</ERROR___EXEC>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
InputStream processInputStream =proc.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(processInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
System.out.println("<RESULTAT___EXEC>");
while ( (line = bufferedReader.readLine()) != null){
System.out.println(line);
node.put("lineR",line );
listFileNode.add(node);
}
System.out.println("</RESULTAT___EXEC>");
}catch (Throwable t)
{
t.printStackTrace();
}
model.addAttribute("usersize",user.getUserfiles().size());
model.addAttribute("listfiles",user.getUserfiles());
model.addAttribute("user",user);
model.addAttribute("MsgTranscode","Votre video a bien ete encodee, vous pouvez desormais la telecharger de votre portfolio!");
return "userhome";
}
Thank you for your reply, i think it cannot be done so i put the data in the database than recover it in the second RequestMapping

Java - Remote Console

For my server coded in java I want to add a console. I connect to my server using a socket.
Here is the code I've made for the console:
On my server:
public class ServerConsole
{
public String exec(String[] cmd)
{
try
{
Process child = Runtime.getRuntime().exec(cmd);
InputStream in = child.getInputStream();
StringBuffer buffer = new StringBuffer();
int c;
while ((c = in.read()) != -1)
{
buffer.append((char)c);
}
in.close();
return buffer.toString();
}
catch (Exception e) {}
return "FAILED";
}
}
This class execute the given command and returns a string that contains the content of the console after execution.
I call this method like that:
String cmd_data_cmd = inputStream.readUTF();
String[] dataCmd = cmd_data_cmd.split("#");
OSCmd osCmd = new OSCmd();
outputStream.writeUTF(osCmd.exec(dataCmd));
Where inputStream is the stream I use with my socket. It works well!
Now, on the client side, I've made that:
String[] cmd = cmd_input.getText().split(" ");
String new_cmd = "";
for (String part : cmd)
new_cmd += (new_cmd.equals("") ? "": "#") + part;
this.outputSocket.writeUTF(new_cmd);
DataInputStream result_input = new DataInputStream(this.input);
String tmp = result_input.readUTF();
System.out.println(tmp);
This should returns me the result displayed in the console but actually, nothing happens. It just freezes when I start that part of code.
Any idea how to do that?
Thanks.
Here is the solution:
String[] cmd_exec = {};
String os_name = System.getProperty("os.name").toLowerCase();
if (os_name.indexOf("win") >= 0)
cmd_exec = new String[]{"cmd.exe", "/c", cmd};
else if (os_name.indexOf("mac") >= 0)
cmd_exec = new String[]{"/usr/bin/open", "-a", cmd};
else if (os_name.indexOf("nix") >= 0 || os_name.indexOf("nux") >= 0)
cmd_exec = new String[]{"/bin/bash", cmd};
else if (os_name.indexOf("sunos") >= 0)
cmd_exec = new String[]{"/bin/bash", cmd};
Process child = Runtime.getRuntime().exec(cmd_exec);
String line;
while ((line = stdInput.readLine()) != null)
{
buffer.append("\t" + new String(line.getBytes("UTF-8"), "UTF-8") + "\n");
}
stdInput.close();
while ((line = stdError.readLine()) != null)
{
buffer.append("\t" + new String(line.getBytes("UTF-8"), "UTF-8") + "\n");
}
stdError.close();
child.destroy();
Hope this will help someone else.

Categories

Resources