List of usage examples for java.lang Process destroy
public abstract void destroy();
From source file:org.sonar.api.utils.command.CommandExecutor.java
/** * @throws org.sonar.api.utils.command.TimeoutException on timeout, since 4.4 * @throws CommandException on any other error * @param timeoutMilliseconds any negative value means no timeout. * @since 3.0//from www.jav a 2s. c o m */ public int execute(Command command, StreamConsumer stdOut, StreamConsumer stdErr, long timeoutMilliseconds) { ExecutorService executorService = null; Process process = null; StreamGobbler outputGobbler = null; StreamGobbler errorGobbler = null; try { ProcessBuilder builder = new ProcessBuilder(command.toStrings(false)); if (command.getDirectory() != null) { builder.directory(command.getDirectory()); } builder.environment().putAll(command.getEnvironmentVariables()); process = builder.start(); outputGobbler = new StreamGobbler(process.getInputStream(), stdOut); errorGobbler = new StreamGobbler(process.getErrorStream(), stdErr); outputGobbler.start(); errorGobbler.start(); executorService = Executors.newSingleThreadExecutor(); Future<Integer> ft = executorService.submit((Callable<Integer>) process::waitFor); int exitCode; if (timeoutMilliseconds < 0) { exitCode = ft.get(); } else { exitCode = ft.get(timeoutMilliseconds, TimeUnit.MILLISECONDS); } waitUntilFinish(outputGobbler); waitUntilFinish(errorGobbler); verifyGobbler(command, outputGobbler, "stdOut"); verifyGobbler(command, errorGobbler, "stdErr"); return exitCode; } catch (java.util.concurrent.TimeoutException te) { throw new TimeoutException(command, "Timeout exceeded: " + timeoutMilliseconds + " ms", te); } catch (CommandException e) { throw e; } catch (Exception e) { throw new CommandException(command, e); } finally { if (process != null) { process.destroy(); } waitUntilFinish(outputGobbler); waitUntilFinish(errorGobbler); closeStreams(process); if (executorService != null) { executorService.shutdown(); } } }
From source file:org.gytheio.util.exec.RuntimeExec.java
/** * Executes the statement that this instance was constructed with an optional * timeout after which the command is asked to * /*from w ww . j a v a 2s .c om*/ * @param properties the properties that the command might be executed with. * <code>null</code> properties will be treated as an empty string for substitution * purposes. * @param timeoutMs a timeout after which {@link Process#destroy()} is called. * ignored if less than or equal to zero. Note this method does not guarantee * to terminate the process (it is not a kill -9). * @param stdOutGobblerFactory the object used to create the output input stream reader * If null the defaultInputStreamReaderThreadFactory will be used * @param stdErrGobblerFactory the object used to create the error input stream reader * If null the defaultInputStreamReaderThreadFactory will be used * * @return Returns the full execution results */ public ExecutionResult execute(Map<String, String> properties, InputStreamReaderThreadFactory stdOutGobblerFactory, InputStreamReaderThreadFactory stdErrGobblerFactory, final long timeoutMs) { int defaultFailureExitValue = errCodes.size() > 0 ? ((Integer) errCodes.toArray()[0]) : 1; // check that the command has been set if (command == null) { throw new GytheioRuntimeException("Runtime command has not been set: \n" + this); } if (stdOutGobblerFactory == null) { stdOutGobblerFactory = defaultInputStreamReaderThreadFactory; } if (stdErrGobblerFactory == null) { stdErrGobblerFactory = defaultInputStreamReaderThreadFactory; } // create the properties Runtime runtime = Runtime.getRuntime(); Process process = null; String[] commandToExecute = null; try { // execute the command with full property replacement commandToExecute = getCommand(properties); final Process thisProcess = runtime.exec(commandToExecute, processProperties, processDirectory); process = thisProcess; if (timeoutMs > 0) { final String[] command = commandToExecute; timer.schedule(new TimerTask() { @Override public void run() { // Only try to kill the process if it is still running try { thisProcess.exitValue(); } catch (IllegalThreadStateException stillRunning) { if (transformerDebugLogger.isDebugEnabled()) { transformerDebugLogger.debug("Process has taken too long (" + (timeoutMs / 1000) + " seconds). Killing process " + Arrays.deepToString(command)); } thisProcess.destroy(); } } }, timeoutMs); } } catch (IOException e) { // The process could not be executed here, so just drop out with an appropriate error state String execOut = ""; String execErr = e.getMessage(); int exitValue = defaultFailureExitValue; ExecutionResult result = new ExecutionResult(null, commandToExecute, errCodes, exitValue, execOut, execErr); logFullEnvironmentDump(result); return result; } // create the stream gobblers InputStreamReaderThread stdOutGobbler = stdOutGobblerFactory.createInstance(process.getInputStream(), charset); InputStreamReaderThread stdErrGobbler = stdErrGobblerFactory.createInstance(process.getErrorStream(), charset); // start gobbling stdOutGobbler.start(); stdErrGobbler.start(); // wait for the process to finish int exitValue = 0; try { if (waitForCompletion) { exitValue = process.waitFor(); } } catch (InterruptedException e) { // process was interrupted - generate an error message stdErrGobbler.addToBuffer(e.toString()); exitValue = defaultFailureExitValue; } if (waitForCompletion) { // ensure that the stream gobblers get to finish stdOutGobbler.waitForCompletion(); stdErrGobbler.waitForCompletion(); } // get the stream values String execOut = stdOutGobbler.getBuffer(); String execErr = stdErrGobbler.getBuffer(); // construct the return value ExecutionResult result = new ExecutionResult(process, commandToExecute, errCodes, exitValue, execOut, execErr); // done logFullEnvironmentDump(result); return result; }
From source file:org.omegat.core.data.RealProject.java
/** * Clear cache of previously run external processes, terminating any that haven't finished. *//* w w w.j av a 2s .c o m*/ private void flushProcessCache() { while (!processCache.isEmpty()) { Process p = processCache.pop(); try { p.exitValue(); } catch (IllegalThreadStateException ex) { p.destroy(); } } }
From source file:com.esminis.server.mariadb.server.MariaDbServerLauncher.java
void initializeDataDirectory(Context context, File binary, File root) throws IOException { File[] files = root.listFiles(); if (files != null && files.length > 0) { return;// ww w. j a v a 2s. com } synchronized (lock) { final List<String> environment = getEnvironment(); final List<String> command = createCommandInternal(context, binary, root); Collections.addAll(command, "--bootstrap", "--log-warnings=0", "--max_allowed_packet=8M", "--net_buffer_length=16K"); final File dataMysqlDirectory = new File(root, "mysql"); if (dataMysqlDirectory.isDirectory()) { return; } if (!dataMysqlDirectory.mkdirs()) { throw new IOException("Cannot create directory: " + dataMysqlDirectory.getAbsolutePath()); } final Process process = Runtime.getRuntime().exec(command.toArray(new String[command.size()]), environment.toArray(new String[environment.size()]), root); final Object[] finishedWithError = { null }; try { final OutputStream stream = process.getOutputStream(); Observable.create(new Observable.OnSubscribe<Void>() { @Override public void call(Subscriber<? super Void> subscriber) { final InputStream inputStream = process.getErrorStream(); String data = ""; for (;;) { synchronized (finishedWithError) { if (finishedWithError[0] != null) { break; } } try { int available = inputStream.available(); if (available > 0) { for (int i = 0; i < available; i++) { data += (char) inputStream.read(); } if (getFreeSpace(dataMysqlDirectory) < 1024L * 1024L || data.contains("No space left on device")) { synchronized (finishedWithError) { finishedWithError[0] = new IOException("No space left on device"); } process.destroy(); break; } } } catch (Throwable ignored) { } Thread.yield(); } subscriber.onCompleted(); } }).subscribeOn(Schedulers.newThread()).subscribe(); writeToStream(stream, "use mysql;\n"); writeToStream(stream, context, "sql/mysql_system_tables.sql"); writeToStream(stream, context, "sql/mysql_performance_tables.sql"); writeToStream(stream, context, "sql/mysql_system_tables_data.sql"); writeToStream(stream, context, "sql/add_root_from_any_host.sql"); writeToStream(stream, context, "sql/fill_help_tables.sql"); writeToStream(stream, "exit;\n"); process.waitFor(); } catch (Throwable e) { FileUtils.deleteDirectory(root); //noinspection ResultOfMethodCallIgnored root.mkdirs(); synchronized (finishedWithError) { if (finishedWithError[0] != null && finishedWithError[0] instanceof IOException) { throw (IOException) finishedWithError[0]; } else { throw new IOException( e.toString() + "\n\nLog:\n" + IOUtils.toString(process.getErrorStream())); } } } finally { synchronized (finishedWithError) { if (finishedWithError[0] == null) { finishedWithError[0] = true; } } } } }
From source file:com.scooter1556.sms.server.io.AdaptiveStreamingProcess.java
private void postProcess(String path, String format) { // Process for transcoding Process postProcess = null; LogService.getInstance().addLogEntry(LogService.Level.DEBUG, CLASS_NAME, "Post processing segment " + path + " with format '" + format + "'", null); try {//w w w . java 2s. co m // Generate post-process command List<String> command = new ArrayList<>(); command.add(transcoder.getPath().toString()); command.add("-i"); command.add(path); command.add("-c:a"); command.add("copy"); command.add("-f"); command.add(format); command.add(path + ".tmp"); LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME, StringUtils.join(command, " "), null); ProcessBuilder processBuilder = new ProcessBuilder(command); postProcess = processBuilder.start(); new NullStream(postProcess.getInputStream()).start(); // Wait for process to finish postProcess.waitFor(); // Rename file once complete File temp = new File(path + ".tmp"); File segment = new File(path + "." + format); if (temp.exists()) { temp.renameTo(segment); } } catch (IOException ex) { LogService.getInstance().addLogEntry(Level.ERROR, CLASS_NAME, "Failed to post-process file " + path, ex); } catch (InterruptedException ex) { //Do nothing... } finally { if (postProcess != null) { postProcess.destroy(); } } }
From source file:org.sqsh.ConnectionDescriptorManager.java
/** * Execute a program that generates a valid connection XML file. * @param prog the program to execute// w w w . j a v a 2s .c o m */ public void loadFromProgram(String prog) { Process process; try { process = Runtime.getRuntime().exec(prog); } catch (IOException e) { LOG.warning("Failed to execute \"" + prog + "\": " + e.getMessage()); return; } final BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream())); final StringBuilder errBuffer = new StringBuilder(); Thread errorConsumer = new Thread() { public void run() { try { LOG.fine("Error stream reader running"); String line; while ((line = err.readLine()) != null) { errBuffer.append(line).append("\n"); } } catch (IOException e) { // Ignored } LOG.fine("Error stream reader shut down"); } }; errorConsumer.start(); InputStream in = process.getInputStream(); boolean ok = true; if (!load(in, prog)) { ok = false; // Consume left over input so the program can finish try { byte buffer[] = new byte[1024]; while ((in.read(buffer)) >= 0) { // Nothing to see here. Move along. } } catch (IOException e) { // Ignored } } process.destroy(); if (!ok && errBuffer.length() > 0) { LOG.warning(prog + " error output:"); LOG.warning(errBuffer.toString()); } }
From source file:org.trancecode.xproc.step.ExecStepProcessor.java
@Override protected void execute(final StepInput input, final StepOutput output) throws Exception { final String pathSeparator = input.getOptionValue(XProcOptions.PATH_SEPARATOR); final String command; if (pathSeparator != null) { command = input.getOptionValue(XProcOptions.COMMAND).replace(pathSeparator, File.separator); } else {/*from w w w. j av a 2s .co m*/ command = input.getOptionValue(XProcOptions.COMMAND); } final String argSeparator = input.getOptionValue(XProcOptions.ARG_SEPARATOR, " "); final Iterable<String> rawArgs = TcStrings.split(input.getOptionValue(XProcOptions.ARGS), argSeparator); final Iterable<String> args = Iterables.transform(rawArgs, arg -> { if (pathSeparator != null) { return arg.replace(pathSeparator, File.separator); } return arg; }); final String cwd = input.getOptionValue(XProcOptions.CWD); final List<XdmNode> inputDocuments = ImmutableList.copyOf(input.readNodes(XProcPorts.SOURCE)); if (inputDocuments.size() > 1) { throw XProcExceptions.xd0006(input.getStep().getLocation(), input.getStep().getPortReference(XProcPorts.SOURCE)); } final boolean sourceIsXml = Boolean.parseBoolean(input.getOptionValue(XProcOptions.SOURCE_IS_XML)); final boolean resultIsXml = Boolean.parseBoolean(input.getOptionValue(XProcOptions.RESULT_IS_XML)); final boolean wrapResultLines = Boolean.parseBoolean(input.getOptionValue(XProcOptions.WRAP_RESULT_LINES)); final boolean errorsIsXml = Boolean.parseBoolean(input.getOptionValue(XProcOptions.ERRORS_IS_XML)); final boolean wrapErrorLines = Boolean.parseBoolean(input.getOptionValue(XProcOptions.WRAP_ERROR_LINES)); if ((resultIsXml && wrapResultLines) || (errorsIsXml && wrapErrorLines)) { throw XProcExceptions.xc0035(input.getStep().getLocation()); } final List<String> commandLine = Lists.newArrayList(); commandLine.add(command); Iterables.addAll(commandLine, Iterables.filter(args, StringPredicates.isNotEmpty())); LOG.trace(" commandLine = {}", commandLine); final ProcessBuilder processBuilder = new ProcessBuilder(commandLine.toArray(new String[0])); processBuilder.redirectErrorStream(false); if (cwd != null) { final Path newDirectory = Paths.get(cwd); if (!Files.isDirectory(newDirectory)) { throw XProcExceptions.xc0034(input.getLocation()); } processBuilder.directory(new File(cwd)); } final Process process; try { process = processBuilder.start(); } catch (IOException e) { throw XProcExceptions.xc0033(input.getLocation()); } if (!inputDocuments.isEmpty()) { final String inputContent; if (sourceIsXml) { inputContent = inputDocuments.get(0).toString(); } else { inputContent = SaxonAxis.childElement(inputDocuments.get(0)).getStringValue(); } new Thread(() -> { try { IOUtils.write(inputContent, process.getOutputStream()); } catch (final IOException e) { throw new IllegalStateException(e); } finally { Closeables.closeQuietly(process.getOutputStream()); } }).start(); } final Supplier<File> stdout = TcByteStreams.copyToTempFile(process.getInputStream()); final Supplier<File> stderr = TcByteStreams.copyToTempFile(process.getErrorStream()); final int exitCode = process.waitFor(); LOG.trace("exitCode = {}", exitCode); final String failureThreshold = input.getOptionValue(XProcOptions.FAILURE_THRESHOLD); if (failureThreshold != null) { LOG.trace("failureThreshold = {}", failureThreshold); final int numericFailureThreshold = Integer.parseInt(failureThreshold); if (exitCode > numericFailureThreshold) { throw XProcExceptions.xc0064(input.getLocation(), exitCode, numericFailureThreshold); } } final File stdoutFile = stdout.get(); final File stderrFile = stderr.get(); process.destroy(); final Processor processor = input.getPipelineContext().getProcessor(); output.writeNodes(XProcPorts.RESULT, parseOutput(stdoutFile, resultIsXml, wrapResultLines, input.getStep().getNode(), processor)); output.writeNodes(XProcPorts.ERRORS, parseOutput(stderrFile, errorsIsXml, wrapErrorLines, input.getStep().getNode(), processor)); output.writeNodes(XProcPorts.EXIT_STATUS, input.newResultElement(Integer.toString(exitCode))); }
From source file:edu.harvard.hul.ois.pds.ws.PDSWebService.java
/** * Process HTTP GET request./*from w ww . j a v a2 s . c om*/ */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, FileNotFoundException { HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req); //Get parameters from the URL String sOp = req.getParameter("op"); char op = 'f'; if (sOp != null) { op = sOp.charAt(0); } String uri = req.getRequestURI(); uri = uri.substring(1); String[] uriElements = uri.split("/"); Integer id = null; String action = null; if (uriElements.length > 2) { action = uriElements[1]; if (action.equalsIgnoreCase(API_SEARCH)) //go straight to fts { String docParam; if ((uriElements[2]).equalsIgnoreCase("global")) { docParam = ""; } else { try { id = new Integer(uriElements[2]); } catch (Exception e) { printError(req, res, "Invalid DRS ID", null); return; } docParam = "G=" + id + "&"; } String format = ""; format = req.getParameter("F"); if (format != null) { format = "&F=" + format; } else { format = "&F=M"; } String range = ""; String advparams = ""; range = req.getParameter("B"); if (range != null) { range = "&B=" + range; } else { range = ""; } String dataQualification = ""; dataQualification = req.getParameter("D"); if (dataQualification != null) { dataQualification = "&D=" + dataQualification; } else { dataQualification = ""; } String contextScope = ""; contextScope = req.getParameter("C"); if (contextScope != null) { contextScope = "&C=" + contextScope; } else { contextScope = ""; } String jumplistRefs = ""; jumplistRefs = req.getParameter("J"); if (jumplistRefs != null) { jumplistRefs = "&J=" + jumplistRefs; } else { jumplistRefs = ""; } String lowerDate = ""; lowerDate = req.getParameter("L"); if (lowerDate != null) { lowerDate = "&L=" + lowerDate; } else { lowerDate = ""; } String upperDate = ""; upperDate = req.getParameter("U"); if (upperDate != null) { upperDate = "&U=" + upperDate; } else { upperDate = ""; } String resultsize = ""; resultsize = req.getParameter("P"); if (resultsize != null) { resultsize = "&P=" + resultsize; } else { resultsize = ""; } advparams = resultsize + range + dataQualification + contextScope + jumplistRefs + lowerDate + upperDate; //Log the search page request WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("search"); message.setMessage("Search Request: " + id); logger.info(message); String Query = req.getParameter("Q"); if (Query == null) { Query = ""; } try { String queryString = new String("?" + docParam + "Q=" + Query + format + advparams); wrapper.setAttribute("searchurl", ftsUrl + queryString); RequestDispatcher rd = req.getRequestDispatcher("/api-search.jsp?"); rd.forward(req, res); //res.sendRedirect(ftsUrl+queryString); return; } catch (Exception e) { message = new WebAppLogMessage(req, true); message.setContext("main"); Throwable root = e; if (e instanceof ServletException) { ServletException se = (ServletException) e; Throwable t = se.getRootCause(); if (t != null) { logger.error(message, t); root = t; } else { logger.error(message, se); } } else { logger.error(message, e); } printError(req, res, "PDS-WS Error", root); } } try { id = new Integer(uriElements[2]); } catch (Exception e) { } } if (id == null) { printError(req, res, "Invalid DRS ID", null); return; } String n = req.getParameter("n"); if (n == null) { n = "1"; } else if (n.equals("")) { printError(req, res, "Page not found", null); return; } //Set scaling factors. s overrides imagesize. Image size select //boxes are based on S. String scale = req.getParameter("s"); String imagesize = req.getParameter("imagesize"); if (scale == null || !(scale.equals("2") || scale.equals("4") || scale.equals("6") || scale.equals("8"))) { if (imagesize != null && imagesize.equals("300")) { scale = "8"; } else if (imagesize != null && imagesize.equals("600")) { scale = "6"; } else if (imagesize != null && imagesize.equals("1200")) { scale = "4"; } else if (imagesize != null && imagesize.equals("2400")) { scale = "2"; } else { scale = "4"; } } if (imagesize == null || !(imagesize.equals("300") || imagesize.equals("600") || imagesize.equals("1200") || imagesize.equals("2400"))) { if (scale.equals("2")) { imagesize = "2400"; } else if (scale.equals("4")) { imagesize = "1200"; } else if (scale.equals("6")) { imagesize = "600"; } else if (scale.equals("8")) { imagesize = "300"; } } String jp2Rotate = req.getParameter("rotation"); if (jp2Rotate == null || jp2Rotate.equals("360") || jp2Rotate.equals("-360")) { jp2Rotate = "0"; } else if (jp2Rotate.equals("-90")) { jp2Rotate = "270"; } String jp2x = req.getParameter("jp2x"); if (jp2x == null) { jp2x = "0"; } String jp2y = req.getParameter("jp2y"); if (jp2y == null) { jp2y = "0"; } String jp2Res = req.getParameter("jp2Res"); String bbx1 = req.getParameter("bbx1"); if (bbx1 == null) { bbx1 = "0"; } String bby1 = req.getParameter("bby1"); if (bby1 == null) { bby1 = "0"; } String bbx2 = req.getParameter("bbx2"); if (bbx2 == null) { bbx2 = "0"; } String bby2 = req.getParameter("bby2"); if (bby2 == null) { bby2 = "0"; } String printThumbnails = req.getParameter("printThumbnails"); if (printThumbnails == null) { printThumbnails = "no"; } wrapper.setAttribute("printThumbnails", printThumbnails); //cg debug System.out.println("debug1- imagesize: " + imagesize + " jp2Res: " + jp2Res + " scale: " + scale); String clickX = req.getParameter("thumbnail.x"); if (clickX != null) { wrapper.setAttribute("clickX", clickX); } else { clickX = (String) wrapper.getAttribute("clickX"); } String clickY = req.getParameter("thumbnail.y"); if (clickX != null) { wrapper.setAttribute("clickY", clickY); } else { clickY = (String) wrapper.getAttribute("clickY"); } //cg debug System.out.println("debug1- thumbnail.x: " + clickX); System.out.println("debug1- X: " + req.getParameter("x")); System.out.println("debug1- thumbnail.y: " + clickY); System.out.println("debug1- Y: " + req.getParameter("y")); /********************************************************** * Create new, or use existing Session **********************************************************/ HttpSession session = req.getSession(true); PdsUserState pdsUser = (PdsUserState) session.getAttribute("PdsUser"); CacheItem item = memcache.getObject(pdsUser.getMeta()); InternalMets mets = item.getMets(); //compare request header if-modified-since with METS DRS last modified //TODO This is temporarily disabled to allow crawlers access to updated // content that they may have already indexed /* Date metsLastModified = item.getLastModifiedDate(); try { long header = req.getDateHeader("If-Modified-Since"); if (header > 0) { Date headerDate = new Date(header); if (metsLastModified.before(headerDate)) { res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } } catch (Exception e) { e.printStackTrace(); // we just ignore this } */ //Set the last modified response value //TODO Warning - this causes browsers to have problems refreshing the // navigation tree html. Possibly this can be set for the content and // citation frames? //res.setDateHeader("Last-Modified", metsLastModified.getTime()); /****************************************************************************** * Get the flags for if doing a page number (p) or sequence number(s) page find * If p is null, look up sequence, if it is not null, look up with page number. * if getContentPage returns null, the page does not exist or an invalid number was * entered. ******************************************************************************/ PageDiv pdiv = null; try { String pageMode = req.getParameter("P"); if (pageMode == null || !pageMode.equals("p")) { pageMode = "s"; } //if a page number search trim n if (pageMode.equals("p")) { n = n.replace(']', ' '); n = n.replace('[', ' '); n = n.trim(); } pdiv = mets.getContentPage(n, pageMode); //if pdiv is a jpeg2000 and res is null then calculate default res value //SET DEFAULT SIZE IF RES NOT SET if (jp2Res == null && pdiv.getDefaultImageMimeType().equals("image/jp2")) { //judaica fix int maxJP2sz = getMaxJP2DisplaySize(pdiv.getDefaultImageID()); if ((maxJP2sz > 300) && (maxJP2sz < 600)) { maxJP2sz = 300; scale = "8"; } else if ((maxJP2sz > 600) && (maxJP2sz < 1200)) { maxJP2sz = 600; scale = "6"; } else if ((maxJP2sz > 1200) && (maxJP2sz < 2400)) { maxJP2sz = 1200; scale = "4"; } else if (maxJP2sz > 2400) { maxJP2sz = 2400; scale = "2"; } String origImagesize = imagesize; if (Integer.parseInt(imagesize) > maxJP2sz) { imagesize = Integer.toString(maxJP2sz); } String filepath = getFilePath(pdiv.getDefaultImageID()); Jpeg2000 jp2 = new Jpeg2000(new File(filepath)); int newRes = jp2.findResolutionLevelContainedBy(Integer.parseInt(origImagesize), Integer.parseInt(origImagesize)); //convert Res to a scaling decimal if (newRes == 1) jp2Res = "1"; else if (newRes == 2) jp2Res = ".5"; else if (newRes == 3) jp2Res = ".25"; else if (newRes == 4) jp2Res = ".125"; else if (newRes == 5) jp2Res = ".0625"; else if (newRes > 5) { jp2Res = "0.625"; } //recalculate newRes if judaica maxres has changed //the actual imagesize if (!imagesize.equals(origImagesize)) { int oldImgsize = Integer.parseInt(origImagesize); int newImgsize = Integer.parseInt(imagesize); float factor = (oldImgsize / newImgsize) / 2; System.out.println("new factor: " + Double.toString(factor)); jp2Res = Double.toString(Double.parseDouble(jp2Res) / factor); } //cg debug //System.out.println("debug2- newRes: " + newRes + " jp2Res is now: " + jp2Res + " scale: " + scale ); } if (pdiv != null && pageMode.equals("p")) { n = String.valueOf(pdiv.getOrder()); //to keep n in the address bar current, redirect to new URL with equivalent n value of page number res.sendRedirect(pdsUrl + "/view/" + id + "?n=" + n + "&s=" + scale + (imagesize != null ? "&imagesize=" + imagesize : "") + (jp2Res != null ? "&jp2Res=" + jp2Res : "") + (jp2Rotate != null ? "&rotation=" + jp2Rotate : "")); return; } } catch (Exception e) { WebAppLogMessage message = new WebAppLogMessage(); message.setContext("find page"); message.setMessage("invalid page number"); message.processSessionRequest(req); logger.error(message, e); } if (pdiv == null) { printError(req, res, "Page not found", null); return; } /********************************************************** * Process appropriately based on the op variable. **********************************************************/ try { /************************* * If image is a JP2 and this is not a frame request, figure * out x,y to create bounding box on thumbnail ***********************/ if (pdiv.getDefaultImageMimeType().equals("image/jp2") && (op != OP_CITATION && op != OP_CONTENT && op != OP_NAVIGATION)) { //judaica fix int maxJP2size = getMaxJP2DisplaySize(pdiv.getDefaultImageID()); if ((maxJP2size > 300) && (maxJP2size < 600)) { maxJP2size = 300; scale = "8"; } else if ((maxJP2size > 600) && (maxJP2size < 1200)) { maxJP2size = 600; scale = "6"; } else if ((maxJP2size > 1200) && (maxJP2size < 2400)) { maxJP2size = 1200; scale = "4"; } else if (maxJP2size > 2400) { maxJP2size = 2400; scale = "2"; } if (Integer.parseInt(imagesize) > maxJP2size) { imagesize = Integer.toString(maxJP2size); } String jp2Action = req.getParameter("action"); if (jp2Action == null) { jp2Action = "noaction"; } int vHeight = Integer.parseInt(imagesize); int vWidth = Integer.parseInt(imagesize); double imgres = Double.parseDouble(jp2Res); //int tWidth = Integer.parseInt(req.getParameter("thumbwidth")); //int tHeight = Integer.parseInt(req.getParameter("thumbheight")); String filepath = getFilePath(pdiv.getDefaultImageID()); Coordinate dimension = new Coordinate(); int x = Integer.parseInt(jp2x); int y = Integer.parseInt(jp2y); Jpeg2000 jp2 = new Jpeg2000(new File(filepath)); //String clickX = req.getParameter("thumbnail.x"); //String clickY = req.getParameter("thumbnail.y"); int thumbX = -1; int thumbY = -1; if (clickX != null && clickY != null) { thumbX = Integer.parseInt(clickX); thumbY = Integer.parseInt(clickY); } if (jp2Action.equals("noaction")) { thumbX = 0; thumbY = 0; } else if (jp2Action.equals("jp2pan")) { x = thumbX; y = thumbY; //panThumbnail is passed thumbnail scale coordinates. It returns //thumbnail scale coordinates so the new X and Y do not need to be //extracted from the method return object dimension = UIUtil.panThumbnail(vHeight, vWidth, x, y, imgres, jp2, jp2Rotate); } else if (jp2Action.equals("jp2zoomin")) { dimension = UIUtil.zoom(vHeight, vWidth, x, y, imgres, jp2, true, jp2Rotate); Coordinate c = UIUtil.convertFullSizeCoordate(jp2, dimension.getX(), dimension.getY(), vWidth, vHeight, imgres, jp2Rotate); thumbX = c.getX(); thumbY = c.getY(); } else if (jp2Action.equals("jp2zoomout")) { dimension = UIUtil.zoom(vHeight, vWidth, x, y, imgres, jp2, false, jp2Rotate); Coordinate c = UIUtil.convertFullSizeCoordate(jp2, dimension.getX(), dimension.getY(), vWidth, vHeight, imgres, jp2Rotate); thumbX = c.getX(); thumbY = c.getY(); } else if (jp2Action.equals("jp2resize")) { String pres = req.getParameter("pres"); double pvRes = Double.valueOf(pres); String previousWidth = req.getParameter("pvWidth"); String previousHeight = req.getParameter("pvHeight"); int pvWidth = Integer.parseInt(previousWidth); int pvHeight = Integer.parseInt(previousHeight); dimension = UIUtil.centerOnResize(vHeight, vWidth, pvHeight, pvWidth, pvRes, x, y, imgres, jp2, jp2Rotate); Coordinate c = UIUtil.convertFullSizeCoordate(jp2, dimension.getX(), dimension.getY(), vWidth, vHeight, imgres, jp2Rotate); thumbX = c.getX(); thumbY = c.getY(); } else if (jp2Action.equals("jp2rotate")) { dimension = UIUtil.panThumbnail(vHeight, vWidth, 0, 0, imgres, jp2, jp2Rotate); thumbX = 0; thumbY = 0; } jp2x = String.valueOf(dimension.getX()); jp2y = String.valueOf(dimension.getY()); req.setAttribute("jp2x", jp2x); req.setAttribute("jp2y", jp2y); //set up coordinates to draw bounding box on thumbnail CoordinatePair bbCoors = UIUtil.getBoundingBoxDimensions(jp2, imgres, vWidth, vHeight, thumbX, thumbY, jp2Rotate); bbx1 = Integer.toString(bbCoors.getPoint1().getX()); bby1 = Integer.toString(bbCoors.getPoint1().getY()); bbx2 = Integer.toString(bbCoors.getPoint2().getX()); bby2 = Integer.toString(bbCoors.getPoint2().getY()); } wrapper.setAttribute("cite", mets.getCitationDiv()); wrapper.setAttribute("pdiv", pdiv); /*if(action.equalsIgnoreCase(ACTION_VIEW) || action.equalsIgnoreCase(ACTION_VIEW_TEXT)) { int imageId = pdiv.getDefaultImageID(); wrapper.setAttribute("lastPage",String.valueOf(mets.getCitationDiv().getLastPageNumber())); wrapper.setAttribute("imageId",String.valueOf(imageId)); wrapper.setAttribute("id",id); wrapper.setAttribute("n",n); wrapper.setAttribute("s",scale); wrapper.setAttribute("mime",pdiv.getDefaultImageMimeType()); wrapper.setAttribute("filepath",getFilePath(imageId)); wrapper.setAttribute("idsUrl",idsUrl); wrapper.setAttribute("cache",cache); wrapper.setAttribute("cacheUrl",pdsUrl+cacheUrl); wrapper.setAttribute("jp2Rotate",jp2Rotate); wrapper.setAttribute("jp2Res",jp2Res); wrapper.setAttribute("jp2x",jp2x); wrapper.setAttribute("jp2y",jp2y); wrapper.setAttribute("imagesize",imagesize); wrapper.setAttribute("bbx1",bbx1); wrapper.setAttribute("bby1",bby1); wrapper.setAttribute("bbx2",bbx2); wrapper.setAttribute("bby2",bby2); wrapper.setAttribute("pdsUrl",pdsUrl); wrapper.setAttribute("ids",idsUrl); wrapper.setAttribute("action",action); if (op == OP_CITATION) { if( pdiv.getDefaultImageMimeType().equals("image/jp2") ) { //get max res for biling code wrapper.setAttribute("maxjp2res", Integer.toString(getMaxJP2DisplaySize(pdiv.getDefaultImageID())) ); } RequestDispatcher rd = req.getRequestDispatcher("/citation.jsp?"); rd.forward(req,res); } else if (op == OP_CONTENT) { //get paths of the ocr files ArrayList<String> ocrPaths = new ArrayList<String>(); for(int i=0;i<pdiv.getOcrID().size();i++) { Integer ocr = (Integer) pdiv.getOcrID().get(i); ocrPaths.add(getFilePath(ocr.intValue())); } wrapper.setAttribute("ocrList",ocrPaths); //if image is a tiff, convert to gif if(pdiv.getDefaultImageMimeType().equals("image/tiff")) { String delv = cache + "/" + imageId + "-" + scale + ".gif"; File file = new File (delv); if (!file.exists ()) { Runtime rt = Runtime.getRuntime(); String tiffpath = getFilePath(imageId); String exec = giffy + " id=" + imageId + " path=" + tiffpath.substring(0,tiffpath.lastIndexOf("/")) + " scale=" + scale + " cache=" + cache; Process child = rt.exec (exec); child.waitFor(); child.destroy(); } } wrapper.setAttribute("caption",item.getImageCaption()); RequestDispatcher rd = req.getRequestDispatcher("/content.jsp?"); rd.forward(req,res); } else if (op == OP_NAVIGATION) { String treeIndex = req.getParameter("index"); String treeAction = req.getParameter("treeaction"); if (treeAction != null) { if (treeAction.equalsIgnoreCase("expand")) { pdsUser.setExpandedNodes(id,item.getAllNodesIndices()); } else if (treeAction.equalsIgnoreCase("collapse")) { pdsUser.setExpandedNodes(id,new ArrayList<String>()); } } if(treeIndex != null) { pdsUser.toggleNode(id,treeIndex); } wrapper.setAttribute("pdsUser",pdsUser); wrapper.setAttribute("maxThumbnails", maxThumbnails); //wrapper.setAttribute("toggleIndex",toggleIndex); //wrapper.setAttribute("treeaction",treeAction); RequestDispatcher rd = req.getRequestDispatcher("/navigation.jsp?"); rd.forward(req,res); } else { //Log the frameset request WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("frameset"); message.setMessage("Frameset Request: " + id); logger.info(message); RequestDispatcher rd = req.getRequestDispatcher("/frameset.jsp?"); rd.forward(req,res); } } else if (action.equalsIgnoreCase(ACTION_CITE_INFO)) { WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("fullcitation"); message.setMessage("Full Citation: " + id + " Seq: " + n); logger.info(message); wrapper.setAttribute("cite",mets.getCitationDiv()); wrapper.setAttribute("pdsUrl",pdsUrl); wrapper.setAttribute("id",id); wrapper.setAttribute("nStr", n+""); String repos = pdsUser.getMeta().getOwner(); if (repos == null || repos.equals("")) repos = "Harvard University Library"; String mainUrn = pdsUser.getMeta().getUrn(); String pageUrn = pdsUser.getMeta().getUrnFromList("?n=" +n); SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy"); String accDate = sdf.format(new Date()); wrapper.setAttribute("accDate", accDate); wrapper.setAttribute("repos", repos); wrapper.setAttribute("mainUrn", nrsUrl + "/" +mainUrn); wrapper.setAttribute("pageUrn", nrsUrl + "/" + pageUrn); StringBuffer sb = new StringBuffer(""); getAllSectionLabels(mets.getCitationDiv(), Integer.parseInt(n), sb); sb.delete(0,2); wrapper.setAttribute("sectLabels", sb.toString()); RequestDispatcher rd = req.getRequestDispatcher("/fullcitation.jsp?"); rd.forward(req,res); } else if (action.equalsIgnoreCase(ACTION_SEARCH)) { //Log the search page request WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("search"); message.setMessage("Search Request: " + id); logger.info(message); wrapper.setAttribute("cite",mets.getCitationDiv()); wrapper.setAttribute("ftsUrl",ftsUrl); wrapper.setAttribute("pdsUrl",pdsUrl); wrapper.setAttribute("id",id); RequestDispatcher rd = req.getRequestDispatcher("/search.jsp?"); rd.forward(req,res); } else if (action.equalsIgnoreCase(ACTION_PRINTOPS)) { WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("printops"); message.setMessage("print options: " + id); logger.info(message); wrapper.setAttribute("pdsUrl",pdsUrl); wrapper.setAttribute("id",id); wrapper.setAttribute("n",n); RequestDispatcher rd = req.getRequestDispatcher("/printoptions.jsp?"); rd.forward(req,res); } else if (action.equalsIgnoreCase(ACTION_PRINT)) { } else if (action.equalsIgnoreCase(ACTION_LINKS)) { WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("links"); message.setMessage("display links: " + id); logger.info(message); wrapper.setAttribute("cite",mets.getCitationDiv()); wrapper.setAttribute("id",id); wrapper.setAttribute("pdsUrl",pdsUrl); RequestDispatcher rd = req.getRequestDispatcher("/links.jsp?"); rd.forward(req,res); }*/ //START API CALLS if (action.equalsIgnoreCase(API_VIEW) || action.equalsIgnoreCase(API_VIEW_TEXT)) { //main api function. shows ocr'd pages int imageId = pdiv.getDefaultImageID(); wrapper.setAttribute("lastPage", String.valueOf(mets.getCitationDiv().getLastPageNumber())); wrapper.setAttribute("imageId", String.valueOf(imageId)); wrapper.setAttribute("id", id); wrapper.setAttribute("n", n); wrapper.setAttribute("s", scale); wrapper.setAttribute("mime", pdiv.getDefaultImageMimeType()); wrapper.setAttribute("filepath", getFilePath(imageId)); wrapper.setAttribute("idsUrl", idsUrl); wrapper.setAttribute("cache", cache); wrapper.setAttribute("cacheUrl", pdsUrl + cacheUrl); wrapper.setAttribute("jp2Rotate", jp2Rotate); wrapper.setAttribute("jp2Res", jp2Res); wrapper.setAttribute("jp2x", jp2x); wrapper.setAttribute("jp2y", jp2y); wrapper.setAttribute("imagesize", imagesize); wrapper.setAttribute("bbx1", bbx1); wrapper.setAttribute("bby1", bby1); wrapper.setAttribute("bbx2", bbx2); wrapper.setAttribute("bby2", bby2); wrapper.setAttribute("pdsUrl", pdsUrl); wrapper.setAttribute("ids", idsUrl); wrapper.setAttribute("action", action); //get paths of the ocr files ArrayList<String> ocrPaths = new ArrayList<String>(); for (int i = 0; i < pdiv.getOcrID().size(); i++) { Integer ocr = (Integer) pdiv.getOcrID().get(i); ocrPaths.add(getFilePath(ocr.intValue())); } wrapper.setAttribute("ocrList", ocrPaths); //if image is a tiff, convert to gif if (pdiv.getDefaultImageMimeType().equals("image/tiff")) { String delv = cache + "/" + imageId + "-" + scale + ".gif"; File file = new File(delv); if (!file.exists()) { Runtime rt = Runtime.getRuntime(); String tiffpath = getFilePath(imageId); String exec = giffy + " id=" + imageId + " path=" + tiffpath.substring(0, tiffpath.lastIndexOf("/")) + " scale=" + scale + " cache=" + cache; Process child = rt.exec(exec); child.waitFor(); child.destroy(); } } wrapper.setAttribute("caption", item.getImageCaption()); RequestDispatcher rd = req.getRequestDispatcher("/api-content.jsp?"); rd.forward(req, res); } else if (action.equalsIgnoreCase(API_LINKS)) { WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("links"); message.setMessage("display links: " + id); logger.info(message); wrapper.setAttribute("cite", mets.getCitationDiv()); wrapper.setAttribute("id", id); wrapper.setAttribute("pdsUrl", pdsUrl); wrapper.setAttribute("n", n); RequestDispatcher rd = req.getRequestDispatcher("/api-links.jsp?"); rd.forward(req, res); } else if (action.equalsIgnoreCase(API_CITE_INFO)) { WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("fullcitation"); message.setMessage("Full Citation: " + id + " Seq: " + n); logger.info(message); wrapper.setAttribute("cite", mets.getCitationDiv()); wrapper.setAttribute("pdsUrl", pdsUrl); wrapper.setAttribute("id", id); wrapper.setAttribute("nStr", n + ""); String repos = pdsUser.getMeta().getOwner(); if (repos == null || repos.equals("")) repos = "Harvard University Library"; String mainUrn = pdsUser.getMeta().getUrn(); String pageUrn = pdsUser.getMeta().getUrnFromList("?n=" + n); SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy"); String accDate = sdf.format(new Date()); wrapper.setAttribute("accDate", accDate); wrapper.setAttribute("repos", repos); wrapper.setAttribute("mainUrn", nrsUrl + "/" + mainUrn); wrapper.setAttribute("pageUrn", nrsUrl + "/" + pageUrn); StringBuffer sb = new StringBuffer(""); getAllSectionLabels(mets.getCitationDiv(), Integer.parseInt(n), sb); sb.delete(0, 2); wrapper.setAttribute("sectLabels", sb.toString()); RequestDispatcher rd = req.getRequestDispatcher("/api-fullcitation.jsp?"); rd.forward(req, res); } else if (action.equalsIgnoreCase(API_DOC_TREE)) { String treeIndex = req.getParameter("index"); String treeAction = req.getParameter("treeaction"); /*if (treeAction != null) { if (treeAction.equalsIgnoreCase("expand")) { pdsUser.setExpandedNodes(id,item.getAllNodesIndices()); } else if (treeAction.equalsIgnoreCase("collapse")) { pdsUser.setExpandedNodes(id,new ArrayList<String>()); } } if(treeIndex != null) { pdsUser.toggleNode(id,treeIndex); }*/ //expand the tree pdsUser.setExpandedNodes(id, item.getAllNodesIndices()); wrapper.setAttribute("pdsUser", pdsUser); wrapper.setAttribute("pdsUrl", pdsUrl); wrapper.setAttribute("cacheUrl", pdsUrl + cacheUrl); wrapper.setAttribute("cache", cache); wrapper.setAttribute("id", id); wrapper.setAttribute("n", n); wrapper.setAttribute("s", scale); wrapper.setAttribute("action", "get"); wrapper.setAttribute("idsUrl", idsUrl); wrapper.setAttribute("maxThumbnails", maxThumbnails); wrapper.setAttribute("jp2Rotate", jp2Rotate); wrapper.setAttribute("jp2x", jp2x); wrapper.setAttribute("jp2y", jp2y); wrapper.setAttribute("caption", item.getImageCaption()); //wrapper.setAttribute("toggleIndex",toggleIndex); //wrapper.setAttribute("treeaction",treeAction); RequestDispatcher rd = req.getRequestDispatcher("/api-navigation.jsp?"); rd.forward(req, res); } //todo? else if (action.equalsIgnoreCase(API_MAX_SECTIONS)) { } else if (action.equalsIgnoreCase(API_MAX_PAGES)) { } else if (action.equalsIgnoreCase(API_MAX_CHAPTERS)) { } } //END MAIN catch (Exception e) { WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("main"); Throwable root = e; if (e instanceof ServletException) { ServletException se = (ServletException) e; Throwable t = se.getRootCause(); if (t != null) { logger.error(message, t); root = t; } else { logger.error(message, se); } } else { logger.error(message, e); } printError(req, res, "PDS-WS Error", root); } }
From source file:org.pepstock.jem.node.tasks.JobTask.java
/** * Internal method which creates the process, preparing environment * variables, creating directories, setting listener of output and error * log, and wait for end of job execution. * //from w ww .j a va 2s . c o m * @return return code of execution * @throws NodeMessageException * @throws InterruptedException * @throws Exception occurs if there is any error */ private int launchProcess() throws IOException, NodeMessageException, InterruptedException { int returnCode = 0; Process process = null; try { String user = job.isUserSurrogated() ? job.getJcl().getUser() : job.getUser(); AbstractFactory currFactory = (AbstractFactory) getFactory(); boolean useSudo = currFactory.isUseSudo() && !user.equalsIgnoreCase(Main.getNode().getUser()); // create a process builder ProcessBuilder builder = new ProcessBuilder(); Shell shell = CurrentPlatform.getInstance().getShell(); String command = CurrentPlatform.getInstance().getCommand(job, getCommand(), useSudo); builder.command(shell.getName(), shell.getParameters(), command); // set directory where execute process if (getStartDir() != null) { builder.directory(new File(getStartDir())); } // load variable environment from a temporary maps that you can use // inside of configure method. Map<String, String> env = getEnv(); Map<String, String> map = builder.environment(); for (Map.Entry<String, String> e : env.entrySet()) { map.put(e.getKey(), e.getValue()); } // writes JEM log with headers JobLogManager.printHeader(job); // start process and save instance process = builder.start(); // wait for end of job execution returnCode = process.waitFor(); // check if cancelled, setting the return code 222 if (isCancelled) { returnCode = Result.CANCELED; } } finally { if (process != null) { process.destroy(); } } return returnCode; }
From source file:name.livitski.tools.persista.StorageBootstrap.java
/** * Checks whether the database server is available and * attempts to start it on the local machine if not. * @throws ServerStartException if there is an error * during server startup//w ww . j a v a 2 s . c o m * @throws ConfigurationException if there is a problem * with configuration */ public void startServer() throws ServerStartException, ConfigurationException { boolean wasOpen = (null != db); try { String user, pass; if (null == creatorPass) { user = readSetting(UserNameSetting.class); pass = readSetting(PasswordSetting.class); } else { user = creatorUser; pass = creatorPass; } if (!wasOpen) db = openDB(null, user, pass); if (null != db) { log().info("Database server is running, skipping server launch request ..."); return; } } catch (ConfigurationException fault) { Throwable cause = fault.getCause(); if (cause instanceof SQLException && "08S01".equals(((SQLException) cause).getSQLState())) { log().trace("Intercepted connection failure, proceeding with server start ...", cause); } else throw fault; } finally { if (!wasOpen && null != db) { closeDB(db); db = null; } } String command = readSetting(ServerStatupCommandSetting.class); log().debug("Starting local database server ..."); Process process = null; try { process = Runtime.getRuntime().exec(command); InputStream stderr = process.getErrorStream(); byte[] messages = new byte[2048]; int messagesLength; for (messagesLength = 0; messagesLength < messages.length;) { int read = stderr.read(messages, messagesLength, messages.length - messagesLength); if (0 > read) break; messagesLength += read; } int exitCode = process.waitFor(); process = null; if (0 != exitCode) throw new ServerStartException(this, "Server launch command '" + command + "' returned code " + exitCode + (0 < messagesLength ? " with message(s): " + new String(messages, 0, messagesLength) : "")); } catch (InterruptedException e) { throw new ServerStartException(this, "Server launch command '" + command + "' did not complete", e); } catch (IOException e) { throw new ServerStartException(this, "Server launch command '" + command + "' caused an I/O error", e); } finally { if (null != process) process.destroy(); } }