Example usage for java.net URISyntaxException getMessage

List of usage examples for java.net URISyntaxException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns a string describing the parse error.

Usage

From source file:com.espertech.esper.client.ConfigurationParser.java

private static void handlePlugIneventTypeNameResolution(Configuration configuration, Element element) {
    DOMElementIterator nodeIterator = new DOMElementIterator(element.getChildNodes());
    List<URI> uris = new ArrayList<URI>();
    while (nodeIterator.hasNext()) {
        Element subElement = nodeIterator.next();
        if (subElement.getNodeName().equals("resolution-uri")) {
            String uriValue = getRequiredAttribute(subElement, "value");
            URI uri;//from  w w w.  j a  v a  2  s . c  o  m
            try {
                uri = new URI(uriValue);
            } catch (URISyntaxException ex) {
                throw new ConfigurationException("Error parsing URI '" + uriValue
                        + "' as a valid java.net.URI string:" + ex.getMessage(), ex);
            }
            uris.add(uri);
        }
    }

    configuration.setPlugInEventTypeResolutionURIs(uris.toArray(new URI[uris.size()]));
}

From source file:eu.freme.broker.eservices.ELink.java

@RequestMapping(value = "/e-link/templates/{templateid}", method = RequestMethod.PUT)
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> updateTemplateById(
        @RequestHeader(value = "Accept", required = false) String acceptHeader,
        @RequestHeader(value = "Content-Type", required = false) String contentTypeHeader,
        // @RequestParam(value = "informat", required=false) String
        // informat,
        // @RequestParam(value = "f", required=false) String f,
        // @RequestParam(value = "outformat", required=false) String
        // outformat,
        // @RequestParam(value = "o", required=false) String o,
        @RequestParam(value = "owner", required = false) String ownerName,
        @PathVariable("templateid") long templateId, @RequestParam Map<String, String> allParams,
        @RequestBody String postBody) {

    try {/* ww  w.  j  a  va2  s .co  m*/
        // NOTE: informat was defaulted to JSON before! Now it is TURTLE.
        // NOTE: outformat was defaulted to turtle, if acceptHeader=="*/*"
        // and informat==null, otherwise to JSON. Now it is TURTLE.
        NIFParameterSet nifParameters = this.normalizeNif(postBody, acceptHeader, contentTypeHeader, allParams,
                true);

        // validateTemplateID(templateId);
        // check read access
        Template template = templateDAO.findOneById(templateId);

        // Was the nif-input empty?
        if (nifParameters.getInput() != null) {
            if (nifParameters.getInformat().equals(RDFConstants.RDFSerialization.JSON)) {
                JSONObject jsonObj = new JSONObject(nifParameters.getInput());
                template.update(jsonObj);
            } else {
                Model model = rdfConversionService.unserializeRDF(nifParameters.getInput(),
                        nifParameters.getInformat());
                template.setTemplateWithModel(model);
            }
        }

        template = templateDAO.save(template);

        if (!Strings.isNullOrEmpty(ownerName)) {
            User owner = userDAO.getRepository().findOneByName(ownerName);
            if (owner == null)
                throw new BadRequestException(
                        "Can not change owner of the template. User \"" + ownerName + "\" does not exist.");
            template = templateDAO.updateOwner(template, owner);
        }

        String serialization;
        if (nifParameters.getOutformat().equals(RDFConstants.RDFSerialization.JSON)) {
            ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
            serialization = ow.writeValueAsString(template);
        } else {
            serialization = rdfConversionService.serializeRDF(template.getRDF(), nifParameters.getOutformat());
        }

        HttpHeaders responseHeaders = new HttpHeaders();
        URI location = new URI("/e-link/templates/" + template.getId());
        responseHeaders.setLocation(location);
        responseHeaders.set("Content-Type", nifParameters.getOutformat().contentType());
        return new ResponseEntity<>(serialization, responseHeaders, HttpStatus.OK);
    } catch (URISyntaxException ex) {
        logger.error(ex.getMessage(), ex);
        throw new BadRequestException(ex.getMessage());
    } catch (AccessDeniedException ex) {
        logger.error(ex.getMessage(), ex);
        throw new eu.freme.broker.exception.AccessDeniedException();
    } catch (BadRequestException ex) {
        logger.error(ex.getMessage(), ex);
        throw ex;
    } catch (OwnedResourceNotFoundException ex) {
        logger.error(ex.getMessage(), ex);
        throw new TemplateNotFoundException("Template not found. " + ex.getMessage());
    } catch (org.json.JSONException ex) {
        logger.error(ex.getMessage(), ex);
        throw new BadRequestException(
                "The JSON object is incorrectly formatted. Problem description: " + ex.getMessage());
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
    throw new InternalServerErrorException("Unknown problem. Please contact us.");
}

From source file:jproxy.HttpRequestHdr.java

private void parseFirstLine(String firstLine) {
    this.firstLine = firstLine;
    if (log.isDebugEnabled()) {
        log.debug("browser request: " + firstLine.replaceFirst("\r\n$", "<CRLF>"));
    }/*from w w w  .  j a v  a  2 s . c om*/
    StringTokenizer tz = new StringTokenizer(firstLine);
    method = getToken(tz).toUpperCase(java.util.Locale.ENGLISH);
    url = getToken(tz);
    version = getToken(tz);
    if (log.isDebugEnabled()) {
        log.debug("parsed method:   " + method);
        log.debug("parsed url/host: " + url); // will be host:port for CONNECT
        log.debug("parsed version:  " + version);
    }
    // SSL connection
    if (getMethod().startsWith(HTTPConstants.CONNECT)) {
        paramHttps = url;
        return; // Don't try to adjust the host name
    }
    /* The next line looks odd, but proxied HTTP requests look like:
     * GET http://www.apache.org/foundation/ HTTP/1.1
     * i.e. url starts with "http:", not "/"
     * whereas HTTPS proxy requests look like:
     * CONNECT www.google.co.uk:443 HTTP/1.1
     * followed by
     * GET /?gws_rd=cr HTTP/1.1
     */
    if (url.startsWith("/")) { // it must be a proxied HTTPS request
        url = HTTPS + "://" + paramHttps + url; // $NON-NLS-1$
    }
    // JAVA Impl accepts URLs with unsafe characters so don't do anything
    if (HTTPSamplerFactory.IMPL_JAVA.equals(httpSamplerName)) {
        log.debug("First Line url: " + url);
        return;
    }
    try {
        // See Bug 54482
        URI testCleanUri = new URI(url);
        if (log.isDebugEnabled()) {
            log.debug("Successfully built URI from url:" + url + " => " + testCleanUri.toString());
        }
    } catch (URISyntaxException e) {
        log.warn("Url '" + url + "' contains unsafe characters, will escape it, message:" + e.getMessage());
        try {
            String escapedUrl = ConversionUtils.escapeIllegalURLCharacters(url);
            if (log.isDebugEnabled()) {
                log.debug("Successfully escaped url:'" + url + "' to:'" + escapedUrl + "'");
            }
            url = escapedUrl;
        } catch (Exception e1) {
            log.error("Error escaping URL:'" + url + "', message:" + e1.getMessage());
        }
    }
    log.debug("First Line url: " + url);
}

From source file:org.apache.synapse.transport.nhttp.Axis2HttpRequest.java

/**
 * Create and return a new HttpPost request to the destination EPR
 *
 * @return the HttpRequest to be sent out
 * @throws IOException in error retrieving the <code>HttpRequest</code>
 *///from  www  .j a va 2  s.co m
public HttpRequest getRequest() throws IOException, HttpException {
    String httpMethod = (String) msgContext.getProperty(Constants.Configuration.HTTP_METHOD);
    if (httpMethod == null) {
        httpMethod = "POST";
    }
    endpointURLPrefix = (String) msgContext.getProperty(NhttpConstants.ENDPOINT_PREFIX);

    boolean forceHTTP10 = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0);
    HttpVersion httpver = forceHTTP10 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;

    HttpRequest httpRequest;

    try {
        if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)) {

            URI uri = rewriteRequestURI(new URI(epr.getAddress()));
            BasicHttpEntityEnclosingRequest requestWithEntity = new BasicHttpEntityEnclosingRequest(httpMethod,
                    uri.toASCIIString(), httpver);

            BasicHttpEntity entity = new BasicHttpEntity();

            if (forceHTTP10) {
                setStreamAsTempData(entity);
            } else {
                entity.setChunked(chunked);
                if (!chunked) {
                    setStreamAsTempData(entity);
                }
            }
            requestWithEntity.setEntity(entity);
            requestWithEntity.setHeader(HTTP.CONTENT_TYPE,
                    messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
            httpRequest = requestWithEntity;

        } else if ("GET".equals(httpMethod) || "DELETE".equals(httpMethod)) {

            URL url = messageFormatter.getTargetAddress(msgContext, format, new URL(epr.getAddress()));

            URI uri = rewriteRequestURI(url.toURI());
            httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver);
            /*GETs and DELETEs do not need Content-Type headers because they do not have payloads*/
            //httpRequest.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType(
            //        msgContext, format, msgContext.getSoapAction()));

        } else {
            URI uri = rewriteRequestURI(new URI(epr.getAddress()));
            httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver);
        }

    } catch (URISyntaxException ex) {
        throw new HttpException(ex.getMessage(), ex);
    }

    // set any transport headers
    Object o = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (o != null && o instanceof Map) {
        Map headers = (Map) o;
        for (Object header : headers.keySet()) {
            Object value = headers.get(header);
            if (header instanceof String && value != null && value instanceof String) {
                if (!HTTPConstants.HEADER_HOST.equalsIgnoreCase((String) header)) {
                    httpRequest.setHeader((String) header, (String) value);

                    String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;

                    Map map = (Map) msgContext.getProperty(excessProp);
                    if (map != null && map.get(header) != null) {
                        log.debug("Number of excess values for " + header + " header is : "
                                + ((Collection) (map.get(header))).size());

                        for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
                            String key = (String) iterator.next();

                            for (String excessVal : (Collection<String>) map.get(key)) {
                                httpRequest.addHeader((String) header, (String) excessVal);
                            }

                        }
                    }

                } else {
                    if (msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER) != null) {
                        httpRequest.setHeader((String) header,
                                (String) msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER));
                    }
                }

            }
        }
    }

    // if the message is SOAP 11 (for which a SOAPAction is *required*), and
    // the msg context has a SOAPAction or a WSA-Action (give pref to SOAPAction)
    // use that over any transport header that may be available
    String soapAction = msgContext.getSoapAction();
    if (soapAction == null) {
        soapAction = msgContext.getWSAAction();
    }
    if (soapAction == null) {
        msgContext.getAxisOperation().getInputAction();
    }

    if (msgContext.isSOAP11() && soapAction != null && soapAction.length() >= 0) {
        Header existingHeader = httpRequest.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
        if (existingHeader != null) {
            httpRequest.removeHeader(existingHeader);
        }
        httpRequest.setHeader(HTTPConstants.HEADER_SOAP_ACTION,
                messageFormatter.formatSOAPAction(msgContext, null, soapAction));
    }

    if (NHttpConfiguration.getInstance().isKeepAliveDisabled()
            || msgContext.isPropertyTrue(NhttpConstants.NO_KEEPALIVE)) {
        httpRequest.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
    }

    return httpRequest;
}

From source file:com.espertech.esper.client.ConfigurationParser.java

private static void handlePlugInEventType(Configuration configuration, Element element) {
    DOMElementIterator nodeIterator = new DOMElementIterator(element.getChildNodes());
    List<URI> uris = new ArrayList<URI>();
    String name = getRequiredAttribute(element, "name");
    String initializer = null;/*from   w w w .  j av a  2s.c om*/
    while (nodeIterator.hasNext()) {
        Element subElement = nodeIterator.next();
        if (subElement.getNodeName().equals("resolution-uri")) {
            String uriValue = getRequiredAttribute(subElement, "value");
            URI uri;
            try {
                uri = new URI(uriValue);
            } catch (URISyntaxException ex) {
                throw new ConfigurationException("Error parsing URI '" + uriValue
                        + "' as a valid java.net.URI string:" + ex.getMessage(), ex);
            }
            uris.add(uri);
        }
        if (subElement.getNodeName().equals("initializer")) {
            DOMElementIterator nodeIter = new DOMElementIterator(subElement.getChildNodes());
            if (!nodeIter.hasNext()) {
                throw new ConfigurationException("Error handling initializer for plug-in event type '" + name
                        + "', no child node found under initializer element, expecting an element node");
            }

            StringWriter output = new StringWriter();
            try {
                TransformerFactory.newInstance().newTransformer().transform(new DOMSource(nodeIter.next()),
                        new StreamResult(output));
            } catch (TransformerException e) {
                throw new ConfigurationException(
                        "Error handling initializer for plug-in event type '" + name + "' :" + e.getMessage(),
                        e);
            }
            initializer = output.toString();
        }
    }

    configuration.addPlugInEventType(name, uris.toArray(new URI[uris.size()]), initializer);
}

From source file:com.qwazr.crawler.web.manager.WebCrawlThread.java

/**
 * Remove the fragment and the query parameters following the configuration
 *
 * @param uri//from www.  jav a  2 s. c o  m
 * @return
 */
private URI checkLink(URI uri) {
    URIBuilder uriBuilder = new URIBuilder(uri);
    checkRemoveFragment(uriBuilder);
    checkRemoveParameter(uriBuilder);
    try {
        return uriBuilder.build();
    } catch (URISyntaxException e) {
        logger.warn(e.getMessage(), e);
        return null;
    }
}

From source file:com.sonymobile.jenkins.plugins.mq.mqnotifier.MQNotifierConfig.java

/**
 * Tests connection to the server URI./*from   w w  w . j av a2s . co  m*/
 *
 * @param uri the URI.
 * @param name the user name.
 * @param pw the user password.
 * @return FormValidation object that indicates ok or error.
 * @throws javax.servlet.ServletException Exception for servlet.
 */
public FormValidation doTestConnection(@QueryParameter(SERVER_URI) final String uri,
        @QueryParameter(USERNAME) final String name, @QueryParameter(PASSWORD) final Secret pw)
        throws ServletException {
    UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS);
    FormValidation result = FormValidation.ok();
    if (urlValidator.isValid(uri)) {
        try {
            ConnectionFactory conn = new ConnectionFactory();
            conn.setUri(uri);
            if (StringUtils.isNotEmpty(name)) {
                conn.setUsername(name);
                if (StringUtils.isNotEmpty(Secret.toString(pw))) {
                    conn.setPassword(Secret.toString(pw));
                }
            }
            conn.newConnection();
        } catch (URISyntaxException e) {
            result = FormValidation.error("Invalid Uri");
        } catch (PossibleAuthenticationFailureException e) {
            result = FormValidation.error("Authentication Failure");
        } catch (Exception e) {
            result = FormValidation.error(e.getMessage());
        }
    } else {
        result = FormValidation.error("Invalid Uri");

    }
    return result;
}

From source file:org.craftercms.search.service.impl.RestClientSearchService.java

public String delete(String site, String id) throws SearchException {
    String deleteUrl = serverUrl + URL_ROOT + URL_DELETE + "?" + REQUEST_PARAM_SITE + "=" + site + "&"
            + REQUEST_PARAM_ID + "=" + id;

    try {/*from  w  w  w.  j  a v  a2  s.c om*/
        return restTemplate.postForObject(new URI(deleteUrl), null, String.class);
    } catch (URISyntaxException e) {
        throw new SearchException("Invalid URI: " + deleteUrl, e);
    } catch (HttpStatusCodeException e) {
        throw new SearchException("Delete for XML '" + id + "' failed: [" + e.getStatusText() + "] "
                + e.getResponseBodyAsString());
    } catch (Exception e) {
        throw new SearchException("Delete for XML '" + id + "' failed: " + e.getMessage(), e);
    }
}

From source file:org.craftercms.search.service.impl.RestClientSearchService.java

public String update(String site, String id, String xml, boolean ignoreRootInFieldNames)
        throws SearchException {
    String updateUrl = serverUrl + URL_ROOT + URL_UPDATE + "?" + REQUEST_PARAM_SITE + "=" + site + "&"
            + REQUEST_PARAM_ID + "=" + id + "&" + REQUEST_PARAM_IGNORE_ROOT_IN_FIELD_NAMES + "="
            + ignoreRootInFieldNames;/*  ww w .j a  v a2  s .  co  m*/

    try {
        return restTemplate.postForObject(new URI(updateUrl), xml, String.class);
    } catch (URISyntaxException e) {
        throw new SearchException("Invalid URI: " + updateUrl, e);
    } catch (HttpStatusCodeException e) {
        throw new SearchException("Update for XML '" + id + "' failed: [" + e.getStatusText() + "] "
                + e.getResponseBodyAsString());
    } catch (Exception e) {
        throw new SearchException("Update for XML '" + id + "' failed: " + e.getMessage(), e);
    }
}

From source file:ch.cyberduck.core.azure.AzureSession.java

@Override
protected void login(LoginController controller, Credentials credentials) throws IOException {
    // http://*.blob.core.windows.net
    try {// www .j ava  2  s .  co m
        client = new BlobStorageRest(new URI(host.getProtocol().getScheme() + "://" + host.getHostname()),
                false, credentials.getUsername(), credentials.getPassword());
    } catch (URISyntaxException e) {
        log.error("Failure parsing URI:" + e.getMessage());
        IOException failure = new IOException(e.getMessage());
        failure.initCause(e);
        throw failure;
    }
    client.setTimeout(TimeSpan.fromMilliseconds(this.timeout()));
    try {
        this.getContainers(true);
    } catch (StorageServerException e) {
        if (this.isLoginFailure(e)) {
            this.message(Locale.localizedString("Login failed", "Credentials"));
            controller.fail(host.getProtocol(), credentials);
            this.login();
        } else {
            IOException failure = new IOException(e.getCause().getMessage());
            failure.initCause(e);
            throw failure;
        }
    }
}