Example usage for java.lang System setErr

List of usage examples for java.lang System setErr

Introduction

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

Prototype

public static void setErr(PrintStream err) 

Source Link

Document

Reassigns the "standard" error output stream.

Usage

From source file:org.neo4j.io.pagecache.PageCacheTest.java

@RepeatRule.Repeat(times = 100)
@Test(timeout = SHORT_TIMEOUT_MILLIS)
public void flushingDuringPagedFileCloseMustRetryUntilItSucceeds() throws IOException {
    FileSystemAbstraction fs = new DelegatingFileSystemAbstraction(this.fs) {
        @Override//from w  w w  .j a  v a2  s .c  o m
        public StoreChannel open(File fileName, String mode) throws IOException {
            return new DelegatingStoreChannel(super.open(fileName, mode)) {
                private int writeCount = 0;

                @Override
                public void writeAll(ByteBuffer src, long position) throws IOException {
                    if (writeCount++ < 10) {
                        throw new IOException("This is a benign exception that we expect to be thrown "
                                + "during a flush of a PagedFile.");
                    }
                    super.writeAll(src, position);
                }
            };
        }
    };
    getPageCache(fs, maxPages, pageCachePageSize, PageCacheTracer.NULL);
    PrintStream oldSystemErr = System.err;

    try (PagedFile pf = pageCache.map(file("a"), filePageSize);
            PageCursor cursor = pf.io(0, PF_SHARED_WRITE_LOCK)) {
        assertTrue(cursor.next());
        writeRecords(cursor);

        // Silence any stack traces the failed flushes might print.
        System.setErr(new PrintStream(new ByteArrayOutputStream()));
    } finally {
        System.setErr(oldSystemErr);
    }

    verifyRecordsInFile(file("a"), recordsPerFilePage);
}

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

private void initProject(Project project, ClassLoader coreLoader, DeploymentPhase phase) {
    if (coreLoader == null) {
        coreLoader = getClass().getClassLoader();
    }/*from   w  w w .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.openlaszlo.sc.SWF9External.java

/**
 * Run the compiler using the command/arguments in cmd. Invokes the Flex compiler classes
 * directly, does not exec a subprocess. 
 * Collect and report any errors, and check for the existence
 * of the output file.//from  w ww .  ja v  a 2 s. co  m
 * @throw CompilerError if there are errors messages from the external
 *        compiler, or if any part of the compilation process has problems
 */
public void callJavaCompileCommand(List acmd, String dir, List tunits, String outfileName) throws IOException // TODO: [2007-11-20 dda] clean up, why catch only some exceptions?
{
    final List cmd = acmd;
    final String compilerClass = (String) cmd.remove(0);
    String[] cmdstr = (String[]) cmd.toArray(new String[0]);
    String prettycmd = prettyCommand(cmd);
    System.err.println("Executing compiler: (cd " + dir + "; " + prettycmd + ")");
    BigErrorString bigErrorString = new BigErrorString();

    // Generate a small script (unix style) to document how
    // to build this batch of files.
    String buildsh = isWindows() ? "rem build script\n" : "#!/bin/sh\n";
    buildsh += "cd \"" + dir + "\"\n";
    buildsh += prettycmd + "\n";
    String buildfn = isWindows() ? "build.bat" : "build.sh";
    Compiler.emitFile(workDirectoryName(buildfn), buildsh);

    // Remove the shell script executable path from beginning of cmd arg list
    cmd.remove(0);

    if (options.getBoolean(Compiler.EMIT_AS3_ONLY)) {
        // write out the command line as the output instead
        PrintWriter outf = new PrintWriter(new FileWriter(outfileName));
        for (Iterator iter = cmd.iterator(); iter.hasNext();) {
            String arg = (String) iter.next();
            outf.println(arg);
        }
        outf.close();
        System.err.println(
                "option EMIT_AS3_ONLY set, returning without invoking flex compiler, call 'lcompile #' to compile as3");
        return;
    }
    // Save original System.err, System.out
    PrintStream sout = System.out;
    PrintStream serr = System.err;

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ByteArrayOutputStream berr = new ByteArrayOutputStream();

    PrintStream nout = new PrintStream(bout);
    PrintStream nerr = new PrintStream(berr);

    // Rebind to capture output
    System.setErr(nerr);
    System.setOut(nout);

    // flex2.tools.Mxmlc +flexlib="$FLEX_HOME/frameworks"
    // flex2.tools.Compc
    // 

    System.setProperty("FLEX_HOME", FLEX_HOME());
    // The Mxlmc and Compc util classes need to see this arg first in the args list
    cmd.add(0, "+flexlib=" + FLEX_HOME() + "/frameworks");

    final Integer exitval[] = new Integer[1];

    Thread worker = new Thread() {
        public void run() {
            //Process proc = Runtime.getRuntime().exec(cmdstr, (String[])newenv.toArray(new String[0]), null);

            String args[] = (String[]) cmd.toArray(new String[0]);
            if (compilerClass.equals("mxmlc")) {
                flex2.tools.Mxmlc.mxmlc(args);
                exitval[0] = new Integer(flex2.compiler.util.ThreadLocalToolkit.errorCount());

            } else if (compilerClass.equals("compc")) {
                flex2.tools.Compc.compc(args);
                exitval[0] = new Integer(flex2.compiler.util.ThreadLocalToolkit.errorCount());
            }

        }
    };

    try {
        worker.start();
        worker.join();
    } catch (java.lang.InterruptedException e) {
        throw new CompilerError("Errors from compiler, output file not created" + e);
    } finally {
        // Restore system output and err streams
        System.setErr(serr);
        System.setOut(sout);
    }

    try {
        nerr.flush();
        nout.flush();

        System.out.println("compiler output is " + bout.toString());

        OutputCollector outcollect = new OutputCollector(new ByteArrayInputStream(bout.toByteArray()));
        ExternalCompilerErrorCollector errcollect = new ExternalCompilerErrorCollector(
                new ByteArrayInputStream(berr.toByteArray()), tunits);
        outcollect.start();
        errcollect.start();
        outcollect.join();
        errcollect.join();

        if (outcollect.getException() != null) {
            System.err.println("Error collecting compiler output: " + outcollect.getException());
            // TODO: [2007-11-20 dda] log this
        }
        String compilerOutput = outcollect.getOutput();
        if (compilerOutput.length() > 0) {
            System.err.println("compiler output:\n" + compilerOutput);
        }

        if (errcollect.getException() != null) {
            System.err.println("Error collecting compiler output: " + errcollect.getException());
            // TODO: [2007-11-20 dda] log this
        }
        List severe = errcollect.getSevereErrors();
        if (severe.size() > 0) {
            for (Iterator iter = severe.iterator(); iter.hasNext();) {
                String errstr = "SEVERE ERROR: " + (String) iter.next();
                bigErrorString.add(errstr);
                System.err.println(errstr);
            }
        }
        List errs = errcollect.getErrors();
        if (errs.size() > 0) {
            System.err.println("ERRORS: ");
            for (Iterator iter = errs.iterator(); iter.hasNext();) {
                ExternalCompilerError err = (ExternalCompilerError) iter.next();
                TranslationUnit tunit = err.getTranslationUnit();
                String srcLineStr;
                TranslationUnit.SourceFileLine srcFileLine;

                // actualSrcLine is the name/linenumber of the actual files
                // used in compilation, not the original sources.
                String actualSrcFile = null;
                if (tunit == null) {
                    actualSrcFile = "(unknown)";
                } else {
                    actualSrcFile = tunit.getSourceFileName();
                    if (actualSrcFile == null)
                        actualSrcFile = "(" + tunit.getName() + ")";
                }

                String actualSrcLine = "[" + actualSrcFile + ": " + err.getLineNumber() + "] ";

                if (tunit == null) {
                    srcLineStr = "tunit/line unknown: ";
                } else if ((srcFileLine = tunit.originalLineNumber(err.getLineNumber())) == null) {
                    srcLineStr = "line unknown: ";
                } else {
                    srcLineStr = srcFileLine.sourcefile.name + ": " + srcFileLine.line + ": ";
                }
                System.err.println(actualSrcLine + srcLineStr + err.getErrorString());

                bigErrorString.add(srcLineStr + err.cleanedErrorString());
            }
        }

        if (exitval[0].intValue() != 0) {
            System.err.println("FAIL: compiler returned " + exitval[0].intValue());
        }
    } catch (InterruptedException ie) {
        throw new CompilerError("Interrupted compiler");
    }

    System.err.println("Done executing compiler");
    if (!new File(outfileName).exists()) {
        System.err.println("Intermediate file " + outfileName + ": does not exist");
        if (bigErrorString.str.length() > 0) {
            throw new CompilerError(bigErrorString.str);
        } else {
            throw new CompilerError("Errors from compiler, output file not created");
        }
    }

}

From source file:de.huxhorn.lilith.Lilith.java

public static void startUI(final String appTitle) {
    final Logger logger = LoggerFactory.getLogger(Lilith.class);

    UIManager.installLookAndFeel("JGoodies Windows", "com.jgoodies.looks.windows.WindowsLookAndFeel");
    UIManager.installLookAndFeel("JGoodies Plastic", "com.jgoodies.looks.plastic.PlasticLookAndFeel");
    UIManager.installLookAndFeel("JGoodies Plastic 3D", "com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
    UIManager.installLookAndFeel("JGoodies Plastic XP", "com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
    // Substance requires 1.6
    UIManager.installLookAndFeel("Substance Dark - Twilight",
            "org.pushingpixels.substance.api.skin.SubstanceTwilightLookAndFeel");
    UIManager.installLookAndFeel("Substance Light - Business",
            "org.pushingpixels.substance.api.skin.SubstanceBusinessLookAndFeel");

    //UIManager.installLookAndFeel("Napkin", "net.sourceforge.napkinlaf.NapkinLookAndFeel");

    // look & feels must be installed before creation of ApplicationPreferences.
    ApplicationPreferences applicationPreferences = new ApplicationPreferences();

    // init look & feel
    String lookAndFeelName = applicationPreferences.getLookAndFeel();
    String systemLookAndFeelClassName = UIManager.getSystemLookAndFeelClassName();
    String lookAndFeelClassName = systemLookAndFeelClassName;
    if (lookAndFeelName != null) {
        for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if (lookAndFeelName.equals(info.getName())) {
                lookAndFeelClassName = info.getClassName();
                break;
            }//from  w w w .  ja v a  2 s  . c o  m
        }
    }

    try {
        UIManager.setLookAndFeel(lookAndFeelClassName);
    } catch (Throwable e) {
        if (logger.isWarnEnabled())
            logger.warn("Failed to set look&feel to '{}'.", lookAndFeelClassName, e);
        if (!lookAndFeelClassName.equals(systemLookAndFeelClassName)) {
            try {
                UIManager.setLookAndFeel(systemLookAndFeelClassName);
                lookAndFeelClassName = systemLookAndFeelClassName;
            } catch (Throwable e2) {
                if (logger.isWarnEnabled())
                    logger.warn("Failed to set look&feel to '{}'.", systemLookAndFeelClassName, e);
                lookAndFeelClassName = null;
            }
        }
    }

    boolean screenMenuBar = false;
    if (systemLookAndFeelClassName.equals(lookAndFeelClassName)) {
        // This instance of application is only used to query some info. The real one is in MainFrame.
        Application application = new DefaultApplication();

        if (application.isMac()) {
            // Use Apple Aqua L&F screen menu bar if available; set property before any frames created
            try {
                System.setProperty(APPLE_SCREEN_MENU_BAR_SYSTEM_PROPERTY, "true");
                screenMenuBar = true;
            } catch (Throwable e) {
                try {
                    screenMenuBar = Boolean
                            .parseBoolean(System.getProperty(APPLE_SCREEN_MENU_BAR_SYSTEM_PROPERTY, "false"));
                } catch (Throwable e2) {
                    // ignore
                }
            }
        }
    }

    applicationPreferences.setUsingScreenMenuBar(screenMenuBar);

    boolean splashScreenDisabled = applicationPreferences.isSplashScreenDisabled();
    try {
        SplashScreen splashScreen = null;
        if (!splashScreenDisabled) {
            CreateSplashRunnable createRunnable = new CreateSplashRunnable(appTitle);
            EventQueue.invokeAndWait(createRunnable);
            splashScreen = createRunnable.getSplashScreen();
            Thread.sleep(500); // so the splash gets the chance to get displayed :(
            updateSplashStatus(splashScreen, "Initialized application preferences...");
        }

        File startupApplicationPath = applicationPreferences.getStartupApplicationPath();
        if (startupApplicationPath.mkdirs()) {
            if (logger.isDebugEnabled())
                logger.debug("Created '{}'.", startupApplicationPath.getAbsolutePath());
        }

        // System.err redirection
        {
            File errorLog = new File(startupApplicationPath, "errors.log");
            boolean freshFile = false;
            if (!errorLog.isFile()) {
                freshFile = true;
            }
            try {
                FileOutputStream fos = new FileOutputStream(errorLog, true);
                PrintStream ps = new PrintStream(fos, true, StandardCharsets.UTF_8.name());
                if (!freshFile) {
                    ps.println("----------------------------------------");
                }
                String currentDateTime = DateTimeFormatters.DATETIME_IN_SYSTEM_ZONE_SPACE.format(Instant.now());
                ps.println("Started " + APP_NAME + " V" + APP_VERSION + " at " + currentDateTime);
                System.setErr(ps);
                if (logger.isInfoEnabled())
                    logger.info("Writing System.err to '{}'.", errorLog.getAbsolutePath());
            } catch (FileNotFoundException | UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        File prevPathFile = new File(startupApplicationPath,
                ApplicationPreferences.PREVIOUS_APPLICATION_PATH_FILENAME);
        if (prevPathFile.isFile()) {
            updateSplashStatus(splashScreen, "Moving application path content...");
            moveApplicationPathContent(prevPathFile, startupApplicationPath);
        }
        if (!applicationPreferences.isLicensed()) {
            hideSplashScreen(splashScreen);

            LicenseAgreementDialog licenseDialog = new LicenseAgreementDialog();
            licenseDialog.setAlwaysOnTop(true);
            licenseDialog.setAutoRequestFocus(true);
            Windows.showWindow(licenseDialog, null, true);
            if (licenseDialog.isLicenseAgreed()) {
                applicationPreferences.setLicensed(true);
            } else {
                if (logger.isWarnEnabled())
                    logger.warn("Didn't accept license! Exiting...");
                System.exit(-1);
            }
        }

        updateSplashStatus(splashScreen, "Creating main window...");
        CreateMainFrameRunnable createMain = new CreateMainFrameRunnable(applicationPreferences, splashScreen,
                appTitle);
        EventQueue.invokeAndWait(createMain);
        final MainFrame frame = createMain.getMainFrame();
        if (logger.isDebugEnabled())
            logger.debug("After show...");
        updateSplashStatus(splashScreen, "Initializing application...");
        EventQueue.invokeAndWait(frame::startUp);
        hideSplashScreen(splashScreen);
        mainFrame = frame;

    } catch (InterruptedException ex) {
        if (logger.isInfoEnabled())
            logger.info("Interrupted...", ex);
        IOUtilities.interruptIfNecessary(ex);
    } catch (InvocationTargetException ex) {
        if (logger.isWarnEnabled())
            logger.warn("InvocationTargetException...", ex);
        if (logger.isWarnEnabled())
            logger.warn("Target-Exception: ", ex.getTargetException());

    }
}

From source file:com.twinsoft.convertigo.eclipse.ConvertigoPlugin.java

/**
 * This method is called upon plug-in activation
 *//*from   www .j  ava  2 s .c o m*/
@Override
public void start(final BundleContext context) throws Exception {
    super.start(context);

    // Version check
    if (!com.twinsoft.convertigo.eclipse.Version.productVersion
            .equals(com.twinsoft.convertigo.beans.Version.productVersion)) {
        throw new Exception(
                "The product version numbers of Eclipse Plugin and Objects libraries are differents.");
    } else if (!com.twinsoft.convertigo.eclipse.Version.productVersion
            .equals(com.twinsoft.convertigo.engine.Version.productVersion)) {
        throw new Exception(
                "The product version numbers of Eclipse Plugin and Engine libraries are differents.");
    }

    Engine.setStudioMode();

    plugin = this;
    try {
        resourceBundle = ResourceBundle.getBundle("com.twinsoft.convertigo.eclipse.ConvertigoPluginResources");
    } catch (MissingResourceException x) {
        resourceBundle = null;
    }

    log = getLog();
    projectManager = new ProjectManager();
    clipboardManagerSystem = new ClipboardManager();
    clipboardManagerDND = new ClipboardManager();
    //learnProxy = new LearnProxy();

    // Create consoles
    createConsoles();

    // Redirect stdout and stderr
    System.setOut(new StdoutStream());
    System.setErr(new StderrStream());

    studioLog = new Log(ConvertigoPlugin.getDefault().studioConsoleStream);
    studioLog.logLevel = Log.LOGLEVEL_DEBUG;

    try {
        studioLog.logLevel = new Integer(ConvertigoPlugin.getProperty(ConvertigoPlugin.PREFERENCE_LOG_LEVEL))
                .intValue();
    } catch (NumberFormatException e) {
        studioLog.warning("Unable to retrieve the log level; using default log level (4).");
    }

    studioLog.message("Starting the Convertigo studio eclipse plugin");

    try {
        highlightDetectedObject = new Boolean(
                ConvertigoPlugin.getProperty(ConvertigoPlugin.PREFERENCE_TREE_HIGHLIGHT_DETECTED))
                        .booleanValue();
    } catch (NumberFormatException e) {
        studioLog.warning("Unable to retrieve the highlight option; using default highlight option (true).");
    }

    // In STUDIO, the Convertigo User Workspace is in the current Eclipse Workspace/.metadata/.plugins/com.twinsoft.convertigo.studio
    Engine.USER_WORKSPACE_PATH = getDefault().getStateLocation().toFile().getCanonicalPath();

    // In STUDIO, the Convertigo Projects directory is the current Eclipse Workspace
    Engine.PROJECTS_PATH = ResourcesPlugin.getWorkspace().getRoot().getRawLocation().toFile()
            .getCanonicalPath();

    //      checkPre_6_2_0_Migration();

    // Adds listeners
    addListeners();

    DatabaseObjectsManager.openableProject = new DatabaseObjectsManager.OpenableProject() {

        @Override
        public boolean canOpen(String projectName) {
            if ("true".equals(ConvertigoPlugin.getProperty(PREFERENCE_ENGINE_LOAD_ALL_PROJECTS))) {
                return true;
            }
            return isProjectOpened(projectName);
        }

    };

    final Exception afterPscException[] = { null };
    final Runnable afterPscOk = new Runnable() {

        public void run() {
            try {
                // Create embedded Tomcat
                studioLog.message("Starting the embedded Tomcat");
                System.setProperty("org.apache.commons.logging.log",
                        "org.apache.commons.logging.impl.Jdk14Logger");

                Path path = new Path("tomcat");
                URL tomcatHomeUrl = FileLocator.find(context.getBundle(), path, null);

                String xulrunner_url = System.getProperty("org.eclipse.swt.browser.XULRunnerPath");
                if (xulrunner_url == null || xulrunner_url.equals("")) {
                    Bundle[] bundles = Platform.getFragments(context.getBundle());
                    for (Bundle bundle : bundles) {
                        String symbolicName = bundle.getSymbolicName();
                        if (symbolicName.startsWith("com.twinsoft.convertigo.studio.xulrunner")) {
                            URL url = FileLocator.find(bundle, new Path("xulrunner"), null);
                            xulrunner_url = FileLocator.toFileURL(url).getPath();
                            System.setProperty("org.eclipse.swt.browser.XULRunnerPath", xulrunner_url);
                            break;
                        }
                    }
                }

                String tomcatHome = FileLocator.toFileURL(tomcatHomeUrl).getPath();

                int index = (System.getProperty("os.name").indexOf("Windows") != -1) ? 1 : 0;
                tomcatHome = tomcatHome.substring(index);

                embeddedTomcat = new EmbeddedTomcat(tomcatHome);

                configureDeployConfiguration();

                displayWaitScreen();

                new Thread(embeddedTomcat, "Embedded Tomcat").start();
                new Thread(new Runnable() {

                    public void run() {
                        int nbRetry = 0;
                        while (!Engine.isStartFailed && !Engine.isStarted) {
                            try {
                                Thread.sleep(500);
                                nbRetry++;
                            } catch (InterruptedException e) {
                                // Ignore
                            }

                            // Aborting if too many retries
                            if (nbRetry > 360)
                                return;
                        }

                        if (Engine.isStartFailed) {
                            logError("Unable to start engine; see console for more details");
                            return;
                        }

                        // The console threads must be started AFTER the engine
                        consolePipes.startConsoleThreads();

                        try {
                            deploymentConfigurationManager.doMigration();
                        } catch (Exception e) {
                            logException(e, "Unable to migrate deployment configurations");
                        }

                        studioLog.message("Embedded Tomcat started");

                        for (Runnable runnable : runAtStartup) {
                            Display.getDefault().asyncExec(runnable);
                        }
                        runAtStartup.clear();
                    }

                }, "Wait Embedded Tomcat started").start();

            } catch (Exception e) {
                afterPscException[0] = e;
            }
        }

    };

    try {
        decodePsc();
        //Engine.isStartFailed = true;
        afterPscOk.run();
        if (afterPscException[0] != null) {
            throw afterPscException[0];
        }
    } catch (PscException e) {
        studioLog.message(
                "No valid PSC, the Engine will start after the registration wizard.\nFailure message : "
                        + e.getMessage());
        Engine.isStartFailed = true;
        Display display = getDisplay();
        display.asyncExec(new Runnable() {

            public void run() {
                try {
                    boolean success = SetupAction.runSetup();
                    if (success) {
                        Engine.isStartFailed = false;
                        new Thread(afterPscOk, "Start embedded Tomcat").start();
                    } else {
                        IWorkbench workbench = PlatformUI.getWorkbench();
                        workbench.close();
                    }
                } catch (Throwable t) {
                    studioLog.exception(t, "Failure during the Convertigo setup wizard");
                }
            }

        });
    }

    studioLog.message("Convertigo studio started");
}

From source file:org.ohdsi.whiteRabbit.WhiteRabbitMain.java

private JComponent createConsolePanel() {
    JTextArea consoleArea = new JTextArea();
    consoleArea.setToolTipText("General progress information");
    consoleArea.setEditable(false);//  ww  w .ja va  2 s .  c o  m
    Console console = new Console();
    console.setTextArea(consoleArea);
    System.setOut(new PrintStream(console));
    System.setErr(new PrintStream(console));
    JScrollPane consoleScrollPane = new JScrollPane(consoleArea);
    consoleScrollPane.setBorder(BorderFactory.createTitledBorder("Console"));
    consoleScrollPane.setPreferredSize(new Dimension(800, 200));
    consoleScrollPane.setAutoscrolls(true);
    ObjectExchange.console = console;
    return consoleScrollPane;
}

From source file:org.exist.launcher.Launcher.java

/**
 * Ensure that stdout and stderr messages are also printed
 * to the logs.//from w w  w. j  a  v a2 s  . c  om
 */
private void captureConsole() {
    System.setOut(createLoggingProxy(System.out));
    System.setErr(createLoggingProxy(System.err));
}

From source file:org.hyperic.hq.agent.server.AgentDaemon.java

private void redirectStreams(Properties props) {
    //redirect System.{out,err} to log4j appender
    PrintStream stream;/*  ww w.j ava  2s .c  om*/
    if ((stream = newLogStream("SystemOut", props)) != null) {
        System.setOut(stream);
    }
    if ((stream = newLogStream("SystemErr", props)) != null) {
        System.setErr(stream);
    }
}

From source file:org.hammurapi.TaskBase.java

/**
 * @param options/*from www  .ja  v a2s  .c  om*/
 * @param line
 * @param task
 * @param project
 */
protected void configure(Options options, CommandLine line) {
    String[] largs = line.getArgs();
    if (largs.length == 0) {
        System.out.println("Output dir has to be provided");
        printHelpAndExit(options);
    }

    if (!line.hasOption('o')) {
        new File(largs[0]).mkdirs();
        Output output = createOutput();
        output.setDir(largs[0]);

        if (line.hasOption('x')) {
            output.setEmbeddedStyle(false);
            output.setExtension(".xml");
        }
    }

    if (largs.length == 1 && !line.hasOption('A')) {
        System.out.println("At least one source directory or archive must be provided");
        printHelpAndExit(options);
    }

    if (line.hasOption('y')) {
        setReviewDescription(line.getOptionValue('y'));
    }

    for (int i = 1; i < largs.length; i++) {
        File file = new File(largs[i]);
        if (file.isFile()) {
            srcFiles.add(file);
        } else if (file.isDirectory()) {
            createSrc().setDir(file);
        }
    }

    String[] values = line.getOptionValues('c');
    for (int i = 0; values != null && i < values.length; i++) {
        createClasspath().append(new Path(project, values[i]));
    }

    values = line.getOptionValues('m');
    for (int i = 0; values != null && i < values.length; i++) {
        createConfig().setFile(new File(values[i]));
    }

    values = line.getOptionValues('q');
    for (int i = 0; values != null && i < values.length; i++) {
        createConfig().setURL(values[i]);
    }

    values = line.getOptionValues('I');
    for (int i = 0; values != null && i < values.length; i++) {
        InspectorEntry ie = createInspector();
        ie.setName(values[i]);
        ie.setEnabled(true);
    }

    values = line.getOptionValues('X');
    for (int i = 0; values != null && i < values.length; i++) {
        InspectorEntry ie = createInspector();
        ie.setName(values[i]);
        ie.setEnabled(false);
    }

    setEvictBadInspectors(line.hasOption('E'));

    setEmbeddedInspectors(!line.hasOption('e'));

    if (line.hasOption('t')) {
        setDebugType(line.getOptionValue('t'));
    }

    if (line.hasOption('r')) {
        setUnpackDir(new File(line.getOptionValue('r')));
    }

    if (line.hasOption('T')) {
        setTitle(line.getOptionValue('T'));
    }

    BuildLogger logger = new DefaultLogger();
    logger.setMessageOutputLevel(Project.MSG_INFO);
    logger.setOutputPrintStream(System.out);
    logger.setErrorPrintStream(System.err);
    logger.setEmacsMode(false);

    if (line.hasOption('v')) {
        logger.setMessageOutputLevel(Project.MSG_VERBOSE);
    }

    if (line.hasOption('g')) {
        logger.setMessageOutputLevel(Project.MSG_DEBUG);
    }

    project.addBuildListener(logger);

    System.setOut(new PrintStream(new DemuxOutputStream(project, false)));
    System.setErr(new PrintStream(new DemuxOutputStream(project, true)));

    if (line.hasOption('w')) {
        setWaiverStubs(new File(line.getOptionValue('w')));
    }

    if (line.hasOption('s')) {
        setSigmaThreshold(Double.parseDouble(line.getOptionValue('s')));
    }

    if (line.hasOption('d')) {
        setDpmoThreshold(Integer.parseInt(line.getOptionValue('d')));
    }

    if (line.hasOption('S')) {
        setSeverityThreshold(Integer.parseInt(line.getOptionValue('S')));
    }

    if (line.hasOption('f')) {
        setForce(true);
    }

    if (line.hasOption('k')) {
        setForceOnWarnings(false);
    }

    if (line.hasOption('D')) {
        setDatabase(new File(line.getOptionValue('D')));
    }

    values = line.getOptionValues('i');
    for (int i = 0; values != null && i < values.length; i++) {
        createInspectors().setFile(new File(values[i]));
    }

    values = line.getOptionValues('u');
    for (int i = 0; values != null && i < values.length; i++) {
        createInspectors().setURL(values[i]);
    }

    values = line.getOptionValues('l');
    for (int i = 0; values != null && i < values.length; i++) {
        ListenerEntry listenerEntry = new ListenerEntry();
        listenerEntry.setClassName(values[i]);
        addConfiguredListener(listenerEntry);
    }

    values = line.getOptionValues('W');
    for (int i = 0; values != null && i < values.length; i++) {
        createWaivers().setFile(new File(values[i]));
    }

    values = line.getOptionValues('U');
    for (int i = 0; values != null && i < values.length; i++) {
        createWaivers().setURL(values[i]);
    }

    if (line.hasOption('A')) {
        setArchive(new File(line.getOptionValue('A')));
    }

    //Anu 20050701 : baselining
    if (line.hasOption('B')) {
        setBaselining(line.getOptionValue('B'));
    }
}

From source file:org.openconcerto.sql.PropsConfiguration.java

public void setupLogging(final String dirName, final boolean redirectToFile) {
    final File logDir;
    synchronized (this.restLock) {
        if (this.logDir != null)
            throw new IllegalStateException("Already set to " + this.logDir);
        logDir = getValidLogDir(dirName);
        this.logDir = logDir;
    }// w  ww  .j a va  2 s  .c o m
    final String logNameBase = this.getAppName() + "_" + getLogDateFormat().format(new Date());

    // must be done before setUpConsoleHandler(), otherwise log output not redirected
    if (redirectToFile) {
        final File logFile = new File(logDir, (logNameBase + ".txt"));
        try {
            FileUtils.mkdir_p(logFile.getParentFile());
            System.out.println("Log file: " + logFile.getAbsolutePath());
            final OutputStream fileOut = new FileOutputStream(logFile, true);
            final OutputStream out, err;
            System.out.println("Java System console:" + System.console());
            boolean launchedFromEclipse = new File(".classpath").exists();
            if (launchedFromEclipse) {
                System.out.println("Launched from eclipse");
            }
            if ((System.console() != null || launchedFromEclipse)
                    && this.keepStandardStreamsWhenRedirectingToFile()) {
                System.out.println("Redirecting standard output to file and console");
                out = new MultipleOutputStream(fileOut, new FileOutputStream(FileDescriptor.out));
                System.out.println("Redirecting error output to file and console");
                err = new MultipleOutputStream(fileOut, new FileOutputStream(FileDescriptor.err));

            } else {
                out = fileOut;
                err = fileOut;
            }
            System.setErr(new PrintStream(new BufferedOutputStream(err, 128), true));
            System.setOut(new PrintStream(new BufferedOutputStream(out, 128), true));
            // Takes about 350ms so run it async
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        FileUtils.ln(logFile, new File(logDir, "last.log"));
                    } catch (final IOException e) {
                        // the link is not important
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (final Exception e) {
            ExceptionHandler.handle("Redirection des sorties standards impossible", e);
        }
    } else {
        System.out.println("Standard streams not redirected to file");
    }

    // removes default
    LogUtils.rmRootHandlers();
    // add console handler
    LogUtils.setUpConsoleHandler();
    // add file handler (supports concurrent launches, doesn't depend on date)
    try {
        final File logFile = new File(logDir, this.getAppName() + "-%u-age%g.log");
        FileUtils.mkdir_p(logFile.getParentFile());
        System.out.println("Logger logs: " + logFile.getAbsolutePath());
        // 2 files of at most 5M, each new launch append
        // if multiple concurrent launches %u is used
        final FileHandler fh = new FileHandler(logFile.getPath(), 5 * 1024 * 1024, 2, true);
        fh.setFormatter(new SimpleFormatter());
        Logger.getLogger("").addHandler(fh);
    } catch (final Exception e) {
        ExceptionHandler.handle("Enregistrement du Logger dsactiv", e);
    }

    this.setLoggersLevel();
}