Example usage for java.net URL getPort

List of usage examples for java.net URL getPort

Introduction

In this page you can find the example usage for java.net URL getPort.

Prototype

public int getPort() 

Source Link

Document

Gets the port number of this URL .

Usage

From source file:org.jboss.as.test.integration.security.loginmodules.IdentityLoginModuleTestCase.java

/**
 * Calls {@link PrincipalPrintingServlet} and checks if the returned principal name is the expected one.
 * //from w w  w .  ja  va2 s .c  om
 * @param url
 * @param expectedPrincipal
 * @return Principal name returned from {@link PrincipalPrintingServlet}
 */
private String assertPrincipal(URL url, String expectedPrincipal) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    Credentials creds = new UsernamePasswordCredentials("anyUsername");
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), creds);
    HttpGet httpget = new HttpGet(url.toExternalForm() + PrincipalPrintingServlet.SERVLET_PATH);
    String text;

    try {
        HttpResponse response = httpclient.execute(httpget);
        assertEquals("Unexpected status code", HttpServletResponse.SC_OK,
                response.getStatusLine().getStatusCode());
        text = EntityUtils.toString(response.getEntity());
    } catch (IOException e) {
        throw new RuntimeException("Servlet response IO exception", e);
    }

    assertEquals("Unexpected principal name assigned by IdentityLoinModule", expectedPrincipal, text);
    return text;
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.VitroURL.java

public VitroURL(String urlStr, String characterEncoding) {
    this.characterEncoding = characterEncoding;
    if (urlStr.indexOf("&") > -1) {
        wasXMLEscaped = true;/*from w  w  w  .ja v  a2s.c  om*/
        urlStr = StringEscapeUtils.unescapeXml(urlStr);
    }
    try {
        URL url = new URL(urlStr);
        this.protocol = url.getProtocol();
        this.host = url.getHost();
        this.port = Integer.toString(url.getPort());
        this.pathParts = splitPath(url.getPath());
        this.pathBeginsWithSlash = beginsWithSlash(url.getPath());
        this.pathEndsInSlash = endsInSlash(url.getPath());
        this.queryParams = parseQueryParams(url.getQuery());
        this.fragment = url.getRef();
    } catch (Exception e) {
        // Under normal circumstances, this is because the urlStr is relative
        // We'll assume that we just have a path and possibly a query string.
        // This is likely to be a bad assumption, but let's roll with it.
        Matcher m = pathPattern.matcher(urlStr);
        String[] urlParts = new String[2];
        if (m.matches()) {
            urlParts[0] = m.group(1);
            if (m.groupCount() == 2)
                urlParts[1] = m.group(2);
        } else {
            //???
        }

        try {
            this.pathParts = splitPath(URLDecoder.decode(getPath(urlStr), characterEncoding));
            this.pathBeginsWithSlash = beginsWithSlash(urlParts[0]);
            this.pathEndsInSlash = endsInSlash(urlParts[0]);
            if (urlParts.length > 1) {
                this.queryParams = parseQueryParams(URLDecoder.decode(urlParts[1], characterEncoding));
            }
        } catch (UnsupportedEncodingException uee) {
            log.error("Unable to use character encoding " + characterEncoding, uee);
        }
    }
}

From source file:org.modeshape.web.jcr.rest.client.http.HttpClientConnection.java

/**
 * @param server the server with the host and port information (never <code>null</code>)
 * @param url the URL that will be used in the request (never <code>null</code>)
 * @param method the HTTP request method (never <code>null</code>)
 * @throws Exception if there is a problem establishing the connection
 *//*from   w w w  . j  a v  a2s . c om*/
public HttpClientConnection(Server server, URL url, RequestMethod method) throws Exception {
    assert server != null;
    assert url != null;
    assert method != null;

    this.httpClient = new DefaultHttpClient();
    this.httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(server.getUser(), server.getPassword()));
    // determine the request type
    if (RequestMethod.GET == method) {
        this.request = new HttpGet();
    } else if (RequestMethod.DELETE == method) {
        this.request = new HttpDelete();
    } else if (RequestMethod.POST == method) {
        this.request = new HttpPost();
    } else if (RequestMethod.PUT == method) {
        this.request = new HttpPut();
    } else {
        throw new RuntimeException(unknownHttpRequestMethodMsg.text(method));
    }

    //set the accepts header to application/json
    this.request.setHeader("Accept", MediaType.APPLICATION_JSON);

    // set request URI
    this.request.setURI(url.toURI());
}

From source file:com.predic8.membrane.core.interceptor.rewrite.ReverseProxyingInterceptor.java

private boolean isSameSchemeHostAndPort(String location2, String location) throws MalformedURLException {
    try {/*from  w w w . ja  v a  2 s. c  om*/
        if (location.startsWith("/") || location2.startsWith("/"))
            return false; // no host info available
        URL loc2 = new URL(location2);
        URL loc1 = new URL(location);
        if (loc2.getProtocol() != null && !loc2.getProtocol().equals(loc1.getProtocol()))
            return false;
        if (loc2.getHost() != null && !loc2.getHost().equals(loc1.getHost()))
            return false;
        int loc2Port = loc2.getPort() == -1 ? loc2.getDefaultPort() : loc2.getPort();
        int loc1Port = loc1.getPort() == -1 ? loc1.getDefaultPort() : loc1.getPort();
        if (loc2Port != loc1Port)
            return false;
        return true;
    } catch (MalformedURLException e) {
        log.warn("", e); // TODO: fix these cases
        return false;
    }
}

From source file:fr.gael.dhus.datastore.scanner.ScannerFactory.java

private String showPublicURL(URL url) {
    String protocol = url.getProtocol();
    String host = url.getHost();//from w w w  .j  a v  a 2 s.c  om
    int port = url.getPort();
    String path = url.getFile();
    if (protocol == null)
        protocol = "";
    else
        protocol += "://";

    String s_port = "";
    if (port != -1)
        s_port = ":" + port;

    return protocol + host + s_port + path;
}

From source file:org.callimachusproject.test.WebResource.java

public void patch(String type, byte[] body) throws IOException {
    ByteArrayEntity entity = new ByteArrayEntity(body);
    entity.setContentType(type);//ww w  .  j  a  v a  2s.c o  m
    HttpPatch req = new HttpPatch(uri);
    req.setEntity(entity);
    DefaultHttpClient client = new DefaultHttpClient();
    URL url = req.getURI().toURL();
    int port = url.getPort();
    String host = url.getHost();
    PasswordAuthentication passAuth = Authenticator.requestPasswordAuthentication(url.getHost(),
            InetAddress.getByName(url.getHost()), port, url.getProtocol(), "", "digest", url,
            RequestorType.SERVER);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(passAuth.getUserName(),
            new String(passAuth.getPassword()));
    client.getCredentialsProvider().setCredentials(new AuthScope(host, port), credentials);
    client.execute(req, new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            StatusLine status = response.getStatusLine();
            int code = status.getStatusCode();
            if (code != 200 && code != 204) {
                Assert.assertEquals(status.getReasonPhrase(), 204, code);
            }
            return null;
        }
    });
}

From source file:org.talend.librariesmanager.maven.ArtifactsDeployer.java

private void installToRemote(HttpEntity entity, URL targetURL) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {/*  w w  w.  j a v a2 s  .co m*/
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(targetURL.getHost(), targetURL.getPort()),
                new UsernamePasswordCredentials(nexusServer.getUserName(), nexusServer.getPassword()));

        HttpPut httpPut = new HttpPut(targetURL.toString());
        httpPut.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPut);
        StatusLine statusLine = response.getStatusLine();
        int responseCode = statusLine.getStatusCode();
        EntityUtils.consume(entity);
        if (responseCode > 399) {
            if (responseCode == 500) {
                // ignor this error , if .pom already exist on server and deploy again will get this error
            } else if (responseCode == 401) {
                throw new BusinessException("Authrity failed");
            } else {
                throw new BusinessException(
                        "Deploy failed: " + responseCode + ' ' + statusLine.getReasonPhrase());
            }
        }
    } catch (Exception e) {
        throw new Exception(targetURL.toString(), e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.talend.components.dataprep.connection.DataPrepConnectionHandler.java

private String fetchDataSetId() throws IOException {
    if (dataSetName == null || authorisationHeader == null) {
        return null;
    }/*  w  w w  .ja  va2s . c om*/

    String result = null;

    URI uri = null;
    URL localUrl = new URL(url);
    try {
        uri = new URI(localUrl.getProtocol(), null, localUrl.getHost(), localUrl.getPort(), "/api/datasets",
                "name=" + dataSetName, null);
    } catch (URISyntaxException e) {
        throw new ComponentException(e);
    }

    Request request = Request.Get(uri);
    request.addHeader(authorisationHeader);
    HttpResponse response = request.execute().returnResponse();
    String content = extractResponseInformationAndConsumeResponse(response);

    if (returnStatusCode(response) != HttpServletResponse.SC_OK) {
        throw new IOException(content);
    }

    if (content != null && !"".equals(content)) {
        Object object = JsonReader.jsonToJava(content);
        if (object != null && object instanceof Object[]) {
            Object[] array = (Object[]) object;
            if (array.length > 0) {
                @SuppressWarnings("rawtypes")
                JsonObject jo = (JsonObject) array[0];
                result = (String) jo.get("id");
            }
        }
    }

    return result;
}

From source file:org.seedstack.w20.internal.W20BridgeIT.java

@Test
@RunAsClient//from w ww.ja  va  2s.  c  om
public void paths_are_correctly_built(@ArquillianResource URL baseUrl) {
    String response = given().auth().basic("ThePoltergeist", "bouh").expect().statusCode(200).when()
            .get(baseUrl.toString() + "seed-w20/application/configuration").getBody().asString();
    String prefix = baseUrl.toString().substring(
            (baseUrl.getProtocol() + "://" + baseUrl.getHost() + ":" + baseUrl.getPort()).length(),
            baseUrl.toString().length() - 1);
    assertThat(response).contains("\"components-path\":\"" + prefix + "/bower_components\"");
    assertThat(response).contains("\"components-path-slash\":\"" + prefix + "/bower_components/\"");
    assertThat(response).contains("\"seed-base-path\":\"" + prefix + "\"");
    assertThat(response).contains("\"seed-base-path-slash\":\"" + prefix + "/\"");
    assertThat(response).contains("\"seed-rest-path\":\"" + prefix + "\"");
    assertThat(response).contains("\"seed-rest-path-slash\":\"" + prefix + "/\"");

}

From source file:org.openremote.android.console.util.AsyncGroupLoader.java

@Override
public void run() {
    synchronized (this) {
        String server = AppSettingsModel.getSecuredServer(context);
        if (!TextUtils.isEmpty(server)) {
            HttpResponse response = null;
            try {
                URL url = new URL(server + "/rest/device/group");
                HttpGet request = new HttpGet(url.toString());
                HttpClient client = new DefaultHttpClient();
                Scheme sch = new Scheme(url.getProtocol(), new SelfCertificateSSLSocketFactory(context),
                        url.getPort());
                client.getConnectionManager().getSchemeRegistry().register(sch);

                response = client.execute(request);
            } catch (ClientProtocolException e) {
                Log.e(LOG_CATEGORY + " run:", e.getMessage());
            } catch (IOException e) {
                Log.e(LOG_CATEGORY + " run:", e.getMessage());
            }//from  w  w  w .  ja  v a 2 s  .  c  o m

            String group = "";
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                String tmp;
                try {
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent()));
                    while ((tmp = in.readLine()) != null) {
                        group += tmp;
                    }
                } catch (IOException e) {
                    Log.e(LOG_CATEGORY + " urlConnectionDidReceiveData:", e.getMessage());
                }

            }
            AppSettingsModel.setGroup(context, group);
        }
        done = true;
        notify();
    }
}