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:net.daporkchop.porkbot.util.HTTPUtils.java

/**
 * Performs a POST request to the specified URL and returns the result.
 * <p/>//  w  w  w . j a  v a2 s .  c  o  m
 * The POST data will be encoded in UTF-8 as the specified contentType. The response will be parsed as UTF-8.
 * If the server returns an error but still provides a body, the body will be returned as normal.
 * If the server returns an error without any body, a relevant {@link java.io.IOException} will be thrown.
 *
 * @param url         URL to submit the POST request to
 * @param post        POST data in the correct format to be submitted
 * @param contentType Content type of the POST data
 * @return Raw text response from the server
 * @throws IOException The request was not successful
 */
public static String performPostRequestWithAuth(@NonNull URL url, @NonNull String post,
        @NonNull String contentType, @NonNull String auth) throws IOException {
    final HttpURLConnection connection = createUrlConnection(url);
    final byte[] postAsBytes = post.getBytes(Charsets.UTF_8);

    connection.setRequestProperty("Authorization", auth);
    connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
    connection.setRequestProperty("Content-Length", "" + postAsBytes.length);
    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        IOUtils.write(postAsBytes, outputStream);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    return sendRequest(connection);
}

From source file:com.openkm.misc.TemplateTest.java

public void testHtml() throws IOException, TemplateException {
    log.debug("testHtml()");
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("okp_tpl_name", "el nombre");
    model.put("okp_tpl_bird_date", new Date());
    model.put("okp_tpl_language", "el lenguaje");
    InputStream input = new FileInputStream(BASE_DIR + "/templates/sample.html");
    OutputStream output = new FileOutputStream(BASE_DIR + "/templates/sample_out.html");
    String in = IOUtils.toString(input);
    String out = TemplateUtils.replace("sample", in, model);
    IOUtils.write(out, output);
    input.close();//from   w ww.  j  ava2s .  com
    output.close();
}

From source file:de.banapple.maven.antlr.SyntaxDiagramMojo.java

/**
 * Creates an index file in the output directory containing all
 * generated images./*from  ww w.  jav a  2  s  . com*/
 */
private void createIndex() {
    /* retrieve all png files */
    String[] imageFilenames = outputDirectory.list(new FilenameFilter() {
        public boolean accept(File dir, String filename) {
            return filename.endsWith("png");
        }
    });

    /* sort filenames by lower case first */
    Arrays.sort(imageFilenames);

    StringBuilder content = new StringBuilder();
    content.append("<html>");
    content.append("<body>");

    /* table of contents */
    content.append("<a name=\"top\" />");
    content.append("<ol>");
    for (String filename : imageFilenames) {
        String name = filename.substring(0, filename.length() - 4);
        content.append("<li>").append("<a href=\"#").append(name).append("\">").append(name).append("</a>")
                .append("</li>");
    }
    content.append("</ol>");

    /* images */
    for (String filename : imageFilenames) {
        String name = filename.substring(0, filename.length() - 4);
        content.append("<h2>").append(name).append("</h2>");
        content.append("<a name=\"").append(name).append("\" />");
        content.append("<img src=\"").append(filename).append("\" />");
        content.append("<br/><a href=\"#top\">up</a>");
    }
    content.append("</body>");
    content.append("</html>");

    File indexFile = new File(outputDirectory, "index.html");
    try {
        IOUtils.write(content.toString(), new FileOutputStream(indexFile));
    } catch (Exception e) {
        getLog().error("failed to generate index file", e);
        throw new RuntimeException(e);
    }
}

From source file:ctrus.pa.bow.core.Vocabulary.java

public final void writeDocVocabularyTo(OutputStream out) throws IOException {
    IOUtils.write("DOC_REF,DOC_NAME\n", out);
    for (String docref : _docVocabulary.keySet()) {
        DocMeta d = _docVocabulary.get(docref);
        IOUtils.write(docref + "," + d.file_name + "\n", out);
    }/*from   www. j ava2  s  . c o  m*/
}

From source file:com.thoughtworks.go.server.controller.GoConfigAdministrationController.java

@RequestMapping(value = "/admin/restful/configuration/file/GET/historical-xml", method = RequestMethod.GET)
public void getConfigRevision(@RequestParam(value = "version", required = true) String version,
        HttpServletResponse response) throws Exception {
    GoConfigRevision configRevision = goConfigService.getConfigAtVersion(version);
    String md5 = configRevision.getMd5();
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("text/xml");
    response.setCharacterEncoding("utf-8");
    response.setHeader(X_CRUISE_CONFIG_MD5, md5);
    if (configRevision.isByteArrayBacked()) {
        IOUtils.write(configRevision.getConfigXmlBytes(), response.getOutputStream());
    } else {//from   ww w  .j a  v  a 2 s . c  o  m
        response.getWriter().write(configRevision.getContent());
    }
}

From source file:com.streamsets.datacollector.restapi.AdminResource.java

@POST
@Path("/appToken")
@ApiOperation(value = "Update Application Token SDC", authorizations = @Authorization(value = "basic"))
@Produces(MediaType.APPLICATION_JSON)/*from www.jav a2s .com*/
@RolesAllowed({ AuthzRole.ADMIN, AuthzRole.ADMIN_REMOTE })
public Response updateAppToken(String authToken) throws IOException {
    DataStore dataStore = new DataStore(new File(runtimeInfo.getConfigDir(), APP_TOKEN_FILE));
    try (OutputStream os = dataStore.getOutputStream()) {
        IOUtils.write(authToken, os);
        dataStore.commit(os);
    } finally {
        dataStore.release();
        dataStore.close();
    }
    return Response.ok().build();
}

From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.PosterImageServlet.java

/**
 * Returns poster image/*from   www .j a v a 2  s. c o m*/
 *
 * @param request the request
 * @param response the response
 * @throws ServletException the servlet exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String sIdProduct = request.getParameter(PARAMETER_PRODUCT_ID);

    if (StringUtils.isNotEmpty(sIdProduct)) {
        Integer idProduct = Integer.parseInt(sIdProduct);
        boolean isThumbnail = (request.getParameter(PARAMETER_TB) != null)
                && request.getParameter(PARAMETER_TB).equals(String.valueOf(true));
        byte[] bImage;

        if (isThumbnail) {
            bImage = _productService.getTbImage(idProduct);
        } else {
            bImage = _productService.getImage(idProduct);
        }

        response.setContentLength(bImage.length);
        response.setContentType(CONTENT_TYPE_IMAGE_JPEG);

        ServletOutputStream os = response.getOutputStream();
        IOUtils.write(bImage, os);
        os.flush();
        os.close();
    } else {
        LOGGER.error(ERROR_MESSAGE);
    }
}

From source file:com.marcolotz.lung.debug.InputTester.java

/***
 * Writes the byte content of the input stream to the local file system.
 * @param filePath//from   ww  w.j av  a 2  s.c  o m
 * @param outputContent
 */
public void generateLocalOutput(String filePath, byte[] outputContent) {
    try {
        FileOutputStream output = new FileOutputStream(new File(filePath));
        IOUtils.write(outputContent, output);
    } catch (IOException e) {
        System.err.println("Error during debug output process.");
        e.printStackTrace();
    }
}

From source file:ch.cyberduck.core.cryptomator.SingleTransferWorkerTest.java

@Test
public void testUpload() throws Exception {
    final Host host = new Host(new DAVProtocol(), "test.cyberduck.ch",
            new Credentials(System.getProperties().getProperty("webdav.user"),
                    System.getProperties().getProperty("webdav.password")));
    host.setDefaultPath("/dav/basic");
    final DAVSession session = new DAVSession(host);
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path home = new DefaultHomeFinderService(session).find();
    final Path vault = new Path(home, new AlphanumericRandomStringService().random(),
            EnumSet.of(Path.Type.directory));
    final Path dir1 = new Path(vault, new AlphanumericRandomStringService().random(),
            EnumSet.of(Path.Type.directory));
    final Local localDirectory1 = new Local(System.getProperty("java.io.tmpdir"),
            new AlphanumericRandomStringService().random());
    localDirectory1.mkdir();/*from ww  w .  j  a v  a 2s. co m*/
    final byte[] content = RandomUtils.nextBytes(62768);
    final Path file1 = new Path(dir1, new AlphanumericRandomStringService().random(),
            EnumSet.of(Path.Type.file));
    final Local localFile1 = new Local(localDirectory1, file1.getName());
    final OutputStream out1 = localFile1.getOutputStream(false);
    IOUtils.write(content, out1);
    out1.close();
    final Path file2 = new Path(dir1, new AlphanumericRandomStringService().random(),
            EnumSet.of(Path.Type.file));
    final Local localFile2 = new Local(localDirectory1, file2.getName());
    final OutputStream out2 = localFile2.getOutputStream(false);
    IOUtils.write(content, out2);
    out2.close();
    final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore());
    cryptomator.create(session, null, new VaultCredentials("test"));
    session.withRegistry(new DefaultVaultRegistry(new DisabledPasswordStore(), new PasswordCallback() {
        @Override
        public Credentials prompt(final Host bookmark, final String title, final String reason,
                final LoginOptions options) throws LoginCanceledException {
            return new VaultCredentials("test");
        }
    }));
    PreferencesFactory.get().setProperty("factory.vault.class", CryptoVault.class.getName());
    final Transfer t = new UploadTransfer(new Host(new TestProtocol()),
            Collections.singletonList(new TransferItem(dir1, localDirectory1)), new NullFilter<>());
    assertTrue(new SingleTransferWorker(session, session, t, new TransferOptions(), new TransferSpeedometer(t),
            new DisabledTransferPrompt() {
                @Override
                public TransferAction prompt(final TransferItem file) {
                    return TransferAction.overwrite;
                }
            }, new DisabledTransferErrorCallback(), new DisabledProgressListener(),
            new DisabledStreamListener(), new DisabledLoginCallback(), new DisabledPasswordCallback()) {

    }.run(session, session));
    assertTrue(new CryptoFindFeature(session, new DAVFindFeature(session), cryptomator).find(dir1));
    assertEquals(content.length,
            new CryptoAttributesFeature(session, new DAVAttributesFinderFeature(session), cryptomator)
                    .find(file1).getSize());
    {
        final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length);
        final InputStream in = new CryptoReadFeature(session, new DAVReadFeature(session), cryptomator)
                .read(file1, new TransferStatus().length(content.length), new DisabledConnectionCallback());
        new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(in, buffer);
        assertArrayEquals(content, buffer.toByteArray());
    }
    assertEquals(content.length,
            new CryptoAttributesFeature(session, new DAVAttributesFinderFeature(session), cryptomator)
                    .find(file2).getSize());
    {
        final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length);
        final InputStream in = new CryptoReadFeature(session, new DAVReadFeature(session), cryptomator)
                .read(file1, new TransferStatus().length(content.length), new DisabledConnectionCallback());
        new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(in, buffer);
        assertArrayEquals(content, buffer.toByteArray());
    }
    new CryptoDeleteFeature(session, new DAVDeleteFeature(session), cryptomator).delete(
            Arrays.asList(file1, file2, dir1, vault), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    localFile1.delete();
    localFile2.delete();
    localDirectory1.delete();
}

From source file:com.google.mr4c.sources.MetafilesDatasetSource.java

public synchronized void writeDataset(Dataset dataset, WriteMode writeMode) throws IOException {
    if (writeMode == WriteMode.FILES_ONLY) {
        return; // nothing to do yet

    }/*from  ww w  . jav  a 2 s  .c o m*/
    s_log.info("Begin writing dataset");
    DataKey key = DataKeyFactory.newKey();
    MetadataMap map = dataset.getMetadata(key);
    if (map == null) {
        throw new IOException("Missing metadata map");
    }
    for (String name : map.getMap().keySet()) {
        s_log.info("Begin writing metadata item {}", name);
        MetadataElement element = map.getMap().get(name);
        MetadataElementType type = element.getMetadataElementType();
        if (type != MetadataElementType.FIELD) {
            throw new IOException(String.format(
                    "Element [%s] is type %s in metafiles dataset; all elements must be FIELD with String content",
                    name, type));
        }
        MetadataField field = (MetadataField) map.getMap().get(name);
        String content = field.getValue().toString();
        DataFileSink sink = m_fileSrc.getFileSink(name);
        OutputStream output = sink.getFileOutputStream();
        try {
            IOUtils.write(content, output);
        } finally {
            output.close();
        }
        s_log.info("Done writing metadata item {}", name);
    }
    s_log.info("Done writing dataset");
}