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.linkedin.r2.filter.compression.stream.TestStreamingCompression.java

@Test
public void testBzip2Compressor()
        throws IOException, InterruptedException, CompressionException, ExecutionException {
    StreamingCompressor compressor = new Bzip2Compressor(_executor);
    final byte[] origin = new byte[BUF_SIZE];
    Arrays.fill(origin, (byte) 'c');

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    BZip2CompressorOutputStream bzip = new BZip2CompressorOutputStream(out);
    IOUtils.write(origin, bzip);
    bzip.close();// ww w.  j ava2 s .  co m
    byte[] compressed = out.toByteArray();

    testCompress(compressor, origin, compressed);
    testDecompress(compressor, origin, compressed);
    testCompressThenDecompress(compressor, origin);
}

From source file:jp.co.acroquest.endosnipe.web.explorer.controller.ProfileController.java

/**
 * ?// w ww . j a  v a2  s  .c o m
 * @param response {@link HttpServletResponse}
 * @param agentName ??
 */
@RequestMapping(value = "/download", method = RequestMethod.POST)
public void download(final HttpServletResponse response,
        @RequestParam(value = "agentName") final String agentName) {
    ProfilerManager manager = ProfilerManager.getInstance();
    ClassModel[] classModels = manager.getProfilerData(agentName);

    String result = profilerService_.createCsvData(classModels);

    //?
    response.setContentType("application/octet-stream");
    response.setCharacterEncoding("Windows-31j");
    response.setHeader("Content-Disposition", "filename=\"profile.csv\"");

    try {
        IOUtils.write(result, response.getOutputStream());
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.nubits.nubot.notifications.jhipchat.HipChat.java

public Room createRoom(String name, String ownerId, boolean isPrivate, String topic, boolean allowGuests)
        throws IOException {
    String query = String.format(HipChatConstants.ROOMS_CREATE_QUERY_FORMAT, HipChatConstants.JSON_FORMAT,
            authToken);/*from  w  w w .  j  a v  a  2 s.co  m*/

    // build param string
    StringBuilder params = new StringBuilder();
    if (name == null || name.length() == 0) {
        throw new IllegalArgumentException("Cannot create room with null or empty name");
    } else {
        params.append("name=");
        params.append(name);
    }

    if (ownerId != null && ownerId.length() != 0) {
        params.append("&owner_user_id=");
        params.append(ownerId);
    }

    if (isPrivate) {
        params.append("&privacy=private");
    } else {
        params.append("&privacy=public");
    }

    if (topic != null && topic.length() != 0) {
        params.append("&topic=");
        params.append(topic);
    }

    if (allowGuests) {
        params.append("&guest_access=1");
    }

    final String paramsToSend = params.toString();

    OutputStream output = null;
    InputStream input = null;
    Room result = null;
    HttpURLConnection connection = null;

    try {
        URL requestUrl = new URL(HipChatConstants.API_BASE + HipChatConstants.ROOMS_CREATE + query);
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setDoOutput(true);

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", Integer.toString(paramsToSend.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        output = new BufferedOutputStream(connection.getOutputStream());
        IOUtils.write(paramsToSend, output);
        IOUtils.closeQuietly(output);

        input = connection.getInputStream();
        result = RoomParser.parseRoom(this, input);

    } finally {
        IOUtils.closeQuietly(input);
        connection.disconnect();
    }

    return result;
}

From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

/** Obtiene el fichero OOXMLK firmado.
 * @param signatureData/*from  w  w w . jav a2  s  .  co  m*/
 * @return Fichero OOXML firmado
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws TransformerException
 */
public final byte[] outputSignedOfficeOpenXMLDocument(final byte[] signatureData)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {

    final ByteArrayOutputStream signedOOXMLOutputStream = new ByteArrayOutputStream();

    final String signatureZipEntryName = "_xmlsignatures/sig-" + UUID.randomUUID().toString() + ".xml"; //$NON-NLS-1$ //$NON-NLS-2$

    /*
     * Copy the original OOXML content to the signed OOXML package. During
     * copying some files need to changed.
     */
    final ZipOutputStream zipOutputStream = copyOOXMLContent(signatureZipEntryName, signedOOXMLOutputStream);

    // Add the OOXML XML signature file to the OOXML package.
    zipOutputStream.putNextEntry(new ZipEntry(signatureZipEntryName));
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();

    return signedOOXMLOutputStream.toByteArray();
}

From source file:com.taobao.tanggong.DataFilePersisterImpl.java

public void save(TangRequest r, List<TangRequest> data) {
    if (null != dataDirectory) {
        File dataFile = new File(this.dataDirectory, r.md5hash());

        OutputStream output = null;
        try {/*  w  w  w .ja  v  a  2 s  . co  m*/
            output = new FileOutputStream(dataFile);
            IOUtils.write(JSON.toJSONString(data), output);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(output);
        }

        this.uri2HashCodes.put(r.getUri(), r.md5hash());
        this.saveHash2UrlMap();
    }
}

From source file:de.griffel.confluence.plugins.plantuml.PlantUmlMacroTest.java

@Test
public void basic() throws Exception {
    Assume.assumeNotNull(GraphvizUtils.getDotExe());
    Assume.assumeTrue(!GraphvizUtils.dotVersion().startsWith("Error:"));

    final MockExportDownloadResourceManager resourceManager = new MockExportDownloadResourceManager();
    resourceManager.setDownloadResourceWriter(new MockDownloadResourceWriter());
    final PlantUmlMacro macro = new PlantUmlMacro(resourceManager, null, mocks.getSpaceManager(),
            mocks.getSettingsManager(), mocks.getPluginAccessor(), mocks.getShortcutLinksManager(),
            mocks.getConfigurationManager(), mocks.getI18NBeanFactory());
    final Map<String, String> macroParams = ImmutableMap.<String, String>builder()
            .put(PlantUmlMacroParams.Param.title.name(), "Sample Title")
            .put(PlantUmlMacroParams.Param.type.name(), DiagramType.UML.name().toLowerCase()).build();
    final String macroBody = "A <|-- B\nurl for A is [[Home]]";
    final String result = macro.execute(macroParams, macroBody, new PageContextMock());
    StringBuilder sb = new StringBuilder();
    sb.append("<map id=\"x\" name=\"plantumlx_map\">");
    sb.append(NEWLINE);/*  w  w  w .j ava2  s  .  co m*/
    sb.append("<area shape=\"rect\" id=\"x\" href=\"x\" title=\"x\" alt=\"\" coords=\"x\"/>");
    sb.append(NEWLINE);
    sb.append("</map><span class=\"image-wrap\" style=\"\">");
    sb.append("<img usemap=\"#plantumlx_map\" src='junit/resource.png' style=\"\" /></span>");
    assertEquals(sb.toString(), result
            // GraphViz Version Specific
            .replaceAll("id=\"[^\"]*\"", "id=\"x\"").replaceAll("plantuml[^\"]*_map\"", "plantumlx_map\"")
            .replaceFirst("href=\"[^\"]*\"", "href=\"x\"").replaceFirst("title=\"[^\"]*\"", "title=\"x\"")
            .replaceFirst("coords=\"[^\"]*\"", "coords=\"x\""));
    final ByteArrayOutputStream out = (ByteArrayOutputStream) resourceManager
            .getResourceWriter(null, null, null).getStreamForWriting();
    assertTrue(out.toByteArray().length > 0); // file size depends on installation of graphviz
    IOUtils.write(out.toByteArray(), new FileOutputStream("target/junit-basic.png"));
}

From source file:at.tfr.securefs.client.SecurefsFileServiceClient.java

public void run() {
    DateTime start = new DateTime();
    try {/*  w w  w.j a  v  a  2  s.co  m*/
        FileService svc = new FileService(new URL(fileServiceUrl));
        BindingProvider binding = (BindingProvider) svc.getFileServicePort();
        binding.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
        binding.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);

        for (Path path : files) {

            if (write) {
                if (!path.toFile().exists()) {
                    System.err.println(Thread.currentThread() + ": NoSuchFile: " + path + " currentWorkdir="
                            + Paths.get("./").toAbsolutePath());
                    continue;
                }

                System.out.println(Thread.currentThread() + ": Sending file: " + start + " : " + path);
                svc.getFileServicePort().write(path.toString(),
                        IOUtils.toByteArray(Files.newInputStream(path)));
            }

            Path out = path.resolveSibling(
                    path.getFileName() + (asyncTest ? "." + Thread.currentThread().getId() : "") + ".out");

            if (read) {
                System.out.println(Thread.currentThread() + ": Reading file: " + new DateTime() + " : " + out);
                if (out.getParent() != null) {
                    Files.createDirectories(out.getParent());
                }

                byte[] arr = svc.getFileServicePort().read(path.toString());
                IOUtils.write(arr, Files.newOutputStream(out));
            }

            if (write && read) {
                long inputChk = FileUtils.checksumCRC32(path.toFile());
                long outputChk = FileUtils.checksumCRC32(out.toFile());
                if (inputChk != outputChk) {
                    throw new IOException(Thread.currentThread()
                            + ": Checksum Failed: failure to write/read: in=" + path + ", out=" + out);
                }
                System.out.println(Thread.currentThread() + ": Checked Checksums: " + new DateTime() + " : "
                        + inputChk + " / " + outputChk);
            }

            if (delete) {
                boolean deleted = svc.getFileServicePort().delete(path.toString());
                if (!deleted) {
                    throw new IOException(
                            Thread.currentThread() + ": Delete Failed: failure to delete: in=" + path);
                } else {
                    System.out.println(Thread.currentThread() + ": Deleted File: in=" + path);
                }
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException(t);
    }
}

From source file:edu.cmu.cs.diamond.android.Filter.java

private void sendBlank() throws IOException {
    IOUtils.write("\n", os);
    os.flush();
}

From source file:com.gargoylesoftware.htmlunit.UrlFetchWebConnection.java

/**
 * {@inheritDoc}/*  www . j a va  2s  .  c  o  m*/
 */
@Override
public WebResponse getResponse(final WebRequest webRequest) throws IOException {
    final long startTime = System.currentTimeMillis();
    final URL url = webRequest.getUrl();
    if (LOG.isTraceEnabled()) {
        LOG.trace("about to fetch URL " + url);
    }

    // hack for JS, about, and data URLs.
    final WebResponse response = produceWebResponseForGAEProcolHack(url);
    if (response != null) {
        return response;
    }

    // this is a "normal" URL
    try {
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //            connection.setUseCaches(false);
        connection.setConnectTimeout(webClient_.getOptions().getTimeout());

        connection.addRequestProperty("User-Agent", webClient_.getBrowserVersion().getUserAgent());
        connection.setInstanceFollowRedirects(false);

        // copy the headers from WebRequestSettings
        for (final Entry<String, String> header : webRequest.getAdditionalHeaders().entrySet()) {
            connection.addRequestProperty(header.getKey(), header.getValue());
        }
        addCookies(connection);

        final HttpMethod httpMethod = webRequest.getHttpMethod();
        connection.setRequestMethod(httpMethod.name());
        if (HttpMethod.POST == httpMethod || HttpMethod.PUT == httpMethod || HttpMethod.PATCH == httpMethod) {
            connection.setDoOutput(true);
            final String charset = webRequest.getCharset();
            connection.addRequestProperty("Content-Type", FormEncodingType.URL_ENCODED.getName());

            try (final OutputStream outputStream = connection.getOutputStream()) {
                final List<NameValuePair> pairs = webRequest.getRequestParameters();
                final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs);
                final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset);
                outputStream.write(query.getBytes(charset));
                if (webRequest.getRequestBody() != null) {
                    IOUtils.write(webRequest.getRequestBody().getBytes(charset), outputStream);
                }
            }
        }

        final int responseCode = connection.getResponseCode();
        if (LOG.isTraceEnabled()) {
            LOG.trace("fetched URL " + url);
        }

        final List<NameValuePair> headers = new ArrayList<>();
        for (final Map.Entry<String, List<String>> headerEntry : connection.getHeaderFields().entrySet()) {
            final String headerKey = headerEntry.getKey();
            if (headerKey != null) { // map contains entry like (null: "HTTP/1.1 200 OK")
                final StringBuilder sb = new StringBuilder();
                for (final String headerValue : headerEntry.getValue()) {
                    if (sb.length() != 0) {
                        sb.append(", ");
                    }
                    sb.append(headerValue);
                }
                headers.add(new NameValuePair(headerKey, sb.toString()));
            }
        }

        final byte[] byteArray;
        try (final InputStream is = responseCode < 400 ? connection.getInputStream()
                : connection.getErrorStream()) {
            byteArray = IOUtils.toByteArray(is);
        }

        final long duration = System.currentTimeMillis() - startTime;
        final WebResponseData responseData = new WebResponseData(byteArray, responseCode,
                connection.getResponseMessage(), headers);
        saveCookies(url.getHost(), headers);
        return new WebResponse(responseData, webRequest, duration);
    } catch (final IOException e) {
        LOG.error("Exception while tyring to fetch " + url, e);
        throw new RuntimeException(e);
    }
}

From source file:eu.europa.ejusticeportal.dss.controller.action.NoSealMethodTest.java

/**
 * Initialises the trusted list store and creates the sealed PDF for the other tests.
 *
 * @throws Exception//from   ww  w  . ja  v  a2s  .co m
 */
@BeforeClass
public static void createSealedPDF() throws Exception {
    System.setProperty(SealedPDFService.PASSWORD_FILE_PROPERTY, "classpath:server.pwd");
    System.setProperty(SealedPDFService.CERTIFICATE_FILE_PROPERTY, "classpath:server.p12");
    portal = new PortalFacadeTestImpl(TEST_XML, "dss/hello-world.pdf");
    HttpProxyConfig hc = Mockito.mock(HttpProxyConfig.class);
    Mockito.when(hc.isHttpEnabled()).thenReturn(Boolean.FALSE);
    Mockito.when(hc.isHttpsEnabled()).thenReturn(Boolean.FALSE);

    Mockito.when(config.getExpiredValidationLevel()).thenReturn(ValidationLevel.EXCEPTION);
    Mockito.when(config.getOriginValidationLevel()).thenReturn(ValidationLevel.EXCEPTION);
    Mockito.when(config.getTamperedValidationLevel()).thenReturn(ValidationLevel.WARN);
    Mockito.when(config.getRevokedValidationLevel()).thenReturn(ValidationLevel.WARN);
    Mockito.when(config.getSignedValidationLevel()).thenReturn(ValidationLevel.EXCEPTION);
    Mockito.when(config.getTrustedValidationLevel()).thenReturn(ValidationLevel.WARN);
    Mockito.when(config.getWorkflowValidationLevel()).thenReturn(ValidationLevel.DISABLED);
    Mockito.when(config.getLotlUrl())
            .thenReturn("https://ec.europa.eu/information_society/policy/esignature/trusted-list/tl-mp.xml");
    Mockito.when(config.getRefreshPeriod()).thenReturn(3600);
    Mockito.when(config.getSealMethod()).thenReturn(SEAL_METHOD);
    ((PortalFacadeTestImpl) portal).setConfig(config);
    RefreshingTrustedListsCertificateSource.init(hc, config);
    RefreshingTrustedListsCertificateSource.getInstance().refresh();

    byte[] originalDocument = portal.getPDFDocument(getRequest());
    byte[] doc = SealedPDFService.getInstance().sealDocument(originalDocument,
            portal.getPDFDocumentXML(getRequest()), "disclaimer", SEAL_METHOD);// document with embedded XML, signed by the server
    OutputStream os = new FileOutputStream(SEALED_PDF_FILE);
    IOUtils.write(doc, os);

}