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:com.streamsets.pipeline.kafka.impl.TestSaslEnabledKafka.java

@BeforeClass
public static void beforeClass() throws Exception {
    testDir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
    Assert.assertTrue(testDir.mkdirs());

    File kdcDir = new File(testDir, KDC);
    Assert.assertTrue(kdcDir.mkdirs());//  w  w  w .  j a v  a  2s.co m
    keytabFile = new File(testDir, TEST_KEYTAB);

    miniKdc = new MiniKdc(MiniKdc.createConf(), kdcDir);
    miniKdc.start();
    miniKdc.createPrincipal(keytabFile, KAFKA_BROKER_PRINCIPAL, KAFKA_CLIENT_PRINCIPAL);

    jaasConfigFile = new File(testDir, KAFKA_JAAS_CONF);
    jaasConfigFile.createNewFile();
    jaasConfigFile.setReadable(true);
    String jaasConf = JAAS_CONF.replaceAll("keyTabFile", keytabFile.getAbsolutePath());
    FileOutputStream outputStream = new FileOutputStream(jaasConfigFile);
    IOUtils.write(jaasConf, outputStream);
    outputStream.close();

    plainTextPort = TestUtil.getFreePort();
    securePort = TestUtil.getFreePort();

    // reload configuration when getConfiguration is called next
    Configuration.setConfiguration(null);
    System.setProperty(JAVA_SECURITY_AUTH_LOGIN_CONFIG, jaasConfigFile.getAbsolutePath());

    TestSecureKafkaBase.beforeClass();
}

From source file:de.knurt.fam.template.controller.letter.LetterGeneratorEMailLetter.java

public ModelAndView process(HttpServletResponse response, TemplateResource tr) {
    // prepare result
    JSONObject result = new JSONObject();

    EMailLetterAdapter ema = new EMailLetterAdapter(tr);
    String customid = tr.getAuthUser().getUsername() + "-m";
    PostMethod post = new LetterFromHttpServletRequestToPostMethod(customid).process(tr.getRequest());
    String errormessage = ema.send(post, customid);

    try {/*from  www .jav a  2  s  . c  o  m*/

        if (errormessage.isEmpty()) {
            result.put("succ", true);

            InvoiceBookingResolver lgub = new InvoiceBookingResolver(tr);
            result.put("invoiced", lgub.invoice());
        } else {
            result.put("errormessage", errormessage);
            result.put("succ", false);
        }
    } catch (JSONException e) {
        FamLog.exception(e, 201106131728l);
    }

    // response answer
    PrintWriter pw = null;
    try {
        response.setHeader("Content-type", "application/json");
        pw = response.getWriter();
        IOUtils.write(result.toString(), pw);
    } catch (IOException ex) {
        FamLog.exception(ex, 201106131727l);
    } finally {
        IOUtils.closeQuietly(pw);
    }
    return null;
}

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 av 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 performPostRequest(@NonNull URL url, @NonNull String post, @NonNull String contentType)
        throws IOException {
    final HttpURLConnection connection = createUrlConnection(url);
    final byte[] postAsBytes = post.getBytes(Charsets.UTF_8);

    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.truebanana.cache.AbstractDiskLruCache.java

private boolean writeToFile(byte[] data, OutputStream os) {
    try {/*from w ww .  jav  a 2 s  . c  o m*/
        IOUtils.write(data, os);
        os.flush();
        os.close();
        Log.d("AbstractDiskLruCache", "Write file to disk successful");
        return true;
    } catch (IOException e) {
        Log.d("AbstractDiskLruCache", "Write file to disk failed");
        return false;
    }
}

From source file:ductive.console.jline.NonInteractiveTerminal.java

@Override
public void error(String value) throws IOException {
    IOUtils.write(new Ansi().bold().fg(Color.RED).a(value).reset().toString(), out);
}

From source file:me.springframework.di.gen.factory.BeanFactoryGenerator.java

/**
 * Generates a Java source file with everything on board to construct the application context of
 * an application./* ww  w. j  a v  a  2 s  .  com*/
 * 
 * @param destination An abstraction of where and how to generate the target output.
 * @param definitions The definitions of the object instances wired together.
 * @param details Some metadata on the BeanFactory to generate. (Typically, one of the values of
 *            {@link BeanFactoryTypes}.
 * @throws GeneratorException If - for some reason - the {@link BeanFactoryGenerator} fails to
 *             generate the desired output.
 */
public static void generate(Destination destination, me.springframework.di.Configuration definitions,
        BeanFactoryType beanFactoryType) throws GeneratorException {
    Writer writer = null;
    try {
        writer = destination.getWriter();
        IOUtils.write(process(destination, definitions, beanFactoryType), writer);
    } catch (IOException ioe) {
        throw new GeneratorException(ioe);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:de.micromata.genome.gwiki.web.StaticFileServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String uri = req.getPathInfo();
    String servletp = req.getServletPath();
    String respath = servletp + uri;
    if (uri == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from  ww  w.  ja v  a 2s.  c  om
    }

    InputStream is = getServletContext().getResourceAsStream(respath);
    if (is == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    long nt = new Date().getTime() + TimeInMillis.DAY;
    String mime = MimeUtils.getMimeTypeFromFile(respath);
    if (StringUtils.equals(mime, "application/x-shockwave-flash")) {
        resp.setHeader("Cache-Control", "cache, must-revalidate");
        resp.setHeader("Pragma", "public");
    }
    resp.setDateHeader("Expires", nt);
    resp.setHeader("Cache-Control", "max-age=86400, public");
    if (mime != null) {
        resp.setContentType(mime);
    }

    byte[] data = IOUtils.toByteArray(is);
    IOUtils.closeQuietly(is);
    resp.setContentLength(data.length);
    IOUtils.write(data, resp.getOutputStream());
}

From source file:com.norconex.importer.ImporterTest.java

@Before
public void setUp() throws Exception {
    ImporterConfig config = new ImporterConfig();
    config.setPostParseHandlers(new IDocumentTransformer[] { new IDocumentTransformer() {
        @Override/*w  w  w .  ja  v  a  2s. co  m*/
        public void transformDocument(String reference, InputStream input, OutputStream output,
                ImporterMetadata metadata, boolean parsed) throws ImporterHandlerException {
            try {
                // Clean up what we know is extra noise for a given format
                Pattern pattern = Pattern.compile("[^a-zA-Z ]", Pattern.MULTILINE);
                String txt = IOUtils.toString(input);
                txt = pattern.matcher(txt).replaceAll("");
                txt = txt.replaceAll("DowntheRabbitHole", "");
                txt = StringUtils.replace(txt, " ", "");
                txt = StringUtils.replace(txt, "httppdfreebooksorg", "");
                IOUtils.write(txt, output);
            } catch (IOException e) {
                throw new ImporterHandlerException(e);
            }
        }
    } });
    importer = new Importer(config);
}

From source file:com.hortonworks.registries.schemaregistry.avro.LocalRegistryServerHATest.java

@Before
public void startZooKeeper() throws Exception {
    testingServer = new TestingServer(true);
    URI configPath = Resources.getResource("schema-registry-test-ha.yaml").toURI();
    String fileContent = IOUtils.toString(configPath, "UTF-8");

    File registryConfigFile = File.createTempFile("ha-", ".yaml");
    registryConfigFile.deleteOnExit();/*from  ww w.j a  v a  2 s  . c  om*/
    try (FileWriter writer = new FileWriter(registryConfigFile)) {
        IOUtils.write(fileContent.replace("__zk_connect_url__", testingServer.getConnectString()), writer);
    }

    List<LocalSchemaRegistryServer> schemaRegistryServers = new ArrayList<>();
    for (int i = 1; i < 4; i++) {
        LocalSchemaRegistryServer server = new LocalSchemaRegistryServer(registryConfigFile.getAbsolutePath());
        schemaRegistryServers.add(server);
        server.start();
    }

    registryServers = Collections.unmodifiableList(schemaRegistryServers);
}

From source file:com.simiacryptus.util.io.IOUtil.java

/**
 * Write string./*  ww w .  j a  va  2s  . c o m*/
 *
 * @param obj  the obj
 * @param file the file
 */
public static void writeString(String obj, OutputStream file) {
    try {
        IOUtils.write(obj.getBytes("UTF-8"), file);
        file.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}