Example usage for java.net URISyntaxException URISyntaxException

List of usage examples for java.net URISyntaxException URISyntaxException

Introduction

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

Prototype

public URISyntaxException(String input, String reason) 

Source Link

Document

Constructs an instance from the given input string and reason.

Usage

From source file:com.microsoftopentechnologies.windowsazurestorage.helper.AzureUtils.java

/**
 * Returns suffix for blob endpoint.//from  ww  w.  j  a  v a2s .  c om
 *
 * @param blobURL endpoint
 * @return the endpoint suffix
 */
private static String getEndpointSuffix(final String blobURL) throws URISyntaxException {
    final int endSuffixStartIndex = blobURL.toLowerCase().indexOf(Utils.BLOB_ENDPOINT_ENDSUFFIX_KEYWORD);
    if (endSuffixStartIndex < 0) {
        throw new URISyntaxException(blobURL, "The blob endpoint is not correct!");
    }

    return blobURL.substring(endSuffixStartIndex);
}

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

/**
 * This method takes an URL as input and returns it in a normalized form. There should be no change in the functionality of the URL.
 * @param location the unnormalized URL/*w ww.  j a  v  a 2 s  .c  om*/
 * @param charset the {@link Charset} of the document this link was extracted from. It is needed to transform URL-encoded entities
 *        to Java's Unicode representation. If <code>null</code> is passed, the default charset will be used
 * @return the normalized URL consisting of protocol, username/password if given, hostname, port if it is not the default port for
 *         its protocol, the path and all given query arguments. The fragment part is omitted. It also performs Punycode- and
 *         URL-decoding.
 * @author Roland Ramthun, Franz Brau&szlig;e
 * @throws MalformedURLException if the given URL-String could not be parsed due to inconsistency with the URI-standard
 * 
 * FIXME doesn't handle unescaped characters in other charsets than UTF-8 correctly
 */
public URI parseBaseUrlString(final String url, final Charset charset) throws URISyntaxException {
    /*
     * What happens here?
     * 
     * Every URL has to end with a slash, if it only consists of a scheme and authority.
     * 
     * This slash is a part of the path. Even a simple URL like "http://example.org/" is a mapping on a directory on the server.
     * As directories have to end with a slash, there _must_ be a slash if there is no path given ending with a filename.
     * 
     * In the next step we will remove default ports from the URL.
     * 
     * Then we convert the protocol identifier and the (sub-) domain to lowercase.
     * Case is not important for these parts, for the path it is.
     * 
     * Then we resolve backpaths in the path.
     * 
     * Later the resulting normalized URL is assembled, along this way possible fragments are removed, as they are simply not added
     */

    // init
    String protocol = null;
    String username = null;
    String password = null;
    String host = null;
    int port = -1;
    String path = "/";
    String query = null;
    // String fragment = null;

    // extract the protocol
    int urlStart = 0;
    int colonpos = url.indexOf(':', urlStart);
    if (colonpos <= 0)
        throw new URISyntaxException(url, "No protocol specified");
    protocol = url.substring(0, colonpos).toLowerCase();

    int protocolEnd = colonpos + 1;
    int slashAfterHost = url.indexOf('/', protocolEnd);
    if (url.length() > (colonpos + 1) && url.charAt(colonpos + 1) == '/' && url.charAt(colonpos + 2) == '/') {
        protocolEnd = colonpos + 3;

        slashAfterHost = url.indexOf('/', protocolEnd);
        // extract username / password
        final int at = url.indexOf('@', protocolEnd);
        final int hostStart;
        final int credSepColon = url.indexOf(':', protocolEnd); //the colon which separates username and password
        if (at != -1 && at < slashAfterHost) {
            if (credSepColon > (protocolEnd + 1) && credSepColon < at) {
                username = url.substring(protocolEnd, credSepColon);
                password = url.substring(credSepColon + 1, at);
            } else {
                username = url.substring(protocolEnd, at);
            }
            hostStart = at + 1;
        } else {
            hostStart = protocolEnd;
        }

        // extract the hostname
        final int portColon = url.indexOf(':', hostStart);
        final int hostEndTmp = (slashAfterHost == -1) ? url.length() : slashAfterHost;
        final int hostEnd = (portColon > hostStart && portColon < hostEndTmp) ? portColon : hostEndTmp;
        // TODO: de-punycode
        // host = IDN.toUnicode(url.substring(hostStart, hostEnd).toLowerCase());      // de-punycode (sub-)domain(s) - java 1.6 code
        host = url.substring(hostStart, hostEnd).toLowerCase();

        // extract the port
        final int portEnd = (slashAfterHost == -1) ? url.length() : slashAfterHost;
        if (portColon != -1 && portColon < portEnd) {
            final String portNr = url.substring(portColon + 1, portEnd);
            if (!PORT_PATTERN.matcher(portNr).matches())
                throw new URISyntaxException(url, "Illegal port-number");
            port = Integer.parseInt(portNr);
            if (port < 1 || port > 65535)
                throw new URISyntaxException(url, "Port-number out of range");
        }

        if (includePort ^ port != -1) {
            final Integer defPort = DEFAULT_PORTS.get(protocol);
            if (includePort) {
                // no port value in input, try to get it from the default ports for the protocol
                if (defPort == null)
                    throw new URISyntaxException(url,
                            "no port number given and no default port for protocol '" + protocol + "'");
                port = defPort.intValue();
            } else {
                // don't make default port-number for the protocol part of the resulting url
                if (defPort != null && port == defPort.intValue())
                    port = -1;
            }
        }
    } else if (slashAfterHost == -1) {
        throw new URISyntaxException(url, "No valid protocol identifier given");
    }

    final int hashmark = url.indexOf('#', (slashAfterHost == -1) ? url.length() : slashAfterHost);
    if (slashAfterHost != -1) {
        // extract the path
        final int qmark = url.indexOf('?', slashAfterHost);
        final int pathEnd = (qmark == -1) ? (hashmark == -1) ? url.length() : hashmark : qmark;
        // XXX path = resolveBackpath(urlDecode(url.substring(slashAfterHost, pathEnd), charset));
        path = resolveBackpath(url.substring(slashAfterHost, pathEnd));
        if (appendSlash && qmark == -1 && path.charAt(path.length() - 1) != '/'
                && path.indexOf('.', path.lastIndexOf('/')) == -1) {
            path += '/';
        }

        // extract the query
        if (qmark != -1) {
            final int queryEnd = (hashmark == -1) ? url.length() : hashmark;
            if (queryEnd > qmark + 1) {
                final List<QueryEntry> queryList = new ArrayList<QueryEntry>();
                int paramStart = qmark + 1;
                do {
                    int paramEnd = url.indexOf('&', paramStart);
                    if (paramEnd == -1 || paramEnd > queryEnd)
                        paramEnd = queryEnd;
                    if (paramEnd > paramStart) {
                        int eq = url.indexOf('=', paramStart);
                        if (eq == -1 || eq > paramEnd)
                            eq = paramEnd;

                        try {
                            String key = url.substring(paramStart, eq);
                            try {
                                // urlDecode(key.replace('+', ' '), charset);
                                key = URLDecoder.decode(key, charset.name());
                            } catch (IllegalArgumentException e) {
                                // Illegal hex characters in escape (%) pattern
                                logger.debug("error URL-decoding query-key '" + key + "': " + e.getMessage());
                                // treat key as already replaced
                            }

                            String val = (eq < paramEnd) ? url.substring(eq + 1, paramEnd) : null;
                            if (val != null)
                                try {
                                    // urlDecode(val.replace('+', ' '), charset)
                                    val = URLDecoder.decode(val, charset.name());
                                } catch (IllegalArgumentException e) {
                                    // Illegal hex characters in escape (%) pattern
                                    logger.debug(
                                            "error URL-decoding query-value '" + val + "': " + e.getMessage());
                                    // treat val as already replaced
                                }

                            // System.out.println("query arg: " + key + " <-> " + val);
                            queryList.add(new QueryEntry(key, val));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    paramStart = paramEnd + 1;
                } while (paramStart < queryEnd);
                if (sortQuery)
                    Collections.sort(queryList);
                try {
                    final StringBuilder sb = new StringBuilder(queryEnd - qmark);
                    for (QueryEntry e : queryList) {
                        sb.append(URLEncoder.encode(e.key, "UTF-8"));
                        final String val = e.val;
                        if (val != null)
                            sb.append('=').append(URLEncoder.encode(val, "UTF-8"));
                        sb.append('&');
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    query = sb.toString();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }

        // extract the fragment
        if (hashmark != -1)
            // XXX fragment = urlDecode(url.substring(hashmark + 1), charset);
            // fragment = url.substring(hashmark + 1);
            ;
    }

    // output
    final StringBuilder sb = new StringBuilder();
    sb.append(protocol).append(":");
    if (host != null) {
        sb.append("//");
        if (username != null) {
            sb.append(username);
            if (password != null)
                sb.append(':').append(password);
            sb.append('@');
        }
        sb.append(host);
        if (port != -1)
            sb.append(':').append(port);
    }
    sb.append(path);
    if (query != null)
        sb.append('?').append(query);

    return new URI(sb.toString());
}

From source file:fi.mystes.synapse.mediator.ReadFileMediator.java

/**
 * Helper method to initialize file to read content from. Will try to get file name
 * first from fileName attribute. If it fails, it will try to read file name from property.
 * /*  www.  j  a va2s  .  c om*/
 * @param context Contains property which may hold XML file name.
 * 
 * @return Reference to file object
 * @throws URISyntaxException 
 * @throws SftpException 
 * @throws JSchException 
 * @throws FileNotFoundException 
 * @throws IOException 
 */
private InputStream initProcessableFile(MessageContext context)
        throws URISyntaxException, JSchException, SftpException, FileNotFoundException {
    InputStream fileToProcess = null;
    if (fileName != null) {
        URI aURI = new URI(fileName);

        if (aURI.getScheme().equals("file"))
            fileToProcess = new FileInputStream(new File(aURI));

        else if (aURI.getScheme().equals("ftp") || aURI.getScheme().equals("sftp"))
            fileToProcess = processFtpSftpInput(aURI);

        else
            throw new URISyntaxException(fileName, "Unknown protocol");

    } else if (property != null) {
        fileToProcess = new FileInputStream(new File((String) context.getProperty(property)));
    }
    return fileToProcess;
}

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

/**
 * Downloads file from remote .git repository with specified commit.
 * @param git repository address with .git ending
 * @param tag tag or commit to clone from; the latest commit will be downloaded if null
 * @param file relative to repository's root path to file; the whole repository will be downloaded if null
 * @param output symbolic link to the directory on the local file system where the downloaded file will be stored
 * @throws FileAlreadyExistsException if output file has already exists
 * @throws FileNotFoundException if repository doesn't exist
 * @throws URISyntaxException if URI has unsupported or wrong format
 * @throws IOException if operation couldn't be successfully completed because of other reasons
 *//*from  w ww.  jav  a  2 s. co  m*/
public static void downloadFileFromGit(@NonNull URI git, @Nullable String tag, @Nullable Path file,
        @NonNull File output)
        throws FileAlreadyExistsException, FileNotFoundException, URISyntaxException, IOException {

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

    if (!output.mkdir()) {
        throw new IOException("Couldn't create directory " + output);
    }

    String gitRepo = git.toString();

    if (!gitRepo.endsWith(".git")) {
        throw new URISyntaxException(gitRepo, "doesn't match expected pattern");
    }
    String svnCommandAddress = gitRepo.substring(0, gitRepo.length() - 4)
            + (tag == null ? "/trunk/" : "/tags/" + tag + "/") + (file == null ? "" : file.toString());
    try {
        Svn.export(output, svnCommandAddress);
    } catch (SvnNotFoundException e) {
        throw new IOException(e.getMessage());
    } catch (ConnectionException e) {
        throw new IOException(e.getMessage());
    } catch (RepositoryNotFoundException e) {
        throw new FileNotFoundException(e.getMessage());
    } catch (NotDirectoryException e) {
        // this is not realizable case
        e.printStackTrace();
    }
}

From source file:URISupport.java

public static String createQueryString(Map options) throws URISyntaxException {
    try {//w ww.  j  a va2s . c  om
        if (options.size() > 0) {
            StringBuffer rc = new StringBuffer();
            boolean first = true;
            for (Iterator iter = options.keySet().iterator(); iter.hasNext();) {
                if (first) {
                    first = false;
                } else {
                    rc.append("&");
                }
                String key = (String) iter.next();
                String value = (String) options.get(key);
                rc.append(URLEncoder.encode(key, "UTF-8"));
                rc.append("=");
                rc.append(URLEncoder.encode(value, "UTF-8"));
            }
            return rc.toString();
        } else {
            return "";
        }
    } catch (UnsupportedEncodingException e) {
        throw (URISyntaxException) new URISyntaxException(e.toString(), "Invalid encoding").initCause(e);
    }
}

From source file:com.granita.icloudcalsync.resource.RemoteCollection.java

Resource.AssetDownloader getDownloader() {
    return new Resource.AssetDownloader() {
        @Override//from   w w  w  .j a v  a2s . com
        public byte[] download(URI uri) throws URISyntaxException, IOException, HttpException, DavException {
            if (!uri.isAbsolute())
                throw new URISyntaxException(uri.toString(), "URI referenced from entity must be absolute");

            if (uri.getScheme().equalsIgnoreCase(baseURI.getScheme())
                    && uri.getAuthority().equalsIgnoreCase(baseURI.getAuthority())) {
                // resource is on same server, send Authorization
                WebDavResource file = new WebDavResource(collection, uri);
                file.get("image/*");
                return file.getContent();
            } else {
                // resource is on an external server, don't send Authorization
                return IOUtils.toByteArray(uri);
            }
        }
    };
}

From source file:at.bitfire.davdroid.resource.WebDavCollection.java

Resource.AssetDownloader getDownloader() {
    return new Resource.AssetDownloader() {
        @Override/*from w  w  w  .  jav  a2s.  c  o m*/
        public byte[] download(URI uri) throws URISyntaxException, IOException, HttpException, DavException {
            if (!uri.isAbsolute())
                throw new URISyntaxException(uri.toString(), "URI referenced from entity must be absolute");

            // send credentials when asset has same URI authority as baseURI
            // we have to construct these helper URIs because
            // "https://server:443" is NOT equal to "https://server" otherwise
            URI baseUriAuthority = new URI(baseURI.getScheme(), null, baseURI.getHost(), baseURI.getPort(),
                    null, null, null),
                    assetUriAuthority = new URI(uri.getScheme(), null, uri.getHost(), baseURI.getPort(), null,
                            null, null);

            if (baseUriAuthority.equals(assetUriAuthority)) {
                Log.d(TAG, "Asset is on same server, sending credentials");
                WebDavResource file = new WebDavResource(collection, uri);
                file.get("image/*");
                return file.getContent();

            } else
                // resource is on an external server, don't send credentials
                return IOUtils.toByteArray(uri);
        }
    };
}

From source file:org.opentravel.schemacompiler.security.impl.DefaultAuthorizationProvider.java

/**
 * Returns the namespace hierarchy in the order that it must be traversed in order to determine
 * a user's authorization scheme.//  w w w .j a  v  a2  s  . c o  m
 * 
 * @param namespace
 *            the namespace for which to return the hierarchy
 * @return List<String>
 * @throws RepositorySecurityException
 *             thrown if the namespace URI is not valid
 */
private List<String> getNamespaceHierarchy(String namespace) throws RepositorySecurityException {
    try {
        List<String> hierarchy = new ArrayList<String>();
        URI ns = new URI(namespace);
        String nsScheme = ns.getScheme();
        String nsAuthority = ns.getAuthority();
        String nsPath = ns.getPath();

        hierarchy.add(null); // null hierarchy member represents global authorizations

        if ((nsScheme != null) && (nsAuthority != null) && (nsPath != null)) {
            String[] pathParts = ns.getPath().split("/");
            StringBuilder nsBuilder = new StringBuilder();

            nsBuilder.append(nsScheme).append("://").append(nsAuthority);
            hierarchy.add(nsBuilder.toString());

            for (String pathPart : pathParts) {
                if ((pathPart != null) && !pathPart.equals("")) {
                    nsBuilder.append("/").append(pathPart);
                    hierarchy.add(nsBuilder.toString());
                }
            }
        } else {
            throw new URISyntaxException(namespace, "Invalid namespace URI format.");
        }
        return hierarchy;

    } catch (URISyntaxException e) {
        throw new RepositorySecurityException(
                "Unable to determine security hierarchy for namespace: " + namespace, e);
    }
}

From source file:org.apache.cocoon.servletservice.ServletServiceContext.java

/**
 * Takes the scheme specific part of a servlet service URI (the scheme is the
 * responsibilty of the ServletSource) and resolve it with respect to the
 * servlets mount point.//from www.  ja v a  2 s.  co m
 */
public URI absolutizeURI(URI uri) throws URISyntaxException {
    String servletServiceName = uri.getScheme();
    ServletServiceContext servletServiceContext;
    if (servletServiceName == null) {
        // this servlet service
        servletServiceContext = this;
    } else {
        // another servlet service
        servletServiceContext = (ServletServiceContext) this.getNamedContext(servletServiceName);
        if (servletServiceContext == null) {
            throw new URISyntaxException(uri.toString(), "Unknown servlet service name");
        }
    }

    String mountPath = servletServiceContext.getMountPath();
    if (mountPath == null) {
        throw new URISyntaxException(uri.toString(), "No mount point for this URI");
    }
    if (mountPath.endsWith("/")) {
        mountPath = mountPath.substring(0, mountPath.length() - 1);
    }

    String absoluteURI = mountPath + uri.getSchemeSpecificPart();
    if (logger.isInfoEnabled()) {
        logger.info("Resolving " + uri.toString() + " to " + absoluteURI);
    }

    return new URI(absoluteURI);
}

From source file:com.granita.icloudcalsync.resource.DavResourceFinder.java

/**
 * Finds the initial service URL from a given base URI (HTTP[S] or mailto URI, user name, password)
 * @param serverInfo   User-given service information (including base URI, i.e. HTTP[S] URL+user name+password or mailto URI and password)
 * @param serviceName   Service name ("carddav" or "caldav")
 * @return            Initial service URL (HTTP/HTTPS), without user credentials
 * @throws URISyntaxException when the user-given URI is invalid
 * @throws MalformedURLException when the user-given URI is invalid
 *///from   w w  w  . j  a va 2s.  c o  m
public URI getInitialContextURL(ServerInfo serverInfo, String serviceName)
        throws URISyntaxException, MalformedURLException {
    String scheme = null, domain;
    int port = -1;
    String path = "/";

    URI baseURI = serverInfo.getBaseURI();
    if ("mailto".equalsIgnoreCase(baseURI.getScheme())) {
        // mailto URIs
        String mailbox = serverInfo.getBaseURI().getSchemeSpecificPart();

        // determine service FQDN
        int pos = mailbox.lastIndexOf("@");
        if (pos == -1)
            throw new URISyntaxException(mailbox, "Missing @ sign");

        scheme = "https";
        domain = mailbox.substring(pos + 1);
        if (domain.isEmpty())
            throw new URISyntaxException(mailbox, "Missing domain name");
    } else {
        // HTTP(S) URLs
        scheme = baseURI.getScheme();
        domain = baseURI.getHost();
        port = baseURI.getPort();
        path = baseURI.getPath();
    }

    // try to determine FQDN and port number using SRV records
    try {
        String name = "_" + serviceName + "s._tcp." + domain;
        Log.d(TAG, "Looking up SRV records for " + name);
        Record[] records = new Lookup(name, Type.SRV).run();
        if (records != null && records.length >= 1) {
            SRVRecord srv = selectSRVRecord(records);

            scheme = "https";
            domain = srv.getTarget().toString(true);
            port = srv.getPort();
            Log.d(TAG, "Found " + serviceName + "s service for " + domain + " -> " + domain + ":" + port);

            if (port == 443) // no reason to explicitly give the default port
                port = -1;

            // SRV record found, look for TXT record too (for initial context path)
            records = new Lookup(name, Type.TXT).run();
            if (records != null && records.length >= 1) {
                TXTRecord txt = (TXTRecord) records[0];
                for (Object o : txt.getStrings().toArray()) {
                    String segment = (String) o;
                    if (segment.startsWith("path=")) {
                        path = segment.substring(5);
                        Log.d(TAG, "Found initial context path for " + serviceName + " at " + domain + " -> "
                                + path);
                        break;
                    }
                }
            }
        }
    } catch (TextParseException e) {
        throw new URISyntaxException(domain, "Invalid domain name");
    }

    return new URI(scheme, null, domain, port, path, null, null);
}