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

The following are Jave code examples for showing how to use toInputStream() of the org.apache.commons.io.IOUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: carml   File: RmlMapperTest.java   View Source Code Vote up 6 votes
@Test
public void mapper_boundWithMultipleNamedAndOneUnnamedInputStreams_shouldReadCorrespondingStreams() {
	String streamName = "foo";
	String secondStreamName = "bar";
	stream = new CarmlStream(streamName);
	InputStream inputStream = IOUtils.toInputStream(input);
	InputStream secondInputStream = IOUtils.toInputStream(secondInput);
	String unnamedInput = "unnamed test input";
	InputStream unnamedInputStream = IOUtils.toInputStream(unnamedInput);
	mapper.bindInputStream(streamName, inputStream);
	mapper.bindInputStream(secondStreamName, secondInputStream);
	mapper.bindInputStream(unnamedInputStream);
	assertThat(mapper.getSourceManager().getSource(streamName), is(input));
	assertThat(mapper.getSourceManager().getSource(secondStreamName), is(secondInput));
	assertThat(mapper.getSourceManager().getSource(RmlMapper.DEFAULT_STREAM_NAME), is(unnamedInput));
}
 
Example 2
Project: jhipster-microservices-example   File: SwaggerBasePathRewritingFilterTest.java   View Source Code Vote up 6 votes
@Test
public void run_on_valid_response() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

    MockHttpServletResponse response = new MockHttpServletResponse();
    context.setResponseGZipped(false);
    context.setResponse(response);

    InputStream in = IOUtils.toInputStream("{\"basePath\":\"/\"}", StandardCharsets.UTF_8);
    context.setResponseDataStream(in);

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());
    assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody());
}
 
Example 3
Project: Microservices-with-JHipster-and-Spring-Boot   File: SwaggerBasePathRewritingFilterTest.java   View Source Code Vote up 6 votes
@Test
public void run_on_valid_response() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

    MockHttpServletResponse response = new MockHttpServletResponse();
    context.setResponseGZipped(false);
    context.setResponse(response);

    InputStream in = IOUtils.toInputStream("{\"basePath\":\"/\"}", StandardCharsets.UTF_8);
    context.setResponseDataStream(in);

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());
    assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody());
}
 
Example 4
Project: Armory   File: SwaggerBasePathRewritingFilterTest.java   View Source Code Vote up 6 votes
@Test
public void run_on_valid_response() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

    MockHttpServletResponse response = new MockHttpServletResponse();
    context.setResponseGZipped(false);
    context.setResponse(response);

    InputStream in = IOUtils.toInputStream("{\"basePath\":\"/\"}", StandardCharsets.UTF_8);
    context.setResponseDataStream(in);

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());
    assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody());
}
 
Example 5
Project: xm-gate   File: SwaggerBasePathRewritingFilterTest.java   View Source Code Vote up 6 votes
@Test
public void run_on_valid_response() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

    MockHttpServletResponse response = new MockHttpServletResponse();
    context.setResponseGZipped(false);
    context.setResponse(response);

    InputStream in = IOUtils.toInputStream("{\"basePath\":\"/\"}", StandardCharsets.UTF_8);
    context.setResponseDataStream(in);

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());
    assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody());
}
 
Example 6
Project: ureport   File: DesignerServletAction.java   View Source Code Vote up 6 votes
public void saveReportFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String file=req.getParameter("file");
	file=ReportUtils.decodeFileName(file);
	String content=req.getParameter("content");
	ReportProvider targetReportProvider=null;
	for(ReportProvider provider:reportProviders){
		if(file.startsWith(provider.getPrefix())){
			targetReportProvider=provider;
			break;
		}
	}
	if(targetReportProvider==null){
		throw new ReportDesignException("File ["+file+"] not found available report provider.");
	}
	targetReportProvider.saveReport(file, content);
	InputStream inputStream=IOUtils.toInputStream(content,"utf-8");
	ReportDefinition reportDef=reportParser.parse(inputStream, file);
	reportRender.rebuildReportDefinition(reportDef);
	CacheUtils.cacheReportDefinition(file, reportDef);
	IOUtils.closeQuietly(inputStream);
}
 
Example 7
Project: pay   File: XMLParser.java   View Source Code Vote up 6 votes
public static Map<String,Object> getMapFromXML(String xmlString) throws ParserConfigurationException, IOException, SAXException {

        //这里用Dom的方式解析回包的最主要目的是防止API新增回包字段
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream is =  IOUtils.toInputStream(xmlString);
        Document document = builder.parse(is);
        //获取到document里面的全部结点
        NodeList allNodes = document.getFirstChild().getChildNodes();
        Node node;
        Map<String, Object> map = new HashMap<String, Object>();
        int i=0;
        while (i < allNodes.getLength()) {
            node = allNodes.item(i);
            if(node instanceof Element){
                map.put(node.getNodeName(),node.getTextContent());
            }
            i++;
        }
        return map;

    }
 
Example 8
Project: osc-core   File: VersionUtilTest.java   View Source Code Vote up 6 votes
public void testGetVersion_WithMockedManifest_ReturnsValidVersion() throws IOException {
    //  Arrange.
    PowerMockito.mockStatic(VersionUtil.class);
    PowerMockito.when(VersionUtil.getVersion()).thenCallRealMethod();
    PowerMockito.when(VersionUtil.class.getPackage()).thenReturn(this.aPackage);
    PowerMockito.when(VersionUtil.class.getClassLoader()).thenReturn(this.classLoader);
    PowerMockito.when(this.classLoader.findResource(Matchers.anyString())).thenReturn(this.mockedUrl);
    InputStream stubInputStream = IOUtils.toInputStream(this.MANIFEST_CONTENT, Charset.defaultCharset());
    PowerMockito.when(this.mockedUrl.openStream()).thenReturn(stubInputStream);
    PowerMockito.when(this.aPackage.getImplementationVersion()).thenReturn("1.0.0");

    // Act.
    Version version = VersionUtil.getVersion();

    // Assert.
    Assert.assertTrue("11" == version.getBuild());
    Assert.assertEquals("1476885882", version.getBuildTime());
    Assert.assertTrue(1 == version.getMajor());
    Assert.assertTrue(2 == version.getMinor());
}
 
Example 9
Project: osc-core   File: ServerUtilTest.java   View Source Code Vote up 6 votes
@Test
public void testGetPidByProcessName_WithImproperData_ReturnsNothing() throws IOException, InterruptedException {
    // Arrange.
    InputStream stubInputStream = IOUtils.toInputStream(
            " PID TTY STAT TIME COMMAND\n 9990 ? Ss 0:07 /test/java\n " + this.oldProcessId + " ? Ss 0:07 /osc/java",
            Charset.defaultCharset());

    PowerMockito.when(this.processMock.getInputStream()).thenReturn(stubInputStream);
    PowerMockito.when(this.runtimeMock.exec(this.linuxProcessExec)).thenReturn(this.processMock);

    Mockito.when(Runtime.getRuntime()).thenReturn(this.runtimeMock);

    // Act.
    String foundPid = ServerUtil.getPidByProcessName("/osc/test");

    // Assert.
    Assert.assertNull(foundPid);
}
 
Example 10
Project: mxisd   File: EmailSmtpConnector.java   View Source Code Vote up 5 votes
@Override
public void send(String senderAddress, String senderName, String recipient, String content) {
    if (StringUtils.isBlank(senderAddress)) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - " +
                "You must set a value for notifications to work");
    }

    if (StringUtils.isBlank(content)) {
        throw new InternalServerError("Notification content is empty");
    }

    try {
        InternetAddress sender = new InternetAddress(senderAddress, senderName);
        MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8));
        msg.setHeader("X-Mailer", "mxisd"); // FIXME set version
        msg.setSentDate(new Date());
        msg.setFrom(sender);
        msg.setRecipients(Message.RecipientType.TO, recipient);
        msg.saveChanges();

        log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort());
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        transport.setStartTLS(cfg.getTls() > 0);
        transport.setRequireStartTLS(cfg.getTls() > 1);

        log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort());
        transport.connect(cfg.getHost(), cfg.getPort(), cfg.getLogin(), cfg.getPassword());
        try {
            transport.sendMessage(msg, InternetAddress.parse(recipient));
            log.info("Invite to {} was sent", recipient);
        } finally {
            transport.close();
        }
    } catch (UnsupportedEncodingException | MessagingException e) {
        throw new RuntimeException("Unable to send e-mail invite to " + recipient, e);
    }
}
 
Example 11
Project: esup-sgc   File: CsvExportP2sService.java   View Source Code Vote up 5 votes
public void sync() throws IOException {
	InputStream csv = IOUtils.toInputStream(sgc2csv(null).toString(), ENCODING_P2S);
	AppliConfig appliConfig = AppliConfig.findAppliConfigByKey("P2S_EXPORT_CSV_FILE_NAME");
	String filename = appliConfig.getValue();
	Date date = new Date();
	p2sVfsAccessService.putFile(null, date.getTime() + "_" + filename, csv, false);
}
 
Example 12
Project: TOSCAna   File: PluginFileAccessTest.java   View Source Code Vote up 5 votes
@Test
public void readSuccessful() throws IOException {
    String path = "file";
    File file = new File(sourceDir, path);
    InputStream inputStream = IOUtils.toInputStream(fileContent, "UTF-8");
    FileUtils.copyInputStreamToFile(inputStream, file);
    String result = access.read(path);

    assertNotNull(result);

    assertEquals(fileContent, result);
}
 
Example 13
Project: esup-sgc   File: CsvExportTilService.java   View Source Code Vote up 5 votes
@Override
public void sync(List<String> eppns) throws IOException {
	InputStream csv = IOUtils.toInputStream(sgc2csv(eppns).toString(), ENCODING_TIL);
	AppliConfig appliConfig = AppliConfig.findAppliConfigByKey("TIL_EXPORT_CSV_FILE_NAME");
	String filename = appliConfig.getValue();
	tilVfsAccessService.putFile(null, filename, csv, true);
}
 
Example 14
Project: carml   File: RmlMapperTest.java   View Source Code Vote up 5 votes
@Test
public void mapper_boundWithMultipleNamedInputStreams_shouldReadLastBoundStream() {
	String streamName = "foo";
	String secondStreamName = "bar";
	InputStream inputStream = IOUtils.toInputStream(input);
	InputStream secondInputStream = IOUtils.toInputStream(secondInput);
	mapper.bindInputStream(streamName, inputStream);
	assertThat(mapper.getSourceManager().getSource(streamName), is(input));
	mapper.bindInputStream(secondStreamName, secondInputStream);
	assertThat(mapper.getSourceManager().getSource(secondStreamName), is(secondInput));
}
 
Example 15
Project: carml   File: RmlMapperTest.java   View Source Code Vote up 5 votes
@Test
public void mapper_boundWithMultipleUnnamedInputStreams_shouldReadLastBoundStream() {
	InputStream inputStream = IOUtils.toInputStream(input);
	InputStream secondInputStream = IOUtils.toInputStream(secondInput);
	mapper.bindInputStream(inputStream);
	assertThat(mapper.getSourceManager().getSource(RmlMapper.DEFAULT_STREAM_NAME), is(input));
	mapper.bindInputStream(secondInputStream);
	assertThat(mapper.getSourceManager().getSource(RmlMapper.DEFAULT_STREAM_NAME), is(secondInput));
}
 
Example 16
Project: carml   File: RmlMapperTest.java   View Source Code Vote up 5 votes
@Test
public void mapper_boundWithMultipleNamedInputStreams_shouldReadCorrespondingStreams() {
	String streamName = "foo";
	String secondStreamName = "bar";
	stream = new CarmlStream(streamName);
	InputStream inputStream = IOUtils.toInputStream(input);
	String secondInput = "second test input";
	InputStream secondInputStream = IOUtils.toInputStream(secondInput);
	mapper.bindInputStream(streamName, inputStream);
	mapper.bindInputStream(secondStreamName, secondInputStream);
	assertThat(mapper.getSourceManager().getSource(streamName), is(input));
	assertThat(mapper.getSourceManager().getSource(secondStreamName), is(secondInput));
}
 
Example 17
Project: carml   File: RmlMapperTest.java   View Source Code Vote up 5 votes
@Test
public void mapper_boundWithNamedInputStream_shouldReadCorrespondingInputStream() {
	String streamName = "foo";
	stream = new CarmlStream(streamName);
	InputStream inputStream = IOUtils.toInputStream(input);
	mapper.bindInputStream(streamName, inputStream);
	assertThat(mapper.getSourceManager().getSource(streamName), is(input));
}
 
Example 18
Project: sonar-issueresolver-plugin   File: MockRequest.java   View Source Code Vote up 4 votes
@Override
public InputStream paramAsInputStream(String key) {
	return IOUtils.toInputStream(param(key));
}
 
Example 19
Project: alfresco-repository   File: EmailServiceImplTest.java   View Source Code Vote up 4 votes
/**
 * MNT-9289
 * 
 * Change in case in email Subject causes DuplicateChildNodeNameException
 */
public void testCaseSensitivity() throws Exception
{
 NodeRef person = personService.getPerson(TEST_USER);
 String TEST_EMAIL="[email protected]";
 NodeRef testUserHomeFolder = (NodeRef)nodeService.getProperty(person, ContentModel.PROP_HOMEFOLDER);
    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 TEST_CASE_SENSITIVITY_SUBJECT = "Test (Mail)";
    String testUserHomeDBID = ((Long)nodeService.getProperty(testUserHomeFolder, ContentModel.PROP_NODE_DBID)).toString() + "@Alfresco.com";
 
    String from = TEST_EMAIL;
    String to = testUserHomeDBID;
    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) };
    
    EmailDelivery delivery = new EmailDelivery(to, from, null);

    msg.setFrom(new InternetAddress(TEST_EMAIL));
    msg.setRecipients(Message.RecipientType.TO, toa);
    msg.setContent(content, "text/plain");
 
    msg.setSubject(TEST_CASE_SENSITIVITY_SUBJECT);
    ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
    msg.writeTo(bos1);
    InputStream is = IOUtils.toInputStream(bos1.toString());
    assertNotNull("is is null", is);
    SubethaEmailMessage m = new SubethaEmailMessage(is);  
    folderEmailMessageHandler.setOverwriteDuplicates(false);
    emailService.importMessage(delivery, m);
    
    QName safeQName = QName.createQNameWithValidLocalName(NamespaceService.CONTENT_MODEL_1_0_URI, TEST_CASE_SENSITIVITY_SUBJECT);
    List<ChildAssociationRef> assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, safeQName);
    assertEquals(1, assocs.size());
    
    msg.setSubject(TEST_CASE_SENSITIVITY_SUBJECT.toUpperCase());
    ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
    msg.writeTo(bos2);
    is = IOUtils.toInputStream(bos2.toString());
    assertNotNull("is is null", is);
    m = new SubethaEmailMessage(is);  
    folderEmailMessageHandler.setOverwriteDuplicates(false);
    emailService.importMessage(delivery, m);
    
    safeQName = QName.createQNameWithValidLocalName(NamespaceService.CONTENT_MODEL_1_0_URI, TEST_CASE_SENSITIVITY_SUBJECT.toUpperCase() +  "(1)");
    assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, safeQName);
    assertEquals(1, assocs.size());
}
 
Example 20
Project: uflo   File: DesignerServletHandler.java   View Source Code Vote up 4 votes
public void deploy(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String content=req.getParameter("content");
	InputStream inputStream=IOUtils.toInputStream(content, "utf-8");
	processService.deployProcess(inputStream);
	IOUtils.closeQuietly(inputStream);
}