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:uk.ac.ed.inf.ace.Ace.java

/**
 * @param args the command line arguments
 */// www.j  ava  2 s.c o  m
public static void main(String[] args) {
    try {
        OutStream outStream = new OutStream(System.out);
        System.setOut(outStream);
        System.setErr(outStream);
        LOGGER.info("Starting");
        CommandLine commandLine = getCommandLine(args);
        Engine<?, ?> engine = null;

        try {
            // Load the configuration
            engine = Config.load(commandLine.getOptionValue(CONFIG_PATH_OPTION),
                    commandLine.getOptionValue(ENVIRONMENT_NAME_OPTION),
                    commandLine.getOptionValue(EXTENSION_SCHEMA_PATH_OPTION),
                    commandLine.getOptionValue(EXTENSION_CONTEXT_PATH_OPTION));

            // Set up the output directory
            File file = engine.getEnvironment().getOutputDirectory();

            if (commandLine.hasOption(PURGE_OUTPUT_OPTION)) {
                File resultsFile = engine.getEnvironment().getResultsFile();

                synchronized (resultsFile) {
                    while (resultsFile.exists()) {
                        resultsFile.delete();
                    }
                }

                if (!commandLine.hasOption(ANALYSIS_ONLY_OPTION)) {
                    while (file.exists()) {
                        FileUtils.deleteQuietly(file);
                    }
                }
            }

            while (!file.exists()) {
                file.mkdirs();
            }

            // Start the engine (it runs on its own thread)
            engine.start(commandLine.hasOption(REBUILD_DATABASE_OPTION),
                    commandLine.hasOption(GENERATE_TEST_DATA_OPTION),
                    commandLine.hasOption(DATABASE_QUERY_MODE_OPTION),
                    commandLine.hasOption(ANALYSIS_ONLY_OPTION));

            // Set up a basic REPL
            try (InputStreamReader inputStreamReader = new InputStreamReader(System.in)) {
                try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {

                    CommandInterface commandInterface = new CommandInterface(engine);
                    outStream.printPrompt("> ");
                    String command;

                    while ((command = bufferedReader.readLine()) != null) {
                        if (commandInterface.execute(command)) {
                            break;
                        }
                    }
                }
            }

            LOGGER.info("Quitting");
        } finally {
            if (engine != null) {
                engine.stop();
            }
        }
    } catch (Exception exception) {
        LOGGER.log(Level.SEVERE, "System thread failed", exception);
    }
}

From source file:Redirect.java

public static void main(String[] argv) throws IOException {
    //+//from  w w  w .  j ava  2s.c  o m
    String LOGFILENAME = "error.log";
    System.setErr(new PrintStream(new FileOutputStream(LOGFILENAME)));
    System.out.println("Please look for errors in " + LOGFILENAME);
    // Now assume this is somebody else's code; you'll see it writing to
    // stderr...
    int[] a = new int[5];
    a[10] = 0; // here comes an ArrayIndexOutOfBoundsException
    //-
}

From source file:com.muni.fi.pa165.survive.rest.client.SurviveRESTClient.java

public static void main(String[] args) {

    File file = new File("err.txt");
    FileOutputStream fos = null;//from  w  w  w.  j  a v a  2 s .  c  om
    try {
        fos = new FileOutputStream(file);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(SurviveRESTClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    PrintStream ps = new PrintStream(fos);
    System.setErr(ps);

    CommandLineParser parser = new PosixParser();
    Options options = OptionsProvider.getInstance().getOptions();

    try {
        CommandLine line = parser.parse(options, args);
        List<String> validate = CommandLineValidator.validate(line);
        if (!validate.isEmpty()) {
            System.out.println("The following errors occured when parsing the command:");

            for (String string : validate) {
                System.out.println(string);
            }

            System.out.println("");
            printHelp(options);
            System.exit(1);
        }

        if (line.hasOption("h")) {
            printHelp(options);
            System.exit(0);
        }

        CustomRestService crudService;

        String operation = line.getOptionValue("o");

        // weapon mode
        if (line.hasOption("w")) {
            crudService = new WeaponServiceImpl();
            switch (operation) {
            case "C": {
                WeaponDto dto = DtoBuilder.getWeaponDto(line);
                Object byId = crudService.create(dto);
                printEntity(crudService.getResponse(), "Creating a weapon", byId);
                break;
            }
            case "R": {
                Long id = Long.parseLong(line.getOptionValue("i"));
                Object byId = crudService.getById(id);
                printEntity(crudService.getResponse(), "Reading a weapon with id " + id, byId);
                break;
            }
            case "U": {

                WeaponDto dto = DtoBuilder.getWeaponDto(line);
                Object byId = crudService.update(dto);
                printEntity(crudService.getResponse(), "Updating a weapon with id " + line.getOptionValue("i"),
                        byId);

                break;
            }
            case "D": {
                Long id = Long.parseLong(line.getOptionValue("i"));
                Response delete = crudService.delete(id);
                printEntity(crudService.getResponse(), "Deleting a weapon with id " + line.getOptionValue("i"),
                        crudService.getResponse().getStatusInfo());
                break;
            }
            case "A":
                List<AbstractDto> all = crudService.getAll();
                printEntities(crudService.getResponse(), "Reading all weapons", all);

                break;
            }
        } else if (line.hasOption("a")) {
            crudService = new AreaServiceImpl();
            switch (operation) {
            case "C": {
                AreaDto dto = DtoBuilder.getAreaDto(line);
                Object byId = crudService.create(dto);
                printEntity(crudService.getResponse(), "Creating an area", byId);
                break;
            }
            case "R": {
                Long id = Long.parseLong(line.getOptionValue("i"));
                Object byId = crudService.getById(id);
                printEntity(crudService.getResponse(), "Reading an area with id " + id, byId);
                break;
            }
            case "U": {
                AreaDto dto = DtoBuilder.getAreaDto(line);
                Object byId = crudService.update(dto);
                printEntity(crudService.getResponse(), "Updating an area with id " + line.getOptionValue("i"),
                        byId);
                break;
            }
            case "D": {
                Long id = Long.parseLong(line.getOptionValue("i"));
                Object byId = crudService.delete(id);
                printEntity(crudService.getResponse(), "Deleting an area with id " + line.getOptionValue("i"),
                        crudService.getResponse().getStatusInfo());
                break;
            }
            case "A":
                List<AbstractDto> all = crudService.getAll();
                printEntities(crudService.getResponse(), "Reading all areas", all);
                break;
            }
        } else {
            printHelp(options);
        }
    } catch (ParseException ex) {
        System.out.println(ex.getMessage());
        printHelp(options);
        System.exit(1);
    } catch (NumberFormatException ex) {
        System.out.println(ex.getMessage());
        printHelp(options);
        System.exit(2);
    } catch (MessageBodyProviderNotFoundException ex) {
        System.out.println("Couldn't connect to the server! Please make sure that the server side is running.");
        System.exit(3);
    } catch (ProcessingException ex) {
        System.out.println("Couldn't connect to the server! Please make sure that the server side is running.");
        System.exit(4);
    } catch (Exception ex) {
        System.out.println(
                "There was an error when connecting to the server. Please make sure that the server side is running.");
    }
}

From source file:org.superfuntime.chatty.Core.java

public static void main(String[] args) {
    botsDirecotry.mkdir();/* w w  w.  j  av a 2  s  .  c o m*/
    pluginsDirecotry.mkdir();
    logger.info("Setting up");
    EventManager.addListener(new ChatListener());
    System.setOut(new PrintStream(new LoggingStream(LogManager.getLogger("STDOUT"), Level.INFO)));
    System.setErr(new PrintStream(new LoggingStream(LogManager.getLogger("STDERR"), Level.ERROR)));
    loadBots();
    startBots();
    if (BOTS.size() == 0) {
        logger.error("No bots started! Stopping...");
        return;
    }
    startPlugins();
    logger.info("Setup finished");
}

From source file:utils.execution.runningExtractors.RunExtractor.java

/**
 * @param args/*www.  ja  va  2 s  .  c om*/
 * @throws IOException 
 * @throws ServiceException 
 * @throws ParserException 
 */
public static void main(String[] args) throws IOException, ParserException, ServiceException {

    for (int hh = 0; hh < 1000; hh++) {

        System.gc();

        System.setErr(new PrintStream(new File(
                "/proj/db-files2/NoBackup/pjbarrio/Experiments/Bootstrapping/tfidf/extraction" + hh + ".err")));

        Set<URL> processed = new HashSet<URL>();

        paramsXML = FileUtils.readFileToString(
                new File("/proj/dbNoBackup/pjbarrio/workspace/SampleGeneration/data/calaisParams.xml"));

        String type = "smalltraining";

        String technique = "TEDW";

        String extractionType = "total";

        List<String> ids = FileUtils
                .readLines(new File("/proj/dbNoBackup/pjbarrio/Experiments/Wrappers/" + type));

        File folder = new File(
                "/proj/db-files2/NoBackup/pjbarrio/Experiments/Bootstrapping/tfidf/SizeOrderedResults/" + type
                        + "/" + technique + "/" + extractionType + "/");

        File outputFolder = new File(
                "/proj/db-files2/NoBackup/pjbarrio/Experiments/Bootstrapping/tfidf/SizeOrderedExtractions/"
                        + type + "/" + technique + "/" + extractionType + "/");

        File databaseIndex = new File(
                "/local/pjbarrio/Files/Projects/AutomaticQueryGeneration/Forms/FinalSelection/FinalInteractionIndex.txt");

        Map<Integer, String> table = DatabaseIndexHandler.loadInvertedDatabaseIndex(databaseIndex);

        Map<Integer, URL> urlTable = new HashMap<Integer, URL>();

        for (String string : ids) {

            int id = Integer.valueOf(string);

            urlTable.put(id, new URL(table.get(id)));

        }

        table.clear();

        File[] bySizeFolder = folder.listFiles();

        for (int i = 0; i < bySizeFolder.length; i++) {

            File bySize = bySizeFolder[i];

            System.out.println("Size: " + bySize.getName());

            File[] toExtract = bySize.listFiles();

            File outPref = new File(outputFolder, bySize.getName());

            outPref.mkdir();

            for (int j = 0; j < toExtract.length; j++) {

                System.out.println("Extract: " + toExtract[j].getName());

                File toSavePrefix = new File(outPref, FilenameUtils.getBaseName(toExtract[j].getName()) + "/");

                toSavePrefix.mkdir();

                extract(processed,
                        urlTable.get(Integer.valueOf(FilenameUtils.getBaseName(toExtract[j].getName()))),
                        toExtract[j], toSavePrefix);

            }

        }

    }

}

From source file:TeePrintStream.java

/** A simple test case. */
public static void main(String[] args) throws IOException {
    TeePrintStream ts = new TeePrintStream(System.err, "err.log", true);
    System.setErr(ts);
    System.err.println("An imitation error message");
    ts.close();//from  ww w. j  ava 2  s . com
}

From source file:it.cnr.isti.labse.glimpse.MainMonitoring.java

/**
 * Read the properties and init the connections to the enterprise service bus
 * /*w  w  w .  j av a2  s .com*/
 * @param is the systemSettings file
 */
public static void main(String[] args) {
    try {
        FileOutputStream fos = new FileOutputStream("glimpseLog.log");
        PrintStream ps = new PrintStream(fos);
        System.setErr(ps);

        if (MainMonitoring.initProps(args[0]) && MainMonitoring.init()) {

            SplashScreen.Show();
            System.out.println("Please wait until setup is done...");
            //the buffer where the events are stored to be analyzed
            EventsBuffer<GlimpseBaseEvent<?>> buffer = new EventsBufferImpl<GlimpseBaseEvent<?>>();

            //The complex event engine that will be used (in this case drools)
            ComplexEventProcessor engine = new ComplexEventProcessorImpl(Manager.Read(MANAGERPARAMETERFILE),
                    buffer, connFact, initConn);
            engine.start();

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //the manager of all the architecture
            GlimpseManager manager = new GlimpseManager(Manager.Read(MANAGERPARAMETERFILE), connFact, initConn,
                    engine.getRuleManager());
            manager.start();
        }
    } catch (Exception e) {
        System.out.println("USAGE: java -jar MainMonitoring.jar \"systemSettings\"");
    }
}

From source file:com.denimgroup.threadfix.importer.cli.CommandLineMigration.java

public static void main(String[] args) {

    if (!check(args))
        return;/*from  www.j  av a 2s.co  m*/

    try {
        String inputScript = args[0];
        String inputMySqlConfig = args[1];
        String outputScript = "import.sql";
        String outputMySqlConfigTemp = "jdbc_temp.properties";
        String errorLogFile = "error.log";
        String fixedSqlFile = "error_sql.sql";
        String errorLogAttemp1 = "error1.log";
        String infoLogFile = "info.log";
        String rollbackScript = "rollback.sql";

        deleteFile(outputScript);
        deleteFile(errorLogFile);
        deleteFile(errorLogFile);
        deleteFile(fixedSqlFile);
        deleteFile(errorLogAttemp1);
        deleteFile(infoLogFile);
        deleteFile(rollbackScript);

        PrintStream infoPrintStream = new PrintStream(new FileOutputStream(new File(infoLogFile)));
        System.setOut(infoPrintStream);

        long startTime = System.currentTimeMillis();

        copyFile(inputMySqlConfig, outputMySqlConfigTemp);

        LOGGER.info("Creating threadfix table in mySql database ...");
        ScriptRunner scriptRunner = SpringConfiguration.getContext().getBean(ScriptRunner.class);

        startTime = printTimeConsumed(startTime);
        convert(inputScript, outputScript);

        startTime = printTimeConsumed(startTime);

        PrintStream errPrintStream = new PrintStream(new FileOutputStream(new File(errorLogFile)));
        System.setErr(errPrintStream);

        LOGGER.info("Sending sql script to MySQL server ...");
        scriptRunner.run(outputScript, outputMySqlConfigTemp);

        long errorCount = scriptRunner.checkRunningAndFixStatements(errorLogFile, fixedSqlFile);
        long lastCount = errorCount + 1;
        int times = 1;
        int sameFixedSet = 0;

        // Repeat
        while (errorCount > 0) {
            //Flush error log screen to other file
            errPrintStream = new PrintStream(new FileOutputStream(new File(errorLogAttemp1)));
            System.setErr(errPrintStream);

            times += 1;

            if (errorCount == lastCount) {
                sameFixedSet++;
            } else {
                sameFixedSet = 0;
            }

            LOGGER.info("Found " + errorCount + " error statements. Sending fixed sql script to MySQL server "
                    + times + " times ...");
            scriptRunner.run(fixedSqlFile, outputMySqlConfigTemp);
            lastCount = errorCount;
            errorCount = scriptRunner.checkRunningAndFixStatements(errorLogAttemp1, fixedSqlFile);

            if (errorCount > lastCount || sameFixedSet > SAME_SET_TRY_LIMIT)
                break;
        }

        if (errorCount > 0) {
            LOGGER.error("After " + times + " of trying, still found errors in sql script. "
                    + "Please check error_sql.sql and error1.log for more details.");
            LOGGER.info("Do you want to keep data in MySQL, and then import manually error statements (y/n)? ");
            try (java.util.Scanner in = new java.util.Scanner(System.in)) {
                String answer = in.nextLine();
                if (!answer.equalsIgnoreCase("y")) {
                    rollbackData(scriptRunner, outputMySqlConfigTemp, rollbackScript);
                } else {
                    LOGGER.info(
                            "Data imported to MySQL, but still have some errors. Please check error_sql.sql and error1.log to import manually.");
                }

            }

        } else {
            printTimeConsumed(startTime);
            LOGGER.info("Migration successfully finished");
        }

        deleteFile(outputMySqlConfigTemp);

    } catch (Exception e) {
        LOGGER.error("Error: ", e);
    }
}

From source file:edu.wpi.margrave.MCommunicator.java

public static void main(String[] args) {
    ArrayList<String> foo = new ArrayList<String>();

    Set<String> argsSet = new HashSet<String>();
    for (int ii = 0; ii < args.length; ii++) {
        argsSet.add(args[ii].toLowerCase());
    }//  w  ww .  j  a v a  2s  . co  m

    if (argsSet.contains("-log")) {
        // parser is in racket now. instead, require -log switch for logging
        //MEnvironment.debugParser = true;
        bDoLogging = true;
    }

    if (argsSet.contains("-min")) {
        bMinimalModels = true;
    }

    // Re-direct all System.err input to our custom buffer
    // Uses Apache Commons IO for WriterOutputStream.
    System.setErr(new PrintStream(new WriterOutputStream(MEnvironment.errorWriter), true));

    // Re-direct all System.out input to our custom buffer.
    // (We have already saved System.out.)
    // This is useful in case we start getting GC messages from SAT4j.
    System.setOut(new PrintStream(new WriterOutputStream(MEnvironment.outWriter), true));

    initializeLog();
    writeToLog("\n\n");

    // Inform the caller that we are ready to receive commands
    sendReadyReply();

    while (true) {
        // Block until a command is received, handle it, and then return the result.
        handleXMLCommand(in);
    }

    // outLog will be closed as it goes out of scope
}

From source file:it.cnr.isti.labsedc.glimpse.MainMonitoring.java

/**
 * Read the properties and init the connections to the enterprise service bus
 * /*from ww  w.  ja  v  a  2s.c o m*/
 * @param is the systemSettings file
 */
public static void main(String[] args) {
    try {
        FileOutputStream fos = new FileOutputStream("glimpseLog.log");
        PrintStream ps = new PrintStream(fos);
        System.setErr(ps);

        Logger log = Logger.getLogger(MainMonitoring.class.getName());

        log.debug("Hello this is an debug message");
        log.info("Hello this is an info message");

        if (MainMonitoring.initProps(args[0]) && MainMonitoring.init()) {

            SplashScreen.Show();
            System.out.println("Please wait until setup is done...");

            //the buffer where the events are stored to be analyzed, in this version
            //the buffer object is not used because Drools has it's own eventStream object
            EventsBuffer<GlimpseBaseEvent<?>> buffer = new EventsBufferImpl<GlimpseBaseEvent<?>>();

            //The complex event engine that will be used (in this case drools)
            ComplexEventProcessor engineOne = new ComplexEventProcessorImpl(Manager.Read(MANAGERPARAMETERFILE),
                    buffer, connFact, initConn);
            engineOne.start();

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            RuleTemplateManager templateManager = new RuleTemplateManager(DROOLSRULEREQUESTTEMPLATE1,
                    DROOLSRULEREQUESTTEMPLATE2, DROOLSRULEREQUESTTEMPLATE3_1, DROOLSRULEREQUESTTEMPLATE3_2);

            //the component in charge to locate services and load specific rules.
            ServiceLocatorFactory.getServiceLocatorParseViolationReceivedFromBSM(engineOne, templateManager,
                    REGEXPATTERNFILEPATH).start();

            //start MailNotifier component
            MailNotification mailer = new MailNotification(Manager.Read(MAILNOTIFICATIONSETTINGSFILEPATH));
            mailer.start();

            //the manager of all the architecture
            GlimpseManager manager = new GlimpseManager(Manager.Read(MANAGERPARAMETERFILE), connFact, initConn,
                    engineOne.getRuleManager());
            manager.start();
        }
    } catch (Exception e) {
        System.out.println("USAGE: java -jar MainMonitoring.jar \"systemSettings\"");
    }
}