List of usage examples for com.google.common.io CharStreams toString
public static String toString(Readable r) throws IOException
From source file:com.axemblr.provisionr.core.templates.xml.XmlTemplate.java
/** * @return an XmlTemplate instance resulted from parsing a file *///ww w . ja va2 s . c o m public static XmlTemplate newXmlTemplate(File file) { FileReader reader = null; try { reader = new FileReader(file); return newXmlTemplate(CharStreams.toString(reader)); } catch (IOException e) { throw Throwables.propagate(e); } finally { Closeables.closeQuietly(reader); } }
From source file:com.cisco.oss.foundation.directory.utils.HttpUtils.java
/** * Invoke REST Service using POST method. * * @param urlStr/* w ww.j av a 2 s .c o m*/ * the REST service URL String * @param body * the Http Body String. * @return * the HttpResponse. * @throws IOException */ public static HttpResponse postJson(String urlStr, String body) throws IOException { URL url = new URL(urlStr); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.addRequestProperty("Accept", "application/json"); urlConnection.setRequestMethod("POST"); urlConnection.addRequestProperty("Content-Type", "application/json"); urlConnection.addRequestProperty("Content-Length", Integer.toString(body.length())); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setUseCaches(false); OutputStream out = urlConnection.getOutputStream(); out.write(body.getBytes()); ByteStreams.copy(new ByteArrayInputStream(body.getBytes()), out); BufferedReader in = null; try { int errorCode = urlConnection.getResponseCode(); if ((errorCode <= 202) && (errorCode >= 200)) { in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); } else { InputStream error = urlConnection.getErrorStream(); if (error != null) { in = new BufferedReader(new InputStreamReader(error)); } } String json = null; if (in != null) { json = CharStreams.toString(in); } return new HttpResponse(errorCode, json); } finally { if (in != null) { in.close(); } } }
From source file:com.axmor.eclipse.typescript.editor.compare.TypeScriptViewer.java
/** * @param input// w w w . ja va 2s . c o m * input source * @return string content of input */ private static String getString(Object input) { if (input instanceof IStreamContentAccessor) { IStreamContentAccessor sca = (IStreamContentAccessor) input; try { return CharStreams.toString(new InputStreamReader(sca.getContents(), Charsets.UTF_8)); } catch (Exception e) { Activator.error(e); } } return ""; }
From source file:util.HttpUtils.java
/** * Makes a HTTP Get.// w w w. j a v a 2s . c o m * @return Response string */ public static String getRequest(String url) { try { URL urlObj = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(getDefaultProxy()); conn.setDoOutput(true); return CharStreams.toString(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); } catch (Exception e) { return "ERROR: " + Throwables.getStackTraceAsString(e); } }
From source file:hyper.momitor.util.etcd.HMEtcdClientImpl.java
@Override public String version() throws HMEtcdException { try (InputStreamReader reader = new InputStreamReader(etcd.version().getBody().in(), Charsets.UTF_8)) { return CharStreams.toString(reader); } catch (IOException e) { return "ERROR: " + e.getMessage(); }/*www .j a va 2 s .co m*/ }
From source file:org.eclipse.recommenders.args.completion.rcp.usagedb.UsageDBJSONReader.java
/** * Read param info from json file./*from w ww . ja v a 2s . c o m*/ * * Include the list of ParamInfo , and list of frequency. * * @return "true" for success */ public final boolean readMapFromJSON() { boolean success = false; String content; try { content = CharStreams.toString(new InputStreamReader(inputStream)); //The json file contains only a list of ParamInfoToJson. List<ParamInfoToJson> paramInfos = (List<ParamInfoToJson>) new Gson().fromJson(content, new TypeToken<List<ParamInfoToJson>>() { }.getType()); for (ParamInfoToJson p : paramInfos) { index2param.put(p.getIndex(), p.getParaminfo()); index2freq.put(p.getIndex(), p.getFreq()); success = true; } } catch (IOException e) { e.printStackTrace(); } return success; }
From source file:controllers.oer.NtToEs.java
static String config() throws IOException, FileNotFoundException { return CharStreams.toString(new FileReader(CONFIG)); }
From source file:com.example.appengine.pusher.AuthorizeServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // Instantiate a pusher connection Pusher pusher = PusherService.getDefaultInstance(); // Get current logged in user credentials User user = UserServiceFactory.getUserService().getCurrentUser(); // redirect to homepage if user is not authorized if (user == null) { response.sendRedirect("/"); return;/* w ww. j a v a 2 s. c om*/ } String currentUserId = user.getUserId(); String displayName = user.getNickname().replaceFirst("@.*", ""); String query = CharStreams.toString(request.getReader()); // socket_id, channel_name parameters are automatically set in the POST body of the request // eg.socket_id=1232.12&channel_name=presence-my-channel Map<String, String> data = splitQuery(query); String socketId = data.get("socket_id"); String channelId = data.get("channel_name"); // Presence channels (presence-*) require user identification for authentication Map<String, String> userInfo = new HashMap<>(); userInfo.put("displayName", displayName); // Inject custom authentication code for your application here to allow /deny current request String auth = pusher.authenticate(socketId, channelId, new PresenceUser(currentUserId, userInfo)); // if successful, returns authorization in the format // { // "auth":"49e26cb8e9dde3dfc009:a8cf1d3deefbb1bdc6a9d1547640d49d94b4b512320e2597c257a740edd1788f", // "channel_data":"{\"user_id\":\"23423435252\",\"user_info\":{\"displayName\":\"John Doe\"}}" // } response.getWriter().append(auth); }
From source file:com.skcraft.launcher.creator.util.ModInfoReader.java
/** * Detect the mods listed in the given .jar * * @param file The file// w w w . ja v a 2 s . co m * @return A list of detected mods */ public List<? extends ModInfo> detectMods(File file) { Closer closer = Closer.create(); try { FileInputStream fis = closer.register(new FileInputStream(file)); BufferedInputStream bis = closer.register(new BufferedInputStream(fis)); ZipInputStream zis = closer.register(new ZipInputStream(bis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (entry.getName().equalsIgnoreCase(FORGE_INFO_FILENAME)) { List<ForgeModInfo> mods; String content = CharStreams.toString(new InputStreamReader(zis, Charsets.UTF_8)); try { mods = mapper.readValue(content, ForgeModManifest.class).getMods(); } catch (JsonMappingException | JsonParseException e) { mods = mapper.readValue(content, new TypeReference<List<ForgeModInfo>>() { }); } if (mods != null) { // Ignore "examplemod" return Collections.unmodifiableList( mods.stream().filter(info -> !info.getModId().equals("examplemod")) .collect(Collectors.toList())); } else { return Collections.emptyList(); } } else if (entry.getName().equalsIgnoreCase(LITELOADER_INFO_FILENAME)) { String content = CharStreams.toString(new InputStreamReader(zis, Charsets.UTF_8)); return new ImmutableList.Builder<ModInfo>() .add(mapper.readValue(content, LiteLoaderModInfo.class)).build(); } } return Collections.emptyList(); } catch (JsonMappingException e) { log.log(Level.WARNING, "Unknown format " + FORGE_INFO_FILENAME + " file in " + file.getAbsolutePath(), e); return Collections.emptyList(); } catch (JsonParseException e) { log.log(Level.WARNING, "Corrupt " + FORGE_INFO_FILENAME + " file in " + file.getAbsolutePath(), e); return Collections.emptyList(); } catch (IOException e) { log.log(Level.WARNING, "Failed to read " + file.getAbsolutePath(), e); return Collections.emptyList(); } finally { try { closer.close(); } catch (IOException ignored) { } } }
From source file:de.dentrassi.pm.usage.Pinger.java
protected static void performPing(final Statistics statistics) throws Exception { final URLConnection con = URL.openConnection(); con.setDoOutput(true);//from w ww. j a va 2 s. co m con.setUseCaches(false); logger.debug("Connection: {}", con); if (con instanceof HttpURLConnection) { ((HttpURLConnection) con).setRequestMethod("POST"); ((HttpURLConnection) con).setInstanceFollowRedirects(false); } con.setRequestProperty("Content-type", "text/json"); con.setRequestProperty("User-agent", VersionInformation.USER_AGENT); try (OutputStream out = con.getOutputStream()) { final GsonBuilder gb = new GsonBuilder(); final Gson g = gb.create(); final OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8); g.toJson(statistics, writer); writer.flush(); } try (InputStream in = con.getInputStream()) { final String result = CharStreams.toString(new InputStreamReader(in, StandardCharsets.UTF_8)); logger.debug("Ping result: {}", result); } }