List of usage examples for java.net URI getHost
public String getHost()
From source file:com.brightcove.com.uploader.helper.MediaAPIHelper.java
/** * Executes a file upload write api call against the given URI. * This is useful for create_video and add_image * @param json the json representation of the call you are making * @param file the file you are uploading * @param uri the api servlet you want to execute against * @return json response from api// www. java 2 s .com * @throws BadEnvironmentException * @throws MediaAPIError */ public JsonNode executeWrite(JsonNode json, File file, URI uri) throws BadEnvironmentException, MediaAPIError { mLog.debug("using " + uri.getHost() + " on port " + uri.getPort() + " for api write"); HttpPost method = new HttpPost(uri); MultipartEntity entityIn = new MultipartEntity(); FileBody fileBody = null; if (file != null) { fileBody = new FileBody(file); } try { entityIn.addPart("JSON-RPC", new StringBody(json.toString(), Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new BadEnvironmentException("UTF-8 no longer supported"); } if (file != null) { entityIn.addPart(file.getName(), fileBody); } method.setEntity(entityIn); return executeCall(method); }
From source file:io.seldon.external.ExternalPredictionServer.java
public JsonNode predict(String client, JsonNode jsonNode, OptionsHolder options) { long timeNow = System.currentTimeMillis(); URI uri = URI.create(options.getStringOption(URL_PROPERTY_NAME)); try {// ww w.j a va2s. c om URIBuilder builder = new URIBuilder().setScheme("http").setHost(uri.getHost()).setPort(uri.getPort()) .setPath(uri.getPath()).setParameter("client", client) .setParameter("json", jsonNode.toString()); uri = builder.build(); } catch (URISyntaxException e) { throw new APIException(APIException.GENERIC_ERROR); } HttpContext context = HttpClientContext.create(); HttpGet httpGet = new HttpGet(uri); try { if (logger.isDebugEnabled()) logger.debug("Requesting " + httpGet.getURI().toString()); CloseableHttpResponse resp = httpClient.execute(httpGet, context); try { if (resp.getStatusLine().getStatusCode() == 200) { ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser parser = factory.createParser(resp.getEntity().getContent()); JsonNode actualObj = mapper.readTree(parser); return actualObj; } else { logger.error( "Couldn't retrieve prediction from external prediction server -- bad http return code: " + resp.getStatusLine().getStatusCode()); throw new APIException(APIException.GENERIC_ERROR); } } finally { if (resp != null) resp.close(); if (logger.isDebugEnabled()) logger.debug( "External prediction server took " + (System.currentTimeMillis() - timeNow) + "ms"); } } catch (IOException e) { logger.error("Couldn't retrieve prediction from external prediction server - ", e); throw new APIException(APIException.GENERIC_ERROR); } catch (Exception e) { logger.error("Couldn't retrieve prediction from external prediction server - ", e); throw new APIException(APIException.GENERIC_ERROR); } finally { } }
From source file:org.apache.zeppelin.notebook.repo.zeppelinhub.rest.HttpProxyClient.java
private CloseableHttpAsyncClient getAsyncProxyHttpClient(URI proxyUri) { LOG.info("Creating async proxy http client"); PoolingNHttpClientConnectionManager cm = getAsyncConnectionManager(); HttpHost proxy = new HttpHost(proxyUri.getHost(), proxyUri.getPort()); HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom(); if (cm != null) { clientBuilder = clientBuilder.setConnectionManager(cm); }//from w ww . ja va 2 s. c om if (proxy != null) { clientBuilder = clientBuilder.setProxy(proxy); } clientBuilder = setRedirects(clientBuilder); return clientBuilder.build(); }
From source file:es.juntadeandalucia.panelGestion.negocio.utiles.Geoserver.java
/** * This method creates a new DataStore in the established workspace * with the specified name and using the data from the entity table * * @param workspace the workspace name where the data store will be created * @param datastoreName the name of the new data store * @param schema schema to use to create the data store * //from w w w . ja v a 2 s . c o m * @return true if the data store was created successfully * * @throws MalformedURLException thrown if the data base URL is not valid */ public boolean createDataStore(String workspace, String datastoreName, Schema schema) throws MalformedURLException { boolean createdDatastore = false; if (StringUtils.isEmpty(workspace) || StringUtils.isEmpty(datastoreName) || (schema == null)) { throw new IllegalArgumentException("No se han especificado todos los parmetros necesarios"); } // gets datastore params DataBase database = schema.getDataBase(); String connectionUrlString = database.getConnectionUrl(); connectionUrlString = connectionUrlString.substring(5); //TODO: pillar el nombre de la url de conexion http......./nombd y ponerlo en el campo databaseName URI connectionUri = URI.create(connectionUrlString); String host = connectionUri.getHost(); int port = connectionUri.getPort(); //String databaseName = database.getAlias(); String databaseName = getNameByUrlConecction(connectionUrlString); String schemaName = schema.getName(); String user = schema.getUser(); String password = schema.getPassword(); boolean validateConnections = true; boolean enabled = true; // creates store GSPostGISDatastoreEncoder store = new GSPostGISDatastoreEncoder(datastoreName); store.setHost(host); store.setPort(port); store.setDatabase(databaseName); store.setSchema(schemaName); store.setUser(user); store.setPassword(password); store.setEnabled(enabled); store.setValidateConnections(validateConnections); // uses the API REST createdDatastore = gsManager.getStoreManager().create(workspace, store); return createdDatastore; }
From source file:org.bedework.synch.cnctrs.orgSyncV2.OrgSyncV2ConnectorInstance.java
@Override public URI getUri() throws SynchException { try {//from w ww. j a v a 2s . co m //Get yesterdays date final LocalDate yesterday = LocalDate.now().minus(1, ChronoUnit.DAYS); final String yesterdayStr = yesterday.format(DateTimeFormatter.ISO_LOCAL_DATE); final URI infoUri = new URI(info.getUri()); return new URIBuilder().setScheme(infoUri.getScheme()).setHost(infoUri.getHost()) .setPort(infoUri.getPort()).setPath(infoUri.getPath()) .setParameter("key", cnctr.getSyncher().decrypt(info.getPassword())) .setParameter("start_date", yesterdayStr).build(); } catch (final SynchException se) { throw se; } catch (final Throwable t) { throw new SynchException(t); } }
From source file:org.coffeebreaks.validators.w3c.W3cMarkupValidator.java
private ValidationResult validateW3cMarkup(String type, String value, boolean get) throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpRequestBase method;/*from w w w . j a v a 2s .c om*/ if (get) { List<NameValuePair> qParams = new ArrayList<NameValuePair>(); qParams.add(new BasicNameValuePair("output", "soap12")); qParams.add(new BasicNameValuePair(type, value)); try { URI uri = new URI(baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "check"); URI uri2 = URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(), URLEncodedUtils.format(qParams, "UTF-8"), null); method = new HttpGet(uri2); } catch (URISyntaxException e) { throw new IllegalArgumentException("invalid uri. Check your baseUrl " + baseUrl, e); } } else { HttpPost httpPost = new HttpPost(baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "check"); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); formParams.add(new BasicNameValuePair("output", "soap12")); formParams.add(new BasicNameValuePair(type, value)); UrlEncodedFormEntity requestEntity = new UrlEncodedFormEntity(formParams, "UTF-8"); httpPost.setEntity(requestEntity); method = httpPost; } HttpResponse response = httpclient.execute(method); HttpEntity responseEntity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= HttpStatus.SC_BAD_REQUEST) { throw new IllegalStateException( "Unexpected HTTP status code: " + statusCode + ". Implementation error ?"); } if (responseEntity == null) { throw new IllegalStateException( "No entity but HTTP status code: " + statusCode + ". Server side error ?"); } InputStream entityContentInputStream = responseEntity.getContent(); StringWriter output = new StringWriter(); IOUtils.copy(entityContentInputStream, output, "UTF-8"); final String soap = output.toString(); // we can use the response headers instead of the soap // final W3cSoapValidatorSoapOutput soapObject = parseSoapObject(soap); String headerValue = getHeaderValue(response, "X-W3C-Validator-Status"); final boolean indeterminate = headerValue.equals("Abort"); final int errorCount = Integer.parseInt(getHeaderValue(response, "X-W3C-Validator-Errors")); final int warningCount = Integer.parseInt(getHeaderValue(response, "X-W3C-Validator-Warnings")); return new ValidationResult() { public boolean isResultIndeterminate() { return indeterminate; } public int getErrorCount() { return errorCount; } public int getWarningCount() { return warningCount; } public String getResponseContent() { return soap; } }; }
From source file:org.droidparts.http.CookieJar.java
private Collection<Cookie> getCookies(URI uri) { HashMap<String, Cookie> map = new HashMap<String, Cookie>(); for (Cookie cookie : getCookies()) { boolean suitable = uri.getHost().equals(cookie.getDomain()) && uri.getPath().startsWith(cookie.getPath()); if (suitable) { boolean put = true; if (map.containsKey(cookie.getName())) { Cookie otherCookie = map.get(cookie.getName()); boolean betterMatchingPath = cookie.getPath().length() > otherCookie.getPath().length(); put = betterMatchingPath; }//from w ww. j av a2 s.c om if (put) { map.put(cookie.getName(), cookie); } } } return map.values(); }
From source file:com.fortify.bugtracker.common.tgt.processor.AbstractTargetProcessorUpdateIssues.java
protected boolean compareTargetURIWithDeepLinkURI(URI targetURI, URI deepLinkURI) { return targetURI.getHost().equals(deepLinkURI.getHost()) && targetURI.getPort() == deepLinkURI.getPort(); }
From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java
/** * @param request a RestRequest object to be encoded as a tunneled POST * @param requestContext a RequestContext object associated with the request * @param threshold the size of the query params above which the request will be encoded * * @return an encoded RestRequest/*from ww w .ja v a2s.c om*/ */ public static RestRequest encode(final RestRequest request, RequestContext requestContext, int threshold) throws URISyntaxException, MessagingException, IOException { URI uri = request.getURI(); // Check to see if we should tunnel this request by testing the length of the query // if the query is NULL, we won't bother to encode. // 0 length is a special case that could occur with a url like http://www.foo.com? // which we don't want to encode, because we'll lose the "?" in the process // Otherwise only encode queries whose length is greater than or equal to the // threshold value. String query = uri.getRawQuery(); boolean forceQueryTunnel = requestContext.getLocalAttr(R2Constants.FORCE_QUERY_TUNNEL) != null && (Boolean) requestContext.getLocalAttr(R2Constants.FORCE_QUERY_TUNNEL); if (query == null || query.length() == 0 || (query.length() < threshold && !forceQueryTunnel)) { return request; } RestRequestBuilder requestBuilder = new RestRequestBuilder(request); // reconstruct URI without query uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null, uri.getFragment()); // If there's no existing body, just pass the request as x-www-form-urlencoded ByteString entity = request.getEntity(); if (entity == null || entity.length() == 0) { requestBuilder.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED); requestBuilder.setEntity(ByteString.copyString(query, Data.UTF_8_CHARSET)); } else { // If we have a body, we must preserve it, so use multipart/mixed encoding MimeMultipart multi = createMultiPartEntity(entity, request.getHeader(HEADER_CONTENT_TYPE), query); requestBuilder.setHeader(HEADER_CONTENT_TYPE, multi.getContentType()); ByteArrayOutputStream os = new ByteArrayOutputStream(); multi.writeTo(os); requestBuilder.setEntity(ByteString.copy(os.toByteArray())); } // Set the base uri, supply the original method in the override header, and change method to POST requestBuilder.setURI(uri); requestBuilder.setHeader(HEADER_METHOD_OVERRIDE, requestBuilder.getMethod()); requestBuilder.setMethod(RestMethod.POST); return requestBuilder.build(); }
From source file:com.abiquo.abiserver.pojo.service.RemoteService.java
private boolean modifiedUri() { try {/* w w w . j a v a 2s. c o m*/ URI u = new URI(uri); return !fixProtocol(u.getScheme()).equals(fixProtocol(protocol)) || !u.getHost().equals(domainName) || u.getPort() != port || !StringUtils.isEmpty(u.getPath()) && !u.getPath().replaceFirst("/", "").equals(serviceMapping); } catch (URISyntaxException e) { return true; } catch (NullPointerException e) { return true; } }