下面列出了java.net.URL#openStream ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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("=======================================");
}
}
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);
}
}
/**
* 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;
}
}
/**
* 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);
}
}
/**
* 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;
}
}
@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;
}
@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);
});
}
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;
}
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();
}
}
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);
}
}
public RandomAccessFileOrArray(URL url) throws IOException {
InputStream is = url.openStream();
try {
this.arrayIn = InputStreamToArray(is);
}
finally {
try {is.close();}catch(IOException ioe){}
}
}
/**
* 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();
}
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;
}
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;
}
/**
* 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;
}
}
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);
}
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());
}
@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);
}
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);
}
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);
}
}