public void runImpl() throws Exception { // create the URL corresponding to the date URL u = new URL(ADDRESS_ + dateFormatter1_.format(date)); Messages.debug(3, "Rag::runImpl - reading data from URL=%1", u); // fetch the page into the buffer buffer_ = new char[BUF_SIZE_]; Reader r = new InputStreamReader(u.openStream()); int size = 1; charsread_ = 0; while (charsread_ < BUF_SIZE_ && size > 0) { size = r.read(buffer_, 0, BUF_SIZE_ - charsread_); if (size != -1) charsread_ += size; // Messages.debug(3, "Rag::runImpl - read %1 chars", String.valueOf(size)); if (!r.ready()) break; } r.close(); // Messages.debug(3, "Rag::runImpl - buffer=\"%1\"XXXXXXX", new String(buffer_, 0, charsread_)); // create the results createResults_(); }
/** * Parse a repository document. * * @param url * @throws IOException * @throws XmlPullParserException * @throws Exception */ void parseDocument(URL url) throws IOException, XmlPullParserException, Exception { if (!visited.contains(url)) { visited.add(url); try { System.out.println("Visiting: " + url); InputStream in = null; if (url.getPath().endsWith(".zip")) { ZipInputStream zin = new ZipInputStream(url.openStream()); ZipEntry entry = zin.getNextEntry(); while (entry != null) { if (entry.getName().equals("repository.xml")) { in = zin; break; } entry = zin.getNextEntry(); } } else { in = url.openStream(); } Reader reader = new InputStreamReader(in); XmlPullParser parser = new KXmlParser(); parser.setInput(reader); parseRepository(parser); } catch (MalformedURLException e) { System.out.println("Cannot create connection to url"); } } }
static { Attributes m = null; final URL loc = Prop.LOCATION; if (loc != null) { final String jar = loc.getFile(); try { final ClassLoader cl = JarManifest.class.getClassLoader(); final Enumeration<URL> list = cl.getResources("META-INF/MANIFEST.MF"); while (list.hasMoreElements()) { final URL url = list.nextElement(); if (!url.getFile().contains(jar)) continue; final InputStream in = url.openStream(); try { m = new Manifest(in).getMainAttributes(); break; } finally { in.close(); } } } catch (final IOException ex) { Util.errln(ex); } } MAP = m; }
@Override public InputStream getInputStream() throws IOException, UnsupportedFileOperationException { VsphereConnHandler connHandler = null; try { connHandler = getConnHandler(); ManagedObjectReference fileManager = getFileManager(connHandler); FileTransferInformation fileDlInfo = connHandler .getClient() .getVimPort() .initiateFileTransferFromGuest(fileManager, vm, credentials, getPathInVm()); String fileDlUrl = fileDlInfo.getUrl().replace("*", connHandler.getClient().getServer()); // http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java URL website = new URL(fileDlUrl); return website.openStream(); } catch (InvalidPropertyFaultMsg e) { translateandLogException(e); } catch (RuntimeFaultFaultMsg e) { translateandLogException(e); } catch (FileFaultFaultMsg e) { translateandLogException(e); } catch (GuestOperationsFaultFaultMsg e) { translateandLogException(e); } catch (InvalidStateFaultMsg e) { translateandLogException(e); } catch (TaskInProgressFaultMsg e) { translateandLogException(e); } finally { releaseConnHandler(connHandler); } return null; }
/** * Load string map from a URL. * * @param mapURL URL for map file. * @param separator Field separator. * @param qualifier Quote character. * @param encoding Character encoding for the file. * @throws FileNotFoundException If input file does not exist. * @throws IOException If input file cannot be opened. * @return Map with values read from file. */ public static Map<String, String> loadMap( URL mapURL, String separator, String qualifier, String encoding) throws IOException, FileNotFoundException { Map<String, String> map = MapFactory.createNewMap(); if (mapURL != null) { BufferedReader bufferedReader = new BufferedReader(new UnicodeReader(mapURL.openStream(), encoding)); String inputLine = bufferedReader.readLine(); String[] tokens; while (inputLine != null) { tokens = inputLine.split(separator); if (tokens.length > 1) { map.put(tokens[0], tokens[1]); } inputLine = bufferedReader.readLine(); } bufferedReader.close(); } return map; }
public static void main(String[] argv) { try { URL url = new URL(argv[0]); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); MarkupReader mr = new MarkupReader(br, new AceViewerConfig(), false); } catch (Exception e) { System.err.println(e); // debug } }
public static void saveURL(URL url, OutputStream os) throws IOException { InputStream is = url.openStream(); byte[] buf = new byte[1048576]; int n = is.read(buf); while (n != -1) { os.write(buf, 0, n); n = is.read(buf); } }
public static ModuleImpl loadModule(String resource) throws IOException, CoreException { URL url = ModuleSyncRunnerTest.class.getResource(resource); if (url == null) { Assert.fail("resource not found: " + resource); } ModuleImpl module = new ModuleManifestParser().parse(url.openStream()); module.setLocation(url); return module; }
public InputStream getResourceAsStream(String path) { URL url = getResource(path); if (url == null) return null; try { return url.openStream(); } catch (IOException ioe) { throw new RuntimeException("can't getResourceAsStream [" + path + "]", ioe); } }
private void doImportFromURL(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { URL source = getSourceURL(); IOUtilities.pipe( source.openStream(), new FileOutputStream(new File(getStorageDirectory(), FILE_DATA), true), true, true); completeTransfer(req, resp); }
public static void main(String[] argv) { try { URL url = new URL(argv[0]); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); FASTASequenceReader fa = new FASTASequenceReader(br, false); StringBuffer sb = fa.get_sequences().get("chr7"); // StringBuffer sb = fa.get_sequences().get("302P7AAXX090507:5:73:1207:509#0.F1"); System.err.println(sb); // debug } catch (Exception e) { System.err.println(e); // debug } }
private static Set<String> findStandardMBeansFromJar(URL codeBase) throws Exception { InputStream is = codeBase.openStream(); JarInputStream jis = new JarInputStream(is); Set<String> names = new TreeSet<String>(); JarEntry entry; while ((entry = jis.getNextJarEntry()) != null) { String name = entry.getName(); if (!name.endsWith(".class")) continue; name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); names.add(name); } return names; }
private void readFromStorableInput(String filename) { try { URL url = new URL(getCodeBase(), filename); InputStream stream = url.openStream(); StorableInput input = new StorableInput(stream); fDrawing.release(); fDrawing = (Drawing) input.readStorable(); view().setDrawing(fDrawing); } catch (IOException e) { initDrawing(); showStatus("Error:" + e); } }
private void setup() { env = new EnvAdvanced(); // Load the game objects try { URL url = Sysutil.getURL("world.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { String[] fields = line.split(","); if (fields[0].equalsIgnoreCase("skybox")) { // The background env.setRoom(new EnvSkyRoom(fields[1])); } else if (fields[0].equalsIgnoreCase("camera")) { // The camera env.setCameraXYZ( Double.parseDouble(fields[1]), Double.parseDouble(fields[2]), Double.parseDouble(fields[3])); env.setCameraYaw(Double.parseDouble(fields[4])); env.setCameraPitch(Double.parseDouble(fields[5])); } else if (fields[0].equalsIgnoreCase("terrain")) { terrain = new EnvTerrain(fields[1]); terrain.setTextureAlpha(fields[2]); terrain.setTexture(fields[3], 1); terrain.setTexture(fields[4], 2); terrain.setTexture(fields[5], 3); env.addObject(terrain); } else if (fields[0].equalsIgnoreCase("object")) { GameObject n = (GameObject) Class.forName(fields[10]).newInstance(); n.setX(Double.parseDouble(fields[1])); n.setY(Double.parseDouble(fields[2])); n.setZ(Double.parseDouble(fields[3])); n.setScale(Double.parseDouble(fields[4])); n.setRotateX(Double.parseDouble(fields[5])); n.setRotateY(Double.parseDouble(fields[6])); n.setRotateZ(Double.parseDouble(fields[7])); n.setTexture(fields[9]); n.setModel(fields[8]); n.setEnv(env); env.addObject(n); } } } catch (Exception e) { e.printStackTrace(); } }
public static String getContent(URL url) throws IOException { String content = ""; InputStream inst = url.openStream(); InputStreamReader insr = new InputStreamReader(inst); BufferedReader buff = new BufferedReader(insr); while (true) { String line = buff.readLine(); if (line != null) content += line + "\n"; else break; } inst.close(); insr.close(); buff.close(); return content; }
static { try { URL url = SpellCheckActivator.bundleContext.getBundle().getResource(RESOURCE_LOC); InputStream stream = url.openStream(); if (stream == null) throw new IOException(); // strict parsing options DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); // parses configuration xml /*- * Warning: Felix is unable to import the com.sun.rowset.internal * package, meaning this can't use the XmlErrorHandler. This causes * a warning and a default handler to be attached. Otherwise this * should have: builder.setErrorHandler(new XmlErrorHandler()); */ DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(stream); // iterates over nodes, parsing contents Node root = doc.getChildNodes().item(1); NodeList categories = root.getChildNodes(); for (int i = 0; i < categories.getLength(); ++i) { Node node = categories.item(i); if (node.getNodeName().equals(NODE_DEFAULTS)) { parseDefaults(node.getChildNodes()); } else if (node.getNodeName().equals(NODE_LOCALES)) { parseLocales(node.getChildNodes()); } else { logger.warn("Unrecognized category: " + node.getNodeName()); } } } catch (IOException exc) { logger.error("Unable to load spell checker parameters", exc); } catch (SAXException exc) { logger.error("Unable to parse spell checker parameters", exc); } catch (ParserConfigurationException exc) { logger.error("Unable to parse spell checker parameters", exc); } }
String openUrlAsString(String address, int maxLines) { StringBuffer sb; try { URL url = new URL(address); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); sb = new StringBuffer(); int count = 0; String line; while ((line = br.readLine()) != null && count++ < maxLines) sb.append(line + "\n"); in.close(); } catch (IOException e) { sb = null; } return sb != null ? new String(sb) : null; }
private void readFromObjectInput(String filename) { try { URL url = new URL(getCodeBase(), filename); InputStream stream = url.openStream(); ObjectInput input = new ObjectInputStream(stream); fDrawing.release(); fDrawing = (Drawing) input.readObject(); view().setDrawing(fDrawing); } catch (IOException e) { initDrawing(); showStatus("Error: " + e); } catch (ClassNotFoundException e) { initDrawing(); showStatus("Class not found: " + e); } }
/** Create a FILE object to read from the specified URL. */ public static FILE open(URL url) { try { InputStream urlInputStream = url.openStream(); // urlConnection.getInputStream(); // System.out.println("open(URL) urlInputStream " + urlInputStream); return new FILE(urlInputStream); } catch (Exception e) { if (debug) { System.out.println("open(URL) exception " + e); } setException(e); return null; } }
/** * Reads GIF file from specified file/URL source (URL assumed if name contains ":/" or "file:") * * @param name String containing source * @return read status code (0 = no errors) */ public int read(String name) { status = STATUS_OK; try { name = name.trim().toLowerCase(); if ((name.indexOf("file:") >= 0) || (name.indexOf(":/") > 0)) { URL url = new URL(name); in = new BufferedInputStream(url.openStream()); } else { in = new BufferedInputStream(new FileInputStream(name)); } status = read(in); } catch (IOException e) { status = STATUS_OPEN_ERROR; } return status; }
public EmailContent(String fileName) throws URISyntaxException, IOException { URL entry = GitActivator.getDefault().getBundleContext().getBundle().getEntry(fileName); if (entry == null) throw new IOException("File not found: " + fileName); BufferedReader reader = new BufferedReader(new InputStreamReader(entry.openStream())); String line = null; try { title = reader.readLine(); StringBuilder stringBuilder = new StringBuilder(); String ls = System.getProperty("line.separator"); while ((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append(ls); } content = stringBuilder.toString(); } finally { reader.close(); } }
public static void parse(String fileNameOrURL, RDFParser parser, Model model) throws IOException, SAXException, MalformedURLException, ModelException { URL url = new URL(normalizeURI(fileNameOrURL)); // maybe this model is loaded as schema... // Model model = factory.registry().get(url.toString()); // if(model != null) // return model; // Prepare input source model.setSourceURI(url.toString()); InputStream in = url.openStream(); InputSource source = new InputSource(in); source.setSystemId(url.toString()); parser.parse(source, new ModelConsumer(model)); in.close(); }
public static void download(String index, String fname) throws Exception { int avd = Integer.parseInt(index.split("-")[0]); String type; URL ylink_download; int dindex = Integer.parseInt(index.split("-")[1]); if (avd == 3) { ylink_download = new URL((av_set.get(dindex - 1)).split("\n")[0]); type = (av_set.get(dindex - 1)).split("\n")[1]; } else if (avd == 2) { ylink_download = new URL((video_set.get(dindex - 1)).split("\n")[0]); type = (video_set.get(dindex - 1)).split("\n")[1]; } else if (avd == 1) { ylink_download = new URL((audio_set.get(dindex - 1)).split("\n")[0]); type = (audio_set.get(dindex - 1)).split("\n")[1]; } else { System.out.println("Enter valid input"); return; } InputStream is = ylink_download.openStream(); URLConnection con = (URLConnection) ylink_download.openConnection(); double dsize = con.getContentLength() / 1048576; System.out.println("\nDownloading : " + dsize + " MB"); if (con != null) { String wd = System.getProperty("user.dir"); String fo = fname + "." + type.split("%2F")[1]; File f = new File(wd, fo); FileOutputStream fos = new FileOutputStream(f); byte[] buffer = new byte[1024]; progressbar t1 = new progressbar(dsize * 1048576, fo); t1.start(); int len1 = 0; if (is != null) { while ((len1 = is.read(buffer)) > 0) { fos.write(buffer, 0, len1); } } if (fos != null) { fos.close(); } } System.out.println("Download Complete"); }
String[] openUrlAsList(String address) { Vector v = new Vector(); try { URL url = new URL(address); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while (true) { line = br.readLine(); if (line == null) break; if (!line.equals("")) v.addElement(line); } br.close(); } catch (Exception e) { } String[] lines = new String[v.size()]; v.copyInto((String[]) lines); return lines; }
public static byte[] loadUrlIntoByteArray(String urlString) throws IOException { URL url = new URL(urlString); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); InputStream inputStream = null; try { inputStream = url.openStream(); byte[] byteChunk = new byte[8192]; int n; while ((n = inputStream.read(byteChunk)) > 0) { outputStream.write(byteChunk, 0, n); } } finally { if (inputStream != null) { inputStream.close(); } } return outputStream.toByteArray(); }
/** * Enables to get the name of an object in the spoken language thanks to the jar file * * @param jarName the file that contains the object classes * @return the object name in the spoken language */ private String getLangName(File jarName) { String name = null; try { URL url = jarName.toURI().toURL(); JarInputStream jarFile = new JarInputStream(url.openStream()); JarEntry jarEntry = jarFile.getNextJarEntry(); while (jarEntry != null) { if (!jarEntry.isDirectory() && jarEntry.getName().contains(Configuration.instance().getLanguage())) { int lang_index = jarEntry.getName().lastIndexOf(Configuration.instance().getLanguage()); name = jarEntry.getName().substring(lang_index + 3, jarEntry.getName().length() - 6); } jarEntry = jarFile.getNextJarEntry(); } } catch (Exception e) { LOG.error("Error getLangName " + jarName + " " + e); } return name; }
public static void loadPermissions(URL url) throws IOException, PermissionParseException { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; Pattern ignore = Pattern.compile("^\\s*(//.*)?$"); Pattern valid = Pattern.compile("^\\s*permission\\s+(\\S+)" + "(\\s+\"([^\"]*)\"(,\\s+\"([^\"]*)\")?)?;$"); Set<Permission> perms = new HashSet<Permission>(); while ((line = in.readLine()) != null) { if (ignore.matcher(line).matches()) { continue; } Matcher matcher = valid.matcher(line); if (!matcher.matches()) { throw new PermissionParseException("invalid syntax: " + line); } int nGroups = matcher.groupCount(); String type = matcher.group(1); String name = expand(nGroups >= 3 ? matcher.group(3) : null); String actions = expand(nGroups >= 5 ? matcher.group(5) : null); try { Permission perm = getPermission(type, name, actions); perms.add(perm); } catch (Throwable e) { String message = String.format( "could not instantiate permission: " + "type=%s name=%s actions=", type, name, actions); throw new PermissionParseException(message, e); } } in.close(); permSet.addAll(perms); }
public void downloadFile(String url, String savePath, String fileName) { try { URL theURL = new URL(url); InputStream input = theURL.openStream(); OutputStream output = new FileOutputStream(new File(savePath, fileName)); try { byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { output.write(buffer, 0, bytesRead); } } catch (Exception e) { debug(e.toString()); } finally { output.close(); } } catch (Exception e) { debug(e.toString()); } }
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); int i, j; String amount = req.getParameter("amount"); String from = req.getParameter("from"); String to = req.getParameter("to"); String ch = req.getParameter("choice"); String answer, answer1, answer2, answer3; if ("INFO".equals(ch)) { Redirect_info newurl = (Redirect_info) getServletContext().getAttribute("redirect"); res.sendRedirect(newurl.getUrl()); } else { out.println("<html>"); out.println("<title>Currency Converter</title>"); String addr = "http://www.google.com/ig/calculator?hl=en&q=" + amount + from + "=?" + to; URL convert = new URL(addr); BufferedReader in = new BufferedReader(new InputStreamReader(convert.openStream())); answer = in.readLine(); answer = new String(answer.getBytes("ISO-8859-1"), "ISO-8859-7"); from = new String(from.getBytes("ISO-8859-1"), "ISO-8859-7"); to = new String(to.getBytes("ISO-8859-1"), "ISO-8859-7"); amount = new String(amount.getBytes("ISO-8859-1"), "ISO-8859-7"); in.close(); i = answer.indexOf('"'); answer = answer.substring(i + 1); i = answer.indexOf('"'); answer = answer.substring(i + 1); i = answer.indexOf('"'); answer = answer.substring(i + 1); i = answer.indexOf('"'); answer = answer.substring(0, i); out.println("<p ALIGN=CENTER>" + amount + " " + from + " == " + answer + "(" + to + ")</p>"); out.println("</body>"); out.println("</html>"); } }
/** * (Re)Compiles the given source. This method starts the compilation of a given source, if the * source has changed since the class was created. For this isSourceNewer is called. * * @param source the source pointer for the compilation * @param className the name of the class to be generated * @param oldClass a possible former class * @return the old class if the source wasn't new enough, the new class else * @throws CompilationFailedException if the compilation failed * @throws IOException if the source is not readable * @see #isSourceNewer(URL, Class) */ protected Class recompile(URL source, String className, Class oldClass) throws CompilationFailedException, IOException { if (source != null) { // found a source, compile it if newer if ((oldClass != null && isSourceNewer(source, oldClass)) || (oldClass == null)) { synchronized (sourceCache) { String name = source.toExternalForm(); sourceCache.remove(name); if (isFile(source)) { try { return parseClass( new GroovyCodeSource(new File(source.toURI()), config.getSourceEncoding())); } catch (URISyntaxException e) { // do nothing and fall back to the other version } } return parseClass(source.openStream(), name); } } } return oldClass; }