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.comcast.magicwand.spells.saucelabs.SauceProvider.java

/**
 * Generates URL to use in order to connect to SauceLabs
 * @return URL for SauceLabs//from w ww  .ja v  a 2s  . c om
 * @throws FlyingPhoenixException If URL is malformed or invalid
 */
protected URL generateSauceURL() throws FlyingPhoenixException {
    try {
        URL baseUrl = new URL(urlStr);
        String userInfo = getUserInfo(baseUrl);

        String auth = String.format("http://%s@%s:%d%s", userInfo, baseUrl.getHost(), baseUrl.getPort(),
                baseUrl.getFile());
        URL remoteAddress = new URL(auth);
        LOG.debug("Remote URL is: " + remoteAddress.toURI());
        return remoteAddress;
    } catch (MalformedURLException | URISyntaxException e) {
        String msg = "There was an error while creating sauce url " + e.getMessage();
        LOG.error(msg);
        throw new FlyingPhoenixException(msg, e);
    }
}

From source file:edu.du.penrose.systems.fedoraApp.batchIngest.data.BatchIngestURLhandlerImpl.java

/**
 * This location will vary depending on if the ingest is running as a task.
 * A task will put the reports into a temporary directory prior to performing
 * the finalization of the ingest (e-mailing results, posting rest responses).
 * //from  www.jav a 2s . c o m
 * @see edu.du.penrose.systems.fedoraApp.batchIngest.data.BatchIngestOptions#isRunningAsRemoteTask()
 */
public URL getIngestReportLocationURL() {
    URL ingestReportURL = null;

    ingestReportURL = this.getLogFilesFolderURL();

    String host = ingestReportURL.getHost();
    String protocol = ingestReportURL.getProtocol();
    int port = ingestReportURL.getPort();
    String filePath = ingestReportURL.getFile();

    try {
        ingestReportURL = new URL(protocol, host, port,
                filePath + this.getUniqueBatchRunName() + FedoraAppConstants.BATCH_INGEST_REPORT_FILE_EXT);
    } catch (MalformedURLException e) {
        // the original url has already been checked so this should never happen.
        throw new RuntimeException(e.getMessage());
    }

    return ingestReportURL;
}

From source file:io.fabric8.kubernetes.api.KubernetesFactory.java

public void setAddress(String address) {
    this.address = address;
    if (Strings.isNullOrBlank(address)) {
        this.address = findKubernetesMaster();
    }/*  w  ww .j  a va  2 s.c  om*/

    if (verifyAddress) {
        try {
            URL url = new URL(this.address);
            if (KubernetesHelper.isServiceSsl(url.getHost(), url.getPort(), true)) {
                this.address = "https://" + url.getHost() + ":" + url.getPort();
            } else {
                this.address = "http://" + url.getHost() + ":" + url.getPort();
            }
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("Invalid kubernetes master address", e);
        }
    }
}

From source file:org.openqa.grid.internal.TestSession.java

private HttpResponse sendRequestToNode(HttpRequest proxyRequest) throws ClientProtocolException, IOException {
    HttpClient client = getClient();/* ww w.j  av a2 s.  com*/
    URL remoteURL = slot.getRemoteURL();
    HttpHost host = new HttpHost(remoteURL.getHost(), remoteURL.getPort());

    return client.execute(host, proxyRequest);
}

From source file:org.wso2.carbon.device.mgt.etc.controlqueue.xmpp.XmppServerClient.java

public boolean createXMPPAccount(XmppAccount newUserAccount) throws DeviceControllerException {
    if (xmppEnabled) {
        String xmppUsersAPIEndpoint = xmppEndpoint + XMPP_SERVER_API_CONTEXT + USERS_API;
        if (log.isDebugEnabled()) {
            log.debug("The API Endpoint URL of the XMPP Server is set to: " + xmppUsersAPIEndpoint);
        }//from   w w w  . j  a va  2 s .  co  m

        String encodedString = xmppUsername + ":" + xmppPassword;
        encodedString = new String(Base64.encodeBase64(encodedString.getBytes(StandardCharsets.UTF_8)));
        String authorizationHeader = "Basic " + encodedString;
        String jsonRequest = "{\n" + "    \"username\": \"" + newUserAccount.getUsername() + "\","
                + "    \"password\": \"" + newUserAccount.getPassword() + "\"," + "    \"name\": \""
                + newUserAccount.getAccountName() + "\"," + "    \"email\": \"" + newUserAccount.getEmail()
                + "\"," + "    \"properties\": {" + "        \"property\": [" + "            {"
                + "                \"@key\": \"console.rows_per_page\","
                + "                \"@value\": \"user-summary=8\"" + "            }," + "            {"
                + "                \"@key\": \"console.order\","
                + "                \"@value\": \"session-summary=1\"" + "            }" + "        ]" + "    }"
                + "}";
        StringEntity requestEntity;
        try {
            requestEntity = new StringEntity(jsonRequest, "application/json", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return false;
        }

        URL xmppUserApiUrl;
        try {
            xmppUserApiUrl = new URL(xmppUsersAPIEndpoint);
        } catch (MalformedURLException e) {
            String errMsg = "Malformed URL + " + xmppUsersAPIEndpoint;
            log.error(errMsg);
            throw new DeviceControllerException(errMsg);
        }
        HttpClient httpClient;
        try {
            httpClient = IoTUtil.getHttpClient(xmppUserApiUrl.getPort(), xmppUserApiUrl.getProtocol());
        } catch (Exception e) {
            log.error("Error on getting a http client for port :" + xmppUserApiUrl.getPort() + " protocol :"
                    + xmppUserApiUrl.getProtocol());
            return false;
        }
        HttpPost httpPost = new HttpPost(xmppUsersAPIEndpoint);

        httpPost.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader);
        httpPost.setEntity(requestEntity);

        try {
            HttpResponse httpResponse = httpClient.execute(httpPost);

            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
                String response = IoTUtil.getResponseString(httpResponse);
                String errorMsg = "XMPP Server returned status: '"
                        + httpResponse.getStatusLine().getStatusCode() + "' for account creation with error:\n"
                        + response;
                log.error(errorMsg);
                throw new DeviceControllerException(errorMsg);
            } else {
                EntityUtils.consume(httpResponse.getEntity());
                return true;
            }
        } catch (IOException | DeviceMgtCommonsException e) {
            String errorMsg = "Error occurred whilst trying a 'POST' at : " + xmppUsersAPIEndpoint + " error: "
                    + e.getMessage();
            log.error(errorMsg);
            throw new DeviceControllerException(errorMsg, e);
        }

    } else {
        log.warn("XMPP <Enabled> set to false in 'device-mgt-config.xml'");
        return false;
    }
}

From source file:io.hummer.util.ws.AbstractNode.java

@SuppressWarnings("all")
public static void deploy(final Object service, String url, Handler<?>... handler)
        throws AbstractNodeException {

    long t1 = System.currentTimeMillis();

    try {/* www.j a va2  s.  co m*/

        URL u = new URL(url);

        if (strUtil.isEmpty(System.getProperty(SYSPROP_HTTP_SERVER_PROVIDER_CLASS))) {
            System.setProperty(SYSPROP_HTTP_SERVER_PROVIDER_CLASS, JettyHttpServerProvider.class.getName());
        }

        ContextHandlerCollection chc = new ContextHandlerCollection();

        // disable log output from Metro and Jetty
        java.util.logging.Logger.getAnonymousLogger().getParent().setLevel(Level.WARNING);
        Class<?> cls3 = org.eclipse.jetty.server.Server.class;
        Class<?> cls4 = org.eclipse.jetty.server.AbstractConnector.class;
        org.apache.log4j.Level lev3 = Logger.getLogger(cls3).getLevel();
        org.apache.log4j.Level lev4 = Logger.getLogger(cls4).getLevel();
        Logger.getLogger(cls3).setLevel(org.apache.log4j.Level.WARN);
        Logger.getLogger(cls4).setLevel(org.apache.log4j.Level.WARN);

        JettyHttpServer httpServer = httpServers.get(u.getPort());
        Server server = servers.get(u.getPort());
        if (httpServer == null) {
            org.eclipse.jetty.util.log.Log.setLog(new Slf4jLog());
            server = new Server(u.getPort());

            SelectChannelConnector connector = new SelectChannelConnector();
            connector.setPort(u.getPort());
            connector.setAcceptQueueSize(1000);
            connector.setThreadPool(new ExecutorThreadPool(GlobalThreadPool.getExecutorService()));
            server.setConnectors(new Connector[] { connector });

            server.setHandler(chc);

            httpServer = new JettyHttpServer(server, true);

            httpServers.put(u.getPort(), httpServer);
            servers.put(u.getPort(), server);

            if (!server.isStarted())
                server.start();
        }

        JettyHttpContext wsContext1 = (JettyHttpContext) httpServer.createContext(u.getPath());
        Endpoint endpoint = Endpoint.create(service);
        if (service instanceof AbstractNode) {
            if (((AbstractNode) service).endpoint != null)
                logger.warn("AbstractNode " + service + " has apparently been double-deployed, "
                        + "because there already exists an endpoint for this instance.");
            ((AbstractNode) service).endpoint = endpoint;
        }

        // add JAX-WS handlers (e.g., needed for TeCoS invocation intercepting...)
        List<Handler> handlers = endpoint.getBinding().getHandlerChain();
        handlers.addAll(Arrays.asList(handler));
        endpoint.getBinding().setHandlerChain(handlers);
        if (service instanceof AbstractNode) {
            AbstractNode a = (AbstractNode) service;
            for (Handler h : handlers)
                if (!a.activeHandlers.contains(h))
                    a.activeHandlers.add(h);
        }

        Class<?> cls1 = org.eclipse.jetty.util.component.AbstractLifeCycle.class;
        Class<?> cls2 = org.eclipse.jetty.server.handler.ContextHandler.class;
        org.apache.log4j.Level lev1 = Logger.getLogger(cls1).getLevel();
        org.apache.log4j.Level lev2 = Logger.getLogger(cls2).getLevel();
        try {
            String bindUrl = u.getProtocol() + "://0.0.0.0:" + u.getPort() + u.getPath();
            if (u.getQuery() != null) {
                bindUrl += "?" + u.getQuery();
            }
            Logger.getLogger(cls1).setLevel(org.apache.log4j.Level.OFF);
            Logger.getLogger(cls2).setLevel(org.apache.log4j.Level.WARN);
            logger.info("Binding service to " + bindUrl);
            endpoint.publish(bindUrl);
        } catch (Exception e) {
            if (e instanceof BindException || (e.getCause() != null && e.getCause() instanceof BindException)
                    || (e.getCause() != null && e.getCause().getCause() != null
                            && e.getCause().getCause() instanceof BindException)) {
                /** we expect a BindException here, just swallow */
            } else {
                logger.warn("Unexpected error.", e);
            }
        } finally {
            Logger.getLogger(cls1).setLevel(lev1);
            Logger.getLogger(cls2).setLevel(lev2);
            Logger.getLogger(cls3).setLevel(lev3);
            Logger.getLogger(cls4).setLevel(lev4);
        }

        Field f = endpoint.getClass().getDeclaredField("actualEndpoint");
        f.setAccessible(true);

        // DO NOT do this (the two lines below), because HttpEndpoint creates some nasty 
        // compile-time dependencies with respect to JAXWS-RT. At runtime, we can (hopefully) 
        // assume that this class is present, in all newer Sun JVM implementations..
        //HttpEndpoint httpEndpoint = (HttpEndpoint)f.get(e1);
        //httpEndpoint.publish(wsContext1);
        Object httpEndpoint = f.get(endpoint);
        httpEndpoint.getClass().getMethod("publish", Object.class).invoke(httpEndpoint, wsContext1);

        Endpoint e2 = Endpoint.create(new CrossdomainXML());
        JettyHttpContext wsContext2 = (JettyHttpContext) httpServer.createContext("/crossdomain.xml");
        e2.publish(wsContext2);

        // Also deploy as RESTful service..
        if (service instanceof AbstractNode) {
            AbstractNode node = (AbstractNode) service;
            if (node.isRESTfulService()) {
                String path = u.getPath();
                if (!path.contains("/"))
                    path = "/";
                path = "/rest";
                String wadlURL = netUtil.getUrlBeforePath(u) + path + "/application.wadl";
                if (logger.isDebugEnabled())
                    logger.debug("Deploying node as RESTful service: " + wadlURL);
                JettyHttpContext wsContext3 = (JettyHttpContext) httpServer.createContext(path);

                ResourceConfig rc = new PackagesResourceConfig(service.getClass().getPackage().getName(),
                        AbstractNode.class.getPackage().getName());
                HttpHandler h = RuntimeDelegate.getInstance().createEndpoint(rc, HttpHandler.class);
                wsContext3.setHandler(h);
                node.setWadlURL(wadlURL);
            }
            deployedNodes.put(url, node);
        }

        final HttpHandler h = wsContext1.getHandler();
        wsContext1.setHandler(new HttpHandler() {
            public void handle(com.sun.net.httpserver.HttpExchange ex) throws IOException {

                if (!ex.getRequestMethod().equals("OPTIONS")) {
                    addCORSHeaders(ex);
                    h.handle(ex);
                    //System.out.println(ex.getRequestMethod() + ": " + ex.getResponseHeaders() + " - " + new HashMap<>(ex.getResponseHeaders()));
                    return;
                }

                if (ex.getRequestMethod().equals("OPTIONS")) {
                    addCORSHeaders(ex);
                    ex.sendResponseHeaders(200, -1);
                    ex.getResponseBody().close();
                    return;
                }
                //System.out.println(new HashMap<>(ex.getResponseHeaders()));
            }
        });

        // add shutdown task for this node
        if (service instanceof AbstractNode) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    try {
                        Runnable r = ((AbstractNode) service).getTerminateTask(null);
                        if (r != null)
                            r.run();
                    } catch (Exception e) {
                    }
                }
            });
        }

    } catch (Exception e) {
        throw new AbstractNodeException(e);
    }

    long diff = System.currentTimeMillis() - t1;
    logger.info("Deployment took " + diff + "ms");

}

From source file:com.apache.ivy.ApacheURLLister.java

/**
 * Retrieves a {@link List} of {@link URL}s corresponding to the files and/or directories found
 * at the supplied base URL./*from ww  w . j  a  v a2s.c om*/
 * 
 * @param url
 *            The base URL from which to retrieve the listing.
 * @param includeFiles
 *            If true include files in the returned list.
 * @param includeDirectories
 *            If true include directories in the returned list.
 * @return A {@link List} of {@link URL}s.
 * @throws IOException
 *             If an error occures retrieving the HTML.
 */
public List retrieveListing(URL url, boolean includeFiles, boolean includeDirectories,
        ArrayList<NameValuePair> postData) throws IOException {
    List urlList = new ArrayList();

    // add trailing slash for relative urls
    if (!url.getPath().endsWith("/") && !url.getPath().endsWith(".html")) {
        url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getPath() + "/");
    }

    /*
    URLHandler urlHandler = URLHandlerRegistry.getDefault();
    String charset = urlHandler.getURLInfo(url).getBodyCharset();
    InputStream contentStream = urlHandler.openStream(url);
    */
    BufferedReader r = null;
    if (postData == null) {
        r = new BufferedReader(new InputStreamReader(URLHandlerRegistry.getDefault().openStream(url)));

    } else {
        r = new BufferedReader(
                new InputStreamReader(URLHandlerRegistry.getDefault().openStreamPost(url, postData)));

    }

    //BufferedReader r = new BufferedReader(new InputStreamReader(contentStream, charset));

    String htmlText = FileUtil.readEntirely(r);

    Matcher matcher = PATTERN.matcher(htmlText);

    while (matcher.find()) {
        // get the href text and the displayed text
        String href = matcher.group(1);
        String text = matcher.group(2);

        if ((href == null) || (text == null)) {
            // the groups were not found (shouldn't happen, really)
            continue;
        }

        text = text.trim();

        // handle complete URL listings
        if (href.startsWith("http:") || href.startsWith("https:")) {
            try {
                href = new URL(href).getPath();
                if (!href.startsWith(url.getPath())) {
                    // ignore URLs which aren't children of the base URL
                    continue;
                }
                href = href.substring(url.getPath().length());
            } catch (Exception ignore) {
                // incorrect URL, ignore
                continue;
            }
        }

        if (href.startsWith("../")) {
            // we are only interested in sub-URLs, not parent URLs, so skip this one
            continue;
        }

        // absolute href: convert to relative one
        if (href.startsWith("/")) {
            int slashIndex = href.substring(0, href.length() - 1).lastIndexOf('/');
            href = href.substring(slashIndex + 1);
        }

        // relative to current href: convert to simple relative one
        if (href.startsWith("./")) {
            href = href.substring("./".length());
        }

        // exclude those where they do not match
        // href will never be truncated, text may be truncated by apache
        if (text.endsWith("..>")) {
            // text is probably truncated, we can only check if the href starts with text
            if (!href.startsWith(text.substring(0, text.length() - 3))) {
                continue;
            }
        } else if (text.endsWith("..&gt;")) {
            // text is probably truncated, we can only check if the href starts with text
            if (!href.startsWith(text.substring(0, text.length() - 6))) {
                continue;
            }
        } else {
            // text is not truncated, so it must match the url after stripping optional
            // trailing slashes
            String strippedHref = href.endsWith("/") ? href.substring(0, href.length() - 1) : href;
            String strippedText = text.endsWith("/") ? text.substring(0, text.length() - 1) : text;
            if (!strippedHref.equalsIgnoreCase(strippedText)) {
                continue;
            }
        }

        boolean directory = href.endsWith("/");

        if ((directory && includeDirectories) || (!directory && includeFiles)) {
            URL child = new URL(url, href);
            urlList.add(child);
            //Message.debug("ApacheURLLister found URL=[" + child + "].");
        }
    }

    return urlList;
}

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

private String downloadFile(int position) {
    Vector<DownloadNode> tmp_serv = new Vector<DownloadNode>();
    String getserv = new String();
    String md5hash = null;//from  ww w  . j  a v a2  s  .  c  o m
    String repo = null;

    try {
        tmp_serv = db.getPathHash(apk_lst.get(position).apkid);

        if (tmp_serv.size() > 0) {
            DownloadNode node = tmp_serv.get(0);
            getserv = node.repo + "/" + node.path;
            md5hash = node.md5h;
            repo = node.repo;
        }

        if (getserv.length() == 0)
            throw new TimeoutException();

        Message msg = new Message();
        msg.arg1 = 0;
        msg.obj = new String(getserv);
        download_handler.sendMessage(msg);

        /*BufferedInputStream getit = new BufferedInputStream(new URL(getserv).openStream());
                
        String path = new String(APK_PATH+apk_lst.get(position).name+".apk");
                
        FileOutputStream saveit = new FileOutputStream(path);
        BufferedOutputStream bout = new BufferedOutputStream(saveit,1024);
        byte data[] = new byte[1024];
                
        int readed = getit.read(data,0,1024);
        while(readed != -1) {
           bout.write(data,0,readed);
           readed = getit.read(data,0,1024);
        }
        bout.close();
        getit.close();
        saveit.close();*/

        String path = new String(APK_PATH + apk_lst.get(position).name + ".apk");
        FileOutputStream saveit = new FileOutputStream(path);
        DefaultHttpClient mHttpClient = new DefaultHttpClient();
        HttpGet mHttpGet = new HttpGet(getserv);

        String[] logins = null;
        logins = db.getLogin(repo);
        if (logins != null) {
            URL mUrl = new URL(getserv);
            mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mUrl.getHost(), mUrl.getPort()),
                    new UsernamePasswordCredentials(logins[0], logins[1]));
        }

        HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
        if (mHttpResponse.getStatusLine().getStatusCode() == 401) {
            return null;
        } else {
            byte[] buffer = EntityUtils.toByteArray(mHttpResponse.getEntity());
            saveit.write(buffer);
        }

        File f = new File(path);
        Md5Handler hash = new Md5Handler();
        if (md5hash == null || md5hash.equalsIgnoreCase(hash.md5Calc(f))) {
            return path;
        } else {
            return null;
        }
    } catch (Exception e) {
        return null;
    }
}