static { InputStream vertStream = Shader.class .getClassLoader() .getResourceAsStream("org/terasology/include/globalFunctionsVertIncl.glsl"); InputStream fragStream = Shader.class .getClassLoader() .getResourceAsStream("org/terasology/include/globalFunctionsFragIncl.glsl"); try { IncludedFunctionsVertex = CharStreams.toString(new InputStreamReader(vertStream)); IncludedFunctionsFragment = CharStreams.toString(new InputStreamReader(fragStream)); } catch (IOException e) { Logger.getLogger(Shader.class.getName()).severe("Failed to load Include shader resources"); } finally { // JAVA7: Clean up try { vertStream.close(); } catch (IOException e) { Logger.getLogger(Shader.class.getName()) .severe("Failed to close globalFunctionsVertIncl.glsl stream"); } try { fragStream.close(); } catch (IOException e) { Logger.getLogger(Shader.class.getName()) .severe("Failed to close globalFunctionsFragIncl.glsl stream"); } } }
static { try { // 读取resource下文件使用下面代码,能够在IDE里面使用,也能在打成jar包后,单独使用 InputStream mainStream = DictTools.class.getClassLoader().getResourceAsStream("main.txt"); String main = CharStreams.toString(new InputStreamReader(mainStream, "UTF-8")); InputStream assitStream = DictTools.class.getClassLoader().getResourceAsStream("assist.txt"); String assist = CharStreams.toString(new InputStreamReader(assitStream, "UTF-8")); main_kws = buildModelList(main.split("\n")); assist_kws = Lists.newArrayList(assist.split("\n")); } catch (Exception e) { LOG.error("初始化词典错误!", e); } }
private List<ServiceDescriptor> getServiceInventory(SlotStatus slotStatus) { Assignment assignment = slotStatus.getAssignment(); if (assignment == null) { return null; } String config = assignment.getConfig(); File cacheFile = getCacheFile(config); if (cacheFile.canRead()) { try { String json = CharStreams.toString(Files.newReaderSupplier(cacheFile, Charsets.UTF_8)); List<ServiceDescriptor> descriptors = descriptorsJsonCodec.fromJson(json); invalidServiceInventory.remove(config); return descriptors; } catch (Exception ignored) { // delete the bad cache file cacheFile.delete(); } } InputSupplier<? extends InputStream> configFile = ConfigUtils.newConfigEntrySupplier(repository, config, "airship-service-inventory.json"); if (configFile == null) { return null; } try { String json; try { json = CharStreams.toString(CharStreams.newReaderSupplier(configFile, Charsets.UTF_8)); } catch (FileNotFoundException e) { // no service inventory in the config, so replace with json null so caching works json = "null"; } invalidServiceInventory.remove(config); // cache json cacheFile.getParentFile().mkdirs(); Files.write(json, cacheFile, Charsets.UTF_8); List<ServiceDescriptor> descriptors = descriptorsJsonCodec.fromJson(json); return descriptors; } catch (Exception e) { if (invalidServiceInventory.add(config)) { log.error(e, "Unable to read service inventory for %s" + config); } } return null; }
@Test(groups = {"functional", "real_server"}) public void test404withIndex() throws IOException { String filePath = "newDir-" + System.currentTimeMillis(); final File newDir = new File(documentRoot, filePath); newDir.mkdir(); // this should be empty // create adn write an index file File index = new File(newDir, "index.html"); index.createNewFile(); filePath = filePath + "/doesntexist"; // Open a client socket and send a simple request final Socket socket = new Socket("localhost", this.port); OutputStream out = socket.getOutputStream(); out.write(("GET /" + filePath + " HTTP/1.1\r\n").getBytes()); out.write("Host: localhost\r\n".getBytes()); out.write("Connection: close\r\n".getBytes()); out.write("\r\n".getBytes()); out.flush(); InputStream in = socket.getInputStream(); String response = CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)); System.out.println("response=" + response); Assert.assertEquals(response.substring(0, 12), "HTTP/1.1 404"); }
/** * Create CDMI data object with InputStream value * * @param value InputSteam * @param charset character set of input stream InputSteam is converted to a String value with * charset UTF_8 * @return CreateDataObjectOptions */ public CreateDataObjectOptions value(InputStream value, Charset charset) throws IOException { jsonObjectBody.addProperty( "value", (value == null) ? "" : CharStreams.toString(new InputStreamReader(value, charset))); this.payload = jsonObjectBody.toString(); return this; }
@Override public void performAction(CmdLineParser parser) throws CommandException { if (!configStdIn && null == configFile) { throw new ExitWithCodeException(1, "Policy configuration must be provided", true); } // read configuration from STDIN or file String policyConfig; try (InputStream is = (configStdIn ? System.in : Files.newInputStream(configFile))) { policyConfig = CharStreams.toString(new InputStreamReader(is)); } catch (IOException e) { throw new CommandException(e); } LOGGER.debug( "Adding policy '{}' to API '{}' with configuration: {}", () -> policyName, this::getModelName, () -> policyConfig); final ApiPolicy apiPolicy = new ApiPolicy(policyName); apiPolicy.setDefinitionId(policyName); ManagementApiUtil.invokeAndCheckResponse( () -> buildServerApiClient(VersionAgnosticApi.class, serverVersion) .addPolicy(orgName, name, version, apiPolicy)); }
@Test(groups = {"functional", "real_server"}) public void testGetIndex() throws IOException { File index = new File(this.documentRoot, "index.html"); index.createNewFile(); final int fileSize = 100; String content = TestUtils.generateFileContent(fileSize); Files.write(content, index, Charsets.UTF_8); // Open a client socket and send a simple request final Socket socket = new Socket("localhost", this.port); OutputStream out = socket.getOutputStream(); out.write("GET / HTTP/1.1\r\n".getBytes()); out.write(("Host: localhost:" + this.port + "\r\n").getBytes()); // this is necessary so we can get the response and not wait for timeout out.write("Connection: close\r\n".getBytes()); out.write("\r\n".getBytes()); out.flush(); InputStream in = socket.getInputStream(); String response = CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)); System.out.println(this.documentRoot.getAbsolutePath()); System.out.println("response=" + response); // Assert.assertTrue(response.indexOf("200 OK") > 0); Assert.assertEquals(response.substring(0, 15), "HTTP/1.1 200 OK"); Assert.assertTrue(response.contains(content)); }
@Override public SlackPersona.SlackPresence getPresence(SlackPersona persona) { HttpClient client = getHttpClient(); HttpPost request = new HttpPost("https://slack.com/api/users.getPresence"); List<NameValuePair> nameValuePairList = new ArrayList<>(); nameValuePairList.add(new BasicNameValuePair("token", authToken)); nameValuePairList.add(new BasicNameValuePair("user", persona.getId())); try { request.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8")); HttpResponse response = client.execute(request); String jsonResponse = CharStreams.toString(new InputStreamReader(response.getEntity().getContent())); LOGGER.debug("PostMessage return: " + jsonResponse); JSONObject resultObject = parseObject(jsonResponse); // quite hacky need to refactor this SlackUserPresenceReply reply = (SlackUserPresenceReply) SlackJSONReplyParser.decode(resultObject, this); if (!reply.isOk()) { return SlackPersona.SlackPresence.UNKNOWN; } String presence = (String) resultObject.get("presence"); if ("active".equals(presence)) { return SlackPersona.SlackPresence.ACTIVE; } if ("away".equals(presence)) { return SlackPersona.SlackPresence.AWAY; } } catch (Exception e) { // TODO : improve exception handling e.printStackTrace(); } return SlackPersona.SlackPresence.UNKNOWN; }
private static String getBodyForError(Response response) { try { return CharStreams.toString(new InputStreamReader(response.getInputStream(), Charsets.UTF_8)); } catch (IOException e) { return "(error getting body)"; } }
private String getSourceMapContentsAt(String urlString) throws IOException { URL url = new URL(urlString); URLConnection connection = url.openConnection(); return CharStreams.toString(new InputStreamReader(connection.getInputStream())); }
public List<Child> getAllChildren() throws IOException { HttpResponse response = fluentRequest.context(context).path("/children").get(); String childrenJson = CharStreams.toString(new InputStreamReader(response.getEntity().getContent())); return convertToChildRecords(childrenJson); }
@Override public SlackMessageHandle<GenericSlackReply> postGenericSlackCommand( Map<String, String> params, String command) { HttpClient client = getHttpClient(); HttpPost request = new HttpPost(SLACK_API_HTTPS_ROOT + command); List<NameValuePair> nameValuePairList = new ArrayList<>(); for (Map.Entry<String, String> arg : params.entrySet()) { if (!"token".equals(arg.getKey())) { nameValuePairList.add(new BasicNameValuePair(arg.getKey(), arg.getValue())); } } nameValuePairList.add(new BasicNameValuePair("token", authToken)); try { SlackMessageHandleImpl<GenericSlackReply> handle = new SlackMessageHandleImpl<>(getNextMessageId()); request.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8")); HttpResponse response = client.execute(request); String jsonResponse = CharStreams.toString(new InputStreamReader(response.getEntity().getContent())); LOGGER.debug("PostMessage return: " + jsonResponse); GenericSlackReplyImpl reply = new GenericSlackReplyImpl(parseObject(jsonResponse)); handle.setReply(reply); return handle; } catch (Exception e) { // TODO : improve exception handling e.printStackTrace(); } return null; }
public static String load(Class<? extends Template> type) { com.vercer.leaf.annotation.Template annotation = type.getAnnotation(com.vercer.leaf.annotation.Template.class); String name; if (annotation != null) { name = annotation.value(); } else { name = type.getSimpleName() + ".html"; } InputStream stream = type.getResourceAsStream(name); if (stream == null) { return null; } String text; try { text = CharStreams.toString(new InputStreamReader(stream)); } catch (IOException e) { throw new RuntimeException(e); } try { stream.close(); } catch (IOException e) { throw new RuntimeException(e); } // remove windows carriage returns text = text.replaceAll("\r", ""); return text; }
static String loadTextResource(Class<?> clazz, String path) { try { return CharStreams.toString(new InputStreamReader(clazz.getResourceAsStream(path), UTF_8)); } catch (IOException e) { throw new RuntimeException(e); } }
private void connectImpl() throws IOException, ClientProtocolException, ConnectException { LOGGER.info("connecting to slack"); lastPingSent = 0; lastPingAck = 0; HttpClient httpClient = getHttpClient(); HttpGet request = new HttpGet(SLACK_HTTPS_AUTH_URL + authToken); HttpResponse response; response = httpClient.execute(request); LOGGER.debug(response.getStatusLine().toString()); String jsonResponse = CharStreams.toString(new InputStreamReader(response.getEntity().getContent())); SlackJSONSessionStatusParser sessionParser = new SlackJSONSessionStatusParser(jsonResponse); try { sessionParser.parse(); } catch (ParseException e1) { LOGGER.error(e1.toString()); } if (sessionParser.getError() != null) { LOGGER.error("Error during authentication : " + sessionParser.getError()); throw new ConnectException(sessionParser.getError()); } users = sessionParser.getUsers(); channels = sessionParser.getChannels(); sessionPersona = sessionParser.getSessionPersona(); team = sessionParser.getTeam(); LOGGER.info("Team " + team.getId() + " : " + team.getName()); LOGGER.info("Self " + sessionPersona.getId() + " : " + sessionPersona.getUserName()); LOGGER.info(users.size() + " users found on this session"); LOGGER.info(channels.size() + " channels found on this session"); String wssurl = sessionParser.getWebSocketURL(); LOGGER.debug("retrieved websocket URL : " + wssurl); ClientManager client = ClientManager.createClient(); if (proxyAddress != null) { client .getProperties() .put(ClientProperties.PROXY_URI, "http://" + proxyAddress + ":" + proxyPort); } final MessageHandler handler = this; LOGGER.debug("initiating connection to websocket"); try { websocketSession = client.connectToServer( new Endpoint() { @Override public void onOpen(Session session, EndpointConfig config) { session.addMessageHandler(handler); } }, URI.create(wssurl)); } catch (DeploymentException e) { LOGGER.error(e.toString()); } if (websocketSession != null) { SlackConnectedImpl slackConnectedImpl = new SlackConnectedImpl(sessionPersona); dispatcher.dispatch(slackConnectedImpl); LOGGER.debug("websocket connection established"); LOGGER.info("slack session ready"); } }
private String readFileAsString(String resourcePath) throws IOException { InputStream stream = ConquesoClientTest.class.getResourceAsStream(resourcePath); try { return CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8)); } finally { stream.close(); } }
public static List<byte[]> parseMessages(final InputStream is) throws IOException { Preconditions.checkNotNull(is); try (InputStreamReader isr = new InputStreamReader(is, "UTF-8")) { return parseMessages(CharStreams.toString(isr)); } finally { is.close(); } }
private static String exec(final String command) { try { final Process process = Runtime.getRuntime().exec(command); return CharStreams.toString(new InputStreamReader(process.getInputStream(), UTF_8)); } catch (IOException e) { throw propagate(e); } }
private String httpGet(int port, String path) throws IOException { URL url = new URL("http://localhost:" + port + path); URLConnection conn = url.openConnection(); Reader reader = new InputStreamReader(conn.getInputStream()); String response = CharStreams.toString(reader); reader.close(); return response; }
public static String toStringAndClose(InputStream input) throws IOException { checkNotNull(input, "input"); try { return CharStreams.toString(new InputStreamReader(input, Charsets.UTF_8)); } finally { closeQuietly(input); } }
public static String getHtml(HttpEntity entity) throws IOException { String html = null; if (entity != null) { InputStream in = entity.getContent(); html = CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)); if (in != null) in.close(); } return html; }
public String streamTOString(InputStream stream) { String string = null; try { string = CharStreams.toString(new InputStreamReader(stream, "UTF-8")); } catch (IOException e) { e.printStackTrace(); } return string; }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { assertThat(req.getHeader(HttpHeaders.CONTENT_TYPE)).isEqualToIgnoringCase(PLAIN_TEXT_UTF_8); assertThat(req.getHeader(HttpHeaders.CONTENT_ENCODING)).isNull(); System.out.println(CharStreams.toString(req.getReader())); resp.setContentType(PLAIN_TEXT_UTF_8); resp.getWriter().write("Banner has been updated"); }
public static Iterable<String> getLines(final InputStream in) throws IOException { final Reader reader = new InputStreamReader(in, Charsets.UTF_8); try { final String content = CharStreams.toString(reader); return getLines(content); } finally { Closeables.closeQuietly(reader); } }
@Override public String get(String url) throws ServidorIndisponivelException { try (InputStream resposta = new URL(url).openStream(); Reader reader = new InputStreamReader(resposta)) { return CharStreams.toString(reader); } catch (MalformedURLException e) { throw new IllegalArgumentException("A url " + url + " está inválida, corrija-a!", e); } catch (IOException e) { throw new ServidorIndisponivelException(url, e); } }
@Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final String body = CharStreams.toString(new InputStreamReader(request.getInputStream(), "UTF-8")); System.out.print("Got " + body); response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("{\"key\"=12}"); }
public static String inputStreamToString(InputStream inputStream) throws IOException { String text; InputStreamReader reader = new InputStreamReader(inputStream, Charsets.UTF_8); boolean threw = true; try { text = CharStreams.toString(reader); threw = false; } finally { Closeables.close(reader, threw); } return text; }
/** This tests based on an imported JSON data file. */ @Test @Ignore public void testImport() throws Exception { // perform operations // adding a new key jmemcache.add( "key", 5, CharStreams.toString( new InputStreamReader( Thread.currentThread().getContextClassLoader().getResourceAsStream("sample.json"), Charsets.UTF_8))); // getting the key value String object = jmemcache.get("key").toString(); assertEquals( CharStreams.toString( new InputStreamReader( Thread.currentThread().getContextClassLoader().getResourceAsStream("sample.json"), Charsets.UTF_8)), object); }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); RemoteWorkResponse.Builder workResponse = RemoteWorkResponse.newBuilder(); // TODO(alpha): Choose a better temp directory name. Path tempRoot = workPath.getRelative("build-" + UUID.randomUUID().toString()); FileSystemUtils.createDirectoryAndParents(tempRoot); boolean deleteTree = true; try { String workJson = CharStreams.toString(request.getReader()); RemoteWorkRequest.Builder workRequest = RemoteWorkRequest.newBuilder(); JsonFormat.parser().merge(workJson, workRequest); RemoteWorkRequest work = workRequest.build(); final MemcacheActionCache actionCache = new MemcacheActionCache(tempRoot, remoteOptions, cache); final MemcacheWorkExecutor workExecutor = new MemcacheWorkExecutor(actionCache, executorService, tempRoot); if (options.debug) { System.out.println( "[INFO] Work received has " + work.getInputFilesCount() + " inputs files and " + work.getOutputFilesCount() + " output files."); } RemoteWorkExecutor.Response executorResponse = workExecutor.submit(work).get(); if (options.debug) { if (!executorResponse.success()) { deleteTree = false; System.out.println("[WARNING] Work failed."); System.out.println(workJson); } else { System.out.println("[INFO] Work completed."); } } workResponse .setSuccess(executorResponse.success()) .setOut(executorResponse.getOut()) .setErr(executorResponse.getErr()); } catch (Exception e) { workResponse.setSuccess(false).setOut("").setErr("").setException(e.toString()); } finally { if (deleteTree) { FileSystemUtils.deleteTree(tempRoot); } else { System.out.println("[WARNING] Preserving work directory " + tempRoot.toString() + "."); } response.setStatus(HttpServletResponse.SC_OK); response.getWriter().print(JsonFormat.printer().print(workResponse.build())); } }
/** * Send notification to Jenkins using the provided settings * * @param repo The repository to base the notification on. * @param jenkinsBase Base URL for Jenkins instance * @param ignoreCerts True if all certs should be allowed * @param cloneType The repository type * @param cloneUrl The repository url * @param strRef The branch ref related to the commit * @param strSha1 The commit's SHA1 hash code. * @param omitHashCode Defines whether the commit's SHA1 hash code is omitted in notification to * Jenkins. * @param omitBranchName Defines whether the commit's branch name is omitted * @return The notification result. */ public @Nullable NotificationResult notify( @Nonnull Repository repo, // CHECKSTYLE:annot String jenkinsBase, boolean ignoreCerts, String cloneType, String cloneUrl, String strRef, String strSha1, boolean omitHashCode, boolean omitBranchName) { HttpClient client = null; String url; try { url = getUrl( repo, maybeReplaceSlash(jenkinsBase), cloneType, cloneUrl, strRef, strSha1, omitHashCode, omitBranchName); } catch (Exception e) { LOGGER.error("Error getting Jenkins URL", e); return new NotificationResult(false, null, e.getMessage()); } try { client = httpClientFactory.getHttpClient(url.startsWith("https"), ignoreCerts); HttpResponse response = client.execute(new HttpGet(url)); LOGGER.debug("Successfully triggered jenkins with url '{}': ", url); InputStream content = response.getEntity().getContent(); String responseBody = CharStreams.toString(new InputStreamReader(content, Charsets.UTF_8)); boolean successful = responseBody.startsWith("Scheduled"); NotificationResult result = new NotificationResult(successful, url, "Jenkins response: " + responseBody); return result; } catch (Exception e) { LOGGER.error("Error triggering jenkins with url '" + url + "'", e); return new NotificationResult(false, url, e.getMessage()); } finally { if (client != null) { client.getConnectionManager().shutdown(); LOGGER.debug("Successfully shutdown connection"); } } }