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

The following are Jave code examples for showing how to use toString() 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: bootstrap   File: ExceptionMapperIT.java   View Source Code Vote up 7 votes
/**
 * @see ExceptionMapperResource#throwDataIntegrityUnicityException()
 */
@Test
public void testIntegrityUnicityError() throws IOException {
	final HttpDelete httpdelete = new HttpDelete(BASE_URI + RESOURCE + "/integrity-unicity");
	HttpResponse response = null;
	try {
		response = httpclient.execute(httpdelete);
		Assert.assertEquals(HttpStatus.SC_PRECONDITION_FAILED, response.getStatusLine().getStatusCode());
		final String content = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
		final Map<?, ?> result = new ObjectMapperTrim().readValue(content, HashMap.class);
		Assert.assertEquals("integrity-unicity", result.get("code"));
		Assert.assertNull(result.get("cause"));
		Assert.assertEquals("2003/PRIMARY", result.get("message"));
	} finally {
		if (response != null) {
			response.getEntity().getContent().close();
		}
	}
}
 
Example 2
Project: spring-react-example   File: ReactViewResolver.java   View Source Code Vote up 6 votes
public ReactViewResolver()
{
    final ClassLoader classLoader = this.getClass().getClassLoader();

    try
    {
        template = new BaseTemplate(
            IOUtils.toString(
                classLoader.getResourceAsStream(TEMPLATE_RESOURCE),
                BaseTemplate.UTF_8
            )
        );
    }
    catch (IOException e)
    {
        throw new ExampleException(e);
    }
}
 
Example 3
Project: urule   File: RepositoryResourceProvider.java   View Source Code Vote up 6 votes
@Override
public Resource provide(String path,String version) {
	String newpath=path.substring(4,path.length());
	InputStream inputStream=null;
	try {
		if(StringUtils.isEmpty(version) || version.equals("LATEST")){
			inputStream=repositoryService.readFile(newpath,null);											
		}else{
			inputStream=repositoryService.readFile(newpath,version);														
		}
		String content=IOUtils.toString(inputStream,"utf-8");
		IOUtils.closeQuietly(inputStream);
		return new Resource(content,path);
	} catch (Exception e) {
		throw new RuleException(e);
	}
}
 
Example 4
Project: AnyMall   File: GoodsCtrl.java   View Source Code Vote up 6 votes
@Override
protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	response.setContentType("application/json");
	response.setCharacterEncoding("utf-8");

	PrintWriter out = response.getWriter();

	String rawContent = IOUtils.toString(request.getReader());
	log.debug(String.format("request content: %s", rawContent));

	out.print(goodsDAO.findById(1));
}
 
Example 5
Project: nfse   File: GerarLoteRpsRespostaTest.java   View Source Code Vote up 5 votes
@Test
public void quandoErroPojoDeveSerGeradoCorretamente() throws IOException {
  String xmlTest = IOUtils
      .toString(getClass().getClassLoader().getResourceAsStream("erroConsultarLoteRpsResposta.xml"));

  ConsultarLoteRpsResposta pojo = ConsultarLoteRpsResposta.toPojo(xmlTest);
  assertNotNull(pojo.getListaMensagemRetornoLote());

}
 
Example 6
Project: InComb   File: TxtContentReader.java   View Source Code Vote up 5 votes
/**
 * Returns the content read form content-source.
 * @return read {@link Content}
 */
@Override
public Content[] read(final FetchHistory lastFetch) {

	final CloseableHttpClient httpClient = HttpClients.createDefault();
	final HttpGet httpget = new HttpGet(contentSource.getUrl());
	final HttpContext context = new BasicHttpContext();

	CloseableHttpResponse response = null;
	String stringRead = null;

	try {
		try {
			LOGGER.info("Loading uri: " + httpget.getURI());
			response = httpClient.execute(httpget, context);
			final HttpEntity entity = response.getEntity();

			if (entity != null) {
				stringRead = IOUtils.toString(entity.getContent());
				LOGGER.info("Read {} bytes from: {}", stringRead.getBytes().length, httpget.getURI());
			}

		} finally {
			CloseUtil.close(response);
			CloseUtil.close(httpClient);
		}

	} catch (final Exception e) {
		LOGGER.warn("Error occurred while reading text document: " + contentSource.getUrl());
	}

	return new Content[] { createContentObject(stringRead) };
}
 
Example 7
Project: xm-uaa   File: TenantService.java   View Source Code Vote up 5 votes
@SneakyThrows
private void addUaaSpecification(String tenantName) {
    String specificationName = applicationProperties.getTenantPropertiesName();
    InputStream in = new ClassPathResource(Constants.DEFAULT_CONFIG_PATH).getInputStream();
    String specification = IOUtils.toString(in, UTF_8);
    tenantConfigRepository.updateConfig(tenantName, "/" + specificationName, specification);
}
 
Example 8
Project: nfse   File: LoteRpsConsultaSituacaoTest.java   View Source Code Vote up 5 votes
@Test
public void xmlDeveSerGeradoCorretamente() throws IOException{
  String xmlTest = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("loteRpsConsultaSituacao.xml"));
  LoteRpsConsultaSituacao consultaSituacaoLote = new LoteRpsConsultaSituacao("AP1057893n16X103sfhF4RPm", FabricaDeObjetosFake.getRpsPrestador());
  String xml = consultaSituacaoLote.converterParaXml();
  
  Assert.assertEquals(xml, xmlTest);
}
 
Example 9
Project: urule   File: RepositoryServiceImpl.java   View Source Code Vote up 5 votes
@Override
public List<UserPermission> loadResourceSecurityConfigs(String companyId) throws Exception{
	List<UserPermission> configs=new ArrayList<UserPermission>();
	String filePath=RESOURCE_SECURITY_CONFIG_FILE+(companyId == null ? "" : companyId);
	Node rootNode=getRootNode();
	Node fileNode = rootNode.getNode(filePath);
	Property property = fileNode.getProperty(DATA);
	Binary fileBinary = property.getBinary();
	InputStream inputStream = fileBinary.getStream();
	String content = IOUtils.toString(inputStream, "utf-8");
	inputStream.close();
	Document document = DocumentHelper.parseText(content);
	Element rootElement = document.getRootElement();
	for (Object obj : rootElement.elements()) {
		if (!(obj instanceof Element)) {
			continue;
		}
		Element element = (Element) obj;
		if (!element.getName().equals("user-permission")) {
			continue;
		}
		UserPermission userResource=new UserPermission();
		userResource.setUsername(element.attributeValue("username"));
		userResource.setProjectConfigs(parseProjectConfigs(element));
		configs.add(userResource);
	}
	return configs;
}
 
Example 10
Project: ymate-payment-v2   File: WxPayRequestProcessor.java   View Source Code Vote up 5 votes
public Map<String, Object> processRequestParams(IWebMvc owner, RequestMeta requestMeta) throws Exception {
    Map<String, Object> _params = new HashMap<String, Object>();
    //
    if (!requestMeta.getMethodParamNames().isEmpty()) {
        String _protocol = IOUtils.toString(WebContext.getRequest().getInputStream(), owner.getModuleCfg().getDefaultCharsetEncoding());
        if (StringUtils.isNotBlank(_protocol)) {
            WxPayNotifyResponse _response = WxPayNotifyResponse.bind(_protocol);
            _params.put(requestMeta.getMethodParamNames().get(0), _response);
        }
    }
    return _params;
}
 
Example 11
Project: wayf-cloud   File: ClientJsFacadeImpl.java   View Source Code Vote up 5 votes
public void initTemplateFile() {
    if (templateFile == null) {
        try {
            templateFile = IOUtils.toString(Thread.currentThread().getContextClassLoader().getResourceAsStream(TEMPLATE_FILE), StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Could not read widget tempalte file", e);
        }
    }
}
 
Example 12
Project: ibm-cos-sdk-java   File: ResettableInputStreamTest.java   View Source Code Vote up 5 votes
@Test
public void testResetFileInputStream() throws IOException {
    ResettableInputStream is = new ResettableInputStream(
            new FileInputStream(file));
    assertTrue(is.markSupported());
    final String content = IOUtils.toString(is);
    is.reset();
    final String content2 = IOUtils.toString(is);
    assertTrue(content.length() == 100);
    assertEquals(content, content2);
    is.close();
    assertNull(is.getFile());
}
 
Example 13
Project: libcwfincore   File: JdbiProductEntityDao.java   View Source Code Vote up 5 votes
private String getAllQuery() {
    URL queryLoc = getClass().getResource(getClass().getSimpleName() + "_getAll.sql");
    try {
        return IOUtils.toString(queryLoc, "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 14
Project: living-documentation   File: FileUtils.java   View Source Code Vote up 5 votes
public static String read(File file) throws MojoExecutionException {
    if (file == null || !file.exists()) {
        return StringUtils.EMPTY;
    }
    try {
        return IOUtils.toString(file.toURI(), Charset.defaultCharset());
    } catch (IOException e) {
        throw new MojoExecutionException("Unable to read header file !", e);
    }
}
 
Example 15
Project: domino   File: ServerModuleAnnotationProcessorTest.java   View Source Code Vote up 4 votes
private String getExpectedResultFileContent(String resourceName) throws IOException {
    try (InputStream resourceInputStream = this.getClass().getResourceAsStream("results/" + resourceName)) {
        return IOUtils.toString(resourceInputStream, "UTF-8");
    }
}
 
Example 16
Project: trellis   File: AbstractLdpResourceTest.java   View Source Code Vote up 4 votes
@Test
public void testGetTimeMapJsonCompact() throws IOException {
    when(mockResource.getMementos()).thenReturn(asList(
            between(ofEpochSecond(timestamp - 2000), ofEpochSecond(timestamp - 1000)),
            between(ofEpochSecond(timestamp - 1000), time),
            between(time, ofEpochSecond(timestamp + 1000))));

    final Response res = target(RESOURCE_PATH).queryParam("ext", "timemap").request()
        .accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();

    assertEquals(OK, res.getStatusInfo());
    assertTrue(APPLICATION_LD_JSON_TYPE.isCompatible(res.getMediaType()));
    assertTrue(res.getMediaType().isCompatible(APPLICATION_LD_JSON_TYPE));
    assertNull(res.getHeaderString(ACCEPT_POST));
    assertNull(res.getHeaderString(ACCEPT_PATCH));
    assertNull(res.getHeaderString(ACCEPT_RANGES));
    assertNull(res.getLastModified());

    // Jersey's client doesn't parse complex link headers correctly, so res.getLinks() is not used here
    final List<Link> links = res.getStringHeaders().get(LINK).stream().map(Link::valueOf).collect(toList());

    assertTrue(links.stream().anyMatch(l -> l.getRels().contains("memento") &&
                RFC_1123_DATE_TIME.withZone(UTC).format(ofEpochSecond(timestamp - 2000))
                    .equals(l.getParams().get("datetime")) &&
                l.getUri().toString().equals(BASE_URL + RESOURCE_PATH + "?version=1496260729000")));
    assertTrue(links.stream().anyMatch(l -> l.getRels().contains("memento") &&
                RFC_1123_DATE_TIME.withZone(UTC).format(ofEpochSecond(timestamp - 1000))
                    .equals(l.getParams().get("datetime")) &&
                l.getUri().toString().equals(BASE_URL + RESOURCE_PATH + "?version=1496261729000")));
    assertTrue(links.stream().anyMatch(l -> l.getRels().contains("memento") &&
                RFC_1123_DATE_TIME.withZone(UTC).format(time).equals(l.getParams().get("datetime")) &&
                l.getUri().toString().equals(BASE_URL + RESOURCE_PATH + "?version=1496262729000")));
    assertTrue(links.stream().anyMatch(l -> l.getRels().contains("timemap") &&
                RFC_1123_DATE_TIME.withZone(UTC).format(ofEpochSecond(timestamp - 2000))
                    .equals(l.getParams().get("from")) &&
                RFC_1123_DATE_TIME.withZone(UTC).format(ofEpochSecond(timestamp + 1000))
                    .equals(l.getParams().get("until")) &&
                APPLICATION_LINK_FORMAT.equals(l.getType()) &&
                l.getUri().toString().equals(BASE_URL + RESOURCE_PATH + "?ext=timemap")));
    assertTrue(links.stream().anyMatch(l -> l.getRels().contains("timegate") &&
                l.getUri().toString().equals(BASE_URL + RESOURCE_PATH)));
    assertTrue(links.stream().anyMatch(l -> l.getRels().contains("original") &&
                l.getUri().toString().equals(BASE_URL + RESOURCE_PATH)));
    assertTrue(links.stream().anyMatch(hasType(LDP.Resource)));
    assertTrue(links.stream().anyMatch(hasType(LDP.RDFSource)));
    assertFalse(links.stream().anyMatch(hasType(LDP.Container)));

    assertFalse(res.getAllowedMethods().contains("PATCH"));
    assertFalse(res.getAllowedMethods().contains("PUT"));
    assertFalse(res.getAllowedMethods().contains("DELETE"));
    assertTrue(res.getAllowedMethods().contains("GET"));
    assertTrue(res.getAllowedMethods().contains("HEAD"));
    assertTrue(res.getAllowedMethods().contains("OPTIONS"));
    assertFalse(res.getAllowedMethods().contains("POST"));
    assertNull(res.getHeaderString(MEMENTO_DATETIME));

    final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
    final Map<String, Object> obj = MAPPER.readValue(entity,
            new TypeReference<Map<String, Object>>(){});

    @SuppressWarnings("unchecked")
    final List<Map<String, Object>> graph = (List<Map<String, Object>>) obj.get("@graph");

    assertEquals(5L, graph.size());
    assertTrue(graph.stream().anyMatch(x -> x.containsKey("@id") &&
                x.get("@id").equals(BASE_URL + RESOURCE_PATH) &&
                x.containsKey("timegate") && x.containsKey("timemap") && x.containsKey("memento")));
    assertTrue(graph.stream().anyMatch(x -> x.containsKey("@id") &&
                x.get("@id").equals(BASE_URL + RESOURCE_PATH + "?ext=timemap") &&
                x.containsKey("hasBeginning") &&
                x.containsKey("hasEnd")));
    assertTrue(graph.stream().anyMatch(x -> x.containsKey("@id") &&
                x.get("@id").equals(BASE_URL + RESOURCE_PATH + "?version=1496260729000") &&
                x.containsKey("hasTime")));
    assertTrue(graph.stream().anyMatch(x -> x.containsKey("@id") &&
                x.get("@id").equals(BASE_URL + RESOURCE_PATH + "?version=1496261729000") &&
                x.containsKey("hasTime")));
    assertTrue(graph.stream().anyMatch(x -> x.containsKey("@id") &&
                x.get("@id").equals(BASE_URL + RESOURCE_PATH + "?version=1496262729000") &&
                x.containsKey("hasTime")));
}
 
Example 17
Project: qpp-conversion-tool   File: PathSourceTest.java   View Source Code Vote up 4 votes
@Test
void testInputStream() throws IOException {
	String content = IOUtils.toString(source.toInputStream(), StandardCharsets.UTF_8);
	assertWithMessage("stream content was not as expected")
			.that(content).isEqualTo("hello, world");
}
 
Example 18
Project: gdl2   File: TestCommon.java   View Source Code Vote up 4 votes
String loadJson(String name) throws Exception {
    return IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream((name + ".json")), "UTF-8");
}
 
Example 19
Project: SuprDiscordBot   File: InternetAPI.java   View Source Code Vote up 3 votes
/**
 * Performs a HTTP request, returns a string.
 *
 * @param urlStr The URL to be (HTTP) requested.
 * @return A string with the page's content.
 * @throws IOException May throw an IOException, so you can handle errors yourself.
 * @since 1.2
 */
public String httpString(String urlStr) throws IOException
{
	java.net.URL url = new URL(urlStr);
	HttpURLConnection uc = (HttpURLConnection) url.openConnection();
	InputStream in = uc.getInputStream();
	return IOUtils.toString(in, "UTF-8");
}
 
Example 20
Project: GitHub   File: OutputEncodingIT.java   View Source Code Vote up 3 votes
@Test
public void writeExtendedCharactersAsSingleByteSourceCode() throws IOException {

    File outputDirectory = schemaRule.generate("/schema/regression/extendedCharacters.json", "com.example", config("outputEncoding", "iso-8859-5"));

    File sourceFile = new File(outputDirectory, "com/example/ExtendedCharacters.java");
    String javaSource = IOUtils.toString(new FileInputStream(sourceFile), "iso-8859-5");

    assertThat(javaSource, containsString("ЫЩДђиЊЉЯ"));
}