Example usage for java.lang System setIn

List of usage examples for java.lang System setIn

Introduction

In this page you can find the example usage for java.lang System setIn.

Prototype

public static void setIn(InputStream in) 

Source Link

Document

Reassigns the "standard" input stream.

Usage

From source file:org.perf4j.LogParserTest.java

public void testLogParserMain() throws Exception {
    PrintStream realOut = System.out;
    ByteArrayOutputStream fakeOut = new ByteArrayOutputStream();
    System.setOut(new PrintStream(fakeOut, true));
    try {/* ww w  . jav a  2s  .  c  om*/
        //usage
        realOut.println("-- Usage Test --");
        LogParser.runMain(new String[] { "--help" });
        realOut.println(fakeOut.toString());
        assertTrue(fakeOut.toString().indexOf("Usage") >= 0);
        fakeOut.reset();

        //log on std in, write to std out
        InputStream realIn = System.in;
        ByteArrayInputStream fakeIn = new ByteArrayInputStream(testLog.getBytes());
        System.setIn(fakeIn);
        try {
            realOut.println("-- Std in -> Std out Test --");
            LogParser.runMain(new String[0]);
            realOut.println(fakeOut.toString());
            assertTrue(fakeOut.toString().indexOf("tag") >= 0 && fakeOut.toString().indexOf("tag2") >= 0
                    && fakeOut.toString().indexOf("tag3") >= 0);
            fakeOut.reset();
        } finally {
            System.setIn(realIn);
        }

        //Log from a file
        FileUtils.writeStringToFile(new File("./target/logParserTest.log"), testLog);

        //log from file, write to std out
        realOut.println("-- File in -> Std out Test --");
        LogParser.runMain(new String[] { "./target/logParserTest.log" });
        realOut.println(fakeOut.toString());
        assertTrue(fakeOut.toString().indexOf("tag") >= 0 && fakeOut.toString().indexOf("tag2") >= 0
                && fakeOut.toString().indexOf("tag3") >= 0);
        fakeOut.reset();

        //CSV format test
        realOut.println("-- File in -> Std out Test with CSV --");
        LogParser.runMain(new String[] { "-f", "csv", "./target/logParserTest.log" });
        realOut.println(fakeOut.toString());
        assertTrue(fakeOut.toString().indexOf("\"tag\",") >= 0 && fakeOut.toString().indexOf("\"tag2\",") >= 0
                && fakeOut.toString().indexOf("\"tag3\",") >= 0);
        fakeOut.reset();

        //log from file, write to file
        realOut.println("-- File in -> File out Test --");
        LogParser.runMain(new String[] { "-o", "./target/statistics.out", "./target/logParserTest.log" });
        String statsOut = FileUtils.readFileToString(new File("./target/statistics.out"));
        realOut.println(statsOut);
        assertTrue(
                statsOut.indexOf("tag") >= 0 && statsOut.indexOf("tag2") >= 0 && statsOut.indexOf("tag3") >= 0);

        //log from file, write to file, different timeslice
        realOut.println("-- File in -> File out with different timeslice Test --");
        LogParser.runMain(new String[] { "-o", "./target/statistics.out", "--timeslice", "120000",
                "./target/logParserTest.log" });
        statsOut = FileUtils.readFileToString(new File("./target/statistics.out"));
        realOut.println(statsOut);
        assertTrue(
                statsOut.indexOf("tag") >= 0 && statsOut.indexOf("tag2") >= 0 && statsOut.indexOf("tag3") >= 0);

        //missing param test
        realOut.println("-- Missing param test --");
        assertEquals(1, LogParser.runMain(new String[] { "./target/logParserTest.log", "-o" }));

        //unknown arg test
        realOut.println("-- Unknown arg test --");
        assertEquals(1, LogParser.runMain(new String[] { "./target/logParserTest.log", "--foo" }));
        realOut.println(fakeOut);
        assertTrue(fakeOut.toString().indexOf("Unknown") >= 0);

        //graphing test
        realOut.println("-- File in -> File out with graphing --");
        LogParser.runMain(new String[] { "-o", "./target/statistics.out", "-g", "./target/perfGraphs.out",
                "./src/test/resources/org/perf4j/dummyLog.txt" });
        statsOut = FileUtils.readFileToString(new File("./target/statistics.out"));
        realOut.println(statsOut);
        String graphsOut = FileUtils.readFileToString(new File("./target/perfGraphs.out"));
        realOut.println(graphsOut);
        assertTrue(graphsOut.indexOf("chtt=TPS") > 0 && graphsOut.indexOf("chtt=Mean") > 0);
    } finally {
        System.setOut(realOut);
    }
}

From source file:org.rhq.bundle.ant.AntMain.java

private void initProject(Project project, ClassLoader coreLoader, DeploymentPhase phase) {
    if (coreLoader == null) {
        coreLoader = getClass().getClassLoader();
    }//w  ww  .ja  v  a  2s.  c o m

    project.setCoreLoader(coreLoader);
    project.setProperty(DeployPropertyNames.DEPLOY_PHASE, phase.name());

    addBuildListeners(project);
    addInputHandler(project);

    PrintStream savedErr = System.err;
    PrintStream savedOut = System.out;
    InputStream savedIn = System.in;

    // use a system manager that prevents from System.exit()
    SecurityManager oldsm = null;
    oldsm = System.getSecurityManager();

    //SecurityManager can not be installed here for backwards
    //compatibility reasons (PD). Needs to be loaded prior to
    //ant class if we are going to implement it.
    //System.setSecurityManager(new NoExitSecurityManager());
    try {
        if (allowInput) {
            project.setDefaultInputStream(System.in);
        }
        System.setIn(new DemuxInputStream(project));
        System.setOut(new PrintStream(new DemuxOutputStream(project, false)));
        System.setErr(new PrintStream(new DemuxOutputStream(project, true)));

        if (!projectHelp) {
            project.fireBuildStarted();
        }

        // set the thread priorities
        if (threadPriority != null) {
            try {
                project.log("Setting Ant's thread priority to " + threadPriority, Project.MSG_VERBOSE);
                Thread.currentThread().setPriority(threadPriority.intValue());
            } catch (SecurityException swallowed) {
                //we cannot set the priority here.
                project.log("A security manager refused to set the -nice value");
            }
        }

        project.init();

        // set user-define properties
        Enumeration e = definedProps.keys();
        while (e.hasMoreElements()) {
            String arg = (String) e.nextElement();
            String value = (String) definedProps.get(arg);
            project.setProperty(arg, value);
        }

        try {
            addTaskDefsForBundledTasks(project);
        } catch (IOException ie) {
            throw new RuntimeException(ie);
        } catch (ClassNotFoundException ce) {
            throw new RuntimeException(ce);
        }

        project.setProperty(MagicNames.ANT_FILE, buildFile.getAbsolutePath());
        project.setProperty(MagicNames.ANT_FILE_TYPE, MagicNames.ANT_FILE_TYPE_FILE);

        project.setKeepGoingMode(keepGoingMode);
        if (proxy) {
            //proxy setup if enabled
            ProxySetup proxySetup = new ProxySetup(project);
            proxySetup.enableProxies();
        }

        // RHQ NOTE: Besides parsing the build file, this will also execute the implicit ("") target.
        ProjectHelper.configureProject(project, buildFile);
    } finally {
        // put back the original security manager
        //The following will never eval to true. (PD)
        if (oldsm != null) {
            System.setSecurityManager(oldsm);
        }

        System.setOut(savedOut);
        System.setErr(savedErr);
        System.setIn(savedIn);
    }
}

From source file:org.rzo.yajsw.app.WrapperManagerImpl.java

/**
 * Tee system streams.//  ww  w . j a  va 2  s  .  co  m
 * 
 * @param outFile
 *            the out file
 * @param path
 *            the path
 * @param visible
 *            the visible
 */
private void teeSystemStreams(String outFile, String path, boolean visible) {
    File fOut = createRWfile(path, "out_" + outFile);
    // if (fOut.exists())
    // fOut.delete();
    File fErr = createRWfile(path, "err_" + outFile);
    // if (fErr.exists())
    // fErr.delete();
    File fIn = createRWfile(path, "in_" + outFile);

    try {
        PrintStream wrapperOut = (PrintStream) new CyclicBufferFilePrintStream(fOut);
        TeeOutputStream newOut = (TeeOutputStream) new TeeOutputStream();
        newOut.connect(wrapperOut);
        // pipe output to console only if it is visible
        if (visible)
            newOut.connect(System.out);
        _outStream = wrapperOut;
        System.setOut(new PrintStream(newOut));
    } catch (Throwable e) {
        e.printStackTrace();
    }

    try {

        PrintStream wrapperErr = (PrintStream) new CyclicBufferFilePrintStream(fErr);
        TeeOutputStream newErr = (TeeOutputStream) new TeeOutputStream();
        newErr.connect(wrapperErr);
        // pipe output to console only if it is visible
        if (visible)
            newErr.connect(System.err);
        _errStream = newErr;
        System.setErr(new PrintStream(newErr));
    } catch (Throwable e) {
        e.printStackTrace();
    }

    try {
        CyclicBufferFileInputStream wrapperIn = new CyclicBufferFileInputStream(fIn);
        TeeInputStream newIn = (TeeInputStream) new TeeInputStream();
        newIn.connect(wrapperIn);
        newIn.connect(System.in);
        System.setIn(newIn);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:probos.TestQsub.java

@Test
public void testCommandLineWithoutJobScript() throws Exception {
    qsub qs = new qsub();
    InputStream in = System.in;
    System.setIn(IOUtils.toInputStream("hostname", "UTF-8"));
    PBSJob job = qs.createJob(new String[] { "-N", "hostname" });
    assertEquals("hostname", job.getJob_Name());
    System.setIn(in);/*from  w  w  w  .j a  v a2s.  c om*/
}

From source file:webx.studio.projectcreation.ui.ProjectCreationWizard.java

@Override
public boolean performFinish() {
    if (_DEBUG)//from w ww . j av  a2s. co m
        time = System.currentTimeMillis();
    final NameRule nameRule = new NameRule(projectInfomationWizardPage.getProjectGroupId(),
            projectInfomationWizardPage.getProjectName());
    final Model parentModel = projectInfomationWizardPage.getModel(nameRule);
    projectStructureWizardPage.updateModel(parentModel, nameRule);
    final IPath location = Path.fromOSString(projectInfomationWizardPage.getPathValue());

    final JejuProject webxProject = new JejuProject(nameRule.getProjectName());
    webxProject.setWebxVersion(projectInfomationWizardPage.getWebxVersion());
    final WebxStructureModel webxStructureModel = projectStructureWizardPage.getWebxStructureModel();
    final String settingFilePath = projectInfomationWizardPage.getSeetingFilePath();
    final String antxPropertiesPath = projectInfomationWizardPage.getAntxPropertiesPath();
    final String autoconfigCharset = projectInfomationWizardPage.getAutoconfigCharset();
    webxProject.setSettingFile(StringUtils.trimToEmpty(settingFilePath));
    webxProject.setAntxPropertiesFile(StringUtils.trimToEmpty(antxPropertiesPath));
    webxProject.setAutoconfigCharset(StringUtils.trimToEmpty(autoconfigCharset));
    webxProject.setWebRoot(getWebRoot(location, nameRule));
    WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
        protected void execute(IProgressMonitor monitor) throws CoreException {
            IOConsole mc = getIOConsole();
            IOConsoleOutputStream consoleStream = mc.newOutputStream();

            System.setIn(mc.getInputStream());
            System.setErr(new PrintStream(consoleStream));
            System.setOut(new PrintStream(consoleStream));
            try {
                if (_DEBUG) {
                    time = System.currentTimeMillis();
                }
                monitor.beginTask("Create a Jeju project[ " + nameRule.getProjectName() + " ]", 20);
                List<IProject> projects = ProjectHelper.createProject(location, parentModel, webxStructureModel,
                        nameRule, new SubProgressMonitor(monitor, 10));
                if (_DEBUG) {
                    System.out.println("Creating eclipse project costs "
                            + (System.currentTimeMillis() - time) / 1000 + " second.");
                    time = System.currentTimeMillis();
                }

                if (JavaCore.getClasspathVariable(ProjectCreationConstants.M2_REPO_KEY) == null) {
                    JavaCore.setClasspathVariable(ProjectCreationConstants.M2_REPO_KEY,
                            new Path(MavenHelper.getLocalRepository()));
                }
                File parentPomFile = new File(location.toFile(), nameRule.getProjectName() + "/pom.xml");
                MavenHelper.generateEclipse(parentPomFile.getParent(), settingFilePath,
                        new SubProgressMonitor(monitor, 10));
                if (_DEBUG)
                    System.out.println("Running maven command costs "
                            + (System.currentTimeMillis() - time) / 1000 + " second.");
                for (IProject project : projects) {
                    webxProject.getProjectNames().add(project.getName());
                }
                Job job = new Job("Save Metadata") {

                    protected IStatus run(IProgressMonitor monitor) {
                        JejuProjectCore.addWebXProject(webxProject);
                        return Status.OK_STATUS;
                    }

                };
                job.schedule();
            } catch (Exception e) {
                throw new CoreException(
                        new Status(IStatus.ERROR, ProjectCreationPlugin.PLUGIN_ID, -1, e.getMessage(), e));
            } finally {
                System.setIn(System.in);
                System.setErr(System.err);
                System.setOut(System.out);
                try {
                    // mc.getInputStream().close();
                    consoleStream.close();
                } catch (Exception e) {
                    ProjectCreationPlugin.logThrowable(e);
                }
            }
        }
    };

    try {
        getContainer().run(true, true, op);
        UIUtil.refreshPackageExplorer();
    } catch (InterruptedException e) {
        return false;
    } catch (InvocationTargetException e) {
        e.printStackTrace();

        Throwable t = e.getTargetException();
        if (t instanceof CoreException) {
            CoreException ce = (CoreException) t;
            Throwable tmpt = ce.getStatus().getException();
            String errMessage = null;
            if (tmpt instanceof MavenExecuteException) {
                errMessage = "Maven command execute failed!";
            }
            ErrorDialog.openError(getShell(),
                    NLS.bind("Failed to create project \"{0}\"", nameRule.getProjectName()), errMessage,
                    ((CoreException) t).getStatus());
        } else {
            MessageDialog.openError(getShell(), "Creation Problems",
                    NLS.bind("Internal error: {0}", t.getMessage()));
        }
        ProjectCreationPlugin.logThrowable(t);
        return false;
    }
    return true;

}