List of usage examples for com.google.common.io CharStreams toString
public static String toString(Readable r) throws IOException
From source file:com.spotify.it.frontend.Main.java
public static void main(String[] args) { if (args.length < 1) { System.err.println("Needs backend URL as command-line argument"); System.exit(1);//from w w w . j ava 2 s.c o m return; } URI backendUri = URI.create(args[0]); Random random = new SecureRandom(); Spark.port(1338); Spark.get("/", (req, res) -> { String uppercase = new BigInteger(130, random).toString(32).toUpperCase(); String version; try (InputStream versionStream = backendUri.resolve("/api/version").toURL().openStream()) { version = CharStreams.toString(new InputStreamReader(versionStream, StandardCharsets.UTF_8)); } String lowercase; try (InputStream lowercaseStream = backendUri.resolve("/api/lowercase/" + uppercase).toURL() .openStream()) { lowercase = CharStreams.toString(new InputStreamReader(lowercaseStream, StandardCharsets.UTF_8)); } return "<!DOCTYPE html><html>" + "<head><title>frontend</title></head>" + "<body>" + "<p>Backend version: " + version + "</p>" + "<p>Lower case of " + uppercase + " is according to backend " + lowercase + "</p>" + "</body></html>"; }); }
From source file:com.wamad.Example.java
public static void main(String[] args) throws IOException { String server = "irc.freenode.net"; int port = 6667; String nick = "irc-bot"; String login = nick;//w w w . jav a2 s . c om Socket socket = new Socket(server, port); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("loging in with nick " + nick); bw.write("NICK " + nick + "\n"); bw.flush(); // System.out.println("loging in with login " + login); // bw.write("USER " + login + "\n"); // bw.flush(); System.out.println("join gibson"); bw.write("JOIN ##gibson\n"); bw.flush(); System.out.println("print"); bw.write("HELLO WORLD\n"); bw.flush(); String out = CharStreams.toString(br); System.out.println("output so far" + out); }
From source file:net.sf.qualitycheck.immutableobject.ImmutableObjectGeneratorMain.java
public static void main(final String[] args) throws IOException { final ImmutableSettings.Builder settings = new ImmutableSettings.Builder(); // global settings settings.fieldPrefix(""); settings.jsr305Annotations(true);// w w w. j a v a 2 s. com settings.guava(true); settings.qualityCheck(true); // immutable settings settings.copyMethods(false); settings.hashCodePrecomputation(false); settings.hashCodeAndEquals(true); settings.replacement(true); settings.serializable(false); settings.toString(true); // builder settings settings.builderCopyConstructor(true); settings.builderFlatMutators(false); settings.builderFluentMutators(true); settings.builderName(""); settings.builderImplementsInterface(false); final String name = "Constructor.java"; final InputStream stream = ImmutableObjectGeneratorMain.class.getClassLoader().getResourceAsStream(name); final Result result = ImmutableObjectGenerator.generate(CharStreams.toString(new InputStreamReader(stream)), settings.build()); LOG.info("\n" + result.getImplCode()); LOG.info("\n" + result.getTestCode()); }
From source file:com.google.android.work.emmnotifications.PushSubscriber.java
public static void main(String[] args) throws Exception { Pubsub client = ServiceAccountConfiguration.createPubsubClient( Settings.getSettings().getServiceAccountEmail(), Settings.getSettings().getServiceAccountP12KeyPath()); ensureSubscriptionExists(client);/* w w w. j av a 2 s. c o m*/ // Kicking off HttpServer which will listen on the specified port and process all // incoming push pub/sub notifications HttpServer server = HttpServer.create(new InetSocketAddress(Settings.getSettings().getPort()), 0); server.createContext("/", new HttpHandler() { public void handle(HttpExchange httpExchange) throws IOException { String rawRequest = CharStreams.toString(new InputStreamReader(httpExchange.getRequestBody())); LOG.info("Raw request: " + rawRequest); try { JsonParser parser = JacksonFactory.getDefaultInstance().createJsonParser(rawRequest); parser.skipToKey(MESSAGE_FIELD); PubsubMessage message = parser.parseAndClose(PubsubMessage.class); LOG.info("Pubsub message received: " + message.toPrettyString()); // Decode Protocol Buffer message from base64 encoded byte array. EmmPubsub.MdmPushNotification mdmPushNotification = EmmPubsub.MdmPushNotification.newBuilder() .mergeFrom(message.decodeData()).build(); LOG.info("Message received: " + mdmPushNotification.toString()); } catch (InvalidProtocolBufferException e) { LOG.log(Level.WARNING, "Error occured when decoding message", e); } // CloudPubSub will interpret 2XX as ACK, anything that isn't 2XX will trigger a retry httpExchange.sendResponseHeaders(HttpStatusCodes.STATUS_CODE_NO_CONTENT, 0); httpExchange.close(); } }); server.setExecutor(null); server.start(); // Will keep running until killed }
From source file:com.music.tools.SongDBDownloader.java
public static void main(String[] args) throws Exception { HttpClient client = new DefaultHttpClient(); // HttpHost proxy = new HttpHost("localhost", 8888); // client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); HttpContext ctx = new BasicHttpContext(); HttpUriRequest req = new HttpGet( "http://www.hooktheory.com/analysis/view/the-beatles/i-want-to-hold-your-hand"); client.execute(req, ctx);// w w w . j a va 2 s . c om req.abort(); List<String> urls = getSongUrls( "http://www.hooktheory.com/analysis/browseSearch?sQuery=&sOrderBy=views&nResultsPerPage=525&nPage=1", client, ctx); List<List<? extends NameValuePair>> paramsList = new ArrayList<>(urls.size()); for (String songUrl : urls) { paramsList.addAll(getSongParams(songUrl, client, ctx)); } int i = 0; for (List<? extends NameValuePair> params : paramsList) { HttpPost request = new HttpPost("http://www.hooktheory.com/songs/getXML"); request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1"); request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); request.setHeader("Accept-Encoding", "gzip, deflate"); request.setHeader("Accept-Language", "en,en-us;q=0.7,bg;q=0.3"); request.setHeader("Content-Type", "application/x-www-form-urlencoded"); request.setHeader("Origin", "http://www.hooktheory.com"); request.setHeader("Referer", URLEncoder.encode("http://www.hooktheory.com/swf/DNALive Version 1.0.131.swf", "utf-8")); HttpEntity entity = new UrlEncodedFormEntity(params); request.setEntity(entity); try { HttpResponse response = client.execute(request, ctx); if (response.getStatusLine().getStatusCode() == 200) { InputStream is = response.getEntity().getContent(); String xml = CharStreams.toString(new InputStreamReader(is)); is.close(); Files.write(xml, new File("c:/tmp/musicdb/" + i + ".xml"), Charset.forName("utf-8")); } else { System.out.println(response.getStatusLine()); System.out.println(params); } i++; request.abort(); } catch (Exception ex) { System.out.println(params); ex.printStackTrace(); } } }
From source file:org.opendaylight.netconf.test.tool.ScaleUtil.java
public static void main(final String[] args) { final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser()); setUpLoggers(params);/*from w w w . ja v a2 s .c o m*/ // cleanup at the start in case controller was already running final Runtime runtime = Runtime.getRuntime(); cleanup(runtime, params); while (true) { root.warn("Starting scale test with {} devices", params.deviceCount); timeoutGuardFuture = executor.schedule(new TimeoutGuard(), timeout, TimeUnit.MINUTES); final NetconfDeviceSimulator netconfDeviceSimulator = new NetconfDeviceSimulator(params.threadAmount); try { final List<Integer> openDevices = netconfDeviceSimulator.start(params); if (openDevices.size() == 0) { root.error("Failed to start any simulated devices, exiting..."); System.exit(1); } if (params.distroFolder != null) { final Main.ConfigGenerator configGenerator = new Main.ConfigGenerator(params.distroFolder, openDevices); final List<File> generated = configGenerator.generate(params.ssh, params.generateConfigBatchSize, params.generateConfigsTimeout, params.generateConfigsAddress, params.devicesPerPort); configGenerator.updateFeatureFile(generated); configGenerator.changeLoadOrder(); } } catch (final Exception e) { root.error("Unhandled exception", e); netconfDeviceSimulator.close(); System.exit(1); } root.warn(params.distroFolder.getAbsolutePath()); try { runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/start"); String status; do { final Process exec = runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/status"); try { Thread.sleep(2000l); } catch (InterruptedException e) { root.warn("Failed to sleep", e); } status = CharStreams.toString(new BufferedReader(new InputStreamReader(exec.getInputStream()))); root.warn("Current status: {}", status); } while (!status.startsWith("Running ...")); root.warn("Doing feature install {}", params.distroFolder.getAbsolutePath() + "/bin/client -u karaf feature:install odl-restconf-noauth odl-netconf-connector-all"); final Process featureInstall = runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/client -u karaf feature:install odl-restconf-noauth odl-netconf-connector-all"); root.warn(CharStreams .toString(new BufferedReader(new InputStreamReader(featureInstall.getInputStream())))); root.warn(CharStreams .toString(new BufferedReader(new InputStreamReader(featureInstall.getErrorStream())))); } catch (IOException e) { root.warn("Failed to start karaf", e); System.exit(1); } root.warn("Karaf started, starting stopwatch"); stopwatch.start(); try { executor.schedule(new ScaleVerifyCallable(netconfDeviceSimulator, params.deviceCount), retryDelay, TimeUnit.SECONDS); root.warn("First callable scheduled"); semaphore.acquire(); root.warn("semaphore released"); } catch (InterruptedException e) { throw new RuntimeException(e); } timeoutGuardFuture.cancel(false); params.deviceCount += deviceStep; netconfDeviceSimulator.close(); stopwatch.reset(); cleanup(runtime, params); } }
From source file:com.indeed.imhotep.builder.tsv.KerberosUtils.java
/** * Use for testing keytab logins// w ww .j av a 2 s. c o m */ public static void main(String[] args) throws Exception { KerberosUtils.loginFromKeytab(new BaseConfiguration()); final FileSystem fileSystem = FileSystem.get(new org.apache.hadoop.conf.Configuration()); final Path path = new Path("/CLUSTERNAME"); if (fileSystem.exists(path)) { System.out.println(CharStreams.toString(new InputStreamReader(fileSystem.open(path), Charsets.UTF_8))); } }
From source file:io.knotx.junit.util.FileReader.java
static String readText(String path) throws IOException { return CharStreams.toString(new InputStreamReader(Resources.getResource(path).openStream(), "utf-8")); }
From source file:com.mdrsolutions.external.xml.XmlCalls.java
public static final String getXml(String filePath) { String xml = ""; try {/*from w ww . j av a 2 s . c o m*/ InputStream is = SqlCalls.class.getResourceAsStream(filePath); xml = CharStreams.toString(new InputStreamReader(is)); if (null == xml || xml.isEmpty()) { Closeables.closeQuietly(is); throw new IOException("File path to XML file could not be read!"); } else { Closeables.closeQuietly(is); return xml; } } catch (IOException ex) { logger.error("Could not read the sql file specified!", ex); } return xml; }
From source file:org.lobid.lodmill.StreamToStringReader.java
private static void process(final Reader reader, final ObjectReceiver<String> receiver) { try {// w ww . j a va 2s .c o m receiver.process(CharStreams.toString(reader)); } catch (IOException e) { e.printStackTrace(); } }