/** * Gets the destination of a redirection * * @return absolute URL of new location; null if not available */ static URI getLocation(HttpRequest request, HttpResponse response, HttpContext context) { Header locationHdr = response.getFirstHeader("Location"); if (locationHdr == null) { Log.e(TAG, "Received redirection without Location header, ignoring"); return null; } try { URI location = URIUtils.parseURI(locationHdr.getValue(), false); // some servers don't return absolute URLs as required by RFC 2616 if (!location.isAbsolute()) { Log.w(TAG, "Received invalid redirection to relative URL, repairing"); URI originalURI = URIUtils.parseURI(request.getRequestLine().getUri(), false); if (!originalURI.isAbsolute()) { final HttpHost target = HttpClientContext.adapt(context).getTargetHost(); if (target != null) originalURI = org.apache.http.client.utils.URIUtilsHC4.rewriteURI(originalURI, target); else return null; } return originalURI.resolve(location); } return location; } catch (URISyntaxException e) { Log.e(TAG, "Received redirection from/to invalid URI, ignoring", e); } return null; }
public InputStream openResource(URI uri) throws IOException { if (uri.isAbsolute() && uri.getScheme().equals("file")) { try { return uri.toURL().openStream(); } catch (Exception except) { log.error("openResource: unable to open file URL " + uri + "; " + except.toString()); return null; } } // Note that if we get an absolute URI, the relativize operation will simply // return the absolute URI. URI relative = baseUri.relativize(uri); if (relative.isAbsolute() && relative.getScheme().equals("http")) { try { return relative.toURL().openStream(); } catch (Exception except) { log.error("openResource: unable to open http URL " + uri + "; " + except.toString()); return null; } } if (relative.isAbsolute() && !relative.getScheme().equals("urn")) { log.error("openResource: invalid scheme (should be urn:) " + uri); return null; } File f = new File(baseUri.getPath(), relative.getPath()); if (!f.exists()) { log.error("openResource: file not found " + f); return null; } return new FileInputStream(f); }
/** * Resolve a source uri against a target. * * @param sourcePartUri The source URI. * @param targetUri The target URI. * @return The resolved URI. */ public static URI resolvePartUri(URI sourcePartUri, URI targetUri) { if (sourcePartUri == null || sourcePartUri.isAbsolute()) { throw new IllegalArgumentException("sourcePartUri invalid - " + sourcePartUri); } if (targetUri == null || targetUri.isAbsolute()) { throw new IllegalArgumentException("targetUri invalid - " + targetUri); } return sourcePartUri.resolve(targetUri); }
private void testUri(String input) { URI uri = new UriBuilderImpl().uri(input).clone().build(); URI originalUri = URI.create(input); assertEquals(originalUri.getScheme(), uri.getScheme()); assertEquals(originalUri.getHost(), uri.getHost()); assertEquals(originalUri.getPort(), uri.getPort()); assertEquals(originalUri.getUserInfo(), uri.getUserInfo()); assertEquals(originalUri.getPath(), uri.getPath()); assertEquals(originalUri.getQuery(), uri.getQuery()); assertEquals(originalUri.getFragment(), uri.getFragment()); assertEquals(originalUri.getRawSchemeSpecificPart(), uri.getRawSchemeSpecificPart()); assertEquals(originalUri.isAbsolute(), uri.isAbsolute()); assertEquals(input, uri.toString()); }
private String parseURI(URI uri) { if (!uri.isAbsolute()) { throw new IllegalArgumentException(uri + " is not an absolute URI"); } return uri.isOpaque() ? parseOpaqueURI(uri) : parseHierarchicalURI(uri); }
/** * Get Base64 encoding content. For ODT transformation * * @param dirName - The directory name that will be added to the path of the image file. * @param fileName - The file name of the image file. * @return base64 encoded binary data. */ public static String getBASE64(final String dirName, final String fileName) { final DITAOTJavaLogger logger = new DITAOTJavaLogger(); final URI imgInputURI = toURI(fileName); final File imgInput = imgInputURI.isAbsolute() ? new File(imgInputURI) : new File(dirName, toFile(imgInputURI).getPath()); // BASE64Encoder encoder = new BASE64Encoder(); final Base64 encoder = new Base64(); final byte buff[] = new byte[(int) imgInput.length()]; FileInputStream file = null; try { file = new FileInputStream(imgInput); file.read(buff); // String ret = encoder.encode(buff); return encoder.encodeToString(buff); } catch (final FileNotFoundException e) { logger.error(MessageUtils.getInstance().getMessage("DOTJ023E").toString()); logger.error(e.getMessage(), e); return null; } catch (final IOException e) { logger.error(MessageUtils.getInstance().getMessage("DOTJ023E").toString()); logger.error(e.getMessage(), e); return null; } finally { if (file != null) { try { file.close(); } catch (final IOException ioe) { logger.error(ioe.getMessage(), ioe); } } } }
/* 43: */ /* 44: */ private ModuleSource loadFromPathArray( String moduleId, Scriptable paths, Object validator) /* 45: */ throws IOException /* 46: */ { /* 47: 60 */ long llength = ScriptRuntime.toUint32(ScriptableObject.getProperty(paths, "length")); /* 48: */ /* 49: */ /* 50: 63 */ int ilength = llength > 2147483647L ? 2147483647 : (int) llength; /* 51: 66 */ for (int i = 0; i < ilength; i++) /* 52: */ { /* 53: 67 */ String path = ensureTrailingSlash((String) ScriptableObject.getTypedProperty(paths, i, String.class)); /* 54: */ try /* 55: */ { /* 56: 70 */ URI uri = new URI(path); /* 57: 71 */ if (!uri.isAbsolute()) { /* 58: 72 */ uri = new File(path).toURI().resolve(""); /* 59: */ } /* 60: 74 */ ModuleSource moduleSource = loadFromUri(uri.resolve(moduleId), uri, validator); /* 61: 76 */ if (moduleSource != null) { /* 62: 77 */ return moduleSource; /* 63: */ } /* 64: */ } /* 65: */ catch (URISyntaxException e) /* 66: */ { /* 67: 81 */ throw new MalformedURLException(e.getMessage()); /* 68: */ } /* 69: */ } /* 70: 84 */ return null; /* 71: */ }
/** * Working on behalf of the given source factory, resolve the (possibly relative) contained URI * against the URI associated with the containing source object. Return a {@link Source source} * representing the file to which it was resolved, or {@code null} if it could not be resolved. * * @param factory the source factory requesting the resolution of the URI * @param containingSource the source containing the given URI * @param containedUri the (possibly relative) URI to be resolved against the containing source * @return a {@link Source source} representing the URI to which given URI was resolved */ public Source resolve(SourceFactory factory, Source containingSource, URI containedUri) { if (containedUri.isAbsolute()) { return resolveAbsolute(factory, containedUri); } else { return resolveRelative(factory, containingSource, containedUri); } }
public static URI build(URI prefix, URI localName) throws NamingAuthorityConfigurationException { try { verifyPrefix(prefix); } catch (Exception e) { throw new NamingAuthorityConfigurationException(e.getMessage()); } if (localName == null) { throw new IllegalArgumentException("Localname must not be null."); } else if (localName.isAbsolute()) { throw new IllegalArgumentException("Localname must be a relative URI."); } // request.getPathInfo() strips required "/" from identifier URL, replace it String scheme = localName.getScheme(); String path = localName.getPath(); // trim off any leading / so the URI resolving doesn't treat it as an // absolute path if (path.startsWith("/")) { path = path.substring(1); } String url = path; if (scheme != null) { url = scheme + ":/" + path; } localName = URI.create(url); return prefix.resolve(localName); }
public InputSource(URI uri) { if (!uri.isAbsolute()) { throw new IllegalArgumentException(uri.toString()); } this.uri = uri; this.uriStr = uri.toString(); }
/** * Creates absolute request URI with full path from passed in context, honoring proxy if in play. */ @Nonnull private URI getRequestURI(final HttpContext context) { final HttpClientContext clientContext = HttpClientContext.adapt(context); final HttpRequest httpRequest = clientContext.getRequest(); try { URI uri; if (httpRequest instanceof HttpUriRequest) { uri = ((HttpUriRequest) httpRequest).getURI(); } else { uri = URI.create(httpRequest.getRequestLine().getUri()); } final RouteInfo routeInfo = clientContext.getHttpRoute(); if (routeInfo != null) { if (routeInfo.getHopCount() == 1 && uri.isAbsolute()) { return uri; } HttpHost target = routeInfo.getHopTarget(0); return URIUtils.resolve(URI.create(target.toURI()), uri); } else { return uri; } } catch (Exception e) { log.warn("Could not create absolute request URI", e); return URI.create(clientContext.getTargetHost().toURI()); } }
/* * InputStream must be closed * (non-Javadoc) * @see org.eclipse.equinox.simpleconfigurator.manipulator.SimpleConfiguratorManipulator#loadConfiguration(java.io.InputStream, java.net.URI) */ public BundleInfo[] loadConfiguration(InputStream stream, URI installArea) throws IOException { if (stream == null) return NULL_BUNDLEINFOS; List simpleBundles = SimpleConfiguratorUtils.readConfiguration(stream, installArea); // convert to FrameworkAdmin BundleInfo Type BundleInfo[] result = new BundleInfo[simpleBundles.size()]; int i = 0; for (Iterator iterator = simpleBundles.iterator(); iterator.hasNext(); ) { org.eclipse.equinox.internal.simpleconfigurator.utils.BundleInfo simpleInfo = (org.eclipse.equinox.internal.simpleconfigurator.utils.BundleInfo) iterator.next(); URI location = simpleInfo.getLocation(); if (!location.isAbsolute() && simpleInfo.getBaseLocation() != null) location = URIUtil.makeAbsolute(location, simpleInfo.getBaseLocation()); BundleInfo bundleInfo = new BundleInfo( simpleInfo.getSymbolicName(), simpleInfo.getVersion(), location, simpleInfo.getStartLevel(), simpleInfo.isMarkedAsStarted()); bundleInfo.setBaseLocation(simpleInfo.getBaseLocation()); result[i++] = bundleInfo; } return result; }
public CssUrlRewriter(File cssBasePath, final CharSequence input) throws BundlerProcessingException { Matcher urlMatcher = URL_PATTERN.matcher(input); while (urlMatcher.find()) { String relativePath = urlMatcher.group(1); // this is used to ignore any spacing so can be read as a URI correctly. String withoutSpacesOrNewLines = relativePath.replaceAll("(\\s)", ""); boolean parsableUrl = true; try { /* if it parses as a URI don't rewrite */ URI uri = new URI(withoutSpacesOrNewLines); if (uri.isAbsolute()) { parsableUrl = false; } } catch (URISyntaxException ex) { throw new RuntimeException( "URI \"" + relativePath + "\" is invalid (" + ex.getReason() + ").", ex); } if (parsableUrl) { String parsedUrl = parseUrl(cssBasePath, relativePath); urlMatcher.appendReplacement(css, parsedUrl); } } urlMatcher.appendTail(css); }
private static void construct(String str, String host, String path, boolean absolute) throws URISyntaxException { URI uri = new URI(str); assertEquals(host, uri.getHost()); assertEquals(path, uri.getPath()); assertEquals(absolute, uri.isAbsolute()); }
private Uri resolveUri(URI uri) { if (uri.isAbsolute() || absoluteUri == null) { return convertToAndroidUriAndFixScheme(uri, uri); } else { return convertToAndroidUriAndFixScheme(absoluteUri.resolve(uri), absoluteUri); } }
@Deprecated public void setResourceURL(URI url) { if (!url.isAbsolute()) { throw new IllegalArgumentException("URL is not absolute: " + url); } this.url = url.toString(); }
@Override public ILayer createLayer(URI source) throws LayerException { if (!source.isAbsolute()) { // If URI is not absolute ex URI.create("../folder/myfile.shp"), then create a canonical URI try { source = new File(location != null ? new File(location) : new File("./"), source.toString()) .getCanonicalFile() .toURI(); } catch (IOException ex) { throw new LayerException(ex); } } String layerName; try { layerName = FileUtils.getNameFromURI(source); } catch (UnsupportedOperationException ex) { try { layerName = dataManager.findUniqueTableName(I18N.tr("Layer")); } catch (SQLException ex2) { throw new LayerException(ex2); } } return createLayer(layerName, source); }
public String getAbsolutePath(String path) { try { URI uri = new URI(path); if (uri.isAbsolute()) { return path; } } catch (URISyntaxException e) { } if (this.base != null && !this.base.equals("")) // $NON-NLS-1$ { return makeAbsolute(base, path); } String result = path; Catalog catalog = (Catalog) getOwnerCatalog(); if (catalog != null) { String base = catalog.getBase(); if (base == null || base.equals("")) // $NON-NLS-1$ { base = catalog.getLocation(); } result = makeAbsolute(base, path); } return result; }
private static URI resolveUri(String uriStr, URI baseUri) throws URISyntaxException { URI resolved; URI resourceUri = new URI(uriStr); if (resourceUri.isAbsolute()) resolved = resourceUri; else resolved = baseUri.resolve(resourceUri); return resolved; }
private static URI getEffectiveURI(HttpRequest httpRequest) { URI requestURI = URI.create(httpRequest.getUri()); if (requestURI.isAbsolute()) { return requestURI; } String host = getHost(httpRequest); return (host != null) ? URI.create(format("http://%s%s", host, requestURI)) : null; }
/** * Set the absolute URI of the ultimate request that was made to receive this response. * * <p>If the original request URI has been modified (e.g. due to redirections), the absolute URI * of the ultimate request being made to receive the response should be set by the caller on the * response instance using this method. * * @param uri absolute URI of the ultimate request made to receive this response. Must not be * {@code null}. * @throws java.lang.NullPointerException in case the passed {@code uri} parameter is null. * @throws java.lang.IllegalArgumentException in case the passed {@code uri} parameter does not * represent an absolute URI. * @see ClientProperties#FOLLOW_REDIRECTS * @see #getResolvedRequestUri() * @since 2.6 */ public void setResolvedRequestUri(final URI uri) { if (uri == null) { throw new NullPointerException(LocalizationMessages.CLIENT_RESPONSE_RESOLVED_URI_NULL()); } if (!uri.isAbsolute()) { throw new IllegalArgumentException( LocalizationMessages.CLIENT_RESPONSE_RESOLVED_URI_NOT_ABSOLUTE()); } this.resolvedUri = uri; }
/** * Creates a URI contatenating the specified {@code base} and {@code relativeUri}. * * @param base the URI base * @param relativeUri the uri * @return the final URI used to make the request * @throws URISyntaxException if the given string violates RFC 2396 */ default URI createUri(final String base, final String relativeUri) throws URISyntaxException { URI uri = new URI(relativeUri); if (!uri.isAbsolute()) { String uriBase = base; if (!uriBase.endsWith("/") && !relativeUri.startsWith("/")) { uriBase += "/"; } uri = new URI(uriBase + relativeUri); } return uri; }
protected static String resolveIfRelative(String base, URI toResolve) { if (toResolve.isAbsolute()) { return toResolve.toString(); } try { return new URI(base).resolve(toResolve).toString(); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
/** * Returns results from parsing a {@link java.net.URI} with this pattern. If the URI doesn't match * the pattern, this will return null. * * @param uri A URI to match against this URIPattern * @return A Map of the pattern's variable names to values from the parsed URI */ public Map<String, String> getMatch(URI uri) { // verify that the schemes match if (pattern.isAbsolute()) { // if there should be a scheme, make sure it matches if (!pattern.getScheme().equalsIgnoreCase(uri.getScheme())) { return null; } } else if (uri.getScheme() != null) { return null; } Map<String, String> result = Maps.newLinkedHashMap(defaults); if (pattern.isOpaque()) { if (!uri.isOpaque()) { return null; } Iterator<String> pathQuery = PATH_QUERY_SPLITTER.split(uri.getRawSchemeSpecificPart()).iterator(); if (!addPath(patternPath, Iterators.getNext(pathQuery, null), result)) { return null; } addQuery(Iterators.getNext(pathQuery, null), result); } else if (!uri.isOpaque()) { addAuthority(uri, result); if (patternPath.isEmpty() && !uri.getRawPath().isEmpty()) { return null; } if (!addPath(patternPath, uri.getRawPath(), result)) { return null; } addQuery(uri.getRawQuery(), result); } else { return null; } if (!addComplexMatch(pattern.getFragment(), uri.getFragment(), result)) { return null; } // save this match this.lastMatch = result; // return the new result, so that this is thread-safe return result; }
/** * Recursive function to parse a layer tree * * @param lt * @param parentLayer */ private void parseJaxbLayer(LayerType lt, ILayer parentLayer) throws LayerException { // Test if lt is a group if (!lt.getLayer().isEmpty() || (lt.getDataURL() == null)) { // it will create a LayerCollection parseJaxbLayerCollection(lt, parentLayer); } else { // it corresponding to a leaf layer // We need to read the data declaration and create the layer URLType dataUrl = lt.getDataURL(); if (dataUrl != null) { OnlineResourceType resType = dataUrl.getOnlineResource(); try { URI layerURI = new URI(resType.getHref()); // The resource is given as relative to MapContext location if (!layerURI.isAbsolute() && getLocation() != null) { try { // Resolve the relative resource ex: new Uri("myFile.shp") layerURI = getLocation().resolve(layerURI); } catch (IllegalArgumentException ex) { LOGGER.warn( "Error while trying to find an absolute path for an external resource", ex); } } // Get table name ILayer leafLayer = createLayer(layerURI); leafLayer.setDescription(new Description(lt)); leafLayer.setVisible(!lt.isHidden()); // Parse styles if (lt.isSetStyleList()) { for (StyleType st : lt.getStyleList().getStyle()) { if (st.isSetSLD()) { if (st.getSLD().isSetAbstractStyle()) { leafLayer.addStyle( new Style( (JAXBElement<net.opengis.se._2_0.core.StyleType>) st.getSLD().getAbstractStyle(), leafLayer)); } } } } parentLayer.addLayer(leafLayer); } catch (URISyntaxException ex) { throw new LayerException( I18N.tr("Unable to parse the href URI {0}.", resType.getHref()), ex); } catch (InvalidStyle ex) { throw new LayerException( I18N.tr("Unable to load the description of the layer {0}", lt.getTitle().toString()), ex); } } } }
protected Message createMessage( Object body, String httpMethod, MultivaluedMap<String, String> headers, URI currentURI, Exchange exchange, Map<String, Object> invocationContext, boolean proxy) { Message m = cfg.getConduitSelector().getEndpoint().getBinding().createMessage(); m.put(Message.REQUESTOR_ROLE, Boolean.TRUE); m.put(Message.INBOUND_MESSAGE, Boolean.FALSE); m.put(Message.HTTP_REQUEST_METHOD, httpMethod); m.put(Message.PROTOCOL_HEADERS, headers); if (currentURI.isAbsolute() && currentURI.getScheme().startsWith(HTTP_SCHEME)) { m.put(Message.ENDPOINT_ADDRESS, currentURI.toString()); } else { m.put(Message.ENDPOINT_ADDRESS, state.getBaseURI().toString()); } Object requestURIProperty = cfg.getRequestContext().get(Message.REQUEST_URI); if (requestURIProperty == null) { m.put(Message.REQUEST_URI, currentURI.toString()); } else { m.put(Message.REQUEST_URI, requestURIProperty.toString()); } m.put(Message.CONTENT_TYPE, headers.getFirst(HttpHeaders.CONTENT_TYPE)); body = checkIfBodyEmpty(body); setEmptyRequestPropertyIfNeeded(m, body); m.setContent(List.class, getContentsList(body)); m.put(URITemplate.TEMPLATE_PARAMETERS, getState().getTemplates()); PhaseInterceptorChain chain = setupOutInterceptorChain(cfg); chain.setFaultObserver(setupInFaultObserver(cfg)); m.setInterceptorChain(chain); exchange = createExchange(m, exchange); exchange.put(Message.REST_MESSAGE, Boolean.TRUE); exchange.setOneWay("true".equals(headers.getFirst(Message.ONE_WAY_REQUEST))); exchange.put(Retryable.class, new RetryableImpl()); // context setContexts(m, exchange, invocationContext, proxy); // setup conduit selector prepareConduitSelector(m, currentURI, proxy); return m; }
@Override protected void writeURI(org.openrdf.model.URI uri) throws IOException { URI create = URI.create(uri.toString()); URI rel = baseURI.relativize(create); if (!rel.isAbsolute()) { writer.write("<"); writer.write(TurtleUtil.encodeURIString(rel.toString())); writer.write(">"); } else { super.writeURI(uri); } }
private String getKBServerUrl(final String uri) throws KillBillClientException { try { final URI u = new URI(uri); if (u.isAbsolute()) { return uri; } else { return String.format("%s%s", kbServerUrl, uri); } } catch (URISyntaxException e) { throw new KillBillClientException(e); } }
/** * creates a canonical representation of the uriString. This method performs certain translations * depending on the type of URI generated by the string. */ private URI canonicalize(String uriString) throws URISyntaxException { if ((uriString == null) || (uriString.compareTo("localhost") == 0)) { uriString = "//localhost"; return new URI(uriString); } URI u = new URI(uriString); if (u.isAbsolute()) { if (u.isOpaque()) { /* * this code is here to deal with a special case. For ease of use, we'd like to be able to handle the case where the user specifies hostname:port, not requiring the scheme part. This introduces some subtleties. hostname:port - scheme = hostname - schemespecificpart = port - hostname = null - userinfo=null however, someone could also enter scheme:hostname:port and get into this code. the strategy is to consider this syntax illegal and provide some code to defend against it. * Basically, we test that the string contains only one ":" and that the ssp is numeric. If we get two colons, we will attempt to insert the "//" after the first colon and then try to create a URI from the resulting string. */ String scheme = u.getScheme(); String ssp = u.getSchemeSpecificPart(); String frag = u.getFragment(); URI u2 = null; int c1index = uriString.indexOf(":"); int c2index = uriString.lastIndexOf(":"); if (c2index != c1index) { /* * this is the scheme:hostname:port case. Attempt to transform this to scheme://hostname:port. If a path part is part of the original strings, it will be included in the SchemeSpecificPart. however, the fragment part must be handled separately. */ if (frag == null) { u2 = new URI(scheme + "://" + ssp); } else { u2 = new URI(scheme + "://" + ssp + "#" + frag); } return u2; } /* * here we have the <string>:<string> case, possibly with optional path and fragment components. we assume that the part following the colon is a number. we don't check this condition here as it will get detected later anyway. */ u2 = new URI("//" + uriString); return u2; } else { return u; } } else { /* * This is the case where we were given a hostname followed by a path part, fragment part, or both a path and fragment part. The key here is that no scheme part was specified. For this case, if the scheme specific part does not begin with "//", then we prefix the "//" to the given string and attempt to create a URI from the resulting string. */ String ssp = u.getSchemeSpecificPart(); if (ssp.startsWith("//")) { return u; } else { return new URI("//" + uriString); } } }
private Writer createFileWriter(File outBase, File inBase, URI file) throws IOException { URI relative = inBase.toURI().relativize(file); File outFile; if (relative.isAbsolute()) { outFile = new File(outBase, new File(relative).getName()); } else { outFile = new File(outBase, relative.getPath()); } outFile.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(outFile); return createUnicodeEscapeWriter(out); }