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.vmware.loginsightapi.LogInsightClientMockTest.java

@Before
public void setUp() {
    config = Configuration.buildFromConfig("config-mock.properties");
    when(connectionStrategy.getHttpClient()).thenReturn(asyncHttpClient);
    HttpResponse response = mock(HttpResponse.class);
    Future<HttpResponse> future = ConcurrentUtils.constantFuture(response);
    when(asyncHttpClient.execute(any(HttpUriRequest.class), any(FutureCallback.class))).thenReturn(future,
            null);// w w w  . j av 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);
    try {
        InputStream inputStream = IOUtils.toInputStream(SERVER_RESPONSE_EXPECTED, "UTF-8");
        when(httpEntity.getContent()).thenReturn(inputStream);
        client = new LogInsightClient(config, connectionStrategy);
        // client.connect(user, password);
        assertEquals("Invalid session id!!",
                "qyOLWEe7f/GjdM1WnczrCeQure97B/NpTbWTeqqYPBd1AYMf9cMNfQYqltITI4ffPMx822Sz9i/X47t8VwsDb0oGckclJUdn83cyIPk6WlsOpI4Yjw6WpurAnv9RhDsYSzKhAMzskzhTOJKfDHZjWR5v576WwtJA71wqI7igFrG91LG5c/3GfzMb68sUHF6hV+meYtGS4A1y/lUItvfkqTTAxBtTCZNoKrvCJZ4R+b6vuAAYoBNSWL7ycIy2LsALrVFxftAkA8n9DBAZYA9T5A==",
                client.getSessionId());
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
    }
}

From source file:io.microprofile.showcase.speaker.domain.VenueJavaOne2016.java

private Speaker processSpeakerToken(final String token) {
    final Speaker speaker = new Speaker();
    speaker.setId(UUID.randomUUID().toString());
    //System.out.println("token = " + token);

    try (InputStream is = IOUtils.toInputStream(token, Charset.forName("UTF-8"))) {
        final StreamLexer lexer = new StreamLexer(is);
        speaker.setPicture(this.getImage(lexer));

        final String fullName = lexer.readToken("<h4>", "</h4>");
        speaker.setNameFirst(fullName.substring(0, fullName.indexOf(" ")));
        speaker.setNameLast(fullName.substring(fullName.indexOf(" ") + 1));

        speaker.setBiography(lexer.readToken("<p>", "</p>"));
        speaker.setTwitterHandle(lexer.readToken("href=\"https://twitter.com/", "\">@"));

    } catch (final Exception e) {
        this.log.log(Level.SEVERE, "Failed to parse token: " + token, e);
    }/*  www  .  java  2 s.  com*/

    this.log.log(Level.FINE, "Found:" + speaker);

    return speaker;
}

From source file:com.twinsoft.convertigo.eclipse.editors.jscript.JscriptStatementEditor.java

public void init(IEditorSite site, IEditorInput input) throws PartInitException {
    // Get from the input the necessary objects as the temp IFile to create to hold the jscript code itself.
    file = ((FileEditorInput) input).getFile();
    statement = (SimpleStatement) ((JscriptStatementEditorInput) input).getStatement();

    try {//from  w  ww  . j  ava  2  s . co m
        file.setCharset("UTF-8", null);
    } catch (CoreException e1) {
        ConvertigoPlugin.logDebug("Failed to set UTF-8 charset for editor file: " + e1);
    }

    try {
        // Create a temp  file to hold statement jscript code
        InputStream sbisHandlersStream = IOUtils.toInputStream(statement.getExpression(), "UTF-8");

        // Overrides temp file with statement jscript code
        if (file.exists()) {
            try {
                file.setContents(sbisHandlersStream, true, false, null);
            } catch (CoreException e) {
                ConvertigoPlugin.logException(e, "Error while editing statement jscript code");
            }
        }
        // Create a temp file to hold statement jscript code
        else {
            try {
                file.getParent().refreshLocal(IResource.DEPTH_ONE, null);
                file.create(sbisHandlersStream, true, null);
            } catch (CoreException e) {
                ConvertigoPlugin.logException(e, "Error while editing the statement jscript code");
            }
        }

        setSite(site);
        setInput(input);
        eSite = site;
        eInput = input;
        String[] splits = file.getName().split(" ");
        setPartName(splits[splits.length - 1]);
    } catch (Exception e) {
        throw new PartInitException("Unable to create JS editor", e);
    }
}

From source file:edu.lternet.pasta.common.eml.EMLParser.java

/**
 * Parses an EML document./*from   w ww . j a  v  a  2  s  .c  o m*/
 * 
 * @param   xml          The XML string representation of the EML document
 * @return  dataPackage  a DataPackage object holding parsed values
 */
public DataPackage parseDocument(String xml) {
    DataPackage dataPackage = null;

    if (xml != null) {
        try {
            InputStream inputStream = IOUtils.toInputStream(xml, "UTF-8");
            dataPackage = parseDocument(inputStream);
        } catch (Exception e) {
            logger.error("Error parsing EML metacdata: " + e.getMessage());
        }
    }

    return dataPackage;
}

From source file:com.adaptris.core.lms.FileBackedMessageImpl.java

/**
 * @see com.adaptris.core.lms.FileBackedMessage#getInputStream()
 *//* w  w w . j a  v  a2s .c  o m*/
@Override
public InputStream getInputStream() throws IOException {
    // If we have an inputFile, return a stream for it. If we don't, return an empty stream
    if (inputFile == null) {
        return IOUtils.toInputStream("", Charset.defaultCharset());
    }
    return streamWrapper.openInputStream(inputFile, () -> {
    });

}

From source file:gate.corpora.FastInfosetDocumentFormat.java

/**
 * Unpacks markup in the GATE-specific standoff XML markup format.
 * /*w w  w.  ja  va  2s.c  o m*/
 * @param doc
 *          the document to process
 * @param statusListener
 *          optional status listener to receive status messages
 * @throws DocumentFormatException
 *           if a fatal error occurs during parsing
 */
private void unpackGateFormatMarkup(Document doc, StatusListener statusListener)
        throws DocumentFormatException {
    boolean docHasContentButNoValidURL = hasContentButNoValidUrl(doc);

    try {
        Reader inputReader = null;
        InputStream inputStream = null;
        XMLStreamReader xsr = null;
        String encoding = ((TextualDocument) doc).getEncoding();
        if (docHasContentButNoValidURL) {
            xsr = new StAXDocumentParser(IOUtils.toInputStream(doc.getContent().toString(), encoding),
                    getStAXManager());
        } else {
            inputStream = doc.getSourceUrl().openStream();
            xsr = new StAXDocumentParser(inputStream, getStAXManager());
        }

        // find the opening GateDocument tag
        xsr.nextTag();

        // parse the document
        try {
            DocumentStaxUtils.readGateXmlDocument(xsr, doc, statusListener);
        } finally {
            xsr.close();
            if (inputStream != null) {
                inputStream.close();
            }
            if (inputReader != null) {
                inputReader.close();
            }
        }
    } catch (XMLStreamException e) {
        doc.getFeatures().put("parsingError", Boolean.TRUE);

        Boolean bThrow = (Boolean) doc.getFeatures().get(GateConstants.THROWEX_FORMAT_PROPERTY_NAME);

        if (bThrow != null && bThrow.booleanValue()) {
            // the next line is commented to avoid Document creation fail on
            // error
            throw new DocumentFormatException(e);
        } else {
            Out.println("Warning: Document remains unparsed. \n" + "\n  Stack Dump: ");
            e.printStackTrace(Out.getPrintWriter());
        } // if
    } catch (IOException ioe) {
        throw new DocumentFormatException("I/O exception for " + doc.getSourceUrl().toString(), ioe);
    }
}

From source file:eulermind.importer.FreemindImporter.java

public List importString(Object parentDBId, int pos, final String str) throws Exception {
    InputStream inputStream = IOUtils.toInputStream(str, "UTF-8");
    return importFromInputStream(parentDBId, pos, inputStream);
}

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

@Test
public void testStaleEntries() throws IOException, CacheException, InterruptedException {
    cache.setMaxStaleTime(-1);/*w  w  w  . j av  a2  s.  c  om*/

    FileStreamCacheEntry entry = new FileStreamCacheEntry("body");

    assertFalse(entry.isValid());

    assertNull(entry.getFile(false));

    String content = "Some content";

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

    assertTrue(entry.isValid());

    File file1 = entry.getFile(false);

    assertTrue(file1.exists());

    String key = "key";

    cache.addEntry(key, entry);

    entry = new FileStreamCacheEntry("other body");

    content = "Other content";

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

    File file2 = entry.getFile(false);

    assertTrue(file2.exists());

    cache.addEntry(key, entry);

    assertNotNull(cache.getEntry(key, entry.getId()));

    assertNotNull(cache.getWrapper(key, false));

    cache.kick();

    Thread.sleep(100);

    List<CacheEntry> entries = cache.getAllEntries(key);

    assertEquals(0, entries.size());

    assertFalse(file1.exists());
    assertFalse(file2.exists());

    assertNull(cache.getEntry(key, entry.getId()));
    assertNull(cache.getWrapper(key, false));
}

From source file:co.cask.hydrator.plugin.batch.CopybookSource.java

/**
 * Get the output schema from the COBOL copybook contents specified by the user.
 *
 * @return outputSchema/* w w w  . j  a  v  a 2s .co m*/
 */
private Schema getOutputSchema() {

    InputStream inputStream = null;
    ExternalRecord externalRecord = null;
    List<Schema.Field> fields = Lists.newArrayList();
    try {
        inputStream = IOUtils.toInputStream(config.copybookContents, "UTF-8");
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        externalRecord = CopybookIOUtils.getExternalRecord(bufferedInputStream);
        String fieldName;
        for (ExternalField field : externalRecord.getRecordFields()) {
            fieldName = field.getName();
            if (fieldsToDrop.contains(fieldName)) {
                continue;
            }
            fields.add(Schema.Field.of(field.getName(),
                    Schema.nullableOf(Schema.of(getFieldSchemaType(field.getType())))));
        }
        return Schema.recordOf("record", fields);
    } catch (IOException e) {
        throw new IllegalArgumentException(
                "Exception while creating input stream for COBOL Copybook. Invalid output " + "schema: "
                        + e.getMessage(),
                e);
    } catch (RecordException e) {
        throw new IllegalArgumentException(
                "Exception while creating record from COBOL Copybook. Invalid output " + "schema: "
                        + e.getMessage(),
                e);
    }
}

From source file:com.hortonworks.registries.storage.filestorage.DbFileStorageTest.java

@Test(expected = StorageException.class)
public void testConcurrentUpload() throws Throwable {
    try {/* w  w  w  .j a  va 2  s. c  o  m*/
        transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
        String input = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(FILE_NAME),
                "UTF-8");
        String updated = input + " new text";
        dbFileStorage.upload(IOUtils.toInputStream(input, "UTF-8"), FILE_NAME);
        InputStream slowStream = new InputStream() {
            byte[] bytes = updated.getBytes("UTF-8");
            int i = 0;

            @Override
            public int read() throws IOException {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException ex) {
                }
                return (i < bytes.length) ? (bytes[i++] & 0xff) : -1;
            }
        };
        FutureTask<String> ft1 = new FutureTask<>(() -> {
            try {
                transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
                String name = dbFileStorage.upload(slowStream, FILE_NAME);
                transactionManager.commitTransaction();
                return name;
            } catch (Exception e) {
                transactionManager.rollbackTransaction();
                throw e;
            }
        });
        FutureTask<String> ft2 = new FutureTask<>(() -> {
            try {
                transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
                String name = dbFileStorage.upload(IOUtils.toInputStream(updated, "UTF-8"), FILE_NAME);
                transactionManager.commitTransaction();
                return name;
            } catch (Exception e) {
                transactionManager.rollbackTransaction();
                throw e;
            }
        });
        Thread t1 = new Thread(ft1);
        Thread t2 = new Thread(ft2);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        try {
            ft1.get();
        } catch (ExecutionException ex) {
            throw ex.getCause();
        }
        transactionManager.commitTransaction();
    } catch (Exception e) {
        transactionManager.rollbackTransaction();
        throw e;
    }
}