Example usage for java.lang Process getErrorStream

List of usage examples for java.lang Process getErrorStream

Introduction

In this page you can find the example usage for java.lang Process getErrorStream.

Prototype

public abstract InputStream getErrorStream();

Source Link

Document

Returns the input stream connected to the error output of the process.

Usage

From source file:com.f9g4.webapp.servicesFacade.impl.UploadFacadeApacheCommonsUploadImpl.java

public boolean upload(UploadProperties uploadDetails, int uploadMode, UploadResult result) {
    int exitVal;/*  w w  w  .j  a  va  2  s.  c om*/
    boolean isFailedProcessing = false;
    //check the folder, if not exist create it.=================
    uploadMode = 3;
    System.out.println("mode ");
    logger.trace("Beginning");

    File folder = new File(profileLocation);
    File folder_100x100 = new File(profileLocation_100);
    File folder_400x400 = new File(profileLocation_400);
    File folder_bigimage = new File(profileLocation_bigimage);
    File folder_source = new File(profileLocation_source);
    //Add folder for files
    File folder_files = new File(profileLocation_files);
    if (!folder.exists())
        folder.mkdir();
    if (!folder_100x100.exists())
        folder_100x100.mkdir();
    if (!folder_400x400.exists())
        folder_400x400.mkdir();
    if (!folder_bigimage.exists())
        folder_bigimage.mkdir();
    if (!folder_source.exists())
        folder_source.mkdir();
    if (!folder_files.exists())
        folder_files.mkdir();

    //      User u = userDAO.getUser(username);

    FileOutputStream fos = null;
    int extIndex = uploadDetails.getFiledata().getOriginalFilename().lastIndexOf('.');
    //fileName = file.name.substr(0, extIndex);
    String original_ext = uploadDetails.getFiledata().getOriginalFilename().substring(extIndex,
            uploadDetails.getFiledata().getOriginalFilename().length());
    //normalize file extension 06/11/2013
    original_ext = original_ext.toLowerCase(); //change to lower case
    if (extIndex != -1 && uploadMode != 3) //skip the ext check when uploadMode is files 
    {
        //if the extension is pdf, then change to AI
        if (original_ext.equals(".pdf"))
            original_ext = ".ai";
        if (original_ext.equals(".jpeg")) //if the extension equals to jpeg, reset to jpg
            original_ext = ".jpg";
    }
    //create filename
    final String uuid = UUID.randomUUID().toString();
    String filename = profileLocation + uuid + original_ext;
    /* 
    this.fileName=uuid + original_ext;
    this.fileName_size_100=UUID.randomUUID().toString()+".jpg";
    this.fileName_size_400=UUID.randomUUID().toString()+".jpg";
    this.fileName_size_original=UUID.randomUUID().toString()+".jpg";
    this.originalFileName = uploadDetails.getFiledata().getOriginalFilename();
    */

    //Set value to UploadResult object
    result.setOriginal_ext(original_ext.replace(".", ""));
    result.setFileName(uuid + original_ext);
    result.setFileName_size_100(UUID.randomUUID().toString() + ".jpg");
    result.setFileName_size_400(UUID.randomUUID().toString() + ".jpg");
    result.setFileName_size_original(UUID.randomUUID().toString() + ".jpg");
    result.setOriginalFileName(uploadDetails.getFiledata().getOriginalFilename());

    try {

        File f = new File(filename);
        if (!f.exists()) {
            f.createNewFile();
        }
        //      
        //         if (!f.exists()){
        //            boolean result = f.mkdir();
        //            
        //            if (!result){
        //               System.out.println("Could not create dir");
        //            }
        //            
        //         }

        //         fos = new FileOutputStream("C:\\Users\\kamlesh\\Downloads\\" + uploadDetails.getFiledata().getOriginalFilename().toUpperCase());
        fos = new FileOutputStream(f);

        fos.write(uploadDetails.getFiledata().getBytes());
        fos.flush();
        fos.close();

        //Convert AI files to Jpeg - use Utility along ghost script
        //decide the parameter by uploadMode
        //Mode==1, no watermark; Mode==2, with watermark; Mode==3, files mode. skip the plmsplitter process.

        String runtimecoomand = "";
        if (uploadMode == 1) {
            runtimecoomand = plmsplitter + " " + filename + " " + plmsplitterparameters + " Renderer="
                    + ghostscript;
        } else if (uploadMode == 2) {
            runtimecoomand = plmsplitter + " " + filename + " " + plmsplitterparametersWithWatermark
                    + " Renderer=" + ghostscript;
        } else if (uploadMode == 3) {
            // Do not need to run plmsplitter.
            // Move the file to files folder.
            //get file
            File temp = new File(filename);
            //create new file
            File dest = new File(profileLocation_files + result.getFileName());
            temp.renameTo(dest);
            return true;
        } else {
            runtimecoomand = plmsplitter + " " + filename + " " + plmsplitterparametersWithWatermark
                    + " Renderer=" + ghostscript;
        }

        //Process process= Runtime.getRuntime().exec(runtimecoomand);
        logger.trace("COMPLETE");

        //wait the process finish and continue the program.====================
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(runtimecoomand);

            // any error message?
            StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERR");

            // any output?
            StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUT");

            // kick them off
            errorGobbler.start();
            outputGobbler.start();

            // any error???
            exitVal = proc.waitFor();
            //this.uploadStatus=exitVal;
            if (exitVal != 0)
                isFailedProcessing = true;
            else
                isFailedProcessing = false;
        } catch (Throwable t) {
            t.printStackTrace();
            result.setFailedProcessing(true);
            return false;
        }
        /*try
        {
           process.wait();
        }
        catch (Exception e)
        //catch (InterruptedException e) 
        {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }*/

        logger.trace("READEING FILE LIST");
        File dir = new File(profileLocation);
        FilenameFilter filefilter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                //if the file extension is .jpg return true, else false
                return name.matches(".*" + uuid + ".*jpg");
            }
        };
        String[] fileList = dir.list(filefilter);
        if (fileList.length <= 0) //if no thumbnails images are created after plmsplitter, it's failed processing.
        {
            isFailedProcessing = true;
        }
        //create a FilenameFilter and override its accept-method
        if (isFailedProcessing) {
            //create the dummy images to thumbnails folder to occupies the file name.
            //get dummy image file
            File dummyImageFile = new File(dummyImage);
            File dest100 = new File(profileLocation_100 + result.getFileName_size_100());
            File dest400 = new File(profileLocation_400 + result.getFileName_size_400());
            File destOriginalSize = new File(profileLocation_bigimage + result.getFileName_size_original());
            FileUtils.copyFile(dummyImageFile, dest100); //100*100
            FileUtils.copyFile(dummyImageFile, dest400); //400*400
            FileUtils.copyFile(dummyImageFile, destOriginalSize); //original image size
            //move the file to error files folder
            File temp = new File(filename);
            //create new file
            File dest = new File(profileLocation_error_files + result.getFileName());
            temp.renameTo(dest);
        } else {
            //move source files==================================
            //get file
            File temp = new File(filename);
            //create new file
            File dest = new File(profileLocation_source + result.getFileName());
            temp.renameTo(dest);
            //move generated jpg files.
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].matches(".*400x400.*")) {
                    logger.trace("MOVE " + fileList[i] + " to 400x400 folder");
                    //move to 400x400 folder
                    //get file
                    temp = new File(profileLocation + fileList[i]);
                    //create new file
                    dest = new File(profileLocation_400 + result.getFileName_size_400());
                    temp.renameTo(dest);
                } else if (fileList[i].matches(".*100x100.*")) {
                    logger.trace("MOVE " + fileList[i] + " to 100x100 folder");
                    //move to 100x100 folder
                    //get file
                    temp = new File(profileLocation + fileList[i]);
                    //create new file
                    dest = new File(profileLocation_100 + result.getFileName_size_100());
                    temp.renameTo(dest);
                } else {
                    logger.trace("MOVE " + fileList[i] + " to bigimage folder");
                    //move to original folder
                    //get file
                    temp = new File(profileLocation + fileList[i]);
                    //create new file
                    dest = new File(profileLocation_bigimage + result.getFileName_size_original());
                    temp.renameTo(dest);
                }
            }
        }
        /*Update uploadResult object*/
        result.setUploadStatus(exitVal);
        result.setFailedProcessing(isFailedProcessing);
        return true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;

    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Add Runtime to parse the AI files and convert it to jpg    
}

From source file:de.unibi.techfak.bibiserv.BiBiToolsTest.java

@Test
public void testGetFileSize() throws Exception {
    LOG.info("+++++++++++++++++++\ntest creation of spooldir and temp spooldir\n+++++++++++++++++++\n");
    // initalize BiBiTools object
    InputStream is = new FileInputStream(GUUGLE);
    BiBiTools bibitools = new BiBiTools(is);
    // run du from system

    long expected_size = 0;

    Process p = Runtime.getRuntime().exec("du -s --bytes .");
    if (p.waitFor() == 0) {
        String tmp = BiBiTools.i2s(new InputStreamReader(p.getInputStream()));
        expected_size = Long.parseLong(tmp.split("\\s")[0]);
    } else {//from w w w.  j  a va2s.  c  o  m
        fail(BiBiTools.i2s(new InputStreamReader(p.getErrorStream())));
    }

    long size = bibitools.getFileSize(new File("."));

    assertEquals(expected_size, size);

}

From source file:PVGraph.java

private static void runSmatool() throws IOException {
    String cmd = props.getProperty("smatool.cmd", "smatool");
    System.out.println("Executing " + cmd + " at " + new java.util.Date());
    Process p = Runtime.getRuntime().exec(cmd);
    if (Integer.decode(props.getProperty("smatool.printstdout", "0")) != 0) {
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;//from w w w .j  a v  a  2s . c om
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
    if (Integer.decode(props.getProperty("smatool.printstderr", "1")) != 0) {
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        String line;
        while ((line = br.readLine()) != null) {
            System.err.println(line);
        }
    }
    try {
        p.waitFor();
    } catch (InterruptedException ie) {
        // relax
    }
}

From source file:com.telefonica.euro_iaas.sdc.pupperwrapper.services.tests.ActionsServiceTest.java

@Test
public void isNodeRegisteredNO() throws IOException {

    Process shell = mock(Process.class);

    String[] cmd = { anyString() };
    when(processBuilderFactory.createProcessBuilder(cmd)).thenReturn(shell);

    String str = "Node 3 is registered";
    when(shell.getInputStream()).thenReturn(new ByteArrayInputStream(str.getBytes("UTF-8")));

    String strEr = " ";
    when(shell.getErrorStream()).thenReturn(new ByteArrayInputStream(strEr.getBytes("UTF-8")));

    Assert.assertFalse(actionsService.isNodeRegistered("1"));

}

From source file:com.telefonica.euro_iaas.sdc.pupperwrapper.services.tests.ActionsServiceTest.java

@Test
public void isNodeRegisteredYES() throws IOException {

    Process shell = mock(Process.class);

    String[] cmd = { anyString() };

    when(processBuilderFactory.createProcessBuilder(cmd)).thenReturn(shell);

    String str = "Node 1 is registered";
    when(shell.getInputStream()).thenReturn(new ByteArrayInputStream(str.getBytes("UTF-8")));

    String strEr = " ";
    when(shell.getErrorStream()).thenReturn(new ByteArrayInputStream(strEr.getBytes("UTF-8")));

    Assert.assertTrue(actionsService.isNodeRegistered("1"));

}

From source file:it.cnr.icar.eric.client.ui.thin.security.SecurityUtil.java

/** Generate a key pair and add it to the keystore.
  */*  w w  w . jav a 2 s .c  o m*/
  * @param alias
  * @return
  *     A HashSet of X500PrivateCredential objects.
  * @throws Exception
  */
private Set<Object> generateCredentials(String alias) throws JAXRException {

    try {
        HashSet<Object> credentials = new HashSet<Object>();

        // The keystore file is at ${jaxr-ebxml.home}/security/keystore.jks. If
        // the 'jaxr-ebxml.home' property is not set, ${user.home}/jaxr-ebxml/ is
        // used.
        File keyStoreFile = KeystoreUtil.getKeystoreFile();
        String storepass = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.storepass",
                "ebxmlrr");
        String keypass = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.keypass");
        if (keypass == null) {
            // keytool utility requires a six character minimum password.
            // pad passwords with < six chars
            if (alias.length() >= 6) {
                keypass = alias;
            } else if (alias.length() == 5) {
                keypass = alias + "1";
            } else if (alias.length() == 4) {
                keypass = alias + "12";
            } else if (alias.length() == 3) {
                keypass = alias + "123";
            }
            // alias should have at least 3 chars
        }
        log.debug("Generating key pair for '" + alias + "' in '" + keyStoreFile.getAbsolutePath() + "'");

        // When run in S1WS 6.0, this caused some native library errors. It appears that S1WS
        // uses different encryption spis than those in the jdk. 
        //            String[] args = {
        //                "-genkey", "-alias", uid, "-keypass", "keypass",
        //                "-keystore", keyStoreFile.getAbsolutePath(), "-storepass",
        //                new String(storepass), "-dname", "uid=" + uid + ",ou=People,dc=sun,dc=com"
        //            };
        //            KeyTool keytool = new KeyTool();
        //            ByteArrayOutputStream keytoolOutput = new ByteArrayOutputStream();
        //            try {
        //                keytool.run(args, new PrintStream(keytoolOutput));
        //            }
        //            finally {
        //                log.info(keytoolOutput.toString());
        //            }
        // To work around this problem, generate the key pair using keytool (which executes
        // in its own vm. Note that all the parameters must be specified, or keytool prompts
        // for their values and this 'hangs'
        String[] cmdarray = { "keytool", "-genkey", "-alias", alias, "-keypass", keypass, "-keystore",
                keyStoreFile.getAbsolutePath(), "-storepass", storepass, "-dname", "cn=" + alias };
        Process keytool = Runtime.getRuntime().exec(cmdarray);
        try {
            keytool.waitFor();
        } catch (InterruptedException ie) {
        }
        if (keytool.exitValue() != 0) {
            log.error(WebUIResourceBundle.getInstance().getString("message.keytoolCommandFailedDetails"));
            Reader reader = new InputStreamReader(keytool.getErrorStream());
            BufferedReader bufferedReader = new BufferedReader(reader);
            while (bufferedReader.ready()) {
                log.error(bufferedReader.readLine());
            }
            throw new JAXRException(
                    WebUIResourceBundle.getInstance().getString("excKeyToolCommandFail") + keytool.exitValue());
        }
        log.debug("Key pair generated successfully.");

        // After generating the keypair in the keystore file, we have to reload
        // SecurityUtil's KeyStore object.
        KeyStore keyStore = it.cnr.icar.eric.client.xml.registry.util.SecurityUtil.getInstance().getKeyStore();
        keyStore.load(new FileInputStream(keyStoreFile), storepass.toCharArray());

        credentials.add(it.cnr.icar.eric.client.xml.registry.util.SecurityUtil.getInstance()
                .aliasToX500PrivateCredential(alias));

        return credentials;
    } catch (Exception e) {
        if (e instanceof JAXRException) {
            throw (JAXRException) e;
        } else {
            throw new JAXRException(e);
        }
    }
}

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;//from   w w w  .ja v a  2  s . co  m
    }
    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.sastix.cms.common.services.htmltopdf.PdfImpl.java

public byte[] getPDF() throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder(getCommandAsArray());
    Process process = processBuilder.start();
    //Runtime runtime = Runtime.getRuntime();
    //Process process = runtime.exec(getCommandAsArray());

    for (Page page : pages) {
        if (page.getType().equals(PageType.htmlAsString)) {
            OutputStream stdInStream = process.getOutputStream();
            stdInStream.write(page.getSource().getBytes("UTF-8"));
            stdInStream.close();/*  ww  w.  j av a  2s  .c  om*/
        }
    }

    StreamEater outputStreamEater = new StreamEater(process.getInputStream());
    outputStreamEater.start();

    StreamEater errorStreamEater = new StreamEater(process.getErrorStream());
    errorStreamEater.start();

    outputStreamEater.join();
    errorStreamEater.join();
    process.waitFor();

    if (process.exitValue() != 0) {
        throw new RuntimeException("Process (" + getCommand() + ") exited with status code "
                + process.exitValue() + ":\n" + new String(errorStreamEater.getBytes()));
    }

    if (outputStreamEater.getError() != null) {
        throw outputStreamEater.getError();
    }

    if (errorStreamEater.getError() != null) {
        throw errorStreamEater.getError();
    }

    return outputStreamEater.getBytes();
}

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/*from w w  w  .jav  a2 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();
    }
}

From source file:edu.ucsb.eucalyptus.storage.fs.FileSystemStorageManager.java

private int losetup(String absoluteFileName, String loDevName) {
    try {//from ww  w .ja  v  a  2s .c  o m
        Runtime rt = Runtime.getRuntime();
        Process proc = rt
                .exec(new String[] { eucaHome + EUCA_ROOT_WRAPPER, "losetup", loDevName, absoluteFileName });
        StreamConsumer error = new StreamConsumer(proc.getErrorStream());
        StreamConsumer output = new StreamConsumer(proc.getInputStream());
        error.start();
        output.start();
        int errorCode = proc.waitFor();
        output.join();
        LOG.info("losetup " + loDevName + " " + absoluteFileName);
        LOG.info(output.getReturnValue());
        LOG.info(error.getReturnValue());
        return errorCode;
    } catch (Throwable t) {
        LOG.error(t);
    }
    return -1;
}