Я пытаюсь запустить JAR-файл с 3 аргументами. Одним из аргументов является путь к файлу xml. Он хорошо работает в Eclipse перед экспортом файла JAR. Но это не работает при запуске файла JAR вне Eclipse.
Solutiton - это решение клиент / сервер, где я запускаю локальный файл jar (клиент) с javaScript. Клиент вызывает сервлет на стороне сервера.
1) JavaScript код:
function runClientFunc(arg1, arg2, arg3) {
debugger;
var jarFilePath = document.interpret("PRGDIR()") + "\Scripts\\";
var jarFile = jarFilePath + "WebClient.jar";
var runJar = new ActiveXObject("Shell.Application");
runJar.ShellExecute(jarFile, "arg1 arg2 arg3", "", "open", 1);
}
2) Код в файле JAR:
public class WebClient {
static final int BUFFER_SIZE = 4096;
public static void main(String[] args) throws IOException, URISyntaxException {
//Takes file path (input file), url and savedir (directory to save output file) as arguments
String filePath = args[0];
String uploadUrl = args[1];
String saveDir = args[2];
File uploadFile = new File(filePath);
//
//File uploadFile = new File(TaxWebClient.class.getResource(filePath).toURI());
System.out.println("File to upload: " + filePath);
HttpURLConnection httpConn = null;
OutputStream outputStream = null;
FileInputStream inputStream = null;
//InputStream inputStream = null;
try {
//Creates a HTTP connection
URL url = new URL(uploadUrl);
httpConn = (HttpURLConnection) url.openConnection();
//Set timeout (10 and 15 sec.)
httpConn.setConnectTimeout(10000);
httpConn.setReadTimeout(15000);
//Set output & request type
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
//Set headers
httpConn.setRequestProperty("Accept", "text/xml");
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
//Sets file name as a HTTP header
httpConn.setRequestProperty("fileName", uploadFile.getName());
//Opens output stream of the HTTP connection for writing data
outputStream = httpConn.getOutputStream();
//Opens input stream of the file for reading data
inputStream = new FileInputStream(uploadFile);
//Loads file from filePath (arg0) when running as JAR file else JAR file won't work
//inputStream = TaxWebClient.class.getClassLoader().getResourceAsStream(filePath);
//Writing data to servlet (outputstream)
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Start writing data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data was send to servlet.");
} catch (IOException ioe) {
System.out.println("Error:" + ioe.getMessage());
ioe.printStackTrace();
} finally {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
//**RESPONSE**
//************
//Always check HTTP response code from server
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
System.out.println("Server's response: " + responseCode);
InputStream inputStreamFromServlet = null;
//ByteArrayOutputStream byteOutputStreamFromServlet = null;
FileOutputStream fileOutputStreamFromServlet = null;
//OutputStreamWriter outputStreamWriterFromServlet = null;
//String xmlContentFromServlet = null;
try {
//****Getting xml file from response****
//Making output filename from input filename
String fileNameInputWithOutExtension = FilenameUtils.removeExtension(uploadFile.getName());
String fileNameOutput = fileNameInputWithOutExtension + "Output.xml";
File saveFile = new File(saveDir + fileNameOutput);
//Opens input stream of the response for reading data
inputStreamFromServlet = httpConn.getInputStream();
//Opens output stream for writing bytes
//byteOutputStreamFromServlet = new ByteArrayOutputStream();
//Opens an output stream for writing file
fileOutputStreamFromServlet = new FileOutputStream(saveFile);
//Turns bytes based stream into character based writer
//outputStreamWriterFromServlet = new OutputStreamWriter(new FileOutputStream(saveFile), "UTF-8");
//Writes response from servlet (bites) to byte object - the approach is used because the byte object can be used in more situations
byte[] bufferOutput = new byte[BUFFER_SIZE];
int bytesReadOutput = -1;
System.out.println("Receiving data...");
//Writes file from input stream
while ((bytesReadOutput = inputStreamFromServlet.read(bufferOutput)) != -1) {
fileOutputStreamFromServlet.write(bufferOutput, 0, bytesReadOutput);
}
/*Nedenstående kan bruges hvis outputstream skal gemmes som en variabel mv.
while ((bytesReadOutput = inputStreamFromServlet.read(bufferOutput)) != -1) {
byteOutputStreamFromServlet.write(bufferOutput, 0, bytesReadOutput);
}
//Converts byte object to string object using the specified character set
xmlContentFromServlet = byteOutputStreamFromServlet.toString("UTF-8");
//Turns bytes based stream into character based writer (and Opening an output stream for writing file)
outputStreamWriterFromServlet = new OutputStreamWriter(new FileOutputStream(saveFile), "UTF-8");
//Writes file with the chosen UTF
outputStreamWriterFromServlet.write(xmlContentFromServlet);
*/
System.out.println("Data received.");
System.out.println("File written to: " + saveFile.getAbsolutePath());
} catch (IOException ioe) {
System.out.println("Error:" + ioe.getMessage());
ioe.printStackTrace();
} finally {
if (fileOutputStreamFromServlet != null) {
fileOutputStreamFromServlet.close();
}
if (inputStreamFromServlet != null) {
inputStreamFromServlet.close();
}
/*
if (byteOutputStreamFromServlet != null) {
byteOutputStreamFromServlet.close();
}
if (outputStreamWriterFromServlet != null) {
outputStreamWriterFromServlet.close();
}
*/
}
} else {
System.out.println("Server returned non-OK code: " + responseCode);
}
}
}
3) Код сервлета:
public class CalcServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static final int BUFFER_SIZE = 4096;
//Do required initialization of servlet
public void init() throws ServletException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//Gets file name from HTTP header and makes new name for output file
String fileNameInput = request.getHeader("fileName");
//Prints out all header values for test purpose
System.out.println("===== Begin headers =====");
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String headerName = names.nextElement();
System.out.println(headerName + " = " + request.getHeader(headerName));
}
System.out.println("===== End headers =====\n");
FileOutputStream outputStream = null;
InputStream inputStream = null;
try {
//Opens input stream of the request for reading data
inputStream = request.getInputStream();
//Opens an output stream for writing file
outputStream = new FileOutputStream(fileNameInput);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Receiving data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data received.");
} catch (IOException ioe) {
System.out.println("Error:" + ioe.getMessage());
ioe.printStackTrace();
} finally {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
//*****Using file from client in server side calculation*****
//Some business calculation is done here and the result is outputxml
//Making string from output stream
outputXml = new String(outputStreamFromCalc.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
} catch (XmlException e) {
e.printStackTrace();
}
//**RESPONSE**
//************
//Opens an output stream for writing file
ServletOutputStream outputStreamOutput = null;
//Opens an input stream for reading data
InputStream inputStreamOutput = null;
try {
//Converts from string variable to inputstream
inputStreamOutput = new ByteArrayInputStream(outputXml.getBytes(StandardCharsets.UTF_8));
outputStreamOutput = response.getOutputStream();
response.setContentType("text/xml");
response.setHeader("Content-Disposition", "attachment; filename=" + fileNameInput);
byte[] bufferOutput = new byte[BUFFER_SIZE];
int bytesReadOutput = -1;
System.out.println("Sending xml to client...");
while ((bytesReadOutput = inputStreamOutput.read(bufferOutput)) != -1) {
outputStreamOutput.write(bufferOutput, 0, bytesReadOutput);
}
System.out.println("Data received.");
} catch (IOException ioe) {
System.out.println("Error:" + ioe.getMessage());
ioe.printStackTrace();
} finally {
if (outputStreamOutput != null) {
outputStreamOutput.close();
}
if (inputStreamOutput != null) {
inputStreamOutput.close();
}
}
}
//Ensures that POST method, and not browser default GET method, is used or else failure 405
public void doGet (HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
//Do required destroy of servlet
public void destroy() {
}
}
Я получаю следующую ошибку на локальном хосте - Tomcat:
Статус HTTP 500 - Внутренняя ошибка сервера
Тип Отчет об исключении
Описание Сервер возникла непредвиденная ситуация, которая помешала ему выполнить запрос.
Exception
java.lang.NullPointerException
java.io.FileOutputStream.<init>(Unknown Source)
java.io.FileOutputStream.<init>(Unknown Source)
CalcServlet.doPost(CalcServlet.java:71)
CalcServlet.doGet(CalcServlet.java:180)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)