Example usage for java.io ByteArrayOutputStream toByteArray

List of usage examples for java.io ByteArrayOutputStream toByteArray

Introduction

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

Prototype

public synchronized byte[] toByteArray() 

Source Link

Document

Creates a newly allocated byte array.

Usage

From source file:com.payne.test.StringTest.java

public static void main(String[] args) throws IOException {
    //        String a = "160504185452148809-1";
    //        a = a.split("-")[0];
    //        System.out.println(a);
    //        Random r = new Random();
    //        long a = 0l;
    //        for(int i=0;i<10000;i++){
    //            a = r.nextInt(5001) + 5000;
    //            if(a==5000){
    //                System.out.println(a);
    //            }
    //        }//from  www .ja  va2 s.com

    /**
     * ????
     */
    //        List<Integer> numberList = new ArrayList<>();
    //        numberList.add(1);
    //        numberList.add(2);
    //        Integer[] numbers = numberList.toArray(new Integer[numberList.size()]);
    ////        int[] numbers = new int[]{1,2};
    //        
    //        System.out.println(new Integer[]{}.length==0?0:1);
    //        
    //        Student s =  new Student();
    //        s.sumUp(new Integer[]{}.length==0?numbers:new Integer[]{1});
    //        s.sumUp(numbers);
    //        Parent p = null;
    //        Parent p2 = new Parent(new Student(5));
    //
    //        Student s = new Student();
    //        p = s.print(p);

    //        System.out.println(p==null?0:1);
    //        System.out.println(p.getAge());
    //        System.out.println(p.getStudent().getAge());
    //        int ai = 0;
    //        for(int i=0;i<2;i++){
    //            int b = 0;
    //            int b_grow = 0;
    //            for(int j=0;j<5;j++){
    //                b += new Random().nextInt(5);
    //            }
    //            
    //        }
    //        
    //        
    //        System.out.println(UUID.randomUUID().toString());

    //        int a = 1;
    //        a = doAdd(a);
    //        System.out.println(a);
    Pattern p = Pattern.compile("^\\d{1,9}(.\\d{1,2})?$");
    Matcher m = p.matcher("666666541.13");
    boolean b = m.matches();
    System.out.println(b);
    //          System.out.println(-2>>4);
    //        BigDecimal b = new BigDecimal(100.50);
    //        System.out.println(b.toString());
    // indexOf   ??
    //        String a = "?";
    //        
    //        String[] split = a.split("?");
    //        if(a.indexOf("?")>-1){
    //            System.out.println("111");
    //        }
    //        for(String s: split){
    //            System.out.println(s);
    //        }
    //        MapTestObject mto = new MapTestObject();
    //        mto.setOrderType(OrderType.TWO);
    //        
    //        String str = "\":\"";
    //        System.out.println(str);
    //        String a = ",";
    ////
    //        String[] splits = a.split(".");
    //        List<String> asList = Arrays.asList(splits);

    //        String last = "";
    //        String last = "";
    //        String last = "";
    //        if (!asList.isEmpty()) {
    //            if (asList.indexOf(last) > -1) {
    //                int indexOf = asList.indexOf(last);
    //                if (indexOf + 1 >= asList.size()) {
    //                    System.out.println("?");
    //                }else{
    //                    String next = asList.get(indexOf + 1);
    //                    if (OTHERStringUtils.isEmpty(next)) {
    //                        System.out.println("?");
    //                    } else {
    //                        System.out.println("?" + next);
    //                    }
    //                }
    //            } else {
    //                System.out.println("?");
    //            }
    //        } else {
    //            System.out.println("??");
    //        }

    //           System.out.println("?\",\""); 
    //           String a ="1123";
    //           a = StringUtils.substring(a, 0, a.length()-1);
    //           System.out.println("a="+a);
    //           
    int a = 0x12345678;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    dos.writeInt(a);
    System.out.println(Integer.toHexString(a));
    byte[] c = baos.toByteArray();
    for (int i = 0; i < 4; i++) {
        System.out.println(Integer.toHexString(c[i]));
    }
}

From source file:ObfuscatingStream.java

/**
 * Obfuscates or unobfuscates the second command-line argument, depending on
 * whether the first argument starts with "o" or "u"
 * /*  ww  w . j a  v a  2 s  . co  m*/
 * @param args
 *            Command-line arguments
 * @throws IOException
 *             If an error occurs obfuscating or unobfuscating
 */
public static void main(String[] args) throws IOException {
    InputStream input = new ByteArrayInputStream(args[1].getBytes());
    StringBuilder toPrint = new StringBuilder();
    if (args[0].startsWith("o")) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        OutputStream out = obfuscate(bytes);
        int read = input.read();
        while (read >= 0) {
            out.write(read);
            read = input.read();
        }
        byte[] receiptBytes = bytes.toByteArray();
        for (int b = 0; b < receiptBytes.length; b++) {
            int chr = (receiptBytes[b] + 256) % 256;
            toPrint.append(HEX_CHARS[chr >>> 4]);
            toPrint.append(HEX_CHARS[chr & 0xf]);
        }
    } else if (args[0].startsWith("u")) {
        input = unobfuscate(input);
        InputStreamReader reader = new InputStreamReader(input);

        int read = reader.read();
        while (read >= 0) {
            toPrint.append((char) read);
            read = reader.read();
        }
    } else
        throw new IllegalArgumentException("First argument must start with o or u");
    System.out.println(toPrint.toString());
}

From source file:net.padaf.xmpbox.parser.XMLValueTypeDescriptionManager.java

/**
 * Sample of using to write/read information
 * /*from w  w w  .  jav  a2s.  com*/
 * @param args
 *            not used
 * @throws BuildPDFAExtensionSchemaDescriptionException
 *             When errors during building/reading xml file
 */
public static void main(String[] args) throws BuildPDFAExtensionSchemaDescriptionException {
    XMLValueTypeDescriptionManager vtMaker = new XMLValueTypeDescriptionManager();

    // add Descriptions
    for (int i = 0; i < 3; i++) {
        vtMaker.addValueTypeDescription("testType" + i, "nsURI" + i, "prefix" + i, "description" + i);

    }
    List<FieldDescription> fieldSample = new ArrayList<FieldDescription>();
    for (int i = 0; i < 2; i++) {
        fieldSample.add(new FieldDescription("fieldName" + i, "valueType" + i, "description" + i));
    }
    vtMaker.addValueTypeDescription("testTypeField", "http://test.withfield.com/vt/", "prefTest",
            " value type description", fieldSample);

    // Display XML conversion
    System.out.println("Display XML Result:");
    vtMaker.toXML(System.out);

    // Sample to show how to build object from XML file
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    vtMaker.toXML(bos);
    IOUtils.closeQuietly(bos);

    // emulate a new reading
    InputStream is = new ByteArrayInputStream(bos.toByteArray());
    vtMaker = new XMLValueTypeDescriptionManager();
    vtMaker.loadListFromXML(is);
    List<ValueTypeDescription> result = vtMaker.getValueTypesDescriptionList();
    System.out.println();
    System.out.println();
    System.out.println("Result of XML Loading :");
    for (ValueTypeDescription propertyDescription : result) {
        System.out.println(propertyDescription.getType() + " :" + propertyDescription.getDescription());
        if (propertyDescription.getFields() != null) {
            Iterator<FieldDescription> fit = propertyDescription.getFields().iterator();
            FieldDescription field;
            while (fit.hasNext()) {
                field = fit.next();
                System.out.println("Field " + field.getName() + " :" + field.getValueType());
            }
        }
    }

}

From source file:com.javacreed.examples.sql.Example4.java

public static void main(final String[] args) throws Exception {
    try (BasicDataSource dataSource = DatabaseUtils.createDataSource();
            Connection connection = dataSource.getConnection()) {
        final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") {

            @Override/*  ww w .j  av a  2s .  c  om*/
            protected String parseRow(final ResultSet resultSet) throws Exception {
                try (InputStream in = new LZ4BlockInputStream(
                        CryptoUtils.wrapInToCipheredInputStream(resultSet.getBinaryStream("compressed")))) {
                    return IOUtils.toString(in, "UTF-8");
                }
            }

            @Override
            protected void setPreparedStatement(final String data, final PreparedStatement statement)
                    throws Exception {
                final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length());
                try (OutputStream out = new LZ4BlockOutputStream(
                        CryptoUtils.wrapInToCipheredOutputStream(baos))) {
                    out.write(data.getBytes("UTF-8"));
                }
                statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray()));
            }

        };
        test.runTest();
    }
    Example4.LOGGER.debug("Done");
}

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

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

    Options options = createOptions();//from   w w w  . j  a  va  2s  . c  om
    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:ID.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    ID id = new ID();
    List employees = new ArrayList();
    employees.add(new Employee("A", id));
    employees.add(new Employee("B", id));
    employees.add(new Employee("C", id));
    System.out.println("employees: " + employees);
    ByteArrayOutputStream buf1 = new ByteArrayOutputStream();
    ObjectOutputStream o1 = new ObjectOutputStream(buf1);
    o1.writeObject(employees);//from w w  w. j a va2 s. c  o  m
    o1.writeObject(employees);

    ByteArrayOutputStream buf2 = new ByteArrayOutputStream();
    ObjectOutputStream o2 = new ObjectOutputStream(buf2);
    o2.writeObject(employees);

    ObjectInputStream in1 = new ObjectInputStream(new ByteArrayInputStream(buf1.toByteArray()));
    ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(buf2.toByteArray()));
    List emp1 = (List) in1.readObject(), emp2 = (List) in1.readObject(), emp3 = (List) in2.readObject();
    System.out.println("emp1: " + emp1);
    System.out.println("emp2: " + emp2);
    System.out.println("emp3: " + emp3);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    InputStream is = new FileInputStream("test.xml");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document oldDoc = builder.parse(is);
    Node oldRoot = oldDoc.getDocumentElement();
    Document newDoc = builder.newDocument();
    Element newRoot = newDoc.createElement("newroot");
    newDoc.appendChild(newRoot);/*from w  ww.  j  a  v  a2 s  .  c  o m*/
    newRoot.appendChild(newDoc.importNode(oldRoot, true));

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DOMSource domSource = new DOMSource(newDoc);
    Writer writer = new OutputStreamWriter(out);
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.transform(domSource, result);
    writer.flush();

    InputStream isNewXML = new ByteArrayInputStream(out.toByteArray());
}

From source file:de.serverfrog.pw.crypt.SerpentUtil.java

/**
 * Print all Security providers and their algos
 *
 * @param args args/*w w  w.j  a  va2s  .co  m*/
 * @throws Exception Exception
 */
public static void main(String[] args) throws Exception {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    SecretKeySpec keySpec = new SecretKeySpec("test".getBytes("UTF-8"), "AES");
    try (CipherOutputStream outputStream = SerpentUtil.getOutputStream(byteArrayOutputStream, keySpec)) {
        IOUtils.write("TEST", outputStream);
    }
    System.out.println(Arrays.toString(byteArrayOutputStream.toByteArray()));
    System.out.println(byteArrayOutputStream.toString("UTF-8"));
    byte[] toByteArray = byteArrayOutputStream.toByteArray();
    ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(toByteArray);
    CipherInputStream inputStream = SerpentUtil.getInputStream(arrayInputStream,
            new SecretKeySpec("test".getBytes("UTF-8"), "AES"));
    byte[] bytes = new byte[1048576];

    IOUtils.read(inputStream, bytes);

    System.out.println(new String(bytes, "UTF-8").trim());

    //
    //        for (Provider provider : Security.getProviders()) {
    //            System.out.println("");
    //            System.out.println("");
    //            System.out.println("");
    //            System.out.println("-------------------------------");
    //            System.out.println("Name: " + provider.getName());
    //            System.out.println("Info: " + provider.getInfo());
    //            for (Map.Entry<Object, Object> entry : provider.entrySet()) {
    //                System.out.println("Key: Class:" + entry.getKey().getClass() + " String: " + entry.getKey());
    //                System.out.println("Value: Class:" + entry.getValue().getClass() + " String: " + entry.getValue());
    //            }
    //            for (Provider.Service service : provider.getServices()) {
    //                System.out.println("Service: Algorithm:" + service.getAlgorithm()
    //                        + " ClassName:" + service.getClassName()
    //                        + " Type:" + service.getType() + " toString:" + service.toString());
    //            }
    //            for (Object object : provider.values()) {
    //                System.out.println("Value: " + object.getClass() + " toString:" + object.toString());
    //
    //            }
    //            System.out.println("-------------------------------");
    //        }
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step5LinguisticPreprocessing.java

public static void main(String[] args) throws Exception {
    // input dir - list of xml query containers
    // step4-boiler-plate/
    File inputDir = new File(args[0]);

    // output dir
    File outputDir = new File(args[1]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();//  www  .  j  av a 2 s . com
    }

    // iterate over query containers
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));

        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            //                System.out.println(rankedResults.plainText);

            if (rankedResults.plainText != null) {
                String[] lines = StringUtils.split(rankedResults.plainText, "\n");

                // collecting all cleaned lines
                List<String> cleanLines = new ArrayList<>(lines.length);
                // collecting line tags
                List<String> lineTags = new ArrayList<>(lines.length);

                for (String line : lines) {
                    // get the tag
                    String tag = null;
                    Matcher m = OPENING_TAG_PATTERN.matcher(line);

                    if (m.find()) {
                        tag = m.group(1);
                    }

                    if (tag == null) {
                        throw new IllegalArgumentException("No html tag found for line:\n" + line);
                    }

                    // replace the tag at the beginning and the end
                    String noTagText = line.replaceAll("^<\\S+>", "").replaceAll("</\\S+>$", "");

                    // do some html cleaning
                    noTagText = noTagText.replaceAll("&nbsp;", " ");

                    noTagText = noTagText.trim();

                    // add to the output
                    if (!noTagText.isEmpty()) {
                        cleanLines.add(noTagText);
                        lineTags.add(tag);
                    }
                }

                if (cleanLines.isEmpty()) {
                    // the document is empty
                    System.err.println("Document " + rankedResults.clueWebID + " in query "
                            + queryResultContainer.qID + " is empty");
                } else {
                    // now join them back to paragraphs
                    String text = StringUtils.join(cleanLines, "\n");

                    // create JCas
                    JCas jCas = JCasFactory.createJCas();
                    jCas.setDocumentText(text);
                    jCas.setDocumentLanguage("en");

                    // annotate WebParagraph
                    SimplePipeline.runPipeline(jCas,
                            AnalysisEngineFactory.createEngineDescription(WebParagraphAnnotator.class));

                    // fill the original tag information
                    List<WebParagraph> webParagraphs = new ArrayList<>(
                            JCasUtil.select(jCas, WebParagraph.class));

                    // they must be the same size as original ones
                    if (webParagraphs.size() != lineTags.size()) {
                        throw new IllegalStateException(
                                "Different size of annotated paragraphs and original lines");
                    }

                    for (int i = 0; i < webParagraphs.size(); i++) {
                        WebParagraph p = webParagraphs.get(i);
                        // get tag
                        String tag = lineTags.get(i);

                        p.setOriginalHtmlTag(tag);
                    }

                    SimplePipeline.runPipeline(jCas,
                            AnalysisEngineFactory.createEngineDescription(StanfordSegmenter.class,
                                    // only on existing WebParagraph annotations
                                    StanfordSegmenter.PARAM_ZONE_TYPES, WebParagraph.class.getCanonicalName()));

                    // now convert to XMI
                    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
                    XmiCasSerializer.serialize(jCas.getCas(), byteOutputStream);

                    // encode to base64
                    String encoded = new BASE64Encoder().encode(byteOutputStream.toByteArray());

                    rankedResults.originalXmi = encoded;
                }
            }
        }

        // and save the query to output dir
        File outputFile = new File(outputDir, queryResultContainer.qID + ".xml");
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);

    MessageDigest md = MessageDigest.getInstance("MD5");
    SomeObject testObject = new SomeObject();

    dos.writeInt(testObject.count);//from w w  w.j ava2  s  .com
    dos.writeLong(testObject.product);
    dos.writeDouble(testObject.stdDev);
    dos.writeUTF(testObject.name);
    dos.writeChar(testObject.delimiter);
    dos.flush();

    byte[] hashBytes = md.digest(baos.toByteArray());
    BigInteger testObjectHash = new BigInteger(hashBytes);

    System.out.println("Hash " + testObjectHash);

    dos.close();

}