Example usage for java.io ByteArrayOutputStream ByteArrayOutputStream

List of usage examples for java.io ByteArrayOutputStream ByteArrayOutputStream

Introduction

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

Prototype

public ByteArrayOutputStream() 

Source Link

Document

Creates a new ByteArrayOutputStream .

Usage

From source file:edu.umd.cs.marmoset.modelClasses.ZipFileAggregator.java

public static void main(String[] args) throws Exception {
    FileInputStream fis = new FileInputStream("inputfile1.zip");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    CopyUtils.copy(fis, baos);/*from w  w  w  .  j a  va2s .c om*/

    byte[] byteArr = baos.toByteArray();
    fis.close();

    fis = new FileInputStream("inputfile2.zip");
    baos = new ByteArrayOutputStream();
    CopyUtils.copy(fis, baos);

    byteArr = baos.toByteArray();
    fis.close();

    //      if (args.length < 2) {
    //         System.err.println("Usage: " +
    //               ZipFileAggregator.class.getName() +
    //               " <output file> <file1, file2...>");
    //         System.exit(1);
    //      }
    //
    //      ZipFileAggregator agg=null;
    //      try {
    //         agg=new ZipFileAggregator(new FileOutputStream(args[0]));
    //         for (int i = 1; i < args.length; ++i) {
    //            File inputFile = new File(args[i]);
    //            System.out.println("Adding " + args[i]);
    //            try {
    //               agg.addFile(args[i], inputFile);
    //            } catch (ZipFileAggregator.BadInputZipFileException e) {
    //               System.out.println("Recoverable exception: " + e);
    //               System.out.println("Continuing...");
    //            }
    //         }
    //      } finally {
    //         if (agg != null) agg.close();
    //      }
    //      System.out.println("Done!");
}

From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java

public static void main(String[] args) throws Exception {
    // Let's use some colors :)
    //        AnsiConsole.systemInstall();
    CommandLineParser cliParser = new BasicParser();
    CommandLine cli = null;/* www .j  av  a2  s .c o  m*/
    try {
        cli = cliParser.parse(OPTIONS, args);
    } catch (ParseException e) {
        printHelp();
    }
    if (!cli.hasOption("s")) {
        printHelp();
    }

    String sourcePattern;
    if (cli.hasOption("p")) {
        sourcePattern = cli.getOptionValue("p");
    } else {
        sourcePattern = DEFAULT_SOURCE_PATTERN;
    }

    String defaultAnswer;
    if (cli.hasOption("default-answer")) {
        defaultAnswer = cli.getOptionValue("default-answer");
    } else {
        defaultAnswer = DEFAULT_DEFAULT_PROMPT_ANSWER;
    }

    boolean defaultAnswerYes = defaultAnswer.equalsIgnoreCase("y");
    boolean quiet = cli.hasOption("q");
    boolean testWrite = cli.hasOption("t");
    Path sourceDirectory = Paths.get(cli.getOptionValue("s")).toAbsolutePath();
    // Since we use IO we will have some blocking threads hanging around
    int threadCount = Runtime.getRuntime().availableProcessors() * 2;
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());
    BlockingQueue<WidgetVarLocation> foundUsages = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> unusedOrAmbiguous = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> skippedUsages = new LinkedBlockingQueue<>();
    List<Future<?>> futures = new ArrayList<>();

    findWidgetVars(sourceDirectory, sourcePattern, threadPool).forEach(widgetVarLocation -> {
        // We can't really find usages of widget vars that use EL expressions :(
        if (widgetVarLocation.widgetVar.contains("#")) {
            unusedOrAmbiguous.add(widgetVarLocation);
            return;
        }

        try {
            FileActionVisitor visitor = new FileActionVisitor(sourceDirectory, sourcePattern,
                    sourceFile -> futures.add(threadPool.submit((Callable<?>) () -> {
                        findWidgetVarUsages(sourceFile, widgetVarLocation, foundUsages, skippedUsages,
                                unusedOrAmbiguous);
                        return null;
                    })));

            Files.walkFileTree(sourceDirectory, visitor);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });

    awaitAll(futures);

    new TreeSet<>(skippedUsages).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped " + relativePath + " at line " + widgetUsage.lineNr + " and col "
                + widgetUsage.columnNr + " for widgetVar '" + widgetUsage.widgetVar + "'");
        System.out.println("\t" + previous);
    });

    Map<WidgetVarLocation, List<WidgetVarLocation>> written = new HashMap<>();

    new TreeSet<>(foundUsages).forEach(widgetUsage -> {
        WidgetVarLocation key = new WidgetVarLocation(null, widgetUsage.location, widgetUsage.lineNr, -1, null);
        List<WidgetVarLocation> writtenList = written.get(key);
        int existing = writtenList == null ? 0 : writtenList.size();
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String next = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED)
                .a("PF('" + widgetUsage.widgetVar + "')").reset().toString());
        System.out
                .println(relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + next);
        System.out.print("Replace (Y/N)? [" + (defaultAnswerYes ? "Y" : "N") + "]: ");

        String input;

        if (quiet) {
            input = "";
            System.out.println();
        } else {
            try {
                do {
                    input = in.readLine();
                } while (input != null && !input.isEmpty() && !"y".equalsIgnoreCase(input)
                        && !"n".equalsIgnoreCase(input));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        if (input == null) {
            System.out.println("Aborted!");
        } else if (input.isEmpty() && defaultAnswerYes || !input.isEmpty() && !"n".equalsIgnoreCase(input)) {
            System.out.println("Replaced!");
            System.out.print("\t");
            if (writtenList == null) {
                writtenList = new ArrayList<>();
                written.put(key, writtenList);
            }

            writtenList.add(widgetUsage);
            List<String> lines;
            try {
                lines = Files.readAllLines(widgetUsage.location);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

            try (OutputStream os = testWrite ? new ByteArrayOutputStream()
                    : Files.newOutputStream(widgetUsage.location);
                    PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
                String line;

                for (int i = 0; i < lines.size(); i++) {
                    int lineNr = i + 1;
                    line = lines.get(i);

                    if (lineNr == widgetUsage.lineNr) {
                        int begin = widgetUsage.columnNr + (testWrite ? 0 : existing * 6);
                        int end = begin + widgetUsage.widgetVar.length();
                        String newLine = replace(line, begin, end, "PF('" + widgetUsage.widgetVar + "')",
                                false);

                        if (testWrite) {
                            System.out.println(newLine);
                        } else {
                            pw.println(newLine);
                        }
                    } else {
                        if (!testWrite) {
                            pw.println(line);
                        }
                    }
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } else {
            System.out.println("Skipped!");
        }
    });

    new TreeSet<>(unusedOrAmbiguous).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped unused or ambiguous " + relativePath + " at line " + widgetUsage.lineNr
                + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + previous);
    });

    threadPool.shutdown();
}

From source file:com.netscape.cmstools.OCSPClient.java

public static void main(String args[]) throws Exception {

    Options options = createOptions();//from w w  w .ja  v a 2 s .  c o  m
    CommandLine cmd = null;

    try {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        printError(e);
        System.exit(1);
    }

    if (cmd.hasOption("help")) {
        printHelp();
        System.exit(0);
    }

    boolean verbose = cmd.hasOption("v");

    String databaseDir = cmd.getOptionValue("d", ".");
    String hostname = cmd.getOptionValue("h", InetAddress.getLocalHost().getCanonicalHostName());
    int port = Integer.parseInt(cmd.getOptionValue("p", "8080"));
    String path = cmd.getOptionValue("t", "/ocsp/ee/ocsp");
    String caNickname = cmd.getOptionValue("c", "CA Signing Certificate");
    int times = Integer.parseInt(cmd.getOptionValue("n", "1"));

    String input = cmd.getOptionValue("input");
    String serial = cmd.getOptionValue("serial");
    String output = cmd.getOptionValue("output");

    if (times < 1) {
        printError("Invalid number of submissions");
        System.exit(1);
    }

    try {
        if (verbose)
            System.out.println("Initializing security database");
        CryptoManager.initialize(databaseDir);

        String url = "http://" + hostname + ":" + port + path;

        OCSPProcessor processor = new OCSPProcessor();
        processor.setVerbose(verbose);

        OCSPRequest request;
        if (serial != null) {
            if (verbose)
                System.out.println("Creating request for serial number " + serial);

            BigInteger serialNumber = new BigInteger(serial);
            request = processor.createRequest(caNickname, serialNumber);

        } else if (input != null) {
            if (verbose)
                System.out.println("Loading request from " + input);

            try (FileInputStream in = new FileInputStream(input)) {
                byte[] data = new byte[in.available()];
                in.read(data);
                request = processor.createRequest(data);
            }

        } else {
            throw new Exception("Missing serial number or input file.");
        }

        OCSPResponse response = null;
        for (int i = 0; i < times; i++) {

            if (verbose)
                System.out.println("Submitting OCSP request");
            response = processor.submitRequest(url, request);

            ResponseBytes bytes = response.getResponseBytes();
            BasicOCSPResponse basic = (BasicOCSPResponse) BasicOCSPResponse.getTemplate()
                    .decode(new ByteArrayInputStream(bytes.getResponse().toByteArray()));

            ResponseData rd = basic.getResponseData();
            for (int j = 0; j < rd.getResponseCount(); j++) {
                SingleResponse sr = rd.getResponseAt(j);

                if (sr == null) {
                    throw new Exception("No OCSP Response data.");
                }

                System.out.println("CertID.serialNumber=" + sr.getCertID().getSerialNumber());

                CertStatus status = sr.getCertStatus();
                if (status instanceof GoodInfo) {
                    System.out.println("CertStatus=Good");

                } else if (status instanceof UnknownInfo) {
                    System.out.println("CertStatus=Unknown");

                } else if (status instanceof RevokedInfo) {
                    System.out.println("CertStatus=Revoked");
                }
            }
        }

        if (output != null) {
            if (verbose)
                System.out.println("Storing response into " + output);

            try (FileOutputStream out = new FileOutputStream(output)) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                response.encode(os);
                out.write(os.toByteArray());
            }

            System.out.println("Success: Output " + output);
        }

    } catch (Exception e) {
        if (verbose)
            e.printStackTrace();
        printError(e);
        System.exit(1);
    }
}

From source file:marytts.tools.analysis.CopySynthesis.java

/**
 * @param args//from w  ww  .  j ava  2s .  c o m
 */
public static void main(String[] args) throws Exception {
    String wavFilename = null;
    String labFilename = null;
    String pitchFilename = null;
    String textFilename = null;

    String locale = System.getProperty("locale");
    if (locale == null) {
        throw new IllegalArgumentException("No locale given (-Dlocale=...)");
    }

    for (String arg : args) {
        if (arg.endsWith(".txt"))
            textFilename = arg;
        else if (arg.endsWith(".wav"))
            wavFilename = arg;
        else if (arg.endsWith(".ptc"))
            pitchFilename = arg;
        else if (arg.endsWith(".lab"))
            labFilename = arg;
        else
            throw new IllegalArgumentException("Don't know how to treat argument: " + arg);
    }

    // The intonation contour
    double[] contour = null;
    double frameShiftTime = -1;
    if (pitchFilename == null) { // need to create pitch contour from wav file 
        if (wavFilename == null) {
            throw new IllegalArgumentException("Need either a pitch file or a wav file");
        }
        AudioInputStream ais = AudioSystem.getAudioInputStream(new File(wavFilename));
        AudioDoubleDataSource audio = new AudioDoubleDataSource(ais);
        PitchFileHeader params = new PitchFileHeader();
        params.fs = (int) ais.getFormat().getSampleRate();
        F0TrackerAutocorrelationHeuristic tracker = new F0TrackerAutocorrelationHeuristic(params);
        tracker.pitchAnalyze(audio);
        frameShiftTime = tracker.getSkipSizeInSeconds();
        contour = tracker.getF0Contour();
    } else { // have a pitch file -- ignore any wav file
        PitchReaderWriter f0rw = new PitchReaderWriter(pitchFilename);
        if (f0rw.contour == null) {
            throw new NullPointerException("Cannot read f0 contour from " + pitchFilename);
        }
        contour = f0rw.contour;
        frameShiftTime = f0rw.header.skipSizeInSeconds;
    }
    assert contour != null;
    assert frameShiftTime > 0;

    // The ALLOPHONES data and labels
    if (labFilename == null) {
        throw new IllegalArgumentException("No label file given");
    }
    if (textFilename == null) {
        throw new IllegalArgumentException("No text file given");
    }
    MaryTranscriptionAligner aligner = new MaryTranscriptionAligner();
    aligner.SetEnsureInitialBoundary(false);
    String labels = MaryTranscriptionAligner.readLabelFile(aligner.getEntrySeparator(),
            aligner.getEnsureInitialBoundary(), labFilename);
    MaryHttpClient mary = new MaryHttpClient();
    String text = FileUtils.readFileToString(new File(textFilename), "ASCII");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mary.process(text, "TEXT", "ALLOPHONES", locale, null, null, baos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);
    DocumentBuilder builder = docFactory.newDocumentBuilder();
    Document doc = builder.parse(bais);
    aligner.alignXmlTranscriptions(doc, labels);
    assert doc != null;

    // durations
    double[] endTimes = new LabelfileDoubleDataSource(new File(labFilename)).getAllData();
    assert endTimes.length == labels.split(Pattern.quote(aligner.getEntrySeparator())).length;

    // Now add durations and f0 targets to document
    double prevEnd = 0;
    NodeIterator ni = MaryDomUtils.createNodeIterator(doc, MaryXML.PHONE, MaryXML.BOUNDARY);
    for (int i = 0; i < endTimes.length; i++) {
        Element e = (Element) ni.nextNode();
        if (e == null)
            throw new IllegalStateException("More durations than elements -- this should not happen!");
        double durInSeconds = endTimes[i] - prevEnd;
        int durInMillis = (int) (1000 * durInSeconds);
        if (e.getTagName().equals(MaryXML.PHONE)) {
            e.setAttribute("d", String.valueOf(durInMillis));
            e.setAttribute("end", new Formatter(Locale.US).format("%.3f", endTimes[i]).toString());
            // f0 targets at beginning, mid, and end of phone
            StringBuilder f0String = new StringBuilder();
            double startF0 = getF0(contour, frameShiftTime, prevEnd);
            if (startF0 != 0 && !Double.isNaN(startF0)) {
                f0String.append("(0,").append((int) startF0).append(")");
            }
            double midF0 = getF0(contour, frameShiftTime, prevEnd + 0.5 * durInSeconds);
            if (midF0 != 0 && !Double.isNaN(midF0)) {
                f0String.append("(50,").append((int) midF0).append(")");
            }
            double endF0 = getF0(contour, frameShiftTime, endTimes[i]);
            if (endF0 != 0 && !Double.isNaN(endF0)) {
                f0String.append("(100,").append((int) endF0).append(")");
            }
            if (f0String.length() > 0) {
                e.setAttribute("f0", f0String.toString());
            }
        } else { // boundary
            e.setAttribute("duration", String.valueOf(durInMillis));
        }
        prevEnd = endTimes[i];
    }
    if (ni.nextNode() != null) {
        throw new IllegalStateException("More elements than durations -- this should not happen!");
    }

    // TODO: add pitch values

    String acoustparams = DomUtils.document2String(doc);
    System.out.println("ACOUSTPARAMS:");
    System.out.println(acoustparams);
}

From source file:Main.java

static public byte[] getObjectBytes(Object o) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(o);//from  w w  w  .  j a  v  a 2  s.c o m
    oos.close();
    return baos.toByteArray();
}

From source file:Main.java

public static byte[] readInput(InputStream in) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int len = 0;//from  w  w w . ja  v a2s  .  c  o m
    byte[] buffer = new byte[1024];
    while ((len = in.read(buffer)) > 0) {
        out.write(buffer, 0, len);
    }
    out.close();
    in.close();
    return out.toByteArray();
}

From source file:Main.java

public static byte[] Bitmap2Jpeg(Bitmap src) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    src.compress(Bitmap.CompressFormat.JPEG, 50, os);

    byte[] array = os.toByteArray();
    return array;
}

From source file:Main.java

public static Object cloneObject(Object obj) {
    try {// w w  w  .j a v a2s  .  com
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(obj);
        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
        ObjectInputStream in = new ObjectInputStream(byteIn);
        return in.readObject();
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:Main.java

public static byte[] compressGZIP(byte bytes[]) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    GZIPOutputStream gzipos = new GZIPOutputStream(os);
    gzipos.write(bytes, 0, bytes.length);
    gzipos.close();//w  w w  .  jav  a2s .  co m
    return os.toByteArray();
}

From source file:Main.java

public static byte[] compressZip(byte bytes[]) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ZipOutputStream zipos = new ZipOutputStream(os);
    zipos.putNextEntry(new ZipEntry("ZIP"));
    zipos.write(bytes, 0, bytes.length);
    zipos.close();/*  www .  ja  v  a 2s.  co m*/
    return os.toByteArray();
}