Example usage for java.lang System setOut

List of usage examples for java.lang System setOut

Introduction

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

Prototype

public static void setOut(PrintStream out) 

Source Link

Document

Reassigns the "standard" output stream.

Usage

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:functionaltests.TagCommandsFunctTest.java

@Test
public void testListTaskStates() throws Exception {
    typeLine("taskstates(" + jobId.longValue() + ")");

    runCli();/*  w w w .j  a  va  2  s. com*/

    String out = this.capturedOutput.toString();
    System.setOut(stdOut);
    System.out.println("------------- testListTaskStates:");
    System.out.println(out);
    assertTrue(out.contains("T1#1"));
    assertTrue(out.contains("Print1#1"));
    assertTrue(out.contains("Print2#1"));
    assertTrue(out.contains("T2#1"));
    assertTrue(out.contains("T1#2"));
    assertTrue(out.contains("Print1#2"));
    assertTrue(out.contains("Print2#2"));
    assertTrue(out.contains("T2#2"));
}

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 w  w  .  j  ava 2 s .c o  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.cw.litenote.DrawerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    /////w  ww  .  j av a2  s . c om
    //        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
    //
    //          .detectDiskReads()
    //          .detectDiskWrites()
    //          .detectNetwork() 
    //          .penaltyLog()
    //          .build());
    //
    //           StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
    ////          .detectLeakedSqlLiteObjects() //??? unmark this line will cause strict mode error
    //          .penaltyLog() 
    //          .penaltyDeath()
    //          .build());        
    ///
    super.onCreate(savedInstanceState);

    mDrawerActivity = this;
    setContentView(R.layout.drawer_activity);

    // Release mode: no debug message
    if (Define.CODE_MODE == Define.RELEASE_MODE) {
        OutputStream nullDev = new OutputStream() {
            public void close() {
            }

            public void flush() {
            }

            public void write(byte[] b) {
            }

            public void write(byte[] b, int off, int len) {
            }

            public void write(int b) {
            }
        };
        System.setOut(new PrintStream(nullDev));
    }

    //Log.d below can be disabled by applying proguard
    //1. enable proguard-android-optimize.txt in project.properties
    //2. be sure to use newest version to avoid build error
    //3. add the following in proguard-project.txt
    /*-assumenosideeffects class android.util.Log {
    public static boolean isLoggable(java.lang.String, int);
    public static int v(...);
    public static int i(...);
    public static int w(...);
    public static int d(...);
    public static int e(...);
    }
    */
    Log.d("test log tag", "start app");

    System.out.println("================start application ==================");
    System.out.println("DrawerActivity / onCreate");

    UtilImage.getDefaultSacleInPercent(DrawerActivity.this);

    mAppTitle = getTitle();

    mDrawerChildTitles = new ArrayList<String>();

    Context context = getApplicationContext();

    if (mDb != null)
        mDb.close();

    mDb = new DB(context);
    mDb.initDrawerDb(mDb);

    if (mDb_tabs != null)
        mDb_tabs.close();

    mDb_tabs = new DB(context, Util.getPref_lastTimeView_tabs_tableId(this));
    mDb_tabs.initTabsDb(mDb_tabs);

    if (mDb_notes != null)
        mDb_tabs.close();

    mDb_notes = new DB(context, Util.getPref_lastTimeView_notes_tableId(this));
    mDb_notes.initNotesDb(mDb_notes);

    //Add note with the link
    String intentLink = addIntentLink(getIntent());
    if (!Util.isEmptyString(intentLink)) {
        finish(); // for no active DrawerActivity case
    } else {
        // check DB
        final boolean ENABLE_DB_CHECK = false;//true;//
        if (ENABLE_DB_CHECK) {
            // list all drawer tables
            int drawerCount = mDb.getDrawerChildCount();
            for (int drawerPos = 0; drawerPos < drawerCount; drawerPos++) {
                String drawerTitle = mDb.getDrawerChild_Title(drawerPos);
                DrawerActivity.mFocus_drawerChildPos = drawerPos;

                // list all tab tables
                int tabsTableId = mDb.getTabsTableId(drawerPos);
                System.out.println("--- tabs table Id = " + tabsTableId + ", drawer title = " + drawerTitle);
                mDb_tabs = new DB(context, tabsTableId);
                mDb_tabs.initTabsDb(mDb_tabs);
                int tabsCount = mDb_tabs.getTabsCount(true);
                for (int tabPos = 0; tabPos < tabsCount; tabPos++) {
                    TabsHostFragment.mCurrent_tabIndex = tabPos;
                    int tabId = mDb_tabs.getTabId(tabPos, true);
                    int notesTableId = mDb_tabs.getNotesTableId(tabPos, true);
                    String tabTitle = mDb_tabs.getTabTitle(tabPos, true);
                    System.out.println("   --- tab Id = " + tabId);
                    System.out.println("   --- notes table Id = " + notesTableId);
                    System.out.println("   --- tab title = " + tabTitle);

                    mLastOkTabId = tabId;

                    try {
                        mDb_notes = new DB(context, String.valueOf(notesTableId));
                        mDb_notes.initNotesDb(mDb_notes);
                        mDb_notes.doOpenNotes();
                        mDb_notes.doCloseNotes();
                    } catch (Exception e) {
                    }
                }
            }

            // recover focus
            int tabsTableId = Util.getPref_lastTimeView_tabs_tableId(this);
            DB.setFocus_tabsTableId(tabsTableId);
            String notesTableId = Util.getPref_lastTimeView_notes_tableId(this);
            DB.setFocus_notes_tableId(notesTableId);
        } //if(ENABLE_DB_CHECK)

        // get last time drawer number, default drawer number: 1
        if (savedInstanceState == null) {
            for (int i = 0; i < mDb.getDrawerChildCount(); i++) {
                if (mDb.getTabsTableId(i) == Util.getPref_lastTimeView_tabs_tableId(this)) {
                    mFocus_drawerChildPos = i;
                    System.out
                            .println("DrawerActivity / onCreate /  mFocusDrawerId = " + mFocus_drawerChildPos);
                }
            }
            AudioPlayer.mPlayerState = AudioPlayer.PLAYER_AT_STOP;
            UtilAudio.mIsCalledWhilePlayingAudio = false;
        }

        // set drawer title
        if (mDb.getDrawerChildCount() == 0) {
            for (int i = 0; i < Define.ORIGIN_TABS_TABLE_COUNT; i++) {
                String drawerTitle = Define.getDrawerTitle(mDrawerActivity, i);
                mDrawerChildTitles.add(drawerTitle);
                mDb.insertDrawerChild(i + 1, drawerTitle);
            }
        } else {
            for (int i = 0; i < mDb.getDrawerChildCount(); i++) {
                mDrawerChildTitles.add(""); // init only
                mDrawerChildTitles.set(i, mDb.getDrawerChild_Title(i));
            }
        }

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerListView = (DragSortListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        // set adapter
        mDb.doOpenDrawer();
        Cursor cursor = DB.mCursor_drawerChild;

        String[] from = new String[] { DB.KEY_DRAWER_TITLE };
        int[] to = new int[] { R.id.drawerText };

        drawerAdapter = new DrawerAdapter(this, R.layout.drawer_list_item, cursor, from, to, 0);

        mDb.doCloseDrawer();

        mDrawerListView.setAdapter(drawerAdapter);

        // set up click listener
        MainUi.addDrawerItemListeners();//??? move to resume?
        mDrawerListView.setOnItemClickListener(MainUi.itemClick);
        // set up long click listener
        mDrawerListView.setOnItemLongClickListener(MainUi.itemLongClick);

        mController = DrawerListview.buildController(mDrawerListView);
        mDrawerListView.setFloatViewManager(mController);
        mDrawerListView.setOnTouchListener(mController);

        // init drawer dragger
        mPref_show_note_attribute = getSharedPreferences("show_note_attribute", 0);
        if (mPref_show_note_attribute.getString("KEY_ENABLE_DRAWER_DRAGGABLE", "no").equalsIgnoreCase("yes"))
            mDrawerListView.setDragEnabled(true);
        else
            mDrawerListView.setDragEnabled(false);

        mDrawerListView.setDragListener(DrawerListview.onDrag);
        mDrawerListView.setDropListener(DrawerListview.onDrop);

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
        //         getActionBar().setBackgroundDrawable(new ColorDrawable(ColorSet.bar_color));
        getActionBar().setBackgroundDrawable(new ColorDrawable(ColorSet.getBarColor(mDrawerActivity)));

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
                mDrawerLayout, /* DrawerLayout object */
                R.drawable.ic_drawer, /* navigation drawer image to replace 'Up' caret */
                R.string.drawer_open, /* "open drawer" description for accessibility */
                R.string.drawer_close /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed(View view) {
                System.out.println("mDrawerToggle onDrawerClosed ");
                int pos = mDrawerListView.getCheckedItemPosition();
                int tblId = mDb.getTabsTableId(pos);
                DB.setSelected_tabsTableId(tblId);
                mDrawerChildTitle = mDb.getDrawerChild_Title(pos);
                setTitle(mDrawerChildTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()

                // add for deleting drawer
                if (TabsHostFragment.mTabHost == null) {
                    MainUi.selectDrawerChild(mFocus_drawerChildPos);
                    setTitle(mDrawerChildTitle);
                }
            }

            public void onDrawerOpened(View drawerView) {
                System.out.println("mDrawerToggle onDrawerOpened ");
                setTitle(mAppTitle);
                drawerAdapter.notifyDataSetChanged();
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        mContext = getBaseContext();
        bEnableConfig = false;

        // add on back stack changed listener
        fragmentManager = getSupportFragmentManager();
        mOnBackStackChangedListener = DrawerActivity.this;
        fragmentManager.addOnBackStackChangedListener(mOnBackStackChangedListener);

        // register an audio stream receiver
        if (noisyAudioStreamReceiver == null) {
            noisyAudioStreamReceiver = new NoisyAudioStreamReceiver();
            intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
            registerReceiver(noisyAudioStreamReceiver, intentFilter);
        }

    }

    // Show license dialog
    new EULA_dlg(this).show();
}

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

private boolean process(String inputFileName) {
    boolean success = false;
    try {//from  w  w w  . j  ava2 s  .c  om
        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:ddf.catalog.pubsub.command.ListCommandTest.java

/**
 * Test subscriptions:list command with one subscription ID argument not matching any registered
 * subscriptions. Should return no subscriptions.
 *
 * @throws Exception/*from   w ww  . j a v  a2s . c  o  m*/
 */
@Test
public void testListOneNonMatchingSubscriptionIdArg() throws Exception {
    // Setup argument captor for LDAP filter that will be passed in to getServiceReferences()
    // call
    ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);

    ListCommand listCommand = new ListCommand();

    BundleContext bundleContext = mock(BundleContext.class);
    listCommand.setBundleContext(bundleContext);

    when(bundleContext.getServiceReferences(eq(SubscriptionsCommand.SERVICE_PID), anyString()))
            .thenReturn(new ServiceReference[] {});

    PrintStream realSystemOut = System.out;

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    System.setOut(new PrintStream(buffer));

    // when
    listCommand.id = MY_SUBSCRIPTION_ID;
    listCommand.doExecute();

    /* cleanup */
    System.setOut(realSystemOut);

    // then
    assertThat(buffer.toString(), startsWith(ListCommand.RED_CONSOLE_COLOR
            + ListCommand.NO_SUBSCRIPTIONS_FOUND_MSG + ListCommand.DEFAULT_CONSOLE_COLOR));

    buffer.close();

    // Verify the LDAP filter passed in when mock BundleContext.getServiceReferences() was
    // called.
    verify(bundleContext).getServiceReferences(anyString(), argument.capture());
    String expectedLdapFilter = "(" + SUBSCRIPTION_ID_PROPERTY_KEY + "=" + MY_SUBSCRIPTION_ID + ")";
    assertThat(argument.getValue(), containsString(expectedLdapFilter));
}

From source file:dk.netarkivet.archive.bitarchive.distribute.BitarchiveServer.java

/**
 * The server creates an instance of the bitarchive it provides access to
 * and starts to listen to JMS messages on the incomming jms queue
 * <p/>/*from  ww w.j a  v a2 s .c o  m*/
 * Also, heartbeats are sent out at regular intervals to the Bitarchive
 * Monitor, to tell that this bitarchive is alive.
 *
 * @throws UnknownID        - if there was no heartbeat frequency or temp
 *                            dir defined in settings or if the
 *                            bitarchiveid cannot be created.
 * @throws PermissionDenied - if the temporary directory or the file
 *                            directory cannot be written
 */
private BitarchiveServer() throws UnknownID, PermissionDenied {
    System.setOut(
            new PrintStream(new LoggingOutputStream(LoggingOutputStream.LoggingLevel.INFO, log, "StdOut: ")));
    System.setErr(
            new PrintStream(new LoggingOutputStream(LoggingOutputStream.LoggingLevel.WARN, log, "StdErr: ")));
    boolean listening = false; // are we listening to queue ANY_BA
    File serverdir = FileUtils.getTempDir();
    if (!serverdir.exists()) {
        serverdir.mkdirs();
    }
    if (!serverdir.canWrite()) {
        throw new PermissionDenied("Not allowed to write to temp directory '" + serverdir + "'");
    }
    log.info("Storing temporary files at '" + serverdir.getPath() + "'");

    bitarchiveAppId = createBitarchiveAppId();

    allBa = Channels.getAllBa();
    anyBa = Channels.getAnyBa();
    baMon = Channels.getTheBamon();
    ba = Bitarchive.getInstance();
    con = JMSConnectionFactory.getInstance();
    con.setListener(allBa, this);
    baa = BitarchiveAdmin.getInstance();
    if (baa.hasEnoughSpace()) {
        con.setListener(anyBa, this);
        listening = true;
    } else {
        log.warn("Not enough space to guarantee store -- not listening " + "to " + anyBa.getName());
    }

    // create map for batchjobs
    batchProcesses = Collections.synchronizedMap(new HashMap<String, Thread>());

    // Create and start the heartbeat sender
    Timer timer = new Timer(true);
    heartBeatSender = new HeartBeatSender(baMon, this);
    long frequency = Settings.getLong(ArchiveSettings.BITARCHIVE_HEARTBEAT_FREQUENCY);
    timer.scheduleAtFixedRate(heartBeatSender, 0, frequency);
    log.info("Heartbeat frequency: '" + frequency + "'");
    // Next logentry depends on whether we are listening to ANY_BA or not
    String logmsg = "Created bitarchive server listening on: " + allBa.getName();
    if (listening) {
        logmsg += " and " + anyBa.getName();
    }

    log.info(logmsg);

    log.info("Broadcasting heartbeats on: " + baMon.getName());
}

From source file:org.lnicholls.galleon.util.Tools.java

public static void redirectStandardStreams() {
    // Determine the path to the log dir
    String logDir = "";
    if (System.getProperty("logfile") == null) {
        File file = new File(".");
        logDir = file.getAbsolutePath() + "/../logs";
    } else {//www  .j  a  v a  2s.  c  o  m
        File logFile = new File(System.getProperty("logfile"));
        File dir = new File(logFile.getPath().substring(0, logFile.getPath().lastIndexOf(File.separator)));
        logDir = dir.getAbsolutePath();
    }

    // Create a new output stream for the standard output.
    PrintStream stdout = null;
    try {
        stdout = new PrintStream(new FileOutputStream(logDir + "/Redirect.out"));
        System.setOut(stdout);
    } catch (Exception e) {
        log.error(e.toString());
    }

    // Create new output stream for the standard error output.
    PrintStream stderr = null;
    try {
        stderr = new PrintStream(new FileOutputStream(logDir + "/Redirect.err"));
        System.setErr(stderr);
    } catch (Exception e) {
        log.error(e.toString());
    }
}

From source file:edu.upenn.ircs.lignos.morsel.MorphLearner.java

/**
 * Create a new learner using the given paths for I/O.
 * @param corpusPath the path of the input corpus
 * @param outPath the path for the analysis output
 * @param logPath the path for the log/*from   www  .j  a v  a 2s  .  com*/
 * @param paramPath the path of the parameter file
 * @param encoding the encoding of the input corpus file
 * @param outputBaseInf Whether to output the examples of base inference
 * @param outputConflation Whether to output conflation sets
 * @param outputCompounds Whether to output an analysis before compounding
 * @throws FileNotFoundException if the corpus or parameter files do not exist.
 * @throws UnsupportedEncodingException if the corpus's encoding is not readable.
 */
public MorphLearner(String corpusPath, String outPath, String logPath, String paramPath, String encoding,
        boolean outputBaseInf, boolean outputConflation, boolean outputCompounds)
        throws FileNotFoundException, UnsupportedEncodingException {
    this.corpusPath = corpusPath;
    this.outputBaseInf = outputBaseInf;
    this.outputConflation = outputConflation;
    this.outputCompounds = outputCompounds;
    try {
        this.output = new PrintWriter(
                new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(outPath)), encoding));
    } catch (FileNotFoundException e) {
        throw new FileNotFoundException("Cannot open output file: " + outPath);
    }

    // If log is "-", don't redirect
    if (!"-".equals(logPath)) {
        this.log = new PrintStream(new BufferedOutputStream(new FileOutputStream(logPath)), true, encoding);
        // Redirect output to log
        System.setOut(new PrintStream(logPath));
    }

    System.out.println("Setting parameters from " + paramPath);
    this.setParams(paramPath);

    System.out.println("Loading corpus from " + corpusPath);
    loadCorpus(encoding);

    // Shorten the analysis path down to a base for use in 
    analysisBase = outPath.contains(".") ? outPath.substring(0, outPath.lastIndexOf('.')) : outPath;
}

From source file:com.izforge.izpack.event.AntAction.java

/**
 * Performs all defined actions./*from www . j a v  a  2  s .  com*/
 *
 * @param uninstall An install/uninstall switch. If this is <tt>true</tt> only the uninstall
 *                  actions, otherwise only the install actions are being performed.
 * @throws IzPackException for any error
 * @see #performInstallAction() for calling all install actions.
 * @see #performUninstallAction() for calling all uninstall actions.
 */
public void performAction(boolean uninstall) throws IzPackException {
    if (verbose) {
        System.out.print("Calling ANT with buildfile: " + buildFile);
        System.out.print(buildDir != null ? " in directory " + buildDir : " in default base directory");
        System.out.println();
    }
    SecurityManager oldsm = null;
    if (!JavaEnvUtils.isJavaVersion("1.0") && !JavaEnvUtils.isJavaVersion("1.1")) {
        oldsm = System.getSecurityManager();
    }
    PrintStream err = System.err;
    PrintStream out = System.out;
    Project antProj = new Project();
    try {
        antProj.setInputHandler(new AntActionInputHandler());
        antProj.setName("antcallproject");
        if (verbose) {
            logLevel = AntLogLevel.VERBOSE;
        } else if (quiet) {
            logLevel = AntLogLevel.WARNING;
        }
        final int antLogLevel = logLevel.getLevel();
        antProj.addBuildListener(new AntSystemLogBuildListener(antLogLevel));
        if (logFile != null) {
            antProj.addBuildListener(new AntActionLogBuildListener(logFile, logFileAppend, antLogLevel));
        }
        antProj.setSystemProperties();
        addProperties(antProj, getProperties());
        addPropertiesFromPropertyFiles(antProj);
        // TODO: propertyfiles, logFile
        antProj.fireBuildStarted();
        antProj.init();
        List<Ant> antcalls = new ArrayList<Ant>();
        List<String> choosenTargets = (uninstall) ? uninstallTargets : targets;
        if (choosenTargets.size() > 0) {
            Ant antcall;
            for (String choosenTarget : choosenTargets) {
                antcall = (Ant) antProj.createTask("ant");
                if (buildDir != null) {
                    antcall.setDir(buildDir);
                }
                antcall.setAntfile(buildFile.getAbsolutePath());
                antcall.setTarget(choosenTarget);
                antcalls.add(antcall);
            }
        }
        Target target = new Target();
        target.setName("calltarget");

        for (Ant antcall : antcalls) {
            target.addTask(antcall);
        }
        antProj.addTarget(target);
        System.setOut(new PrintStream(new DemuxOutputStream(antProj, false)));
        System.setErr(new PrintStream(new DemuxOutputStream(antProj, true)));
        antProj.executeTarget("calltarget");
        antProj.fireBuildFinished(null);
    } catch (BuildException exception) {
        antProj.fireBuildFinished(exception);
        throw new IzPackException("Ant build failed", exception, getSeverity());
    } finally {
        if (oldsm != null) {
            System.setSecurityManager(oldsm);
        }
        System.setOut(out);
        System.setErr(err);
    }
}