List of usage examples for java.net URISyntaxException getMessage
public String getMessage()
From source file:groovyx.net.http.thirdparty.GAEClientConnection.java
public void sendRequestHeader(HttpRequest request) throws HttpException, IOException { try {/*w ww.java 2s. c o m*/ HttpHost host = route.getTargetHost(); URI uri = new URI(host.getSchemeName() + "://" + host.getHostName() + ((host.getPort() == -1) ? "" : (":" + host.getPort())) + request.getRequestLine().getUri()); this.request = new HTTPRequest(uri.toURL(), HTTPMethod.valueOf(request.getRequestLine().getMethod()), FetchOptions.Builder.disallowTruncate().doNotFollowRedirects()); } catch (URISyntaxException ex) { throw new IOException("Malformed request URI: " + ex.getMessage(), ex); } catch (IllegalArgumentException ex) { throw new IOException("Unsupported HTTP method: " + ex.getMessage(), ex); } // System.err.println("SEND: " + this.request.getMethod() + " " + this.request.getURL()); for (Header h : request.getAllHeaders()) { // System.err.println("SEND: " + h.getName() + ": " + h.getValue()); this.request.addHeader(new HTTPHeader(h.getName(), h.getValue())); } }
From source file:org.apache.http2.impl.client.DefaultRedirectStrategy.java
public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); }//w w w.j av a2 s. co m if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } //get the location header to find out where to redirect to 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"); } String location = locationHeader.getValue(); if (this.log.isDebugEnabled()) { this.log.debug("Redirect requested to location '" + location + "'"); } URI uri = createLocationURI(location); HttpParams params = request.getParams(); // rfc2616 demands the location value be a complete URI // Location = "Location" ":" absoluteURI try { // Drop fragment uri = URIUtils.rewriteURI(uri); if (!uri.isAbsolute()) { if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) { throw new ProtocolException("Relative redirect location '" + uri + "' not allowed"); } // Adjust location URI HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target == null) { throw new IllegalStateException("Target host not available " + "in the HTTP context"); } URI requestURI = new URI(request.getRequestLine().getUri()); URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true); uri = URIUtils.resolve(absoluteRequestURI, uri); } } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS); if (redirectLocations == null) { redirectLocations = new RedirectLocations(); context.setAttribute(REDIRECT_LOCATIONS, redirectLocations); } if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) { if (redirectLocations.contains(uri)) { throw new CircularRedirectException("Circular redirect to '" + uri + "'"); } } redirectLocations.add(uri); return uri; }
From source file:com.movilizer.mds.webservice.services.UploadFileService.java
private CompletableFuture<UploadResponse> upload(HttpEntity entity, Integer connectionTimeoutInMillis) { CompletableFuture<UploadResponse> future = new CompletableFuture<>(); try {//from ww w. j av a2 s .c o m Async.newInstance().execute( Request.Post(documentUploadAddress.toURI()) .addHeader(USER_AGENT_HEADER_KEY, DefaultValues.USER_AGENT) .connectTimeout(connectionTimeoutInMillis).body(entity), new ResponseHandlerAdapter<UploadResponse>(future) { @Override public UploadResponse convertHttpResponse(HttpResponse httpResponse) { logger.info(Messages.UPLOAD_COMPLETE); int statusCode = httpResponse.getStatusLine().getStatusCode(); String errorMessage = httpResponse.getStatusLine().getReasonPhrase(); if (statusCode == POSSIBLE_BAD_CREDENTIALS) { errorMessage = errorMessage + Messages.FAILED_FILE_UPLOAD_CREDENTIALS; } return new UploadResponse(statusCode, errorMessage); } }); } catch (URISyntaxException e) { if (logger.isErrorEnabled()) { logger.error(String.format(Messages.UPLOAD_ERROR, e.getMessage())); } future.completeExceptionally(new MovilizerWebServiceException(e)); } return future; }
From source file:org.mythdroid.services.JSONClient.java
/** * Perform a GET request of the specified path * @param path relative path of the query * @param query HashMap of query parameters * @return a JSONObject with the results * @throws IOException /*from w w w. j a v a 2s. c om*/ */ public JSONObject Get(String path, Params query) throws IOException { try { return Request(new HttpGet(CreateURI(path, query))); } catch (URISyntaxException e) { ErrUtil.logErr(e); ErrUtil.report(e); throw new IOException(e.getMessage()); } catch (IllegalStateException e) { ErrUtil.logErr(e); ErrUtil.report(e); throw new IOException(e.getMessage()); } catch (OutOfMemoryError e) { System.gc(); ErrUtil.logErr(e.getMessage()); ErrUtil.report(e.getMessage()); throw new IOException(e.getMessage()); } }
From source file:org.mythdroid.services.JSONClient.java
/** * Perform a POST request to the specified path * @param path relative path of the query * @param query HashMap of query parameters * @return a JSONObject with the results * @throws IOException //w w w .j ava 2 s . c o m */ public JSONObject Post(String path, Params query) throws IOException { try { return Request(new HttpPost(CreateURI(path, query))); } catch (URISyntaxException e) { ErrUtil.logErr(e); ErrUtil.report(e); throw new IOException(e.getMessage()); } catch (IllegalStateException e) { ErrUtil.logErr(e); ErrUtil.report(e); throw new IOException(e.getMessage()); } catch (OutOfMemoryError e) { System.gc(); ErrUtil.logErr(e.getMessage()); ErrUtil.report(e.getMessage()); throw new IOException(e.getMessage()); } }
From source file:org.wso2.carbon.appmgt.usage.publisher.APPMgtGoogleAnalayticsHandler.java
public boolean handleRequest(MessageContext messageContext) { if (!enabled) { return true; }//w ww .j ava 2 s. c o m /** Get Header Map **/ Map headers = (Map) ((Axis2MessageContext) messageContext).getAxis2MessageContext() .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); /** Get document referer **/ String documentReferer = (String) headers.get(HttpHeaders.REFERER); if (isEmpty(documentReferer)) { documentReferer = ""; } else { try { documentReferer = new URI(documentReferer).getPath(); } catch (URISyntaxException e) { log.error(e.getMessage(), e); return true; } } /** Get invoked Application Name **/ String appName = APPMgtUsageUtils.getAppNameFromSynapseEnvironment(messageContext, documentReferer); String appBasedCookieName = COOKIE_NAME + "_" + appName; /** Get User Agent **/ String userAgent = (String) headers.get(HttpHeaders.USER_AGENT); if (isEmpty(userAgent)) { userAgent = ""; } /** Get Analytics Cookie **/ String cookieString = (String) headers.get(HTTPConstants.COOKIE_STRING); String analyticCookie = findCookie(cookieString, appBasedCookieName); /** Retrieve or create client UUID - and store in MC to lookup in response path **/ String uuid = null; try { uuid = getClientUUID(messageContext, userAgent, analyticCookie); messageContext.setProperty(appBasedCookieName, uuid); } catch (Exception e) { log.error(e.getMessage(), e); return true; } /** Get host and domain name **/ String host = (String) headers.get(HttpHeaders.HOST); String domainName = host; if (host != null && host.indexOf(":") != -1) { domainName = host.substring(0, host.indexOf(":")); } if (isEmpty(domainName)) { domainName = ""; } GoogleAnalyticsData data = null; data = new GoogleAnalyticsData.DataBuilder(trackingID, PROTOCOL_VERSION, uuid, GoogleAnalyticsConstants.HIT_TYPE_PAGEVIEW).setDocumentPath(documentReferer) .setCacheBuster(getRandomNumber()).setDocumentHostName(host).setClientId(uuid).build(); Runnable googleAnalyticsPublisher = new GoogleAnalyticsPublisher(data, userAgent); executor.execute(googleAnalyticsPublisher); return true; }
From source file:org.expath.exist.SendRequestFunction.java
private Sequence sendRequest(final NodeValue request, final String href, final Sequence bodies) throws XPathException { HttpRequest req = null;//from w w w. j ava2 s .c o m try { final org.expath.tools.model.Sequence b = new EXistSequence(bodies, getContext()); final Element r = new EXistElement(request, getContext()); final RequestParser parser = new RequestParser(r); req = parser.parse(b, href); // override anyway it href exists if (href != null && !href.isEmpty()) { req.setHref(href); } final URI uri = new URI(req.getHref()); final EXistResult result = sendOnce(uri, req, parser); return result.getResult(); } catch (final URISyntaxException ex) { throw new XPathException(this, "Href is not valid: " + req != null ? req.getHref() : "" + ". " + ex.getMessage(), ex); } catch (final HttpClientException hce) { throw new XPathException(this, hce.getMessage(), hce); } }
From source file:com.dp.bigdata.taurus.web.servlet.CreateTaskServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpClient httpclient = new DefaultHttpClient(); // Determine final URL StringBuffer uri = new StringBuffer(); if (req.getParameter("update") != null) { uri.append(targetUri).append("/").append(req.getParameter("update")); } else {//from www . j a v a 2s .co m uri.append(targetUri); } LOG.info("Access URI : " + uri.toString()); // 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<?> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = (String) headers.nextElement(); String headerValue = req.getHeader(headerName); //LOG.info("header: " + headerName + " value: " + headerValue); // Skip Content-Length and Host String lowerHeader = headerName.toLowerCase(); if (lowerHeader.equals("content-type")) { request.addHeader(headerName, headerValue + ";charset=\"utf-8\""); } else if (!lowerHeader.equals("content-length") && !lowerHeader.equals("host")) { 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()); // Transfer headers to the response Header[] responseHeaders = response.getAllHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header header = responseHeaders[i]; if (!header.getName().equals("Transfer-Encoding")) 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(); byte buffer[] = new byte[50]; while (input.read(buffer) != -1) { output.write(buffer); } // 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:org.jvoicexml.documentserver.schemestrategy.HttpSchemeStrategy.java
/** * {@inheritDoc}//from www .j a va 2 s . c om */ @Override public InputStream getInputStream(final String sessionId, final URI uri, final RequestMethod method, final long timeout, final Collection<KeyValuePair> parameters) throws BadFetchError { final HttpClient client = SESSION_STORAGE.getSessionIdentifier(sessionId); final URI fullUri; try { final URI fragmentLessUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), uri.getQuery(), null); fullUri = addParameters(parameters, fragmentLessUri); } catch (URISyntaxException e) { throw new BadFetchError(e.getMessage(), e); } catch (SemanticError e) { throw new BadFetchError(e.getMessage(), e); } final String url = fullUri.toString(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("connecting to '" + url + "'..."); } final HttpUriRequest request; if (method == RequestMethod.GET) { request = new HttpGet(url); } else { request = new HttpPost(url); } attachFiles(request, parameters); try { final HttpParams params = client.getParams(); setTimeout(timeout, params); final HttpResponse response = client.execute(request); final StatusLine statusLine = response.getStatusLine(); final int status = statusLine.getStatusCode(); if (status != HttpStatus.SC_OK) { throw new BadFetchError(statusLine.getReasonPhrase() + " (HTTP error code " + status + ")"); } final HttpEntity entity = response.getEntity(); return entity.getContent(); } catch (IOException e) { throw new BadFetchError(e.getMessage(), e); } }
From source file:cn.isif.util_plus.http.client.util.URIBuilder.java
public URIBuilder(final String uri) { try {//from w w w . j a va 2s . c o m digestURI(new URI(uri)); } catch (URISyntaxException e) { LogUtils.e(e.getMessage(), e); } }