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

The following examples show how to use java.net.URL#openStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JdbcMetricsTest.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the DB with the apiman gateway DDL.
 * @param connection
 */
private static void initDB(Connection connection) throws Exception {
    ClassLoader cl = JdbcMetricsTest.class.getClassLoader();
    URL resource = cl.getResource("ddls/apiman-gateway_h2.ddl");
    try (InputStream is = resource.openStream()) {
        System.out.println("=======================================");
        System.out.println("Initializing database.");
        DdlParser ddlParser = new DdlParser();
        List<String> statements = ddlParser.parse(is);
        for (String sql : statements){
            System.out.println(sql);
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.execute();
        }
        System.out.println("=======================================");
    }
}
 
Example 2
Source File: Util.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static StringBuffer load(URL url) {
  try {
    StringBuffer sb = new StringBuffer();
    {
      byte[] buf = new byte[1024];
      int n;
      InputStream is = url.openStream();
      while(-1 != (n = is.read(buf))) {
        sb.append(new String(buf));
      }
    }
    return sb;
  } catch (Exception e) {
    throw new RuntimeException("Failed to load " + url, e);
  }
}
 
Example 3
Source File: DownloadZipAndUnpack.java    From native-samples with Apache License 2.0 6 votes vote down vote up
@TaskAction
public void doDownloadZipAndUnpack() throws IOException {
    URL downloadUrl = new URL(url.get());
    getLogger().warn("Downloading " + downloadUrl);
    final File zipDestination = new File(getTemporaryDir(), "zip.zip");
    zipDestination.delete();
    try (InputStream inStream = downloadUrl.openStream()) {
        Files.copy(inStream, zipDestination.toPath());
    }
    getLogger().warn("Downloaded to " + zipDestination.getAbsolutePath());

    final File unzipDestination = outputDirectory.get().getAsFile();
    getProject().copy(copySpec -> {
        copySpec.from(getProject().zipTree(zipDestination));
        copySpec.into(unzipDestination);
    });
}
 
Example 4
Source File: Configuration.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/** 
 * Get an input stream attached to the configuration resource with the
 * given <code>name</code>.
 * 
 * @param name configuration resource name.
 * @return an input stream attached to the resource.
 */
public InputStream getConfResourceAsInputStream(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 url.openStream();
  } catch (Exception e) {
    return null;
  }
}
 
Example 5
Source File: OpenApiParser.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the resource found at the given URL. This method accepts resources
 * either in JSON or YAML format. It will parse the input and, assuming it is
 * valid, return an instance of {@link OpenAPI}.
 * 
 * @param url URL to OpenAPI document
 * @return OpenAPIImpl parsed from URL
 * @throws IOException URL parameter is not found
 */
public static final OpenAPI parse(URL url) throws IOException {
    try {
        String fname = url.getFile();
        if (fname == null) {
            throw IoMessages.msg.noFileName(url.toURI().toString());
        }
        int lidx = fname.lastIndexOf('.');
        if (lidx == -1 || lidx >= fname.length()) {
            throw IoMessages.msg.invalidFileName(url.toURI().toString());
        }
        String ext = fname.substring(lidx + 1);
        boolean isJson = ext.equalsIgnoreCase("json");
        boolean isYaml = ext.equalsIgnoreCase("yaml") || ext.equalsIgnoreCase("yml");
        if (!isJson && !isYaml) {
            throw IoMessages.msg.invalidFileExtension(url.toURI().toString());
        }

        try (InputStream stream = url.openStream()) {
            return parse(stream, isJson ? Format.JSON : Format.YAML);
        }
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}
 
Example 6
Source File: MainActivity.java    From paystack-android with Apache License 2.0 6 votes vote down vote up
@Override
protected String doInBackground(String... reference) {
    try {
        this.reference = reference[0];
        URL url = new URL(backend_url + "/verify/" + this.reference);
        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                        url.openStream()));

        String inputLine;
        inputLine = in.readLine();
        in.close();
        return inputLine;
    } catch (Exception e) {
        error = e.getClass().getSimpleName() + ": " + e.getMessage();
    }
    return null;
}
 
Example 7
Source File: Configuration.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * 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(), Charsets.UTF_8);
  } catch (Exception e) {
    return null;
  }
}
 
Example 8
Source File: HostApplication.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
public Bundle install(URL url) throws IOException, BundleException {
    System.out.println("install = " + url);
    InputStream is = url.openStream();
    try {
        Bundle b = install(url.toString(), is);
        b.start();
        return b;
    } finally {
        is.close();
    }
}
 
Example 9
Source File: NettyServerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetWsdl() throws Exception {
    URL url = new URL("http://localhost:" + PORT + "/SoapContext/SoapPort?wsdl");

    InputStream in = url.openStream();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copyAndCloseInput(in, bos);
    String result = bos.toString();
    assertTrue("Expect the SOAPService", result.indexOf("<service name=\"SOAPService\">") > 0);
}
 
Example 10
Source File: Web.java    From outbackcdx with Apache License 2.0 5 votes vote down vote up
static Handler serve(String file) {
    URL url = Web.class.getResource(file);
    if (url == null) {
        throw new IllegalArgumentException("No such resource: " + file);
    }
    return req -> new Response(OK, guessType(file), url.openStream());
}
 
Example 11
Source File: AgentManagementUtil.java    From Insights with Apache License 2.0 5 votes vote down vote up
public  JsonObject getAgentConfigfile(URL filePath, File targetDir) throws IOException  {
	if (!targetDir.exists()) {
		targetDir.mkdirs();
	}
	File zip = File.createTempFile("agent_", ".zip", targetDir);
	try(InputStream in = new BufferedInputStream(filePath.openStream(), 1024);
			OutputStream out = new BufferedOutputStream(new FileOutputStream(zip))){
		copyInputStream(in, out);
	}
	return getAgentConfiguration(zip, targetDir);
}
 
Example 12
Source File: ObjectUtilities.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the inputstream for the resource specified by the
 * <strong>absolute</strong> name.
 *
 * @param name the name of the resource
 * @param context the source class
 * @return the url of the resource or null, if not found.
 */
public static InputStream getResourceAsStream(final String name,
                                              final Class context) {
    final URL url = getResource(name, context);
    if (url == null) {
        return null;
    }

    try {
        return url.openStream();
    }
    catch (IOException e) {
        return null;
    }
}
 
Example 13
Source File: EditablePropertiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private EditableProperties loadTestProperties() throws IOException {
    URL u = EditablePropertiesTest.class.getResource("data/test.properties");
    EditableProperties ep = new EditableProperties(false);
    InputStream is = u.openStream();
    try {
        ep.load(is);
    } finally {
        is.close();
    }
    return ep;
}
 
Example 14
Source File: Main.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private static File extractFromJar(String resource, String fileName, String suffix)
		throws IOException {
	final URL res = Main.class.getResource(resource);

	// put this jar in a file system so that we can load jars from there
	final File tmp;
	try {
		tmp = File.createTempFile(fileName, suffix);
	} catch (final IOException e) {
		final String tmpdir = System.getProperty("java.io.tmpdir");
		throw new IllegalStateException(
				"JavaMelody has failed to create a temporary file in " + tmpdir, e);
	}
	final InputStream is = res.openStream();
	try {
		final OutputStream os = new FileOutputStream(tmp);
		try {
			copyStream(is, os);
		} finally {
			os.close();
		}
	} finally {
		is.close();
	}
	tmp.deleteOnExit();
	return tmp;
}
 
Example 15
Source File: CamelNewBeanWizard.java    From tesb-studio-se with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new NewProjectWizard.
 *
 * @param author Project author.
 * @param server
 * @param password
 */
public CamelNewBeanWizard(IPath path) {
    super();
    this.path = path;

    this.property = PropertiesFactory.eINSTANCE.createProperty();
    this.property
            .setAuthor(((RepositoryContext) CorePlugin.getContext().getProperty(Context.REPOSITORY_CONTEXT_KEY)).getUser());
    this.property.setVersion(VersionUtils.DEFAULT_VERSION);
    this.property.setStatusCode(""); //$NON-NLS-1$

    beanItem = CamelPropertiesFactory.eINSTANCE.createBeanItem();

    beanItem.setProperty(property);

    ILibrariesService service = CorePlugin.getDefault().getLibrariesService();
    URL url = service.getBeanTemplate();
    ByteArray byteArray = PropertiesFactory.eINSTANCE.createByteArray();
    InputStream stream = null;
    try {
        stream = url.openStream();
        byte[] innerContent = new byte[stream.available()];
        stream.read(innerContent);
        stream.close();
        byteArray.setInnerContent(innerContent);
    } catch (IOException e) {
        RuntimeExceptionHandler.process(e);
    }

    beanItem.setContent(byteArray);

    addDefaultModulesForBeans();
}
 
Example 16
Source File: RandomAccessFileOrArray.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
public RandomAccessFileOrArray(URL url) throws IOException {
    InputStream is = url.openStream();
    try {
        this.arrayIn = InputStreamToArray(is);
    }
    finally {
        try {is.close();}catch(IOException ioe){}
    }
}
 
Example 17
Source File: PropertyBundle.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void loadPropertiesFromURL(URL url) {

        if (url == null) {
            return;
        }
        InputStream in = null;
        try {
            in = url.openStream();
            properties.load(in);
        } catch (IOException e) {
            AnalysisContext.logError("Unable to load properties from " + url, e);
        } finally {
            IO.close(in);
        }
    }
 
Example 18
Source File: WaveFloatFileReader.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
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 19
Source File: ServiceLiveTest.java    From tutorials with MIT License 4 votes vote down vote up
private Student getStudent(int courseOrder, int studentOrder) throws IOException {
    final URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder);
    final InputStream input = url.openStream();
    return JAXB.unmarshal(new InputStreamReader(input), Student.class);
}
 
Example 20
Source File: PluginBundleManager.java    From BIMserver with GNU Affero General Public License v3.0 4 votes vote down vote up
public PluginBundle loadPluginsFromJar(PluginBundleVersionIdentifier pluginBundleVersionIdentifier, Path file, SPluginBundle sPluginBundle, SPluginBundleVersion pluginBundleVersion, ClassLoader parentClassLoader)
		throws PluginException {
	PluginBundleIdentifier pluginBundleIdentifier = pluginBundleVersionIdentifier.getPluginBundleIdentifier();
	if (pluginBundleIdentifierToPluginBundle.containsKey(pluginBundleIdentifier)) {
		throw new PluginException("Plugin " + pluginBundleIdentifier.getHumanReadable() + " already loaded (version " + pluginBundleIdentifierToPluginBundle.get(pluginBundleIdentifier).getPluginBundleVersion().getVersion() + ")");
	}
	LOGGER.debug("Loading plugins from " + file.toString());
	if (!Files.exists(file)) {
		throw new PluginException("Not a file: " + file.toString());
	}
	FileJarClassLoader jarClassLoader = null;
	try {
		jarClassLoader = new FileJarClassLoader(pluginManager, parentClassLoader, file);
		jarClassLoaders.add(jarClassLoader);
		final JarClassLoader finalLoader = jarClassLoader;
		URL resource = jarClassLoader.findResource("plugin/plugin.xml");
		if (resource == null) {
			throw new PluginException("No plugin/plugin.xml found in " + file.getFileName().toString());
		}
		PluginDescriptor pluginDescriptor = null;
		try (InputStream pluginStream = resource.openStream()) {
			pluginDescriptor = pluginManager.getPluginDescriptor(pluginStream);
			if (pluginDescriptor == null) {
				jarClassLoader.close();
				throw new PluginException("No plugin descriptor could be created");
			}
		}
		LOGGER.debug(pluginDescriptor.toString());

		URI fileUri = file.toAbsolutePath().toUri();
		URI jarUri = new URI("jar:" + fileUri.toString());

		ResourceLoader resourceLoader = new ResourceLoader() {
			@Override
			public InputStream load(String name) {
				return finalLoader.getResourceAsStream(name);
			}
		};

		return loadPlugins(pluginBundleVersionIdentifier, resourceLoader, jarClassLoader, jarUri, file.toAbsolutePath().toString(), pluginDescriptor, PluginSourceType.JAR_FILE, new HashSet<org.bimserver.plugins.Dependency>(),
				sPluginBundle, pluginBundleVersion);
	} catch (Exception e) {
		if (jarClassLoader != null) {
			try {
				jarClassLoader.close();
			} catch (IOException e1) {
				LOGGER.error("", e1);
			}
		}
		throw new PluginException(e);
	}
}