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.uf.togathor.Togathor.java

@Override
public void onCreate() {
    super.onCreate();
    sInstance = this;
    mPreferences = new Preferences(this);
    mPreferences.clearFlagsForTutorialEachBoot(getApplicationContext().getPackageName());
    gOpenFromBackground = true;//from w ww .j a  va2  s  .  c  om
    mFileDir = new FileDir(this);

    mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
    googleAPIService = new GoogleAPIService(this);
    messagesDataSource = new MessagesDataSource(this);
    eventMessagesDataSource = new EventMessagesDataSource(this);
    contactsDataSource = new ContactsDataSource(this);
    startEventService();
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("s3lab", "S3LAB!!".toCharArray());
        }
    });

    // Create typefaces
    mTfMyriadPro = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Regular.ttf");
    mTfMyriadProBold = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Bold.ttf");

    setTransportBasedOnScreenDensity(42);

    // Example interpolator; could use linear or accelerate interpolator
    // instead
    final AccelerateDecelerateInterpolator accDecInterpolator = new AccelerateDecelerateInterpolator();
    final LinearInterpolator linearInterpolator = new LinearInterpolator();
    final int slidingDuration = getResources().getInteger(R.integer.sliding_duration);

    // Set up animations
    mSlideInLeft = new TranslateAnimation(-mTransport, 0, 0, 0);
    mSlideInLeft.setDuration(slidingDuration);
    // mSlideInLeft.setFillAfter(true); // hmm not sure
    mSlideInLeft.setFillEnabled(false);
    mSlideInLeft.setInterpolator(linearInterpolator);

    mSlideOutRight = new TranslateAnimation(0, mTransport, 0, 0);
    mSlideOutRight.setDuration(slidingDuration);
    mSlideOutRight.setFillAfter(true);
    mSlideOutRight.setFillEnabled(true);
    mSlideOutRight.setInterpolator(linearInterpolator);

    mSlideOutLeft = new TranslateAnimation(0, -mTransport, 0, 0);
    mSlideOutLeft.setDuration(slidingDuration);
    mSlideOutLeft.setInterpolator(linearInterpolator);

    mSlideInRight = new TranslateAnimation(mTransport, 0, 0, 0);
    mSlideInRight.setDuration(slidingDuration);
    mSlideInRight.setFillAfter(true);
    mSlideInRight.setFillEnabled(true);
    mSlideInRight.setInterpolator(linearInterpolator);

    mSlideFromTop.setFillAfter(true);
    mSlideFromTop.setFillEnabled(true);
    mSlideFromTop.setDuration(this.getResources().getInteger(android.R.integer.config_mediumAnimTime));
    mSlideFromTop.setInterpolator(linearInterpolator);

    mSlideOutTop.setDuration(this.getResources().getInteger(android.R.integer.config_mediumAnimTime));
    mSlideOutTop.setInterpolator(linearInterpolator);

    String strUUID = UUID.randomUUID().toString();
    Logger.debug("uuid", strUUID);

    mBaseUrl = mPreferences.getUserServerURL();
}

From source file:com.cloudera.recordservice.tests.ClusterConfiguration.java

/**
 * This method gets a cluster configuration and write the configuration to a
 * zipfile. The method returns the path of the zipfile.
 *//*from   ww w.j a  va2 s .  co m*/
private String getClusterConfiguration(URL url) throws IOException {
    // This Authenticator object sets the user and password field, similar to
    // using the --user username:password flag with the linux curl command
    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username_, password_.toCharArray());
        }
    });

    int num = rand_.nextInt(10000000);
    String confZipFileName = "/tmp/" + "clusterConf" + "_" + num + ".zip";
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        URLConnection conn = url.openConnection();
        is = conn.getInputStream();
        fos = new FileOutputStream(confZipFileName);
        byte[] buffer = new byte[4096];
        int len;
        while ((len = is.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }
    return confZipFileName;
}

From source file:sce.RESTJobStateful.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    try {/*from w  ww.j ava2 s  . 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:org.geotools.wfs.protocol.DefaultConnectionFactory.java

private static HttpURLConnection getConnection(final URL url, final boolean tryGzip, final HttpMethod method,
        final Authenticator auth, final int timeoutMillis) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    if (POST == method) {
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);//from w  w w . j  av a  2s  . c o m
        /*ESRI ArcGis has a bug when sending xml and content-type = text/xml. When omitting
        it, it works fine.*/
        if (url == null || !url.toString().contains("/ArcGIS/services/")) {
            connection.setRequestProperty("Content-type", "text/xml, application/xml");
        }
    } else {
        connection.setRequestMethod("GET");
    }
    connection.setDoInput(true);
    if (tryGzip) {
        connection.addRequestProperty("Accept-Encoding", "gzip");
    }

    connection.setConnectTimeout(timeoutMillis);
    connection.setReadTimeout(timeoutMillis);

    // auth must be after connection because one branch makes the connection
    if (auth != null) {
        if (auth instanceof WFSAuthenticator) {
            WFSAuthenticator wfsAuth = (WFSAuthenticator) auth;
            String user = wfsAuth.pa.getUserName();
            char[] pass = wfsAuth.pa.getPassword();

            String combined = String.format("%s:%s", user, String.valueOf(pass));
            byte[] authBytes = combined.getBytes("US-ASCII");
            String encoded = new String(Base64.encodeBase64(authBytes));
            String authorization = "Basic " + encoded;
            connection.setRequestProperty("Authorization", authorization);
        } else {
            /*
             * FIXME this could breaks uDig. Not quite sure what to do otherwise.
             * Maybe have a mechanism that would allow an authenticator to ask the
             * datastore itself for a previously supplied user/pass.
             */
            synchronized (Authenticator.class) {
                Authenticator.setDefault(auth);
                connection.connect();
                //                Authenticator.setDefault(null);
            }
        }
    }

    return connection;
}

From source file:com.adaptris.core.http.JdkHttpProducer.java

@Override
protected AdaptrisMessage doRequest(AdaptrisMessage msg, ProduceDestination destination, long timeout)
        throws ProduceException {

    AdaptrisMessage reply = defaultIfNull(getMessageFactory()).newMessage();
    ThreadLocalCredentials threadLocalCreds = null;
    try {//from  w  ww . j  av  a2s.  com
        URL url = new URL(destination.getDestination(msg));
        if (getPasswordAuthentication() != null) {
            Authenticator.setDefault(AdapterResourceAuthenticator.getInstance());
            threadLocalCreds = ThreadLocalCredentials.getInstance(url.toString());
            threadLocalCreds.setThreadCredentials(getPasswordAuthentication());
            AdapterResourceAuthenticator.getInstance().addAuthenticator(threadLocalCreds);
        }
        HttpURLConnection http = (HttpURLConnection) url.openConnection();
        http.setRequestMethod(methodToUse(msg).name());
        http.setInstanceFollowRedirects(handleRedirection());
        http.setDoInput(true);
        http.setConnectTimeout(Long.valueOf(timeout).intValue());
        http.setReadTimeout(Long.valueOf(timeout).intValue());
        // ProxyUtil.applyBasicProxyAuthorisation(http);
        addHeaders(msg, http);
        if (getContentTypeKey() != null && msg.containsKey(getContentTypeKey())) {
            http.setRequestProperty(CONTENT_TYPE, msg.getMetadataValue(getContentTypeKey()));
        }
        // if (getAuthorisation() != null) {
        // http.setRequestProperty(AUTHORIZATION, getAuthorisation());
        // }
        // logHeaders("Request Information", "Request Method : " + http.getRequestMethod(), http.getRequestProperties().entrySet());
        sendMessage(msg, http);
        readResponse(http, reply);
        // logHeaders("Response Information", http.getResponseMessage(), http.getHeaderFields().entrySet());
    } catch (IOException e) {
        throw new ProduceException(e);
    } catch (CoreException e) {
        if (e instanceof ProduceException) {
            throw (ProduceException) e;
        } else {
            throw new ProduceException(e);
        }
    } finally {
        if (threadLocalCreds != null) {
            threadLocalCreds.removeThreadCredentials();
            AdapterResourceAuthenticator.getInstance().removeAuthenticator(threadLocalCreds);
        }
    }
    return reply;
}

From source file:com.freedomotic.helpers.HttpHelper.java

/**
 *
 * @return @throws IOException if the URL format is wrong or if cannot read
 * from source//  w  ww. j  a  v a  2 s. c o  m
 */
private String doGet(String url, String username, String password) throws IOException {

    Authenticator.setDefault(new MyAuthenticator(username, password));

    DefaultHttpClient client = new DefaultHttpClient(httpParams);
    String decodedUrl;
    HttpGet request = null;
    try {
        decodedUrl = URLDecoder.decode(url, "UTF-8");
        request = new HttpGet(new URL(decodedUrl).toURI());
    } catch (URISyntaxException | MalformedURLException ex) {
        throw new IOException("The URL " + url + "' is not properly formatted: " + ex.getMessage(), ex);
    }
    HttpResponse response = client.execute(request);

    Reader reader = null;
    try {
        reader = new InputStreamReader(response.getEntity().getContent());

        StringBuilder buffer = new StringBuilder();
        int read;
        char[] cbuf = new char[1024];
        while ((read = reader.read(cbuf)) != -1) {
            buffer.append(cbuf, 0, read);
        }
        return buffer.toString();

    } finally {
        IOUtils.closeQuietly(reader);
    }
}

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

private static void search(String nexusUrl, final String userName, final String password, String repositoryId,
        String groupIdToSearch, String artifactId, String versionToSearch, int searchFrom, int searchCount,
        List<MavenArtifact> artifacts) throws Exception {
    HttpURLConnection urlConnection = null;
    int totalCount = 0;
    final Authenticator defaultAuthenticator = NetworkUtil.getDefaultAuthenticator();
    if (userName != null && !"".equals(userName)) {
        Authenticator.setDefault(new Authenticator() {

            @Override/*from   w w w  .  j a  v a2 s. com*/
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password.toCharArray());
            }

        });
    }
    try {
        String service = NexusConstants.SERVICES_SEARCH + getSearchQuery(repositoryId, groupIdToSearch,
                artifactId, versionToSearch, searchFrom, searchCount);
        urlConnection = getHttpURLConnection(nexusUrl, service, userName, password);
        SAXReader saxReader = new SAXReader();

        InputStream inputStream = urlConnection.getInputStream();
        Document document = saxReader.read(inputStream);
        // test
        // writeDocument(document, new File("D:/search.txt"));
        Node countNode = document.selectSingleNode("/searchNGResponse/totalCount");
        if (countNode != null) {
            try {
                totalCount = Integer.parseInt(countNode.getText());
            } catch (NumberFormatException e) {
                totalCount = 0;
            }
        }

        List<Node> list = document.selectNodes("/searchNGResponse/data/artifact");//$NON-NLS-1$ 
        for (Node arNode : list) {
            MavenArtifact artifact = new MavenArtifact();
            artifacts.add(artifact);
            artifact.setGroupId(arNode.selectSingleNode("groupId").getText());//$NON-NLS-1$ 
            artifact.setArtifactId(arNode.selectSingleNode("artifactId").getText());//$NON-NLS-1$ 
            artifact.setVersion(arNode.selectSingleNode("version").getText());//$NON-NLS-1$ 
            Node descNode = arNode.selectSingleNode("description");//$NON-NLS-1$ 
            if (descNode != null) {
                artifact.setDescription(descNode.getText());
            }
            Node urlNode = arNode.selectSingleNode("url");//$NON-NLS-1$ 
            if (urlNode != null) {
                artifact.setUrl(urlNode.getText());
            }
            Node licenseNode = arNode.selectSingleNode("license");//$NON-NLS-1$ 
            if (licenseNode != null) {
                artifact.setLicense(licenseNode.getText());
            }

            Node licenseUrlNode = arNode.selectSingleNode("licenseUrl");//$NON-NLS-1$ 
            if (licenseUrlNode != null) {
                artifact.setLicenseUrl(licenseUrlNode.getText());
            }

            List<Node> artLinks = arNode.selectNodes("artifactHits/artifactHit/artifactLinks/artifactLink");//$NON-NLS-1$ 
            for (Node link : artLinks) {
                Node extensionElement = link.selectSingleNode("extension");//$NON-NLS-1$ 
                String extension = null;
                String classifier = null;
                if (extensionElement != null) {
                    if ("pom".equals(extensionElement.getText())) {//$NON-NLS-1$ 
                        continue;
                    }
                    extension = extensionElement.getText();
                }
                Node classifierElement = link.selectSingleNode("classifier");//$NON-NLS-1$ 
                if (classifierElement != null) {
                    classifier = classifierElement.getText();
                }
                artifact.setType(extension);
                artifact.setClassifier(classifier);
            }
        }
        int searchDone = searchFrom + searchCount;
        int count = MAX_SEARCH_COUNT;
        if (searchDone < totalCount) {
            if (totalCount - searchDone < MAX_SEARCH_COUNT) {
                count = totalCount - searchDone;
            }
            search(nexusUrl, userName, password, repositoryId, groupIdToSearch, artifactId, versionToSearch,
                    searchDone + 1, count, artifacts);
        }

    } finally {
        Authenticator.setDefault(defaultAuthenticator);
        if (null != urlConnection) {
            urlConnection.disconnect();
        }
    }
}

From source file:sce.RESTAppMetricJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    Connection conn = null;/*from   w w w .  java 2  s . c  o m*/
    try {
        String url1 = prop.getProperty("kb_url");
        //required parameters #url
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String callUrl = jobDataMap.getString("#url"); // url to call when passing result data from SPARQL query
        if (callUrl == null) {
            throw new JobExecutionException("#url parameter must be not null");
        }
        String timeout = jobDataMap.getString("#timeout"); // timeout in ms to use when calling the #url
        if (timeout == null) {
            timeout = "5000";
        }

        //first SPARQL query to retrieve application related metrics and business configurations
        String url = url1 + "?query=" + URLEncoder.encode(getSPARQLQuery(), "UTF-8");
        URL u = new URL(url);
        final String usernamePassword = u.getUserInfo();
        if (usernamePassword != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(usernamePassword.split(":")[0],
                            usernamePassword.split(":")[1].toCharArray());
                }
            });
        }
        this.urlConnection = u.openConnection();
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json");
        HashMap<String, Object> res = new ObjectMapper().readValue(urlConnection.getInputStream(),
                HashMap.class);
        HashMap<String, Object> r = (HashMap<String, Object>) res.get("results");
        ArrayList<Object> list = (ArrayList<Object>) r.get("bindings");
        ArrayList<String[]> lst = new ArrayList<>();
        for (Object obj : list) {
            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value");
            String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value");
            lst.add(new String[] { mn, bc });
        }

        //second SPARQL query to retrieve alerts for SLA
        url = url1 + "?query=" + URLEncoder.encode(getValuesForMetrics(lst), "UTF-8");
        u = new URL(url);
        //java.io.FileWriter fstream = new java.io.FileWriter("/var/www/html/sce/log.txt", false);
        //java.io.BufferedWriter out = new java.io.BufferedWriter(fstream);
        //out.write(getAlertsForSLA(lst, slaTimestamp));
        //out.close();
        this.urlConnection = u.openConnection();
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json");

        //format the result
        HashMap<String, Object> alerts = new ObjectMapper().readValue(urlConnection.getInputStream(),
                HashMap.class);
        HashMap<String, Object> r1 = (HashMap<String, Object>) alerts.get("results");
        ArrayList<Object> list1 = (ArrayList<Object>) r1.get("bindings");
        String result = "";

        //MYSQL CONNECTION
        conn = Main.getConnection();
        // conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); // use for transactions and at the end call conn.commit() conn.close()
        int counter = 0;

        //SET timestamp FOR MYSQL ROW
        Date dt = new java.util.Date();
        SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = sdf.format(dt);

        // JSON to be sent to the SM
        JSONArray jsonArray = new JSONArray();

        for (Object obj : list1) {
            //JSON to insert into database
            //JSONArray jsonArray = new JSONArray();
            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value"); //metric
            String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value"); //metric_name
            String mu = (String) ((HashMap<String, Object>) o.get("mu")).get("value"); //metric_unit
            String v = (String) ((HashMap<String, Object>) o.get("v")).get("value"); //value
            String mt = (String) ((HashMap<String, Object>) o.get("mt")).get("value"); //metric_timestamp
            String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value"); //business_configuration

            // add these metric value to the json array
            JSONObject object = new JSONObject();
            object.put("business_configuration", bc);
            object.put("metric", sm);
            object.put("metric_name", mn);
            object.put("metric_unit", mu);
            object.put("value", v);
            object.put("metric_timestamp", mt);
            jsonArray.add(object);

            //INSERT THE DATA INTO DATABASE
            PreparedStatement preparedStatement = conn.prepareStatement(
                    "INSERT INTO quartz.QRTZ_APP_METRICS (timestamp, metric, metric_name, metric_unit, value, metric_timestamp, business_configuration) VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE timestamp=?");
            preparedStatement.setString(1, timestamp); // date
            preparedStatement.setString(2, sm); // metric
            preparedStatement.setString(3, mn); // metric_name
            preparedStatement.setString(4, mu); // metric_unit
            preparedStatement.setString(5, v); // value
            preparedStatement.setString(6, mt); // metric_timestamp (e.g., 2014-12-01T16:14:00)
            preparedStatement.setString(7, bc); // business_configuration 
            preparedStatement.setString(8, timestamp); // date
            preparedStatement.executeUpdate();
            preparedStatement.close();

            result += "\nService Metric: " + sm + "\n";
            result += "\nMetric Name: " + mn + "\n";
            result += "\nMetric Unit: " + mu + "\n";
            result += "Timestamp: " + mt + "\n";
            result += "Business Configuration: " + bc + "\n";
            result += "Value" + (counter + 1) + ": " + v + "\n";
            result += "Call Url: " + callUrl + "\n";

            counter++;
        }

        // send the JSON to the CM
        URL tmp_u = new URL(callUrl);
        final String usr_pwd = tmp_u.getUserInfo();
        String usr = null;
        String pwd = null;
        if (usr_pwd != null) {
            usr = usr_pwd.split(":")[0];
            pwd = usr_pwd.split(":")[1];
        }
        sendPostRequest(jsonArray.toJSONString(), callUrl, usr, pwd, Integer.parseInt(timeout));

        //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 (jobDataMap.containsKey("#notificationEmail")) {
            sendEmail(context, jobDataMap.getString("#notificationEmail"));
        }
        jobChain(context);
    } catch (MalformedURLException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (IOException | SQLException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (!conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:es.gva.cit.catalog.DiscoveryServiceClient.java

/**
 * It tries if the server is ready/*from  w  w w .j a  v a  2 s  .  com*/
 * 
 * @return boolean true --> server is ready false --> server is not ready
 */
public boolean serverIsReady() throws ServerIsNotReadyException {
    Properties systemSettings = System.getProperties();

    Object isProxyEnabled = systemSettings.get("http.proxySet");
    if ((isProxyEnabled == null) || (isProxyEnabled.equals("false"))) {
        Socket sock;
        try {
            sock = new Socket(getUri().getHost(), getUri().getPort());
        } catch (UnknownHostException e) {
            throw new ServerIsNotReadyException(e);
        } catch (IOException e) {
            throw new ServerIsNotReadyException(e);
        }
        return (sock != null);
    } else {
        Object host = systemSettings.get("http.proxyHost");
        Object port = systemSettings.get("http.proxyPort");
        Object user = systemSettings.get("http.proxyUserName");
        Object password = systemSettings.get("http.proxyPassword");
        if ((host != null) && (port != null)) {
            int iPort = 80;
            try {
                iPort = Integer.parseInt((String) port);
            } catch (Exception e) {
                // Use 80
            }
            HttpConnection connection = new HttpConnection(getUri().getHost(), getUri().getPort());
            connection.setProxyHost((String) host);
            connection.setProxyPort(iPort);
            Authenticator.setDefault(new SimpleAuthenticator(user, password));

            try {
                connection.open();
                connection.close();
            } catch (IOException e) {
                throw new ServerIsNotReadyException(e);
            }
        }
    }
    return true;
}

From source file:org.nuxeo.ecm.core.storage.sql.JCloudsBinaryManager.java

@Override
public void initialize(BinaryManagerDescriptor binaryManagerDescriptor) throws IOException {
    super.initialize(binaryManagerDescriptor);

    // Get settings from the configuration
    storeProvider = Framework.getProperty(BLOBSTORE_PROVIDER_KEY);
    if (isBlank(storeProvider)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_PROVIDER_KEY);
    }//from   w  ww  .  j a  v  a2 s . com
    container = Framework.getProperty(BLOBSTORE_MAP_NAME_KEY);
    if (isBlank(container)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_MAP_NAME_KEY);
    }

    String storeLocation = Framework.getProperty(BLOBSTORE_LOCATION_KEY);
    if (isBlank(storeLocation)) {
        storeLocation = null;
    }

    String storeIdentity = Framework.getProperty(BLOBSTORE_IDENTITY_KEY);
    if (isBlank(storeIdentity)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_IDENTITY_KEY);
    }

    String storeSecret = Framework.getProperty(BLOBSTORE_SECRET_KEY);
    if (isBlank(storeSecret)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_SECRET_KEY);
    }

    String cacheSizeStr = Framework.getProperty(CACHE_SIZE_KEY);
    if (isBlank(cacheSizeStr)) {
        cacheSizeStr = DEFAULT_CACHE_SIZE;
    }

    String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST);
    String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT);
    final String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN);
    final String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD);

    // Set up proxy
    if (isNotBlank(proxyHost)) {
        System.setProperty("https.proxyHost", proxyHost);
    }
    if (isNotBlank(proxyPort)) {
        System.setProperty("https.proxyPort", proxyPort);
    }
    if (isNotBlank(proxyLogin)) {
        System.setProperty("https.proxyUser", proxyLogin);
        System.setProperty("https.proxyPassword", proxyPassword);
        Authenticator.setDefault(new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyLogin, proxyPassword.toCharArray());
            }
        });
    }

    BlobStoreContext context = ContextBuilder.newBuilder(storeProvider).credentials(storeIdentity, storeSecret)
            .buildView(BlobStoreContext.class);

    // Try to create container if it doesn't exist
    blobStore = context.getBlobStore();
    boolean created = false;
    if (storeLocation == null) {
        created = blobStore.createContainerInLocation(null, container);
    } else {
        Location location = new LocationBuilder().scope(LocationScope.REGION).id(storeLocation)
                .description(storeLocation).build();
        created = blobStore.createContainerInLocation(location, container);
    }
    if (created) {
        log.debug("Created container " + container);
    }

    // Create file cache
    initializeCache(cacheSizeStr, new JCloudsFileStorage());
    createGarbageCollector();
}