List of usage examples for java.net URL getPort
public int getPort()
From source file:com.tremolosecurity.unison.proxy.auth.twitter.TwitterAuth.java
public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException { HttpSession session = ((HttpServletRequest) request).getSession(); HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session .getAttribute(ProxyConstants.AUTH_MECH_PARAMS); ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ); MyVDConnection myvd = cfg.getMyVD(); String consumerKey = authParams.get("consumerKey").getValues().get(0); String consumerSecret = authParams.get("consumerSecret").getValues().get(0); String accessToken = authParams.get("accessToken").getValues().get(0); String accessSecret = authParams.get("accessSecret").getValues().get(0); boolean linkToDirectory = Boolean.parseBoolean(authParams.get("linkToDirectory").getValues().get(0)); String noMatchOU = authParams.get("noMatchOU").getValues().get(0); String uidAttr = authParams.get("uidAttr").getValues().get(0); String lookupFilter = authParams.get("lookupFilter").getValues().get(0); //String userLookupClassName = authParams.get("userLookupClassName").getValues().get(0); UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG); RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder(); URL reqURL = new URL(request.getRequestURL().toString()); String redirectURL = reqURL.getProtocol() + "://" + reqURL.getHost(); if (reqURL.getPort() != -1) { redirectURL += ":" + reqURL.getPort(); }//from w ww . j a v a 2 s . co m String urlChain = holder.getUrl().getAuthChain(); AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName()); AuthMechType amt = act.getAuthMech().get(as.getId()); String authMechName = amt.getName(); redirectURL += cfg.getAuthMechs().get(authMechName).getUri(); if (request.getParameter("oauth_verifier") == null) { BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager( GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry()); RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build(); CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc) .build(); HttpPost post = new HttpPost("https://api.twitter.com/oauth/request_token"); this.signRequest(post, "", accessToken, accessSecret, consumerKey, consumerSecret); CloseableHttpResponse httpResp = http.execute(post); BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent())); StringBuffer token = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { token.append(line); } httpResp.close(); bhcm.close(); System.err.println(token); List<NameValuePair> parsed = URLEncodedUtils.parse(token.toString(), Charsets.UTF_8); HashMap<String, String> accessTokens = new HashMap<String, String>(); for (NameValuePair nvp : parsed) { accessTokens.put(nvp.getName(), nvp.getValue()); } request.getSession().setAttribute("twitterAccessToken", accessTokens); StringBuffer b = new StringBuffer().append("https://api.twitter.com/oauth/authenticate?oauth_token=") .append(accessTokens.get("oauth_token")); response.sendRedirect(b.toString()); } else { String oauthVerifier = request.getParameter("oauth_verifier"); HashMap<String, String> accessTokens = (HashMap<String, String>) request.getSession() .getAttribute("twitterAccessToken"); BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager( GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry()); RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build(); CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc) .build(); HttpUriRequest post = new HttpPost(); try { post = RequestBuilder.post().setUri(new java.net.URI("https://api.twitter.com/oauth/access_token")) .addParameter("oauth_verifier", oauthVerifier).build(); } catch (URISyntaxException e) { throw new ServletException("Could not create post request"); } this.signRequest(post, "oauth_verifier=" + oauthVerifier, accessTokens.get("oauth_token"), accessTokens.get("oauth_token_secret"), consumerKey, consumerSecret); CloseableHttpResponse httpResp = http.execute(post); BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent())); StringBuffer token = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { token.append(line); } EntityUtils.consumeQuietly(httpResp.getEntity()); httpResp.close(); System.err.println(token); List<NameValuePair> parsed = URLEncodedUtils.parse(token.toString(), Charsets.UTF_8); HashMap<String, String> userTokens = new HashMap<String, String>(); for (NameValuePair nvp : parsed) { userTokens.put(nvp.getName(), nvp.getValue()); } request.getSession().setAttribute("twitterUserToken", accessTokens); HttpGet get = new HttpGet( "https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true"); this.signRequest(get, "", userTokens.get("oauth_token"), userTokens.get("oauth_token_secret"), consumerKey, consumerSecret); httpResp = http.execute(get); in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent())); token.setLength(0); line = null; while ((line = in.readLine()) != null) { token.append(line); } EntityUtils.consumeQuietly(httpResp.getEntity()); httpResp.close(); System.err.println(token); httpResp.close(); bhcm.close(); Map attrs = com.cedarsoftware.util.io.JsonReader.jsonToMaps(token.toString()); if (!linkToDirectory) { loadUnlinkedUser(session, noMatchOU, uidAttr, act, attrs); as.setSuccess(true); } else { lookupUser(as, session, myvd, noMatchOU, uidAttr, lookupFilter, act, attrs); } String redirectToURL = request.getParameter("target"); if (redirectToURL != null && !redirectToURL.isEmpty()) { reqHolder.setURL(redirectToURL); } holder.getConfig().getAuthManager().nextAuth(request, response, session, false); } }
From source file:org.openremote.android.console.net.ORConnection.java
/** * TODO/*w ww . ja v a 2 s . c o m*/ * * Establish the httpconnection with url for caller and then the caller can deal with the * httprequest result within ORConnectionDelegate instance. if check failed, return null. * * @param context global Android application context * @param httpMethod enum POST or GET * @param url the URL to connect to * @param useHTTPAuth indicates whether the HTTP 'Authentication' header should be added * to the HTTP request * * @return TODO * * @throws IOException if the URL cannot be resolved by DNS (UnknownHostException), * if the URL was not correctly formed (MalformedURLException), * if the connection timed out (SocketTimeoutException), * there was an error in the HTTP protocol (ClientProtocolException), * or any other IO error occured (generic IOException) */ public static HttpResponse checkURLWithHTTPProtocol(Context context, ORHttpMethod httpMethod, String urlString, boolean useHTTPAuth) throws IOException { // TODO : could move this method to ORNetworkCheck class, no one else is using it. // // TODO : use URL in the API instead of string // // Validate the URL by creating a proper URL instance from the string... it will throw // an MalformedURLException (IOException) in case the URL was invalid. // // This can go away when the API is fixed... URL targetURL = new URL(urlString); URI targetURI; try { targetURI = targetURL.toURI(); } catch (URISyntaxException e) { // Not sure if we're ever going to hit this, but in case we do, just convert to // MalformedURLException... throw new MalformedURLException( "Could not convert " + urlString + " to a compliant URI: " + e.getMessage()); } HttpRequestBase request = null; HttpResponse response = null; HttpParams params = new BasicHttpParams(); // TODO : seems like timeouts ought to be externalized... HttpConnectionParams.setConnectionTimeout(params, 5 * 1000); HttpConnectionParams.setSoTimeout(params, 5 * 1000); HttpClient client = new DefaultHttpClient(params); switch (httpMethod) { case POST: request = new HttpPost(targetURI); break; case GET: request = new HttpGet(targetURI); break; default: throw new IOException("Unsupported HTTP Method: " + httpMethod); } if (useHTTPAuth) { SecurityUtil.addCredentialToHttpRequest(context, request); } if ("https".equals(targetURL.getProtocol())) { Scheme sch = new Scheme(targetURL.getProtocol(), new SelfCertificateSSLSocketFactory(context), targetURL.getPort()); client.getConnectionManager().getSchemeRegistry().register(sch); } try { response = client.execute(request); } catch (IllegalArgumentException e) { throw new MalformedURLException("Illegal argument: " + e.getMessage()); } return response; }
From source file:com.ngdata.hbaseindexer.indexer.FusionPipelineClient.java
protected FusionSession establishSession(String url, String user, String password, String realm) throws Exception { FusionSession fusionSession = new FusionSession(); if (!isKerberos && realm != null) { int at = url.indexOf("/api"); String proxyUrl = url.substring(0, at); String sessionApi = proxyUrl + "/api/session?realmName=" + realm; String jsonString = "{\"username\":\"" + user + "\", \"password\":\"" + password + "\"}"; // TODO: ugly! URL sessionApiUrl = new URL(sessionApi); String sessionHost = sessionApiUrl.getHost(); try {/*from w ww .j a va2 s. com*/ clearCookieForHost(sessionHost); } catch (Exception exc) { log.warn("Failed to clear session cookie for " + sessionHost + " due to: " + exc); } HttpPost postRequest = new HttpPost(sessionApiUrl.toURI()); postRequest.setEntity( new StringEntity(jsonString, ContentType.create("application/json", StandardCharsets.UTF_8))); HttpClientContext context = HttpClientContext.create(); context.setCookieStore(cookieStore); HttpResponse response = httpClient.execute(postRequest, context); HttpEntity entity = response.getEntity(); try { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200 && statusCode != 201 && statusCode != 204) { String body = extractResponseBodyText(entity); throw new SolrException(SolrException.ErrorCode.getErrorCode(statusCode), "POST credentials to Fusion Session API [" + sessionApi + "] failed due to: " + response.getStatusLine() + ": " + body); } else if (statusCode == 401) { // retry in case this is an expired error String body = extractResponseBodyText(entity); if (body != null && body.indexOf("session-idle-timeout") != -1) { EntityUtils.consume(entity); // have to consume the previous entity before re-trying the request log.warn( "Received session-idle-timeout error from Fusion Session API, re-trying to establish a new session to " + url); try { clearCookieForHost(sessionHost); } catch (Exception exc) { log.warn("Failed to clear session cookie for " + sessionHost + " due to: " + exc); } response = httpClient.execute(postRequest, context); entity = response.getEntity(); statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200 && statusCode != 201 && statusCode != 204) { body = extractResponseBodyText(entity); throw new SolrException(SolrException.ErrorCode.getErrorCode(statusCode), "POST credentials to Fusion Session API [" + sessionApi + "] failed due to: " + response.getStatusLine() + ": " + body); } } } } finally { if (entity != null) EntityUtils.consume(entity); } log.info("Established secure session with Fusion Session API on " + url + " for user " + user + " in realm " + realm); } fusionSession.sessionEstablishedAt = System.nanoTime(); URL fusionUrl = new URL(url); String hostAndPort = fusionUrl.getHost() + ":" + fusionUrl.getPort(); fusionSession.docsSentMeter = getMeterByHost("Docs Sent to Fusion", hostAndPort); return fusionSession; }
From source file:org.bedework.calsvc.scheduling.hosts.IscheduleClient.java
private BasicHttpClient getCio(final String urlStr) throws Throwable { URL url = new URL(urlStr); String host = url.getHost();//from ww w . j av a2 s . co m int port = url.getPort(); String proto = url.getProtocol(); boolean secure = "https".equals(proto); BasicHttpClient cio = cioTable.get(host + port + secure); if (cio == null) { cio = new BasicHttpClient(30 * 1000, false); // followRedirects cioTable.put(host + port + secure, cio); } return cio; }
From source file:org.spiffyui.server.AuthServlet.java
private void doLogout(HttpServletRequest request, HttpServletResponse response, String token, String tsUrl) throws ServletException, IOException { if (token == null || tsUrl == null) { returnError(response, "Logout requires a token and a token server URL", RESTAuthConstants.INVALID_LOGOUT_REQUEST); return;//from w w w . j a va 2 s. c om } LOGGER.info("Making logout request for " + token + " to server " + tsUrl); try { validateURI(request, tsUrl); } catch (IllegalArgumentException iae) { returnError(response, iae.getMessage(), RESTAuthConstants.INVALID_TS_URL); return; } HttpClient httpclient = new DefaultHttpClient(); URI.create(tsUrl); URL url = new URL(tsUrl); LOGGER.info("url: " + url); if (url.getProtocol() != null && url.getProtocol().equalsIgnoreCase("https")) { setupClientSSL(httpclient, url.getPort()); } HttpDelete httpdel = new HttpDelete(tsUrl + "/" + URLEncoder.encode(token, "UTF-8")); httpdel.setHeader("Accept", "application/json"); httpdel.setHeader("Accept-Charset", "UTF-8"); httpdel.setHeader("Authorization", request.getHeader("Authorization")); httpdel.setHeader("TS-URL", request.getHeader("TS-URL")); // Execute the request HttpResponse authResponse = httpclient.execute(httpdel); int status = authResponse.getStatusLine().getStatusCode(); if (status == 404) { LOGGER.info("The authentication server " + tsUrl + " was not found."); returnError(response, "The token server URL was not found", RESTAuthConstants.NOTFOUND_TS_URL); return; } // Get hold of the response entity HttpEntity entity = authResponse.getEntity(); StringBuffer authResponseData = new StringBuffer(); // If the response does not enclose an entity, there is no need // to worry about connection release if (entity != null) { InputStream instream = entity.getContent(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(instream)); // do something useful with the response authResponseData.append(reader.readLine()); } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. httpdel.abort(); LOGGER.throwing(AuthServlet.class.getName(), "doLogout", ex); throw ex; } finally { // Closing the input stream will trigger connection release if (reader != null) { reader.close(); } } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } //Now we write the response back to our client. response.setStatus(status); OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); out.write(authResponseData.toString()); out.flush(); out.close(); }
From source file:de.jlo.talendcomp.jasperrepo.RepositoryClient.java
public String getCurrentDownloadLink() throws MalformedURLException { URL url = new URL(server.getUrl()); String path = url.getPath();// www . j av a2s . c o m int pos = path.indexOf('/', 1); StringBuilder sb = new StringBuilder(); sb.append(url.getProtocol()); sb.append("://"); sb.append(url.getHost()); if (url.getPort() != 80) { sb.append(":"); sb.append(url.getPort()); } sb.append(path.substring(0, pos)); sb.append(fileViewUri); sb.append(currentUri); return sb.toString(); }
From source file:cn.com.loopj.android.http.AsyncHttpClient.java
/** * Will encode url, if not disabled, and adds params on the end of it * * @param url String with URL, should be valid URL without params * @param params RequestParams to be appended on the end of URL * @param shouldEncodeUrl whether url should be encoded (replaces spaces with %20) * @return encoded url if requested with params appended if any available *///www . j av a2 s. c o m public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams params) { if (url == null) return null; if (shouldEncodeUrl) { try { String decodedURL = URLDecoder.decode(url, "UTF-8"); URL _url = new URL(decodedURL); URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(), _url.getPath(), _url.getQuery(), _url.getRef()); url = _uri.toASCIIString(); } catch (Exception ex) { // Should not really happen, added just for sake of validity log.e(LOG_TAG, "getUrlWithQueryString encoding URL", ex); } } if (params != null) { // Construct the query string and trim it, in case it // includes any excessive white spaces. String paramString = params.getParamString().trim(); // Only add the query string if it isn't empty and it // isn't equal to '?'. if (!paramString.equals("") && !paramString.equals("?")) { url += url.contains("?") ? "&" : "?"; url += paramString; } } return url; }
From source file:com.twinsoft.convertigo.beans.steps.TransactionStep.java
protected void prepareForRequestable(Context javascriptContext, Scriptable scope) throws MalformedURLException, EngineException { Transaction targetTransaction = getTargetTransaction(); Connector targetConnector = targetTransaction.getConnector(); String ctxName = getContextName(javascriptContext, scope); boolean useSequenceJSession = sequence.useSameJSessionForSteps(); String connectionStringValue = (String) getConnectionStringValue(); if (isInternalInvoke()) { request.put(Parameter.Project.getName(), new String[] { projectName }); // request.put(Parameter.Pool.getName(), new String[] { "" }); request.put(Parameter.MotherSequenceContext.getName(), new String[] { sequence.context.contextID }); request.put(Parameter.Transaction.getName(), new String[] { targetTransaction.getName() }); request.put(Parameter.Connector.getName(), new String[] { targetConnector.getName() }); request.put(Parameter.Context.getName(), new String[] { sequence.addStepContextName(ctxName) }); request.put(Parameter.SessionId.getName(), new String[] { getTransactionSessionId() }); if (!connectionStringValue.equals("")) request.put(Parameter.ConnectorConnectionString.getName(), new String[] { connectionStringValue }); getPostQuery(scope);//from w w w . ja v a 2 s . c om } else { targetUrl = EnginePropertiesManager.getProperty(PropertyName.APPLICATION_SERVER_CONVERTIGO_URL); targetUrl += "/projects/" + projectName + "/.xml?"; URL url = new URL(targetUrl); String host = url.getHost(); int port = url.getPort(); Engine.logBeans.trace("(TransactionStep) Host: " + host + ":" + port); hostConfiguration.setHost(host, port); method = new PostMethod(targetUrl); HeaderName.ContentType.setRequestHeader(method, MimeType.WwwForm.value()); // Set transaction sessionId from context maintainer String sessionId = getTransactionSessionId(); if (useSequenceJSession) { Engine.logBeans.trace("(TransactionStep) JSESSIONID required : " + sessionId); if (sessionId != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + sessionId + ";"); Engine.logBeans.trace("(TransactionStep) JSESSIONID used : " + sessionId); } else { Engine.logBeans.trace("(TransactionStep) JSESSIONID is null"); } } else { if (sessionId != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + sessionId + ";"); Engine.logBeans.trace("(TransactionStep) Transaction JSESSIONID used : " + sessionId); } else { Engine.logBeans.trace("(TransactionStep) Transaction JSESSIONID is null"); } } String postQuery = getPostQuery(scope); if (postQuery.indexOf(Parameter.Connector.getName()) == -1) postQuery = addParamToPostQuery(Parameter.Connector.getName(), targetConnector.getName(), postQuery); if (postQuery.indexOf(Parameter.Transaction.getName()) == -1) postQuery = addParamToPostQuery(Parameter.Transaction.getName(), targetTransaction.getName(), postQuery); if (postQuery.indexOf(Parameter.MotherSequenceContext.getName()) == -1) postQuery = addParamToPostQuery(Parameter.MotherSequenceContext.getName(), sequence.context.contextID, postQuery); if (postQuery.indexOf(Parameter.Context.getName()) == -1) postQuery = addParamToPostQuery(Parameter.Context.getName(), sequence.addStepContextName(ctxName), postQuery); if (!connectionStringValue.equals("")) postQuery = addParamToPostQuery(Parameter.ConnectorConnectionString.getName(), connectionStringValue, postQuery); if (Engine.logBeans.isTraceEnabled()) Engine.logBeans.trace("(TransactionStep) postQuery :" + Visibility.Logs.replaceVariables(getVariables(), postQuery)); try { method.setRequestEntity(new StringRequestEntity(postQuery, null, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new EngineException("Encoding error", e); } } }
From source file:com.esri.geoevent.solutions.processor.geometry.QueryReportProcessor.java
public void CreateQueryMap() { Collection<ArcGISServerConnection> serviceConnections = this.connectionManager.getArcGISServerConnections(); Iterator<ArcGISServerConnection> it = serviceConnections.iterator(); ArcGISServerConnection conn;//from w w w.j av a 2s .c o m while (it.hasNext()) { conn = it.next(); //String connName = conn.getName(); String[] folders = conn.getFolders(); URL url = conn.getUrl(); String baseUrl = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + url.getPath() + "rest/services/"; //HashMap<String, Object> folderMap = new HashMap<String, Object>(); for (int i = 0; i < folders.length; ++i) { String path = baseUrl + folders[i] + "/"; String folder = folders[i]; String[] fservices = conn.getFeatureServices(folder); //HashMap<String,Object>serviceMap = new HashMap<String,Object>(); for (int j = 0; j < fservices.length; ++j) { String fs = fservices[j]; path += fs + "/FeatureServer/"; String fqService = folder + "_" + fs; String pdName = "use_" + fqService; pdName = pdName.replace(" ", "_"); if ((Boolean) properties.get(pdName).getValue()) { ArrayList<Layer> layers = (ArrayList<Layer>) conn.getLayers(folder, fs, ArcGISServerType.FeatureServer); //HashMap<String, Object> layerMap = new HashMap<String, Object>(); for (int k = 0; k < layers.size(); ++k) { HashMap<String, Object> query = new HashMap<String, Object>(); HashMap<String, String> fieldMap = new HashMap<String, String>(); String fldsString = ""; Field[] fields = conn.getFields(folder, fs, k, ArcGISServerType.FeatureServer); Boolean usingDist = false; String curPath = ""; String restpath = ""; String lyrHeaderCfg = ""; String distToken = ""; String distUnits = ""; String wc = ""; String itemConfig = ""; String curLyr = layers.get(k).getName(); String lyrName = fqService + "_" + ((Integer) k).toString(); lyrName = lyrName.replace(" ", "_"); if ((Boolean) properties.get(lyrName).getValue()) { curPath = path + ((Integer) k).toString(); restpath = path + ((Integer) k).toString() + "/query?"; wc = properties.get(lyrName + "_whereclause").getValueAsString(); lyrHeaderCfg = properties.get(lyrName + "_header").getValueAsString(); usingDist = (Boolean) properties.get(lyrName + "_calcDistance").getValue(); if (usingDist) { distToken = properties.get(lyrName + "_dist_token").getValueAsString(); distUnits = properties.get(lyrName + "_dist_units").getValueAsString(); } itemConfig = properties.get(lyrName + "_config").getValueAsString(); Boolean first = true; for (int l = 0; l < fields.length; ++l) { String fld = fields[l].getName(); String fldPropName = lyrName + fld; fldPropName = fldPropName.replace(" ", "_"); if ((Boolean) properties.get(fldPropName).getValue()) { if (!first) { fldsString += ","; } else { first = false; } fldsString += fld; String fldToken = fldPropName + "_token"; String token = properties.get(fldToken).getValueAsString(); fieldMap.put(fld, token); } } query.put("restpath", restpath); query.put("path", curPath); query.put("whereclause", wc); query.put("fields", fldsString); query.put("outfields", fields); query.put("tokenMap", fieldMap); query.put("headerconfig", lyrHeaderCfg); query.put("usingdist", usingDist); query.put("distunits", distUnits); query.put("disttoken", distToken); query.put("itemconfig", itemConfig); query.put("layer", curLyr); UUID uid = UUID.randomUUID(); query.put("id", uid); queries.add(query); //layerMap.put(layers.get(k).getName(), fieldMap); } } } } //folderMap.put(folder, serviceMap); } //connmap.put(connName,folderMap); } }