Example usage for java.net Authenticator setDefault

List of usage examples for java.net Authenticator setDefault

Introduction

In this page you can find the example usage for java.net Authenticator setDefault.

Prototype

public static synchronized void setDefault(Authenticator a) 

Source Link

Document

Sets the authenticator that will be used by the networking code when a proxy or an HTTP server asks for authentication.

Usage

From source file:com.cisco.dvbu.ps.common.util.wsapi.CisApiFactory.java

/**
 * Returns the UserPort of AdminAPI//from  w w  w  .  ja v  a2s .  c o m
 * @param server Composite Server
 * @return UserPort of AdminAPI
 */
public static UserPortType getUserPort(CompositeServer server) {

    Authenticator.setDefault(new BasicAuthenticator(server));

    URL url = null;
    String protocol = "http";
    int wsPort = server.getPort();
    if (server.isUseHttps()) {
        protocol = "https";
        wsPort += 2;
    }
    try {
        url = new URL(protocol + "://" + server.getHostname() + ":" + wsPort + "/services/system/admin?wsdl");
        if (logger.isDebugEnabled()) {
            logger.debug("Entering CisApiFactory.getUserPort() with following params " + " url: " + url);
        }
    } catch (MalformedURLException e) {
        String errorMessage = DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                "Creating User Port", "Admin API", "UserPort", server);
        CompositeLogger.logException(e, errorMessage);
        throw new CompositeException(errorMessage, e);
    }

    int retry = 0;
    while (retry < numRetries) {
        retry++;
        try {
            User user = new User(url, new QName(nsUserUrl, nsUserName)); // Get the connection to the server.
            if (logger.isDebugEnabled()) {
                if (user != null)
                    logger.debug("Entering CisApiFactory.getUserPort(). User acquired " + " User: "
                            + user.toString());
            }
            UserPortType port = user.getUserPort(); // Get the server port
            if (logger.isDebugEnabled()) {
                if (port != null)
                    logger.debug("Entering CisApiFactory.getUserPort(). Port acquired " + " Port: "
                            + port.toString());
            }
            return port; // Return the port connection to the server.
        } catch (Exception e) {
            String errorMessage = DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                    "Getting Server Port, [CONNECT ATTEMPT=" + retry + "]", "Admin API", "ServerPort", server);
            if (retry == numRetries) {
                throw new CompositeException(errorMessage, e);
            } else {
                // Log the error and sleep before retrying
                CompositeLogger.logException(e, errorMessage);
                Sleep.sleep(sleepDebug, sleepRetry);
            }
        }
    }
    throw new CompositeException(
            "Maximum connection attempts reached without connecting to the Composite Information Server.");
}

From source file:org.panlab.tgw.restclient.RepoAdapter.java

public static ResourceSpec getResourceSpec(String type, String ptm_id) {
    log.info(type + "@" + ptm_id);
    Ptm ptm = getPtm(ptm_id);/*from   ww  w .  j a  va 2s  .c  o  m*/
    String info_id = ptm.getDescribedByPtmInfo().getId();
    PtmInfo ptmInfo = getPtmInfo(info_id);

    Client c = Client.create();
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/resourceSpec/");

    String resp = r.get(String.class);

    //System.out.println(resp);
    resp = addSchemaDefinition(resp);
    try {
        ListDocument lDoc = ListDocument.Factory.parse(resp);
        ResourceSpec[] rsArray = lDoc.getList().getResourceSpecArray();

        for (int i = 0; i < rsArray.length; i++)
            if (rsArray[i].isSetCommonName() && rsArray[i].getCommonName().equalsIgnoreCase(type)) {
                if (containsSpec(ptmInfo, rsArray[i].getId()))
                    return rsArray[i];
            }
    } catch (XmlException ex) {
        ex.printStackTrace();
        return null;
    }
    return null;
}

From source file:com.tremolosecurity.provisioning.sharepoint.SharePointGroups.java

private UserGroupSoap getConnection(URL url) throws Exception {
    UserGroup ss = new UserGroup(wsdl.toURI().toURL(), SERVICE);
    UserGroupSoap port = ss.getUserGroupSoap12();

    BindingProvider provider = (BindingProvider) port;

    if (authType == AuthType.UnisonLastMile) {
        DateTime now = new DateTime();
        DateTime future = now.plusMillis(this.skew);
        now = now.minusMillis(skew);/*from   w  w w  .j a  v  a2 s. com*/
        com.tremolosecurity.lastmile.LastMile lastmile = new com.tremolosecurity.lastmile.LastMile(
                url.getPath(), now, future, 0, "chainName");
        lastmile.getAttributes().add(new Attribute("userPrincipalName", this.administratorUPN));

        SecretKey sk = this.cfg.getSecretKey(this.keyAlias);
        Map<String, List<String>> headers = (Map<String, List<String>>) provider.getRequestContext()
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        if (headers == null) {
            headers = new HashMap<String, List<String>>();
        }

        headers.put(this.headerName, Collections.singletonList(lastmile.generateLastMileToken(sk)));

        provider.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, headers);
    } else if (authType == AuthType.NTLM) {
        NtlmAuthenticator authenticator = new NtlmAuthenticator(this.administratorUPN,
                this.administratorPassword);
        Authenticator.setDefault(authenticator);

    }

    provider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url.toString());

    return port;
}

From source file:org.owasp.proxy.Main.java

private static HttpRequestHandler configureAuthentication(HttpRequestHandler rh, final Configuration config) {
    if (config.authUser != null) {
        if (config.authPassword == null) {
            System.err.println("authPassword must be provided!");
            System.exit(1);//from w w w  .ja  va  2s.  co  m
        }
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.authUser, config.authPassword.toCharArray());
            }
        });
        return new AuthenticatingHttpRequestHandler(rh);
    } else {
        return rh;
    }
}

From source file:org.panlab.tgw.restclient.RepoAdapter.java

public static ConfigParamComposite getComposite(String id) {
    Client c = Client.create();/*w  ww  .j av  a2 s .c  o  m*/
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/configParamComposite/" + id);

    String resp = r.get(String.class);

    //System.out.println(resp);
    resp = addSchemaDefinition(resp);
    try {
        ConfigParamCompositeDocument cpcDoc = ConfigParamCompositeDocument.Factory.parse(resp);
        return cpcDoc.getConfigParamComposite();
    } catch (XmlException ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.panlab.tgw.restclient.RepoAdapter.java

public static ConfigParamAtomic getAtomic(String id) {
    Client c = Client.create();/*from   ww w.j  a  v a2 s  .c  o m*/
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/configParamAtomic/" + id);

    String resp = r.get(String.class);

    //System.out.println(resp);
    resp = addSchemaDefinition(resp);
    try {
        ConfigParamAtomicDocument cpcDoc = ConfigParamAtomicDocument.Factory.parse(resp);
        return cpcDoc.getConfigParamAtomic();
    } catch (XmlException ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.cisco.dvbu.ps.common.util.wsapi.CisApiFactory.java

/**
 * Returns the ServerPort of AdminAPI/*from   www  .j  a va2s.  c om*/
 * @param server Composite Server
 * @return ServerPort of AdminAPI
 */
public static ServerPortType getServerPort(CompositeServer server) {

    Authenticator.setDefault(new BasicAuthenticator(server));

    URL url = null;
    String protocol = "http";
    int wsPort = server.getPort();
    if (server.isUseHttps()) {
        protocol = "https";
        wsPort += 2;
    }
    try {
        url = new URL(protocol + "://" + server.getHostname() + ":" + wsPort + "/services/system/admin?wsdl");
        if (logger.isDebugEnabled()) {
            logger.debug("Entering CisApiFactory.getServerPort() with following params " + " url: " + url);
        }
    } catch (MalformedURLException e) {
        String errorMessage = DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                "Creating Server Port", "Admin API", "ServerPort", server);
        CompositeLogger.logException(e, errorMessage);
        throw new CompositeException(errorMessage, e);
    }

    int retry = 0;
    while (retry < numRetries) {
        retry++;
        try {
            Server srvr = new Server(url, new QName(nsServerUrl, nsServerName)); // Get the connection to the server.
            if (logger.isDebugEnabled()) {
                if (srvr != null)
                    logger.debug("Entering CisApiFactory.getServerPort(). Server acquired " + " Server: "
                            + srvr.toString());
            }
            ServerPortType port = srvr.getServerPort(); // Get the server port
            if (logger.isDebugEnabled()) {
                if (port != null)
                    logger.debug("Entering CisApiFactory.getServerPort(). Port acquired " + " Port: "
                            + port.toString());
            }
            return port; // Return the port connection to the server.
        } catch (Exception e) {
            String errorMessage = DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                    "Getting Server Port, [CONNECT ATTEMPT=" + retry + "]", "Admin API", "ServerPort", server);
            if (retry == numRetries) {
                throw new CompositeException(errorMessage, e);
            } else {
                // Log the error and sleep before retrying
                CompositeLogger.logException(e, errorMessage);
                Sleep.sleep(sleepDebug, sleepRetry);
            }
        }
    }
    throw new CompositeException(
            "Maximum connection attempts reached without connecting to the  to Composite Information Server.");
}

From source file:org.panlab.tgw.restclient.RepoAdapter.java

public static Ptm getPtm(String ptm_id) {
    Client c = Client.create();/*  ww  w .j  a  v a 2 s  .  co  m*/
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/ptm/");

    String resp = r.get(String.class);

    //System.out.println(resp);
    resp = addSchemaDefinition(resp);
    try {
        ListDocument lDoc = ListDocument.Factory.parse(resp);
        Ptm[] ptmArray = lDoc.getList().getPtmArray();

        for (int i = 0; i < ptmArray.length; i++)
            if (ptmArray[i].isSetCommonName() && ptmArray[i].getCommonName().equalsIgnoreCase(ptm_id)) {
                return ptmArray[i];
            }
    } catch (XmlException ex) {
        ex.printStackTrace();
        return null;
    }
    return null;
}

From source file:org.panlab.tgw.restclient.RepoAdapter.java

public static PtmInfo getPtmInfo(String ptmInfoId) {
    Client c = Client.create();//from  ww w.  j a v a 2  s .c o  m
    c.setFollowRedirects(true);
    Authenticator.setDefault(new PwdAuthenticator());
    WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/ptmInfo/");

    String resp = r.get(String.class);

    //System.out.println(resp);
    resp = addSchemaDefinition(resp);
    try {
        ListDocument lDoc = ListDocument.Factory.parse(resp);
        PtmInfo[] pInfo = lDoc.getList().getPtmInfoArray();

        for (int i = 0; i < pInfo.length; i++)
            if (pInfo[i].isSetId() && pInfo[i].getId().equalsIgnoreCase(ptmInfoId)) {
                return pInfo[i];
            }
    } catch (XmlException ex) {
        ex.printStackTrace();
        return null;
    }
    return null;
}

From source file:com.motorola.studio.android.localization.translators.GoogleTranslator.java

/**
 * Creates an HTTP request with the URL, execute it as a get, and returns
 * the a string with the result.//  w w w .ja  v a  2 s.  c om
 * 
 * @param url
 *            URL to be executed.
 * @return String with the URL execution result.
 * @throws IOException
 *             If an exception occurs on transport
 * @throws HttpException
 *             If an exception occurs on the protocol
 * @throws Exception
 *             on error.
 */
protected static String executeHttpGetRequest(final URL url) throws HttpException {

    // Checking query size due to google policies
    if (url.toString().length() > MAX_QUERY_SIZE) {
        throw new HttpException(TranslateNLS.GoogleTranslator_Error_QueryTooBig);
    }

    // Try to retrieve proxy configuration to use if necessary
    IProxyService proxyService = ProxyManager.getProxyManager();
    IProxyData proxyData = null;
    if (proxyService.isProxiesEnabled() || proxyService.isSystemProxiesEnabled()) {
        Authenticator.setDefault(new ProxyAuthenticator());
        String urlStr = url.toString();
        if (urlStr.startsWith("https")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTPS_PROXY_TYPE);
            StudioLogger.debug(GoogleTranslator.class, "Using https proxy"); //$NON-NLS-1$
        } else if (urlStr.startsWith("http")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTP_PROXY_TYPE);
            StudioLogger.debug(GoogleTranslator.class, "Using http proxy"); //$NON-NLS-1$
        } else {
            StudioLogger.debug(GoogleTranslator.class, "Not using any proxy"); //$NON-NLS-1$
        }
    }

    // Creates the http client and the method to be executed
    HttpClient client = null;
    client = new HttpClient();

    // If there is proxy data, work with it
    if (proxyData != null) {
        if (proxyData.getHost() != null) {
            // Sets proxy host and port, if any
            client.getHostConfiguration().setProxy(proxyData.getHost(), proxyData.getPort());
        }

        if (proxyData.getUserId() != null && proxyData.getUserId().trim().length() > 0) {
            // Sets proxy user and password, if any
            Credentials cred = new UsernamePasswordCredentials(proxyData.getUserId(),
                    proxyData.getPassword() == null ? "" : proxyData.getPassword()); //$NON-NLS-1$
            client.getState().setProxyCredentials(AuthScope.ANY, cred);
        }
    }

    // Creating the method to be executed, the URL at this point is enough
    // because it is complete
    GetMethod method = new GetMethod(url.toString());

    // Set method to be retried three times in case of error
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(RETRIES, false));

    method.setRequestHeader(REFERER_HEADER, REFERER_SITE);

    // Set the connection timeout               
    client.getHttpConnectionManager().getParams().setConnectionTimeout(new Integer(TIMEOUT));

    String result = ""; //$NON-NLS-1$
    try {
        // Execute the method.
        int statusCode;
        try {
            statusCode = client.executeMethod(method);
            result = method.getResponseBodyAsString(MAX_SIZE);
        } catch (IOException e) {
            throw new HttpException(TranslateNLS.GoogleTranslator_Error_CannotConnectToServer + e.getMessage());
        }

        checkStatusCode(statusCode, result);

        // Unescape any possible unicode char
        result = unescapeUnicode(result);

        // Unescape any possible HTML sequence
        result = unescapeHTML(result);

    }

    finally {
        // Release the connection.
        method.releaseConnection();
    }

    return result;
}