List of usage examples for java.io Reader read
public int read() throws IOException
From source file:com.varaneckas.hawkscope.plugin.PluginManager.java
private void processPlugin(final File pluginDir, final String jar) { try {// w w w. j ava 2 s . co m final File jarFile = new File(pluginDir.getAbsolutePath() + "/" + jar); final URLClassLoader classLoader = new URLClassLoader(new URL[] { jarFile.toURI().toURL() }); final Reader r = new InputStreamReader(classLoader.getResourceAsStream("plugin.loader")); String pluginClass = ""; int c = 0; while ((c = r.read()) != -1) { pluginClass += (char) c; } r.close(); log.debug("Processing Plugin: " + pluginClass); if (!isPluginEnabled(pluginClass)) { log.debug("Plugin disabled, skipping"); getAllPlugins().add(new DisabledPlugin(pluginClass)); return; } Class<?> p = classLoader.loadClass(pluginClass); Method creator = null; try { creator = p.getMethod("getInstance", new Class[] {}); } catch (final NoSuchMethodException no) { log.debug("Plugin does not implement a singleton getter"); } Plugin plugin; if (creator == null) { plugin = (Plugin) p.newInstance(); } else { plugin = (Plugin) creator.invoke(p, new Object[] {}); } creator = null; p = null; if (plugin != null) { log.debug("Adding plugin: " + plugin); getAllPlugins().add(plugin); } } catch (final Exception e) { log.warn("Failed loading plugin: " + jar, e); } }
From source file:com.google.acre.script.NHttpAsyncUrlfetch.java
private Scriptable callback_result(long start_time, URL url, HttpResponse res, boolean system, boolean log_to_user, String response_encoding) { BrowserCompatSpecFactory bcsf = new BrowserCompatSpecFactory(); CookieSpec cspec = bcsf.newInstance(null); String protocol = url.getProtocol(); boolean issecure = ("https".equals(protocol)); int port = url.getPort(); if (port == -1) port = 80;/*w w w .ja va 2s . com*/ CookieOrigin origin = new CookieOrigin(url.getHost(), port, url.getPath(), issecure); Object body = ""; int status = res.getStatusLine().getStatusCode(); Context ctx = Context.getCurrentContext(); Scriptable out = ctx.newObject(_scope); Scriptable headers = ctx.newObject(_scope); Scriptable cookies = ctx.newObject(_scope); out.put("status", out, status); out.put("headers", out, headers); out.put("cookies", out, cookies); Header content_type_header = null; StringBuilder response_header_log = new StringBuilder(); for (Header h : res.getAllHeaders()) { if (h.getName().equalsIgnoreCase("set-cookie")) { String set_cookie = h.getValue(); Matcher m = Pattern.compile("\\s*(([^,]|(,\\s*\\d))+)").matcher(set_cookie); while (m.find()) { Header ch = new BasicHeader("Set-Cookie", set_cookie.substring(m.start(), m.end())); try { List<Cookie> pcookies = cspec.parse(ch, origin); for (Cookie c : pcookies) { cookies.put(c.getName(), cookies, new AcreCookie(c).toJsObject(_scope)); } } catch (MalformedCookieException e) { throw new RuntimeException(e); } } } else if (h.getName().equalsIgnoreCase("content-type")) { content_type_header = h; } response_header_log.append(h.getName() + ": " + h.getValue() + "\r\n"); headers.put(h.getName(), headers, h.getValue()); } String charset = null; if (content_type_header != null) { HeaderElement values[] = content_type_header.getElements(); if (values.length == 1) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } if (charset == null) charset = response_encoding; // read body HttpEntity ent = res.getEntity(); try { if (ent != null) { InputStream res_stream = ent.getContent(); Header cenc = ent.getContentEncoding(); if (cenc != null && res_stream != null) { HeaderElement[] codecs = cenc.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase("gzip")) { res_stream = new GZIPInputStream(res_stream); } } } long first_byte_time = 0; long end_time = 0; if (content_type_header != null && (content_type_header.getValue().startsWith("image/") || content_type_header.getValue().startsWith("application/octet-stream") || content_type_header.getValue().startsWith("multipart/form-data"))) { // HttpClient's InputStream doesn't support mark/reset, so // wrap it with one that does. BufferedInputStream bufis = new BufferedInputStream(res_stream); bufis.mark(2); bufis.read(); first_byte_time = System.currentTimeMillis(); bufis.reset(); byte[] data = IOUtils.toByteArray(bufis); end_time = System.currentTimeMillis(); body = new JSBinary(); ((JSBinary) body).set_data(data); try { if (res_stream != null) res_stream.close(); } catch (IOException e) { // ignore } } else if (res_stream == null || charset == null) { first_byte_time = end_time = System.currentTimeMillis(); body = ""; } else { StringWriter writer = new StringWriter(); Reader reader = new InputStreamReader(res_stream, charset); int i = reader.read(); first_byte_time = System.currentTimeMillis(); writer.write(i); IOUtils.copy(reader, writer); end_time = System.currentTimeMillis(); body = writer.toString(); try { reader.close(); writer.close(); } catch (IOException e) { // ignore } } long reading_time = end_time - first_byte_time; long waiting_time = first_byte_time - start_time; String httprephdr = response_header_log.toString(); // XXX need to log start-time of request _logger.syslog4j("DEBUG", "urlfetch.response.async", "URL", url.toString(), "Status", Integer.toString(status), "Headers", httprephdr, "Reading time", reading_time, "Waiting time", waiting_time); if (system && log_to_user) { _response.userlog4j("DEBUG", "urlfetch.response.async", "URL", url.toString(), "Status", Integer.toString(status), "Headers", httprephdr); } // XXX seems like AcreResponse should be able to use // the statistics object to generate x-metaweb-cost // given a bit of extra information Statistics.instance().collectUrlfetchTime(start_time, first_byte_time, end_time); _costCollector.collect((system) ? "asuc" : "auuc").collect((system) ? "asuw" : "auuw", waiting_time); } } catch (IOException e) { throw new RuntimeException(e); } out.put("body", out, body); return out; }
From source file:net.metanotion.json.StreamingParser.java
private Lexeme maybeNumber(final Reader in, int firstChar) throws IOException { // this might be a number, if it is, lex it and return the token, otherwise throw an exception. final String integer = lexInt(in, firstChar); in.mark(MAX_BUFFER);//from w w w .j a v a 2 s .c om final int c = in.read(); if (c == '.') { final String decimal = integer + lexFraction(in); return new Lexeme(Token.FLOAT, Double.valueOf(decimal)); } else if (Character.toLowerCase(c) == 'e') { in.reset(); final String decimal = integer + lexExp(in); return new Lexeme(Token.FLOAT, Double.valueOf(decimal)); } else { in.reset(); return new Lexeme(Token.INT, Long.valueOf(integer)); } }
From source file:com.hp.avmon.home.service.LicenseService.java
/** * ?servercpuID//from w w w . j a va2 s .co m * * @return */ public String getServerCpuIdFromFile() { StringBuffer cpuidStrBf = new StringBuffer(); // callVbExeFile(); // String cpuidFullPath = getLicensePath() + "mycpuid.txt"; File file = new File(cpuidFullPath); if (!file.exists()) { log.info("mycpuid is not exist!"); } Reader reader = null; try { reader = new InputStreamReader(new FileInputStream(file)); int buffer = 0; while ((buffer = reader.read()) != -1) { if ((char) buffer != '\n' && (char) buffer != '\r' && (char) buffer != ' ') { cpuidStrBf.append((char) buffer); } } reader.close(); } catch (Exception e) { try { reader.close(); } catch (IOException e1) { e1.printStackTrace(); } } return cpuidStrBf.toString(); }
From source file:com.bigdata.rdf.sail.webapp.AbstractTestNanoSparqlClient.java
protected static String getResponseBody(final HttpURLConnection conn) throws IOException { final Reader r = new InputStreamReader(conn.getInputStream()); try {//from w w w .j a va 2 s. co m final StringWriter w = new StringWriter(); int ch; while ((ch = r.read()) != -1) { w.append((char) ch); } return w.toString(); } finally { r.close(); } }
From source file:com.formkiq.core.equifax.service.EquifaxServiceImpl.java
/** * Sends request to Equifax./*from w w w . j a v a2s. com*/ * @param server {@link String} * @param send {@link String} * @return {@link String} * @throws IOException IOException */ public String sendToEquifax(final String server, final String send) throws IOException { String params = "InputSegments=" + URLEncoder.encode(send, "UTF-8") + "&cmdSubmit=Submit"; byte[] postData = params.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; URL url = new URL(server); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", Integer.toString(postDataLength)); conn.setUseCaches(false); Reader in = null; DataOutputStream wr = null; try { wr = new DataOutputStream(conn.getOutputStream()); wr.write(postData); StringBuilder sb = new StringBuilder(); in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); for (int c = in.read(); c != -1; c = in.read()) { sb.append((char) c); } String receive = sb.toString(); return receive; } finally { if (in != null) { in.close(); } if (wr != null) { wr.close(); } } }
From source file:io.kaif.kmark.KmarkProcessor.java
private Block readLines(final Reader reader, final Emitter emitter) throws IOException { final Block block = new Block(); final StringBuilder sb = new StringBuilder(200); boolean underCodeBlock = false; int c = reader.read(); LinkRef lastLinkRef = null;/* www. jav a2 s. c o m*/ while (c != -1) { sb.setLength(0); int pos = 0; boolean eol = false; while (!eol) { switch (c) { case -1: eol = true; break; case '\n': c = reader.read(); if (c == '\r') { c = reader.read(); } eol = true; break; case '\r': c = reader.read(); if (c == '\n') { c = reader.read(); } eol = true; break; case '\t': { final int np = pos + (4 - (pos & 3)); while (pos < np) { sb.append(' '); pos++; } c = reader.read(); break; } default: pos++; sb.append((char) c); c = reader.read(); break; } } final Line line = new Line(); line.value = sb.toString(); line.init(); if (line.getLineType() == LineType.FENCED_CODE) { underCodeBlock = !underCodeBlock; } if (underCodeBlock) { block.appendLine(line); continue; } // Check for link definitions boolean isLinkRef = false; String id = null, link = null, comment = null; if (!line.isEmpty && line.value.charAt(line.leading) == '[') { line.pos = line.leading + 1; // Read ID up to ']' id = line.readUntil(']'); // Is ID valid and are there any more characters? if (id != null && line.pos + 2 < line.value.length()) { // Check for ':' ([...]:...) if (line.value.charAt(line.pos + 1) == ':') { line.pos += 2; line.skipSpaces(); // Check for link syntax if (line.value.charAt(line.pos) == '<') { line.pos++; link = line.readUntil('>'); line.pos++; } else { link = line.readUntil(' ', '\n'); } // Is link valid? if (link != null) { // Any non-whitespace characters following? if (line.skipSpaces()) { final char ch = line.value.charAt(line.pos); // Read comment if (ch == '\"' || ch == '\'' || ch == '(') { line.pos++; comment = line.readUntil(ch == '(' ? ')' : ch); // Valid linkRef only if comment is valid if (comment != null) { isLinkRef = true; } } } else { isLinkRef = true; } } } } } if (isLinkRef) { // Store linkRef and skip line final LinkRef lr = emitter.addLinkRef(id, link, comment); if (comment == null) { lastLinkRef = lr; } } else { comment = null; // Check for multi-line linkRef if (!line.isEmpty && lastLinkRef != null) { line.pos = line.leading; final char ch = line.value.charAt(line.pos); if (ch == '\"' || ch == '\'' || ch == '(') { line.pos++; comment = line.readUntil(ch == '(' ? ')' : ch); } if (comment != null) { lastLinkRef.title = comment; } lastLinkRef = null; } // No multi-line linkRef, store line if (comment == null) { line.pos = 0; block.appendLine(line); } } } return block; }
From source file:com.moss.appsnap.keeper.Keeper.java
public Keeper(final Url location) { log.info("Starting keeper for " + location); final DesktopIntegrationStrategy desktop = new Bootstrapper().discover(); final ProxyFactory proxyFactory = new ProxyFactory(new HessianProxyProvider()); final AppsnapService snap = proxyFactory.create(AppsnapService.class, location.toString()); AppsnapServiceInfo serviceInfo;/*from w w w. j a v a 2 s. c o m*/ while (true) { try { serviceInfo = snap.serviceInfo(); break; } catch (Exception e) { log.error("Error talking to appsnap. Will try again in 5 seconds. The message was: " + e.getMessage(), e); try { Thread.sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); } } } final File dataLocation = desktop.keeperDataDir(serviceInfo.id()); try { final File logOutput = new File(dataLocation, "log4j.log"); Logger.getRootLogger().addAppender(new FileAppender(new SimpleLayout(), logOutput.getAbsolutePath())); log.info("Configured logging to " + logOutput.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } log.info("Starting from " + dataLocation.getAbsolutePath()); Data data; try { data = new Data(dataLocation); } catch (Exception e1) { throw new RuntimeException(e1); } if (data.config.get() == null) { if (System.getProperty("dev-bootstrap", "false").equals("true")) { KeeperConfig config = new KeeperConfig(); data.config.put(config); } else { throw new NullPointerException("Keeper data has no config: have you run the installer?"); } } if (location == null) { throw new NullPointerException(); } guts = new Guts(serviceInfo, location, proxyFactory, snap, data, desktop); desktop.noLongerGutless(guts); final Poller poller = new Poller(guts, true); poller.start(); desktop.thePollerWasStartedAndHereItIs(poller); desktop.startLocalApiServer(new ApiMessageHandler() { final SocketFunction[] commands = new SocketFunction[] { new PollFunction(guts, poller), new InstallFunction(guts, poller), new ControlPanelLaunchFunction(guts), new LaunchFunction(guts, poller), new PingFuction() }; public void handle(ApiMessageConnection socket) { try { log.info("Opening connection"); StringBuilder input = new StringBuilder(); Reader r = new InputStreamReader(socket.in()); log.info("Reading input"); // char[] b = new char[1024]; // for(int x=r.read(b);x!=-1;x=r.read(b)){ // input.append(b, 0, x); // } for (int x = r.read(); x != -1 && x != '\n'; x = r.read()) { input.append((char) x); } // r.close(); log.info("Command: " + input); String commandName; String commandParams; int argsDelimiterPos = input.indexOf(" "); if (argsDelimiterPos != -1) { commandName = input.substring(0, argsDelimiterPos); commandParams = input.substring(argsDelimiterPos + 1); } else { commandName = input.toString(); commandParams = ""; } SocketFunction command = null; for (SocketFunction next : commands) { if (next.name().equals(commandName)) { command = next; } } String response; if (command == null) { response = ("Invalid command: " + commandName); } else { try { response = command.execute(commandParams); } catch (Exception e) { e.printStackTrace(); response = e.getClass().getSimpleName() + ":" + e.getMessage(); } } log.info("Sending response: " + response); Writer w = new OutputStreamWriter(socket.out()); w.write(response); w.write('\n'); w.flush(); w.close(); } catch (Throwable e) { e.printStackTrace(); } finally { socket.close(); } } }); }
From source file:com.p5solutions.core.jpa.orm.ConversionUtilityImpl.java
/** * Convert clob./*from ww w .j ava2 s . com*/ * * @param clob * the clob * @param targetType * the target type * @return the object */ public Object convertCLOB(Clob clob, Class<?> targetType) { if (ReflectionUtility.isStringClass(targetType)) { // TODO charset needs to be passed in from the resultset, or defined // as // part of the transaction template??? try { // TODO THIS NEEDS TO BE APPENDED IN UTF-8 ??? based on the // character // setting of the database??? Reader reader = clob.getCharacterStream(); StringBuilder output = new StringBuilder(); int r = -1; while ((r = reader.read()) >= 0) { output.append((char) r); } return output.toString(); } catch (SQLException e) { // TODO log it throw new RuntimeException(e); } catch (IOException e) { // TODO log it throw new RuntimeException(e); } } else if (ReflectionUtility.isByteArray(targetType)) { } return clob; }
From source file:com.sfs.jbtimporter.JBTProcessor.java
/** * Load xml data from the supplied file. * /*from ww w . j a va2 s . co m*/ * @param filepath the filepath * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public final String loadXmlDataFile(final String filepath) throws IOException { StringBuffer contents = new StringBuffer(); Reader reader = new InputStreamReader(new FileInputStream(filepath), "UTF-8"); int ch; do { ch = reader.read(); if (ch != -1) { contents.append((char) ch); } } while (ch != -1); reader.close(); return contents.toString(); }