Java Code Examples for java.net.URI
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project activemq-apollo, under directory /apollo-broker/src/main/scala/org/apache/activemq/apollo/broker/transport/.
Source file: TcpTransportFactory.java

public TransportServer bind(String location) throws Exception { URI uri=new URI(location); Map<String,String> options=new HashMap<String,String>(URISupport.parseParamters(uri)); TcpTransportServer server=createTcpTransportServer(uri,options); if (server == null) return null; Map<String,String> copy=new HashMap<String,String>(options); IntrospectionSupport.setProperties(server,new HashMap(options)); return server; }
Example 2
From project activemq-apollo, under directory /apollo-broker/src/main/scala/org/apache/activemq/apollo/broker/transport/.
Source file: TcpTransportFactory.java

public Transport connect(String location) throws Exception { URI uri=new URI(location); TcpTransport transport=createTransport(uri); if (transport == null) return null; Map<String,String> options=new HashMap<String,String>(URISupport.parseParamters(uri)); URI localLocation=getLocalLocation(uri); configure(transport,options); verify(transport,options); transport.connecting(uri,localLocation); return transport; }
Example 3
From project adbcj, under directory /jdbc/src/main/java/org/adbcj/jdbc/.
Source file: JdbcConnectionManagerFactory.java

public ConnectionManager createConnectionManager(String url,String username,String password,Properties properties) throws DbException { try { URI uri=new URI(url); uri=new URI(uri.getSchemeSpecificPart()); String jdbcUrl=uri.toString(); return new JdbcConnectionManager(jdbcUrl,username,password,properties); } catch ( URISyntaxException e) { throw new DbException(e); } }
Example 4
From project aether-core, under directory /aether-util/src/test/java/org/eclipse/aether/util/repository/layout/.
Source file: MavenDefaultLayoutTest.java

@Test public void testArtifactPath(){ MavenDefaultLayout layout=new MavenDefaultLayout(); URI uri=layout.getPath(new DefaultArtifact("g.i.d","a-i.d","cls","ext","1.0")); assertEquals("g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext",uri.getPath()); uri=layout.getPath(new DefaultArtifact("g.i.d","aid","","ext","1.0")); assertEquals("g/i/d/aid/1.0/aid-1.0.ext",uri.getPath()); uri=layout.getPath(new DefaultArtifact("g.i.d","aid","","","1.0")); assertEquals("g/i/d/aid/1.0/aid-1.0",uri.getPath()); }
Example 5
From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/util/http/.
Source file: HttpBuilder.java

private <T>HttpResult<T> doGet(Type target){ try { URI path=createPath(address,query()); HttpGet get=new HttpGet(path); return doRequest(get,target); } catch ( URISyntaxException e) { Log.e(Constants.TAG,"Couldn't create path",e); return error(); } }
Example 6
From project airlift, under directory /discovery/src/main/java/io/airlift/discovery/client/.
Source file: HttpDiscoveryAnnouncementClient.java

@Override public CheckedFuture<Void,DiscoveryException> unannounce(){ URI uri=discoveryServiceURI.get(); if (uri == null) { return Futures.immediateFailedCheckedFuture(new DiscoveryException("No discovery servers are available")); } Request request=prepareDelete().setUri(URI.create(uri + "/v1/announcement/" + nodeInfo.getNodeId())).setHeader("User-Agent",nodeInfo.getNodeId()).build(); return httpClient.execute(request,new DiscoveryResponseHandler<Void>("Unannouncement")); }
Example 7
From project airlift, under directory /event/src/test/java/io/airlift/event/client/.
Source file: TestEventSubmissionFailedException.java

@Test public void testPicksFirstCause(){ URI uri1=URI.create("/y"); URI uri2=URI.create("/x"); RuntimeException cause1=new RuntimeException("y"); RuntimeException cause2=new RuntimeException("x"); Map<URI,RuntimeException> causes=ImmutableSortedMap.<URI,RuntimeException>orderedBy(Ordering.explicit(uri1,uri2)).put(uri1,cause1).put(uri2,cause2).build(); EventSubmissionFailedException e=new EventSubmissionFailedException("service","type",causes); assertSame(e.getCause(),cause1); }
Example 8
From project ajah, under directory /ajah-http/src/main/java/com/ajah/http/.
Source file: Http.java

private static String get(final String url) throws IOException, HttpException { URI uri; try { uri=URI.create(url); } catch ( final IllegalArgumentException e) { log.warning("Illegal URI [" + url + "] - "+ e.getMessage()); throw new BadRequestException(e); } return get(uri); }
Example 9
From project akubra, under directory /akubra-fs/src/test/java/org/akubraproject/fs/.
Source file: TestFSBlob.java

private static void assertMoved(Map<String,String> hints) throws Exception { FSBlob source=createFSBlob("file:source"); String dest="file:dest"; URI dest_uri=new URI(dest); long size=source.getSize(); source.moveTo(dest_uri,hints); assertFalse(source.exists()); assertTrue(getFSBlob(dest).exists()); assertEquals(size,getFSBlob(dest).getSize()); getFSBlob(dest).delete(); }
Example 10
From project akubra, under directory /akubra-mem/src/test/java/org/akubraproject/mem/.
Source file: MemStoreTest.java

/** * test expansion of data buffer */ @Test(groups={"blob","manipulatesBlobs"},dependsOnGroups={"init"}) public void testBufferExpansion() throws Exception { URI id=createId("blobBufferExpansion1"); createBlob(id,"Abandon all hope ye who enter here!",true); StringBuilder sb=new StringBuilder(4000); sb.append("A tale told by an idiot, full of sound and fury, signifying nothing. "); for (int idx=0; idx < 4; idx++) sb.append(sb.toString()); setBlob(id,sb.toString(),true); sb.append(sb.toString()); setBlob(id,sb.toString(),true); deleteBlob(id,sb.toString(),true); assertNoBlobs(getPrefixFor("blobBufferExpansion")); }
Example 11
From project accesointeligente, under directory /src/org/accesointeligente/server/solr/.
Source file: SolrClient.java

static public String execQuery(String query){ HttpClient client=new DefaultHttpClient(); HtmlCleaner cleaner=new HtmlCleaner(); HttpGet get; HttpResponse response; TagNode document; String jsonResponse=null; String httpQuery=""; URL url=null; URI uri=null; try { httpQuery=ApplicationProperties.getProperty("solr.server.address") + ApplicationProperties.getProperty("solr.core.path") + ApplicationProperties.getProperty("solr.query.path"); httpQuery+=query; url=new URL(httpQuery); uri=new URI(url.getProtocol(),url.getUserInfo(),url.getHost(),url.getPort(),url.getPath(),url.getQuery(),url.getRef()); url=uri.toURL(); httpQuery=url.toString(); get=new HttpGet(httpQuery); response=client.execute(get); document=cleaner.clean(new InputStreamReader(response.getEntity().getContent())); jsonResponse=document.getText().toString(); } catch ( Exception ex) { logger.error(httpQuery); logger.error(ex.getMessage(),ex); } return jsonResponse; }
Example 12
From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/config/.
Source file: JsonConfigLoader.java

/** * Load the configuration from a URL. This understands any URL that the JVM has a protocol handler for, and also "classpath:" URLs. * @return the configuration or null * @param urlString the URL for the config file * @throws URISyntaxException * @throws MalformedURLException */ public C loadConfigurationFromUrl(String urlString) throws ConfigurationException { InputStream is=null; try { URI uri=new URI(urlString); if (uri.getScheme().equals("classpath")) { String path=uri.getSchemeSpecificPart(); LOG.debug("Loading configuration from classpath resource '" + path + "'"); is=JsonConfigLoader.class.getClassLoader().getResourceAsStream(path); if (is == null) { throw new IllegalArgumentException("Cannot locate resource '" + path + "' on the classpath"); } } else { LOG.debug("Loading configuration from url '" + urlString + "'"); is=uri.toURL().openStream(); } return readConfiguration(is); } catch ( URISyntaxException ex) { throw new IllegalArgumentException("Invalid urlString '" + urlString + "'",ex); } catch ( MalformedURLException ex) { throw new IllegalArgumentException("Invalid urlString '" + urlString + "'",ex); } catch ( IOException ex) { throw new ConfigurationException("Cannot open URL input stream",ex); } finally { closeQuietly(is); } }
Example 13
From project action-core, under directory /src/main/java/com/ning/metrics/action/endpoint/.
Source file: HdfsBrowser.java

@POST @Produces(MediaType.TEXT_PLAIN) @Timed public Response upload(final InputStream body,@QueryParam("path") final String outputPath,@QueryParam("overwrite") @DefaultValue("false") final boolean overwrite,@QueryParam("replication") @DefaultValue("3") final short replication,@QueryParam("blocksize") @DefaultValue("-1") long blocksize,@QueryParam("permission") @DefaultValue("u=rw,go=r") final String permission) throws IOException { if (outputPath == null) { return Response.status(Response.Status.BAD_REQUEST).header("Warning","199 " + "path cannot be null").cacheControl(cacheControl).build(); } if (blocksize == -1) { blocksize=config.getHadoopBlockSize(); } try { final URI path=hdfsWriter.write(body,outputPath,overwrite,replication,blocksize,permission); return Response.created(path).build(); } catch ( IOException e) { final String message; if (e.getMessage() != null) { message=StringUtils.split(e.getMessage(),'\n')[0]; } else { message=e.toString(); } log.warn("Unable to create [{}]: {}",outputPath,message); return Response.serverError().header("Warning","199 " + message).cacheControl(cacheControl).build(); } }
Example 14
From project action-core, under directory /src/test/java/com/ning/metrics/action/hdfs/writer/.
Source file: TestHdfsWriter.java

@Test(groups="fast") public void testWrite() throws Exception { final HdfsWriter writer=new HdfsWriter(fileSystemAccess); final String outputFile=outputPath + "/lorem.txt"; final URI outputURI=writer.write(new FileInputStream(file),outputFile,false,(short)1,1024,"ugo=r"); final FileStatus status=fileSystemAccess.get().getFileStatus(new Path(outputURI)); Assert.assertEquals(status.getPath().toString(),"file:" + outputFile); Assert.assertEquals(status.getReplication(),(short)1); try { writer.write(new FileInputStream(file),outputFile,false,(short)1,1024,"ugo=r"); Assert.fail(); } catch ( IOException e) { Assert.assertEquals(e.getLocalizedMessage(),String.format("File already exists:%s",outputFile)); } }
Example 15
From project adbcj, under directory /api/src/main/java/org/adbcj/.
Source file: ConnectionManagerProvider.java

public static ConnectionManager createConnectionManager(String url,String username,String password,Properties properties) throws DbException { if (url == null) { throw new IllegalArgumentException("Connection url can not be null"); } try { URI uri=new URI(url); String adbcjProtocol=uri.getScheme(); if (!ADBCJ_PROTOCOL.equals(adbcjProtocol)) { throw new DbException("Invalid connection URL: " + url); } URI driverUri=new URI(uri.getSchemeSpecificPart()); String protocol=driverUri.getScheme(); ServiceLoader<ConnectionManagerFactory> serviceLoader=ServiceLoader.load(ConnectionManagerFactory.class); for ( ConnectionManagerFactory factory : serviceLoader) { if (factory.canHandle(protocol)) { return factory.createConnectionManager(url,username,password,properties); } } throw new DbException("Could not find ConnectionManagerFactory for protocol '" + protocol + "'"); } catch ( URISyntaxException e) { throw new DbException("Invalid connection URL: " + url); } }
Example 16
From project aether-core, under directory /aether-util/src/main/java/org/eclipse/aether/util/repository/layout/.
Source file: MavenDefaultLayout.java

private URI toUri(String path){ try { return new URI(null,null,path,null); } catch ( URISyntaxException e) { throw new IllegalStateException(e); } }
Example 17
From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/util/http/.
Source file: HttpBuilder.java

private <T>HttpResult<T> doPost(Type target){ try { URI path=createPath(address); HttpPost post=new HttpPost(path); HttpEntity entity=prepareMultipart(); post.setEntity(entity); return doRequest(post,target); } catch ( UnsupportedEncodingException e) { Log.e(Constants.TAG,"Couldn't process parameters",e); return error(); } catch ( URISyntaxException e) { Log.e(Constants.TAG,"Couldn't create path",e); return error(); } }
Example 18
From project Airports, under directory /src/com/nadmm/airports/library/.
Source file: LibraryService.java

private boolean fetch(String category,File pdfFile){ try { String path=LIBRARY_PATH + "/" + category+ "/"+ pdfFile.getName()+ ".gz"; URI uri=URIUtils.createURI("http",LIBRARY_HOST,80,path,null,null); ProgressReceiver receiver=new ProgressReceiver(); Bundle result=new Bundle(); result.putString(NetworkUtils.CONTENT_NAME,pdfFile.getName()); result.putString(CATEGORY,category); return NetworkUtils.doHttpGet(this,mHttpClient,uri,pdfFile,receiver,result,GZIPInputStream.class); } catch ( Exception e) { UiUtils.showToast(this,e.getMessage()); } return false; }
Example 19
From project 2Degrees-Toolbox, under directory /Toolbox/src/biz/shadowservices/DegreesToolbox/.
Source file: HttpPoster.java

public HttpPoster(URI uri,List<? extends NameValuePair> values){ httppost=new HttpPost(uri); try { httppost.setEntity(new UrlEncodedFormEntity(values,HTTP.UTF_8)); } catch ( UnsupportedEncodingException e) { Log.e(TAG,"Error: Unsupported encoding exception on " + httppost.getURI()); } }
Example 20
From project Aardvark, under directory /aardvark-vedit/src/main/java/gw/vark/editor/.
Source file: VEdit.java

private void launchWikiForMI(IMethodInfo iMethodInfo){ if (iMethodInfo.getOwnersType().getName().equals("gw.vark.CoreFileEnhancement") || iMethodInfo.getOwnersType().getName().equals("gw.vark.CorePathEnhancement") || iMethodInfo.getOwnersType().getName().equals("gw.vark.CoreProjectEnhancement")|| iMethodInfo.getOwnersType().getName().equals("gw.vark.CoreIAardvarkUtilsEnhancement")) { try { Desktop.getDesktop().browse(URI.create("http://github.com/bchang/Aardvark/wiki/" + iMethodInfo.getDisplayName())); } catch ( IOException e) { e.printStackTrace(); } } else if (iMethodInfo.getOwnersType() == null) { try { Desktop.getDesktop().browse(URI.create("http://github.com/bchang/Aardvark/wiki/Ant_" + iMethodInfo.getDisplayName())); } catch ( IOException e) { e.printStackTrace(); } } else { JOptionPane.showMessageDialog(null,"Place the cursor on a method in the Aardvark API"); } }
Example 21
From project adg-android, under directory /src/com/analysedesgeeks/android/service/impl/.
Source file: DownloadServiceImpl.java

@Override public boolean downloadFeed(){ boolean downloadSuccess=false; if (connectionService.isConnected()) { InputStream inputStream=null; try { final HttpGet httpget=new HttpGet(new URI(Const.FEED_URL)); final HttpResponse response=new DefaultHttpClient().execute(httpget); final StatusLine status=response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { Ln.e("Erreur lors du t??hargement:%s,%s",status.getStatusCode(),status.getReasonPhrase()); } else { final HttpEntity entity=response.getEntity(); inputStream=entity.getContent(); final ByteArrayOutputStream content=new ByteArrayOutputStream(); int readBytes=0; final byte[] sBuffer=new byte[512]; while ((readBytes=inputStream.read(sBuffer)) != -1) { content.write(sBuffer,0,readBytes); } final String dataAsString=new String(content.toByteArray()); final List<FeedItem> syndFeed=rssService.parseRss(dataAsString); if (syndFeed != null) { databaseService.save(dataAsString); downloadSuccess=true; } } } catch ( final Throwable t) { Ln.e(t); } finally { closeQuietly(inputStream); } } return downloadSuccess; }
Example 22
From project ajah, under directory /ajah-http/src/main/java/com/ajah/http/cache/.
Source file: DiskCache.java

/** * Returns the content from cache if possible, and if not, will fetch and cache it. * @param uri The URI to fetch. * @param maxAge The maximum age of the cached copy to return. Use -1 to force a fresh fetch. * @return The content from cache or as fetched. * @throws IOException If the URI could not be fetched. * @throws NotFoundException If the URI is 404 * @throws UnexpectedResponseCode If the URI returns a response code that {@link Http} cannotnot handle. */ public static byte[] getBytes(final URI uri,long maxAge) throws IOException, NotFoundException, UnexpectedResponseCode { final String path=FileHashUtils.getHashedFileName(SHA.sha1Hex(uri.toString()),3,2); final File cacheDir=new File(Config.i.get("ajah.http.cache.dir","/tmp/ajah-http-cache")); final File f=new File(cacheDir,path); log.finest("Cache location: " + f.getAbsolutePath()); byte[] data=null; if (f.exists()) { if (maxAge == Long.MAX_VALUE) { log.finest("Indefinite caching enabled; getting " + uri); return FileUtils.readFileAsBytes(f); } else if (maxAge > 0) { long mod=f.lastModified(); if (log.isLoggable(Level.FINEST)) { log.finest("File modified " + new Date(mod)); log.finest("Expiration is " + new Date(System.currentTimeMillis() - maxAge)); } if (mod + maxAge > System.currentTimeMillis()) { log.fine("Cache hit for " + uri + " (expires in "+ DateUtils.formatInterval(System.currentTimeMillis() - mod)+ ")"); return FileUtils.readFileAsBytes(f); } log.fine("Cache expired; getting " + uri); } } else { log.fine("Cache miss; getting " + uri); } data=Http.getBytes(uri); FileUtils.write(f,data); return data; }