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) 

Source Link

Document

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

Usage

From source file:ddf.catalog.registry.transformer.RegistryTransformer.java

@Override
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments)
        throws CatalogTransformerException {
    if (metacard.getTags().contains(RegistryConstants.REGISTRY_TAG)) {
        String metadata = metacard.getMetadata();
        return new BinaryContentImpl(IOUtils.toInputStream(metadata));
    } else {//  w  ww .  ja v  a2s  .  co  m
        throw new CatalogTransformerException(
                "Can't transform metacard of tag type " + metacard.getTags() + " to csw-ebrim xml");
    }
}

From source file:com.googlecode.fascinator.common.storage.impl.GenericDigitalObject.java

/**
 * Instantiates a properties object from the object's metadata payload.
 *
 * @return A properties object//from ww w  .  j a v  a  2s  .  c  o m
 */
@Override
public Properties getMetadata() throws StorageException {
    if (metadata == null) {
        Map<String, Payload> man = getManifest();
        // log.debug("Generic Manifest : " + man);
        boolean hasMetadataPayload = true;
        if (!man.containsKey(METADATA_PAYLOAD)) {
            // May have been created since object was loaded, try a
            // different method to find it
            hasMetadataPayload = false;
            Set<String> payloadIdList = getPayloadIdList();
            for (String string : payloadIdList) {
                if (METADATA_PAYLOAD.equals(string)) {
                    hasMetadataPayload = true;
                    break;
                }
            }
        }

        if (!hasMetadataPayload) {
            Payload payload = createStoredPayload(METADATA_PAYLOAD, IOUtils.toInputStream("# Object Metadata"));
            if (METADATA_PAYLOAD.equals(getSourceId())) {
                setSourceId(null);
            }
            payload.setType(PayloadType.Annotation);
            payload.setLabel(METADATA_LABEL);
        }

        try {
            Payload metaPayload = man.get(METADATA_PAYLOAD);
            metadata = new Properties();
            InputStream is = metaPayload.open();
            metadata.load(is);
            metadata.setProperty("metaPid", METADATA_PAYLOAD);
            metaPayload.close();
            is.close();
            log.debug("Closed init metadata input Stream");
        } catch (IOException ex) {
            throw new StorageException(ex);
        }
    }
    return metadata;
}

From source file:com.collective.celos.ci.testing.fixtures.create.FileTreeFixObjectCreatorTest.java

private FixFile createFile() {
    return new FixFile(IOUtils.toInputStream("1"));
}

From source file:com.github.restdriver.clientdriver.unit.ClientDriverResponseTest.java

@Test
public void creatingEmptyResponseHasNoBody() {

    assertThat(new ClientDriverResponse().hasBody(), is(false));
    assertThat(new ClientDriverResponse((String) null, null).hasBody(), is(false));
    assertThat(new ClientDriverResponse("", null).hasBody(), is(false));
    assertThat(new ClientDriverResponse((InputStream) null, null).hasBody(), is(false));
    assertThat(new ClientDriverResponse(IOUtils.toInputStream(""), null).hasBody(), is(false));

}

From source file:com.lightbox.android.operations.CachedOperation.java

@Override
public List<T> executeServerOperationSync() throws Exception {
    //Log.e(TAG, "CALLING SERVER id: %s" + getId());

    // Query server
    InputStream inputStream = getApiRequest().callApi().getEntity().getContent();
    String stringResultFromServer = IOUtils.toString(inputStream);
    ApiResponse<?> apiResponse = getApiRequest()
            .parseInputStream(IOUtils.toInputStream(stringResultFromServer));
    Object result = apiResponse.getContent();
    mContext = apiResponse.getContext();
    if (result == null) {
        return null;
    }// ww  w.j  a v  a2  s.c o m
    List<T> resultList = wrapInList(result);

    DebugLog.d(TAG, "Getting result from server.");

    // Save in disk cache
    ApiCache.getInstance().putOnDisk(getId(), stringResultFromServer);

    // Hook
    if (resultList != null) {
        onRetrieveDataFromServer(resultList);
    }

    return resultList;
}

From source file:com.norconex.committer.solr.SolrCommitterSolrIntegrationTest.java

@Test
public void testAddWithQueueContaining2documents() throws Exception {
    String content = "Document 1";
    InputStream is = IOUtils.toInputStream(content);

    String content2 = "Document 2";
    InputStream is2 = IOUtils.toInputStream(content2);

    String id = "1";
    String id2 = "2";

    Properties metadata = new Properties();
    metadata.addString("id", id);

    Properties metadata2 = new Properties();
    metadata.addString("id", id2);

    committer.add(id, is, metadata);//from ww w . j a  v  a 2  s. c  o m
    committer.add(id2, is2, metadata2);
    committer.commit();
    IOUtils.closeQuietly(is);

    //Check that there is 2 documents in Solr
    SolrDocumentList results = getAllDocs();
    assertEquals(2, results.getNumFound());
}

From source file:com.github.jarlakxen.embedphantomjs.executor.PhantomJSConsoleExecutor.java

public ListenableFuture<String> execute(final String scriptSource) throws UnexpectedProcessEndException {
    return this.execute(IOUtils.toInputStream(scriptSource), consolePostfix);
}

From source file:cz.lbenda.gui.controls.TextAreaFrmController.java

@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
    textEditor = new TextEditor();
    mainPane.setCenter(textEditor.createCodeArea());
    text.addListener((observer, oldValue, newValue) -> textEditor.changeText(newValue));

    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters().addAll(Constants.allFilesFilter);
    btnLoad.setOnAction(event -> {//from   w  w w .jav  a2  s .c om
        fileChooser.setTitle(msgLoadFile_title);
        if (lastFile != null) {
            fileChooser.setInitialDirectory(lastFile.getParentFile());
        }
        File file = fileChooser.showOpenDialog(mainPane.getScene().getWindow());
        if (file != null) {
            lastFile = file;
            try (FileReader reader = new FileReader(file)) {
                textEditor.changeText(IOUtils.toString(reader));
            } catch (IOException e) {
                ExceptionMessageFrmController
                        .showException("The file " + lastFile.getAbsolutePath() + " isn't openable.", e);
            }
        }
    });
    btnSave.setOnAction(event -> {
        File file = lastFile;
        if (lastFile == null) {
            fileChooser.setTitle(msgSaveFile_title);
            file = fileChooser.showSaveDialog(mainPane.getScene().getWindow());
        }
        if (file != null) {
            lastFile = file;
            try (OutputStream writer = new FileOutputStream(lastFile)) {
                IOUtils.copy(IOUtils.toInputStream(textEditor.getText()), writer);
            } catch (IOException e) {
                ExceptionMessageFrmController
                        .showException("The file " + lastFile.getAbsolutePath() + " isn't writable.", e);
            }
        }
    });
    btnSaveAs.setOnAction(event -> {
        fileChooser.setTitle(msgSaveFile_title);
        if (lastFile != null) {
            fileChooser.setInitialDirectory(lastFile.getParentFile());
        }
        File file = fileChooser.showSaveDialog(mainPane.getScene().getWindow());
        if (file != null) {
            lastFile = file;
            try (OutputStream writer = new FileOutputStream(lastFile)) {
                IOUtils.copy(IOUtils.toInputStream(textEditor.getText()), writer);
            } catch (IOException e) {
                ExceptionMessageFrmController
                        .showException("The file " + lastFile.getAbsolutePath() + " isn't writable.", e);
            }
        }
    });

    btnCancel.setOnAction(event -> ((Stage) btnCancel.getScene().getWindow()).close());
    btnOk.setOnAction(event -> {
        text.setValue(textEditor.getText());
        ((Stage) btnCancel.getScene().getWindow()).close();
    });

    textType.getSelectionModel().select(0);
    textType.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
        if ("Plain".equals(newValue)) {
            textEditor.changeHighlighter(new HighlighterPlain());
        } else if ("SQL".equals(newValue)) {
            textEditor.changeHighlighter(new HighlighterSQL());
        } else if ("XML".equals(newValue)) {
            textEditor.changeHighlighter(new HighlighterXml());
        } else if ("Java".equals(newValue)) {
            textEditor.changeHighlighter(new HighlighterJava());
        }
    });
}

From source file:com.adobe.acs.commons.hc.impl.SMTPMailServiceHealthCheck.java

@Override
@SuppressWarnings("squid:S1141")
public Result execute() {
    final FormattingResultLog resultLog = new FormattingResultLog();

    if (messageGatewayService == null) {
        resultLog.critical("MessageGatewayService OSGi service could not be found.");
        resultLog.info(/*  w w  w  . j a  v a 2s.  c  o m*/
                "Verify the Default Mail Service is active: http://<host>:<port>/system/console/components/com.day.cq.mailer.impl.CqMailingService");
    } else {
        final MessageGateway<SimpleEmail> messageGateway = messageGatewayService.getGateway(SimpleEmail.class);
        if (messageGateway == null) {
            resultLog.critical("The AEM Default Mail Service is INACTIVE, thus e-mails cannot be sent.");
            resultLog.info(
                    "Verify the Default Mail Service is active and configured: http://<host>:<port>/system/console/components/com.day.cq.mailer.DefaultMailService");
            log.warn("Could not retrieve a SimpleEmail Message Gateway");

        } else {
            try {
                List<InternetAddress> emailAddresses = new ArrayList<InternetAddress>();
                emailAddresses.add(new InternetAddress(this.toEmail));
                MailTemplate mailTemplate = new MailTemplate(IOUtils.toInputStream(MAIL_TEMPLATE),
                        CharEncoding.UTF_8);
                SimpleEmail email = mailTemplate.getEmail(StrLookup.mapLookup(Collections.emptyMap()),
                        SimpleEmail.class);

                email.setSubject("AEM E-mail Service Health Check");
                email.setTo(emailAddresses);

                email.setSocketConnectionTimeout(TIMEOUT);
                email.setSocketTimeout(TIMEOUT);
                try {
                    messageGateway.send(email);
                    resultLog.info(
                            "The E-mail Service appears to be working properly. Verify the health check e-mail was sent to [ {} ]",
                            this.toEmail);
                } catch (Exception e) {
                    resultLog.critical(
                            "Failed sending e-mail. Unable to send a test toEmail via the configured E-mail server: "
                                    + e.getMessage(),
                            e);
                    log.warn("Failed to send E-mail for E-mail Service health check", e);
                }

                logMailServiceConfig(resultLog, email);
            } catch (Exception e) {
                resultLog.healthCheckError(
                        "Sling Health check could not formulate a test toEmail: " + e.getMessage(), e);
                log.error("Unable to execute E-mail health check", e);
            }
        }
    }

    return new Result(resultLog);
}

From source file:net.di2e.ecdr.search.transform.atom.response.AtomResponseTransformerTest.java

private SourceResponse getTransformResponse(final String LOCATION_XML) throws Exception {
    AtomSearchResponseTransformerConfig config = mock(AtomSearchResponseTransformerConfig.class);
    QueryRequest request = mock(QueryRequest.class);
    AtomResponseTransformer transformer = new AtomResponseTransformer(config);
    String atomXML = IOUtils.toString(getClass().getResourceAsStream(ATOM_TEMPLATE_FILE));
    atomXML = StringUtils.replace(atomXML, LOCATION_MARKER, LOCATION_XML);
    return transformer.processSearchResponse(IOUtils.toInputStream(atomXML), request, SITE_NAME);
}