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.apache.tools.ant.listener.CommonsLoggingListener.java

private void realLog(final Log log, final String message, final int priority, final Throwable t) {
    final PrintStream tmpOut = System.out;
    final PrintStream tmpErr = System.err;
    System.setOut(out);
    System.setErr(err);//from w  ww  .j a va2  s.  com
    switch (priority) {
    case Project.MSG_ERR:
        if (t == null) {
            log.error(message);
        } else {
            log.error(message, t);
        }
        break;
    case Project.MSG_WARN:
        if (t == null) {
            log.warn(message);
        } else {
            log.warn(message, t);
        }
        break;
    case Project.MSG_INFO:
        if (t == null) {
            log.info(message);
        } else {
            log.info(message, t);
        }
        break;
    case Project.MSG_VERBOSE:
        log.debug(message);
        break;
    case Project.MSG_DEBUG:
        log.debug(message);
        break;
    default:
        log.error(message);
        break;
    }
    System.setOut(tmpOut);
    System.setErr(tmpErr);
}

From source file:com.cw.litenote.main.MainAct.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    /////from   w  w  w .j  a  v  a  2 s. com
    //        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);

    /**
     * Set APP build mode
     * Note:
     *  1. for AdMob: it works after Google Play store release
     *  2. for assets mode: need to enable build.gradle assets.srcDirs = ['preferred/assets/']
     */
    /** 1 debug, initial */
    //        Define.setAppBuildMode(Define.DEBUG_DEFAULT_BY_INITIAL);

    /** 2 debug, assets */
    Define.setAppBuildMode(Define.DEBUG_DEFAULT_BY_ASSETS);

    /** 3 debug, download */
    //        Define.setAppBuildMode(Define.DEBUG_DEFAULT_BY_DOWNLOAD);

    /** 4 release, initial */
    //        Define.setAppBuildMode(Define.RELEASE_DEFAULT_BY_INITIAL);

    /** 5 release, assets */
    //        Define.setAppBuildMode(Define.RELEASE_DEFAULT_BY_ASSETS);

    /** 6 release, download */
    //        Define.setAppBuildMode(Define.RELEASE_DEFAULT_BY_DOWNLOAD);

    // 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));
    }

    System.out.println("================start application ==================");
    System.out.println("MainAct / _onCreate");

    mAct = this;
    mAppTitle = getTitle();
    mMainUi = new MainUi();

    // File provider implementation is needed after Android version 24
    // if not, will encounter android.os.FileUriExposedException
    // cf. https://stackoverflow.com/questions/38200282/android-os-fileuriexposedexception-file-storage-emulated-0-test-txt-exposed

    // add the following to disable this requirement
    if (Build.VERSION.SDK_INT >= 24) {
        try {
            // method 1
            Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
            m.invoke(null);

            // method 2
            //                StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            //                StrictMode.setVmPolicy(builder.build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Show Api version
    if (Define.CODE_MODE == Define.DEBUG_MODE)
        Toast.makeText(this, mAppTitle + " " + "API_" + Build.VERSION.SDK_INT, Toast.LENGTH_SHORT).show();
    else
        Toast.makeText(this, mAppTitle, Toast.LENGTH_SHORT).show();

    //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(...);
    }
    */
    UtilImage.getDefaultScaleInPercent(MainAct.this);

    // EULA
    Dialog_EULA dialog_EULA = new Dialog_EULA(this);
    bEULA_accepted = dialog_EULA.isEulaAlreadyAccepted();

    // Show dialog of EULA
    if (!bEULA_accepted) {
        // Ok button listener
        dialog_EULA.clickListener_Ok = (DialogInterface dialog, int i) -> {

            dialog_EULA.applyPreference();

            // dialog: with default content
            if ((Define.DEFAULT_CONTENT == Define.BY_ASSETS)
                    || (Define.DEFAULT_CONTENT == Define.BY_DOWNLOAD)) {
                // Click Yes
                DialogInterface.OnClickListener click_Yes = (DialogInterface dlg, int j) -> {
                    // Close dialog
                    dialog.dismiss();

                    // check build version for permission request (starts from API 23)
                    if (Build.VERSION.SDK_INT >= 23)
                        checkPermission(savedInstanceState,
                                Util.PERMISSIONS_REQUEST_STORAGE_WITH_DEFAULT_CONTENT_YES);
                    else {
                        if (Define.DEFAULT_CONTENT == Define.BY_DOWNLOAD) {
                            createDefaultContent_byDownload();
                        } else {
                            Pref.setPref_will_create_default_content(this, true);
                            recreate();
                        }
                    }
                };

                // Click No
                DialogInterface.OnClickListener click_No = (DialogInterface dlg, int j) -> {
                    // Close dialog
                    dialog.dismiss();

                    // check build version for permission request
                    if (Build.VERSION.SDK_INT >= 23)
                        checkPermission(savedInstanceState,
                                Util.PERMISSIONS_REQUEST_STORAGE_WITH_DEFAULT_CONTENT_NO);
                    else {
                        Pref.setPref_will_create_default_content(this, false);
                        recreate();
                    }
                };

                AlertDialog.Builder builder = new AlertDialog.Builder(mAct)
                        .setTitle(R.string.sample_notes_title).setMessage(R.string.sample_notes_message)
                        .setCancelable(false).setPositiveButton(R.string.confirm_dialog_button_yes, click_Yes)
                        .setNegativeButton(R.string.confirm_dialog_button_no, click_No);
                builder.create().show();
            } else if ((Define.DEFAULT_CONTENT == Define.BY_INITIAL_TABLES)
                    && (Define.INITIAL_FOLDERS_COUNT > 0)) {
                if (Build.VERSION.SDK_INT >= 23)
                    checkPermission(savedInstanceState,
                            Util.PERMISSIONS_REQUEST_STORAGE_WITH_DEFAULT_CONTENT_YES);
                else {
                    Pref.setPref_will_create_default_content(this, true);
                    recreate();
                }
                // Close dialog
                dialog.dismiss();
            }
        };

        // No button listener
        dialog_EULA.clickListener_No = (DialogInterface dialog, int which) -> {
            // Close the activity as they have declined
            // the EULA
            dialog.dismiss();
            mAct.finish();
        };

        dialog_EULA.show();
    } else
        doCreate(savedInstanceState);

}

From source file:org.eclipselabs.spray.dev.pde.internal.UpdateTargetPlatform.java

protected List<InstallableUnit> readRepositoryContent(URL repositoryURL) {
    LOG.info("Reading repository " + repositoryURL);

    List<InstallableUnit> ius = Lists.newArrayList();

    DirectorApplication director = new DirectorApplication();
    String[] args = new String[] { "-l", "-r", repositoryURL.toString() };
    PrintStream ps = System.out;
    try {//from   www  .  ja  v  a 2  s  .  c  om
        // redirect stdout to bytearray
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        System.setOut(new PrintStream(bos));

        // call director
        Object result = director.run(args);

        // read stdout output from bytearray
        BufferedReader br = new BufferedReader(new StringReader(bos.toString()));
        for (String line = br.readLine(); line != null; line = br.readLine()) {
            LOG.debug("[DIRECTOR] " + line);
            InstallableUnit iu = fromString(line);
            if (iu != null) {
                ius.add(iu);
            }
        }
        if (result instanceof Integer) {
            Integer rc = (Integer) result;
            if (rc != 0) {
                LOG.warn("Director aborted with error. Ignoring repository " + repositoryURL);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        System.setOut(ps);
    }
    return ius;
}

From source file:org.apache.hive.beeline.cli.TestHiveCli.java

private void redirectOutputStream() {
    // Setup output stream to redirect output to
    os = new ByteArrayOutputStream();
    ps = new PrintStream(os);
    errS = new ByteArrayOutputStream();
    errPs = new PrintStream(errS);
    System.setOut(ps);
    System.setErr(errPs);// w w w  .j av  a  2 s.  co  m
}

From source file:org.apache.tika.cli.TikaCLIIT.java

/**
 * Tears down the test. Returns the System.out
 *//*from   ww w . ja v a2s. co  m*/
@After
public void tearDown() throws Exception {
    System.setOut(stdout);
    System.setErr(errout);
    //System.out.println("Output: " + outContent.toString(UTF_8.name()));
    //System.out.println("Error: " + errContent.toString(UTF_8.name()));
}

From source file:functionaltests.NodeSourceCommandsFunctTest.java

private void editNodeSourceAndCheckOutput(String nodeSourceName, String policyParametersString) {

    System.out.println(LOG_HEADER + " Test editns command");

    this.clearAndTypeLine("editns( '" + nodeSourceName + "', " + modifiedInfrastructureParametersString + ", "
            + policyParametersString + ", 'false')");

    this.runCli();

    String out = this.capturedOutput.toString();
    System.setOut(this.stdOut);
    System.out.println(out);// w  w w.ja v a 2  s . c  o  m

    assertThat(out).contains("Node source successfully edited.");
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestDecommissioningStatus.java

private void checkDFSAdminDecommissionStatus(List<DatanodeDescriptor> expectedDecomm, DistributedFileSystem dfs,
        DFSAdmin admin) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    PrintStream oldOut = System.out;
    System.setOut(ps);
    try {//from w  ww . j  a v a 2  s .com
        // Parse DFSAdmin just to check the count
        admin.report(new String[] { "-decommissioning" }, 0);
        String[] lines = baos.toString().split("\n");
        Integer num = null;
        int count = 0;
        for (String line : lines) {
            if (line.startsWith("Decommissioning datanodes")) {
                // Pull out the "(num)" and parse it into an int
                String temp = line.split(" ")[2];
                num = Integer.parseInt((String) temp.subSequence(1, temp.length() - 2));
            }
            if (line.contains("Decommission in progress")) {
                count++;
            }
        }
        assertTrue("No decommissioning output", num != null);
        assertEquals("Unexpected number of decomming DNs", expectedDecomm.size(), num.intValue());
        assertEquals("Unexpected number of decomming DNs", expectedDecomm.size(), count);
        // Check Java API for correct contents
        List<DatanodeInfo> decomming = new ArrayList<DatanodeInfo>(
                Arrays.asList(dfs.getDataNodeStats(DatanodeReportType.DECOMMISSIONING)));
        assertEquals("Unexpected number of decomming DNs", expectedDecomm.size(), decomming.size());
        for (DatanodeID id : expectedDecomm) {
            assertTrue("Did not find expected decomming DN " + id, decomming.contains(id));
        }
    } finally {
        System.setOut(oldOut);
    }
}

From source file:org.apache.eagle.alert.metric.MetricSystemTest.java

@Test
public void testSlf4jSink() throws IOException {
    PrintStream console = System.out;
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    System.setOut(new PrintStream(bytes));

    Slf4jSink sink = new Slf4jSink();
    MetricRegistry registry = new MetricRegistry();
    JvmAttributeGaugeSet jvm = Mockito.mock(JvmAttributeGaugeSet.class);
    Map<String, Metric> metrics = new HashMap<>();
    metrics.put("name", (Gauge) () -> "testname");
    metrics.put("uptime", (Gauge) () -> "testuptime");
    metrics.put("vendor", (Gauge) () -> "testvendor");
    Mockito.when(jvm.getMetrics()).thenReturn(metrics);
    registry.registerAll(jvm);/*from   www  . j av a  2s.c o m*/
    File file = genSlf4jSinkConfig();
    Config config = ConfigFactory.parseFile(file);
    sink.prepare(config, registry);
    sink.report();
    sink.stop();
    String result = bytes.toString();
    String finalResult = "";
    Scanner scanner = new Scanner(result);
    while (scanner.hasNext()) {
        finalResult += scanner.nextLine().substring(DATA_BEGIN_INDEX) + END_LINE;
    }
    Assert.assertEquals("type=GAUGE, name=name, value=testname" + END_LINE + ""
            + "type=GAUGE, name=uptime, value=testuptime" + END_LINE + ""
            + "type=GAUGE, name=vendor, value=testvendor" + END_LINE + "", finalResult);
    System.setOut(console);
}

From source file:functionaltests.TagCommandsFunctTest.java

@Test
public void testJobOutputWithTag() throws Exception {
    typeLine("joboutput(" + jobId.longValue() + ", 'LOOP-T2-1')");

    runCli();//from  w  ww.jav a2  s .  com

    String out = this.capturedOutput.toString();
    System.setOut(stdOut);
    System.out.println("------------- testJobOutputWithTag:");
    System.out.println(out);
    assertEquals(2, StringUtils.countMatches(out, "Task 1 : Test STDERR"));
    assertEquals(2, StringUtils.countMatches(out, "Task 1 : Test STDOUT"));
    assertEquals(2, StringUtils.countMatches(out, "Terminate task number 1"));
    assertTrue(!out.contains("Task 2 : Test STDERR"));
    assertTrue(!out.contains("Task 2 : Test STDOUT"));
    assertTrue(!out.contains("Terminate task number 2"));
}

From source file:org.apache.hadoop.hdfs.TestDFSShell.java

@Test
public void testDu() throws IOException {
    Configuration conf = new HdfsConfiguration();
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
    DistributedFileSystem fs = cluster.getFileSystem();
    PrintStream psBackup = System.out;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PrintStream psOut = new PrintStream(out);
    System.setOut(psOut);
    FsShell shell = new FsShell();
    shell.setConf(conf);//from  www. ja  v a 2s. c o  m

    try {
        Path myPath = new Path("/test/dir");
        assertTrue(fs.mkdirs(myPath));
        assertTrue(fs.exists(myPath));
        Path myFile = new Path("/test/dir/file");
        writeFile(fs, myFile);
        assertTrue(fs.exists(myFile));
        Path myFile2 = new Path("/test/dir/file2");
        writeFile(fs, myFile2);
        assertTrue(fs.exists(myFile2));

        String[] args = new String[2];
        args[0] = "-du";
        args[1] = "/test/dir";
        int val = -1;
        try {
            val = shell.run(args);
        } catch (Exception e) {
            System.err.println("Exception raised from DFSShell.run " + e.getLocalizedMessage());
        }
        assertTrue(val == 0);
        String returnString = out.toString();
        out.reset();
        // Check if size matchs as expected
        assertTrue(returnString.contains("22"));
        assertTrue(returnString.contains("23"));

    } finally {
        System.setOut(psBackup);
        cluster.shutdown();
    }

}