List of usage examples for java.net URL getPort
public int getPort()
From source file:io.github.gsteckman.rpi_rest.SubscriptionManager.java
/** * Generates the UPnP NOTIFY message string. * //from w ww . jav a2 s.c o m * @param url * URL for the subscriber. * @param contentType * Content type header. * @param body * message body content * @param uuid * The universally unique subscription ID. * @param si * Subscription info used to complete the message * @return The String for the message that should be transmitted to the subscriber. */ private String generateNotify(final URL url, String contentType, String body, UUID uuid, SubscriptionInfo si) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.printf("NOTIFY %s HTTP/1.1\r\n", url.getPath()); pw.printf("HOST: %s:%d\r\n", url.getHost(), url.getPort()); pw.printf("CONTENT-TYPE: %s\r\n", contentType); pw.printf("NT: upnp:event\r\n"); pw.printf("NTS: upnp:propchange\r\n"); pw.printf("SID: uuid:%s\r\n", uuid.toString()); pw.printf("SEQ: %d\r\n", si.eventKey); pw.printf("CONTENT-LENGTH: %d\r\n", body.length()); pw.printf("\r\n"); pw.print(body); pw.flush(); String resp = sw.toString(); pw.close(); return resp; }
From source file:de.laeubisoft.tools.ant.validation.W3CMarkupValidationTask.java
/** * Takes an {@link URL} and tries to find out all linked resources * /*from w ww. j a v a2s. c o m*/ * @param uriToRecurse * @return a set of discovered urls */ private Set<URL> recurseInto(final URL uriToRecurse) throws BuildException { final Set<URL> urlsFound = new HashSet<URL>(); XMLReader reader = new Parser(); reader.setContentHandler(new DefaultHandler() { @Override public void startElement(String nsuri, String localName, String qName, Attributes attributes) throws SAXException { if ("a".equalsIgnoreCase(qName)) { String value = attributes.getValue("href"); if (value != null) { try { URL url = new URL(uriToRecurse, value); if (url.getHost().equalsIgnoreCase(uriToRecurse.getHost()) && url.getPort() == uriToRecurse.getPort()) { urlsFound.add(url); } } catch (MalformedURLException e) { log("can't parse URL for href = " + value + ", it will be ignored!", Project.MSG_ERR); } } } } }); // Parsen wird gestartet try { reader.parse(new InputSource(uriToRecurse.openStream())); return urlsFound; } catch (IOException e) { throw new BuildException("error while accessing data at " + uriToRecurse, e); } catch (SAXException e) { throw new BuildException("error while parsing data at " + uriToRecurse, e); } }
From source file:org.jenkinsci.plugins.GitLabSecurityRealm.java
private String buildRedirectUrl(StaplerRequest request) throws MalformedURLException { URL currentUrl = new URL(request.getRequestURL().toString()); URL redirect_uri = new URL(currentUrl.getProtocol(), currentUrl.getHost(), currentUrl.getPort(), request.getContextPath() + "/securityRealm/finishLogin"); return redirect_uri.toString(); }
From source file:de.innovationgate.utils.URLBuilder.java
/** * Creates a URLBuilder that parses an existing URL * @param url The URL to parse/* w ww . j a va 2s .c o m*/ * @param encoding The encoding of URL parameters. The URLBuilder will decode them. */ public URLBuilder(URL url, String encoding) { this(url.getProtocol(), url.getPort(), url.getHost(), url.getPath(), url.getQuery(), url.getRef(), encoding); }
From source file:com.haulmont.cuba.desktop.App.java
protected String getUserFriendlyConnectionUrl(String urlString) { try {/*from w w w . j av a 2 s. co m*/ URL url = new URL(urlString); return url.getHost() + (url.getPort() == -1 ? "" : ":" + url.getPort()); } catch (MalformedURLException e) { return urlString; } }
From source file:net.sbbi.upnp.messages.StateVariableMessage.java
/** * Executes the state variable query and retuns the UPNP device response, according to the UPNP specs, * this method could take up to 30 secs to process ( time allowed for a device to respond to a request ) * @return a state variable response object containing the variable value * @throws IOException if some IOException occurs during message send and reception process * @throws UPNPResponseException if an UPNP error message is returned from the server * or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message ) */// w ww. j a v a2 s .com public StateVariableResponse service() throws IOException, UPNPResponseException { StateVariableResponse rtrVal = null; UPNPResponseException upnpEx = null; IOException ioEx = null; StringBuffer body = new StringBuffer(256); body.append("<?xml version=\"1.0\"?>\r\n"); body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\""); body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"); body.append("<s:Body>"); body.append("<u:QueryStateVariable xmlns:u=\"urn:schemas-upnp-org:control-1-0\">"); body.append("<u:varName>").append(serviceStateVar.getName()).append("</u:varName>"); body.append("</u:QueryStateVariable>"); body.append("</s:Body>"); body.append("</s:Envelope>"); if (log.isDebugEnabled()) log.debug("POST prepared for URL " + service.getControlURL()); URL url = new URL(service.getControlURL().toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); HttpURLConnection.setFollowRedirects(false); //conn.setConnectTimeout( 30000 ); conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort()); conn.setRequestProperty("SOAPACTION", "\"urn:schemas-upnp-org:control-1-0#QueryStateVariable\""); conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\""); conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length())); OutputStream out = conn.getOutputStream(); out.write(body.toString().getBytes()); out.flush(); conn.connect(); InputStream input = null; if (log.isDebugEnabled()) log.debug("executing query :\n" + body); try { input = conn.getInputStream(); } catch (IOException ex) { // java can throw an exception if he error code is 500 or 404 or something else than 200 // but the device sends 500 error message with content that is required // this content is accessible with the getErrorStream input = conn.getErrorStream(); } if (input != null) { int response = conn.getResponseCode(); String responseBody = getResponseBody(input); if (log.isDebugEnabled()) log.debug("received response :\n" + responseBody); SAXParserFactory saxParFact = SAXParserFactory.newInstance(); saxParFact.setValidating(false); saxParFact.setNamespaceAware(true); StateVariableResponseParser msgParser = new StateVariableResponseParser(serviceStateVar); StringReader stringReader = new StringReader(responseBody); InputSource src = new InputSource(stringReader); try { SAXParser parser = saxParFact.newSAXParser(); parser.parse(src, msgParser); } catch (ParserConfigurationException confEx) { // should never happen // we throw a runtimeException to notify the env problem throw new RuntimeException( "ParserConfigurationException during SAX parser creation, please check your env settings:" + confEx.getMessage()); } catch (SAXException saxEx) { // kind of tricky but better than nothing.. upnpEx = new UPNPResponseException(899, saxEx.getMessage()); } finally { try { input.close(); } catch (IOException ex) { // ignoring } } if (upnpEx == null) { if (response == HttpURLConnection.HTTP_OK) { rtrVal = msgParser.getStateVariableResponse(); } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) { upnpEx = msgParser.getUPNPResponseException(); } else { ioEx = new IOException("Unexpected server HTTP response:" + response); } } } try { out.close(); } catch (IOException ex) { // ignore } conn.disconnect(); if (upnpEx != null) { throw upnpEx; } if (rtrVal == null && ioEx == null) { ioEx = new IOException("Unable to receive a response from the UPNP device"); } if (ioEx != null) { throw ioEx; } return rtrVal; }
From source file:ch.cyberduck.core.gdocs.GDSession.java
protected HttpURLConnection getConnection(URL url) throws IOException { URLConnection c = null;/* w ww .ja va 2 s . c o m*/ if (Preferences.instance().getBoolean("connection.proxy.enable")) { final Proxy proxy = ProxyFactory.instance(); if (proxy.isHTTPSProxyEnabled(new Host(Protocol.GDOCS_SSL, url.getHost(), url.getPort()))) { c = url.openConnection(new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)))); } } if (null == c) { log.debug("Direct connection"); c = url.openConnection(); } c.setConnectTimeout(timeout()); c.setReadTimeout(timeout()); if (c instanceof HttpsURLConnection) { ((HttpsURLConnection) c).setSSLSocketFactory( new CustomTrustSSLProtocolSocketFactory(this.getTrustManager(url.getHost()))); ((HttpsURLConnection) c).setHostnameVerifier(new HostnameVerifier() { public boolean verify(String s, javax.net.ssl.SSLSession sslSession) { return true; } }); } if (c instanceof HttpURLConnection) { return (HttpURLConnection) c; } throw new ConnectionCanceledException("Invalid URL connection:" + c); }
From source file:at.spardat.xma.boot.transport.HTTPTransport.java
/** * Get the used port of the url. If no port is defined in the url, * the default port of the protocol is returned. *//* w w w. j a v a 2 s . c om*/ int getPort(URL url) { int port = url.getPort(); if (port == -1) { port = url.getDefaultPort(); } return port; }
From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java
/** * Verifies the signing certificate chain URL and returns a {@code URL} object. * * @param signingCertificateChainUrl/*from ww w .j ava 2 s . c o m*/ * the external form of the URL * @return the URL * @throws CertificateException * if the URL is malformed or contains an invalid hostname, an unsupported protocol, * or an invalid port (if specified) */ static URL getAndVerifySigningCertificateChainUrl(final String signingCertificateChainUrl) throws CertificateException { try { URL url = new URI(signingCertificateChainUrl).normalize().toURL(); // Validate the hostname if (!VALID_SIGNING_CERT_CHAIN_URL_HOST_NAME.equalsIgnoreCase(url.getHost())) { throw new CertificateException(String.format( "SigningCertificateChainUrl [%s] does not contain the required hostname" + " of [%s]", signingCertificateChainUrl, VALID_SIGNING_CERT_CHAIN_URL_HOST_NAME)); } // Validate the path prefix String path = url.getPath(); if (!path.startsWith(VALID_SIGNING_CERT_CHAING_URL_PATH_PREFIX)) { throw new CertificateException(String.format( "SigningCertificateChainUrl path [%s] is invalid. Expecting path to " + "start with [%s]", signingCertificateChainUrl, VALID_SIGNING_CERT_CHAING_URL_PATH_PREFIX)); } // Validate the protocol String urlProtocol = url.getProtocol(); if (!VALID_SIGNING_CERT_CHAIN_PROTOCOL.equalsIgnoreCase(urlProtocol)) { throw new CertificateException( String.format("SigningCertificateChainUrl [%s] contains an unsupported protocol [%s]", signingCertificateChainUrl, urlProtocol)); } // Validate the port uses the default of 443 for HTTPS if explicitly defined in the URL int urlPort = url.getPort(); if ((urlPort != UNSPECIFIED_SIGNING_CERT_CHAIN_URL_PORT_VALUE) && (urlPort != url.getDefaultPort())) { throw new CertificateException( String.format("SigningCertificateChainUrl [%s] contains an invalid port [%d]", signingCertificateChainUrl, urlPort)); } return url; } catch (IllegalArgumentException | MalformedURLException | URISyntaxException ex) { throw new CertificateException( String.format("SigningCertificateChainUrl [%s] is malformed", signingCertificateChainUrl), ex); } }
From source file:org.spiffyui.server.AuthServlet.java
private void doLogin(HttpServletRequest request, HttpServletResponse response, String user, String pwd, String tsUrl, String logoutUrl) throws ServletException, IOException, JSONException { LOGGER.info("Making login request for " + user + " to server " + tsUrl); OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); if (user == null || pwd == null || tsUrl == null) { returnError(response, "Login requires a username, password, and token server URL", RESTAuthConstants.INVALID_LOGIN_REQUEST); return;// w w w.ja va 2s . co m } try { if (!validateURI(request, tsUrl)) { returnError(response, tsUrl, RESTAuthConstants.INVALID_TS_URL); return; } } catch (IllegalArgumentException iae) { returnError(response, iae.getMessage(), RESTAuthConstants.INVALID_TS_URL); return; } catch (MalformedURLException iae) { returnError(response, iae.getMessage(), RESTAuthConstants.INVALID_TS_URL); return; } HttpClient httpclient = new DefaultHttpClient(); URI.create(tsUrl); URL url = new URL(tsUrl); if (url.getProtocol() != null && url.getProtocol().equalsIgnoreCase("https")) { setupClientSSL(httpclient, url.getPort()); } HttpPost httppost = new HttpPost(tsUrl); httppost.setHeader("Accept", "application/json"); httppost.setHeader("Accept-Charset", "UTF-8"); httppost.setHeader("Authorization", BASIC_AUTH + " " + new String(Base64.encodeBase64(new String(user + ":" + pwd).getBytes("UTF-8")))); httppost.setHeader("NovellRptSignOffUri", logoutUrl); // Execute the request HttpResponse authResponse = httpclient.execute(httppost); int status = authResponse.getStatusLine().getStatusCode(); if (status == 404) { returnError(response, "The token server URL was not found", RESTAuthConstants.NOTFOUND_TS_URL); return; } sendLoginResponse(response, authResponse, status, httppost, out, httpclient); }