Java Code Examples for java.net.URL.openStream()

The following are Jave code examples for showing how to use openStream() of the java.net.URL class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: neoscada   File: URLImageLabel.java   View Source Code Vote up 6 votes
private void processLoad ( final String stringUrl ) throws Exception
{
    final ImageLoader loader = new ImageLoader ();

    final URL url = new URL ( stringUrl );

    final ImageData[] data;
    try ( InputStream is = url.openStream () )
    {
        data = loader.load ( is );
    }

    logger.debug ( "Image loaded" );

    Display.getDefault ().asyncExec ( new Runnable () {
        @Override
        public void run ()
        {
            showImage ( stringUrl, data );
        }
    } );
}
 
Example 2
Project: Adblocker-for-Android   File: MainActivity.java   View Source Code Vote up 6 votes
public static String getURL(String surl) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    System.setProperty("java.net.preferIPv4Addresses", "true");
    System.setProperty("java.net.preferIPv6Addresses", "false");
    System.setProperty("validated.ipv6", "false");
    String fullString = "";
    try {

        URL url = new URL(surl);
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            fullString += line;
        }
        reader.close();
    } catch (Exception ex) {
        //showDialog("Verbindungsfehler.",parent);
    }

    return fullString;
}
 
Example 3
Project: incubator-netbeans   File: SetupUtil.java   View Source Code Vote up 6 votes
public MainFS() {
    ALL.addLookupListener(this);
    
    List<URL> layerUrls = new ArrayList<URL>();
    ClassLoader l = Thread.currentThread().getContextClassLoader();
    try {
        for (URL manifest : NbCollections.iterable(l.getResources("META-INF/MANIFEST.MF"))) { // NOI18N
            InputStream is = manifest.openStream();
            try {
                Manifest mani = new Manifest(is);
                String layerLoc = mani.getMainAttributes().getValue("OpenIDE-Module-Layer"); // NOI18N
                if (layerLoc != null) {
                    URL layer = l.getResource(layerLoc);
                    if (layer != null) {
                        layerUrls.add(layer);
                    }
                }
            } finally {
                is.close();
            }
        }
        layers.setXmlUrls(layerUrls.toArray(new URL[layerUrls.size()]));
    } catch (Exception x) {
    }
    resultChanged(null); // run after add listener - see PN1 in #26338
}
 
Example 4
Project: incubator-netbeans   File: ProxyURLStreamHandlerFactoryTest.java   View Source Code Vote up 6 votes
public void testHandleSpaceInPathAsProducedByEclipse() throws Exception {
    File d = new File(getWorkDir(), "space in path");
    d.mkdirs();
    File f = new File(d, "x.jar");
    JarOutputStream os = new JarOutputStream(new FileOutputStream(f));
    os.putNextEntry(new JarEntry("test.txt"));
    os.write(10);
    os.close();
    
    URL u = new URL("jar:" + f.toURL() + "!/test.txt");
    DataInputStream is = new DataInputStream(u.openStream());
    byte[] arr = new byte[100];
    is.readFully(arr, 0, 1);
    assertEquals("One byte", 10, arr[0]);
    is.close();
}
 
Example 5
Project: spark_deep   File: Configuration.java   View Source Code Vote up 6 votes
/** 
 * Get a {@link Reader} attached to the configuration resource with the
 * given <code>name</code>.
 * 
 * @param name configuration resource name.
 * @return a reader attached to the resource.
 */
public Reader getConfResourceAsReader(String name) {
  try {
    URL url= getResource(name);

    if (url == null) {
      LOG.info(name + " not found");
      return null;
    } else {
      LOG.info("found resource " + name + " at " + url);
    }

    return new InputStreamReader(url.openStream());
  } catch (Exception e) {
    return null;
  }
}
 
Example 6
Project: lazycat   File: JasperLoader.java   View Source Code Vote up 6 votes
/**
 * Delegate to parent
 * 
 * @see java.lang.ClassLoader#getResourceAsStream(java.lang.String)
 */
@Override
public InputStream getResourceAsStream(String name) {
	InputStream is = parent.getResourceAsStream(name);
	if (is == null) {
		URL url = findResource(name);
		if (url != null) {
			try {
				is = url.openStream();
			} catch (IOException e) {
				// Ignore
			}
		}
	}
	return is;
}
 
Example 7
Project: jdk8u-jdk   File: ClassLoaderUtils.java   View Source Code Vote up 5 votes
/**
 * This is a convenience method to load a resource as a stream. <p/> The
 * algorithm used to find the resource is given in getResource()
 *
 * @param resourceName The name of the resource to load
 * @param callingClass The Class object of the calling object
 */
static InputStream getResourceAsStream(String resourceName, Class<?> callingClass) {
    URL url = getResource(resourceName, callingClass);

    try {
        return (url != null) ? url.openStream() : null;
    } catch (IOException e) {
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, e.getMessage(), e);
        }
        return null;
    }
}
 
Example 8
Project: monarch   File: ClassPathLoaderIntegrationTest.java   View Source Code Vote up 5 votes
/**
 * Verifies that <tt>getResource</tt> works with custom loader from {@link ClassPathLoader}.
 */
@Test
public void testGetResourceWithCustomLoader() throws Exception {
  System.out.println("\nStarting ClassPathLoaderTest#testGetResourceWithCustomLoader");

  ClassPathLoader dcl = ClassPathLoader.createWithDefaults(false);
  dcl = dcl.addOrReplace(new GeneratingClassLoader());

  String resourceToGet = "com/nowhere/testGetResourceWithCustomLoader.rsc";
  URL url = dcl.getResource(resourceToGet);
  assertNotNull(url);

  InputStream is = url != null ? url.openStream() : null;
  assertNotNull(is);

  int totalBytesRead = 0;
  byte[] input = new byte[128];

  BufferedInputStream bis = new BufferedInputStream(is);
  for (int bytesRead = bis.read(input); bytesRead > -1;) {
    totalBytesRead += bytesRead;
    bytesRead = bis.read(input);
  }
  bis.close();

  assertEquals(TEMP_FILE_BYTES_COUNT, totalBytesRead);
}
 
Example 9
Project: Bobsim-Server   File: School.java   View Source Code Vote up 5 votes
private String getContentFromUrl(URL url, String readAfter, String readBefore) throws SchoolException {

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

            StringBuffer buffer = new StringBuffer();
            String inputLine;

            boolean reading = false;

            while ((inputLine = reader.readLine()) != null) {
                if (reading) {
                    if (inputLine.contains(readBefore))
                        break;
                    buffer.append(inputLine);
                } else {
                    if (inputLine.contains(readAfter))
                        reading = true;
                }
            }
            reader.close();
            return buffer.toString();

        } catch (IOException e) {
            throw new SchoolException("교육청 서버에 접속하지 못하였습니다.");
        }
    }
 
Example 10
Project: waggle-dance   File: ManifestAttributes.java   View Source Code Vote up 5 votes
protected InputStream openManifestStream(ProtectionDomain protectionDomain)
  throws MalformedURLException, IOException {
  URL manifestUrl = null;

  // try to pick the Manifest in the source JAR
  manifestUrl = selectManifestFromJars(protectionDomain);
  LOG.debug("Manifest location in JARs is {}", manifestUrl);

  if (manifestUrl == null) {
    // if we can't locate the correct JAR then try get to manifest file via a file path (e.g. in Hadoop case where
    // jar is unpacked to disk)
    manifestUrl = selectFromFileLocation(protectionDomain);
    LOG.debug("Manifest location on disk is {}", manifestUrl);
  }

  if (manifestUrl == null) {
    // file not found, get via class loader resource (e.g. from inside jar)
    manifestUrl = protectionDomain.getClassLoader().getResource(META_INF_MANIFEST_MF);
    LOG.debug("Manifest location via getResource() is {}", manifestUrl);
  }

  if (manifestUrl == null) {
    LOG.warn("Manifest not found!");
    return null;
  }

  return manifestUrl.openStream();
}
 
Example 11
Project: incubator-netbeans   File: ArchiveURLMapperTest.java   View Source Code Vote up 5 votes
private void doFunnyZipEntryNames(String file) throws Exception {
    File docx = new File(getWorkDir(), "ms-docx.jar");
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(docx));
    ZipEntry entry = new ZipEntry(file);
    jos.putNextEntry(entry);
    jos.write("content".getBytes());
    jos.close();
    
    FileObject docxFO = URLMapper.findFileObject(Utilities.toURI(docx).toURL());
    assertNotNull(docxFO);
    assertTrue(FileUtil.isArchiveFile(docxFO));
    
    FileObject docxRoot = FileUtil.getArchiveRoot(docxFO);
    assertNotNull("Root found", docxRoot);
    FileObject content = docxRoot.getFileObject(file);
    assertNotNull("content.xml found", content);
    
    assertEquals("Has right bytes", "content", content.asText());
    
    CharSequence log = Log.enable("", Level.WARNING);
    URL u = URLMapper.findURL(content, URLMapper.EXTERNAL);
    InputStream is = u.openStream();
    byte[] arr = new byte[30];
    int len = is.read(arr);
    assertEquals("Len is content", "content".length(), len);
    assertEquals("OK", "content", new String(arr, 0, len));
    
    assertEquals("No warnings:\n" + log, 0, log.length());
    assertEquals(u.toString(), content, URLMapper.findFileObject(u));
}
 
Example 12
Project: OpenJSharp   File: ClassLoaderUtils.java   View Source Code Vote up 5 votes
/**
 * This is a convenience method to load a resource as a stream. <p/> The
 * algorithm used to find the resource is given in getResource()
 *
 * @param resourceName The name of the resource to load
 * @param callingClass The Class object of the calling object
 */
static InputStream getResourceAsStream(String resourceName, Class<?> callingClass) {
    URL url = getResource(resourceName, callingClass);

    try {
        return (url != null) ? url.openStream() : null;
    } catch (IOException e) {
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, e.getMessage(), e);
        }
        return null;
    }
}
 
Example 13
Project: tuxguitar   File: WaveExtensibleFileReader.java   View Source Code Vote up 5 votes
public AudioFileFormat getAudioFileFormat(URL url)
        throws UnsupportedAudioFileException, IOException {
    InputStream stream = url.openStream();
    AudioFileFormat format;
    try {
        format = getAudioFileFormat(new BufferedInputStream(stream));
    } finally {
        stream.close();
    }
    return format;
}
 
Example 14
Project: incubator-netbeans   File: Pre90403Phase1CompatibilityTest.java   View Source Code Vote up 5 votes
private static String fromFile(String name) {
    URL url = Pre90403Phase1CompatibilityTest.class.getResource(name);
    if (url == null) {
        return "";
    }
    
    try {
        InputStream is = url.openStream();
        try {
            StringBuilder sb = new StringBuilder();
            byte [] buffer = new byte [1024];
            int size;

            while(0 < (size = is.read(buffer, 0, buffer.length))) {
                String s = new String(buffer, 0, size);
                sb.append(s);
            }

            return sb.toString();
        } finally {
            is.close();
        }
    } catch (IOException e) {
        fail("Can't read file: '" + name + "'");
        return null; // can't be reached
    }
}
 
Example 15
Project: sumo   File: Binding.java   View Source Code Vote up 5 votes
/**
 * Loads a resource from the specified URL. Note that this method does obviously not recognize the <code>useClassLoader</code> flag.
 * @param url of the resource to load
 * @return returns the input stream to the resource
 * @throws MalformedURLException, IOException thrown in case that the resource can not be loaded (can not be found)
 */
public InputStream getResource(URL url) throws MalformedURLException, IOException
{
	InputStream is = url.openStream();
	if (is == null) throw new MalformedURLException("A problem occured while loading the resource (url.openStream() returned null)");
	return is;
}
 
Example 16
Project: directory-ldap-api   File: JarLdifSchemaLoader.java   View Source Code Vote up 5 votes
/**
 * {@inheritDoc}
 */
@Override
public List<Entry> loadSyntaxCheckers( Schema... schemas ) throws LdapException, IOException
{
    List<Entry> syntaxCheckerList = new ArrayList<>();

    if ( schemas == null )
    {
        return syntaxCheckerList;
    }

    for ( Schema schema : schemas )
    {
        String start = getSchemaDirectoryString( schema )
            + SchemaConstants.SYNTAX_CHECKERS_PATH + "/" + "m-oid=";
        String end = "." + LDIF_EXT;

        for ( String resourcePath : RESOURCE_MAP.keySet() )
        {
            if ( resourcePath.startsWith( start ) && resourcePath.endsWith( end ) )
            {
                URL resource = getResource( resourcePath, "syntaxChecker LDIF file" );
                LdifReader reader = new LdifReader( resource.openStream() );
                LdifEntry entry = reader.next();
                reader.close();

                syntaxCheckerList.add( entry.getEntry() );
            }
        }
    }

    return syntaxCheckerList;
}
 
Example 17
Project: openjdk-jdk10   File: ImageIO.java   View Source Code Vote up 5 votes
/**
 * Returns a {@code BufferedImage} as the result of decoding
 * a supplied {@code URL} with an {@code ImageReader}
 * chosen automatically from among those currently registered.  An
 * {@code InputStream} is obtained from the {@code URL},
 * which is wrapped in an {@code ImageInputStream}.  If no
 * registered {@code ImageReader} claims to be able to read
 * the resulting stream, {@code null} is returned.
 *
 * <p> The current cache settings from {@code getUseCache} and
 * {@code getCacheDirectory} will be used to control caching in the
 * {@code ImageInputStream} that is created.
 *
 * <p> This method does not attempt to locate
 * {@code ImageReader}s that can read directly from a
 * {@code URL}; that may be accomplished using
 * {@code IIORegistry} and {@code ImageReaderSpi}.
 *
 * @param input a {@code URL} to read from.
 *
 * @return a {@code BufferedImage} containing the decoded
 * contents of the input, or {@code null}.
 *
 * @exception IllegalArgumentException if {@code input} is
 * {@code null}.
 * @exception IOException if an error occurs during reading or when not
 * able to create required ImageInputStream.
 */
public static BufferedImage read(URL input) throws IOException {
    if (input == null) {
        throw new IllegalArgumentException("input == null!");
    }

    InputStream istream = null;
    try {
        istream = input.openStream();
    } catch (IOException e) {
        throw new IIOException("Can't get input stream from URL!", e);
    }
    ImageInputStream stream = createImageInputStream(istream);
    if (stream == null) {
        /* close the istream when stream is null so that if user has
         * given filepath as URL he can delete it, otherwise stream will
         * be open to that file and he will not be able to delete it.
         */
        istream.close();
        throw new IIOException("Can't create an ImageInputStream!");
    }
    BufferedImage bi;
    try {
        bi = read(stream);
        if (bi == null) {
            stream.close();
        }
    } finally {
        istream.close();
    }
    return bi;
}
 
Example 18
Project: incubator-servicecomb-java-chassis   File: YAMLConfigLoader.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
@Override
protected Map<String, Object> loadData(URL url) throws IOException {
  Yaml yaml = new Yaml();

  try (InputStream inputStream = url.openStream()) {
    return yaml.loadAs(inputStream, Map.class);
  }
}
 
Example 19
Project: Hi-Framework   File: Controller.java   View Source Code Vote up 4 votes
private void doNotIgnoreView(RequestContext requestContext, URL viewResource){

        try {

            InputStream viewInputStream = viewResource.openStream();
            String viewContent = Helper.readLines(viewInputStream, null);
            requestContext.getData().put("view_content",viewContent);


        }catch (Exception ex){

            _log.error(String.format("Failed to read the View HTML Resource : %s",viewResource.getPath()),ex);

        }

    }
 
Example 20
Project: live_master   File: JSONSource.java   View Source Code Vote up 4 votes
public JSONSource(URL url) throws JSONException, IOException{
	this(url.openStream());
}