List of usage examples for org.apache.http.client.utils URIUtils extractHost
public static HttpHost extractHost(final URI uri)
From source file:cn.tiup.httpproxy.ProxyServlet.java
protected void initTarget() throws ServletException { targetUri = getConfigParam(P_TARGET_URI); if (targetUri == null) throw new ServletException(P_TARGET_URI + " is required."); //test it's valid try {//from w w w .j a v a2 s.c o m targetUriObj = new URI(targetUri); } catch (Exception e) { throw new ServletException("Trying to process targetUri init parameter: " + e, e); } targetHost = URIUtils.extractHost(targetUriObj); }
From source file:io.hops.kibana.ProxyServlet.java
protected void initTarget() throws ServletException { // TODO - should get the Kibana URI from Settings.java // targetUri = Settings.getKibanaUri(); targetUri = getConfigParam(P_TARGET_URI); if (targetUri == null) throw new ServletException(P_TARGET_URI + " is required."); //test it's valid try {//www . j a va 2 s . c o m targetUriObj = new URI(targetUri); } catch (Exception e) { throw new ServletException("Trying to process targetUri init parameter: " + e, e); } targetHost = URIUtils.extractHost(targetUriObj); }
From source file:de.derschimi.proxyservlet.TestServlet.java
protected void initTarget() throws ServletException { targetUri = getConfigParam(P_TARGET_URI); if (targetUri == null) throw new ServletException(P_TARGET_URI + " is required."); //test it's valid try {/*from ww w .j ava 2 s .c o m*/ targetUriObj = new URI(targetUri); } catch (Exception e) { throw new ServletException("Trying to process targetUri init parameter: " + e, e); } targetHost = URIUtils.extractHost(targetUriObj); }
From source file:io.uploader.drive.drive.largefile.DriveResumableUpload.java
public boolean checkMD5(String md5) throws IOException { logger.info("Querying metadata of completed upload..."); Preconditions.checkState(org.apache.commons.lang3.StringUtils.isNotEmpty(md5)); CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; try {/*from w w w.j a v a2 s. c o m*/ httpclient = getHttpClient(); BasicHttpRequest httpreq = new BasicHttpRequest("PUT", location); httpreq.addHeader("Authorization", auth.getAuthHeader()); httpreq.addHeader("Content-Length", "0"); httpreq.addHeader("Content-Range", "bytes */" + getFileSizeString()); response = httpclient.execute(URIUtils.extractHost(uri), httpreq); BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity()); EntityUtils.consume(response.getEntity()); String retSrc = EntityUtils.toString(entity); String driveMd5 = null; if (useOldApi) { // Old API will return XML! JSONObject result = XML.toJSONObject(retSrc); logger.info("id : " + result.getJSONObject("entry").getString("gd:resourceId").replace("file:", "")); logger.info("title : " + result.getJSONObject("entry").getString("title")); logger.info("link : " + result.getJSONObject("entry").getJSONArray("link").getJSONObject(0).getString("href")); logger.info("md5Checksum : " + result.getJSONObject("entry").getString("docs:md5Checksum")); driveMd5 = result.getJSONObject("entry").getString("docs:md5Checksum"); } else { JSONObject result = new JSONObject(retSrc); logger.info("id : " + result.getString("id")); logger.info("title : " + result.getString("title")); logger.info("link : " + result.getString("webContentLink")); logger.info("md5Checksum : " + result.getString("md5Checksum")); driveMd5 = result.getString("md5Checksum"); } // verify the consistency of the md5 values return md5.equals(driveMd5); } finally { if (response != null) { response.close(); } if (httpclient != null) { httpclient.close(); } } }
From source file:io.hops.hopsworks.api.kibana.ProxyServlet.java
protected void initTarget() throws ServletException { // TODO - should get the Kibana URI from Settings.java // targetUri = Settings.getKibanaUri(); targetUri = getConfigParam(P_TARGET_URI); if (targetUri == null) { throw new ServletException(P_TARGET_URI + " is required."); }/*from w w w .ja va2s. c o m*/ //test it's valid try { targetUriObj = new URI(targetUri); } catch (Exception e) { throw new ServletException("Trying to process targetUri init parameter: " + e, e); } targetHost = URIUtils.extractHost(targetUriObj); }
From source file:snoopware.api.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest;//from w ww. j a v a 2 s . c om //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else { proxyRequest = new BasicHttpRequest(method, proxyRequestUri); } copyRequestHeaders(servletRequest, proxyRequest); try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURL().toString() + " -- " + proxyRequest.getRequestLine().getUri()); } HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //just to be sure, but is probably a no-op EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but // it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof ServletException) { throw (ServletException) e; } //noinspection ConstantConditions if (e instanceof IOException) { throw (IOException) e; } throw new RuntimeException(e); } }
From source file:be.milieuinfo.core.proxy.controller.ProxyServlet.java
@SuppressWarnings("deprecation") @Override// w ww . ja v a 2 s . c om protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest; //spec: RFC 2616, sec 4.3: either these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, proxyRequestUri); copyRequestHeaders(servletRequest, proxyRequest); try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //just to be sure, but is probably a no-op EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; if (e instanceof IOException) throw (IOException) e; throw new RuntimeException(e); } }
From source file:com.netflix.http4.NFHttpClient.java
private static HttpHost determineTarget(HttpUriRequest request) throws ClientProtocolException { // A null target may be acceptable if there is a default target. // Otherwise, the null target is detected in the director. HttpHost target = null;/*w w w . j a va 2 s . c o m*/ URI requestURI = request.getURI(); if (requestURI.isAbsolute()) { target = URIUtils.extractHost(requestURI); if (target == null) { throw new ClientProtocolException("URI does not specify a valid host name: " + requestURI); } } return target; }
From source file:io.hops.hopsworks.api.jupyter.URITemplateProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { //First collect params /*//from w w w . j ava 2 s .c om * Do not use servletRequest.getParameter(arg) because that will * typically read and consume the servlet InputStream (where our * form data is stored for POST). We need the InputStream later on. * So we'll parse the query string ourselves. A side benefit is * we can keep the proxy parameters in the query string and not * have to add them to a URL encoded form attachment. */ String queryString = "?" + servletRequest.getQueryString();//no "?" but might have "#" int hash = queryString.indexOf('#'); if (hash >= 0) { queryString = queryString.substring(0, hash); } List<NameValuePair> pairs; try { //note: HttpClient 4.2 lets you parse the string without building the URI pairs = URLEncodedUtils.parse(new URI(queryString), "UTF-8"); } catch (URISyntaxException e) { throw new ServletException("Unexpected URI parsing error on " + queryString, e); } LinkedHashMap<String, String> params = new LinkedHashMap<>(); for (NameValuePair pair : pairs) { params.put(pair.getName(), pair.getValue()); } //Now rewrite the URL StringBuffer urlBuf = new StringBuffer();//note: StringBuilder isn't supported by Matcher Matcher matcher = TEMPLATE_PATTERN.matcher(targetUriTemplate); while (matcher.find()) { String arg = matcher.group(1); String replacement = params.remove(arg);//note we remove if (replacement != null) { matcher.appendReplacement(urlBuf, replacement); port = replacement; } else if (port != null) { matcher.appendReplacement(urlBuf, port); } else { throw new ServletException("Missing HTTP parameter " + arg + " to fill the template"); } } matcher.appendTail(urlBuf); String newTargetUri = urlBuf.toString(); servletRequest.setAttribute(ATTR_TARGET_URI, newTargetUri); try { targetUriObj = new URI(newTargetUri); } catch (Exception e) { throw new ServletException("Rewritten targetUri is invalid: " + newTargetUri, e); } servletRequest.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(targetUriObj)); //Determine the new query string based on removing the used names StringBuilder newQueryBuf = new StringBuilder(queryString.length()); for (Map.Entry<String, String> nameVal : params.entrySet()) { if (newQueryBuf.length() > 0) { newQueryBuf.append('&'); } newQueryBuf.append(nameVal.getKey()).append('='); if (nameVal.getValue() != null) { newQueryBuf.append(nameVal.getValue()); } } servletRequest.setAttribute(ATTR_QUERY_STRING, newQueryBuf.toString()); // Create Exchange object with targetUriObj // create transport object // ServiceProxy sp = new ServiceProxy(); // sp.setTargetUrl(ATTR_TARGET_URI); // super.service(servletRequest, servletResponse); // RouterUtil.initializeRoutersFromSpringWebContext(appCtx, config. // getServletContext(), getProxiesXmlLocation(config)); }
From source file:io.hops.hopsworks.api.tensorflow.TensorboardProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { String email = servletRequest.getUserPrincipal().getName(); LOGGER.log(Level.FINE, "Request URL: {0}", servletRequest.getRequestURL()); String uri = servletRequest.getRequestURI(); // valid hostname regex: // https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address Pattern urlPattern = Pattern.compile("([a-zA-Z0-9\\-\\.]{2,255}:[0-9]{4,6})(/.*$)"); Matcher urlMatcher = urlPattern.matcher(uri); String hostPortPair = ""; String uriToFinish = "/"; if (urlMatcher.find()) { hostPortPair = urlMatcher.group(1); uriToFinish = urlMatcher.group(2); }/*from ww w . j av a2 s .c o m*/ if (hostPortPair.isEmpty()) { throw new ServletException("Couldn't extract host:port from: " + servletRequest.getRequestURI()); } Pattern appPattern = Pattern.compile("(application_.*?_\\d*)"); Matcher appMatcher = appPattern.matcher(servletRequest.getRequestURI()); Pattern elasticPattern = Pattern.compile("(experiments)"); Matcher elasticMatcher = elasticPattern.matcher(servletRequest.getRequestURI()); if (elasticMatcher.find()) { List<TensorBoard> TBList = tensorBoardFacade.findByUserEmail(email); if (TBList == null) { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "This TensorBoard is not running right now"); } boolean foundTB = false; for (TensorBoard tb : TBList) { if (tb.getEndpoint().equals(hostPortPair)) { foundTB = true; break; } } if (!foundTB) { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "This TensorBoard is not running right now"); return; } targetUri = uriToFinish; String theHost = "http://" + hostPortPair; URI targetUriHost; try { targetUriObj = new URI(targetUri); targetUriHost = new URI(theHost); } catch (Exception e) { throw new ServletException("Trying to process targetUri init parameter: ", e); } targetHost = URIUtils.extractHost(targetUriHost); servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); servletRequest.setAttribute(ATTR_URI_FINISH, uriToFinish); servletRequest.setAttribute(ATTR_HOST_PORT, hostPortPair); try { super.service(servletRequest, servletResponse); } catch (IOException ex) { sendErrorResponse(servletResponse, "This TensorBoard is not ready to serve requests right now, " + "try refreshing the page"); return; } } else if (appMatcher.find()) { String appId = appMatcher.group(1); YarnApplicationstate appState = yarnApplicationstateFacade.findByAppId(appId); if (appState == null) { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "You don't have the access right for this application"); return; } String projectName = hdfsUsersBean.getProjectName(appState.getAppuser()); ProjectDTO project; try { project = projectController.getProjectByName(projectName); } catch (ProjectException ex) { throw new ServletException(ex); } Users user = userFacade.findByEmail(email); boolean inTeam = false; for (ProjectTeam pt : project.getProjectTeam()) { if (pt.getUser().equals(user)) { inTeam = true; break; } } if (!inTeam) { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "You don't have the access right for this application"); return; } if (appState.getAppsmstate() != null && (appState.getAppsmstate().equalsIgnoreCase(YarnApplicationState.FINISHED.toString()) || appState.getAppsmstate().equalsIgnoreCase(YarnApplicationState.KILLED.toString()))) { sendErrorResponse(servletResponse, "This TensorBoard has finished running"); return; } targetUri = uriToFinish; String theHost = "http://" + hostPortPair; URI targetUriHost; try { targetUriObj = new URI(targetUri); targetUriHost = new URI(theHost); } catch (Exception e) { throw new ServletException("Trying to process targetUri init parameter: ", e); } targetHost = URIUtils.extractHost(targetUriHost); servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); servletRequest.setAttribute(ATTR_URI_FINISH, uriToFinish); servletRequest.setAttribute(ATTR_HOST_PORT, hostPortPair); try { super.service(servletRequest, servletResponse); } catch (IOException ex) { sendErrorResponse(servletResponse, "This TensorBoard is not running right now"); return; } } else { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "You don't have the access right for this application"); return; } }