Example usage for java.io OutputStream OutputStream

List of usage examples for java.io OutputStream OutputStream

Introduction

In this page you can find the example usage for java.io OutputStream OutputStream.

Prototype

OutputStream

Source Link

Usage

From source file:org.codehaus.mojo.VeraxxMojo.java

protected OutputStream getOutputStreamErr() {
    String OutputReportName = new String();
    if (reportsfileDir.isAbsolute()) {
        OutputReportName = reportsfileDir.getAbsolutePath() + "/" + getReportFileName();
    } else {// ww w.j  ava2 s  .  com
        OutputReportName = basedir.getAbsolutePath() + "/" + reportsfileDir.getPath() + "/"
                + getReportFileName();
    }
    getLog().info("Vera++ report location " + OutputReportName);

    OutputStream output = System.err;
    File file = new File(OutputReportName);
    try {
        new File(file.getParent()).mkdirs();
        file.createNewFile();
        output = new FileOutputStream(file);
    } catch (IOException e) {
        getLog().error("Vera++ report redirected to stderr since " + OutputReportName + " can't be opened");
        return output;
    }

    final DataOutputStream out = new DataOutputStream(output);

    try {
        out.writeBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        out.writeBytes("<checkstyle version=\"5.0\">\n");
    } catch (IOException e) {
        getLog().error("Vera++ xml report write failure");
    }

    OutputStream outErrFilter = new OutputStream() {
        StringBuffer sb = new StringBuffer();

        public void write(int b) throws IOException {
            if ((b == '\n') || (b == '\r')) {
                transformCurrentLine();
                // cleanup for next line
                sb.delete(0, sb.length());
            } else {
                sb.append((char) b);
            }
        }

        public void flush() throws IOException {
            transformCurrentLine();
            getLog().debug("Vera++ xml flush() called");
            if (!StringUtils.isEmpty(lastfile)) {
                out.writeBytes("\t</file>\n");
            }
            out.writeBytes("</checkstyle>\n");
            out.flush();
        }

        String lastfile;

        private void transformCurrentLine() {
            if (sb.length() > 0) {
                // parse current line

                // try to replace ' (RULENumber) ' with 'RULENumber:'
                String p = "^(.+) \\((.+)\\) (.+)$";
                Pattern pattern = Pattern.compile(p);
                Matcher matcher = pattern.matcher(sb);
                getLog().debug("match " + sb + " on " + p);

                boolean bWinPath = false;
                if (sb.charAt(1) == ':') {
                    bWinPath = true;
                    sb.setCharAt(1, '_');
                }

                if (matcher.matches()) {
                    String sLine = matcher.group(1) + matcher.group(2) + ":" + matcher.group(3);
                    getLog().debug("rebuild line = " + sLine);

                    // extract informations
                    pattern = Pattern.compile(":");
                    String[] items = pattern.split(sLine);

                    String file, line, rule, comment, severity;
                    file = items.length > 0 ? items[0] : "";
                    line = items.length > 1 ? items[1] : "";
                    rule = items.length > 2 ? items[2] : "";
                    comment = items.length > 3 ? items[3] : "";
                    severity = "warning";

                    if (bWinPath) {
                        StringBuilder s = new StringBuilder(file);
                        s.setCharAt(1, ':');
                        file = s.toString();
                    }

                    // output Xml errors
                    try {
                        // handle <file/> tags
                        if (!file.equals(lastfile)) {
                            if (!StringUtils.isEmpty(lastfile)) {
                                out.writeBytes("\t</file>\n");
                            }
                            out.writeBytes("\t<file name=\"" + file + "\">\n");
                            lastfile = file;
                        }
                        out.writeBytes("\t\t<error line=\"" + line + "\" severity=\"" + severity
                                + "\" message=\"" + comment + "\" source=\"" + rule + "\"/>\n");
                    } catch (IOException e) {
                        getLog().error("Vera++ xml report write failure");
                    }
                }
            }
        }
    };
    return outErrFilter;
}

From source file:org.hibernate.search.elasticsearch.test.GsonStreamedEncodingTest.java

private String optimisedSha256(final List<JsonObject> bodyParts) {
    notEmpty(bodyParts);/*ww  w  .  ja v  a  2s .c  o m*/
    try (GsonHttpEntity entity = new GsonHttpEntity(gson, bodyParts)) {
        final MessageDigest digest = getSha256Digest();
        OutputStream discardingStream = new OutputStream() {
            @Override
            public void write(int b) throws IOException {
            }
        };
        DigestOutputStream digestStream = new DigestOutputStream(discardingStream, digest);
        entity.writeTo(digestStream);
        return encodeHexString(digest.digest());
    } catch (IOException e) {
        throw new RuntimeException("We're mocking IO operations, this should not happen?", e);
    }
}

From source file:org.gradle.play.internal.javascript.GoogleClosureCompiler.java

private PrintStream getDummyPrintStream() {
    OutputStream os = new OutputStream() {
        @Override//www. j a  v  a  2s .c o  m
        public void write(int b) throws IOException {
            // do nothing
        }
    };
    return new PrintStream(os);
}

From source file:org.hibernate.search.test.performance.scenario.TestReporter.java

private static PrintStream createOutputStream(String testScenarioName) {
    try {/*from   ww  w.j av  a  2  s  . c  o  m*/
        Path targetDir = getTargetDir();
        String reportFileName = "report-" + testScenarioName + "-"
                + DateFormatUtils.format(new Date(), "yyyy-MM-dd-HH'h'mm'm'") + ".txt";
        Path reportFile = targetDir.resolve(reportFileName);

        final OutputStream std = System.out;
        final OutputStream file = new PrintStream(new FileOutputStream(reportFile.toFile()), true, "UTF-8");
        final OutputStream stream = new OutputStream() {

            @Override
            public void write(int b) throws IOException {
                std.write(b);
                file.write(b);
            }

            @Override
            public void flush() throws IOException {
                std.flush();
                file.flush();
            }

            @Override
            public void close() throws IOException {
                file.close();
            }
        };
        return new PrintStream(stream, false, "UTF-8");
    } catch (FileNotFoundException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.maven.plugin.cxx.VeraxxMojo.java

@Override
protected OutputStream getOutputStreamErr() {
    String outputReportName = new String();
    if (reportsfileDir.isAbsolute()) {
        outputReportName = reportsfileDir.getAbsolutePath() + File.separator + getReportFileName();
    } else {/*from w ww .j a  v  a  2 s.  c  o m*/
        outputReportName = basedir.getAbsolutePath() + File.separator + reportsfileDir.getPath()
                + File.separator + getReportFileName();
    }
    getLog().info("Vera++ report location " + outputReportName);

    OutputStream output = System.err;
    File file = new File(outputReportName);
    try {
        new File(file.getParent()).mkdirs();
        file.createNewFile();
        output = new FileOutputStream(file);
    } catch (IOException e) {
        getLog().error("Vera++ report redirected to stderr since " + outputReportName + " can't be opened");
        return output;
    }

    final DataOutputStream out = new DataOutputStream(output);

    try {
        out.writeBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        out.writeBytes("<checkstyle version=\"5.0\">\n");
    } catch (IOException e) {
        getLog().error("Vera++ xml report write failure");
    }

    OutputStream outErrFilter = new OutputStream() {
        StringBuffer sb = new StringBuffer();

        public void write(int b) throws IOException {
            if ((b == '\n') || (b == '\r')) {
                transformCurrentLine();
                // cleanup for next line
                sb.delete(0, sb.length());
            } else {
                sb.append((char) b);
            }
        }

        public void flush() throws IOException {
            transformCurrentLine();
            getLog().debug("Vera++ xml flush() called");
            if (!StringUtils.isEmpty(lastfile)) {
                out.writeBytes("\t</file>\n");
            }
            out.writeBytes("</checkstyle>\n");
            out.flush();
        }

        String lastfile;

        private void transformCurrentLine() {
            if (sb.length() > 0) {
                // parse current line

                // try to replace ' (RULENumber) ' with 'RULENumber:'
                String p = "^(.+) \\((.+)\\) (.+)$";
                Pattern pattern = Pattern.compile(p);
                Matcher matcher = pattern.matcher(sb);
                getLog().debug("match " + sb + " on " + p);

                boolean bWinPath = false;
                if (sb.charAt(1) == ':') {
                    bWinPath = true;
                    sb.setCharAt(1, '_');
                }

                if (matcher.matches()) {
                    String sLine = matcher.group(1) + matcher.group(2) + ":" + matcher.group(3);
                    getLog().debug("rebuild line = " + sLine);

                    // extract informations
                    pattern = Pattern.compile(":");
                    String[] items = pattern.split(sLine);

                    String file, line, rule, comment, severity;
                    file = items.length > 0 ? items[0] : "";
                    line = items.length > 1 ? items[1] : "";
                    rule = items.length > 2 ? items[2] : "";
                    comment = items.length > 3 ? items[3] : "";
                    severity = "warning";

                    if (bWinPath) {
                        StringBuilder s = new StringBuilder(file);
                        s.setCharAt(1, ':');
                        file = s.toString();
                    }

                    // output Xml errors
                    try {
                        // handle <file/> tags
                        if (!file.equals(lastfile)) {
                            if (!StringUtils.isEmpty(lastfile)) {
                                out.writeBytes("\t</file>\n");
                            }
                            out.writeBytes("\t<file name=\"" + file + "\">\n");
                            lastfile = file;
                        }
                        out.writeBytes("\t\t<error line=\"" + line + "\" severity=\"" + severity
                                + "\" message=\"" + comment + "\" source=\"" + rule + "\"/>\n");
                    } catch (IOException e) {
                        getLog().error("Vera++ xml report write failure");
                    }
                }
            }
        }
    };
    return outErrFilter;
}

From source file:org.opencastproject.index.service.util.RestUtils.java

public static String getJsonString(JValue json) throws WebApplicationException, IOException {
    OutputStream output = new OutputStream() {
        private StringBuilder string = new StringBuilder();

        @Override/*from  ww  w. j  a v  a  2 s  .  co  m*/
        public void write(int b) throws IOException {
            this.string.append((char) b);
        }

        @Override
        public String toString() {
            return this.string.toString();
        }
    };

    stream(serializer.toJsonFx(json)).write(output);

    return output.toString();
}

From source file:com.alexkli.jhb.Worker.java

private void consumeAndCloseStream(InputStream responseStream) throws IOException {
    try (InputStream ignored = responseStream) {
        IOUtils.copyLarge(responseStream, new OutputStream() {
            @Override//from   w  w w . j  a va  2s . c  o m
            public void write(int b) throws IOException {
                // discard
            }

            @Override
            public void write(byte[] b) throws IOException {
                // discard
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                // discard
            }
        });
    }
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    /////  w  ww .j a  v  a2s  . co m
    //        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:com.adaptris.core.MarshallingBaseCase.java

public void testMarshalToOutputStream_WithException() throws Exception {
    AdaptrisMarshaller marshaller = createMarshaller();
    Adapter adapter = createMarshallingObject();
    OutputStream fail = new OutputStream() {
        @Override/*w  w w.  j  a  va2  s . co  m*/
        public void write(int c) throws IOException {
            throw new IOException("testMarshalToOutputStream_WithException");
        }
    };
    try (OutputStream out = fail) {
        marshaller.marshal(adapter, out);
        fail();
    } catch (CoreException e) {
        assertNotNull(e.getCause());
        // assertEquals(IOException.class, e.getCause().getClass());
        assertRootCause("testMarshalToOutputStream_WithException", e);
    }
}

From source file:com.diversityarrays.dal.server.ServerGui.java

public ServerGui(Image serverIconImage, IDalServer svr, DalServerFactory factory, File wwwRoot,
        DalServerPreferences prefs) {/*  w  ww  . ja  v  a 2 s  .  c om*/

    this.serverIconImage = serverIconImage;
    this.dalServerFactory = factory;
    this.wwwRoot = wwwRoot;
    this.preferences = prefs;

    JMenuBar menuBar = new JMenuBar();

    JMenu serverMenu = new JMenu("Server");
    menuBar.add(serverMenu);
    serverMenu.add(serverStartAction);
    serverMenu.add(serverStopAction);
    serverMenu.add(exitAction);

    JMenu commandMenu = new JMenu("Command");
    menuBar.add(commandMenu);
    commandMenu.add(doSql);

    JMenu urlMenu = new JMenu("URL");
    menuBar.add(urlMenu);
    urlMenu.add(new JMenuItem(copyDalUrlAction));
    urlMenu.add(new JMenuItem(showDalUrlQRcodeAction));

    setJMenuBar(menuBar);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    messages.setFont(GuiUtil.createMonospacedFont(12));
    messages.setEditable(false);

    setServer(svr);

    quietOption.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            boolean q = quietOption.isSelected();
            if (server != null) {
                server.setQuiet(q);
            }
        }
    });

    JScrollPane scrollPane = new JScrollPane(messages, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    final JScrollBar verticalScrollBar = scrollPane.getVerticalScrollBar();

    JButton clear = new JButton(new AbstractAction("Clear") {
        @Override
        public void actionPerformed(ActionEvent e) {
            messages.setText("");
        }
    });

    final boolean[] follow = new boolean[] { true };
    final JCheckBox followTail = new JCheckBox("Follow", follow[0]);

    followTail.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            follow[0] = followTail.isSelected();
        }
    });

    final OutputStream os = new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            char ch = (char) b;
            messages.append(new Character(ch).toString());
            if (ch == '\n' && follow[0]) {
                verticalScrollBar.setValue(verticalScrollBar.getMaximum());
            }
        }
    };

    TeePrintStream pso = new TeePrintStream(System.out, os);
    TeePrintStream pse = new TeePrintStream(System.err, os);

    System.setErr(pse);
    System.setOut(pso);

    Box box = Box.createHorizontalBox();
    box.add(clear);
    box.add(followTail);
    box.add(quietOption);
    box.add(Box.createHorizontalGlue());

    JPanel bottom = new JPanel(new BorderLayout());
    bottom.add(BorderLayout.NORTH, box);
    bottom.add(BorderLayout.SOUTH, statusInfoLine);

    Container cp = getContentPane();
    cp.add(BorderLayout.CENTER, scrollPane);
    cp.add(BorderLayout.SOUTH, bottom);

    pack();
    setSize(640, 480);

    final MemoryUsageMonitor mum = new MemoryUsageMonitor();
    mum.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            statusInfoLine.setMessage(mum.getMemoryUsage());
        }
    });

    if (server == null) {
        // If initial server is null, allow user to specify
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent e) {
                removeWindowListener(this);
                serverStartAction.actionPerformed(null);
            }
        });
    } else {
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent e) {
                removeWindowListener(this);
                ensureDatabaseInitialisedThenStartServer();
            }
        });
    }
}