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:org.elite.jdcbot.util.GoogleCalculation.java

public GoogleCalculation(jDCBot bot, String calc, String u) throws Exception {
    final String authUser = "pforpallav";
    final String authPassword = "buckmin$ter";
    Authenticator.setDefault(new Authenticator() {
        @Override//www  .  j  a  va 2 s  . c  om
        protected PasswordAuthentication getPasswordAuthentication() {
            //logger.info(MessageFormat.format("Generating PasswordAuthentitcation for proxy authentication, using username={0} and password={1}.", username, password));
            return new PasswordAuthentication(authUser, authPassword.toCharArray());
        }
    });

    System.setProperty("http.proxyHost", "netmon.iitb.ac.in");
    System.setProperty("http.proxyPort", "80");
    System.setProperty("http.proxyUser", authUser);
    System.setProperty("http.proxyPassword", authPassword);

    String url = "http://www.google.com/ig/calculator?hl=en&q=";
    _bot = bot;
    user = u;
    calc = URLEncoder.encode(calc, "UTF-8");
    url = url + calc;
    SetURL(url);
}

From source file:org.overlord.sramp.governance.workflow.jbpm.EmbeddedJbpmManager.java

@Override
public long newProcessInstance(String deploymentId, String processId, Map<String, Object> context)
        throws WorkflowException {
    HttpURLConnection connection = null;
    Governance governance = new Governance();
    final String username = governance.getOverlordUser();
    final String password = governance.getOverlordPassword();
    Authenticator.setDefault(new Authenticator() {
        @Override/*from   w ww . j a  v  a  2 s.c  o m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    });

    try {
        deploymentId = URLEncoder.encode(deploymentId, "UTF-8"); //$NON-NLS-1$
        processId = URLEncoder.encode(processId, "UTF-8"); //$NON-NLS-1$
        String urlStr = governance.getGovernanceUrl()
                + String.format("/rest/process/start/%s/%s", deploymentId, processId); //$NON-NLS-1$
        URL url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        StringBuffer params = new StringBuffer();
        for (String key : context.keySet()) {
            String value = String.valueOf(context.get(key));
            value = URLEncoder.encode(value, "UTF-8"); //$NON-NLS-1$
            params.append(String.format("&%s=%s", key, value)); //$NON-NLS-1$
        }
        //remove leading '&'
        if (params.length() > 0)
            params.delete(0, 1);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST"); //$NON-NLS-1$
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(60000);
        if (params.length() > 0) {
            PrintWriter out = new PrintWriter(connection.getOutputStream());
            out.print(params.toString());
            out.close();
        }
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode >= 200 && responseCode < 300) {
            InputStream is = (InputStream) connection.getContent();
            String reply = IOUtils.toString(is);
            logger.info("reply=" + reply); //$NON-NLS-1$
            return Long.parseLong(reply);
        } else {
            logger.error("HTTP RESPONSE CODE=" + responseCode); //$NON-NLS-1$
            throw new WorkflowException("Unable to connect to " + urlStr); //$NON-NLS-1$
        }
    } catch (Exception e) {
        throw new WorkflowException(e);
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

From source file:org.pentaho.supportutility.rest.client.RestFulClient.java

/**
 * to call restful service to get license and data-source details
 * /*from  ww w. j av  a  2 s .co m*/
 * @param server
 * @param required
 * @param prop
 * @param webXml
 * @return
 */
public static String restFulService(String server, String required, final Properties prop, String webXml) {

    String outPut = null;
    String qualifiedUrl = null;
    // based on server get restful url
    if (server.equalsIgnoreCase(RestFulURL.BI_SERVER)) {

        qualifiedUrl = prop.getProperty(RestFulURL.FULLY_QUALIFIED_BISERVER_URL);
    } else if (server.equalsIgnoreCase(RestFulURL.DI_SERVER)) {

        qualifiedUrl = prop.getProperty(RestFulURL.FULLY_QUALIFIED_DISERVER_URL);
    } else if (server.equalsIgnoreCase(RestFulURL.SPOON_IDE)) {

        qualifiedUrl = prop.getProperty(RestFulURL.FULLY_QUALIFIED_DISERVER_URL);
    }
    URL url = null;

    try {
        if (required.equalsIgnoreCase(RestFulURL.LICENSE)) {

            url = getLicenseUrl(qualifiedUrl);
        } else if (required.equalsIgnoreCase(RestFulURL.ANALYSIS)) {

            url = getAnalysisUrl(qualifiedUrl);
        } else if (required.equalsIgnoreCase(RestFulURL.METADATA)) {

            url = getMateDataUrl(qualifiedUrl);
        } else if (required.equalsIgnoreCase(RestFulURL.DSW)) {

            url = getDSW(qualifiedUrl);
        }

        // authenticating the restful service
        Authenticator.setDefault(new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(prop.getProperty(RestFulURL.USER_NAME),
                        prop.getProperty(RestFulURL.USER_PASSWORD).toCharArray());
            }

        });

        String basicAuth = RestFulURL.BASIC
                + new String(Base64.encodeBase64((prop.getProperty(RestFulURL.USER_NAME) + RestFulURL.COLON
                        + prop.getProperty(RestFulURL.USER_PASSWORD)).getBytes()));

        if (url != null) {
            // calling restful service
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection conn = (HttpURLConnection) urlConnection;
            urlConnection.setRequestProperty(RestFulURL.AUTHOR, basicAuth);
            conn.connect();
            if (conn.getResponseCode() == 200) {
                BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
                outPut = br.readLine();
            }

            conn.disconnect();
        }

    } catch (MalformedURLException e) {
        e.getMessage();
    } catch (IOException e) {
        e.getMessage();
    }

    return outPut;

}

From source file:org.openmrs.module.yank.api.impl.RestClient.java

public static String listQuery(String serverName, String username, String password, String resourceName,
        String queryParamName, String query) {
    Authenticator.setDefault(new BasicAuth(username, password));
    return getRootResource(serverName).path(resourceName).queryParam(queryParamName, query)
            .accept(MediaType.APPLICATION_JSON_TYPE).get(String.class);
}

From source file:org.openintents.lib.DeliciousApiHelper.java

public DeliciousApiHelper(String api, String user, String passwd) {
    this.mAPI = api;
    this.mUser = user;
    this.mPasswd = passwd;

    //init the authentication
    Authenticator.setDefault(new Authenticator() {
        @Override// ww  w  .  j a v a  2s.  c o m
        protected PasswordAuthentication getPasswordAuthentication() {
            System.out.printf("url=%s, host=%s, ip=%s, port=%s%n", getRequestingURL(), getRequestingHost(),
                    getRequestingSite(), getRequestingPort());

            return new PasswordAuthentication(DeliciousApiHelper.this.mUser,
                    DeliciousApiHelper.this.mPasswd.toCharArray());
        }
    });

}

From source file:org.talend.core.nexus.NexusServerUtils.java

/**
 * /*from   w  w  w.jav a2s. c om*/
 * DOC check if the repository exist or not
 * 
 * @param nexusUrl
 * @param repositoryId
 * @param userName
 * @param password
 * @return
 */
public static boolean checkConnectionStatus(String nexusUrl, String repositoryId, final String userName,
        final String password) {
    if (StringUtils.isEmpty(nexusUrl)) {
        return false;
    }
    final Authenticator defaultAuthenticator = NetworkUtil.getDefaultAuthenticator();
    if (userName != null && !"".equals(userName)) {
        Authenticator.setDefault(new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password.toCharArray());
            }

        });
    }
    int status = -1;
    try {
        if (nexusUrl == null || "".equals(nexusUrl) || repositoryId == null || "".equals(repositoryId)) {
            return false;
        }
        String newUrl = nexusUrl;
        if (newUrl.endsWith(NexusConstants.SLASH)) {
            newUrl = newUrl.substring(0, newUrl.length() - 1);
        }
        String urlToCheck = newUrl + NexusConstants.CONTENT_REPOSITORIES + repositoryId;

        URL url = new URL(urlToCheck);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        if (urlConnection instanceof HttpsURLConnection) {
            String userDir = Platform.getInstallLocation().getURL().getPath();
            final SSLSocketFactory socketFactory = SSLUtils.getSSLContext(userDir).getSocketFactory();
            HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
            httpsConnection.setSSLSocketFactory(socketFactory);
            httpsConnection.setHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

            });
        }
        IEclipsePreferences node = InstanceScope.INSTANCE.getNode(ORG_TALEND_DESIGNER_CORE);
        int timeout = node.getInt(ITalendCorePrefConstants.NEXUS_TIMEOUT, 10000);

        urlConnection.setConnectTimeout(timeout);
        urlConnection.setReadTimeout(timeout);
        status = urlConnection.getResponseCode();
        if (status == CONNECTION_OK) {
            return true;
        }
    } catch (Exception e) {
        ExceptionHandler.process(e);
    } finally {
        Authenticator.setDefault(defaultAuthenticator);
    }
    return false;
}

From source file:org.elasticsearch.hadoop.rest.commonshttp.SocksSocketFactory.java

SocksSocketFactory(String socksHost, int socksPort, final String user, final String pass) {
    this.socksHost = socksHost;
    this.socksPort = socksPort;

    if (StringUtils.hasText(user)) {
        final PasswordAuthentication auth = new PasswordAuthentication(user, pass.toCharArray());

        Authenticator.setDefault(new Authenticator() {
            @Override//from  w  w w  .  ja  v a  2 s.c  o m
            protected PasswordAuthentication getPasswordAuthentication() {
                return auth;
            }
        });
    }
}

From source file:org.phenotips.internal.ProxyAuthenticator.java

@Override
public void onEvent(Event event, Object source, Object data) {
    final String proxyUser = System.getProperty("http.proxyUser");
    final String proxyPassword = System.getProperty("http.proxyPassword");
    if (StringUtils.isNoneBlank(proxyUser, proxyPassword)) {
        Authenticator.setDefault(new Authenticator() {
            @Override// w w w.j a va 2 s.  c  o m
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
            }
        });
    }
}

From source file:savant.controller.TrackController.java

private TrackController() {
    tracks = new ArrayList<Track>();
    Authenticator.setDefault(new SavantHTTPAuthenticator());
}

From source file:com.freedomotic.plugin.purl.Purl.java

@Override
protected void onRun() {
    //called in a loop while this plugin is running
    //loops waittime is specified using setPollingWait()
    Authenticator.setDefault(new MyAuthenticator());
    String pageContent = "";
    String url = "";
    try {/*from   w ww .j av a2  s.c o m*/
        url = URLDecoder.decode(configuration.getStringProperty("url", ""), "UTF-8");
        pageContent = readPage(new URL(url));
    } catch (Exception ex) {
        Logger.getLogger(Purl.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (!pageContent.isEmpty()) {
        GenericEvent event = new GenericEvent(this);
        event.setDestination("app.event.sensor.url");
        event.addProperty("url", url);
        event.addProperty("url.content", pageContent);
        event.addProperty("url.content.length", String.valueOf(pageContent.length()));
        notifyEvent(event);
        setDescription("Readed " + pageContent.length() + "characters");
    }
}