List of usage examples for com.google.common.io CharStreams toString
public static String toString(Readable r) throws IOException
From source file:org.codice.ddf.spatial.kml.transformer.KmlInputTransformer.java
@Override public Metacard transform(InputStream inputStream, String id) throws IOException, CatalogTransformerException { MetacardImpl metacard;//from ww w .j a v a2s . co m try (TemporaryFileBackedOutputStream fileBackedOutputStream = new TemporaryFileBackedOutputStream()) { try { IOUtils.copy(inputStream, fileBackedOutputStream); } catch (IOException e) { throw new CatalogTransformerException( "Unable to transform KML to Metacard. Error reading input stream.", e); } finally { IOUtils.closeQuietly(inputStream); } try (InputStream inputStreamCopy = fileBackedOutputStream.asByteSource().openStream()) { metacard = (MetacardImpl) unmarshal(inputStreamCopy); } if (metacard == null) { throw new CatalogTransformerException("Unable to transform Kml to Metacard."); } else if (StringUtils.isNotEmpty(id)) { metacard.setAttribute(Metacard.ID, id); } try (Reader reader = fileBackedOutputStream.asByteSource().asCharSource(Charsets.UTF_8).openStream()) { String kmlString = CharStreams.toString(reader); metacard.setAttribute(Metacard.METADATA, kmlString); } } catch (IOException e) { throw new CatalogTransformerException( "Unable to transform KML to Metacard. Error using file-backed stream.", e); } return metacard; }
From source file:org.sonar.sslr.channel.CodeBuffer.java
/** * Note that this constructor will read everything from reader and will close it. *///from w ww . ja va2 s .c om protected CodeBuffer(Reader initialCodeReader, CodeReaderConfiguration configuration) { Reader reader = null; try { lastChar = -1; cursor = new Cursor(); tabWidth = configuration.getTabWidth(); /* Setup the filters on the reader */ reader = initialCodeReader; for (CodeReaderFilter<?> codeReaderFilter : configuration.getCodeReaderFilters()) { reader = new Filter(reader, codeReaderFilter, configuration); } buffer = CharStreams.toString(reader).toCharArray(); } catch (IOException e) { throw new ChannelException(e.getMessage(), e); } finally { Closeables.closeQuietly(reader); } }
From source file:org.jboss.aerogear.security.hawk.authz.HawkAuthenticator.java
/** * @param request Hawk HTTP <i>Authorization</i> request * @param response Hawk HTTP response to authenticated requests with a <i>Server-Authorization</i> header * @throws Exception// w w w . j av a 2 s. c o m */ public void authenticate(HttpServletRequest request, HttpServletResponse response) throws Exception { String hash = null; try { URI uri = getUri(request); ImmutableMap<String, String> authorizationHeaders = server .splitAuthorizationHeader(request.getHeader(AUTHORIZATION)); HawkCredentials credentials = credentialProvider.findByKey(authorizationHeaders.get("id")); if (authorizationHeaders.get(CALCULATED_HASH) != null) { hash = Hawk.calculateMac(credentials, CharStreams.toString(new InputStreamReader(request.getInputStream(), ENCODING))); } server.authenticate(credentials, uri, request.getMethod(), authorizationHeaders, hash, hasBody(request)); addAuthenticateHeader(response); } catch (Throwable de) { throw new Exception(de); } }
From source file:com.nesscomputing.httpclient.response.NumberContentConverter.java
@Override public T convert(HttpClientResponse httpClientResponse, InputStream inputStream) throws IOException { final int responseCode = httpClientResponse.getStatusCode(); switch (responseCode) { case 200:/*from w w w.j a va 2s . c o m*/ case 201: final Charset charset = Charset.forName(Objects.firstNonNull(httpClientResponse.getCharset(), "UTF-8")); final InputStreamReader reader = new InputStreamReader(inputStream, charset); try { final String data = CharStreams.toString(reader); final T result = numberClass.cast(safeInvoke(data)); if (result == null) { // 201 may or may not return a body. Try parsing the body, return the empty value if // none is there (same as 204). if (responseCode == 201) { return emptyValue; } throw new IllegalArgumentException(format("Could not parse result '%s'", data)); } return result; } finally { Closeables.closeQuietly(reader); } case 204: return emptyValue; case 404: if (ignore404) { return emptyValue; } throw throwHttpResponseException(httpClientResponse); default: throw throwHttpResponseException(httpClientResponse); } }
From source file:com.chiorichan.ResourceLoader.java
public String getText(String relPath) { try {//from w ww . j a v a 2 s . co m InputStream is = getInputStream(relPath); return CharStreams.toString(new InputStreamReader(is, "UTF-8")); } catch (IOException e) { return null; } }
From source file:org.sonar.api.utils.HttpDownloader.java
@Override String readString(URI uri, Charset charset) { try {// w w w . j a v a2 s . c om return CharStreams.toString(CharStreams.newReaderSupplier(downloader.newInputSupplier(uri), charset)); } catch (IOException e) { throw failToDownload(uri, e); } }
From source file:ai.nitro.bot4j.integration.slack.receive.webhook.impl.SlackEventWebhookImpl.java
@Override public String post(final HttpServletRequest req, final HttpServletResponse res) { String result = ""; try {//from w w w .ja v a 2s.co m final String body = CharStreams.toString(req.getReader()); final JsonParser jsonParser = new JsonParser(); final JsonObject jsonReq = jsonParser.parse(body).getAsJsonObject(); if (!jsonReq.has(TYPE)) { LOG.warn("no type in JSON"); } else { final JsonElement typeJsonElement = jsonReq.get(TYPE); final String type = typeJsonElement.getAsString(); switch (type) { case URL_VERIFICATION: result = handleUrlVerification(jsonReq, res); break; case EVENT_CALLBACK: handleEvent(jsonReq, res); break; default: LOG.info("unknown type {}", type); break; } } } catch (final Exception e) { handleException(e); } return result; }
From source file:oculus.aperture.geo.BasicCountryLevelGeocodingService.java
/** * Constructs a new geocoder and initialises it by loading local country data. *///www .j a va2s. c o m public BasicCountryLevelGeocodingService() { nameList = new ArrayList<GeopoliticalData>(); countryMap = new HashMap<String, GeopoliticalData>(); final InputStream inp = BasicCountryLevelGeocodingService.class.getResourceAsStream("countries.json"); if (inp != null) { try { final String json = CharStreams .toString(new BufferedReader(new InputStreamReader(inp, Charset.forName("UTF-8")))); final JSONArray array = new JSONArray(json); for (int i = 0; i < array.length(); i++) { final JSONObject record = array.getJSONObject(i); final GeopoliticalData country = new BasicGeopoliticalData( new BasicGeospatialData(getString(record, "CountryName"), getDouble(record, "Latitude"), getDouble(record, "Longitude"), getString(record, "ISOCC3")), getString(record, "GlobalRegion"), Continent.valueOf(getString(record, "ContinentCode"))); final String isoCC2 = getString(record, "ISOCC2"); final String fips = getString(record, "FIPS"); final String ccTLD = getString(record, "InternetCCTLD"); final Long isoNo = getLong(record, "ISONo"); countryMap.put(isoCC2, country); countryMap.put(country.getGeoData().getCountryCode(), country); // add non-conflicting fips. if (fips != null && !countryMap.containsKey(fips)) { countryMap.put(fips, country); } if (isoNo != null) { countryMap.put(String.valueOf(isoNo), country); } // not necessary (same as iso 2), but... if (ccTLD != null && !countryMap.containsKey(ccTLD)) { countryMap.put(ccTLD, country); } nameList.add(country); } // sort countries Collections.sort(nameList, new Comparator<GeopoliticalData>() { public int compare(GeopoliticalData o1, GeopoliticalData o2) { return o2.getGeoData().getText().length() - o1.getGeoData().getText().length(); } }); } catch (IOException e) { s_logger.error("Failed to loan countries.json", e); } catch (JSONException e) { s_logger.error("Failed to parse countries.json", e); } finally { try { inp.close(); } catch (IOException e) { } } } }
From source file:com.liferay.portal.template.soy.internal.SoyTestHelper.java
protected SoyFileSet getSoyFileSet(List<TemplateResource> templateResources) throws Exception { Builder builder = SoyFileSet.builder(); for (TemplateResource templateResource : templateResources) { Reader reader = templateResource.getReader(); builder.add(CharStreams.toString(reader), templateResource.getTemplateId()); }/*w w w .ja v a2 s.com*/ return builder.build(); }
From source file:com.github.cassandra.jdbc.CassandraDataTypeConverters.java
protected void init() { // use "null" instead of empty string to avoid "InvalidQueryException: Key may not be empty" addMapping(String.class, "null", new Function<Object, String>() { public String apply(Object input) { String result;/*from w ww . j ava2s.c o m*/ if (input instanceof Readable) { try { result = CharStreams.toString(((Readable) input)); } catch (IOException e) { throw new IllegalArgumentException("Failed to read from Readable " + input, e); } } else { result = String.valueOf(input); } return result; } }); addMapping(java.util.UUID.class, java.util.UUID.randomUUID(), new Function<Object, UUID>() { public UUID apply(Object input) { return java.util.UUID.fromString(String.valueOf(input)); } }); InetAddress defaultAddress = null; try { defaultAddress = InetAddress.getLocalHost(); } catch (UnknownHostException e) { Logger.warn(e, "Failed to get local host"); } addMapping(InetAddress.class, defaultAddress, new Function<Object, InetAddress>() { public InetAddress apply(Object input) { try { return InetAddress.getByName(String.valueOf(input)); } catch (UnknownHostException e) { throw CassandraErrors.unexpectedException(e); } } }); addMapping(Blob.class, new CassandraBlob(new byte[0]), new Function<Object, Blob>() { public Blob apply(Object input) { CassandraBlob blob; if (input instanceof ByteBuffer) { blob = new CassandraBlob((ByteBuffer) input); } else if (input instanceof byte[]) { blob = new CassandraBlob((byte[]) input); } else if (input instanceof InputStream) { try { blob = new CassandraBlob(ByteStreams.toByteArray((InputStream) input)); } catch (IOException e) { throw new IllegalArgumentException("Failed to read from input stream " + input, e); } } else { blob = new CassandraBlob(String.valueOf(input).getBytes()); } return blob; } }); addMapping(byte[].class, emptyByteArray, new Function<Object, byte[]>() { public byte[] apply(Object input) { byte[] result; if (input instanceof ByteBuffer) { result = ((ByteBuffer) input).array(); } else { result = String.valueOf(input).getBytes(); } return result; } }); /* addMapping(ByteBuffer.class, ByteBuffer.wrap(new byte[0]), new Function<Object, ByteBuffer>() { public ByteBuffer apply(Object input) { return ByteBuffer.wrap(input instanceof byte[] ? (byte[]) input : String.valueOf(input).getBytes()); } }); */ addMapping(Boolean.class, Boolean.FALSE, new Function<Object, Boolean>() { public Boolean apply(Object input) { return Boolean.valueOf(String.valueOf(input)); } }); addMapping(Byte.class, (byte) 0, new Function<Object, Byte>() { public Byte apply(Object input) { return input instanceof Number ? ((Number) input).byteValue() : Ints.tryParse(String.valueOf(input)).byteValue(); } }); addMapping(Short.class, (short) 0, new Function<Object, Short>() { public Short apply(Object input) { return input instanceof Number ? ((Number) input).shortValue() : Ints.tryParse(String.valueOf(input)).shortValue(); } }); addMapping(Integer.class, 0, new Function<Object, Integer>() { public Integer apply(Object input) { return input instanceof Number ? ((Number) input).intValue() : Ints.tryParse(String.valueOf(input)); } }); addMapping(Long.class, 0L, new Function<Object, Long>() { public Long apply(Object input) { return input instanceof Number ? ((Number) input).longValue() : Long.parseLong(String.valueOf(input)); } }); addMapping(Float.class, 0.0F, new Function<Object, Float>() { public Float apply(Object input) { return input instanceof Number ? ((Number) input).floatValue() : Doubles.tryParse(String.valueOf(input)).floatValue(); } }); addMapping(Double.class, 0.0D, new Function<Object, Double>() { public Double apply(Object input) { return input instanceof Number ? ((Number) input).doubleValue() : Doubles.tryParse(String.valueOf(input)); } }); addMapping(BigDecimal.class, BigDecimal.ZERO, new Function<Object, BigDecimal>() { public BigDecimal apply(Object input) { return new BigDecimal(String.valueOf(input)); } }); addMapping(BigInteger.class, BigInteger.ZERO, new Function<Object, BigInteger>() { public BigInteger apply(Object input) { return new BigInteger(String.valueOf(input)); } }); addMapping(Date.class, new Date(System.currentTimeMillis()), new Function<Object, Date>() { public Date apply(Object input) { Date result; if (input instanceof LocalDate) { result = new Date(((LocalDate) input).toDate().getTime()); } else if (input instanceof java.util.Date) { result = new Date(((java.util.Date) input).getTime()); } else { result = new Date(LocalDate.parse(String.valueOf(input)).toDate().getTime()); } return result; } }); addMapping(Time.class, new Time(System.currentTimeMillis()), new Function<Object, Time>() { public Time apply(Object input) { Time result; if (input instanceof LocalTime) { result = new Time(((LocalTime) input).toDateTimeToday().getMillis()); } else if (input instanceof java.util.Date) { result = new Time(((java.util.Date) input).getTime()); } else { result = new Time(LocalTime.parse(String.valueOf(input)).toDateTimeToday().getMillis()); } return result; } }); addMapping(Timestamp.class, new Timestamp(System.currentTimeMillis()), new Function<Object, Timestamp>() { public Timestamp apply(Object input) { Timestamp result; if (input instanceof Instant) { result = new Timestamp(((Instant) input).toDate().getTime()); } else if (input instanceof java.util.Date) { result = new Timestamp(((java.util.Date) input).getTime()); } else if (input instanceof Number) { result = new Timestamp(((Number) input).longValue()); } else { String dateTime = String.valueOf(input); if (dateTime.indexOf(' ') == 10 && dateTime.indexOf('Z') < 0) { StringBuilder builder = new StringBuilder(dateTime).append('Z'); builder.setCharAt(10, 'T'); dateTime = builder.toString(); } result = new Timestamp(Instant.parse(dateTime).toDate().getTime()); } return result; } }); // now collections addMapping(List.class, emptyList, new Function<Object, List>() { public List apply(Object input) { List result; if (input instanceof Iterable) { result = Lists.newArrayList((Iterable) input); } else if (input instanceof Object[]) { result = Lists.newArrayList((Object[]) input); } else { result = valueSplitter.splitToList(String.valueOf(input)); } return result; } }); addMapping(Set.class, emptySet, new Function<Object, Set>() { public Set apply(Object input) { Set result; if (input instanceof Iterable) { result = Sets.newTreeSet((Iterable) input); } else if (input instanceof Object[]) { result = Sets.newHashSet((Object[]) input); } else { result = Sets.newTreeSet(valueSplitter.splitToList(String.valueOf(input))); } return result; } }); addMapping(Set.class, emptyMap, new Function<Object, Map>() { public Map apply(Object input) { return Map.class.cast(input); } }); }