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

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

Introduction

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

Prototype

public static InputStream toInputStream(String input, String encoding) throws IOException 

Source Link

Document

Convert the specified string to an input stream, encoded as bytes using the specified character encoding.

Usage

From source file:com.sunchenbin.store.feilong.core.io.IOWriteUtil.java

/**
 * ./*from  w  w  w . j  a v  a2s. co  m*/
 * 
 * <h3>:</h3>
 * 
 * <blockquote>
 * <ul>
 * <li> <code>Validator.isNullOrEmpty(filePath)</code>, {@link NullPointerException}</li>
 * <li>?,, (?? )</li>
 * <li>,?{@link FileWriteMode#APPEND}?</li>
 * <li>? <code>charsetType</code>,{@link CharsetType#UTF8}?</li>
 * </ul>
 * </blockquote>
 *
 * @param filePath
 *            
 * @param content
 *            
 * @param charsetType
 *            {@link CharsetType} ?,isNullOrEmpty, {@link CharsetType#UTF8}?
 * @param fileWriteMode
 *            ? {@link FileWriteMode}
 * @see java.io.FileOutputStream#FileOutputStream(File, boolean)
 * @see #write(InputStream, OutputStream)
 * @see org.apache.commons.io.FileUtils#writeStringToFile(File, String, Charset, boolean)
 */
public static void write(String filePath, String content, String charsetType, FileWriteMode fileWriteMode) {
    if (Validator.isNullOrEmpty(filePath)) {
        throw new NullPointerException("filePath can't be null/empty!");
    }
    Date beginDate = new Date();

    String useEncode = Validator.isNullOrEmpty(charsetType) ? CharsetType.UTF8 : charsetType;
    FileWriteMode useFileWriteMode = Validator.isNullOrEmpty(fileWriteMode) ? FileWriteMode.COVER
            : fileWriteMode;

    FileUtil.createDirectoryByFilePath(filePath);

    InputStream inputStream = IOUtils.toInputStream(content, Charset.forName(useEncode));
    OutputStream outputStream = FileUtil.getFileOutputStream(filePath, useFileWriteMode);

    write(inputStream, outputStream);

    if (LOGGER.isInfoEnabled()) {
        File file = new File(filePath);
        LOGGER.info("fileWriteMode:[{}],encode:[{}],contentLength:[{}],fileSize:[{}],absolutePath:[{}],time:{}",
                useFileWriteMode, useEncode, content.length(), FileUtil.getFileFormatSize(file),
                file.getAbsolutePath(), DateExtensionUtil.getIntervalForView(beginDate, new Date()));
    }
}

From source file:ch.entwine.weblounge.common.impl.content.movie.LazyMovieResourceImpl.java

/**
 * Loads the audio visual body only.//from  w  ww .j  a  v a2 s. co  m
 */
protected void loadAudioVisualBody() {
    try {

        // Get a hold of the audio visual reader
        MovieResourceReader reader = (readerRef != null) ? readerRef.get() : null;
        if (reader == null) {
            reader = new MovieResourceReader();
            readerRef = new WeakReference<MovieResourceReader>(reader);
        }

        // Load the audio visual body
        audioVisual = reader.readBody(IOUtils.toInputStream(audiovisualXml, "utf-8"), uri.getSite());
        isBodyLoaded = true;
        if (isHeaderLoaded && isBodyLoaded)
            cleanupAfterLoading();
        else if (headerXml != null)
            audiovisualXml = null;

    } catch (Throwable e) {
        logger.error("Failed to lazy-load body of {}: {}", uri, e.getMessage());
        throw new IllegalStateException(e);
    }
}

From source file:ch.entwine.weblounge.common.impl.content.page.LazyPageImpl.java

/**
 * Loads the page body only.//  w  ww  . j a  va 2  s  .c  o  m
 */
protected void loadPageBody() {
    try {

        // Get a hold of the page reader
        PageReader reader = (readerRef != null) ? readerRef.get() : null;
        if (reader == null) {
            reader = new PageReader();
            readerRef = new WeakReference<PageReader>(reader);
        }

        // Load the page body
        page = reader.readBody(IOUtils.toInputStream(pageXml, "utf-8"), uri.getSite());
        isBodyLoaded = true;
        if (isHeaderLoaded && isBodyLoaded)
            cleanupAfterLoading();
        else if (headerXml != null)
            pageXml = null;

    } catch (Throwable e) {
        logger.error("Failed to lazy-load body of {}: {}", uri, e.getMessage());
        throw new IllegalStateException(e);
    }
}

From source file:mitm.common.cache.ContentCacheImplTest.java

@Test
public void testGetEntry() throws IOException, CacheException {
    FileStreamCacheEntry entry = new FileStreamCacheEntry("body");

    assertFalse(entry.isValid());/*from  w ww.j  a v a 2 s  . c o m*/

    assertNull(entry.getFile(false));

    String content = "Some content";

    entry.store(IOUtils.toInputStream(content, "UTF-8"));

    assertTrue(entry.isValid());

    String key = "key";

    cache.addEntry(key, entry);

    entry = new FileStreamCacheEntry("other body");

    content = "Other content";

    entry.store(IOUtils.toInputStream(content, "UTF-8"));

    cache.addEntry(key, entry);

    entry = (FileStreamCacheEntry) cache.getEntry(key, "body");

    assertNotNull(entry);
    assertEquals("body", entry.getId());

    entry = (FileStreamCacheEntry) cache.getEntry(key, "other body");

    assertNotNull(entry);
    assertEquals("other body", entry.getId());

    entry = (FileStreamCacheEntry) cache.getEntry(key, "no entry");

    assertNull(entry);
}

From source file:ch.cyberduck.core.openstack.SwiftSegmentService.java

/**
 * The value of the ETag header is calculated by taking
 * the ETag value of each segment, concatenating them together, and then returning the MD5 checksum of the result.
 *
 * @param checksum Checksum compute service
 * @param objects  Files/*from  w  ww .  j a  v a  2s . c om*/
 * @return Concatenated checksum
 */
public Checksum checksum(final ChecksumCompute checksum, final List<StorageObject> objects)
        throws ChecksumException {
    final StringBuilder concatenated = new StringBuilder();
    for (StorageObject s : objects) {
        concatenated.append(s.getMd5sum());
    }
    return checksum.compute(IOUtils.toInputStream(concatenated.toString(), Charset.defaultCharset()),
            new TransferStatus());
}

From source file:com.vmware.loginsightapi.LogInsightClientMockTest.java

@Test
public void testLogInsightConstructor() {
    HttpResponse response = mock(HttpResponse.class);
    Future<HttpResponse> future = ConcurrentUtils.constantFuture(response);
    when(asyncHttpClient.execute(any(HttpUriRequest.class), any(FutureCallback.class))).thenReturn(future,
            null);//from ww  w. jav a  2  s .  co m
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);
    StatusLine statusLine = mock(StatusLine.class);
    when(response.getStatusLine()).thenReturn(statusLine);
    when(statusLine.getStatusCode()).thenReturn(200);
    AsyncLogInsightConnectionStrategy asyncConnectionStrategy = mock(AsyncLogInsightConnectionStrategy.class);
    when(asyncConnectionStrategy.getHttpClient()).thenReturn(asyncHttpClient);
    LogInsightClient client1 = null;
    try {
        InputStream inputStream = IOUtils.toInputStream(SERVER_RESPONSE_EXPECTED, "UTF-8");
        when(httpEntity.getContent()).thenReturn(inputStream);
        client1 = new LogInsightClient(config.getHost(), config.getUser(), "dummy-password");
        assertEquals("Invalid session id!!",
                "qyOLWEe7f/GjdM1WnczrCeQure97B/NpTbWTeqqYPBd1AYMf9cMNfQYqltITI4ffPMx822Sz9i/X47t8VwsDb0oGckclJUdn83cyIPk6WlsOpI4Yjw6WpurAnv9RhDsYSzKhAMzskzhTOJKfDHZjWR5v576WwtJA71wqI7igFrG91LG5c/3GfzMb68sUHF6hV+meYtGS4A1y/lUItvfkqTTAxBtTCZNoKrvCJZ4R+b6vuAAYoBNSWL7ycIy2LsALrVFxftAkA8n9DBAZYA9T5A==",
                client1.getSessionId());
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
    } finally {
        try {
            client1.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:edu.lternet.pasta.client.ReservationsManager.java

/**
 * Composes HTML table rows to render the list of active reservations for
 * this user./*from   ww w  .java2  s. c o  m*/
 * 
 * @return an HTML snippet of table row (<tr>) elements, one per
 *         active data package identifier reservation for this user.
 * @throws Exception
 */
public String reservationsTableHTML() throws Exception {
    String html;
    StringBuilder sb = new StringBuilder("");

    if (this.uid != null && !this.uid.equals("public")) {
        String xmlString = listActiveReservations();

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        try {
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream inputStream = IOUtils.toInputStream(xmlString, "UTF-8");
            Document document = documentBuilder.parse(inputStream);
            Element documentElement = document.getDocumentElement();
            NodeList reservations = documentElement.getElementsByTagName("reservation");
            int nReservations = reservations.getLength();

            for (int i = 0; i < nReservations; i++) {
                Node reservationNode = reservations.item(i);
                NodeList reservationChildren = reservationNode.getChildNodes();
                String docid = "";
                String principal = "";
                String dateReserved = "";
                boolean include = false;
                for (int j = 0; j < reservationChildren.getLength(); j++) {
                    Node childNode = reservationChildren.item(j);
                    if (childNode instanceof Element) {
                        Element reservationElement = (Element) childNode;

                        if (reservationElement.getTagName().equals("principal")) {
                            Text text = (Text) reservationElement.getFirstChild();
                            if (text != null) {
                                principal = text.getData().trim();
                                if (principal.startsWith(this.uid)) {
                                    include = true;
                                }
                            }
                        } else if (reservationElement.getTagName().equals("docid")) {
                            Text text = (Text) reservationElement.getFirstChild();
                            if (text != null) {
                                docid = text.getData().trim();
                            }
                        } else if (reservationElement.getTagName().equals("dateReserved")) {
                            Text text = (Text) reservationElement.getFirstChild();
                            if (text != null) {
                                dateReserved = text.getData().trim();
                            }
                        }
                    }
                }

                if (include) {
                    sb.append("<tr>\n");

                    sb.append("  <td class='nis' align='center'>");
                    sb.append(docid);
                    sb.append("</td>\n");

                    sb.append("  <td class='nis' align='center'>");
                    sb.append(principal);
                    sb.append("</td>\n");

                    sb.append("  <td class='nis'>");
                    sb.append(dateReserved);
                    sb.append("</td>\n");

                    sb.append("</tr>\n");
                }
            }
        } catch (Exception e) {
            logger.error("Exception:\n" + e.getMessage());
            e.printStackTrace();
            throw new PastaEventException(e.getMessage());
        }
    }

    html = sb.toString();
    return html;
}

From source file:ddf.test.itests.platform.TestConfigStatusCommand.java

private InputStream replaceTextInResource(InputStream is, String textToReplace, String replacement)
        throws IOException {
    StringWriter writer = new StringWriter();
    IOUtils.copy(is, writer);//from  w w w.  j  a  v  a2s . c  o  m
    String original = writer.toString();
    String modified = original.replace(textToReplace, replacement);
    return IOUtils.toInputStream(modified, "UTF-8");
}

From source file:ddf.test.itests.catalog.TestRegistry.java

private String createRegistryEntry(String id) throws Exception {
    Response response = given()//from www .  j  a  v  a  2  s.  co  m
            .body(Library.getCswRegistryInsert().replaceAll("urn:uuid:2014ca7f59ac46f495e32b4a67a51276", id))
            .header("Content-Type", "text/xml").expect().log().all().statusCode(200).when()
            .post(CSW_PATH.getUrl());
    ValidatableResponse validatableResponse = response.then();

    validatableResponse.body(
            hasXPath("//TransactionResponse/TransactionSummary/totalInserted", CoreMatchers.is("1")),
            hasXPath("//TransactionResponse/TransactionSummary/totalUpdated", CoreMatchers.is("0")),
            hasXPath("//TransactionResponse/TransactionSummary/totalDeleted", CoreMatchers.is("0")));

    XPath xPath = XPathFactory.newInstance().newXPath();
    String idPath = "//*[local-name()='identifier']/text()";
    InputSource xml = new InputSource(
            IOUtils.toInputStream(response.getBody().asString(), StandardCharsets.UTF_8.name()));
    return xPath.compile(idPath).evaluate(xml);
}

From source file:com.telefonica.euro_iaas.sdc.installator.InstallatorPuppetTest.java

@Test
public void testIsNodeDeployed() throws OpenStackException, CanNotCallPuppetException, IOException {

    when(statusLine.getStatusCode()).thenReturn(200).thenReturn(500);
    when(openStackRegion.getPuppetDBEndPoint(any(String.class))).thenReturn("http");

    InputStream in = IOUtils.toInputStream(GET_NODES, "UTF-8");
    when(entity.getContent()).thenReturn(in);
    puppetInstallator.isNodeRegistered("aaaa-dddfafff-1-000081", "token");

}