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:com.collective.celos.ci.testing.fixtures.compare.PlainFileComparerTest.java

@Test
public void testCompareFails() throws Exception {

    InputStream inputStream1 = IOUtils.toInputStream("stream");
    InputStream inputStream2 = IOUtils.toInputStream("stream2");

    FixFile fixFile1 = mock(FixFile.class);
    PlainFileComparer comparer = new PlainFileComparer(inputStream2, fixFile1);

    doReturn(inputStream1).when(fixFile1).getContent();
    FixObjectCompareResult compareResult = comparer.check(null);

    Assert.assertEquals(compareResult.getStatus(), FixObjectCompareResult.Status.FAIL);
}

From source file:io.dfox.junit.example.NoteRepositoryTest.java

@Test
public void testSaveFind() throws IOException {

    final String name = "test-note";
    final String contents = "This is my note";

    assertFalse(repository.getNote(name).isPresent());

    try (InputStream contentsStream = IOUtils.toInputStream(contents)) {
        repository.saveNote(name, contentsStream);
    }//from  ww  w  .j a v  a  2s .  co  m

    Optional<InputStream> note = repository.getNote(name);
    assertTrue(note.isPresent());
    try (InputStream stream = note.get()) {
        String savedContents = IOUtils.toString(stream);
        Assert.assertEquals(contents, savedContents);
    }
}

From source file:baggage.guerilla.GuerillaParserTest.java

public void testParse() throws Exception {
    String snippet = "junk <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n"
            + "<html>\n" + "<body foo=\"bar\" hello='world'>\n" + "See, I am able to parseFromJSON\n"
            + "</html>\n";

    GuerillaParser parser = new GuerillaParser(IOUtils.toInputStream(snippet));
    TextItem textItem = (TextItem) parser.next(false);
    assertEquals("junk ", textItem.getStringValue());
    DoctypeDeclaration docTypeDeclaration = (DoctypeDeclaration) parser.next(false);
    assertEquals("DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"",
            docTypeDeclaration.getStringValue());
    assertEquals("\n", parser.next(false).getStringValue());
    OpeningTag html = (OpeningTag) parser.next(false);
    assertEquals("html", html.getStringValue());
    assertEquals("\n", parser.next(false).getStringValue());
    OpeningTag body = (OpeningTag) parser.next(false);
    assertEquals("body", body.getStringValue());
    assertEquals(2, body.getAttributes().size());
    assertEquals("\nSee, I am able to parseFromJSON\n", parser.next(false).getStringValue());
}

From source file:edu.lternet.pasta.common.EmlUtility.java

public static EmlPackageId emlPackageIdFromEML(File emlFile) throws Exception {
    EmlPackageId emlPackageId = null;//  w  w  w . j a  va  2  s  .c o m

    if (emlFile != null) {
        String emlString = FileUtils.readFileToString(emlFile);
        try {
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document document = documentBuilder.parse(IOUtils.toInputStream(emlString));
            emlPackageId = getEmlPackageId(document);
        }
        /*
         * If a parsing exception is thrown, attempt to parse the packageId
         * using regular expressions. This could be fooled by comments text
         * in the EML document but is still better than nothing at all.
         */
        catch (SAXException e) {
            StringTokenizer stringTokenizer = new StringTokenizer(emlString, "\n");
            String DOUBLE_QUOTE_PATTERN = "packageId=\"([^\"]*)\"";
            String SINGLE_QUOTE_PATTERN = "packageId='([^']*)'";
            Pattern doubleQuotePattern = Pattern.compile(DOUBLE_QUOTE_PATTERN);
            Pattern singleQuotePattern = Pattern.compile(SINGLE_QUOTE_PATTERN);
            while (stringTokenizer.hasMoreElements()) {
                String token = stringTokenizer.nextToken();
                if (token.contains("packageId")) {

                    Matcher doubleQuoteMatcher = doubleQuotePattern.matcher(token);
                    if (doubleQuoteMatcher.find()) {
                        String packageId = doubleQuoteMatcher.group(1);
                        System.out.println(packageId);
                        EmlPackageIdFormat formatter = new EmlPackageIdFormat(Delimiter.DOT);
                        emlPackageId = formatter.parse(packageId);
                        break;
                    }

                    Matcher singleQuoteMatcher = singleQuotePattern.matcher(token);
                    if (singleQuoteMatcher.find()) {
                        String packageId = singleQuoteMatcher.group(1);
                        EmlPackageIdFormat formatter = new EmlPackageIdFormat(Delimiter.DOT);
                        emlPackageId = formatter.parse(packageId);
                        break;
                    }

                }
            }
        }
    }

    return emlPackageId;
}

From source file:com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptorParserTest.java

@Test
public void shouldPerformPluginXsdValidationAndFailWhenVersionIsNotPresent() throws Exception {
    InputStream pluginXml = IOUtils.toInputStream("<go-plugin id=\"some\"></go-plugin>");
    try {//  w  w  w . jav  a  2  s.co m
        GoPluginDescriptorParser.parseXML(pluginXml, "/tmp/", new File("/tmp/"), true);
        fail("xsd validation should have failed");
    } catch (SAXException e) {
        assertThat(e.getMessage(), is("XML Schema validation of Plugin Descriptor(plugin.xml) failed"));
    }
}

From source file:com.adobe.cq.wcm.core.components.Utils.java

/**
 * Provided a {@code model} object and an {@code expectedJsonResource} identifying a JSON file in the class path, this method will
 * test the JSON export of the model and compare it to the JSON object provided by the {@code expectedJsonResource}.
 *
 * @param model                the Sling Model
 * @param expectedJsonResource the class path resource providing the expected JSON object
 *///  ww w .  j  a v a  2 s  . c  o m
public static void testJSONExport(Object model, String expectedJsonResource) {
    Writer writer = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    PageModuleProvider pageModuleProvider = new PageModuleProvider();
    mapper.registerModule(pageModuleProvider.getModule());
    DefaultMethodSkippingModuleProvider defaultMethodSkippingModuleProvider = new DefaultMethodSkippingModuleProvider();
    mapper.registerModule(defaultMethodSkippingModuleProvider.getModule());
    try {
        mapper.writer().writeValue(writer, model);
    } catch (IOException e) {
        fail(String.format("Unable to generate JSON export for model %s: %s", model.getClass().getName(),
                e.getMessage()));
    }
    JsonReader outputReader = Json.createReader(IOUtils.toInputStream(writer.toString()));
    InputStream is = Thread.currentThread().getContextClassLoader().getClass()
            .getResourceAsStream(expectedJsonResource);
    if (is != null) {
        JsonReader expectedReader = Json.createReader(is);
        assertEquals(expectedReader.read(), outputReader.read());
    } else {
        fail("Unable to find test file " + expectedJsonResource + ".");
    }
    IOUtils.closeQuietly(is);
}

From source file:com.norconex.importer.handler.transformer.impl.ReplaceTransformerTest.java

@Test
public void testTransformTextDocument() throws IOException, ImporterHandlerException {
    String text = "I like to eat cakes and candies.";

    ReplaceTransformer t = new ReplaceTransformer();

    Reader reader = new InputStreamReader(IOUtils.toInputStream(xml));
    t.loadFromXML(reader);//from  w ww .  j  a v  a 2s  .c o m
    reader.close();

    InputStream is = IOUtils.toInputStream(text);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    t.transformDocument("dummyRef", is, os, new ImporterMetadata(), true);

    String response = os.toString();
    System.out.println(response);
    Assert.assertEquals("i like to eat fruits and vegetables.", response.toLowerCase());

    is.close();
    os.close();
}

From source file:com.collective.celos.ci.testing.fixtures.convert.ConversionCreatorTest.java

@Test
public void testConversionCreatorForDir() throws Exception {
    FixFile fixFile = new FixFile(IOUtils.toInputStream("lowercase"));
    Map<String, FixFsObject> map = Maps.newHashMap();
    map.put("file", fixFile);
    FixObjectCreator<FixDir> creator = Utils.wrap(new FixDir(map));
    AbstractFixObjectConverter<FixDir, FixDir> fixObjectConverter = new FixDirRecursiveConverter(
            new UpperCaseStringFixFileConverter());
    ConversionCreator<FixDir, FixDir> conversionCreator = new ConversionCreator(creator, fixObjectConverter);

    FixDir result = conversionCreator.create(null);
    Assert.assertEquals("LOWERCASE", IOUtils.toString(result.getChildren().get("file").asFile().getContent()));
}

From source file:fm.last.musicbrainz.coverart.impl.FetchJsonListingResponseHandlerTest.java

@Before
public void initialise() throws IllegalStateException, IOException {
    inputStream = IOUtils.toInputStream("JSON");
    when(entity.getContent()).thenReturn(inputStream);
    when(response.getStatusLine()).thenReturn(statusLine);
}

From source file:com.norconex.importer.handler.transformer.impl.ReduceConsecutivesTransformerTest.java

@Test
public void testTransformTextDocument() throws ImporterHandlerException {
    String text = "\t\tThis is the text TeXt I want to modify...\n\r\n\r" + "     Too much space.";

    ReduceConsecutivesTransformer t = new ReduceConsecutivesTransformer();

    Reader reader = new InputStreamReader(IOUtils.toInputStream(xml));
    try {//from   ww  w  .j av a 2s.  c  om
        t.loadFromXML(reader);
    } catch (IOException e) {
        throw new ImporterHandlerException("Could not reduce consecutives.", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    InputStream is = IOUtils.toInputStream(text);
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    try {
        t.transformDocument("dummyRef", is, os, new ImporterMetadata(), true);
        String response = os.toString();
        System.out.println(response);
        Assert.assertEquals("\tthis is the text i want to modify.\n\r too much space.", response.toLowerCase());
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}