Java Code Examples for org.apache.commons.io.IOUtils#toInputStream()

The following examples show how to use org.apache.commons.io.IOUtils#toInputStream() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: celos   File: JsonExpandConverter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FixFile convert(TestRun tr, FixFile ff) throws Exception {

    List<String> stringList = Lists.newArrayList();

    BufferedReader reader = new BufferedReader(new InputStreamReader(ff.getContent()));
    String line;
    while ((line = reader.readLine()) != null) {
        JsonElement jsonElement = jsonParser.parse(line);
        for (String field : expandFields) {
            try {
                String strField = jsonElement.getAsJsonObject().get(field).getAsString();
                JsonElement fieldElem = jsonParser.parse(strField);
                jsonElement.getAsJsonObject().add(field, fieldElem);
            } catch(Exception e) {
                throw new Exception("Error caused in line: " + line + " trying to expand field: " + field, e); 
            }
        }
        stringList.add(gson.toJson(jsonElement));
    }

    return new FixFile(IOUtils.toInputStream(StringUtils.join(stringList,"\n")));
}
 
Example 2
private static WebApp parseXmlFragment() {
    InputStream precompiledJspWebXml = RegisterPrecompiledJSPInitializer.class.getResourceAsStream("/precompiled-jsp-web.xml");
    InputStream webXmlIS = new SequenceInputStream(
            new SequenceInputStream(
                    IOUtils.toInputStream("<web-app>", Charset.defaultCharset()),
                    precompiledJspWebXml),
            IOUtils.toInputStream("</web-app>", Charset.defaultCharset()));

    try {
        JAXBContext jaxbContext = new JAXBDataBinding(WebApp.class).getContext();
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        WebApp webapp = (WebApp) unmarshaller.unmarshal(webXmlIS);
        try {
            webXmlIS.close();
        } catch (java.io.IOException ignored) {}
        return webapp;
    } catch (JAXBException e) {
        throw new RuntimeException("Could not parse precompiled-jsp-web.xml", e);
    }
}
 
Example 3
/**
 * Refresh configuration.
 *
 * @return the RWE Smarthome configuration XML response
 * @throws RWESmarthomeSessionExpiredException
 *             the smart home session expired exception
 */
public String refreshConfiguration() throws RWESmarthomeSessionExpiredException {

    String sResponse = "";
    final String GET_CONFIGURATION_REQUEST = String.format(
            "<BaseRequest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"GetEntitiesRequest\" Version=\"%s\" RequestId=\"%s\" SessionId=\"%s\">\n"
                    + "<EntityType>Configuration</EntityType>" + "</BaseRequest>",
            RWESmarthomeSession.getFirmwareVersion(), rweSmarthomeSession.getRequestId(),
            rweSmarthomeSession.getSessionId());
    sResponse = rweSmarthomeSession.executeRequest(GET_CONFIGURATION_REQUEST, "/cmd");

    try {
        GetEntitiesXMLResponse entitiesXMLRes = new GetEntitiesXMLResponse(
                IOUtils.toInputStream(sResponse, "UTF8"));
        rweSmarthomeSession.setLocations(entitiesXMLRes.getLocations());
        rweSmarthomeSession.setLogicalDevices(entitiesXMLRes.getLogicalDevices());
        rweSmarthomeSession.setCurrentConfigurationVersion(entitiesXMLRes.getConfigurationVersion());
    } catch (IOException e) {
        throw new RWESmarthomeSessionExpiredException(e);
    }

    return sResponse;
}
 
Example 4
Source Project: mogu_blog_v2   File: FreemarkerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateHtml() throws IOException, TemplateException {
    //创建配置类
    Configuration configuration = new Configuration(Configuration.getVersion());
    String classpath = this.getClass().getResource("/").getPath();
    //设置模板路径
    configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
    //设置字符集
    configuration.setDefaultEncoding("utf-8");
    //加载模板
    Template template = configuration.getTemplate("test1.ftl");
    //数据模型
    Map map = getMap();
    //静态化
    String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
    //静态化内容
    System.out.println(content);
    InputStream inputStream = IOUtils.toInputStream(content);
    //输出文件
    FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));
    int copy = IOUtils.copy(inputStream, fileOutputStream);
}
 
Example 5
@Test
public void convert_string_to_inputstream_apache () throws IOException {

	InputStream inputStream = IOUtils.toInputStream(PHRASE);
	
	// now to do some work w/ it
	StringBuffer phraseThroughStream = new StringBuffer();
	int c;
       while ((c = inputStream.read()) != -1) {
       	phraseThroughStream.append((char) c);
       }
	
	assertEquals(phraseThroughStream.toString(), PHRASE);
}
 
Example 6
Source Project: tutorials   File: JavaReaderToXUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException {
    String initialString = "With Commons IO";
    final Reader initialReader = new StringReader(initialString);
    final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);

    String finalString = IOUtils.toString(targetStream, Charsets.UTF_8);
    assertThat(finalString, equalTo(initialString));

    initialReader.close();
    targetStream.close();
}
 
Example 7
@Override
public FixFile convert(TestRun tr, FixTable table) throws Exception {
    List<String> lines = new ArrayList<>();
    for (FixTable.FixRow row : table.getRows()) {
        lines.add(StringUtils.join(row.getOrderedColumns(table.getColumnNames()), "\t"));
    }
    return new FixFile(IOUtils.toInputStream(StringUtils.join(lines, "\n") + "\n"));
}
 
Example 8
/**
 * The PasswordPlaceholderConfigurer will read Kylin properties as the Spring resource
 */
public PasswordPlaceholderConfigurer() throws IOException {
    Resource[] resources = new Resource[1];
    //Properties prop = KylinConfig.getKylinProperties();
    Properties prop = getAllKylinProperties();
    StringWriter writer = new StringWriter();
    prop.store(new PrintWriter(writer), "kylin properties");
    String propString = writer.getBuffer().toString();
    IOUtils.closeQuietly(writer);
    InputStream is = IOUtils.toInputStream(propString, Charset.defaultCharset());
    resources[0] = new InputStreamResource(is);
    this.setLocations(resources);
}
 
Example 9
Source Project: olingo-odata4   File: JSONUtilities.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected InputStream addLinks(
    final String entitySetName, final String entitykey, final InputStream is, final Set<String> links)
        throws IOException {

  final ObjectNode srcNode = (ObjectNode) mapper.readTree(is);
  IOUtils.closeQuietly(is);

  for (String link : links) {
    srcNode.set(link + Constants.get(ConstantKey.JSON_NAVIGATION_SUFFIX),
        new TextNode(Commons.getLinksURI(entitySetName, entitykey, link)));
  }

  return IOUtils.toInputStream(srcNode.toString(), Constants.ENCODING);
}
 
Example 10
Source Project: baleen   File: LineReader.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doGetNext(JCas jCas) throws IOException, CollectionException {
  InputStream is = IOUtils.toInputStream(line, Charset.defaultCharset());
  extractContent(is, file.getPath() + "#" + lineNumber, jCas);

  Metadata md = new Metadata(jCas);
  md.setKey("lineNumber");
  md.setValue(lineNumber.toString());
  getSupport().add(md);
}
 
Example 11
private FixDir createDirWithFileContent(String fileContent) {
    FixDir dir1 = createDirWithSubdirsAndFile(fileContent);
    InputStream inputStream2 = IOUtils.toInputStream(fileContent);
    FixFile file = new FixFile(inputStream2);

    Map<String, FixFsObject> content = Maps.newHashMap();
    content.put("dir1", dir1);
    content.put("file", file);
    return new FixDir(content);
}
 
Example 12
private InputStream createGemspecInputStream() {
    final String gemspec = "Some garbage line" + System.lineSeparator()
                               + "s.add_dependency \"" + externalId1.getName() + "\", \"" + externalId1.getVersion() + "\"" + System.lineSeparator()
                               + "s.add_runtime_dependency \"" + externalId2.getName() + "\", \"" + externalId2.getVersion() + "\"" + System.lineSeparator()
                               + "s.add_development_dependency \"" + externalId3.getName() + "\", \"" + externalId3.getVersion() + "\"" + System.lineSeparator();

    return IOUtils.toInputStream(gemspec, StandardCharsets.UTF_8);
}
 
Example 13
Source Project: olingo-odata4   File: AbstractUtilities.java    License: Apache License 2.0 5 votes vote down vote up
public InputStream writeProperty(final Accept accept, final Property property)
    throws ODataSerializerException {

  final StringWriter writer = new StringWriter();
  if (accept == Accept.XML || accept == Accept.ATOM) {
    atomSerializer.write(writer, property);
  } else {
    jsonSerializer.write(writer, property);
  }

  return IOUtils.toInputStream(writer.toString(), Constants.ENCODING);
}
 
Example 14
private FixDir getFixDirWithTwoFiles1() {
    InputStream inputStream1 = IOUtils.toInputStream("stream");
    FixFile file1 = new FixFile(inputStream1);

    InputStream inputStream2 = IOUtils.toInputStream("stream2");
    FixFile file2 = new FixFile(inputStream2);

    Map<String, FixFsObject> content1 = Maps.newHashMap();
    content1.put("file1", file1);
    content1.put("file2", file2);
    return new FixDir(content1);
}
 
Example 15
/**
 * Finds the corresponding binding provider, replaces formatting markers
 * in the url (@see java.util.Formatter for further information) and executes
 * the formatted url.
 *
 * @param itemName the item context
 * @param command the executed command or one of the virtual commands
 *            (see {@link HttpGenericBindingProvider})
 * @param value the value to be used by the String.format method
 */
private void formatAndExecute(String itemName, Command command, Type value) {
    HttpBindingProvider provider = findFirstMatchingBindingProvider(itemName, command);

    if (provider == null) {
        logger.trace("Couldn't find matching binding provider [itemName={}, command={}]", itemName, command);
        return;
    }

    String httpMethod = provider.getHttpMethod(itemName, command);
    String url = provider.getUrl(itemName, command);
    if (format) {
        url = String.format(url, Calendar.getInstance().getTime(), value);
    }

    String body = provider.getBody(itemName, command);
    String transform = provider.getTransformation(itemName, command);
    if (transform != null) {
        body = transform(transform, command.toString());
        logger.debug("Using transformed command as body contents.");
    }
    InputStream stream = null;

    if (StringUtils.isNotBlank(httpMethod) && StringUtils.isNotBlank(url)) {
        if (httpMethod.equals("POST") && StringUtils.isNotBlank(body)) {
            try {
                stream = IOUtils.toInputStream(body, "UTF-8");
            } catch (IOException ioe) {
                logger.warn("Failed to convert the specified body into an acceptable input stream.", ioe);
                logger.debug("Body contents: {}", body);
            }
            logger.debug("Executing url '{}' via method {}, with body content '{}'", url, httpMethod, body);
            HttpUtil.executeUrl(httpMethod, url, provider.getHttpHeaders(itemName, command), stream, "text/plain",
                    timeout);
        } else {
            logger.debug("Executing url '{}' via method {}", url, httpMethod);
            HttpUtil.executeUrl(httpMethod, url, provider.getHttpHeaders(itemName, command), null, null, timeout);
        }
    } else {
        if (StringUtils.isBlank(httpMethod)) {
            logger.warn("The HTTP method specified was empty.");
        }
        if (StringUtils.isBlank(url)) {
            logger.warn("The URL specified was empty.");
        }
    }
}
 
Example 16
public DefaultHttpInputMessage(HttpInputMessage inputMessage) throws Exception {
    this.headers = inputMessage.getHeaders();
    this.body = IOUtils.toInputStream(DESHelper.decrypt(this.easpString(IOUtils.toString(inputMessage.getBody(), "UTF-8"))), "UTF-8");
}
 
Example 17
/**
   * ENH-560 - Inbound email server not working with custom types
   */
 public void testMessagesToSubTypeOfDocument() throws Exception
 {
     logger.debug("Start testMessagesToSubTypesOfDocument");
     
     String TEST_EMAIL="[email protected]";
     
     String TEST_SUBJECT="Practical Bee Keeping";
     
     String TEST_LONG_SUBJECT = "This is a very very long name in particular it is greater than eitghty six characters which was a problem explored in ALF-9544";
     
     
     // TODO Investigate why setting PROP_EMAIL on createPerson does not work.
     NodeRef person = personService.getPerson(TEST_USER);
     if(person == null)
     {
         logger.debug("new person created");
         Map<QName, Serializable> props = new HashMap<QName, Serializable>();
         props.put(ContentModel.PROP_USERNAME, TEST_USER);
         props.put(ContentModel.PROP_EMAIL, TEST_EMAIL);
         person = personService.createPerson(props);
     }
     nodeService.setProperty(person, ContentModel.PROP_EMAIL, TEST_EMAIL);

     Set<String> auths = authorityService.getContainedAuthorities(null, "GROUP_EMAIL_CONTRIBUTORS", true);
     if(!auths.contains(TEST_USER))
     {
         authorityService.addAuthority("GROUP_EMAIL_CONTRIBUTORS", TEST_USER);
     }
     
     String companyHomePathInStore = "/app:company_home"; 
     String storePath = "workspace://SpacesStore";
     StoreRef storeRef = new StoreRef(storePath);

     NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);
     List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore, null, namespaceService, false);
     NodeRef companyHomeNodeRef = nodeRefs.get(0);
     assertNotNull("company home is null", companyHomeNodeRef);
     String companyHomeDBID = ((Long)nodeService.getProperty(companyHomeNodeRef, ContentModel.PROP_NODE_DBID)).toString() + "@Alfresco.com";
//     String testUserDBID = ((Long)nodeService.getProperty(person, ContentModel.PROP_NODE_DBID)).toString() + "@Alfresco.com";
     NodeRef testUserHomeFolder = (NodeRef)nodeService.getProperty(person, ContentModel.PROP_HOMEFOLDER);
     assertNotNull("testUserHomeFolder is null", testUserHomeFolder);
//     String testUserHomeDBID = ((Long)nodeService.getProperty(testUserHomeFolder, ContentModel.PROP_NODE_DBID)).toString() + "@Alfresco.com";
     
     // Clean up old messages in test folder
     List<ChildAssociationRef> assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
     for(ChildAssociationRef assoc : assocs)
     {
         nodeService.deleteNode(assoc.getChildRef());
     }
     
     
     Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
     properties.put(ContentModel.PROP_NAME, "hamster");
     properties.put(ContentModel.PROP_DESCRIPTION, "syrian hamsters - test doc for email tests, sending to a subtype of cm:content");
     
     // Transfer report is a subtype of cm:content
     ChildAssociationRef testDoc = nodeService.createNode(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "bees"), TransferModel.TYPE_TRANSFER_REPORT, properties);
     NodeRef testDocNodeRef = testDoc.getChildRef();
     
     String testDocDBID = ((Long)nodeService.getProperty(testDocNodeRef, ContentModel.PROP_NODE_DBID)).toString();
     
     /**
      * Send From the test user TEST_EMAIL to the test user's home
      */
     String from = TEST_EMAIL;
     String to = testDocDBID + "@alfresco.com";
     String content = "hello world";
 
     Session sess = Session.getDefaultInstance(new Properties());
     assertNotNull("sess is null", sess);
     SMTPMessage msg = new SMTPMessage(sess);
     InternetAddress[] toa =  { new InternetAddress(to) };
 
     msg.setFrom(new InternetAddress(TEST_EMAIL));
     msg.setRecipients(Message.RecipientType.TO, toa);
     msg.setSubject(TEST_SUBJECT);
     msg.setContent(content, "text/plain");
         
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     msg.writeTo(bos);
     InputStream is = IOUtils.toInputStream(bos.toString());
     assertNotNull("is is null", is);
 
     SubethaEmailMessage m = new SubethaEmailMessage(is);   
     
     /**
      * Turn on overwriteDuplicates
      */
     logger.debug("Step 1: send an email to a transfer report");
           
     EmailDelivery delivery = new EmailDelivery(to, from, null);

     emailService.importMessage(delivery, m);
     
 }
 
Example 18
Source Project: milkman   File: ProtoDescriptorSerializerTest.java    License: MIT License 4 votes vote down vote up
protected FileDescriptorSet toDescriptor(String file) throws ProtocInvocationException {
	ProtocInvoker invoker = new ProtocInvoker(IOUtils.toInputStream(file));
	FileDescriptorSet descriptorSet = invoker.invoke();
	return descriptorSet;
}
 
Example 19
Source Project: hadoop-ozone   File: CRLCodec.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Gets the X.509 CRL from PEM encoded String.
 *
 * @param pemEncodedString - PEM encoded String.
 * @return X509CRL  - Crl.
 * @throws CRLException - Thrown on Failure.
 * @throws CertificateException - Thrown on Failure.
 * @throws IOException          - Thrown on Failure.
 */
public static X509CRL getX509CRL(String pemEncodedString)
    throws CRLException, CertificateException, IOException {
  CertificateFactory fact = CertificateFactory.getInstance("X.509");
  try (InputStream input = IOUtils.toInputStream(pemEncodedString, UTF_8)) {
    return (X509CRL) fact.generateCRL(input);
  }
}
 
Example 20
Source Project: esigate   File: XsltRenderer.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * @param xsl
 *            The xsl template to apply as a String
 * @throws IOException
 *             If an error occurs while writing to the output
 */
public XsltRenderer(String xsl) throws IOException {
    InputStream templateStream = IOUtils.toInputStream(xsl);
    transformer = createTransformer(templateStream);
}