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.web.server.ProxyServlet.java

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Create new client to perform the proxied request
    HttpClient httpclient = new DefaultHttpClient();

    // Determine final URL
    StringBuffer uri = new StringBuffer();
    uri.append(targetServer);//from   w  w  w  .  ja va 2s .c om
    uri.append(req.getRequestURI());

    // Add any supplied query strings
    String queryString = req.getQueryString();
    if (queryString != null) {
        uri.append("?" + queryString);
    }

    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    // Unknown content length ...
    //       if (contentLength == -1)
    //          throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };

        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);

        request = tmpRequest;
    }

    // Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    // Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<String> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = headers.nextElement();
        String headerValue = req.getHeader(headerName);
        // Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) {
            //             System.out.println(headerName.toLowerCase() + ": " + headerValue);
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);

    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());
    // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        resp.addHeader(header.getName(), header.getValue());
    }

    // Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();
    int b = input.read();
    while (b != -1) {
        output.write(b);
        b = input.read();
    }

    // Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:ph.com.globe.connect.AuthenticationActivity.java

/**
 * Build request url.//from  www  .ja v  a  2 s.co  m
 *
 * @param  url target url
 * @param  appId app id
 * @return String
 * @throws ApiException api exception
 */
protected String buildUrl(String url, String appId) throws ApiException {
    // try parsing url
    try {
        // build url
        url = String.format(url, this.DIALOG_URL);
        // initialize url builder
        URIBuilder builder = new URIBuilder(url);

        // set access token parameter
        builder.setParameter("app_id", appId);

        // build the url
        url = builder.build().toString();

        return url;
    } catch (URISyntaxException e) {
        // throw exception
        throw new ApiException(e.getMessage());
    }
}

From source file:com.mifos.mifosxdroid.dialogfragments.DocumentDialogFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case FILE_SELECT_CODE:
        if (resultCode == Activity.RESULT_OK) {
            // Get the Uri of the selected file
            Uri uri = data.getData();/*from  w w w. jav  a  2 s.c  o m*/

            Log.d(LOG_TAG, "File Uri: " + uri.toString());
            // Get the path
            try {

                String scheme = uri.getScheme();

                if (scheme.equals("file")) {
                    filePath = FileUtils.getPath(getActivity(), uri);
                    fileChoosen = new File(filePath);
                    Log.d(LOG_TAG, "File Path: " + filePath);
                } else if (scheme.equals("content")) {

                    Toast.makeText(getActivity(),
                            "The application currently does not "
                                    + "support file picking from apps other than File " + "Managers.",
                            Toast.LENGTH_SHORT).show();
                    resultCode = Activity.RESULT_CANCELED;
                }

                if (fileChoosen != null) {
                    tv_choose_file.setText(fileChoosen.getName());
                } else {
                    break;
                }
                bt_upload.setEnabled(true);

            } catch (URISyntaxException e) {
                Log.d(LOG_TAG, e.getMessage());
            }
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

From source file:net.praqma.jenkins.rqm.request.RQMHttpClient.java

public int logout() {
    log.finest("Logout");
    try {//  w  ww.  j  a  va 2  s.  c  o m
        log.finest("URI:" + url.toURI().toString());
    } catch (URISyntaxException ex) {
        log.finest("Logout URISyntaxException " + ex.getMessage());
    }

    String logoutUrl = this.url.toString() + contextRoot + JAZZ_LOGOUT_URL;
    log.finest("Attempting to log out with this url: " + logoutUrl);
    HttpMethodBase authenticationMethod = new PostMethod(this.url.toString() + contextRoot + JAZZ_LOGOUT_URL);
    authenticationMethod.setFollowRedirects(false);
    UsernamePasswordCredentials credentials = (UsernamePasswordCredentials) super.getState()
            .getCredentials(new AuthScope(host, port));
    if (null != credentials && !(credentials.getUserName().isEmpty() && credentials.getPassword().isEmpty())) {

        log.finest(String.format("Adding authorizationheadder for logout for user: %s",
                credentials.getUserName()));
        authenticationMethod.addRequestHeader("Authorization:",
                "Base " + credentials.getUserName() + ":" + credentials.getPassword());
    }
    String body = "";
    String status = "";
    int responseCode = 0;
    ;
    try {
        responseCode = executeMethod(authenticationMethod);
        body = authenticationMethod.getResponseBodyAsString();
        status = authenticationMethod.getStatusText();
        log.finest(String.format("Response code %s, Status text %s", responseCode, status));
    } catch (Exception e) {
        log.log(Level.SEVERE, "Failed to log out!", e);
        log.log(Level.SEVERE, body);
    }
    return responseCode;
}

From source file:de.uni_koblenz.west.splendid.tools.NQuadSourceAggregator.java

private void process(InputStream in, Writer writer) {

    NxParser parser = new NxParser(in);

    Node[] quad = null;//from   w  w  w . j  av  a  2s. c  o m
    while (parser.hasNext()) {
        try {
            quad = parser.next();

            // ignore path information, just consider host name
            String host = new URI(quad[3].toString()).getHost();

            if (!isIPAddress(host))
                host = truncateHostName(host);

            quad[3] = new Resource("http://" + host);

            ctxCounter.add((Resource) quad[3]);

            writer.write(quad[0].toN3());
            writer.write(" ");
            writer.write(quad[1].toN3());
            writer.write(" ");
            writer.write(quad[2].toN3());
            writer.write(" ");
            writer.write(quad[3].toN3());
            writer.write(" .");
            writer.write(LINE_SEP);

        } catch (URISyntaxException e) {
            System.out.println("Invalid URI: " + e.getMessage());
            continue;
        } catch (Exception e) {
            System.out.println("ERROR: " + e.getClass() + " - " + e.getMessage());
            continue;
        }
    }
}

From source file:net.sourceforge.dita4publishers.tools.dxp.DxpFileOrganizingBosVisitor.java

public void visit(BoundedObjectSet bos) throws Exception {
    // If there is a root map, then everything is
    // handled relative to it and there may not be a need
    // for a manifest, otherwise we need to generate 
    // a manifest map or reorganize the files to put
    // everything below the root map.

    BosMember rootMember = bos.getRoot();
    if (rootMember != null && rootMember instanceof DitaMapBosMemberImpl) {
        this.rootMap = rootMember;
    } else {//  w w w.  ja v a  2s. c  o m
        this.rootMap = constructDxpManifestMap(bos);
    }

    this.rootMapUri = rootMap.getEffectiveUri();
    try {
        this.baseUri = AddressingUtil.getParent(rootMapUri);
    } catch (URISyntaxException e) {
        throw new BosException("URI syntax exception calculating base URI for root map: " + e.getMessage());
    } catch (MalformedURLException e) {
        throw new BosException("MalformedURLException calculating base URI for root map: " + e.getMessage());
    } catch (IOException e) {
        throw new BosException("IOException calculating base URI for root map: " + e.getMessage());
    }

    this.rewriteRequired = false;

    for (BosMember member : bos.getMembers()) {
        if (member.equals(rootMap))
            continue;
        URI memberUri = member.getEffectiveUri();
        URI memberBase = null;
        try {
            memberBase = AddressingUtil.getParent(memberUri);
        } catch (URISyntaxException e) {
            throw new BosException(
                    "URI syntax exception: " + e.getMessage() + " getting base URI for member " + member);
        } catch (MalformedURLException e) {
            throw new BosException(
                    "MalformedURLException: " + e.getMessage() + " getting base URI for member " + member);
        } catch (IOException e) {
            throw new BosException("IOException: " + e.getMessage() + " getting base URI for member " + member);
        }
        URI relativeUri = baseUri.relativize(memberUri);
        boolean isAbsolute = relativeUri.isAbsolute();
        if (isAbsolute || relativeUri.toString().startsWith("..") || relativeUri.toString().startsWith("/")
                || memberBase.equals(baseUri)) {
            // URI is not below the root map, need to rewrite it.
            rewriteRequired = true;
            try {
                URL newUrl = new URL(baseUri.toURL(), "dependencies/" + member.getFileName());
                member.setEffectiveUri(newUrl.toURI());
            } catch (MalformedURLException e) {
                throw new BosException("Malformed URL exception: " + e.getMessage()
                        + " constructing new URL for member " + member);
            } catch (URISyntaxException e) {
                throw new BosException("URI syntax exception: " + e.getMessage()
                        + " constructing new URI for member " + member);
            }
        }
    }

    if (rewriteRequired) {
        UriToUriPointerRewritingBosVisitor rewritingVisitor = new UriToUriPointerRewritingBosVisitor();
        rewritingVisitor.visit(bos);
    }

}

From source file:no.uka.findmyapp.android.rest.client.RestProcessor.java

private URI createURI(ServiceModel serviceModel, String userToken) {
    String tempUri = serviceModel.getUri().toString().replace("?", "%s");
    tempUri = String.format(tempUri, serviceModel.getParameters());
    tempUri = tempUri + "?token=" + userToken;
    URI returURI;//from   w  w  w  .j  av  a  2s.  com
    try {
        returURI = new URI(tempUri);
    } catch (URISyntaxException e) {
        Log.e(debug, e.getMessage());
        return null;
    }
    return returURI;
}

From source file:org.apache.ambari.server.controller.metrics.timeline.MetricsRequestHelper.java

public TimelineMetrics fetchTimelineMetrics(URIBuilder uriBuilder, Long startTime, Long endTime)
        throws IOException {
    LOG.debug("Metrics request url = " + uriBuilder.toString());
    BufferedReader reader = null;
    TimelineMetrics timelineMetrics = null;
    try {//from ww  w . jav a 2s.  co  m

        HttpURLConnection connection = streamProvider.processURL(uriBuilder.toString(), HttpMethod.GET,
                (String) null, Collections.<String, List<String>>emptyMap());

        if (!checkConnectionForPrecisionException(connection)) {
            //Try one more time with higher precision
            String higherPrecision = getHigherPrecision(uriBuilder, startTime, endTime);
            if (higherPrecision != null) {
                LOG.debug("Requesting metrics with higher precision : " + higherPrecision);
                uriBuilder.setParameter("precision", higherPrecision);
                String newSpec = uriBuilder.toString();
                connection = streamProvider.processURL(newSpec, HttpMethod.GET, (String) null,
                        Collections.<String, List<String>>emptyMap());
                if (!checkConnectionForPrecisionException(connection)) {
                    throw new IOException(
                            "Encountered Precision exception : Higher precision request also failed.");
                }
            } else {
                throw new IOException("Encountered Precision exception : Unable to request higher precision");
            }
        }

        InputStream inputStream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(inputStream));
        timelineMetrics = timelineObjectReader.readValue(reader);

        if (LOG.isTraceEnabled()) {
            for (TimelineMetric metric : timelineMetrics.getMetrics()) {
                LOG.trace("metric: " + metric.getMetricName() + ", size = " + metric.getMetricValues().size()
                        + ", host = " + metric.getHostName() + ", app = " + metric.getAppId() + ", instance = "
                        + metric.getInstanceId() + ", time = " + metric.getTimestamp() + ", startTime = "
                        + new Date(metric.getStartTime()));
            }
        }
    } catch (IOException io) {
        String errorMsg = "Error getting timeline metrics : " + io.getMessage();
        LOG.error(errorMsg);
        if (LOG.isDebugEnabled()) {
            LOG.debug(errorMsg, io);
        }

        if (io instanceof SocketTimeoutException) {
            errorMsg += " Can not connect to collector, socket error.";
            LOG.error(errorMsg);
            throw io;
        }
    } catch (URISyntaxException e) {
        String errorMsg = "Error getting timeline metrics : " + e.getMessage();
        LOG.error(errorMsg);
        if (LOG.isDebugEnabled()) {
            LOG.debug(errorMsg, e);
        }
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                if (LOG.isWarnEnabled()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.warn("Unable to close http input stream : spec=" + uriBuilder.toString(), e);
                    } else {
                        LOG.warn("Unable to close http input stream : spec=" + uriBuilder.toString());
                    }
                }
            }
        }
    }
    return timelineMetrics;
}

From source file:com.epam.reportportal.apache.http.impl.client.DefaultRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    Args.notNull(request, "HTTP request");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    //get the location header to find out where to redirect to
    final Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }/*from   ww  w . ja  v a 2s.com*/
    final String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    final RequestConfig config = clientContext.getRequestConfig();

    URI uri = createLocationURI(location);

    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    try {
        if (!uri.isAbsolute()) {
            if (!config.isRelativeRedirectsAllowed()) {
                throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
            }
            // Adjust location URI
            final HttpHost target = clientContext.getTargetHost();
            Asserts.notNull(target, "Target host");
            final URI requestURI = new URI(request.getRequestLine().getUri());
            final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        }
    } catch (final URISyntaxException ex) {
        throw new ProtocolException(ex.getMessage(), ex);
    }

    RedirectLocations redirectLocations = (RedirectLocations) clientContext
            .getAttribute(HttpClientContext.REDIRECT_LOCATIONS);
    if (redirectLocations == null) {
        redirectLocations = new RedirectLocations();
        context.setAttribute(HttpClientContext.REDIRECT_LOCATIONS, redirectLocations);
    }
    if (!config.isCircularRedirectsAllowed()) {
        if (redirectLocations.contains(uri)) {
            throw new CircularRedirectException("Circular redirect to '" + uri + "'");
        }
    }
    redirectLocations.add(uri);
    return uri;
}

From source file:org.gnode.wda.server.ProxyServlet.java

License:asdf

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Create new client to perform the proxied request
    HttpClient httpclient = new DefaultHttpClient();

    // Determine final URL
    StringBuffer uri = new StringBuffer();
    uri.append(targetServer);//from   w  w  w .  jav  a2  s.c  o  m
    // This is a very bad hack. In order to remove my proxy servlet-path, I have used a substring method.
    // Turns "/proxy/asdf" into "/asdf"
    uri.append(req.getRequestURI().substring(6));

    //    Add any supplied query strings
    String queryString = req.getQueryString();
    if (queryString != null) {
        uri.append("?" + queryString);
    }

    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    //    Unknown content length ...
    // if (contentLength == -1)
    // throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };

        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);

        request = tmpRequest;
    }

    //    Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    //       Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<String> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = headers.nextElement();
        String headerValue = req.getHeader(headerName);
        //       Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) {
            //    System.out.println(headerName.toLowerCase() + ": " + headerValue);
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);

    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());
    // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        resp.addHeader(header.getName(), header.getValue());
    }

    //    Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();

    if (entity == null)
        return;

    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();
    int b = input.read();
    while (b != -1) {
        output.write(b);
        b = input.read();
    }

    //       Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}