Example usage for java.lang Process getOutputStream

List of usage examples for java.lang Process getOutputStream

Introduction

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

Prototype

public abstract OutputStream getOutputStream();

Source Link

Document

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

Usage

From source file:tachyon.java.manager.JavaFxManager.java

@Override
public void debugProject(ProcessItem pro, DebuggerController controller) {
    compile(pro);//from w ww  .  j  a va2s. c om
    if (!pro.isCancelled()) {
        ProcessBuilder pb;
        if (OS.contains("win")) {
            pb = getWindowsDebuggerString();
        } else {
            pb = getMacDebuggerString();
        }
        pb.directory(getProject().getBuild().toFile());
        try {
            Process start = pb.start();
            pro.setName("Debug Project " + getProject().getRootDirectory().getFileName().toString());
            pro.setProcess(start);
            ProcessPool.getPool().addItem(pro);
            (new Thread(new Project.OutputReader(start.getInputStream(), pro.getConsole()))).start();
            (new Thread(new Project.ErrorReader(start.getErrorStream(), pro.getConsole()))).start();
            controller.setOutputStream(start.getOutputStream());
            int waitFor = start.waitFor();
            controller.finished();
        } catch (IOException | InterruptedException ex) {
        }
    }
}

From source file:org.opencms.workplace.tools.git.CmsGitCheckin.java

/**
 * Runs the shell script for committing and optionally pushing the changes in the module.
 * @return exit code of the script./*from   w  w  w  .j ava  2  s  .c o  m*/
 */
private int runCommitScript() {

    if (m_checkout && !m_fetchAndResetBeforeImport) {
        m_logStream.println("Skipping script....");
        return 0;
    }
    try {
        m_logStream.flush();
        String commandParam;
        if (m_resetRemoteHead) {
            commandParam = resetRemoteHeadScriptCommand();
        } else if (m_resetHead) {
            commandParam = resetHeadScriptCommand();
        } else if (m_checkout) {
            commandParam = checkoutScriptCommand();
        } else {
            commandParam = checkinScriptCommand();
        }
        String[] cmd = { "bash", "-c", commandParam };
        m_logStream.println("Calling the script as follows:");
        m_logStream.println();
        m_logStream.println(cmd[0] + " " + cmd[1] + " " + cmd[2]);
        ProcessBuilder builder = new ProcessBuilder(cmd);
        m_logStream.close();
        m_logStream = null;
        Redirect redirect = Redirect.appendTo(new File(DEFAULT_LOGFILE_PATH));
        builder.redirectOutput(redirect);
        builder.redirectError(redirect);
        Process scriptProcess = builder.start();
        int exitCode = scriptProcess.waitFor();
        scriptProcess.getOutputStream().close();
        m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, true));
        return exitCode;
    } catch (InterruptedException | IOException e) {
        e.printStackTrace(m_logStream);
        return -1;
    }

}

From source file:fitnesse.testsystems.CommandRunner.java

protected void redirectOutputs(Process process, final ExecutionLogListener executionLogListener)
        throws IOException {
    InputStream stdout = process.getInputStream();
    InputStream stderr = process.getErrorStream();

    // Fit and SlimService
    new Thread(new OutputReadingRunnable(stdout, new OutputWriter() {
        @Override//w w  w .  jav  a2  s  .c o m
        public void write(String output) {
            executionLogListener.stdOut(output);
        }
    }), "CommandRunner stdOut").start();
    new Thread(new OutputReadingRunnable(stderr, new OutputWriter() {
        @Override
        public void write(String output) {
            executionLogListener.stdErr(output);
            setCommandErrorMessage(output);
        }
    }), "CommandRunner stdErr").start();

    // Close stdin
    process.getOutputStream().close();
}

From source file:com.ah.be.communication.BusinessUtil.java

public static void modifyVhmUser(UserInfo userInfo) throws Exception {
    // modify user
    if (userInfo.getUsername() == null || userInfo.getUsername().trim().length() == 0) {
        throw new Exception("'userName' is necessary.");
    }/*  w  ww .j a  v  a 2s.  c o m*/

    HmDomain domain = BoMgmt.getDomainMgmt().getHomeDomain();
    if (userInfo.getVhmName() != null && userInfo.getVhmName().length() > 0) {
        // maybe modify vhm user name
        domain = CacheMgmt.getInstance().getCacheDomainByName(userInfo.getVhmName());
        if (domain == null) {
            throw new Exception("Domain(name=" + userInfo.getVhmName() + ") is not exists.");
        }
    }

    // check user name
    List<HmUser> list = QueryUtil.executeQuery(HmUser.class, null,
            new FilterParams("lower(userName)", userInfo.getUsername().toLowerCase()), domain.getId());
    if (list.isEmpty()) {
        DebugUtil.commonDebugWarn("User (" + userInfo.getUsername() + ") is not exists. ignore modify user");
        return;
    }

    HmUser user = list.get(0);
    String oldPassword = user.getPassword();

    user.setEmailAddress(userInfo.getEmailAddress());
    user.setOwner(domain);
    user.setPassword(userInfo.getPassword());
    user.setUserFullName(userInfo.getFullname());

    HmUserGroup userGroup = QueryUtil.findBoByAttribute(HmUserGroup.class, "groupAttribute",
            (int) userInfo.getGroupAttribute(), domain.getId());

    // the users belong to portal
    if (domain.isHomeDomain()) {
        if (userGroup == null) {
            throw new Exception("User group(attribute=" + userInfo.getGroupAttribute() + ") is not exists.");
        }
        user.setUserGroup(userGroup);
        // the users belong to hivemanager
    } else {
        // only planner default user need to change user group
        if (user.getUserGroup().isPlUserGroup() && user.getDefaultFlag()) {
            user.setUserGroup(userGroup);
        }
    }
    user.setUserName(userInfo.getUsername());
    //      user.setMaxAPNum(userInfo.getMaxAPNum());
    user.setDefapplication(userInfo.getDefaultApp());
    user.setTimeZone(userInfo.getTimeZone());

    try {
        // changed in Geneva, for user setting columns separated from hm_user
        UserSettingsUtil.updateMaxAPNum(userInfo.getEmailAddress(), userInfo.getMaxAPNum());
        QueryUtil.updateBo(user);
    } catch (Exception e) {
        DebugUtil.commonDebugError("BusinessUtil.modifyUser(): catch exception", e);

        // throw exception
        throw new Exception("Modify user error. " + e.getMessage());
    }

    // if modify password of admin user, sync to shell password
    if (domain.isHomeDomain() && user.getUserName().equals(HmUser.ADMIN_USER)) {
        if (!oldPassword.equals(user.getPassword())) {
            String clearPassword = userInfo.getClearPassword();
            if (clearPassword != null && clearPassword.trim().length() > 0) {
                try {
                    String[] cmd = { "bash", "-c", "passwd admin" };
                    Process proc = Runtime.getRuntime().exec(cmd);

                    PrintWriter out = new PrintWriter(new OutputStreamWriter(proc.getOutputStream()));
                    // new password
                    out.println(clearPassword);
                    out.flush();

                    // confirm password
                    out.println(clearPassword);
                    out.flush();
                } catch (Exception e) {
                    DebugUtil.commonDebugError("BusinessUtil.modifyUser(): catch exception", e);
                }
            } else {
                DebugUtil.commonDebugError(
                        "BusinessUtil.modifyUser(): password not same with old password, but clear password in message is empty.");
            }
        }
    }
}

From source file:com.evolveum.midpoint.test.util.Lsof.java

private String execLsof(int pid) throws IOException, InterruptedException {
    Process process = null;
    String output = null;/*from  ww  w  . ja  v  a  2  s  . co  m*/
    try {
        process = Runtime.getRuntime().exec(new String[] { "lsof", "-p", Integer.toString(pid) });
        InputStream inputStream = process.getInputStream();
        output = IOUtils.toString(inputStream, "UTF-8");
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new IllegalStateException("Lsof process ended with error (" + exitCode + ")");
        }
    } finally {
        if (process != null) {
            try {
                process.getInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                process.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                process.getErrorStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            process.destroy();
        }
    }
    return output;
}

From source file:org.kalypso.commons.process.internal.DefaultProcess.java

@Override
public int startProcess(final OutputStream stdOut, final OutputStream stdErr, final InputStream stdIn,
        final ICancelable cancelable) throws IOException, ProcessTimeoutException {
    /* Now start the process in the workDir */
    Process process = null;
    int iRetVal = -1;
    InputStream outStream = null;
    InputStream errStream = null;
    OutputStream inStream = null;
    ProcessControlJob procCtrlThread = null;

    try {// w  ww.  j  a va  2  s.  com
        try {
            m_command.setExecutable(true, false);
        } catch (final Throwable e) {
            KalypsoCommonsPlugin.getDefault().getLog().log(StatusUtilities.statusFromThrowable(e));
        }

        process = m_processBuilder.start();

        procCtrlThread = new ProcessControlJob(process, cancelable, m_timeout);
        procCtrlThread.setSystem(true);
        procCtrlThread.schedule();

        outStream = new BufferedInputStream(process.getInputStream());
        errStream = new BufferedInputStream(process.getErrorStream());
        inStream = new BufferedOutputStream(process.getOutputStream());

        new StreamStreamer(outStream, stdOut);
        new StreamStreamer(errStream, stdErr);
        new StreamStreamer(stdIn, inStream);

        iRetVal = process.waitFor();

        if (procCtrlThread != null)
            procCtrlThread.cancel();
    } catch (final InterruptedException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(inStream);
        IOUtils.closeQuietly(errStream);
        IOUtils.closeQuietly(outStream);
    }

    if (cancelable.isCanceled())
        throw new OperationCanceledException();

    if (procCtrlThread != null) {
        final IStatus result = procCtrlThread.getResult();
        if (result != null && result.matches(IStatus.ERROR))
            throw new ProcessTimeoutException("Timeout executing " + m_executable); //$NON-NLS-1$
    }

    return iRetVal;
}

From source file:com.ssn.event.controller.SSNShareController.java

@Override
public void mouseClicked(MouseEvent e) {
    Object mouseEventObj = e.getSource();
    if (mouseEventObj != null && mouseEventObj instanceof JLabel) {
        JLabel label = (JLabel) mouseEventObj;
        getShareForm().setCursor(new Cursor(Cursor.WAIT_CURSOR));
        // Tracking this sharing event in Google Analytics
        GoogleAnalyticsUtil.track(SSNConstants.SSN_APP_EVENT_SHARING);
        Thread thread = null;//  ww  w .j  a  v a2  s  .com
        switch (label.getName()) {
        case "FacebookSharing":
            thread = new Thread() {
                boolean isAlreadyLoggedIn = false;

                @Override
                public void run() {

                    Set<String> sharedFileList = getFiles();
                    AccessGrant facebookAccessGrant = getHomeModel().getHomeForm().getFacebookAccessGrant();
                    if (facebookAccessGrant == null) {
                        try {
                            LoginWithFacebook loginWithFacebook = new LoginWithFacebook(null);
                            loginWithFacebook.setHomeForm(getHomeModel().getHomeForm());
                            loginWithFacebook.login();

                            boolean processFurther = false;
                            while (!processFurther) {
                                facebookAccessGrant = getHomeModel().getHomeForm().getFacebookAccessGrant();
                                if (facebookAccessGrant == null) {
                                    Thread.sleep(10000);
                                } else {
                                    processFurther = true;
                                    isAlreadyLoggedIn = true;
                                }
                            }
                        } catch (InterruptedException ex) {
                            logger.error(ex);
                        }
                    }

                    FacebookConnectionFactory connectionFactory = new FacebookConnectionFactory(
                            SSNConstants.SSN_FACEBOOK_API_KEY, SSNConstants.SSN_FACEBOOK_SECRET_KEY);
                    Connection<Facebook> connection = connectionFactory.createConnection(facebookAccessGrant);
                    Facebook facebook = connection.getApi();
                    MediaOperations mediaOperations = facebook.mediaOperations();

                    if (!isAlreadyLoggedIn) {
                        // SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                        SSNConfirmationDialogBox confirmeDialog = new SSNConfirmationDialogBox();
                        FacebookProfile userProfile = facebook.userOperations().getUserProfile();
                        String userName = "";
                        if (userProfile != null) {
                            userName = userProfile.getName() != null ? userProfile.getName()
                                    : userProfile.getFirstName();
                        }
                        confirmeDialog.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(),
                                "Confirmation", "",
                                "You are already logged in with " + userName + ", Click OK to continue.");
                        int result = confirmeDialog.getResult();
                        if (result == JOptionPane.YES_OPTION) {
                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                                    messageDialogBox.initDialogBoxUI(
                                            SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Message", "",
                                            "Successfully uploaded.");
                                    messageDialogBox.setFocusable(true);

                                }
                            });
                        } else if (result == JOptionPane.NO_OPTION) {

                            AccessGrant facebookAccessGrant1 = null;
                            if (facebookAccessGrant1 == null) {
                                try {
                                    LoginWithFacebook loginWithFacebook = new LoginWithFacebook(null);
                                    loginWithFacebook.setHomeForm(getHomeModel().getHomeForm());
                                    loginWithFacebook.login();

                                    boolean processFurther = false;
                                    while (!processFurther) {
                                        facebookAccessGrant1 = getHomeModel().getHomeForm()
                                                .getFacebookAccessGrant();
                                        if (facebookAccessGrant1 == null) {
                                            Thread.sleep(10000);
                                        } else {
                                            processFurther = true;
                                            //isAlreadyLoggedIn = true;
                                        }
                                    }
                                    connectionFactory = new FacebookConnectionFactory(
                                            SSNConstants.SSN_FACEBOOK_API_KEY,
                                            SSNConstants.SSN_FACEBOOK_SECRET_KEY);
                                    connection = connectionFactory.createConnection(facebookAccessGrant);
                                    facebook = connection.getApi();
                                    mediaOperations = facebook.mediaOperations();
                                } catch (InterruptedException ex) {
                                    logger.error(ex);
                                }
                            }
                        }
                    }

                    String[] videoSupported = SSNConstants.SSN_VIDEO_FORMAT_SUPPORTED;
                    final List<String> videoSupportedList = Arrays.asList(videoSupported);

                    for (String file : sharedFileList) {
                        String fileExtension = file.substring(file.lastIndexOf(".") + 1, file.length());
                        Resource resource = new FileSystemResource(file);

                        if (!videoSupportedList.contains(fileExtension.toUpperCase())) {
                            String output = mediaOperations.postPhoto(resource);
                        } else {
                            String output = mediaOperations.postVideo(resource);
                        }

                    }

                    getShareForm().dispose();
                }
            };
            thread.start();
            break;
        case "TwitterSharing":
            LoginWithTwitter.deniedPermission = false;
            thread = new Thread() {
                boolean isAlreadyLoggedIn = false;

                @Override
                public void run() {
                    Set<String> sharedFileList = getFiles();
                    OAuthToken twitterOAuthToken = getHomeModel().getHomeForm().getTwitterOAuthToken();
                    if (twitterOAuthToken == null) {
                        try {
                            LoginWithTwitter loginWithTwitter = new LoginWithTwitter(null);
                            loginWithTwitter.setHomeForm(getHomeModel().getHomeForm());
                            loginWithTwitter.login();

                            boolean processFurther = false;
                            while (!processFurther) {
                                if (LoginWithTwitter.deniedPermission)
                                    break;

                                twitterOAuthToken = getHomeModel().getHomeForm().getTwitterOAuthToken();
                                if (twitterOAuthToken == null) {
                                    Thread.sleep(10000);
                                } else {
                                    processFurther = true;
                                    isAlreadyLoggedIn = true;
                                }
                            }
                        } catch (IOException | InterruptedException ex) {
                            logger.error(ex);
                        }
                    }
                    if (!LoginWithTwitter.deniedPermission) {
                        Twitter twitter = new TwitterTemplate(SSNConstants.SSN_TWITTER_API_KEY,
                                SSNConstants.SSN_TWITTER_SECRET_KEY, twitterOAuthToken.getValue(),
                                twitterOAuthToken.getSecret());
                        TimelineOperations timelineOperations = twitter.timelineOperations();
                        if (!isAlreadyLoggedIn) {
                            SSNConfirmationDialogBox confirmeDialog = new SSNConfirmationDialogBox();
                            TwitterProfile userProfile = twitter.userOperations().getUserProfile();

                            String userName = "";
                            if (userProfile != null) {
                                userName = twitter.userOperations().getScreenName() != null
                                        ? twitter.userOperations().getScreenName()
                                        : userProfile.getName();
                            }
                            confirmeDialog.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(),
                                    "Confirmation", "",
                                    "You are already logged in with " + userName + ", Click OK to continue.");
                            int result = confirmeDialog.getResult();
                            if (result == JOptionPane.YES_OPTION) {
                                SwingUtilities.invokeLater(new Runnable() {
                                    public void run() {
                                        SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                                        messageDialogBox.initDialogBoxUI(
                                                SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Message", "",
                                                "Successfully uploaded.");
                                        messageDialogBox.setFocusable(true);

                                    }
                                });
                            } else if (result == JOptionPane.NO_OPTION) {

                                twitterOAuthToken = null;
                                if (twitterOAuthToken == null) {
                                    try {
                                        LoginWithTwitter loginWithTwitter = new LoginWithTwitter(null);
                                        loginWithTwitter.setHomeForm(getHomeModel().getHomeForm());
                                        loginWithTwitter.login();

                                        boolean processFurther = false;
                                        while (!processFurther) {
                                            twitterOAuthToken = getHomeModel().getHomeForm()
                                                    .getTwitterOAuthToken();
                                            if (twitterOAuthToken == null) {
                                                Thread.sleep(10000);
                                            } else {
                                                processFurther = true;

                                            }
                                        }
                                        twitter = new TwitterTemplate(SSNConstants.SSN_TWITTER_API_KEY,
                                                SSNConstants.SSN_TWITTER_SECRET_KEY,
                                                twitterOAuthToken.getValue(), twitterOAuthToken.getSecret());
                                        timelineOperations = twitter.timelineOperations();
                                    } catch (IOException | InterruptedException ex) {
                                        logger.error(ex);
                                    }
                                }
                            }
                        }

                        for (String file : sharedFileList) {
                            Resource image = new FileSystemResource(file);

                            TweetData tweetData = new TweetData("At " + new Date());
                            tweetData.withMedia(image);
                            timelineOperations.updateStatus(tweetData);
                        }
                    } else {
                        SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                        messageDialogBox.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Alert",
                                "", "User denied for OurHive App permission on twitter.");
                        messageDialogBox.setFocusable(true);
                    }
                    getShareForm().dispose();
                }

            };
            thread.start();
            break;
        case "InstagramSharing":
            break;
        case "MailSharing":
            try {
                String OS = System.getProperty("os.name").toLowerCase();

                Set<String> sharedFileList = getFiles();
                Set<String> voiceNoteList = new HashSet<String>();
                for (String sharedFile : sharedFileList) {
                    String voiceNote = SSNDao.getVoiceCommandPath(new File(sharedFile).getAbsolutePath());
                    if (voiceNote != null && !voiceNote.isEmpty()) {
                        voiceNoteList.add(voiceNote);
                    }
                }
                sharedFileList.addAll(voiceNoteList);

                String fileFullPath = "";
                String caption = "";
                if (sharedFileList.size() == 1) {
                    fileFullPath = sharedFileList.toArray(new String[0])[0];

                    caption = SSMMediaGalleryPanel.readMetaDataForTitle(new File(fileFullPath));

                } else if (sharedFileList.size() > 1) {
                    fileFullPath = SSNHelper.createZipFileFromMultipleFiles(sharedFileList);
                }

                if (OS.contains("win")) {

                    // String subject = "SSN Subject";
                    String subject = caption.equals("") ? SSNConstants.SSN_SHARE_WITH_MAIL_SUBJECT : caption;
                    String body = "";
                    String m = "&subject=%s&body=%s";

                    String outLookExeDir = "C:\\Program Files\\Microsoft Office\\Office14\\Outlook.exe";
                    String mailCompose = "/c";
                    String note = "ipm.note";
                    String mailBodyContent = "/m";

                    m = String.format(m, subject, body);
                    String slashA = "/a";

                    String mailClientConfigParams[] = null;
                    Process startMailProcess = null;

                    mailClientConfigParams = new String[] { outLookExeDir, mailCompose, note, mailBodyContent,
                            m, slashA, fileFullPath };
                    startMailProcess = Runtime.getRuntime().exec(mailClientConfigParams);
                    OutputStream out = startMailProcess.getOutputStream();
                    File zipFile = new File(fileFullPath);
                    zipFile.deleteOnExit();
                } else if (OS.indexOf("mac") >= 0) {
                    //Process p = Runtime.getRuntime().exec(new String[]{String.format("open -a mail ", fileFullPath)});
                    Desktop desktop = Desktop.getDesktop();
                    String mailTo = caption.equals("") ? "?SUBJECT=" + SSNConstants.SSN_SHARE_WITH_MAIL_SUBJECT
                            : caption;
                    URI uriMailTo = null;
                    uriMailTo = new URI("mailto", mailTo, null);
                    desktop.mail(uriMailTo);
                }

                this.getShareForm().dispose();
            } catch (Exception ex) {
                logger.error(ex);
            }
            break;
        case "moveCopy":
            getShareForm().dispose();
            File album = new File(SSNHelper.getSsnHiveDirPath());
            File[] albumPaths = album.listFiles();
            Vector albumNames = new Vector();
            for (int i = 0; i < albumPaths.length; i++) {
                if (!(albumPaths[i].getName().equals("OurHive")) && SSNHelper.lastAlbum != null
                        && !(albumPaths[i].getName().equals(SSNHelper.lastAlbum)))
                    albumNames.add(albumPaths[i].getName());
            }
            if (SSNHelper.lastAlbum != null && !SSNHelper.lastAlbum.equals("OurHive"))
                albumNames.insertElementAt("OurHive", 0);

            SSNInputDialogBox inputBox = new SSNInputDialogBox(true, albumNames);
            inputBox.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Copy Media",
                    "Please Select Album Name");
            String destAlbumName = inputBox.getTextValue();
            if (StringUtils.isNotBlank(destAlbumName)) {
                homeModel.moveAlbum(destAlbumName, getFiles());
            }

        }
        getShareForm().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }
}

From source file:org.codelibs.fess.helper.ProcessHelper.java

protected int destroyProcess(final String sessionId, final JobProcess jobProcess) {
    if (jobProcess != null) {
        final InputStreamThread ist = jobProcess.getInputStreamThread();
        try {//from w w w. j a v a 2 s.co  m
            ist.interrupt();
        } catch (final Exception e) {
            logger.warn("Could not interrupt a thread of an input stream.", e);
        }

        final CountDownLatch latch = new CountDownLatch(3);
        final Process process = jobProcess.getProcess();
        new Thread(() -> {
            try {
                CloseableUtil.closeQuietly(process.getInputStream());
            } catch (final Exception e) {
                logger.warn("Could not close a process input stream.", e);
            } finally {
                latch.countDown();
            }
        }, "ProcessCloser-input-" + sessionId).start();
        new Thread(() -> {
            try {
                CloseableUtil.closeQuietly(process.getErrorStream());
            } catch (final Exception e) {
                logger.warn("Could not close a process error stream.", e);
            } finally {
                latch.countDown();
            }
        }, "ProcessCloser-error-" + sessionId).start();
        new Thread(() -> {
            try {
                CloseableUtil.closeQuietly(process.getOutputStream());
            } catch (final Exception e) {
                logger.warn("Could not close a process output stream.", e);
            } finally {
                latch.countDown();
            }
        }, "ProcessCloser-output-" + sessionId).start();

        try {
            latch.await(10, TimeUnit.SECONDS);
        } catch (final InterruptedException e) {
            logger.warn("Interrupted to wait a process.", e);
        }
        try {
            process.destroyForcibly().waitFor(processDestroyTimeout, TimeUnit.SECONDS);
            return process.exitValue();
        } catch (final Exception e) {
            logger.error("Could not destroy a process correctly.", e);
        }
    }
    return -1;
}

From source file:org.openiam.spml2.spi.example.ShellConnectorImpl.java

public AddResponseType add(AddRequestType reqType) {
    log.debug("add request called..");

    //   powershell.exe -command "& C:\appserver\apache-tomcat-6.0.26\powershell\create.ps1 displayName principalName firstName middleInit lastName password"

    String userName = null;//  w ww. j  a v  a 2s . co  m

    String requestID = reqType.getRequestID();
    /* ContainerID - May specify the container in which this object should be created
     *      ie. ou=Development, org=Example */
    PSOIdentifierType containerID = reqType.getContainerID();
    System.out.println("ContainerId =" + containerID);

    /* PSO - Provisioning Service Object -
     *     -  ID must uniquely specify an object on the target or in the target's namespace  
     *     -  Try to make the PSO ID immutable so that there is consistency across changes. */
    PSOIdentifierType psoID = reqType.getPsoID();
    userName = psoID.getID();

    System.out.println("PSOId=" + psoID.getID());

    /* targetID -  */
    String targetID = reqType.getTargetID();

    // Data sent with request - Data must be present in the request per the spec
    ExtensibleType data = reqType.getData();
    Map<QName, String> otherData = reqType.getOtherAttributes();

    /* Indicates what type of data we should return from this operations */
    ReturnDataType returnData = reqType.getReturnData();

    /* A) Use the targetID to look up the connection information under managed systems */
    ManagedSys managedSys = managedSysService.getManagedSys(targetID);
    ManagedSystemObjectMatch matchObj = null;
    List<ManagedSystemObjectMatch> matchObjList = managedSysObjectMatchDao.findBySystemId(targetID, "USER");
    if (matchObjList != null && matchObjList.size() > 0) {
        matchObj = matchObjList.get(0);
    }

    List<ExtensibleObject> requestAttributeList = reqType.getData().getAny();

    String password = null;
    String givenName = null;
    String lastName = null;
    String displayName = null;
    String init = null;
    String cn = null;
    String principalName = null;
    String sAMAccountName = null;
    String middleInit = null;
    String email = null;
    String nickname = null;
    String title = null;
    String getExchange = null;
    String userState = null;

    String host;
    String hostlogin;
    String hostpassword;

    host = managedSys.getHostUrl();
    hostlogin = managedSys.getUserId();
    hostpassword = managedSys.getDecryptPassword();

    for (ExtensibleObject obj : requestAttributeList) {
        List<ExtensibleAttribute> attrList = obj.getAttributes();

        for (ExtensibleAttribute att : attrList) {

            System.out.println("Attr Name=" + att.getName() + " " + att.getValue());

            String name = att.getName();
            String value = att.getValue();

            if (name.equalsIgnoreCase("password")) {
                password = value;

            }
            if (name.equalsIgnoreCase("firstName")) {
                givenName = value;

            }
            if (name.equalsIgnoreCase("lastName")) {
                lastName = value;
            }
            if (name.equalsIgnoreCase("displayName")) {
                displayName = value;

            }
            if (name.equalsIgnoreCase("initials")) {
                init = value;
            }
            if (name.equalsIgnoreCase("cn")) {
                cn = value;
            }
            if (name.equalsIgnoreCase("principalName")) {
                principalName = value;
            }
            if (name.equalsIgnoreCase("sAMAccountName")) {
                sAMAccountName = value;
            }
            if (name.equalsIgnoreCase("middleInit")) {
                middleInit = value;
            }
            if (name.equalsIgnoreCase("email")) {
                email = value;
            }
            if (name.equalsIgnoreCase("nickname")) {
                nickname = value;
            }
            if (name.equalsIgnoreCase("getExchange")) {
                getExchange = value;
            }
            if (name.equalsIgnoreCase("title")) {
                title = value;
            }
            if (name.equalsIgnoreCase("userState")) {
                userState = value;
            }
        }
    }

    /*
     $adHost =          $args[0]
    $user=            $args[1]
    $userpswd=         $args[2]
    $cn=            $args[3]
    $principalName =    $args[4]
    $samAccountName =    $args[5]
    $pswd =          $args[6]
    $givenname =      $args[7]
    $sn =             $args[8]
    $middleInit   =      $args[9]
    $displayName =      $args[10]
    $ou =            $args[11]
            
     */

    //   powershell.exe -command "& C:\appserver\apache-tomcat-6.0.26\powershell\create.ps1 displayName principalName firstName middleInit lastName password"

    StringBuffer strBuf = new StringBuffer();

    strBuf.append("cmd /c powershell.exe -command \"& C:\\powershell\\ad\\Add-UserActiveDir.ps1 ");
    strBuf.append("'" + host + "' ");
    strBuf.append("'" + hostlogin + "' ");
    strBuf.append("'" + hostpassword + "' ");
    strBuf.append("'" + userName + "' ");
    strBuf.append("'" + principalName + "' ");
    strBuf.append("'" + sAMAccountName + "' ");
    strBuf.append("'" + password + "' ");
    strBuf.append("'" + givenName + "' ");
    strBuf.append("'" + lastName + "' ");
    strBuf.append("'" + middleInit + "' ");
    strBuf.append("'" + displayName + "' ");
    strBuf.append("'" + userState + "' ");
    strBuf.append("'" + email + "' ");
    strBuf.append("'" + nickname + "' ");
    strBuf.append("'" + getExchange + "' ");
    strBuf.append("'" + title + "' \" ");

    //System.out.println("Command line string= " + strBuf.toString());
    String[] cmdarray = { "cmd", strBuf.toString() };
    try {
        //Runtime.getRuntime().exec(cmdarray); //exec(strBuf.toString());
        Process p = Runtime.getRuntime().exec(strBuf.toString());
        System.out.println("Process =" + p);
        OutputStream stream = p.getOutputStream();
        //System.out.println( "stream=" + stream.toString() );

    } catch (Exception e) {
        e.printStackTrace();
    }

    AddResponseType response = new AddResponseType();
    response.setStatus(StatusCodeType.SUCCESS);

    return response;
}

From source file:org.jenkinsci.maven.plugins.hpi.AbstractHpiMojo.java

/**
 * If the project is on Git, figure out Git SHA1.
 *
 * @return null if no git repository is found
 *//*  w  w w  .j  a  v a2 s  . c  o m*/
public String getGitHeadSha1() {
    // we want to allow the plugin that's not sitting at the root (such as findbugs plugin),
    // but we don't want to go up too far and pick up unrelated repository.
    File git = new File(project.getBasedir(), ".git");
    if (!git.exists()) {
        git = new File(project.getBasedir(), "../.git");
        if (!git.exists())
            return null;
    }

    try {
        Process p = new ProcessBuilder("git", "rev-parse", "HEAD").redirectErrorStream(true).start();
        p.getOutputStream().close();
        String v = IOUtils.toString(p.getInputStream()).trim();
        if (p.waitFor() != 0)
            return null; // git rev-parse failed to run

        return v.trim().substring(0, 8);
    } catch (IOException e) {
        LOGGER.log(Level.FINE, "Failed to run git rev-parse HEAD", e);
        return null;
    } catch (InterruptedException e) {
        LOGGER.log(Level.FINE, "Failed to run git rev-parse HEAD", e);
        return null;
    }
}