How to make a Rest API call to start an executable

2019-08-09 07:45发布

问题:

Can anyone give suggestions on how to make a Rest API call to start an executable file using java? Suppose I have an executable file in my local and I want to make a REST api call to that executable file.

Code snippet with servlets and jsp

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws   
IOException {

             try{

                 PrintWriter out = res.getWriter();

                  String browsefile = req.getParameter("browsefile");

                  if(browsefile == null || browsefile.equals("")){
                      out.println("File does not exist");

                      throw new ServletException("File Name can't be 
null or empty");

                  }

                  File file = new File("C:/lic/test.li");
                 // File file = new File("C:/apache-tomcat-    
7.0.42/webapps/Lic/test.li");

                  if(!file.exists()){
                      out.println("File does not exist");

                      throw new ServletException("File doesn't exists   
on server.");

                  }

                 res.setContentType("text/html;charset=UTF-8");  


                    Runtime rt = Runtime.getRuntime();
                                        Process pr = rt.exec 
("C:\\tools\\server\\grd.exe" );

                    BufferedReader stdInput = new BufferedReader(new 
InputStreamReader(pr.getInputStream()));
                    BufferedReader input = new BufferedReader(stdInput);
                    String serverstarted="";
                    StringBuffer startOutput = new StringBuffer();
                            while((serverstarted = input.readLine()) != 
null){
                                startOutput.append(serverstarted 
+ "\n");
                            }

                            req.setAttribute("startOutput", 
startOutput.toString());
                            req.getRequestDispatcher
("grdoptions.jsp").forward(req, res);
                }catch (Throwable t)  
                  {  
                    t.printStackTrace();  
                  }  


                finally {  

                }  }

}

JSP:

<form action="start" METHOD="GET" enctype="multipart/form-data">
            <input type="file" name="browsefile" />
            <input type="submit" name="start" 
 value="StartServer" />
            </form>

            <div id="result">
                            <pre>
    ${requestScope.startOutput}
</pre>
                        </div>

Web.XML:

<servlet>       
    <servlet-name>Start</servlet-name>
    <servlet-class>com.abc.lic.Start</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>Start</servlet-name>
    <url-pattern>/start</url-pattern>
</servlet-mapping>

回答1:

You've filed this under Java, so I'll keep it to Java, and assume you have some Java web container or other available. You will need to create a wrapper component (Servlet, etc), deployed to the web container, to create a service with a RESTful API.

The implementation of your service will use the Java API to make a system call via a Runtime.getRuntime().exec() call, or using the Process/ProcessBuilder classes. The latter is probably preferred. Depends on what you need to do with your executable file.

Added as a response to your comment and updated question:

You're most (arguably all) of the way there, I think. To oversimplify, REST is about making services available using standard HTTP approaches and verbs.

You can easily argue that the code you have is already RESTful. You already respond to a POST request that includes a multipart form data and runs the executable file. Right now that's someone using a browser. But any piece of code sitting on another client can post to your service as it sits.

Added a bit more to complete the thought:

Also, one more thing regarding your implementation. You might like to make the URI for the POST parameterless. That is, you could have the URI be /start/[filename reference], rather than /start?browseFile=[filename reference]. That would be a bit more REST-y, but is not totally required to get going. You'd have to extract your filename from the path, in this case.

A final note: If you would like to keep your form-based submission as well, it's probably worthwhile to extract the "meat" of this code into a Java class. There are a lot of ways to slice it, but that class could encapsulate trying to open the file, and executing your EXE once the file is found. This class could be called from your existing form-based JSP, and a new "REST" JSP that has a slightly different URI path and that returns JSON.

You have all the parts, you just need to assemble them into a RESTful service.



回答2:

It sounds like you're confused about what Java should do and what REST is. As you described your problem, this will require two executables running on one machine. One will be a REST server that always stays alive, listening for requests. The other would be a Java executable that presumably runs then dies. The REST server you can write in any language, and I would use a lighter-weight language than Java, since it really shouldn't be longer than 5 lines long based on what it does. In other words, there is no "REST API" here. You can write the server component in Java, using one of its REST libraries.

But this raises the question: Why have two processes? It sounds like you just want a Java server running that performs an operation when a request comes in. This operation will be whatever code the executable would run, but it won't run another executable.

But it sounds like you have a bootstrapping problem. Some application will have to be running as a server, listening for requests. How does that process start? In an init script on the server, by you manually, leveraging a platform like Heroku or AWS, but it's not avoidable to have this component.



标签: java rest