List of usage examples for java.net URL getDefaultPort
public int getDefaultPort()
From source file:fedora.client.FedoraClient.java
/** * Get the appropriate API-A/M stub, given a SOAPEndpoint. *//* w w w.ja v a 2s. c o m*/ private Object getSOAPStub(SOAPEndpoint endpoint) throws ServiceException, IOException { URL url = endpoint.getURL(); String protocol = url.getProtocol(); String host = url.getHost(); int port = url.getPort(); //String path = url.getPath(); if (port == -1) { port = url.getDefaultPort(); } if (endpoint == m_accessEndpoint) { APIAStubFactory.SOCKET_TIMEOUT_SECONDS = SOCKET_TIMEOUT_SECONDS; return APIAStubFactory.getStubAltPath(protocol, host, port, url.getPath(), m_user, m_pass); } else if (endpoint == m_managementEndpoint) { APIMStubFactory.SOCKET_TIMEOUT_SECONDS = SOCKET_TIMEOUT_SECONDS; return APIMStubFactory.getStubAltPath(protocol, host, port, url.getPath(), m_user, m_pass); } else { throw new IllegalArgumentException("Unrecognized endpoint: " + endpoint.getName()); } }
From source file:org.urbanstew.soundcloudapi.SoundCloudAPI.java
/** * Completes the OAuth 1.0a authorization steps with SoundCloud, assuming the consumer application * can use a local port to receive the verification code. * //from www .j a v a2 s .c o m * <p>The function acts as a minimal HTTP server and will listen on the port specified in the * <code>url</code> (or the default HTTP port, if no port is specified in the <code>url</code>). It will provide the * specified <code>response</code> when it receives a request for the path specified in the <code>url</code>, and * assuming the request includes the verification code, terminate successfully. * To all other requests it will respond with a <code>Not Found</code> error, and continue listening. * * <p>The following example assumes the consumer application is running on the client's computer / device. * Hence, it uses a local URL ("http://localhost:8088/") to receive the verification code callback. The function * will listen on specified port 8088 to receive the callback.</p> * * <pre> * {@code * soundcloudapi.authorizeUsingUrl * ( * "http://localhost:8088/", * "Thank you for authorizing", * new AuthorizationURLOpener() * { * public void openAuthorizationURL(String authorizationURL) * { * System.out.println("Please visit " + authorizationURL); * } * } * ); * } * </pre> * * @param url - a callback URL via which the user can provide the verification code. * @param response - a response given back to the user when they allow access and get redirected to the callback URL. * @param URLOpener - an AuthorizationURLOpener which can open the authorization URL to the user when needed. * * @return true if the process is completed successfully, false if the process was canceled via <code>cancelAuthorizeUsingUrl</code>. * * @throws OAuthCommunicationException * @throws OAuthExpectationFailedException * @throws OAuthNotAuthorizedException * @throws OAuthMessageSignerException * @throws IOException * @since 0.9.1 * @see #cancelAuthorizeUsingUrl() */ public boolean authorizeUsingUrl(final String url, final String response, final AuthorizationURLOpener URLOpener) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException, IOException { mCancelAuthorization = false; unauthorize(); URLOpener.openAuthorizationURL(obtainRequestToken(url)); URL parsedUrl = new URL(url); int port = parsedUrl.getPort(); if (port == -1) port = parsedUrl.getDefaultPort(); ServerSocket server = null; String verificationCode = null; try { server = new ServerSocket(port); server.setSoTimeout(500); while (verificationCode == null) { Socket socket = null; BufferedReader in = null; PrintWriter out = null; try { try { socket = server.accept(); } catch (java.io.InterruptedIOException e) { if (mCancelAuthorization) { unauthorize(); return false; } else continue; } in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String requestedUrl = in.readLine().split("\\s+")[1]; URL parsedRequestedUrl = new URL("http://localhost" + requestedUrl); out = new PrintWriter(socket.getOutputStream(), true); if (!parsedRequestedUrl.getPath().equals(parsedUrl.getPath())) out.print("HTTP/1.1 404 Not Found"); else { out.print("HTTP/1.1 200 OK\n\n" + response); for (String parameter : parsedRequestedUrl.getQuery().split("&")) { String[] keyValue = parameter.split("="); if (keyValue[0].equals("oauth_verifier")) verificationCode = keyValue[1]; } if (verificationCode == null) // problem - why didn't we get a verification code? verificationCode = ""; } out.flush(); } finally { closeQuietly(in); closeQuietly(out); closeQuietly(socket); } } } finally { closeQuietly(server); } if (verificationCode.length() > 0) { obtainAccessToken(verificationCode); return true; } else return false; }
From source file:org.apache.jmeter.protocol.http.visualizers.RequestViewHTTP.java
@Override public void setSamplerResult(Object objectResult) { this.searchTextExtension.resetTextToFind(); if (objectResult instanceof HTTPSampleResult) { HTTPSampleResult sampleResult = (HTTPSampleResult) objectResult; // Display with same order HTTP protocol requestModel.addRow(new RowResult(JMeterUtils.getResString("view_results_table_request_http_method"), //$NON-NLS-1$ sampleResult.getHTTPMethod())); // Parsed request headers LinkedHashMap<String, String> lhm = JMeterUtils.parseHeaders(sampleResult.getRequestHeaders()); for (Entry<String, String> entry : lhm.entrySet()) { headersModel.addRow(new RowResult(entry.getKey(), entry.getValue())); }//from w w w . ja v a 2s. co m URL hUrl = sampleResult.getURL(); if (hUrl != null) { // can be null - e.g. if URL was invalid requestModel .addRow(new RowResult(JMeterUtils.getResString("view_results_table_request_http_protocol"), //$NON-NLS-1$ hUrl.getProtocol())); requestModel.addRow(new RowResult(JMeterUtils.getResString("view_results_table_request_http_host"), //$NON-NLS-1$ hUrl.getHost())); int port = hUrl.getPort() == -1 ? hUrl.getDefaultPort() : hUrl.getPort(); requestModel.addRow(new RowResult(JMeterUtils.getResString("view_results_table_request_http_port"), //$NON-NLS-1$ Integer.valueOf(port))); requestModel.addRow(new RowResult(JMeterUtils.getResString("view_results_table_request_http_path"), //$NON-NLS-1$ hUrl.getPath())); String queryGet = hUrl.getQuery() == null ? "" : hUrl.getQuery(); //$NON-NLS-1$ boolean isMultipart = isMultipart(lhm); // Concatenate query post if exists String queryPost = sampleResult.getQueryString(); if (!isMultipart && StringUtils.isNotBlank(queryPost)) { if (queryGet.length() > 0) { queryGet += PARAM_CONCATENATE; } queryGet += queryPost; } if (StringUtils.isNotBlank(queryGet)) { Set<Entry<String, String[]>> keys = RequestViewHTTP.getQueryMap(queryGet).entrySet(); for (Entry<String, String[]> entry : keys) { for (String value : entry.getValue()) { paramsModel.addRow(new RowResult(entry.getKey(), value)); } } } if (isMultipart && StringUtils.isNotBlank(queryPost)) { String contentType = lhm.get(HTTPConstants.HEADER_CONTENT_TYPE); String boundaryString = extractBoundary(contentType); MultipartUrlConfig urlconfig = new MultipartUrlConfig(boundaryString); urlconfig.parseArguments(queryPost); for (JMeterProperty prop : urlconfig.getArguments()) { Argument arg = (Argument) prop.getObjectValue(); paramsModel.addRow(new RowResult(arg.getName(), arg.getValue())); } } } // Display cookie in headers table (same location on http protocol) String cookie = sampleResult.getCookies(); if (cookie != null && cookie.length() > 0) { headersModel .addRow(new RowResult(JMeterUtils.getParsedLabel("view_results_table_request_http_cookie"), //$NON-NLS-1$ sampleResult.getCookies())); } } else { // add a message when no http sample requestModel.addRow(new RowResult("", //$NON-NLS-1$ JMeterUtils.getResString("view_results_table_request_http_nohttp"))); //$NON-NLS-1$ } }
From source file:org.fcrepo.client.FedoraClient.java
/** * Get the appropriate API-A/M stub, given a SOAPEndpoint. * @param <T>//w w w .j ava 2 s . c o m */ private <T> T getSOAPStub(Class<T> type) throws ServiceException, IOException { if (type == org.fcrepo.server.access.FedoraAPIAMTOM.class) { org.fcrepo.client.mtom.APIAStubFactory.SOCKET_TIMEOUT_SECONDS = SOCKET_TIMEOUT_SECONDS; URL url = m_accessMTOMEndpoint.getURL(); String protocol = url.getProtocol(); String host = url.getHost(); int port = url.getPort(); if (port == -1) { port = url.getDefaultPort(); } return (T) org.fcrepo.client.mtom.APIAStubFactory.getStub(protocol, host, port, m_user, m_pass); } else if (type == FedoraAPIMMTOM.class) { org.fcrepo.client.mtom.APIMStubFactory.SOCKET_TIMEOUT_SECONDS = SOCKET_TIMEOUT_SECONDS; URL url = m_managementMTOMEndpoint.getURL(); String protocol = url.getProtocol(); String host = url.getHost(); int port = url.getPort(); if (port == -1) { port = url.getDefaultPort(); } return (T) org.fcrepo.client.mtom.APIMStubFactory.getStub(protocol, host, port, m_user, m_pass); } else if (type == FedoraAPIM.class) { org.fcrepo.client.APIMStubFactory.SOCKET_TIMEOUT_SECONDS = SOCKET_TIMEOUT_SECONDS; URL url = m_managementEndpoint.getURL(); String protocol = url.getProtocol(); String host = url.getHost(); int port = url.getPort(); if (port == -1) { port = url.getDefaultPort(); } return (T) org.fcrepo.client.APIMStubFactory.getStub(protocol, host, port, m_user, m_pass); } else if (type == FedoraAPIA.class) { org.fcrepo.client.APIAStubFactory.SOCKET_TIMEOUT_SECONDS = SOCKET_TIMEOUT_SECONDS; URL url = m_accessEndpoint.getURL(); String protocol = url.getProtocol(); String host = url.getHost(); int port = url.getPort(); if (port == -1) { port = url.getDefaultPort(); } return (T) org.fcrepo.client.APIAStubFactory.getStub(protocol, host, port, m_user, m_pass); } else { throw new IllegalArgumentException("Unrecognized api class: " + type.getName()); } }
From source file:org.dasein.cloud.opsource.OpSourceMethod.java
public Document invoke() throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + OpSource.class.getName() + ".invoke()"); }/*from www. j a v a2 s .c o m*/ try { URL url = null; try { url = new URL(endpoint); } catch (MalformedURLException e1) { throw new CloudException(e1); } final String host = url.getHost(); final int urlPort = url.getPort() == -1 ? url.getDefaultPort() : url.getPort(); final String urlStr = url.toString(); DefaultHttpClient httpclient = new DefaultHttpClient(); /** HTTP Authentication */ String uid = new String(provider.getContext().getAccessPublic()); String pwd = new String(provider.getContext().getAccessPrivate()); /** Type of authentication */ List<String> authPrefs = new ArrayList<String>(2); authPrefs.add(AuthPolicy.BASIC); httpclient.getParams().setParameter("http.auth.scheme-pref", authPrefs); httpclient.getCredentialsProvider().setCredentials(new AuthScope(host, urlPort, null), new UsernamePasswordCredentials(uid, pwd)); if (wire.isDebugEnabled()) { wire.debug("--------------------------------------------------------------> " + urlStr); wire.debug(""); } AbstractHttpMessage method = this.getMethod(parameters.get(OpSource.HTTP_Method_Key), urlStr); method.setParams(new BasicHttpParams().setParameter(urlStr, url)); /** Set headers */ method.addHeader(OpSource.Content_Type_Key, parameters.get(OpSource.Content_Type_Key)); /** POST/PUT method specific logic */ if (method instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityEnclosingMethod = (HttpEntityEnclosingRequest) method; String requestBody = parameters.get(OpSource.HTTP_Post_Body_Key); if (requestBody != null) { if (wire.isDebugEnabled()) { wire.debug(requestBody); } AbstractHttpEntity entity = new ByteArrayEntity(requestBody.getBytes()); entity.setContentType(parameters.get(OpSource.Content_Type_Key)); entityEnclosingMethod.setEntity(entity); } else { throw new CloudException("The request body is null for a post request"); } } /** Now parse the xml */ try { HttpResponse httpResponse; int status; if (wire.isDebugEnabled()) { for (org.apache.http.Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } } /** Now execute the request */ APITrace.trace(provider, method.toString() + " " + urlStr); httpResponse = httpclient.execute((HttpUriRequest) method); status = httpResponse.getStatusLine().getStatusCode(); if (wire.isDebugEnabled()) { wire.debug("invoke(): HTTP Status " + httpResponse.getStatusLine().getStatusCode() + " " + httpResponse.getStatusLine().getReasonPhrase()); } org.apache.http.Header[] headers = httpResponse.getAllHeaders(); HttpEntity entity = httpResponse.getEntity(); if (wire.isDebugEnabled()) { wire.debug("HTTP xml status code ---------" + status); for (org.apache.http.Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } /** Can not enable this line, otherwise the entity would be empty*/ // wire.debug("OpSource Response Body for request " + urlStr + " = " + EntityUtils.toString(entity)); wire.debug("-----------------"); } if (entity == null) { parseError(status, "Empty entity"); } String responseBody = EntityUtils.toString(entity); if (status == HttpStatus.SC_OK) { InputStream input = null; try { input = new ByteArrayInputStream(responseBody.getBytes("UTF-8")); if (input != null) { Document doc = null; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input); if (wire.isDebugEnabled()) { try { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); trans.transform(source, result); String xmlString = sw.toString(); wire.debug(xmlString); } catch (Exception ex) { ex.printStackTrace(); } } } catch (Exception ex) { ex.printStackTrace(); logger.debug(ex.toString(), ex); } return doc; } } catch (IOException e) { logger.error( "invoke(): Failed to read xml error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } /* catch( SAXException e ) { throw new CloudException(e); } catch( ParserConfigurationException e ) { throw new InternalException(e); } */ } else if (status == HttpStatus.SC_NOT_FOUND) { throw new CloudException("An internal error occured: The endpoint was not found"); } else { if (responseBody != null) { parseError(status, responseBody); Document parsedError = null; if (!responseBody.contains("<HR")) { parsedError = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new ByteArrayInputStream(responseBody.getBytes("UTF-8"))); if (wire.isDebugEnabled()) { try { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(parsedError); trans.transform(source, result); String xmlString = sw.toString(); wire.debug(xmlString); } catch (Exception ex) { ex.printStackTrace(); } } } else logger.debug("Error message was unparsable"); return parsedError; } } } catch (ParseException e) { throw new CloudException(e); } catch (SAXException e) { throw new CloudException(e); } catch (IOException e) { e.printStackTrace(); throw new CloudException(e); } catch (ParserConfigurationException e) { throw new CloudException(e); } finally { httpclient.getConnectionManager().shutdown(); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + OpSource.class.getName() + ".invoke()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------------> " + endpoint); } } return null; }
From source file:edu.uci.ics.crawler4j.url.URLCanonicalizer.java
public static String getCanonicalURL(String href, String context) { try {//from www . ja va2 s. c o m URL canonicalURL = new URL(UrlResolver.resolveUrl(context == null ? "" : context, href)); String host = canonicalURL.getHost().toLowerCase(); if (StringUtils.isBlank(host)) { // This is an invalid Url. return null; } String path = canonicalURL.getPath(); /* * Normalize: no empty segments (i.e., "//"), no segments equal to * ".", and no segments equal to ".." that are preceded by a segment * not equal to "..". */ path = new URI(path).normalize().toString(); /* * Convert '//' -> '/' */ int idx = path.indexOf("//"); while (idx >= 0) { path = path.replace("//", "/"); idx = path.indexOf("//"); } /* * Drop starting '/../' */ while (path.startsWith("/../")) { path = path.substring(3); } /* * Trim */ path = path.trim(); final SortedMap<String, String> params = createParameterMap(canonicalURL.getQuery()); final String queryString; if (params != null && params.size() > 0) { String canonicalParams = canonicalize(params); queryString = (canonicalParams.isEmpty() ? "" : "?" + canonicalParams); } else { queryString = ""; } /* * Add starting slash if needed */ if (path.length() == 0) { path = "/" + path; } /* * Drop default port: example.com:80 -> example.com */ int port = canonicalURL.getPort(); if (port == canonicalURL.getDefaultPort()) { port = -1; } String protocol = canonicalURL.getProtocol().toLowerCase(); String pathAndQueryString = normalizePath(path) + queryString; URL result = new URL(protocol, host, port, pathAndQueryString); return result.toExternalForm(); } catch (MalformedURLException ex) { return null; } catch (URISyntaxException ex) { return null; } }
From source file:nl.nn.adapterframework.http.HttpSenderBase.java
protected int getPort(URIBuilder uri) { int port = uri.getPort(); if (port < 1) { try {/*from ww w.j av a2s . c om*/ log.debug(getLogPrefix() + "looking up protocol for scheme [" + uri.getScheme() + "]"); URL url = uri.build().toURL(); port = url.getDefaultPort(); } catch (Exception e) { log.debug(getLogPrefix() + "protocol for scheme [" + uri.getScheme() + "] not found, setting port to 80", e); port = 80; } } return port; }
From source file:com.google.enterprise.connector.sharepoint.client.SharepointClientContext.java
/** * @param sharepointUrl/* www . j a va 2 s .c om*/ * @throws SharepointException */ public void setSiteURL(String sharepointUrl) throws SharepointException { sharepointUrl = sharepointUrl.trim(); if (sharepointUrl.endsWith(SPConstants.SLASH)) { sharepointUrl = sharepointUrl.substring(0, sharepointUrl.lastIndexOf(SPConstants.SLASH)); } try { final URL url = new URL(sharepointUrl); int port = url.getPort(); if (-1 == port) { port = url.getDefaultPort(); } siteURL = url.getProtocol() + SPConstants.URL_SEP + url.getHost() + SPConstants.COLON + port + url.getPath(); } catch (final MalformedURLException e) { throw new SharepointException("Failed to construct sharepoint URL...", e); } }
From source file:org.wyona.yanel.impl.resources.forgotpw.ForgotPassword.java
/** * Get forgot password URL which will be sent via E-Mail (also see YanelServlet#getRequestURLQS(HttpServletRequest, String, boolean)) * @param uuid UUID of forgot password request *///from w ww. j av a 2 s . c o m private String getURL(String uuid) throws Exception { //https://192.168.1.69:8443/yanel" + request.getServletPath().toString() URL url = new URL(request.getRequestURL().toString()); org.wyona.yanel.core.map.Realm realm = getRealm(); if (realm.isProxySet()) { // TODO: Finish proxy settings replacement String proxyHostName = realm.getProxyHostName(); log.debug("Proxy host name: " + proxyHostName); if (proxyHostName != null) { url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile()); } int proxyPort = realm.getProxyPort(); if (proxyPort >= 0) { url = new URL(url.getProtocol(), url.getHost(), proxyPort, url.getFile()); } else { url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile()); } String proxyPrefix = realm.getProxyPrefix(); if (proxyPrefix != null) { url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length())); } } else { log.warn("No proxy set."); } return url.toString() + "?" + PW_RESET_ID + "=" + uuid; }