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.seajas.search.utilities.web.WebResourceLocators.java

/**
 * Gets a resource locator.//from w  w w  .j  a  v  a 2s .c  om
 * 
 * @param uri
 * @throws URISyntaxException
 */
public static URI parseURI(String uri) throws URISyntaxException {
    if (!StringUtils.hasText(uri))
        throw new URISyntaxException("", "No content");
    uri = uri.trim();

    // Escape illegal characters

    for (int i = 0; i < uri.length(); ++i) {
        char c = uri.charAt(i);
        if (ASCII_ESCAPE_SET.indexOf(c) >= 0)
            uri = String.format("%s%%%02X%s", uri.substring(0, i), c & 0xFF, uri.substring(i + 1));
    }

    // Parse XML entities

    for (int start = uri.indexOf('&'); start >= 0; start = uri.indexOf('&', start + 1)) {
        int end = uri.indexOf(';', start);
        if (end < 0)
            break;
        String entity = uri.substring(start + 1, end);

        String replacement = null;
        if (entity.startsWith("#")) {
            try {
                int codepoint = entity.startsWith("#x") ? Integer.parseInt(entity.substring(2), 16)
                        : Integer.parseInt(entity.substring(1));
                if (codepoint <= 0xFF)
                    replacement = String.format("%%%02X", codepoint);
                else
                    replacement = new String(Character.toChars(codepoint));
            } catch (Exception e) {
                logger.trace("Unparseable numeric entity.", e);
            }
        } else {
            replacement = xmlEntityPercentEscapes.get(entity);
        }

        if (replacement != null) {
            if (logger.isDebugEnabled())
                logger.debug(String.format("Replaced entity %s with %s for %s", entity, replacement, uri));
            uri = uri.substring(0, start) + replacement + uri.substring(end + 1);
        } else if (logger.isDebugEnabled()) {
            logger.debug(String.format("Skiped entity %s for %s", entity, uri));
        }
    }

    // Multiple fragments

    while (uri.indexOf('#') != uri.lastIndexOf('#')) {
        int i = uri.lastIndexOf('#');

        // Escape last hash mark

        uri = uri.substring(0, i) + "%23" + uri.substring(i + 1);
    }

    return new URI(uri).normalize();
}

From source file:org.dthume.maven.xpom.impl.saxon.XPomUri.java

public XPomUri(final String uriString) throws URISyntaxException {
    if (null == uriString)
        throw new URISyntaxException(uriString, "Cannot parse null URI");

    final URI jUri = new URI(uriString);

    if (!"xpom".equals(jUri.getScheme())) {
        throw new URISyntaxException(uriString, "Not in xpom://<coords>[/<path>] format");
    }/*from   www  . ja v  a  2  s.c  o m*/

    final Matcher matcher = ARTIFACT_PATTERN.matcher(jUri.getPath());
    if (!matcher.matches()) {
        throw new URISyntaxException(uriString, "XPOM scheme but not in xpom://<coords>[/<path>] format");
    }

    final String groupId = jUri.getAuthority();

    coords = toCoords(matcher, groupId);
    resource = toResource(matcher);
    params = unmodifiableMap(toParams(jUri.getQuery()));
}

From source file:net.oneandone.shared.artifactory.UtilsTest.java

/**
 * Test of toUri method, of class Utils.
 *//*from   www .ja  v a2s. c om*/
@Test(expected = IllegalArgumentException.class)
public void testToUriFailing() throws URISyntaxException {
    URIBuilder mockUriBuilder = mock(URIBuilder.class);
    when(mockUriBuilder.build()).thenThrow(new URISyntaxException("Oops", "Oops"));
    Utils.toUri(mockUriBuilder, "does not matter");
}

From source file:edu.jhu.pha.vospace.node.VospaceId.java

public VospaceId(String idStr) throws URISyntaxException {
    URI voURI = new URI(idStr);

    if (!validId(voURI)) {
        throw new URISyntaxException(idStr, "InvalidURI");
    }//from   w  w  w.  j a va 2  s  .  com

    if (!StringUtils.contains(idStr, "vospace")) {
        throw new URISyntaxException(idStr, "InvalidURI");
    }

    this.uri = StringUtils.substringBetween(idStr, "vos://", "!vospace");

    if (this.uri == null)
        throw new URISyntaxException(idStr, "InvalidURI");

    try {
        String pathStr = URLDecoder.decode(StringUtils.substringAfter(idStr, "!vospace"), "UTF-8");
        this.nodePath = new NodePath(pathStr);
    } catch (UnsupportedEncodingException e) {
        // should not happen
        logger.error(e.getMessage());
    }

}

From source file:com.nesscomputing.service.discovery.client.ServiceURI.java

public ServiceURI(final URI uri) throws URISyntaxException {
    if (!"srvc".equals(uri.getScheme())) {
        throw new URISyntaxException(uri.toString(), "ServiceURI only supports srvc:// URIs");
    }// ww  w  .  j  av a 2 s  .  co m
    if (!StringUtils.startsWith(uri.getSchemeSpecificPart(), "//")) {
        throw new URISyntaxException(uri.toString(), "ServiceURI only supports srvc:// URIs");
    }

    final String schemeSpecificPart = uri.getSchemeSpecificPart().substring(2);
    final int slashIndex = schemeSpecificPart.indexOf('/');
    if (slashIndex == -1) {
        throw new URISyntaxException(uri.toString(), "ServiceURI requires a slash at the end of the service!");
    }
    final int colonIndex = schemeSpecificPart.indexOf(':');
    if (colonIndex == -1 || colonIndex > slashIndex) {
        serviceName = schemeSpecificPart.substring(0, slashIndex);
        serviceType = null;
    } else {
        serviceName = schemeSpecificPart.substring(0, colonIndex);
        serviceType = schemeSpecificPart.substring(colonIndex + 1, slashIndex);
    }

    path = uri.getRawPath();
    query = uri.getRawQuery();
    fragment = uri.getRawFragment();
}

From source file:org.apache.any23.source.HTTPDocumentSource.java

private String normalize(String uri) throws URISyntaxException {
    try {//from w  ww  . j  a  va  2 s .co m
        URI normalized = new URI(uri, DefaultHTTPClient.isUrlEncoded(uri));
        normalized.normalize();
        return normalized.toString();
    } catch (URIException e) {
        LOG.warn("Invalid uri: {}", uri);
        LOG.error("Can not convert URL", e);
        throw new URISyntaxException(uri, e.getMessage());
    }
}

From source file:ste.web.http.api.RRequest.java

/**
 * /* w  w w  .j  a v  a2  s  . c o  m*/
 * @param request - NOT NULL
 * @param body - MAY BE NULL
 * 
 * @throws URISyntaxException if the given request has an invalid URI
 * @throws IllegalArgumentException if request is null
 * 
 */
public RRequest(final RequestLine request, final JSONObject body) throws URISyntaxException {
    if (request == null) {
        throw new IllegalArgumentException("request can not be null");
    }

    uri = new URI(request.getUri());
    String[] elements = StringUtils.split(uri.getPath(), '/');

    if (elements.length < 3) {
        throw new URISyntaxException(uri.toString(),
                "invalid rest request; a valid rest url shall follow the syntax /api/<action>/<resource>");
    }
    action = elements[1];
    handler = elements[2];

    resource = Arrays.copyOfRange(elements, 2, elements.length);

    this.body = body;
}

From source file:Main.java

/** Crea una URI a partir de un nombre de fichero local o una URL.
 * @param file Nombre del fichero local o URL
 * @return URI (<code>file://</code>) del fichero local o URL
 * @throws URISyntaxException Si no se puede crear una URI soportada a partir de la cadena de entrada */
public static URI createURI(final String file) throws URISyntaxException {

    if (file == null || file.isEmpty()) {
        throw new IllegalArgumentException("No se puede crear una URI a partir de un nulo"); //$NON-NLS-1$
    }//  w w  w.  jav a  2s  .  c om

    String filename = file.trim();

    if (filename.isEmpty()) {
        throw new IllegalArgumentException("La URI no puede ser una cadena vacia"); //$NON-NLS-1$
    }

    // Cambiamos los caracteres Windows
    filename = filename.replace('\\', '/');

    // Realizamos los cambios necesarios para proteger los caracteres no
    // seguros
    // de la URL
    filename = filename.replace(" ", "%20") //$NON-NLS-1$ //$NON-NLS-2$
            .replace("<", "%3C") //$NON-NLS-1$ //$NON-NLS-2$
            .replace(">", "%3E") //$NON-NLS-1$ //$NON-NLS-2$
            .replace("\"", "%22") //$NON-NLS-1$ //$NON-NLS-2$
            .replace("{", "%7B") //$NON-NLS-1$ //$NON-NLS-2$
            .replace("}", "%7D") //$NON-NLS-1$ //$NON-NLS-2$
            .replace("|", "%7C") //$NON-NLS-1$ //$NON-NLS-2$
            .replace("^", "%5E") //$NON-NLS-1$ //$NON-NLS-2$
            .replace("[", "%5B") //$NON-NLS-1$ //$NON-NLS-2$
            .replace("]", "%5D") //$NON-NLS-1$ //$NON-NLS-2$
            .replace("`", "%60"); //$NON-NLS-1$ //$NON-NLS-2$

    final URI uri = new URI(filename);

    // Comprobamos si es un esquema soportado
    final String scheme = uri.getScheme();
    for (final String element : SUPPORTED_URI_SCHEMES) {
        if (element.equals(scheme)) {
            return uri;
        }
    }

    // Si el esquema es nulo, aun puede ser un nombre de fichero valido
    // El caracter '#' debe protegerse en rutas locales
    if (scheme == null) {
        filename = filename.replace("#", "%23"); //$NON-NLS-1$ //$NON-NLS-2$
        return createURI("file://" + filename); //$NON-NLS-1$
    }

    // Miramos si el esquema es una letra, en cuyo caso seguro que es una
    // unidad de Windows ("C:", "D:", etc.), y le anado el file://
    // El caracter '#' debe protegerse en rutas locales
    if (scheme.length() == 1 && Character.isLetter((char) scheme.getBytes()[0])) {
        filename = filename.replace("#", "%23"); //$NON-NLS-1$ //$NON-NLS-2$
        return createURI("file://" + filename); //$NON-NLS-1$
    }

    throw new URISyntaxException(filename, "Tipo de URI no soportado"); //$NON-NLS-1$

}

From source file:org.jasig.portlet.calendar.adapter.exchange.CommonsHttpConnection.java

public URI getUri() throws URISyntaxException {
    try {/*from ww w  . j ava 2s .co m*/
        return new URI(postMethod.getURI().toString());
    } catch (URIException ex) {
        throw new URISyntaxException("", ex.getMessage());
    }
}

From source file:com.seajas.search.profiler.wsdl.FeedTesting.java

/**
 * {@inheritDoc}//from w  w w  .j a  v  a2 s  . co  m
 */
@Override
public FeedResult isValidFeedUrl(final String url, final Boolean ignoreExisting) {
    FeedResult result = new FeedResult();

    if (!Boolean.TRUE.equals(ignoreExisting)) {
        List<Feed> existingFeeds = profilerService.getFeedsByUrl(url);

        if (existingFeeds != null && existingFeeds.size() > 0) {
            if (logger.isInfoEnabled())
                logger.info("The given feed URL already exists");

            result.setStatus(Status.ALREADY_EXISTS);

            return result;
        }
    }

    // Validate the URL first

    URI validatedUri;

    try {
        validatedUri = new URI(url);

        if (!StringUtils.hasText(validatedUri.getScheme()) || !StringUtils.hasText(validatedUri.getHost()))
            throw new URISyntaxException("", "No scheme and/or host provided");
    } catch (URISyntaxException e) {
        if (logger.isInfoEnabled())
            logger.info("The given feed URL is not valid", e);

        result.setStatus(Status.UNKNOWN);

        return result;
    }

    // Then run it through the testing service for exploration

    try {
        Map<String, Boolean> testingResult = testingService.exploreUri(validatedUri);

        if (logger.isInfoEnabled())
            logger.info("Exploration resulted in " + testingResult.size() + " result URL(s)");

        List<String> validUrls = new ArrayList<String>();

        for (Entry<String, Boolean> testingResultEntry : testingResult.entrySet()) {
            validUrls.add(testingResultEntry.getKey());

            if (testingResultEntry.getValue()) {
                if (logger.isInfoEnabled())
                    logger.info("The given URL '" + url + "' is a direct RSS feed");

                result.setStatus(Status.VALID);

                break;
            } else
                result.setStatus(Status.INDIRECTLY_VALID);
        }

        result.setValidUrls(validUrls);
    } catch (TestingException e) {
        if (logger.isInfoEnabled())
            logger.info("URL exploration was unsuccessful", e);

        result.setStatus(Status.UNKNOWN);
    }

    return result;
}