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:de.peran.dependency.ChangedTestClassesHandler.java

private void updateDependenciesOnce(final String testClassName, final String testMethodName,
        final File parent) {
    LOG.debug("Parent: " + parent);
    final File[] listFiles = parent.listFiles(new FileFilter() {
        @Override/*from  ww  w  . j av a  2 s. c om*/
        public boolean accept(final File pathname) {
            return pathname.getName().matches("[0-9]*");
        }
    });
    LOG.debug("Kieker-Dateien: {}", listFiles.length);
    final File kiekerAllFolder = listFiles[0];
    LOG.debug("Analysiere Ordner: {} {}", kiekerAllFolder.getAbsolutePath(), testMethodName);
    final File kiekerNextFolder = new File(kiekerAllFolder, testMethodName);
    final File kiekerResultFolder = kiekerNextFolder.listFiles()[0];
    LOG.debug("Test: " + testMethodName);

    final PrintStream out = System.out;
    final PrintStream err = System.err;

    final File kiekerOutputFile = new File(projectFolder.getParent(), "ausgabe_kieker.txt");
    Map<String, Set<String>> calledClasses = null;
    try {
        System.setOut(new PrintStream(kiekerOutputFile));
        System.setErr(new PrintStream(kiekerOutputFile));
        calledClasses = new CalledMethodLoader(kiekerResultFolder).getCalledMethods();
        for (final Iterator<String> iterator = calledClasses.keySet().iterator(); iterator.hasNext();) {
            final String clazz = iterator.next();
            final String onlyClass = clazz.substring(clazz.lastIndexOf(".") + 1);
            final Collection<File> files = FileUtils.listFiles(projectFolder,
                    new WildcardFileFilter(onlyClass + "*"), TrueFileFilter.INSTANCE);
            if (files.size() == 0) {
                iterator.remove();
            }
        }
    } catch (final FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        System.setOut(out);
        System.setErr(err);
    }

    LOG.debug("Test: {} {}", testClassName, testMethodName);
    LOG.debug("Kieker: {} Dependencies: {}", kiekerResultFolder.getAbsolutePath(), calledClasses.size());
    final Map<String, Set<String>> dependencies = this.dependencies
            .getDependenciesForTest(testClassName + "." + testMethodName);
    dependencies.putAll(calledClasses);
}

From source file:org.languagetool.commandline.MainTest.java

@Before
public void setUp() throws Exception {
    super.setUp();
    this.stdout = System.out;
    this.stderr = System.err;
    this.out = new ByteArrayOutputStream();
    this.err = new ByteArrayOutputStream();
    System.setOut(new PrintStream(this.out));
    System.setErr(new PrintStream(this.err));
}

From source file:net.sourceforge.fullsync.cli.Main.java

public static void startup(String[] args, Launcher launcher) throws Exception {
    initOptions();//from  w w  w  . jav a  2 s.  c  om
    String configDir = getConfigDir();
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;

    try {
        line = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        printHelp();
        System.exit(1);
    }

    if (line.hasOption('V')) {
        System.out.println(String.format("FullSync version %s", Util.getFullSyncVersion())); //$NON-NLS-1$
        System.exit(0);
    }

    // Apply modifying options
    if (!line.hasOption("v")) { //$NON-NLS-1$
        System.setErr(new PrintStream(new FileOutputStream(getLogFileName())));
    }

    if (line.hasOption("h")) { //$NON-NLS-1$
        printHelp();
        System.exit(0);
    }

    upgradeLegacyPreferencesLocation(configDir);

    String profilesFile;
    if (line.hasOption("P")) { //$NON-NLS-1$
        profilesFile = line.getOptionValue("P"); //$NON-NLS-1$
    } else {
        profilesFile = configDir + FullSync.PROFILES_XML;
        upgradeLegacyProfilesXmlLocation(profilesFile);
    }
    final String prefrencesFile = configDir + FullSync.PREFERENCES_PROPERTIES;
    final Injector injector = Guice.createInjector(new FullSyncModule(line, prefrencesFile));
    final RuntimeConfiguration rtConfig = injector.getInstance(RuntimeConfiguration.class);
    injector.getInstance(ProfileManager.class).setProfilesFileName(profilesFile);
    final ScheduledExecutorService scheduledExecutorService = injector
            .getInstance(ScheduledExecutorService.class);
    final EventListener deadEventListener = new EventListener() {
        private final Logger logger = LoggerFactory.getLogger("DeadEventLogger"); //$NON-NLS-1$

        @Subscribe
        private void onDeadEvent(DeadEvent deadEvent) {
            if (!(deadEvent.getEvent() instanceof ShutdownEvent)) {
                logger.warn("Dead event triggered: {}", deadEvent); //$NON-NLS-1$
            }
        }
    };
    final EventBus eventBus = injector.getInstance(EventBus.class);
    eventBus.register(deadEventListener);

    final Semaphore sem = new Semaphore(0);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        Logger logger = LoggerFactory.getLogger(Main.class);
        logger.debug("shutdown hook called, starting orderly shutdown"); //$NON-NLS-1$
        eventBus.post(new ShutdownEvent());
        scheduledExecutorService.shutdown();
        try {
            scheduledExecutorService.awaitTermination(5, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            // not relevant
        }
        logger.debug("shutdown hook finished, releaseing main thread semaphore"); //$NON-NLS-1$
        sem.release();
    }));
    if (rtConfig.isDaemon().orElse(false).booleanValue() || rtConfig.getProfileToRun().isPresent()) {
        finishStartup(injector);
        sem.acquireUninterruptibly();
        System.exit(0);
    } else {
        launcher.launchGui(injector);
        System.exit(0);
    }
}

From source file:fr.inrialpes.exmo.align.service.AlignmentService.java

public void run(String[] args) throws Exception {
    services = new Vector<AlignmentServiceProfile>();
    directories = new Hashtable<String, Directory>();

    // Read parameters
    readParameters(args);//from   w ww  .jav a 2 s.com

    // In principle, this is useless
    if (outputfilename != null) {
        // This redirects error outout to log file given by -o
        System.setErr(new PrintStream(outputfilename));
    }

    logger.debug("Parameter parsed");

    // Shut down hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            close();
        }
    });

    // Connect database
    // It may be useful to create a switch to use a simple volatilCache: nodb
    // This requires simple but deeper changes
    // (do not put as default for compatibility)
    if (DBMS.equals("postgres")) {
        logger.debug("postgres driver");
        if (DBPORT == null)
            DBPORT = "5432";
        connection = new DBServiceImpl("org.postgresql.Driver", "jdbc:postgresql", DBPORT, OPTION);
    } else if (DBMS.equals("mysql")) {
        logger.debug("mysql driver");
        if (DBPORT == null)
            DBPORT = "3306";
        connection = new DBServiceImpl("com.mysql.jdbc.Driver", "jdbc:mysql", DBPORT, OPTION);
    } else {
        logger.error("Unsupported JDBC driver: {}", DBMS);
        usage();
        System.exit(-1);
    }
    try {
        logger.debug("Connecting to database");
        connection.init();
        connection.connect(DBHOST, DBPORT, DBUSER, DBPASS, DBBASE);
    } catch (Exception ex) {
        logger.error("Cannot connect to database : {}", ex.getMessage());
        System.exit(-1);
    }

    logger.debug("Database connected");

    // Create a AServProtocolManager
    manager = new AServProtocolManager(directories);
    manager.init(connection, parameters);
    logger.debug("Manager created");

    // Launch services
    for (AlignmentServiceProfile serv : services) {
        try {
            serv.init(parameters, manager);
        } catch (AServException ex) { // This should rather be the job of the caller
            logger.warn("Cannot start {} service on {}:{}", serv);
        }
    }
    logger.debug("Services launched");

    // Register to directories
    for (Directory dir : directories.values()) {
        try {
            dir.open(parameters);
            logger.debug("{} connected.", dir);
        } catch (AServException ex) {
            logger.warn("Cannot connect to {} directory", dir);
            logger.debug("IGNORED Connection exception", ex);
            // JE: this has to be done
            //directories.remove( name, dir );
        }
    }
    logger.debug("Directories registered");

    init(parameters);

    // Enables transports (here only HTTP)
    if (parameters.getProperty("http") != null) { // Possible to have http-less server
        try {
            transport = new HTTPTransport();
            transport.init(parameters, manager, services);
        } catch (AServException ex) {
            logger.error("Cannot start HTTP transport on {}:{}", parameters.getProperty("host"),
                    parameters.getProperty("http"));
            usage();
            System.exit(-1);
        }
        logger.debug("Transport enabled");
    }

    // Wait loop
    logger.info("Alignment server running");
    while (true) {
        // do not exhaust CPU
        Thread.sleep(1000);
    }
}

From source file:org.apache.hadoop.hbase.mapreduce.TestCellCounter.java

/**
 * Test main method of CellCounter//from w w w  .  j a  va2s .  c  o m
 */
@Test(timeout = 300000)
public void testCellCounterMain() throws Exception {

    PrintStream oldPrintStream = System.err;
    SecurityManager SECURITY_MANAGER = System.getSecurityManager();
    LauncherSecurityManager newSecurityManager = new LauncherSecurityManager();
    System.setSecurityManager(newSecurityManager);
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    String[] args = {};
    System.setErr(new PrintStream(data));
    try {
        System.setErr(new PrintStream(data));

        try {
            CellCounter.main(args);
            fail("should be SecurityException");
        } catch (SecurityException e) {
            assertEquals(-1, newSecurityManager.getExitCode());
            assertTrue(data.toString().contains("ERROR: Wrong number of parameters:"));
            // should be information about usage
            assertTrue(data.toString().contains("Usage:"));
        }

    } finally {
        System.setErr(oldPrintStream);
        System.setSecurityManager(SECURITY_MANAGER);
    }
}

From source file:org.jwebsocket.ui.TestDialog.java

public void initializeLogs() {
    PrintStream lPrintStream;//from   www  .  j  a  va 2 s  .co m
    OutputStreamConsole lConsole = new OutputStreamConsole(txaLog);
    lPrintStream = new PrintStream(lConsole);
    System.setOut(lPrintStream);
    System.setErr(lPrintStream);
}

From source file:org.languagetool.commandline.MainTest.java

@After
public void tearDown() throws Exception {
    System.setOut(this.stdout);
    System.setErr(this.stderr);
    super.tearDown();
}

From source file:org.jamocha.gui.JamochaGui.java

@Override
public void start(final Stage primaryStage) {
    this.primaryStage = primaryStage;

    this.jamocha = new Jamocha();

    final Scene scene = generateScene();

    if (file == null) {
        final FileChooser fileChooser = new FileChooser();
        final ExtensionFilter filter = new ExtensionFilter("CLIPS files", "*.clips");
        fileChooser.getExtensionFilters().add(filter);
        fileChooser.getExtensionFilters().add(new ExtensionFilter("All files", "*.*"));
        file = fileChooser.showOpenDialog(primaryStage);
    }//from   w ww .  j av  a 2 s . co  m

    primaryStage.setMinWidth(800);
    primaryStage.setMinHeight(600);
    primaryStage.setTitle("Jamocha");
    primaryStage.setScene(scene);
    loadState(primaryStage);
    primaryStage.show();
    try (final PrintStream out = new PrintStream(new LogOutputStream(this.log))) {
        System.setOut(out);
        System.setErr(out);

        if (file != null) {
            System.out.println("Opening file: \"" + file.getName() + "\"");
            loadFile(file);
        } else {
            System.out.println("No file selected!");
        }
    }
}

From source file:com.cybernostics.forks.jsp2x.Main.java

private boolean process(String inputFileName) {
    boolean success = false;
    try {//from   ww  w  . ja v a 2 s. com
        final File logFile = outputFile(inputFileName + ".log");
        final PrintStream logStream = new PrintStream(logFile);
        try {
            PrintStream stdout = System.out;
            PrintStream stderr = System.err;
            try {
                System.setOut(logStream);
                System.setErr(logStream);
                try {
                    new Jsp2JspX(inputFileName, outputFile(rewritePath(inputFileName)), this).convert();
                } catch (Throwable t) {
                    handleThrowable(t);
                }
            } finally {
                System.setErr(stderr);
                System.setOut(stdout);
            }
        } finally {
            logStream.close();
            if (logFile.length() == 0) {
                success = true;
                logFile.delete();
            }
        }
    } catch (Throwable t) {
        handleThrowable(t);
    }
    return success;
}

From source file:org.openmrs.module.webservices.docs.swagger.SwaggerSpecificationCreator.java

private void toggleLogs(boolean targetState) {
    if (Context.getAdministrationService()
            .getGlobalProperty(RestConstants.SWAGGER_QUIET_DOCS_GLOBAL_PROPERTY_NAME).equals("true")) {
        if (targetState == RestConstants.SWAGGER_LOGS_OFF) {
            // turn off the log4j loggers
            List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
            loggers.add(LogManager.getRootLogger());
            for (Logger logger : loggers) {
                originalLevels.put(logger.hashCode(), logger.getLevel());
                logger.setLevel(Level.OFF);
            }//from w w w  .  j a va  2  s . c  o  m

            // silence stderr and stdout
            originalErr = System.err;
            System.setErr(new PrintStream(new OutputStream() {

                public void write(int b) {
                    // noop
                }
            }));

            originalOut = System.out;
            System.setOut(new PrintStream(new OutputStream() {

                public void write(int b) {
                    // noop
                }
            }));
        } else if (targetState == RestConstants.SWAGGER_LOGS_ON) {
            List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
            loggers.add(LogManager.getRootLogger());
            for (Logger logger : loggers) {
                logger.setLevel(originalLevels.get(logger.hashCode()));
            }

            System.setErr(originalErr);
            System.setOut(originalOut);
        }
    }
}