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.wildfly.core.test.standalone.mgmt.api.core.ResponseAttachmentTestCase.java

private CloseableHttpClient createHttpClient(URL url) {

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(/*from   w  w  w.j  a  v  a  2s.c  om*/
            new AuthScope(url.getHost(), url.getPort(), "ManagementRealm", AuthSchemes.DIGEST),
            new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD));
    return HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:org.apache.solr.client.solrj.impl.CloudSolrClientTest.java

private void queryWithPreferLocalShards(CloudSolrClient cloudClient, boolean preferLocalShards,
        String collectionName) throws Exception {
    SolrQuery qRequest = new SolrQuery("*:*");

    ModifiableSolrParams qParams = new ModifiableSolrParams();
    qParams.add("preferLocalShards", Boolean.toString(preferLocalShards));
    qParams.add(ShardParams.SHARDS_INFO, "true");
    qRequest.add(qParams);/*from w w w . ja  v a  2s.  co  m*/

    // CloudSolrClient sends the request to some node.
    // And since all the nodes are hosting cores from all shards, the
    // distributed query formed by this node will select cores from the
    // local shards only
    QueryResponse qResponse = cloudClient.query(collectionName, qRequest);

    Object shardsInfo = qResponse.getResponse().get(ShardParams.SHARDS_INFO);
    assertNotNull("Unable to obtain " + ShardParams.SHARDS_INFO, shardsInfo);

    // Iterate over shards-info and check what cores responded
    SimpleOrderedMap<?> shardsInfoMap = (SimpleOrderedMap<?>) shardsInfo;
    Iterator<Map.Entry<String, ?>> itr = shardsInfoMap.asMap(100).entrySet().iterator();
    List<String> shardAddresses = new ArrayList<String>();
    while (itr.hasNext()) {
        Map.Entry<String, ?> e = itr.next();
        assertTrue("Did not find map-type value in " + ShardParams.SHARDS_INFO, e.getValue() instanceof Map);
        String shardAddress = (String) ((Map) e.getValue()).get("shardAddress");
        assertNotNull(ShardParams.SHARDS_INFO + " did not return 'shardAddress' parameter", shardAddress);
        shardAddresses.add(shardAddress);
    }
    log.info("Shards giving the response: " + Arrays.toString(shardAddresses.toArray()));

    // Make sure the distributed queries were directed to a single node only
    if (preferLocalShards) {
        Set<Integer> ports = new HashSet<Integer>();
        for (String shardAddr : shardAddresses) {
            URL url = new URL(shardAddr);
            ports.add(url.getPort());
        }

        // This assertion would hold true as long as every shard has a core on each node
        assertTrue("Response was not received from shards on a single node",
                shardAddresses.size() > 1 && ports.size() == 1);
    }
}

From source file:com.tremolosecurity.unison.proxy.auth.openidconnect.OpenIDConnectAuthMech.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 bearerTokenName = authParams.get("bearerTokenName").getValues().get(0);
    String clientid = authParams.get("clientid").getValues().get(0);
    String secret = authParams.get("secretid").getValues().get(0);
    String idpURL = authParams.get("idpURL").getValues().get(0);
    String responseType = authParams.get("responseType").getValues().get(0);
    String scope = authParams.get("scope").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);

    String defaultObjectClass = authParams.get("defaultObjectClass").getValues().get(0);

    boolean forceAuth = true;//authParams.get("forceAuthentication") != null ? authParams.get("forceAuthentication").getValues().get(0).equalsIgnoreCase("true") : false;

    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();

    StringBuffer b = new StringBuffer();

    URL reqURL = new URL(request.getRequestURL().toString());

    b.append(reqURL.getProtocol()).append("://").append(reqURL.getHost());

    if (reqURL.getPort() != -1) {
        b.append(":").append(reqURL.getPort());
    }/*from w  w w.ja v a 2  s .  c  o  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();

    b.append(holder.getConfig().getContextPath()).append(cfg.getAuthMechs().get(authMechName).getUri());

    String hd = authParams.get("hd").getValues().get(0);
    String loadTokenURL = authParams.get("loadTokenURL").getValues().get(0);

    if (request.getParameter("state") == null) {
        //initialize openidconnect

        String state = new BigInteger(130, new SecureRandom()).toString(32);
        request.getSession().setAttribute("UNISON_OPENIDCONNECT_STATE", state);

        StringBuffer redirToSend = new StringBuffer();
        redirToSend.append(idpURL).append("?client_id=").append(URLEncoder.encode(clientid, "UTF-8"))
                .append("&response_type=").append(URLEncoder.encode(responseType, "UTF-8")).append("&scope=")
                .append(URLEncoder.encode(scope, "UTF-8")).append("&redirect_uri=")
                .append(URLEncoder.encode(b.toString(), "UTF-8")).append("&state=")
                .append(URLEncoder.encode("security_token=", "UTF-8"))
                .append(URLEncoder.encode(state, "UTF-8"));

        if (forceAuth) {
            redirToSend.append("&max_age=0");
        }

        if (!hd.isEmpty()) {
            redirToSend.append("&hd=").append(hd);
        }

        response.sendRedirect(redirToSend.toString());

    } else {
        String stateFromURL = request.getParameter("state");
        stateFromURL = URLDecoder.decode(stateFromURL, "UTF-8");
        stateFromURL = stateFromURL.substring(stateFromURL.indexOf('=') + 1);

        String stateFromSession = (String) request.getSession().getAttribute("UNISON_OPENIDCONNECT_STATE");

        if (!stateFromSession.equalsIgnoreCase(stateFromURL)) {
            throw new ServletException("Invalid State");
        }

        HttpUriRequest post = null;

        try {
            post = RequestBuilder.post().setUri(new java.net.URI(loadTokenURL))
                    .addParameter("code", request.getParameter("code")).addParameter("client_id", clientid)
                    .addParameter("client_secret", secret).addParameter("redirect_uri", b.toString())
                    .addParameter("grant_type", "authorization_code").build();
        } catch (URISyntaxException e) {
            throw new ServletException("Could not create post request");
        }

        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();

        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();

        Gson gson = new Gson();

        Map tokenNVP = com.cedarsoftware.util.io.JsonReader.jsonToMaps(token.toString());

        String accessToken;

        //Store the bearer token for use by Unison
        request.getSession().setAttribute(bearerTokenName, tokenNVP.get("access_token"));

        Map jwtNVP = null;
        LoadUserData loadUser = null;
        try {
            loadUser = (LoadUserData) Class.forName(userLookupClassName).newInstance();
            jwtNVP = loadUser.loadUserAttributesFromIdP(request, response, cfg, authParams, tokenNVP);
        } catch (Exception e) {
            throw new ServletException("Could not load user data", e);
        }

        if (jwtNVP == null) {
            as.setSuccess(false);
        } else {
            if (!linkToDirectory) {
                loadUnlinkedUser(session, noMatchOU, uidAttr, act, jwtNVP, defaultObjectClass);

                as.setSuccess(true);

            } else {
                lookupUser(as, session, myvd, noMatchOU, uidAttr, lookupFilter, act, jwtNVP,
                        defaultObjectClass);
            }

            String redirectToURL = request.getParameter("target");
            if (redirectToURL != null && !redirectToURL.isEmpty()) {
                reqHolder.setURL(redirectToURL);
            }
        }

        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);

    }

}

From source file:cm.aptoide.pt.DownloadQueueService.java

private void downloadFile(final int apkidHash) {

    try {/*  w  w w .j a  v a2s  . com*/

        new Thread() {
            public void run() {
                this.setPriority(Thread.MAX_PRIORITY);

                if (!keepScreenOn.isHeld()) {
                    keepScreenOn.acquire();
                }
                int threadApkidHash = apkidHash;

                String remotePath = notifications.get(threadApkidHash).get("remotePath");
                String md5hash = notifications.get(threadApkidHash).get("md5hash");

                String localPath = notifications.get(threadApkidHash).get("localPath");
                Log.d("Aptoide-DownloadQueuService",
                        "thread apkidHash: " + threadApkidHash + " localPath: " + localPath);

                Message downloadArguments = new Message();
                try {

                    // If file exists, removes it...
                    File f_chk = new File(localPath);
                    if (f_chk.exists()) {
                        f_chk.delete();
                    }
                    f_chk = null;

                    FileOutputStream saveit = new FileOutputStream(localPath);
                    DefaultHttpClient mHttpClient = new DefaultHttpClient();
                    HttpGet mHttpGet = new HttpGet(remotePath);

                    if (Boolean.parseBoolean(notifications.get(threadApkidHash).get("loginRequired"))) {
                        URL mUrl = new URL(remotePath);
                        mHttpClient.getCredentialsProvider().setCredentials(
                                new AuthScope(mUrl.getHost(), mUrl.getPort()),
                                new UsernamePasswordCredentials(
                                        notifications.get(threadApkidHash).get("username"),
                                        notifications.get(threadApkidHash).get("password")));

                    }

                    HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);

                    if (mHttpResponse == null) {
                        Log.d("Aptoide", "Problem in network... retry...");
                        mHttpResponse = mHttpClient.execute(mHttpGet);
                        if (mHttpResponse == null) {
                            Log.d("Aptoide", "Major network exception... Exiting!");
                            /*msg_al.arg1= 1;
                            download_error_handler.sendMessage(msg_al);*/
                            throw new TimeoutException();
                        }
                    }

                    if (mHttpResponse.getStatusLine().getStatusCode() == 401) {
                        throw new TimeoutException();
                    } else {
                        InputStream getit = mHttpResponse.getEntity().getContent();
                        byte data[] = new byte[8096];
                        int red;
                        red = getit.read(data, 0, 8096);

                        int progressNotificationUpdate = 200;
                        int intermediateProgress = 0;
                        while (red != -1) {
                            if (progressNotificationUpdate == 0) {
                                if (!keepScreenOn.isHeld()) {
                                    keepScreenOn.acquire();
                                }
                                progressNotificationUpdate = 200;
                                Message progressArguments = new Message();
                                progressArguments.arg1 = threadApkidHash;
                                progressArguments.arg2 = intermediateProgress;
                                downloadProgress.sendMessage(progressArguments);
                                intermediateProgress = 0;
                            } else {
                                intermediateProgress += red;
                                progressNotificationUpdate--;
                            }

                            saveit.write(data, 0, red);
                            red = getit.read(data, 0, 8096);
                        }
                        Log.d("Aptoide",
                                "Download done! apkidHash: " + threadApkidHash + " localPath: " + localPath);
                        saveit.flush();
                        saveit.close();
                        getit.close();
                    }

                    if (keepScreenOn.isHeld()) {
                        keepScreenOn.release();
                    }

                    File f = new File(localPath);
                    Md5Handler hash = new Md5Handler();
                    if (md5hash == null || md5hash.equalsIgnoreCase(hash.md5Calc(f))) {
                        downloadArguments.arg1 = 1;
                        downloadArguments.arg2 = threadApkidHash;
                        downloadArguments.obj = localPath;
                        downloadHandler.sendMessage(downloadArguments);
                    } else {
                        Log.d("Aptoide", md5hash + " VS " + hash.md5Calc(f));
                        downloadArguments.arg1 = 0;
                        downloadArguments.arg2 = threadApkidHash;
                        downloadErrorHandler.sendMessage(downloadArguments);
                    }

                } catch (Exception e) {
                    if (keepScreenOn.isHeld()) {
                        keepScreenOn.release();
                    }
                    downloadArguments.arg1 = 1;
                    downloadArguments.arg2 = threadApkidHash;
                    downloadErrorHandler.sendMessage(downloadArguments);
                }
            }
        }.start();

    } catch (Exception e) {
    }
}

From source file:de.innovationgate.utils.URLBuilder.java

/**
  * Creates a URLBuilder that parses an existing URL
 * @param url The URL to parse/*ww w  . jav a  2 s.  c o m*/
 */
public URLBuilder(URL url) {
    this(url.getProtocol(), url.getPort(), url.getHost(), url.getPath(), url.getQuery(), url.getRef(), "UTF-8");
}

From source file:org.switchyard.component.http.OutboundHandler.java

private AuthScope createAuthScope(String host, String portStr, String realm) throws HttpConsumeException {
    URL url = null;
    try {/*from  ww  w.  j  a v  a2s.c o  m*/
        url = new URL(_baseAddress);
    } catch (MalformedURLException mue) {
        final String m = HttpMessages.MESSAGES.invalidHttpURL();
        LOGGER.error(m, mue);
        throw new HttpConsumeException(m, mue);
    }
    if (realm == null) {
        realm = AuthScope.ANY_REALM;
    }
    int port = url.getPort();
    if (host == null) {
        host = url.getHost();
    }
    if (portStr != null) {
        port = Integer.valueOf(portStr).intValue();
    }
    return new AuthScope(host, port, realm);
}

From source file:de.uniluebeck.itm.spyglass.gui.wizard.WisebedPacketReaderConfigurationWizard.java

private String tryToGetLocalControllerEndpointUrlFromUser() {

    String localControllerEndpointUrl = askLocalControllerEndpointUrlFromUser();
    if (localControllerEndpointUrl != null) {
        try {//  w  w w  .  ja v  a2s  . co  m
            URL url = new URL(localControllerEndpointUrl);
            if (checkIfServerSocketCanBeOpened(url.getHost(), url.getPort())) {
                return localControllerEndpointUrl;
            }
            return null;
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
    return null;
}

From source file:blue.lapis.pore.launch.PoreBootstrap.java

@Inject
public PoreBootstrap(Injector injector) {
    URL location = getClass().getProtectionDomain().getCodeSource().getLocation();
    String path = location.getPath();
    if (location.getProtocol().equals("jar")) {
        int pos = path.lastIndexOf('!');
        if (pos >= 0) {
            path = path.substring(0, pos + 2);
        }/*w  w w. j  a  v a  2s.c  om*/
    } else {
        path = StringUtils.removeEnd(path, getClass().getName().replace('.', '/') + ".class");
    }

    try {
        ClassLoader loader = new PoreClassLoader(getClass().getClassLoader(),
                new URL(location.getProtocol(), location.getHost(), location.getPort(), path));
        Class<?> poreClass = Class.forName(IMPLEMENTATION_CLASS, true, loader);
        this.pore = (PoreEventManager) injector.getInstance(poreClass);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Failed to load Pore implementation", e);
    } catch (MalformedURLException e) {
        throw new RuntimeException("Failed to load Pore implementation", e);
    }
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

/**
 * Creates a new ServerClassLoader/*  ww  w  .ja va 2 s. c o  m*/
 * @param parent The parent class loader
 * @param localCacheDirectory The directory to cache files to
 * @param remoteServer The URL of the remote server
 */
public ServerClassLoader(ClassLoader parent, File localCacheDirectory, URL remoteServer) {
    super(parent);
    this.localCacheDirectory = localCacheDirectory;
    this.localLibDirectory = new File(localCacheDirectory, LIB_DIR);
    File versionFile = new File(localCacheDirectory, "Version");
    boolean versionCorrect = false;
    if (!localCacheDirectory.exists()) {
        localCacheDirectory.mkdirs();
    } else {
        if (versionFile.exists()) {
            try {
                BufferedReader reader = new BufferedReader(new FileReader(versionFile));
                String version = reader.readLine();
                reader.close();
                versionCorrect = Defaults.PAG_VERSION.equals(version);
                log.info(version + " == " + Defaults.PAG_VERSION + " = " + versionCorrect);
            } catch (IOException e) {
                // Do Nothing
            }
        }
        try {
            FileInputStream input = new FileInputStream(new File(localCacheDirectory, INDEX));
            DataInputStream cacheFile = new DataInputStream(input);
            FileChannel channel = input.getChannel();
            while (channel.position() < channel.size()) {
                URL url = new URL(cacheFile.readUTF());
                String file = cacheFile.readUTF();
                if (versionCorrect && url.getHost().equals(remoteServer.getHost())
                        && (url.getPort() == remoteServer.getPort())) {
                    File jar = new File(localCacheDirectory, file);
                    if (jar.exists()) {
                        indexJar(url, jar);
                        CHECKED.put(url, true);
                    }
                }
            }
            input.close();
        } catch (FileNotFoundException e) {
            // Do Nothing - cache will be recreated later

        } catch (IOException e) {
            // Do Nothing - as above

        }
    }
    localLibDirectory.mkdirs();
    try {
        PrintWriter writer = new PrintWriter(versionFile);
        writer.println(Defaults.PAG_VERSION);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    this.remoteServer = remoteServer;
}