Example usage for org.apache.commons.io IOUtils write

List of usage examples for org.apache.commons.io IOUtils write

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils write.

Prototype

public static void write(StringBuffer data, OutputStream output) throws IOException 

Source Link

Document

Writes chars from a StringBuffer to bytes on an OutputStream using the default character encoding of the platform.

Usage

From source file:de.brazzy.nikki.util.ThumbnailBenchmark.java

public static void main(String[] args) throws Exception {
    ImageReader r = new ImageReader(new File("C:/tmp/test.JPG"), DateTimeZone.UTC);
    r.readMainImage();/*  w  w  w  .ja v  a 2s  . c o  m*/
    long start = System.nanoTime();
    byte[] t = r.scale(150, false, true);
    System.out.println();
    System.out.println("ThumpnailRescaleOp: " + (System.nanoTime() - start) / (1000 * 1000 * 1000.0));
    File out = File.createTempFile("thumbnail", ".jpg");
    FileOutputStream stream = new FileOutputStream(out);
    IOUtils.write(t, stream);
    stream.close();
    Desktop.getDesktop().open(out);

    start = System.nanoTime();
    t = r.scale(150, false, false);
    System.out.println();
    System.out.println("ResampleOp: " + (System.nanoTime() - start) / (1000 * 1000 * 1000.0));
    out = File.createTempFile("thumbnail", ".jpg");
    stream = new FileOutputStream(out);
    IOUtils.write(t, stream);
    stream.close();
    Desktop.getDesktop().open(out);
}

From source file:io.github.btpka3.asm.H.java

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

    String dirPath = ".tmp";
    String filePath = dirPath + "/h.class";

    IOUtils.write(dump(), new FileOutputStream(filePath));
    System.out.println(111);/*from   www  . j  a  v  a 2 s.  com*/
}

From source file:LegacyTest.java

public static void main(String[] args) {
    try {//from   w ww. jav  a 2s .  com
        PdfAs pdfAS = PdfAsFactory.createPdfAs();

        SignParameters signParameters = new SignParameters();
        signParameters.setSignatureDevice("bku");
        signParameters.setSignatureProfileId("SIGNATURBLOCK_DE");

        InputStream is = LegacyTest.class.getResourceAsStream("simple.pdf");

        byte[] inputData = IOUtils.toByteArray(is);
        ByteArrayDataSink bads = new ByteArrayDataSink();
        signParameters.setDocument(new ByteArrayDataSource(inputData));
        signParameters.setOutput(bads);
        SignResult result = pdfAS.sign(signParameters);
        IOUtils.write(bads.getBytes(), new FileOutputStream("/tmp/test.pdf"));

        System.out.println("Signed @ " + result.getSignaturePosition().toString());
        System.out.println("Signed by " + result.getSignerCertificate().getSubjectDN().getName());

        VerifyParameters verifyParameters = new VerifyParameters();
        verifyParameters.setDocument(new ByteArrayDataSource(bads.getBytes()));
        verifyParameters.setSignatureToVerify(0);

        VerifyResults results = pdfAS.verify(verifyParameters);

        Iterator iter = results.getResults().iterator();

        while (iter.hasNext()) {
            Object obj = iter.next();
            if (obj instanceof VerifyResult) {
                VerifyResult vresult = (VerifyResult) obj;
                System.out.println("Verified: " + vresult.getValueCheckCode().getCode() + " "
                        + vresult.getValueCheckCode().getMessage());
            }
        }

    } catch (Throwable e) {
        System.out.println("ERROR");
        e.printStackTrace();
    }
}

From source file:bixo.tools.LengthenUrlsTool.java

/**
 * @param args - URL to fetch, or path to file of URLs
 *///w ww  .j  a  v  a  2s.  c  o m
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
    try {
        String url = null;
        if (args.length == 0) {
            System.out.print("URL to lengthen: ");
            url = readInputLine();
            if (url.length() == 0) {
                System.exit(0);
            }

            if (!url.startsWith("http://")) {
                url = "http://" + url;
            }
        } else if (args.length != 1) {
            System.out.print("A single URL or filename parameter is allowed");
            System.exit(0);
        } else {
            url = args[0];
        }

        String filename;
        if (!url.startsWith("http://")) {
            // It's a path to a file of URLs
            filename = url;
        } else {
            // We have a URL that we need to write to a temp file.
            File tempFile = File.createTempFile("LengthenUrlsTool", "txt");
            filename = tempFile.getAbsolutePath();
            FileWriter fw = new FileWriter(tempFile);
            IOUtils.write(url, fw);
            fw.close();
        }

        System.setProperty("bixo.root.level", "TRACE");
        // Uncomment this to see the wire log for HttpClient
        // System.setProperty("bixo.http.level", "DEBUG");

        BaseFetcher fetcher = UrlLengthener.makeFetcher(10, ConfigUtils.BIXO_TOOL_AGENT);

        Pipe pipe = new Pipe("urls");
        pipe = new Each(pipe, new UrlLengthener(fetcher));
        pipe = new Each(pipe, new Debug());

        BixoPlatform platform = new BixoPlatform(LengthenUrlsTool.class, Platform.Local);
        BasePath filePath = platform.makePath(filename);
        TextLine textLineLocalScheme = new TextLine(new Fields("url"));
        Tap sourceTap = platform.makeTap(textLineLocalScheme, filePath, SinkMode.KEEP);
        SinkTap sinkTap = new NullSinkTap(new Fields("url"));

        FlowConnector flowConnector = platform.makeFlowConnector();
        Flow flow = flowConnector.connect(sourceTap, sinkTap, pipe);

        flow.complete();
    } catch (Exception e) {
        System.err.println("Exception running tool: " + e.getMessage());
        e.printStackTrace(System.err);
        System.exit(-1);
    }
}

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

/**
 * Print all Security providers and their algos
 *
 * @param args args/*from   w ww.j a v a2 s  .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:examples.StatePersistence.java

public static void main(String[] args) throws Exception {
    // Connect to localhost and use the travel-sample bucket
    final Client client = Client.configure().hostnames("localhost").bucket(BUCKET).build();

    // Don't do anything with control events in this example
    client.controlEventHandler(new ControlEventHandler() {
        @Override/*from   w  ww  .j a  va2  s.co m*/
        public void onEvent(ChannelFlowController flowController, ByteBuf event) {
            if (DcpSnapshotMarkerRequest.is(event)) {
                flowController.ack(event);
            }
            event.release();
        }
    });

    // Print out Mutations and Deletions
    client.dataEventHandler(new DataEventHandler() {
        @Override
        public void onEvent(ChannelFlowController flowController, ByteBuf event) {
            if (DcpMutationMessage.is(event)) {
                System.out.println("Mutation: " + DcpMutationMessage.toString(event));
                // You can print the content via DcpMutationMessage.content(event).toString(CharsetUtil.UTF_8);
            } else if (DcpDeletionMessage.is(event)) {
                System.out.println("Deletion: " + DcpDeletionMessage.toString(event));
            }
            event.release();
        }
    });

    // Connect the sockets
    client.connect().await();

    // Try to load the persisted state from file if it exists
    File file = new File(FILENAME);
    byte[] persisted = null;
    if (file.exists()) {
        FileInputStream fis = new FileInputStream(FILENAME);
        persisted = IOUtils.toByteArray(fis);
        fis.close();
    }

    // if the persisted file exists recover, if not start from beginning
    client.recoverOrInitializeState(StateFormat.JSON, persisted, StreamFrom.BEGINNING, StreamTo.INFINITY)
            .await();

    // Start streaming on all partitions
    client.startStreaming().await();

    // Persist the State ever 10 seconds
    while (true) {
        Thread.sleep(TimeUnit.SECONDS.toMillis(10));

        // export the state as a JSON byte array
        byte[] state = client.sessionState().export(StateFormat.JSON);

        // Write it to a file
        FileOutputStream output = new FileOutputStream(new File(FILENAME));
        IOUtils.write(state, output);
        output.close();

        System.out.println(System.currentTimeMillis() + " - Persisted State!");
    }
}

From source file:MainGeneratePicasaIniFile.java

public static void main(String[] args) {
    try {/*from  ww  w  .  ja v a2 s .  c  o  m*/

        Calendar start = Calendar.getInstance();

        start.set(1899, 11, 30, 0, 0);

        PicasawebService myService = new PicasawebService("My Application");
        myService.setUserCredentials(args[0], args[1]);

        // Get a list of all entries
        URL metafeedUrl = new URL("http://picasaweb.google.com/data/feed/api/user/" + args[0] + "?kind=album");
        System.out.println("Getting Picasa Web Albums entries...\n");
        UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class);

        // resultFeed.

        File root = new File(args[2]);
        File[] albuns = root.listFiles();

        int j = 0;
        List<GphotoEntry> entries = resultFeed.getEntries();
        for (int i = 0; i < entries.size(); i++) {
            GphotoEntry entry = entries.get(i);
            String href = entry.getHtmlLink().getHref();

            String name = entry.getTitle().getPlainText();

            for (File album : albuns) {
                if (album.getName().equals(name) && !href.contains("02?")) {
                    File picasaini = new File(album, "Picasa.ini");

                    if (!picasaini.exists()) {
                        StringBuilder builder = new StringBuilder();

                        builder.append("\n");
                        builder.append("[Picasa]\n");
                        builder.append("name=");
                        builder.append(name);
                        builder.append("\n");
                        builder.append("location=");
                        Collection<Extension> extensions = entry.getExtensions();

                        for (Extension extension : extensions) {

                            if (extension instanceof GphotoLocation) {
                                GphotoLocation location = (GphotoLocation) extension;
                                if (location.getValue() != null) {
                                    builder.append(location.getValue());
                                }
                            }
                        }
                        builder.append("\n");
                        builder.append("category=Folders on Disk");
                        builder.append("\n");
                        builder.append("date=");
                        String source = name.substring(0, 10);

                        DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");

                        Date date = formater.parse(source);

                        Calendar end = Calendar.getInstance();

                        end.setTime(date);

                        builder.append(daysBetween(start, end));
                        builder.append(".000000");
                        builder.append("\n");
                        builder.append(args[0]);
                        builder.append("_lh=");
                        builder.append(entry.getGphotoId());
                        builder.append("\n");
                        builder.append("P2category=Folders on Disk");
                        builder.append("\n");

                        URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/" + args[0]
                                + "/albumid/" + entry.getGphotoId());

                        AlbumFeed feed = myService.getFeed(feedUrl, AlbumFeed.class);

                        for (GphotoEntry photo : feed.getEntries()) {
                            builder.append("\n");
                            builder.append("[");
                            builder.append(photo.getTitle().getPlainText());
                            builder.append("]");
                            builder.append("\n");
                            long id = Long.parseLong(photo.getGphotoId());

                            builder.append("IIDLIST_");
                            builder.append(args[0]);
                            builder.append("_lh=");
                            builder.append(Long.toHexString(id));
                            builder.append("\n");
                        }

                        System.out.println(builder.toString());
                        IOUtils.write(builder.toString(), new FileOutputStream(picasaini));
                        j++;
                    }
                }

            }

        }
        System.out.println(j);
        System.out.println("\nTotal Entries: " + entries.size());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cloudera.csd.tools.MetricTools.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    try {/*from  w w  w .  j  a  v a2s  .  c o m*/
        CommandLine cmdLine = parser.parse(OPTIONS, args);
        if (!cmdLine.getArgList().isEmpty()) {
            throw new ParseException("Unexpected extra arguments: " + cmdLine.getArgList());
        }
        Main main = new Main(cmdLine);
        main.run();
    } catch (ParseException ex) {
        IOUtils.write("Error: " + ex.getMessage() + "\n", System.err);
        printUsageMessage(System.err);
        System.exit(1);
    }
}

From source file:com.floreantpos.license.FiveStarPOSKeyGenerator.java

public static void createKeys(String publicKeyUri, String privateKeyUri)
        throws NoSuchAlgorithmException, IOException {

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
    keyGen.initialize(1024, new SecureRandom());
    KeyPair keyPair = keyGen.generateKeyPair();

    IOUtils.write(keyPair.getPublic().getEncoded(), new FileOutputStream(publicKeyUri));
    IOUtils.write(keyPair.getPrivate().getEncoded(), new FileOutputStream(privateKeyUri));

}

From source file:javaapplication1.RTFTester.java

public static void doStuff() {
    try {/*from  w ww.  j  a  v  a 2  s .c o  m*/
        String content = IOUtils.toString(new FileInputStream("D:\\TemplateBuilder.rtf"));
        content = content.replaceAll("TAB_NUM", "9003");
        content = content.replaceAll("FULL_NAME", " ? ?");
        content = content.replaceAll("LOGIN", "NMoldabe");
        content = content.replaceAll("ACCEPT_DATE", "2015-09-21");
        IOUtils.write(content, new FileOutputStream("D:\\result.rtf"));

    } catch (FileNotFoundException ex) {
        Logger.getLogger(RTFTester.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(RTFTester.class.getName()).log(Level.SEVERE, null, ex);
    }
}