List of usage examples for java.net URI toASCIIString
public String toASCIIString()
From source file:com.almende.eve.transport.ws.WsClientTransport.java
@Override public void send(final URI receiverUri, final String message, final String tag) throws IOException { if (!receiverUri.equals(serverUrl)) { throw new IOException( "Currently it's only possible to send to the server agent directly, not other agents:" + receiverUri.toASCIIString() + " serverUrl:" + serverUrl.toASCIIString()); }//www .j ava 2 s .co m if (remote == null || !isConnected()) { connect(); } if (remote != null) { try { remote.sendText(message); remote.flushBatch(); } catch (RuntimeException rte) { if (rte.getMessage().equals("Socket is not connected.")) { remote = null; // retry! send(receiverUri, message, tag); } } } else { throw new IOException("Not connected?"); } }
From source file:com.almende.eve.transport.ws.WsClientTransport.java
@Override public void send(final URI receiverUri, final byte[] message, final String tag) throws IOException { if (!receiverUri.equals(serverUrl)) { throw new IOException( "Currently it's only possible to send to the server agent directly, not other agents:" + receiverUri.toASCIIString()); }//from w w w . j a v a2 s. c om if (remote == null || !isConnected()) { connect(); } if (remote != null) { try { remote.sendBinary(ByteBuffer.wrap(message)); remote.flushBatch(); } catch (RuntimeException rte) { if (rte.getMessage().equals("Socket is not connected.")) { remote = null; // retry! send(receiverUri, message, tag); } } } else { throw new IOException("Not connected?"); } }
From source file:org.paxle.core.norm.impl.ReferenceNormalizer.java
/** * Normalizes all {@link IParserDocument#getLinks() links} contained in a * {@link IParserDocument parser-document}. * // w ww .j a v a 2s. co m * @param pdoc the {@link IParserDocument parser-document} */ private void normalizeParserDoc(final IParserDocument pdoc) { /* ============================================================= * Normalize Sub-Documents * ============================================================= */ final Map<String, IParserDocument> subdocMap = pdoc.getSubDocs(); if (subdocMap != null && subdocMap.size() > 0) { for (final IParserDocument subdoc : subdocMap.values()) { this.normalizeParserDoc(subdoc); } } /* ============================================================= * Normalize Links * ============================================================= */ final Map<URI, LinkInfo> linkMap = pdoc.getLinks(); if (linkMap == null || linkMap.size() == 0) return; final Map<URI, LinkInfo> normalizedLinks = new HashMap<URI, LinkInfo>(); final Charset charset = (pdoc.getCharset() == null) ? UTF8 : pdoc.getCharset(); // UTF-8 is a recommended fallback but not standard yet final Iterator<Map.Entry<URI, LinkInfo>> it = linkMap.entrySet().iterator(); while (it.hasNext()) { final Map.Entry<URI, LinkInfo> entry = it.next(); final URI locationURI = entry.getKey(); final String location = locationURI.toASCIIString(); final URI normalizedURI = this.normalizeReference(location, charset); if (normalizedURI == null) { this.logger.info("removing malformed reference: " + location); // FIXME: shouldn't we call it.remove() here? continue; } else if (normalizedURI.equals(locationURI)) { continue; } this.logger.debug("normalized reference " + location + " to " + normalizedURI); normalizedLinks.put(normalizedURI, entry.getValue()); it.remove(); } linkMap.putAll(normalizedLinks); }
From source file:org.pentaho.di.baserver.utils.inspector.Inspector.java
protected boolean inspectEndpoints(final String moduleName) { URI uri = null; try {//from www . jav a 2s. c o m uri = new URI(getApplicationWadlEndpoint(moduleName)); } catch (URISyntaxException e) { // do nothing } if (uri != null) { Response response = callHttp(uri.toASCIIString()); if (response != null && response.getStatusCode() == HttpStatus.SC_OK) { Document doc = getDocument(response.getResult()); if (doc != null) { TreeMap<String, LinkedList<Endpoint>> endpointMap = new TreeMap<String, LinkedList<Endpoint>>(); for (Endpoint endpoint : getParser().getEndpoints(doc)) { final String path = endpoint.getPath(); if (!endpointMap.containsKey(path)) { endpointMap.put(path, new LinkedList<Endpoint>()); } endpointMap.get(path).add(endpoint); } getEndpointsTree().put(moduleName, endpointMap); return true; } } } return false; }
From source file:org.jclouds.mezeo.pcs2.PCSClientLiveTest.java
@Test public void testListContainers() throws Exception { ContainerList response = connection.list(); URI rootUrl = response.getUrl(); String name = "/"; validateContainerList(response, rootUrl, name); long initialContainerCount = response.size(); assertTrue(initialContainerCount >= 0); // Create test containers for (String container : new String[] { containerPrefix + ".testListOwnedContainers1", containerPrefix + ".testListOwnedContainers2" }) { URI containerURI = connection.createContainer(container); connection.putMetadataItem(containerURI, "name", container); response = connection.list(containerURI); validateContainerList(response, rootUrl, container); assertEquals(response.getMetadataItems().get("name"), URI.create(containerURI.toASCIIString() + "/metadata/name")); validateMetadataItemNameEquals(containerURI, container); connection.deleteContainer(containerURI); }//from w ww . ja v a 2 s . co m }
From source file:mecard.security.PAPISecurity.java
/** * Returns the authorization signature string used in the HTTP * header, to get the access token (good for 24 hours, but compute each time) * that is required for privileged operations. * @param HTTPMethod POST usually./*from w w w .j a v a 2 s. c o m*/ * @param uri of the WS operation either patron create or update. * @return Authorization string used to compute initial login Authentication header value. */ public String getSignature(String HTTPMethod, URI uri) { // Authorization - PWS [PAPIAccessKeyID]:[Signature] // PWS must be in caps // No space before or after : // [PAPIAccessKeyID] - Assigned by Polaris // [Signature] - The signature is the following, encoded with SHA1 UTF-8: // [HTTPMethod][URI][Date][PatronPassword] String signature = this.getPAPIHash(this.PAPISecret, HTTPMethod, uri.toASCIIString(), this.getPolarisDate(), ""); return signature; }
From source file:org.messic.server.api.musicinfo.youtube.MusicInfoYoutubePlugin.java
private String search(Locale locale, String search) throws IOException { // http://ctrlq.org/code/19608-youtube-search-api // Based con code writted by Amit Agarwal // YouTube Data API base URL (JSON response) String surl = "v=2&alt=jsonc"; // set paid-content as false to hide movie rentals surl = surl + "&paid-content=false"; // set duration as long to filter partial uploads // url = url + "&duration=long"; // order search results by view count surl = surl + "&orderby=viewCount"; // we can request a maximum of 50 search results in a batch surl = surl + "&max-results=50"; surl = surl + "&q=" + search; URI uri = null; try {/* ww w .j av a2s .c om*/ uri = new URI("http", "gdata.youtube.com", "/feeds/api/videos", surl, null); } catch (URISyntaxException e) { log.error("failed!", e); } URL url = new URL(uri.toASCIIString()); log.info(surl); Proxy proxy = getProxy(); URLConnection connection = (proxy != null ? url.openConnection(proxy) : url.openConnection()); InputStream is = connection.getInputStream(); JsonFactory jsonFactory = new JsonFactory(); // or, for data binding, // org.codehaus.jackson.mapper.MappingJsonFactory JsonParser jParser = jsonFactory.createParser(is); String htmlCode = "<script type=\"text/javascript\">"; htmlCode = htmlCode + " function musicInfoYoutubeDestroy(){"; htmlCode = htmlCode + " $('.messic-musicinfo-youtube-overlay').remove();"; htmlCode = htmlCode + " $('.messic-musicinfo-youtube-iframe').remove();"; htmlCode = htmlCode + " }"; htmlCode = htmlCode + " function musicInfoYoutubePlay(id){"; htmlCode = htmlCode + " var code='<div class=\"messic-musicinfo-youtube-overlay\" onclick=\"musicInfoYoutubeDestroy()\"></div>';"; htmlCode = htmlCode + " code=code+'<iframe class=\"messic-musicinfo-youtube-iframe\" src=\"http://www.youtube.com/embed/'+id+'\" frameborder=\"0\" allowfullscreen></iframe>';"; htmlCode = htmlCode + " $(code).hide().appendTo('body').fadeIn();"; htmlCode = htmlCode + " }"; htmlCode = htmlCode + "</script>"; // loop until token equal to "}" while (jParser.nextToken() != null) { String fieldname = jParser.getCurrentName(); if ("items".equals(fieldname)) { jParser.nextToken(); while (jParser.nextToken() != JsonToken.END_OBJECT) { YoutubeItem yi = new YoutubeItem(); while (jParser.nextToken() != JsonToken.END_OBJECT) { if (jParser.getCurrentToken() == JsonToken.START_OBJECT) { jParser.skipChildren(); } fieldname = jParser.getCurrentName(); if ("id".equals(fieldname)) { jParser.nextToken(); yi.id = jParser.getText(); } if ("category".equals(fieldname)) { jParser.nextToken(); yi.category = jParser.getText(); } if ("title".equals(fieldname)) { jParser.nextToken(); yi.title = jParser.getText(); } if ("description".equals(fieldname)) { jParser.nextToken(); yi.description = jParser.getText(); } if ("thumbnail".equals(fieldname)) { jParser.nextToken(); jParser.nextToken(); jParser.nextToken(); jParser.nextToken(); fieldname = jParser.getCurrentName(); if ("hqDefault".equals(fieldname)) { jParser.nextToken(); yi.thumbnail = jParser.getText(); } jParser.nextToken(); } } if (yi.category != null && "MUSIC".equals(yi.category.toUpperCase()) || (yi.category == null)) { if (yi.title != null) { htmlCode = htmlCode + "<div class=\"messic-musicinfo-youtube-item\"><img src=\"" + yi.thumbnail + "\"/><div class=\"messic-musicinfo-youtube-item-play\" onclick=\"musicInfoYoutubePlay('" + yi.id + "')\"></div>" + "<div class=\"messic-musicinfo-youtube-description\">" + " <div class=\"messic-musicinfo-youtube-item-title\">" + yi.title + "</div>" + " <div class=\"messic-musicinfo-youtube-item-description\">" + yi.description + "</div>" + "</div>" + "</div>"; } } } } } return htmlCode; }
From source file:de.uni_koblenz.aggrimm.icp.interfaceAgents.bing.BingRetriever.java
/** * <p>Returns the URL for a basic query with {@code input} searching on * {@code source}.//ww w . j ava 2s.c om * * <p>This methods does not add any further parameters like file type or * latitude. Currently supported * {@code source} types are "web" and "image". Bing also supports "video", * "news" and "spell" as well as combining those. * <p>Additionally this method escapes the {@code input} to RFC 2396 and RFC * 3986 standard. * <p>We also add our options: * <ul> * <li>Sources={@code source} where we fall back to "web" if the value is * neither "image" nor "web". * <li>Adult=off for no adult content filtering, say no pre-filtering. * <li>DisableQueryAlterations for only results matching exactly the input. * <li>DisableHostCollapsing for not removing results that bing thinks are * duplicates (prevents prefiltering). * <li>$market=String as the market to search for; if unknown, en-US is used. * <li>$top=INT for the amount of results; default is 50. * <li>$skip=INT for the amount of results to skip, default is 0. * <li>$format=JSON for JSON output instead of Atom for XML output. * </ul> * * @param input search query that should be processed - must be escaped * according to RFC 3986! * @param source to search, currently only 'image' and 'web' supported. * @param market to search (bing default is determined by IP, cookies etc.) * @param skip amount of results to skip (bing default=0). * @param top amount of results to fetch (bing default=50). * * @throws MalformedURLException if {@code input} couldn't be used for a * correct URI. * @throws URISyntaxException if {@code input} couldn't be used for a * correct URI. * @throws IllegalArgumentException if {@code source} was unknown or * {@code top} or {@code skip} were out of a * logical range. * @return the most basic Bing query URL without any further parameters. */ private String createBasicQueryString(String input, String source, String market, int top, int skip) throws MalformedURLException, URISyntaxException { source = source.toLowerCase(Locale.ENGLISH); switch (source) { case "web": case "image": break; default: throw new IllegalArgumentException("An unsupported source was specified: " + source); } if (top <= 0 || skip < 0) { throw new IllegalArgumentException( "top, skip or both were outside of a logical range: top=" + top + ", skip=" + skip); } String webFileType = ""; String[] fileTypeInputSplit = input.split("filetype%3A", 2); // split at first found filetype if (fileTypeInputSplit.length == 2) { // contains "filetype:" encoded in RFC 3986 String inputBeforeFiletype = fileTypeInputSplit[0]; // The second array element will contain the trailing string, which might // start with a file type. Therefore, it is being split at the first space: fileTypeInputSplit = fileTypeInputSplit[1].split(" ", 2); // The first array element will now contain either a possible file type // or the whole trailing string (which can still be a file type): fileTypeInputSplit[0] = fileTypeInputSplit[0].toUpperCase(Locale.ENGLISH); if (Arrays.asList(KNOWN_FILE_TYPES).contains(fileTypeInputSplit[0])) { // is known file type webFileType = fileTypeInputSplit[0]; input = inputBeforeFiletype; if (fileTypeInputSplit.length == 2) { input += fileTypeInputSplit[1]; // add trailing search input if any } System.err.println(webFileType + "\n" + input); } } URI uri = new URI("https", "api.datamarket.azure.com", "/Bing/Search/v1/Composite", "Query='" + input, null); // add the Apostrophes as RFC 3986 encoded Strings manually because // otherwise the URI creation would have handled them wrong. String encodedStringURI = uri.toASCIIString().replaceFirst("'", "%27") + "%27"; // now we add our options: if (!"".equals(webFileType)) { encodedStringURI += createParameter("WebFileType", webFileType, true); } if (!Arrays.asList(KNOWN_MARKETS).contains(market)) { market = "en-US"; //set default market if parameter value is unknown } encodedStringURI += createParameter("Sources", source, true); encodedStringURI += createParameter("WebSearchOptions", "DisableQueryAlterations%2BDisableHostCollapsing", true); encodedStringURI += createParameter("Adult", "Off", true); encodedStringURI += createParameter("Market", market, true); encodedStringURI += createParameter("top", top, false); encodedStringURI += createParameter("skip", skip, false); encodedStringURI += createParameter("format", "JSON", false); return encodedStringURI; }
From source file:org.globus.workspace.service.binding.defaults.DefaultBindKernel.java
public void consume(VirtualMachine vm, Kernel kernel) throws CreationException { if (vm == null) { throw new IllegalArgumentException("vm may not be null"); }/*from w w w.j a va 2 s.c o m*/ if (kernel == null) { final String dbg = "kernel specification is not present in '" + vm.getName() + "', setting default"; logger.debug(dbg); vm.setKernel(null); vm.setKernelParameters(null); return; // *** EARLY RETURN *** } final URI uri = kernel.getKernel(); if (uri == null) { final String dbg = "kernel specification is not present in '" + vm.getName() + "', setting default"; logger.debug(dbg); vm.setKernel(null); } else if (!uri.getScheme().equals("file")) { // not supporting propagating kernels currently throw new CreationException("supplied, non-default kernel " + "cannot currently be a remote file"); } else { final String image = uri.toASCIIString(); logger.trace("found kernel image: '" + image + "'"); vm.setKernel(image); } final String params = kernel.getParameters(); if (params != null) { logger.trace("found kernel parameters: '" + params + "'"); vm.setKernelParameters(params); } }
From source file:org.apache.syncope.core.rest.AbstractTest.java
public <T> T getObject(final URI location, final Class<?> serviceClass, final Class<T> resultClass) { WebClient webClient = WebClient.fromClient(WebClient.client(adminClient.getService(serviceClass))); webClient.accept(clientFactory.getContentType().getMediaType()).to(location.toASCIIString(), false); return webClient.get(resultClass); }