Example usage for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory

List of usage examples for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory.

Prototype

public static void setDefaultSSLSocketFactory(SSLSocketFactory sf) 

Source Link

Document

Sets the default SSLSocketFactory inherited by new instances of this class.

Usage

From source file:org.gluu.oxtrust.ldap.service.StatusCheckerTimer.java

private String getHttpdPage(String idpUrl, String httpdTestPageName) {
    String[] urlParts = idpUrl.split("://");
    if ("https".equals(urlParts[0])) {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }// w ww . j  av a  2s.  c  o  m

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
        }
    }

    StringBuilder sb = new StringBuilder();
    // Now you can access an https URL without having the certificate in the
    // truststore
    try {
        String[] hostAndPort = urlParts[1].split(":");
        URL url = null;
        if (hostAndPort.length < 2) {
            url = new URL(urlParts[0], hostAndPort[0], httpdTestPageName);
        } else {
            url = new URL(urlParts[0], hostAndPort[0], Integer.parseInt(hostAndPort[1]), httpdTestPageName);
        }
        InputStream in = url.openConnection().getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        in.close();

    } catch (Exception e) {
        // log.error("Failed to get test page: ", e);
    }
    return sb.toString();
}

From source file:io.fabric8.apiman.ApimanStarter.java

private static URL waitForDependency(URL url, String path, String serviceName, String key, String value,
        String username, String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;/*  w  w  w  .ja  v a 2 s  . com*/
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + path);
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(ApimanStarter.TRUSTSTORE_PATH,
                                ApimanStarter.TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(
                                ApimanStarter.CLIENT_KEYSTORE_PATH,
                                ApimanStarter.CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                    log.info(username + ":" + "*****");
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up. " + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. " + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}

From source file:com.curso.listadapter.net.RESTClient.java

/**
 * this method utoacepts all certificates in httpsurlconections
 * */// w w  w  .  j  a  va  2s .c o  m
@SuppressLint("TrulyRandom")
private static void disableSSLCertificateChecking() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }
    } };
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

From source file:com.sitewhere.wso2.identity.scim.Wso2ScimAssetModule.java

protected SSLContext createContext() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*w  ww. j a  v a2  s.  c o  m*/

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return sc;

    } catch (Exception e) {
    }
    return null;
}

From source file:org.skt.runtime.html5apis.file.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP multipart request.
 * @param source        Full path of the file on the file system
 * @param target        URL of the server to receive the file
 * @param args          JSON Array of args
 *
 * args[2] fileKey       Name of file request parameter
 * args[3] fileName      File name to be used on server
 * args[4] mimeType      Describes file content type
 * args[5] params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 *//*from www .  jav a 2s.  c  om*/
private PluginResult upload(String source, String target, JSONArray args) {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    HttpURLConnection conn = null;
    try {
        // Setup the options
        String fileKey = getArgument(args, 2, "file");
        String fileName = getArgument(args, 3, "image.jpg");
        String mimeType = getArgument(args, 4, "image/jpeg");
        JSONObject params = args.optJSONObject(5);
        if (params == null) {
            params = new JSONObject();
        }
        boolean trustEveryone = args.optBoolean(6);
        boolean chunkedMode = args.optBoolean(7) || args.isNull(7); //Always use chunked mode unless set to false as per API

        Log.d(LOG_TAG, "fileKey: " + fileKey);
        Log.d(LOG_TAG, "fileName: " + fileName);
        Log.d(LOG_TAG, "mimeType: " + mimeType);
        Log.d(LOG_TAG, "params: " + params);
        Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
        Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);

        // Create return object
        FileUploadResult result = new FileUploadResult();

        // Get a input stream of the file on the phone
        FileInputStream fileInputStream = (FileInputStream) getPathFromUri(source);

        DataOutputStream dos = null;

        int bytesRead, bytesAvailable, bufferSize;
        long totalBytes;
        byte[] buffer;
        int maxBufferSize = 8096;

        //------------------ CLIENT REQUEST
        // open a URL connection to the server
        URL url = new URL(target);

        // Open a HTTP connection to the URL based on protocol
        if (url.getProtocol().toLowerCase().equals("https")) {
            // Using standard HTTPS connection. Will not allow self signed certificate
            if (!trustEveryone) {
                conn = (HttpsURLConnection) url.openConnection();
            }
            // Use our HTTPS connection that blindly trusts everyone.
            // This should only be used in debug environments
            else {
                // Setup the HTTPS connection class to trust everyone
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                // Save the current hostnameVerifier
                defaultHostnameVerifier = https.getHostnameVerifier();
                // Setup the connection not to verify hostnames
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            }
        }
        // Return a standard HTTP connection
        else {
            conn = (HttpURLConnection) url.openConnection();
        }

        // Allow Inputs
        conn.setDoInput(true);

        // Allow Outputs
        conn.setDoOutput(true);

        // Don't use a cached copy.
        conn.setUseCaches(false);

        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        // Handle the other headers
        try {
            JSONObject headers = params.getJSONObject("headers");
            for (Iterator iter = headers.keys(); iter.hasNext();) {
                String headerKey = iter.next().toString();
                conn.setRequestProperty(headerKey, headers.getString(headerKey));
            }
        } catch (JSONException e1) {
            // No headers to be manipulated!
        }

        // Set the cookies on the response
        String cookie = CookieManager.getInstance().getCookie(target);
        if (cookie != null) {
            conn.setRequestProperty("Cookie", cookie);
        }

        /*
        * Store the non-file portions of the multipart data as a string, so that we can add it
        * to the contentSize, since it is part of the body of the HTTP request.
        */
        String extraParams = "";
        try {
            for (Iterator iter = params.keys(); iter.hasNext();) {
                Object key = iter.next();
                if (!String.valueOf(key).equals("headers")) {
                    extraParams += LINE_START + BOUNDARY + LINE_END;
                    extraParams += "Content-Disposition: form-data; name=\"" + key.toString() + "\";";
                    extraParams += LINE_END + LINE_END;
                    extraParams += params.getString(key.toString());
                    extraParams += LINE_END;
                }
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }

        extraParams += LINE_START + BOUNDARY + LINE_END;
        extraParams += "Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"";

        String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END;
        String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;

        // Should set this up as an option
        if (chunkedMode) {
            conn.setChunkedStreamingMode(maxBufferSize);
        } else {
            int stringLength = extraParams.getBytes("UTF-8").length + midParams.getBytes("UTF-8").length
                    + tailParams.getBytes("UTF-8").length + fileName.getBytes("UTF-8").length;
            Log.d(LOG_TAG, "String Length: " + stringLength);
            int fixedLength = (int) fileInputStream.getChannel().size() + stringLength;
            Log.d(LOG_TAG, "Content Length: " + fixedLength);
            conn.setFixedLengthStreamingMode(fixedLength);
        }

        dos = new DataOutputStream(conn.getOutputStream());
        dos.write(extraParams.getBytes("UTF-8"));
        //We don't want to chagne encoding, we just want this to write for all Unicode.
        dos.write(fileName.getBytes("UTF-8"));
        dos.write(midParams.getBytes("UTF-8"));

        // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        totalBytes = 0;

        while (bytesRead > 0) {
            totalBytes += bytesRead;
            result.setBytesSent(totalBytes);
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.write(tailParams.getBytes("UTF-8"));

        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();

        //------------------ read the SERVER RESPONSE
        StringBuffer responseString = new StringBuffer("");
        DataInputStream inStream;
        try {
            inStream = new DataInputStream(conn.getInputStream());
        } catch (FileNotFoundException e) {
            Log.e(LOG_TAG, e.toString(), e);
            throw new IOException("Received error from server");
        }

        String line;
        while ((line = inStream.readLine()) != null) {
            responseString.append(line);
        }
        Log.d(LOG_TAG, "got response from server");
        Log.d(LOG_TAG, responseString.toString());

        // send request and retrieve response
        result.setResponseCode(conn.getResponseCode());
        result.setResponse(responseString.toString());

        inStream.close();

        // Revert back to the proper verifier and socket factories
        if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
            ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
        }

        Log.d(LOG_TAG, "****** About to return a result from upload");
        return new PluginResult(PluginResult.Status.OK, result.toJSONObject());

    } catch (FileNotFoundException e) {
        JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (MalformedURLException e) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (IOException e) {
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    } catch (Throwable t) {
        // Shouldn't happen, but will
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        Log.wtf(LOG_TAG, error.toString(), t);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:org.kurento.test.base.BrowserTest.java

public void waitForHostIsReachable(URL url, int timeout) {
    long timeoutMillis = TimeUnit.MILLISECONDS.convert(timeout, TimeUnit.SECONDS);
    long endTimeMillis = System.currentTimeMillis() + timeoutMillis;

    log.debug("Waiting for {} to be reachable (timeout {} seconds)", url, timeout);

    try {//  w  ww. j a  v  a  2s  .  c  o m
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        HostnameVerifier allHostsValid = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        int responseCode = 0;
        while (true) {
            try {
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout((int) timeoutMillis);
                connection.setReadTimeout((int) timeoutMillis);
                connection.setRequestMethod("HEAD");
                responseCode = connection.getResponseCode();

                break;
            } catch (SSLHandshakeException | SocketException e) {
                log.warn("Error {} waiting URL {}, trying again in 1 second", e.getMessage(), url);
                // Polling to wait a consistent SSL state
                Thread.sleep(1000);
            }
            if (System.currentTimeMillis() > endTimeMillis) {
                break;
            }
        }

        if (responseCode != HttpURLConnection.HTTP_OK) {
            log.warn("URL " + url + " not reachable. Response code=" + responseCode);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("URL " + url + " not reachable in " + timeout + " seconds (" + e.getClass().getName() + ", "
                + e.getMessage() + ")");
    }

    log.debug("URL {} already reachable", url);
}

From source file:com.flexvdi.androidlauncher.LoginActivity.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    mContext = this;

    try {//from  w w  w  .  ja  v  a  2  s.  c o  m
        GStreamer.init(mContext);
    } catch (Exception e) {
        Log.e(TAG, "Can't initialize GStreamer" + e.getMessage());
        finish();
    }

    settings = getSharedPreferences("flexVDI", MODE_PRIVATE);
    settingsEditor = settings.edit();
    /* Uncomment this for clearing preferences (useful when debugging) */
    //settingsEditor.clear();
    //settingsEditor.apply();
    //settingsEditor.commit();

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.activity_login);

    textUser = (EditText) findViewById(R.id.textUser);
    textServer = (EditText) findViewById(R.id.textServer);
    textPassword = (EditText) findViewById(R.id.textPassword);

    goButton = (Button) findViewById(R.id.buttonGO);
    goButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ConnectivityManager cm = (ConnectivityManager) mContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

            if (!isConnected) {
                Toast.makeText(view.getContext(), getResources().getString(R.string.no_network),
                        Toast.LENGTH_LONG).show();
                return;
            }

            if (checkBoxGenericSpice.isChecked()) {
                String userField = textUser.getText().toString();
                if (userField.length() == 0 || !userField.contains(":")) {
                    Toast.makeText(view.getContext(), getResources().getString(R.string.invalid_spice_server),
                            Toast.LENGTH_LONG).show();
                    return;
                }

                String spiceAddress = userField.substring(0, userField.indexOf(":"));
                String spicePort = userField.substring(userField.indexOf(":") + 1);

                if (spiceAddress.length() == 0 || spicePort.length() == 0) {
                    Toast.makeText(view.getContext(), getResources().getString(R.string.invalid_spice_server),
                            Toast.LENGTH_LONG).show();
                    return;
                }

                String spicePassword = textPassword.getText().toString();

                settingsEditor.putBoolean("enableSound", checkBoxEnableSound.isChecked());
                settingsEditor.putBoolean("staticResolution", checkBoxStaticResolution.isChecked());
                settingsEditor.putBoolean("genericSpice", checkBoxGenericSpice.isChecked());
                settingsEditor.putString("flexServerName", textServer.getText().toString());

                settingsEditor.putString("spice_address", spiceAddress);
                settingsEditor.putString("spice_port", spicePort);
                settingsEditor.putString("spice_password", spicePassword);
                settingsEditor.putBoolean("use_ws", false);

                settingsEditor.apply();
                settingsEditor.commit();

                startMainActivity();
            } else {
                if (textServer.getText().length() == 0) {
                    Toast.makeText(view.getContext(), getResources().getString(R.string.empty_flexvdi_server),
                            Toast.LENGTH_LONG).show();
                } else {
                    if (textUser.getText().length() != 0 && textPassword.getText().length() != 0) {
                        new RequestTask().execute("authmode", textServer.getText().toString(),
                                textUser.getText().toString(), textPassword.getText().toString(), "");
                    } else
                        Toast.makeText(view.getContext(), getResources().getString(R.string.empty_credentials),
                                Toast.LENGTH_LONG).show();
                }
            }
        }
    });

    // The advanced settings button.
    checkBoxAdvancedOptions = (CheckBox) findViewById(R.id.checkBoxAdvancedSettings);
    layoutAdvancedOptions = (LinearLayout) findViewById(R.id.layoutAdvancedOptions2);
    checkBoxAdvancedOptions.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            if (checked)
                layoutAdvancedOptions.setVisibility(View.VISIBLE);
            else
                layoutAdvancedOptions.setVisibility(View.GONE);
        }
    });

    textServer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View field, boolean hasFocus) {
            if (!hasFocus && checkBoxGenericSpice.isChecked()) {
                if (textUser.getText().toString().length() == 0) {
                    textUser.setText(textServer.getText());
                }
            }
        }
    });

    checkBoxEnableSound = (CheckBox) findViewById(R.id.checkBoxEnableSound);
    if (settings.getBoolean("enableSound", true)) {
        checkBoxEnableSound.setChecked(true);
    } else {
        checkBoxEnableSound.setChecked(false);
    }

    if (!settings.contains("staticResolution")) {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        if ((size.x + size.y) > 2340) {
            /* 2340 = 1440+900 */
            settingsEditor.putBoolean("staticResolution", true);
        } else {
            settingsEditor.putBoolean("staticResolution", false);
        }
        settingsEditor.apply();
        settingsEditor.commit();
    }

    checkBoxStaticResolution = (CheckBox) findViewById(R.id.checkBoxStaticResolution);
    if (settings.getBoolean("staticResolution", true)) {
        checkBoxStaticResolution.setChecked(true);
    } else {
        checkBoxStaticResolution.setChecked(false);
    }

    checkBoxGenericSpice = (CheckBox) findViewById(R.id.checkBoxGenericSpice);
    if (settings.getBoolean("genericSpice", false)) {
        checkBoxGenericSpice.setChecked(true);
        checkBoxAdvancedOptions.setChecked(true);
        layoutAdvancedOptions.setVisibility(View.VISIBLE);

        if (settings.contains("flexServerName")) {
            textServer.setText(settings.getString("flexServerName", ""));
            textUser.setText(settings.getString("flexServerName", ""));
            textServer.setHint(getResources().getString(R.string.spice_server));
            textUser.setHint(getResources().getString(R.string.spice_server_port));
        }
    } else {
        checkBoxGenericSpice.setChecked(false);
        if (settings.contains("flexServerName")) {
            textServer.setText(settings.getString("flexServerName", ""));
            layoutAdvancedOptions.setVisibility(View.GONE);
        } else {
            textServer.setText("manager.flexvdi.com");
            checkBoxAdvancedOptions.setChecked(true);
        }
    }

    checkBoxGenericSpice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            if (checked) {
                textServer.setHint(getResources().getString(R.string.spice_server));
                textUser.setHint(getResources().getString(R.string.spice_server_port));
                String server = textServer.getText().toString();
                if (server.length() != 0) {
                    if (server.contains(":")) {
                        textUser.setText(server);
                    } else {
                        textUser.setText(server + ":5900");
                        textServer.setText(server + ":5900");
                    }
                }
            } else {
                textServer.setHint(getResources().getString(R.string.flexvdi_server));
                String server = textServer.getText().toString();
                if (server.length() != 0 && server.contains(":")) {
                    textServer.setText(server.substring(0, server.indexOf(":")));
                }
                textUser.setText("");
                textUser.setHint(getResources().getString(R.string.user));
            }
        }
    });

    deviceID = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);

    textViewDeviceID = (TextView) findViewById(R.id.textViewDeviceID);
    textViewDeviceID.setText("ID: " + deviceID + " (" + BuildConfig.VERSION_NAME + ")");

    try {
        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[] { new NullX509TrustManager() }, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    } catch (NoSuchAlgorithmException nsae) {
        Log.e(TAG, nsae.getMessage());
    } catch (KeyManagementException kme) {
        Log.e(TAG, kme.getMessage());
    }
}

From source file:com.phonegap.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP 
 * multipart request. //  w w w  . j a v  a 2s  . c  o m
 * @param file      Full path of the file on the file system
 * @param server        URL of the server to receive the file
 * @param fileKey       Name of file request parameter
 * @param fileName      File name to be used on server
 * @param mimeType      Describes file content type
 * @param params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 */
public FileUploadResult upload(String file, String server, final String fileKey, final String fileName,
        final String mimeType, JSONObject params, boolean trustEveryone) throws IOException, SSLException {
    // Create return object
    FileUploadResult result = new FileUploadResult();

    // Get a input stream of the file on the phone
    InputStream fileInputStream = getPathFromUri(file);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    int bytesRead, bytesAvailable, bufferSize;
    long totalBytes;
    byte[] buffer;
    int maxBufferSize = 8096;

    //------------------ CLIENT REQUEST
    // open a URL connection to the server 
    URL url = new URL(server);

    // Open a HTTP connection to the URL based on protocol 
    if (url.getProtocol().toLowerCase().equals("https")) {
        // Using standard HTTPS connection. Will not allow self signed certificate
        if (!trustEveryone) {
            conn = (HttpsURLConnection) url.openConnection();
        }
        // Use our HTTPS connection that blindly trusts everyone.
        // This should only be used in debug environments
        else {
            // Setup the HTTPS connection class to trust everyone
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            // Save the current hostnameVerifier
            defaultHostnameVerifier = https.getHostnameVerifier();
            // Setup the connection not to verify hostnames 
            https.setHostnameVerifier(DO_NOT_VERIFY);
            conn = https;
        }
    }
    // Return a standard HTTP conneciton
    else {
        conn = (HttpURLConnection) url.openConnection();
    }

    // Allow Inputs
    conn.setDoInput(true);

    // Allow Outputs
    conn.setDoOutput(true);

    // Don't use a cached copy.
    conn.setUseCaches(false);

    // Use a post method.
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDRY);

    // Set the cookies on the response
    String cookie = CookieManager.getInstance().getCookie(server);
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    // Send any extra parameters
    try {
        for (Iterator iter = params.keys(); iter.hasNext();) {
            Object key = iter.next();
            dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + key.toString() + "\"; ");
            dos.writeBytes(LINE_END + LINE_END);
            dos.writeBytes(params.getString(key.toString()));
            dos.writeBytes(LINE_END);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }

    dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
    dos.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"" + fileName
            + "\"" + LINE_END);
    dos.writeBytes("Content-Type: " + mimeType + LINE_END);
    dos.writeBytes(LINE_END);

    // create a buffer of maximum size
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // read file and write it into form...
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    totalBytes = 0;

    while (bytesRead > 0) {
        totalBytes += bytesRead;
        result.setBytesSent(totalBytes);
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    // send multipart form data necesssary after file data...
    dos.writeBytes(LINE_END);
    dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END);

    // close streams
    fileInputStream.close();
    dos.flush();
    dos.close();

    //------------------ read the SERVER RESPONSE
    StringBuffer responseString = new StringBuffer("");
    DataInputStream inStream = new DataInputStream(conn.getInputStream());
    String line;
    while ((line = inStream.readLine()) != null) {
        responseString.append(line);
    }
    Log.d(LOG_TAG, "got response from server");
    Log.d(LOG_TAG, responseString.toString());

    // send request and retrieve response
    result.setResponseCode(conn.getResponseCode());
    result.setResponse(responseString.toString());

    inStream.close();
    conn.disconnect();

    // Revert back to the proper verifier and socket factories
    if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
        ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
        HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
    }

    return result;
}

From source file:com.createtank.payments.coinbase.RequestClient.java

public static void disableCertificateValidation() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }/*  ww  w.  j a  v  a 2s.  co m*/

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {
        //Ignore
    }
}

From source file:org.opennms.protocols.vmware.VmwareConfigBuilder.java

public static void main(String[] args) throws ParseException {
    String hostname = null;//from w  ww  .ja  v  a2s.c  om
    String username = null;
    String password = null;
    String rrdRepository = null;

    final Options options = new Options();

    options.addOption("rrdRepository", true,
            "set rrdRepository path for generated config files, default: '/opt/opennms/share/rrd/snmp/'");

    final CommandLineParser parser = new PosixParser();
    final CommandLine cmd = parser.parse(options, args);

    @SuppressWarnings("unchecked")
    List<String> arguments = (List<String>) cmd.getArgList();

    if (arguments.size() < 3) {
        usage(options, cmd);
        System.exit(1);
    }

    hostname = arguments.remove(0);
    username = arguments.remove(0);
    password = arguments.remove(0);

    if (cmd.hasOption("rrdRepository")) {
        rrdRepository = cmd.getOptionValue("rrdRepository");
    } else {
        rrdRepository = "/opt/opennms/share/rrd/snmp/";
    }

    TrustManager[] trustAllCerts = new TrustManager[1];

    trustAllCerts[0] = new TrustAllManager();

    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };

    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    VmwareConfigBuilder vmwareConfigBuilder;

    vmwareConfigBuilder = new VmwareConfigBuilder(hostname, username, password);

    try {
        vmwareConfigBuilder.generateData(rrdRepository);
    } catch (Exception e) {
        e.printStackTrace();
    }
}