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.kapott.hbci.comm.CommPinTan.java

public CommPinTan withProxy(String proxyHost, String proxyUser, String proxyPass) {
    if (proxyHost != null) {
        String[] proxyData = proxyHost.split(":");
        if (proxyData.length == 2) {
            log.info("HTTPS connections will be made using proxy " + proxyData[0] + "(Port " + proxyData[1]
                    + ")");

            Properties sysProps = System.getProperties();
            sysProps.put("https.proxyHost", proxyData[0]);
            sysProps.put("https.proxyPort", proxyData[1]);

            log.debug("initializing HBCI4Java proxy authentication callback");
            Authenticator.setDefault(new PinTanProxyAuthenticator(proxyUser, proxyPass));
        }//from  w  ww  .j av  a2s  .  com
    }
    return this;
}

From source file:org.openecomp.sdnc.sli.resource.mdsal.RestService.java

private HttpURLConnection getRestConnection(String urlString, String method) throws IOException {

    URL sdncUrl = new URL(urlString);
    Authenticator.setDefault(new SdncAuthenticator(user, passwd));

    HttpURLConnection conn = (HttpURLConnection) sdncUrl.openConnection();

    String authStr = user + ":" + passwd;
    String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes()));

    conn.addRequestProperty("Authentication", "Basic " + encodedAuthStr);

    conn.setRequestMethod(method);//  w  w  w .  ja  va2  s.  c o m

    if (payloadType == PayloadType.XML) {
        conn.setRequestProperty("Content-Type", "application/xml");
        conn.setRequestProperty("Accept", "application/xml");
    } else {

        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
    }

    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);

    return (conn);

}

From source file:org.pentaho.reporting.designer.core.settings.ProxySettings.java

public void installAuthenticator() {
    Authenticator.setDefault(new SettingsAuthenticator());
}

From source file:org.rhq.modules.plugins.jbossas7.ASConnection.java

/**
 * Construct an ASConnection object. The real "physical" connection is done in
 * #executeRaw./*w  w w.j av  a 2 s . c  o  m*/
 * @param host Host of the DomainController or standalone server
 * @param port Port of the JSON api.
 * @param user user needed for authentication
 * @param password password needed for authentication
 */
public ASConnection(String host, int port, String user, String password) {
    this.host = host;
    this.port = port;

    try {
        url = new URL("http", host, port, MANAGEMENT);
        urlString = url.toString();

    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(e.getMessage());
    }

    passwordAuthenticator = new AS7Authenticator(user, password);
    Authenticator.setDefault(passwordAuthenticator);

    // read system property "as7plugin.verbose"
    verbose = Boolean.getBoolean("as7plugin.verbose");

    mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

}

From source file:sce.RESTJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    try {/*  w  w w .  j  a  v  a2s.c  o m*/
        JobKey key = context.getJobDetail().getKey();

        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();

        String url = jobDataMap.getString("#url");

        URL u = new URL(url);

        //get user credentials from URL, if present
        final String usernamePassword = u.getUserInfo();

        //set the basic authentication credentials for the connection
        if (usernamePassword != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(usernamePassword.split(":")[0],
                            usernamePassword.split(":")[1].toCharArray());
                }
            });
        }

        //set the url connection, to disconnect if interrupt() is requested
        this.urlConnection = u.openConnection();
        String result = getUrlContents(this.urlConnection);

        //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener)
        context.setResult(result);

        //if notificationEmail is defined in the job data map, then send a notification email to it
        if (jobDataMap.containsKey("#notificationEmail")) {
            sendEmail(context, jobDataMap.getString("#notificationEmail"));
        }

        //trigger the linked jobs of the finished job, depending on the job result [true, false]
        jobChain(context);

        //Mail.sendMail("prova", "disdsit@gmail.com", "prova di email", "", "");
        //System.out.println("Instance " + key + " of REST Job returns: " + truncateResult(result));
    } catch (MalformedURLException e) {
        throw new JobExecutionException(e);
    } catch (IOException e) {
        throw new JobExecutionException(e);
    }
}

From source file:eu.scape_project.planning.repository.RODAConnector.java

private InputStream downloadFile(Map<String, String> config, String identifier)
        throws RepositoryConnectorException {
    String user = config.get(USER_KEY);
    String pass = config.get(PASS_KEY);

    this.isRequredConfigSet(ENDPOINT_KEY,
            "The RODA endpoint is not set. Cannot connect to " + this.getRepositoryIdentifier());
    this.isRequredConfigSet(user,
            "The user config parameter was not set. Cannot connect to " + this.getRepositoryIdentifier());
    this.isRequredConfigSet(pass,
            "The pass config parameter was not set. Cannot connect to " + this.getRepositoryIdentifier());

    Authenticator.setDefault(new RODAAuthenticator(user, pass));

    try {//from   w w w  . j  a v  a  2s  . c o  m
        URL url = new URL(identifier);
        return url.openConnection().getInputStream();
    } catch (IOException e) {
        throw new RepositoryConnectorException(e);
    }
}

From source file:web.kz.rhq.modules.plugins.jbossas7.ASConnection.java

/**
 * Construct an ASConnection object. The real "physical" connection is done in {@link #executeRaw(Operation)}.
 *
 * @param host Host of the DomainController or standalone server
 * @param port Port of the JSON api.//from  w ww  .j a  v  a 2s  .c  o m
 * @param user user needed for authentication
 * @param password password needed for authentication
 */
public ASConnection(String host, int port, String user, String password) {
    if (host == null) {
        throw new IllegalArgumentException("Management host cannot be null.");
    }
    if (port <= 0 || port > 65535) {
        throw new IllegalArgumentException("Invalid port: " + port);
    }
    this.host = host;
    this.port = port;

    try {
        url = new URL("http", host, port, MANAGEMENT);
        urlString = url.toString();
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(e.getMessage());
    }

    passwordAuthenticator = new AS7Authenticator(user, password);
    Authenticator.setDefault(passwordAuthenticator);

    // read system property "as7plugin.verbose"
    verbose = Boolean.getBoolean("as7plugin.verbose");

    mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}

From source file:net.sourceforge.atunes.kernel.modules.network.NetworkHandler.java

/**
 * Initializes proxy authenticator/*  w  ww.  ja v a  2 s  .c o  m*/
 * 
 * @param proxy
 */
private void initProxy(final ExtendedProxy proxy) {
    if (proxy != null) {
        Authenticator.setDefault(new ProxyAuthenticator(proxy));
    } else {
        Authenticator.setDefault(null);
    }
}

From source file:org.restheart.test.performance.LoadGetPT.java

/**
 *
 *///w ww .j a  v a  2 s.  co  m
public void prepare() {
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(id, pwd.toCharArray());
        }
    });

    try {
        MongoDBClientSingleton.init(FileUtils.getConfiguration(CONF_FILE, false));
    } catch (ConfigurationException ex) {
        System.out.println(ex.getMessage() + ", exiting...");
        System.exit(-1);
    }

    httpExecutor = Executor.newInstance();
    // for perf test we disable the restheart security
    //.authPreemptive(new HttpHost("127.0.0.1", 8080, "http")).auth(new HttpHost("127.0.0.1"), id, pwd);
}

From source file:org.eclipse.kura.core.deployment.download.impl.HttpDownloadCountingOutputStream.java

@Override
public void startWork() throws KuraException {

    this.executor = Executors.newSingleThreadExecutor();

    this.future = this.executor.submit(new Callable<Void>() {

        @Override//from  w  w  w .  j a  v a  2s.c om
        public Void call() throws Exception {
            URL localUrl = null;
            boolean shouldAuthenticate = false;
            try {
                shouldAuthenticate = HttpDownloadCountingOutputStream.this.options.getUsername() != null
                        && HttpDownloadCountingOutputStream.this.options.getPassword() != null
                        && !(HttpDownloadCountingOutputStream.this.options.getUsername().trim().isEmpty()
                                && !HttpDownloadCountingOutputStream.this.options.getPassword().trim()
                                        .isEmpty());

                if (shouldAuthenticate) {
                    Authenticator.setDefault(new Authenticator() {

                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(
                                    HttpDownloadCountingOutputStream.this.options.getUsername(),
                                    HttpDownloadCountingOutputStream.this.options.getPassword().toCharArray());
                        }
                    });
                }

                localUrl = new URL(HttpDownloadCountingOutputStream.this.m_downloadURL);
                URLConnection urlConnection = localUrl.openConnection();
                int connectTimeout = getConnectTimeout();
                int readTimeout = getPropReadTimeout();
                urlConnection.setConnectTimeout(connectTimeout);
                urlConnection.setReadTimeout(readTimeout);

                testConnectionProtocol(urlConnection);

                HttpDownloadCountingOutputStream.this.is = localUrl.openStream();

                String s = urlConnection.getHeaderField("Content-Length");
                s_logger.info("Content-lenght: " + s);

                setTotalBytes(s != null ? Integer.parseInt(s) : -1);
                postProgressEvent(HttpDownloadCountingOutputStream.this.options.getClientId(), 0,
                        HttpDownloadCountingOutputStream.this.totalBytes, DOWNLOAD_STATUS.IN_PROGRESS, null);

                int bufferSize = getBufferSize();

                if (bufferSize == 0 && getTotalBytes() > 0) {
                    int newSize = Math.round(HttpDownloadCountingOutputStream.this.totalBytes / 100 * 1);
                    bufferSize = newSize;
                    setBufferSize(newSize);
                } else if (bufferSize == 0) {
                    int newSize = 1024 * 4;
                    bufferSize = newSize;
                    setBufferSize(newSize);
                }

                long numBytes = IOUtils.copyLarge(HttpDownloadCountingOutputStream.this.is,
                        HttpDownloadCountingOutputStream.this, new byte[bufferSize]);
                postProgressEvent(HttpDownloadCountingOutputStream.this.options.getClientId(), numBytes,
                        HttpDownloadCountingOutputStream.this.totalBytes, DOWNLOAD_STATUS.COMPLETED, null);

            } catch (IOException e) {
                postProgressEvent(HttpDownloadCountingOutputStream.this.options.getClientId(), getByteCount(),
                        HttpDownloadCountingOutputStream.this.totalBytes, DOWNLOAD_STATUS.FAILED,
                        e.getMessage());
                throw new KuraConnectException(e);
            } finally {
                if (HttpDownloadCountingOutputStream.this.is != null) {
                    try {
                        HttpDownloadCountingOutputStream.this.is.close();
                    } catch (IOException e) {
                    }
                }
                try {
                    close();
                } catch (IOException e) {
                }
                localUrl = null;
                if (shouldAuthenticate) {
                    Authenticator.setDefault(null);
                }
            }

            return null;
        }

    });

    try {
        this.future.get();
    } catch (ExecutionException ex) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, ex);
    } catch (InterruptedException ex) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, ex);
    }
}