List of usage examples for com.google.common.io CharStreams toString
public static String toString(Readable r) throws IOException
From source file:com.netflix.spinnaker.orca.pipeline.util.HttpClientUtils.java
public static String httpGetAsString(String url) throws IOException { try (CloseableHttpResponse response = httpClient.execute(new HttpGet(url))) { try (final Reader reader = new InputStreamReader(response.getEntity().getContent())) { return CharStreams.toString(reader); }//from ww w .j a v a 2 s.c o m } }
From source file:org.apache.cloudstack.utils.process.ProcessRunner.java
/** * Executes a process with provided list of commands with a given timeout that is less * than or equal to DEFAULT_MAX_TIMEOUT// w w w . java 2 s. c o m * @param commands list of string commands * @param timeOut timeout duration * @return returns process result */ public ProcessResult executeCommands(final List<String> commands, final Duration timeOut) { Preconditions.checkArgument(commands != null && timeOut != null && timeOut.getStandardSeconds() > 0L && (timeOut.compareTo(DEFAULT_MAX_TIMEOUT) <= 0) && executor != null); int retVal = -2; String stdOutput = null; String stdError = null; try { final Process process = new ProcessBuilder().command(commands).start(); final Future<Integer> processFuture = executor.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { return process.waitFor(); } }); try { retVal = processFuture.get(timeOut.getStandardSeconds(), TimeUnit.SECONDS); } catch (ExecutionException e) { retVal = -2; stdError = e.getMessage(); if (LOG.isTraceEnabled()) { LOG.trace("Failed to complete the requested command due to execution error: " + e.getMessage()); } } catch (TimeoutException e) { retVal = -1; stdError = "Operation timed out, aborted"; if (LOG.isTraceEnabled()) { LOG.trace("Failed to complete the requested command within timeout: " + e.getMessage()); } } finally { if (Strings.isNullOrEmpty(stdError)) { stdOutput = CharStreams.toString(new InputStreamReader(process.getInputStream())); stdError = CharStreams.toString(new InputStreamReader(process.getErrorStream())); } process.destroy(); } if (LOG.isTraceEnabled()) { LOG.trace("Process standard output: " + stdOutput); LOG.trace("Process standard error output: " + stdError); } } catch (IOException | InterruptedException e) { stdError = e.getMessage(); LOG.error("Exception caught error running commands: " + e.getMessage()); } return new ProcessResult(stdOutput, stdError, retVal); }
From source file:de.kaixo.mubi.lists.store.MubiListsToElasticSearchLoader.java
public boolean prepareIndex(boolean dropAndCreate) { final IndicesAdminClient indexClient = client.admin().indices(); if (indexClient.exists(new IndicesExistsRequest(INDEX_NAME)).actionGet().isExists()) { if (dropAndCreate) { indexClient.delete(new DeleteIndexRequest(INDEX_NAME)).actionGet(); } else {//from ww w. j a v a 2s.com return false; } } InputStream indexSettingsStream = MubiListsToElasticSearchLoader.class .getResourceAsStream(INDEX_SETTINGS_JSON); if (indexSettingsStream == null) { logger.error("Resource not found: " + INDEX_SETTINGS_JSON); return false; } Settings indexSettings = ImmutableSettings.builder() .loadFromStream(INDEX_SETTINGS_JSON, indexSettingsStream).build(); InputStream mappingInputStream = MubiListsToElasticSearchLoader.class .getResourceAsStream(LIST_MAPPING_JSON); if (mappingInputStream == null) { logger.error("Resource not found: " + LIST_MAPPING_JSON); return false; } try { String mapping = CharStreams.toString(new InputStreamReader(mappingInputStream, "UTF-8")); CompletableFuture<? extends ActionResponse> future = supplyAsync( indexClient.prepareCreate(INDEX_NAME).setSettings(indexSettings).addMapping(TYPE, mapping)::get) .thenApply(r -> indexClient.prepareFlush(INDEX_NAME).get()); future.join(); } catch (IOException e) { // We do not expect this to happen! logger.error("This should not have happened!", e); return false; } catch (ElasticsearchException e) { logger.error("While trying to create index " + INDEX_NAME + ": ", e); return false; } catch (CompletionException e) { logger.error("While trying to create index " + INDEX_NAME + ": ", e); return false; } return true; }
From source file:org.killbill.billing.plugin.core.PluginServlet.java
protected String getRequestData(final ServletRequest req) throws IOException { final InputStream input = req.getInputStream(); final InputSupplier<InputStream> inputStreamInputSupplier = new InputSupplier<InputStream>() { public InputStream getInput() throws IOException { return input; }/*from w w w . j av a 2 s .c om*/ }; final InputSupplier<InputStreamReader> inputSupplier = CharStreams .newReaderSupplier(inputStreamInputSupplier, Charsets.UTF_8); return CharStreams.toString(inputSupplier); }
From source file:net.awired.visuwall.core.application.common.ApplicationHelper.java
public static void changeLogLvl() { Level loglvl = ApplicationHelper.findLogLvl(); try {/*from w w w. j a va 2 s . c o m*/ InputStream logConfStream = ApplicationHelper.class.getResourceAsStream("/visuwall-logback.xml"); String logConfString = CharStreams.toString(new InputStreamReader(logConfStream)); if (loglvl != null) { // TODO replace with a better regexp to replace all tags like that <logger name="net.awired" level="DEBUG" /> // TODO or replace by a xml parser or replace by a deep logback communication to set log lvl logConfString = logConfString.replace("DEBUG", loglvl.toString()); } LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(new ByteArrayInputStream(logConfString.getBytes())); } catch (JoranException je) { je.printStackTrace(); } StatusPrinter.printInCaseOfErrorsOrWarnings(lc); } catch (IOException e) { LOG.error("Can not change application log level", e); } // don't change root lvl as is may put hibernate or jetty in debug // Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); // root.setLevel(loglvl); }
From source file:org.retrostore.request.RequestDataImpl.java
@Override public String getBody() { try {//from ww w . j a v a 2 s . c o m return CharStreams.toString(new InputStreamReader(mRequest.getInputStream(), Charsets.UTF_8)); } catch (IOException ex) { LOG.warning(String.format("Could not read request body: '%s'.", ex.getMessage())); return ""; } }
From source file:oculus.aperture.parchment.ParchmentModule.java
@Override protected void configure() { logger.info("Loading Parchment Module..."); MapBinder<String, ResourceDefinition> resourceBinder = MapBinder.newMapBinder(binder(), String.class, ResourceDefinition.class); // Provides the image service bindings. resourceBinder.addBinding("/parchment/{confidence}/{currency}") .toInstance(new ResourceDefinition(ParchmentResource.class).setVariable("currency", new Variable(Variable.TYPE_URI_PATH, "", false, false))); // Provides the CSS bindings resourceBinder.addBinding("/parchment.css").toInstance(new ResourceDefinition(ParchmentCSSResource.class)); // Prep CSS// w w w. j a v a2 s . c o m InputStream inp = ParchmentModule.class.getResourceAsStream("parchment.css"); String css = null; try { css = CharStreams.toString(new BufferedReader(new InputStreamReader(inp, Charset.forName("UTF-8")))); } catch (IOException e) { logger.error("Failure Loading Parchment Module", e); } finally { Closeables.closeQuietly(inp); } // bind result in guice. Names.bindProperties(this.binder(), ImmutableMap.of("aperture.parchment.css", css != null ? css : "{}")); }
From source file:li.klass.fhem.fhem.FHEMWEBConnection.java
@Override public RequestResult<String> executeCommand(String command, Context context) { LOG.info("executeTask command " + command); String urlSuffix = generateUrlSuffix(command); InputStreamReader reader = null; try {// w ww . j av a 2s . c o m RequestResult<InputStream> response = executeRequest(urlSuffix); if (response.error != null) { return new RequestResult<>(response.error); } reader = new InputStreamReader(response.content); String content = CharStreams.toString(reader); if (content.contains("<title>") || content.contains("<div id=")) { LOG.error("found strange content: " + content); ErrorHolder.setError("found strange content in URL " + urlSuffix + ": \r\n\r\n" + content); return new RequestResult<>(INVALID_CONTENT); } return new RequestResult<>(content); } catch (Exception e) { LOG.error("cannot handle result", e); return new RequestResult<>(INTERNAL_ERROR); } finally { close(reader); } }
From source file:li.klass.fhem.domain.core.DeviceXMLParsingBase.java
@Before public void before() throws Exception { AndFHEMApplication.setContext(context); ObjectGraph graph = AndFHEMApplication.createDaggerGraph(); setFieldValue(deviceListParser, "parser", graph.get(XmlListParser.class)); setFieldValue(deviceListParser, "gPlotHolder", graph.get(GPlotHolder.class)); setFieldValue(deviceListParser, "deviceConfigurationProvider", graph.get(DeviceConfigurationProvider.class)); mockStrings();//from ww w . java 2s . c o m doReturn(true).when(connectionService).mayShowInCurrentConnectionType(any(DeviceType.class), eq(context)); InputStream inputStream = null; InputStreamReader inputStreamReader = null; try { inputStream = getTestFileBaseClass().getResourceAsStream(getFileName()); if (inputStream == null) { throw new IllegalArgumentException("cannot find " + getFileName()); } inputStreamReader = new InputStreamReader(inputStream, Charsets.UTF_8); String content = CharStreams.toString(inputStreamReader); roomDeviceList = deviceListParser.parseXMLListUnsafe(content, context); } finally { CloseableUtil.close(inputStream, inputStreamReader); } }
From source file:com.netflix.spinnaker.kork.web.exceptions.GenericExceptionHandlers.java
@ExceptionHandler(RetrofitError.class) public void handleRetrofitError(RetrofitError e, HttpServletResponse response, HttpServletRequest request) throws IOException { if (e.getResponse() != null) { Map<String, Object> additionalContext = new HashMap<>(); additionalContext.put("url", e.getResponse().getUrl()); Header contentTypeHeader = e.getResponse().getHeaders().stream() .filter(h -> h.getName().equalsIgnoreCase("content-type")).findFirst().orElse(null); if (contentTypeHeader != null && contentTypeHeader.getValue().toLowerCase().contains("application/json")) { // include any json responses additionalContext.put("body", CharStreams .toString(new InputStreamReader(e.getResponse().getBody().in(), Charsets.UTF_8))); }//w w w . j ava2s. co m storeException(request, response, new RetrofitErrorWrapper(e.getMessage(), additionalContext)); response.sendError(e.getResponse().getStatus(), e.getMessage()); } else { // no retrofit response (likely) indicates a NETWORK error handleException(e, response, request); } }