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.toolsverse.io.FtpUtils.java

/**
 * Connects to the FTP server./*from  w  ww  .ja  v a  2s . co  m*/
 *
 * @param urlStr the url
 * @param loginId the login id
 * @param loginPswd the login ppassword
 * @param passiveMode the passive mode flag
 * @throws Exception in case of any error
 */
public void connect(String urlStr, String loginId, String loginPswd, boolean passiveMode) throws Exception {
    boolean success = false;

    URL url = new URL(urlStr);
    String host = url.getHost();
    int port = url.getPort();
    if (port == -1)
        port = FTP_PORT;

    ftpClient.connect(host, port);

    int reply = ftpClient.getReplyCode();
    if (FTPReply.isPositiveCompletion(reply)) {
        success = ftpClient.login(!Utils.isNothing(loginId) ? loginId : "anonymous",
                Utils.makeString(loginPswd));

        if (!success)
            disconnect();
        else {
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (passiveMode)
                ftpClient.enterLocalPassiveMode();
        }
    }
}

From source file:com.iflytek.spider.net.BasicURLNormalizer.java

public String normalize(String urlString) throws MalformedURLException {
    if ("".equals(urlString)) // permit empty
        return urlString;

    urlString = urlString.trim(); // remove extra spaces

    URL url = new URL(urlString);

    String protocol = url.getProtocol();
    String host = url.getHost();//from w ww. j  a v  a 2 s .c o  m
    int port = url.getPort();
    String file = url.getFile();

    boolean changed = false;

    if (!urlString.startsWith(protocol)) // protocol was lowercased
        changed = true;

    if ("http".equals(protocol) || "ftp".equals(protocol)) {

        if (host != null) {
            String newHost = host.toLowerCase(); // lowercase host
            if (!host.equals(newHost)) {
                host = newHost;
                changed = true;
            }
        }

        if (port == url.getDefaultPort()) { // uses default port
            port = -1; // so don't specify it
            changed = true;
        }

        if (file == null || "".equals(file)) { // add a slash
            file = "/";
            changed = true;
        }

        if (url.getRef() != null) { // remove the ref
            changed = true;
        }

        // check for unnecessary use of "/../"
        String file2 = substituteUnnecessaryRelativePaths(file);

        if (!file.equals(file2)) {
            changed = true;
            file = file2;
        }

    }

    if (changed)
        urlString = new URL(protocol, host, port, file).toString();

    return urlString;
}

From source file:fr.eolya.utils.http.HttpUtils.java

/**
 * Encode url//from w  w w .j  a v  a 2s. c o m
 * 
 * @param url url to be encoded
 * @return 
 */
public static String urlEncode(String url) {
    try {
        URL u = new URL(url);
        String host = u.getHost();
        int indexFile = url.indexOf("/", url.indexOf(host));
        if (indexFile == -1)
            return url;

        String urlFile = u.getFile();
        urlFile = URLDecoder.decode(urlFile, "UTF-8");

        String protocol = u.getProtocol();
        int port = u.getPort();
        if (port != -1 && port != 80 && "http".equals(protocol))
            host += ":".concat(String.valueOf(port));
        if (port != -1 && port != 443 && "https".equals(protocol))
            host += ":".concat(String.valueOf(port));

        URI uri = new URI(u.getProtocol(), host, urlFile, null);
        String ret = uri.toASCIIString();
        ret = ret.replaceAll("%3F", "?");
        return ret;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:com.nginious.http.plugin.RollbackState.java

void checkState(IProject project) {
    try {//from  ww w .j  a  va2  s  .  com
        String publishUrl = project.getPersistentProperty(NginiousPlugin.PUBLISH_URL_PROP_KEY);

        if (publishUrl == null) {
            publishUrl = NginiousPlugin.DEFAULT_PUBLISH_URL;
        }

        String publishUsername = project.getPersistentProperty(NginiousPlugin.PUBLISH_USERNAME_PROP_KEY);

        if (publishUsername == null) {
            publishUsername = NginiousPlugin.DEFAULT_PUBLISH_USERNAME;
        }

        String publishPassword = project.getPersistentProperty(NginiousPlugin.PUBLISH_PASSWORD_PROP_KEY);

        if (publishPassword == null) {
            publishPassword = NginiousPlugin.DEFAULT_PUBLISH_PASSWORD;
        }

        URL url = new URL(publishUrl);
        int port = url.getPort();

        if (port == -1) {
            port = url.getDefaultPort();
        }

        HttpClientRequest request = new HttpClientRequest();
        request.setMethod(HttpMethod.GET);
        request.setPath(url.getPath());
        request.setHeader("Host", url.getHost());
        request.setHeader("Content-Type", "text/xml; charset=utf-8");
        request.setHeader("Connection", "close");
        request.setHeader("Content-Length", "0");
        String authorization = createAuthorization(HttpMethod.GET, publishUsername, publishPassword);
        request.setHeader("Authorization", authorization);

        HttpClient client = new HttpClient(url.getHost(), port);
        HttpClientResponse response = client.request(request, "".getBytes());

        if (response.getStatus() == HttpStatus.OK) {
            setState(project, response);
        }
    } catch (HttpClientException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (CoreException e) {
        e.printStackTrace();
    }
}

From source file:jhc.redsniff.webdriver.download.FileDownloader.java

private HttpClient createHttpClient(URL downloadURL) {
    HttpClient client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
    client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort()));
    client.setState(mimicCookieState(driver.manage().getCookies()));
    return client;
}

From source file:org.dataconservancy.access.connector.HttpDcsSearchIteratorTest.java

@Override
protected DcsConnectorConfig getConnectorConfig() {
    DcsConnectorConfig config = new DcsConnectorConfig();
    try {/*  w w  w  .j  a  v a 2  s.c o  m*/
        URL u = new URL(
                String.format(accessServiceUrl, testServer.getServiceHostName(), testServer.getServicePort()));
        config.setScheme(u.getProtocol());
        config.setHost(u.getHost());
        config.setPort(u.getPort());
        config.setContextPath(u.getPath());
        config.setMaxOpenConn(1);
    } catch (MalformedURLException e) {
        fail("Unable to construct connector configuration: " + e.getMessage());
    }

    return config;
}

From source file:com.trunghoang.teammedical.utils.FileDownloader.java

public File urlDownloader(String downloadLocation) throws Exception {
    URL downloadURL = new URL(downloadLocation);
    HttpClient client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
    client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort()));
    client.getParams().makeLenient();//from w  w w .  j ava  2s  . co m
    client.setState(mimicCookieState(driver.manage().getCookies()));
    HttpMethod getRequest = new GetMethod(downloadLocation);
    getRequest.setFollowRedirects(true);
    FileHandler downloadedFile = new FileHandler(
            downloadPath + downloadURL.getFile().replaceFirst("/|\\\\", ""), true);
    try {
        int status = client.executeMethod(getRequest);
        log.info("HTTP Status {} when getting '{}'", status, downloadURL.toExternalForm());
        downloadedFile.getWritableFileOutputStream().write(getRequest.getResponseBody());
        downloadedFile.close();
        log.info("File downloaded to '{}'", downloadedFile.getAbsoluteFile());
    } catch (Exception Ex) {
        log.error("Download failed: {}", Ex);
        throw new Exception("Download failed!");
    } finally {
        getRequest.releaseConnection();
    }
    return downloadedFile.getFile();
}

From source file:com.oakesville.mythling.util.MediaStreamProxy.java

private HttpResponse download() throws IOException {

    httpClient = AndroidHttpClient.newInstance("Android");
    // httpClient.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost("127.0.0.1"));

    URL netUrl = proxyInfo.netUrl;
    HttpHost host = new HttpHost(netUrl.getHost(), netUrl.getPort(), netUrl.getProtocol());

    HttpRequestBase request = new HttpGet(netUrl.toString());
    HttpResponse response = null;/*from ww w . j av  a 2  s .  c o  m*/
    Log.d(TAG, "Proxy starting download");
    if (authType == AuthType.Digest) {
        HttpContext context = HttpHelper.getDigestAuthContext(netUrl.getHost(), netUrl.getPort(),
                proxyInfo.user, proxyInfo.password);
        response = httpClient.execute(host, request, context);
    } else if (authType == AuthType.Basic) {
        String credentials = Base64.encodeToString((proxyInfo.user + ":" + proxyInfo.password).getBytes(),
                Base64.DEFAULT);
        request.setHeader("Authorization", "Basic " + credentials);
        response = httpClient.execute(host, request);
    } else {
        response = httpClient.execute(host, request);
    }
    Log.d(TAG, "Proxy response downloaded");
    return response;
}

From source file:edu.si.services.sidora.rest.batch.beans.BatchRequestControllerBean.java

/**
 * Check Resource MimeType using Apache Tika
 * @param exchange/*from   w w w . j  a v  a  2  s.c om*/
 * @throws URISyntaxException
 * @throws MalformedURLException
 */
public void getMIMEType(Exchange exchange) throws URISyntaxException, MalformedURLException {

    /**
     * TODO:
     *
     * Need to make sure that mimetypes are consistent with what's used in workbench.
     * See link for workbench mimetype list
     *
     * https://github.com/Smithsonian/sidora-workbench/blob/master/workbench/includes/utils.inc#L1119
     *
     */

    out = exchange.getIn();

    URL url = new URL(out.getHeader("resourceFile", String.class));

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

    String resourceFile = uri.toASCIIString();
    String resourceFileExt = FilenameUtils.getExtension(resourceFile);
    String mimeType = null;

    if (resourceFileExt.equalsIgnoreCase("nef")) {
        mimeType = "image/x-nikon-nef";
    } else if (resourceFileExt.equalsIgnoreCase("dng")) {
        mimeType = "image/x-adobe-dng";
    } else {
        LOG.debug("Checking {} for MIME Type", resourceFile);

        mimeType = new Tika().detect(resourceFile);
    }

    LOG.debug("Batch Process " + resourceFile + " || MIME=" + mimeType);

    out.setHeader("dsMIME", mimeType);
}

From source file:com.tasktop.c2c.server.common.service.HttpProxySetup.java

public void setupProxyFromEnvironment() {
    String http_proxy = System.getenv().get("http_proxy");

    if (http_proxy != null) {
        if (!http_proxy.startsWith("http://")) {
            http_proxy = "http://" + http_proxy;
        }//w ww  .  j a  v  a2s  .  com

        logger.info("Configuring http proxy as: " + http_proxy);
        try {
            URL proxyUrl = new URL(http_proxy);
            httpProxyHost = proxyUrl.getHost();
            System.setProperty("http.proxyHost", httpProxyHost);
            httpProxyPort = proxyUrl.getPort();
            if (httpProxyPort != 80) {
                System.setProperty("http.proxyPort", httpProxyPort + "");
            }

        } catch (MalformedURLException e) {
            logger.error("Error configuring proxy", e);
        }

    } else {
        logger.info("No http proxy defined");
    }

    String https_proxy = System.getenv().get("https_proxy");
    if (https_proxy != null) {
        if (!https_proxy.startsWith("https://")) {
            https_proxy = "https://" + https_proxy;
        }

        logger.info("Configuring https proxy as: " + https_proxy);
        try {
            URL proxyUrl = new URL(https_proxy);
            System.setProperty("https.proxyHost", proxyUrl.getHost());
            if (proxyUrl.getPort() != 443) {
                System.setProperty("https.proxyPort", proxyUrl.getPort() + "");
            }
        } catch (MalformedURLException e) {
            logger.error("Error configuring proxy", e);
        }

    } else {
        logger.info("No https proxy defined");
    }

    String no_proxy = System.getenv().get("no_proxy");

    if (no_proxy != null) {
        no_proxy = no_proxy.replace(",", "|");
    }

    if (dontProxyToProfile) {
        if (no_proxy == null) {
            no_proxy = "";
        } else {
            no_proxy = no_proxy + "|";
        }
        no_proxy = no_proxy + profileConfiguration.getBaseWebHost() + "|*."
                + profileConfiguration.getBaseWebHost();
    }

    if (no_proxy != null && !no_proxy.isEmpty()) {
        logger.info("Configuring no_proxy as: " + no_proxy);

        System.setProperty("http.nonProxyHosts", no_proxy);
        System.setProperty("https.nonProxyHosts", no_proxy);
    }

}