public String annotate(String text) throws URISyntaxException, IOException { URI requestURI = new URIBuilder(endpoint).build(); HttpPost request = new HttpPost(requestURI); List<NameValuePair> urlParameters = new ArrayList<>(); urlParameters.add(new BasicNameValuePair("text", text)); urlParameters.add(new BasicNameValuePair("disambiguation", "1")); urlParameters.add(new BasicNameValuePair("topic", "0.25")); urlParameters.add(new BasicNameValuePair("include_text", "1")); urlParameters.add(new BasicNameValuePair("min_weight", "0.25")); urlParameters.add(new BasicNameValuePair("image", "1")); urlParameters.add(new BasicNameValuePair("class", "1")); urlParameters.add(new BasicNameValuePair("app_id", "0")); urlParameters.add(new BasicNameValuePair("app_key", "0")); request.setEntity(new UrlEncodedFormEntity(urlParameters)); CloseableHttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() >= 400) { response.close(); throw new IOException("Wikimachine endpoint didn't understand the request"); } String responseText = IOUtils.toString(new InputStreamReader(response.getEntity().getContent())); response.close(); return responseText; }
private SagaResponse on(Request request) { try { HttpResponse httpResponse = request.execute().returnResponse(); int statusCode = httpResponse.getStatusLine().getStatusCode(); String content = IOUtils.toString(new InputStreamReader(httpResponse.getEntity().getContent())); if (statusCode >= 200 && statusCode < 300) { return new SuccessfulSagaResponse(content); } throw new TransportFailedException("The remote service returned with status code " + statusCode + ", reason " + httpResponse.getStatusLine().getReasonPhrase() + ", and content " + content); } catch (IOException e) { throw new TransportFailedException("Network Error", e); } }
/** * Execute a command from specified path * @param command command to be executed * @param pathName path where the command should be executed * @return command's output */ public static String run(String command, String pathName) { ExecutorService newFixedThreadPool = null; try { logger.info(CMD_LOG_TMPL, Optional.ofNullable(pathName).orElse(""), command); final Process process; String[] cmd = { "/bin/sh", "-c", command}; process = Runtime.getRuntime().exec( cmd, null, StringUtils.isNotBlank(pathName) ? new File(pathName) : null); newFixedThreadPool = Executors.newFixedThreadPool(1); Future<String> output = newFixedThreadPool.submit(() -> IOUtils.toString( new InputStreamReader(process.getInputStream())) ); Future<String> error = newFixedThreadPool.submit(() -> IOUtils.toString( new InputStreamReader(process.getErrorStream())) ); if (!process.waitFor(3, TimeUnit.MINUTES)) { logger.info("Destroy process, it's been hanged out for more than 3 minutes!"); process.destroy(); } logger.info(CMD_LOG_TMPL, Optional.ofNullable(pathName).orElse(""), output.get()); if (StringUtils.isNotBlank(error.get())){ logger.error(CMD_LOG_TMPL, Optional.ofNullable(pathName).orElse(""), error.get()); } return output.get(); } catch (Exception e) { logger.error("Error executing command: " + command, e); } finally { Optional.ofNullable(newFixedThreadPool).ifPresent(ExecutorService::shutdown); } return StringUtils.EMPTY; }
private String getStringContent(URL resource) throws IOException { try (InputStream resourceAsStream = resource.openStream()) { InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream, "UTF-8"); return IOUtils.toString(inputStreamReader); } }
@NotNull private String readResource(@NotNull final String resource) throws IOException { InputStream in = getClass().getResourceAsStream(resource); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); return IOUtils.toString(reader); }
@NotNull private String readResource() throws IOException { InputStream in = VersionInfo.class.getClassLoader().getResourceAsStream(resource); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); return IOUtils.toString(reader); }
@PluginFactory public static ScriptFile createScript( // @formatter:off @PluginAttribute("name") String name, @PluginAttribute("language") String language, @PluginAttribute("path") final String filePathOrUri, @PluginAttribute("isWatched") final Boolean isWatched, @PluginAttribute("charset") final Charset charset) { // @formatter:on if (filePathOrUri == null) { LOGGER.error("No script path provided for ScriptFile"); return null; } if (name == null) { name = filePathOrUri; } final URI uri = NetUtils.toURI(filePathOrUri); final File file = FileUtils.fileFromUri(uri); if (language == null && file != null) { final String fileExtension = FileUtils.getFileExtension(file); if (fileExtension != null) { final ExtensionLanguageMapping mapping = ExtensionLanguageMapping.getByExtension(fileExtension); if (mapping != null) { language = mapping.getLanguage(); } } } if (language == null) { LOGGER.info("No script language supplied, defaulting to {}", DEFAULT_LANGUAGE); language = DEFAULT_LANGUAGE; } final Charset actualCharset = charset == null ? Charset.defaultCharset() : charset; String scriptText; try (final Reader reader = new InputStreamReader( file != null ? new FileInputStream(file) : uri.toURL().openStream(), actualCharset)) { scriptText = IOUtils.toString(reader); } catch (final IOException e) { LOGGER.error("{}: language={}, path={}, actualCharset={}", e.getClass().getSimpleName(), language, filePathOrUri, actualCharset); return null; } final Path path = file != null ? Paths.get(file.toURI()) : Paths.get(uri); if (path == null) { LOGGER.error("Unable to convert {} to a Path", uri.toString()); return null; } return new ScriptFile(name, path, language, isWatched == null ? Boolean.FALSE : isWatched, scriptText); }
@Override public void send(final Layout<?> layout, final LogEvent event) throws IOException { final HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); urlConnection.setAllowUserInteraction(false); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setRequestMethod(method); if (connectTimeoutMillis > 0) { urlConnection.setConnectTimeout(connectTimeoutMillis); } if (readTimeoutMillis > 0) { urlConnection.setReadTimeout(readTimeoutMillis); } if (layout.getContentType() != null) { urlConnection.setRequestProperty("Content-Type", layout.getContentType()); } for (final Property header : headers) { urlConnection.setRequestProperty( header.getName(), header.isValueNeedsLookup() ? getConfiguration().getStrSubstitutor().replace(event, header.getValue()) : header.getValue()); } if (sslConfiguration != null) { ((HttpsURLConnection)urlConnection).setSSLSocketFactory(sslConfiguration.getSslSocketFactory()); } if (isHttps && !verifyHostname) { ((HttpsURLConnection)urlConnection).setHostnameVerifier(LaxHostnameVerifier.INSTANCE); } final byte[] msg = layout.toByteArray(event); urlConnection.setFixedLengthStreamingMode(msg.length); urlConnection.connect(); try (OutputStream os = urlConnection.getOutputStream()) { os.write(msg); } final byte[] buffer = new byte[1024]; try (InputStream is = urlConnection.getInputStream()) { while (IOUtils.EOF != is.read(buffer)) { // empty } } catch (final IOException e) { final StringBuilder errorMessage = new StringBuilder(); try (InputStream es = urlConnection.getErrorStream()) { errorMessage.append(urlConnection.getResponseCode()); if (urlConnection.getResponseMessage() != null) { errorMessage.append(' ').append(urlConnection.getResponseMessage()); } if (es != null) { errorMessage.append(" - "); int n; while (IOUtils.EOF != (n = es.read(buffer))) { errorMessage.append(new String(buffer, 0, n, CHARSET)); } } } if (urlConnection.getResponseCode() > -1) { throw new IOException(errorMessage.toString()); } else { throw e; } } }