Example usage for java.net URI normalize

List of usage examples for java.net URI normalize

Introduction

In this page you can find the example usage for java.net URI normalize.

Prototype

public URI normalize() 

Source Link

Document

Normalizes this URI's path.

Usage

From source file:stargate.commons.recipe.DataObjectPath.java

private URI createPathUri(String authority, String path) {
    try {/*  w  w  w  .  j av a2 s  .c o  m*/
        if (authority == null || authority.isEmpty()) {
            return new URI(STARGATE_SCHEME + ":///");
        }

        URI uri = new URI(STARGATE_SCHEME, authority, normalizePath(path), null, null);
        return uri.normalize();
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.wrml.runtime.rest.UriTemplate.java

public boolean matches(final URI uri) {

    if (uri == null) {
        return false;
    }/* w  ww  .  ja  v  a  2  s.  co  m*/

    final URI staticUri = getStaticUri();
    if (staticUri != null && uri.equals(staticUri)) {
        return true;
    }

    final String uriString = uri.normalize().toString();
    final Matcher matcher = getMatchPattern().matcher(uriString);

    return matcher.matches();
}

From source file:savant.data.sources.TabixDataSource.java

public TabixDataSource(URI uri) throws IOException {

    File indexFile = IndexCache.getIndexFile(uri, "tbi", "gz");
    SeekableStream baseStream = NetworkUtils.getSeekableStreamForURI(uri);
    this.uri = uri.normalize();
    this.reader = new TabixReader(baseStream, indexFile);

    // Check to see how many columns we actually have, and try to initialise a mapping.
    inferMapping();/* w ww  . j a v a 2  s  .  c o m*/
}

From source file:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestResourceServiceImpl.java

private Stream<OwncloudResource> listParentOwncloudResourcesOf(URI searchPath) throws IOException {
    URI parentPath = URI.create(UriComponentsBuilder.fromUri(searchPath.normalize()).path("/../").toUriString())
            .normalize();/*from w  w w.  j a va 2  s  .c om*/
    log.debug("Get the List of WebDAV Resources based by Parent URI {}", parentPath);
    URI userRoot = getUserRoot();
    val parentDirectoryConversionProperties = OwncloudResourceConversionProperties.builder().rootPath(userRoot)
            .searchPath(parentPath).renamedSearchPath("..").build();
    Sardine sardine = getSardine();
    List<DavResource> davResources = sardine.list(parentPath.toString(), 0);
    return davResources.stream()
            .map(davResource -> createOwncloudResourceFrom(davResource, parentDirectoryConversionProperties))
            .map(modifyingResource -> renameOwncloudResource(modifyingResource,
                    parentDirectoryConversionProperties));
}

From source file:org.paxle.core.norm.impl.ReferenceNormalizer.java

public URI normalizeReference(String reference, Charset charset) {
    try {//from  ww  w. j av  a2s . c  om
        // temporary "solution" until I've found a way to escape characters in different charsets than UTF-8
        URI uri;
        // uri = new URI(reference);
        uri = parseBaseUrlString(reference, charset);
        uri = uri.normalize(); // resolve backpaths
        return uri;
    } catch (URISyntaxException e) {
        logger.warn(String.format("Error normalizing reference: %s", e.getMessage()));
        return null;
    }
}

From source file:org.zaproxy.zap.spider.URLCanonicalizer.java

/**
 * Gets the canonical url, starting from a relative or absolute url found in a given context (baseURL).
 * //from www .  j ava2  s. co m
 * @param url the url string defining the reference
 * @param baseURL the context in which this url was found
 * @return the canonical url
 */
public static String getCanonicalURL(String url, String baseURL) {

    try {
        /* Build the absolute URL, from the url and the baseURL */
        String resolvedURL = URLResolver.resolveUrl(baseURL == null ? "" : baseURL, url);
        log.debug("Resolved URL: " + resolvedURL);
        URI canonicalURI;
        try {
            canonicalURI = new URI(resolvedURL);
        } catch (Exception e) {
            canonicalURI = new URI(URIUtil.encodeQuery(resolvedURL));
        }

        /* Some checking. */
        if (canonicalURI.getScheme() == null) {
            throw new MalformedURLException("Protocol could not be reliably evaluated from uri: " + canonicalURI
                    + " and base url: " + baseURL);
        }

        if (canonicalURI.getRawAuthority() == null) {
            log.debug("Ignoring URI with no authority (host[\":\"port]): " + canonicalURI);
            return null;
        }

        if (canonicalURI.getHost() == null) {
            throw new MalformedURLException("Host could not be reliably evaluated from: " + canonicalURI);
        }

        /*
         * Normalize: no empty segments (i.e., "//"), no segments equal to ".", and no segments equal to
         * ".." that are preceded by a segment not equal to "..".
         */
        String path = canonicalURI.normalize().getRawPath();

        /* Convert '//' -> '/' */
        int idx = path.indexOf("//");
        while (idx >= 0) {
            path = path.replace("//", "/");
            idx = path.indexOf("//");
        }

        /* Drop starting '/../' */
        while (path.startsWith("/../")) {
            path = path.substring(3);
        }

        /* Trim */
        path = path.trim();

        /* Process parameters and sort them. */
        final SortedMap<String, String> params = createParameterMap(canonicalURI.getRawQuery());
        final String queryString;
        String canonicalParams = canonicalize(params);
        queryString = (canonicalParams.isEmpty() ? "" : "?" + canonicalParams);

        /* Add starting slash if needed */
        if (path.length() == 0) {
            path = "/" + path;
        }

        /* Drop default port: example.com:80 -> example.com */
        int port = canonicalURI.getPort();
        if (port == 80) {
            port = -1;
        }

        /* Lowercasing protocol and host */
        String protocol = canonicalURI.getScheme().toLowerCase();
        String host = canonicalURI.getHost().toLowerCase();
        String pathAndQueryString = normalizePath(path) + queryString;

        URL result = new URL(protocol, host, port, pathAndQueryString);
        return result.toExternalForm();

    } catch (Exception ex) {
        log.warn("Error while Processing URL in the spidering process (on base " + baseURL + "): "
                + ex.getMessage());
        return null;
    }
}

From source file:at.bitfire.davdroid.mirakel.webdav.WebDavResource.java

public WebDavResource(CloseableHttpClient httpClient, URI baseURL) throws URISyntaxException {
    this.httpClient = httpClient;
    location = baseURL.normalize();

    context = HttpClientContext.create();
    context.setCredentialsProvider(new BasicCredentialsProvider());
}

From source file:org.moe.cli.utils.GrabUtils.java

/**
 * Download file from remote//from ww w. ja v a2s  .c o m
 * @param link address of remote file
 * @param output symbolic link to the local file system where the downloaded file will be stored
 * @throws FileAlreadyExistsException if output file has already exists
 * @throws FileNotFoundException if link isn't present
 * @throws UnsupportedTypeException if URI links to file with unsupported type
 * @throws IOException if operation couldn't be successfully completed because of other reasons
 */
public static void downloadFileFromRemote(@NonNull URI link, @NonNull File output)
        throws FileAlreadyExistsException, FileNotFoundException, UnsupportedTypeException, IOException {

    if (output.exists()) {
        throw new FileAlreadyExistsException(output.toString() + " already exists!");
    }

    String scheme = link.getScheme();
    if (scheme == null) {
        throw new UnsupportedTypeException("Scheme should not be null!");
    } else if (scheme.equals("https")) {
        // Create a new trust manager that trust all certificates
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        // Activate the new trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    URL url = link.normalize().toURL();
    FileUtils.copyURLToFile(url, output); //TODO: Timeout?...
}

From source file:org.seadpdt.impl.ROServicesImpl.java

@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)/*www  . j av  a 2s  .  c o m*/
@Produces(MediaType.APPLICATION_JSON)
public Response startROPublicationProcess(String publicationRequestString,
        @QueryParam("requestUrl") String requestURL, @QueryParam("oreId") String oreId)
        throws URISyntaxException {
    String messageString = "";
    Document request = Document.parse(publicationRequestString);
    Document content = (Document) request.get("Aggregation");
    if (content == null) {
        messageString += "Missing Aggregation ";
    }
    Document preferences = (Document) request.get("Preferences");
    if (preferences == null) {
        messageString += "Missing Preferences ";
    }
    Object repository = request.get("Repository");
    if (repository == null) {
        messageString += "Missing Respository ";
    } else {
        FindIterable<Document> iter = repositoriesCollection.find(new Document("orgidentifier", repository));
        if (iter.first() == null) {
            messageString += "Unknown Repository: " + repository + " ";
        }

    }

    if (messageString.equals("")) {
        // Get organization from profile(s)
        // Add to base document
        Object creatorObject = content.get("Creator");
        String ID = (String) content.get("Identifier");
        BasicBSONList affiliations = new BasicBSONList();
        if (creatorObject != null) {
            if (creatorObject instanceof ArrayList) {
                Iterator<String> iter = ((ArrayList<String>) creatorObject).iterator();

                while (iter.hasNext()) {
                    String creator = iter.next();
                    List<String> orgs = getOrganizationforPerson(creator);
                    if (!orgs.isEmpty()) {
                        affiliations.addAll(orgs);
                    }
                }

            } else {
                // BasicDBObject - single value
                List<String> orgs = getOrganizationforPerson((String) creatorObject);
                if (!orgs.isEmpty()) {
                    affiliations.addAll(orgs);
                }
            }
        }

        request.append("Affiliations", affiliations);

        // Add first status message

        List<DBObject> statusreports = new ArrayList<DBObject>();
        DBObject status = BasicDBObjectBuilder.start()
                .add("date", DateFormat.getDateTimeInstance().format(new Date(System.currentTimeMillis())))
                .add("reporter", Constants.serviceName).add("stage", "Receipt Acknowledged")
                .add("message", "request recorded and processing will begin").get();
        statusreports.add(status);
        request.append("Status", statusreports);
        // Create initial status message - add
        // Add timestamp
        // Generate ID - by calling Workflow?
        // Add doc, return 201

        String newMapURL = requestURL + "/" + ID + "/oremap";
        URI uri = new URI(newMapURL);
        uri = uri.normalize();
        content.put("@id", uri.toString() + "#aggregation");
        content.put("authoratativeMap", oreId);

        publicationsCollection.insertOne(request);
        URI resource = null;
        try {
            resource = new URI("./" + ID);
        } catch (URISyntaxException e) {
            // Should not happen given simple ids
            e.printStackTrace();
        }
        return Response.created(resource).entity(new Document("identifier", ID)).build();
    } else {
        return Response.status(ClientResponse.Status.BAD_REQUEST).entity(messageString).build();
    }
}

From source file:com.reprezen.swagedit.json.references.JsonReferenceFactory.java

protected JsonReference doCreate(String value, Object source) {
    String notNull = Strings.nullToEmpty(value);

    URI uri;
    try {/*www  .ja va 2 s .c om*/
        uri = URI.create(notNull);
    } catch (NullPointerException | IllegalArgumentException e) {
        // try to encode illegal characters, e.g. curly braces
        try {
            uri = URI.create(URLUtils.encodeURL(notNull));
        } catch (NullPointerException | IllegalArgumentException e2) {
            return new JsonReference(null, null, false, false, false, source);
        }
    }

    String fragment = uri.getFragment();
    JsonPointer pointer = null;
    try {
        pointer = JsonPointer.compile(Strings.emptyToNull(fragment));
    } catch (IllegalArgumentException e) {
        // let the pointer be null
    }

    uri = uri.normalize();
    boolean absolute = uri.isAbsolute();
    boolean local = !absolute && uri.getPath().isEmpty();
    // should warn when using curly braces
    boolean warnings = notNull.contains("{") || uri.toString().contains("}");

    return new JsonReference(uri, pointer, absolute, local, warnings, source);
}