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:com.crazytest.config.TestCase.java

protected void postWithCredential(String endpoint, List<NameValuePair> params)
        throws UnsupportedEncodingException, URISyntaxException, MalformedURLException {
    String endpointString = hostUrl + endpoint + "?auth-key=" + this.authToken + "&token=" + this.authToken
            + "&userID=" + this.userID;

    URL url = new URL(endpointString);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    HttpPost postRequest = new HttpPost(uri);
    postRequest.setEntity(new UrlEncodedFormEntity(params));

    postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    postRequest.setHeader("User-Agent", "Safari");
    this.postRequest = postRequest;

    LOGGER.info("request:{}", postRequest.getRequestLine());
    LOGGER.info("request:{}", postRequest.getParams().getParameter("licenseeID"));
}

From source file:com.crazytest.config.TestCase.java

protected void postWithCredential(String endpoint, StringEntity params)
        throws UnsupportedEncodingException, URISyntaxException, MalformedURLException {
    String endpointString = hostUrl + endpoint + "?auth-key=" + this.authToken + "&token=" + this.authToken
            + "&userID=" + this.userID;

    URL url = new URL(endpointString);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    HttpPost postRequest = new HttpPost(uri);
    postRequest.setEntity(params);// w  ww .jav  a  2  s.c o  m
    LOGGER.info("post request entity={}", postRequest);
    postRequest.setHeader("Content-Type", "application/json");
    postRequest.setHeader("User-Agent", "Safari");
    this.postRequest = postRequest;

    LOGGER.info("request:{}", postRequest.getRequestLine());
    LOGGER.info("request:{}", postRequest.getParams().getParameter("licenseeID"));
}

From source file:keywhiz.cli.CommandExecutor.java

public void executeCommand() throws IOException {
    if (command == null) {
        if (config.version) {
            System.out.println("Version: " + APP_VERSION);
        } else {/*  www .jav a  2 s  .  c  o m*/
            System.err.println("Must specify a command.");
            parentCommander.usage();
        }

        return;
    }

    URL url;
    if (config.url == null || config.url.isEmpty()) {
        url = new URL("https", InetAddress.getLocalHost().getHostName(), 4444, "");
    } else {
        url = new URL(config.url);
    }

    HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    KeywhizClient client;
    OkHttpClient encapsulatedClient;

    try {
        List<HttpCookie> cookieList = ClientUtils.loadCookies(COOKIE_PATH);
        encapsulatedClient = ClientUtils.sslOkHttpClient(cookieList);
        client = new KeywhizClient(mapper, ClientUtils.hostBoundWrappedHttpClient(host, encapsulatedClient));

        // Try a simple get request to determine whether or not the cookies are still valid
        if (!client.isLoggedIn()) {
            throw new UnauthorizedException();
        }
    } catch (IOException e) {
        // Either could not find the cookie file, or the cookies were expired -- must login manually.
        encapsulatedClient = ClientUtils.sslOkHttpClient(ImmutableList.of());
        client = new KeywhizClient(mapper, ClientUtils.hostBoundWrappedHttpClient(host, encapsulatedClient));
        String password = ClientUtils.readPassword();
        client.login(USER_NAME.value(), password);
    }
    // Save/update the cookies if we logged in successfully
    ClientUtils.saveCookies((CookieManager) encapsulatedClient.getCookieHandler(), COOKIE_PATH);

    Printing printing = new Printing(client);

    Command cmd = Command.valueOf(command.toUpperCase().trim());
    switch (cmd) {
    case LIST:
        new ListAction((ListActionConfig) commands.get(command), client, printing).run();
        break;

    case DESCRIBE:
        new DescribeAction((DescribeActionConfig) commands.get(command), client, printing).run();
        break;

    case ADD:
        new AddAction((AddActionConfig) commands.get(command), client, mapper).run();
        break;

    case DELETE:
        new DeleteAction((DeleteActionConfig) commands.get(command), client).run();
        break;

    case ASSIGN:
        new AssignAction((AssignActionConfig) commands.get(command), client).run();
        break;

    case UNASSIGN:
        new UnassignAction((UnassignActionConfig) commands.get(command), client).run();
        break;

    case LOGIN:
        // User is already logged in at this point
        break;

    default:
        commander.usage();
    }
}

From source file:com.pocketsoap.salesforce.soap.ChatterClient.java

private String postSuspectsComment(String postId, Map<String, String> suspects, boolean retryOnInvalidSession)
        throws MalformedURLException, IOException, XMLStreamException, FactoryConfigurationError {
    URL instanceUrl = new URL(session.instanceServerUrl);
    URL url = new URL(instanceUrl.getProtocol(), instanceUrl.getHost(), instanceUrl.getPort(),
            "/services/data/v24.0/chatter/feed-items/" + postId + "/comments");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    try {//from w  w  w. j  ava2 s  .co m
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", "OAuth " + session.sessionId);

        final Comment comment = new Comment();
        final List<MessageSegment> messageSegments = comment.getBody().getMessageSegments();
        messageSegments.add(new TextMessageSegment("Suspects: "));

        Iterator<Entry<String, String>> it = suspects.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, String> ids = it.next();

            String sfdcId = ids.getValue();
            if (sfdcId != null) {
                //Convert the login to an SFDC ID
                sfdcId = UserService.getUserId(session, sfdcId);
            }

            if (sfdcId == null) { //not mapped
                messageSegments.add(new TextMessageSegment(ids.getKey()));
            } else {
                messageSegments.add(new MentionMessageSegment(sfdcId));
            }

            if (it.hasNext()) {
                messageSegments.add(new TextMessageSegment(", "));
            }
        }

        final OutputStream bodyStream = conn.getOutputStream();
        ObjectMapper mapper = new ObjectMapper();
        MappingJsonFactory jsonFactory = new MappingJsonFactory();
        JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(bodyStream);
        mapper.writeValue(jsonGenerator, comment);
        bodyStream.close();
        conn.getInputStream().close(); //Don't care about the response
    } catch (IOException e) {
        if (retryOnInvalidSession && conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            SessionCache.get().revoke(credentials);
            return postSuspectsComment(postId, suspects, false);
        }

        BufferedReader r = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        String error = "";
        String line;
        while ((line = r.readLine()) != null) {
            error += line + '\n';
        }
        System.out.println(error);
        throw e;
    }
    return null;
}

From source file:org.wso2.carbon.analytics.api.internal.client.AnalyticsAPIHttpClient.java

public static void init(AnalyticsDataConfiguration dataConfiguration) throws AnalyticsServiceException {
    try {/*  ww  w .  j  a  v  a 2 s . c o m*/
        URL url = new URL(dataConfiguration.getEndpoint());
        instance = new AnalyticsAPIHttpClient(url.getProtocol(), url.getHost(), url.getPort(),
                dataConfiguration.getMaxConnectionsPerRoute(), dataConfiguration.getMaxConnections(),
                dataConfiguration.getSocketConnectionTimeoutMS(), dataConfiguration.getConnectionTimeoutMS(),
                getTrustStoreLocation(dataConfiguration.getTrustStoreLocation()),
                getTrustStorePassword(dataConfiguration.getTrustStorePassword()));
    } catch (MalformedURLException e) {
        throw new AnalyticsServiceException(
                "Error while initializing the analytics http client. " + e.getMessage(), e);
    }
}

From source file:com.moss.veracity.core.load.VtOperationFactory.java

public VtOperationFactory(String identity, String password, URL baseUrl) throws Exception {
    log = LogFactory.getLog(this.getClass());

    if (log.isDebugEnabled()) {
        log.debug("Materializing authentication service");
    }//from   ww w. ja v  a  2s.c  om

    auth = Service.create(
            new URL("http://" + baseUrl.getHost() + ":" + baseUrl.getPort() + "/AuthenticationImpl?wsdl"),
            Authentication.QNAME).getPort(Authentication.class);

    if (log.isDebugEnabled()) {
        log.debug("Materializing management service");
    }

    manage = Service
            .create(new URL("http://" + baseUrl.getHost() + ":" + baseUrl.getPort() + "/ManagementImpl?wsdl"),
                    Management.QNAME)
            .getPort(Management.class);

    adminName = identity;
    universalToken = new VtPassword(password);

    if (log.isDebugEnabled()) {
        log.debug("Populating the veracity service with accounts for testing (100)");
    }

    accounts = new ArrayList<VtAccount>();

    final byte[] profileImage = loadResource("com/moss/veracity/core/root.jpg");

    for (int i = 0; i < 100; i++) {

        VtImage image = new VtImage();
        image.setData(profileImage);

        VtProfile profile = new VtProfile();
        profile.setName(new StFirstMiddleLastName("Wannado", "F", "Mercer"));
        profile.setImage(image);
        profile.setProfileName("default");
        profile.setWhenLastModified(System.currentTimeMillis());

        VtAccount account = new VtAccount();
        account.setName(UUID.randomUUID() + "@localhost");
        account.setAuthMode(VtAuthMode.USER);
        account.getMechanisms().add(new VtPasswordMechanism(password));
        account.getProfiles().add(profile);

        accounts.add(account);
        manage.create(account, adminEndorsement());
    }

    random = new Random(System.currentTimeMillis());
}

From source file:org.zenoss.metrics.reporter.HttpPoster.java

private HttpPoster(final URL url, final String user, final String password, ObjectMapper mapper) {
    this.url = url;
    this.mapper = mapper;
    if (!Strings.nullToEmpty(user).trim().isEmpty()) {
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, password));
        this.needsAuth = true;
    } else {/*w w  w .  j a  v a2  s  .c o  m*/
        this.needsAuth = false;
    }
}

From source file:mobi.jenkinsci.ci.client.JenkinsHttpClient.java

public JenkinsHttpClient(final JenkinsConfig config) throws MalformedURLException {
    this.config = config;
    if (config.getUsername() == null) {
        httpClient = httpClientFactory.getHttpClient();
    } else {//from   ww w . j  ava2 s  . c  o m
        final URL url = new URL(config.getUrl());
        httpClient = httpClientFactory.getBasicAuthHttpClient(url, config.getUsername(), config.getPassword());

        final AuthCache authCache = new BasicAuthCache();
        final BasicScheme basicAuth = new BasicScheme();
        authCache.put(new HttpHost(url.getHost(), url.getPort()), basicAuth);

        httpContext = new BasicHttpContext();
        httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }
}

From source file:ed.net.CookieJar.java

/**
 * Return <tt>true</tt> if the cookie should be submitted with a request
 * with given attributes, <tt>false</tt> otherwise.
 * @param destination the destination of the request
 * @param cookie {@link Cookie} to be matched
 * @return true if the cookie matches the criterium
 *///from w w  w  . j a  v  a 2s.  c o  m
private boolean match(URL destination, final Cookie cookie) {
    String host = destination.getHost();
    int port = destination.getPort();
    String path = destination.getPath();
    boolean secure = "https".equals(destination.getProtocol());

    if (host == null) {
        throw new IllegalArgumentException("Host of origin may not be null");
    }
    if (host.trim().equals("")) {
        throw new IllegalArgumentException("Host of origin may not be blank");
    }
    if (port < 0) {
        port = 80;
    }
    if (path == null) {
        throw new IllegalArgumentException("Path of origin may not be null.");
    }
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (path.trim().equals("")) {
        path = "/";
    }
    host = host.toLowerCase();
    if (cookie.getDomain() == null) {
        return false;
    }
    if (cookie.getPath() == null) {
        return false;
    }

    return
    // only add the cookie if it hasn't yet expired
    !isExpired(cookie)
            // and the domain pattern matches
            && (domainMatch(host, cookie.getDomain()))
            // and the path is null or matching
            && (pathMatch(path, cookie.getPath()))
            // and if the secure flag is set, only if the request is
            // actually secure
            && (cookie.getSecure() ? secure : true);
}