Example usage for javax.net.ssl HttpsURLConnection disconnect

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

Introduction

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

Prototype

public abstract void disconnect();

Source Link

Document

Indicates that other requests to the server are unlikely in the near future.

Usage

From source file:com.carvoyant.modularinput.Program.java

private JSONObject getRefreshToken(EventWriter ew, String clientId, String clientSecret, String refreshToken) {
    JSONObject tokenJson = null;/*from   ww  w . j  a v a2s .  c o m*/
    HttpsURLConnection getTokenConnection = null;

    try {
        BufferedReader tokenResponseReader = null;
        URL url = new URL("https://api.carvoyant.com/oauth/token");
        //         URL url = new URL("https://sandbox-api.carvoyant.com/sandbox/oauth/token");
        getTokenConnection = (HttpsURLConnection) url.openConnection();
        getTokenConnection.setReadTimeout(30000);
        getTokenConnection.setConnectTimeout(30000);
        getTokenConnection.setRequestMethod("POST");
        getTokenConnection.setDoInput(true);
        getTokenConnection.setDoOutput(true);

        List<SimpleEntry> getTokenParams = new ArrayList<SimpleEntry>();
        getTokenParams.add(new SimpleEntry("client_id", clientId));
        getTokenParams.add(new SimpleEntry("client_secret", clientSecret));
        getTokenParams.add(new SimpleEntry("grant_type", "refresh_token"));
        getTokenParams.add(new SimpleEntry("refresh_token", refreshToken));

        String userpass = clientId + ":" + clientSecret;
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

        getTokenConnection.setRequestProperty("Authorization", basicAuth);

        OutputStream os = getTokenConnection.getOutputStream();
        os.write(getQuery(getTokenParams).getBytes("UTF-8"));
        os.close();

        if (getTokenConnection.getResponseCode() < 400) {
            tokenResponseReader = new BufferedReader(
                    new InputStreamReader(getTokenConnection.getInputStream()));
            String inputLine;
            StringBuffer sb = new StringBuffer();
            while ((inputLine = tokenResponseReader.readLine()) != null) {
                sb.append(inputLine);
            }

            tokenJson = new JSONObject(sb.toString());
            ew.synchronizedLog(EventWriter.INFO, "Refreshed Carvoyant access token.");
        } else {
            tokenResponseReader = new BufferedReader(
                    new InputStreamReader(getTokenConnection.getErrorStream()));
            StringBuffer sb = new StringBuffer();
            String inputLine;
            while ((inputLine = tokenResponseReader.readLine()) != null) {
                sb.append(inputLine);
            }
            ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error. CLIENT_ID:" + clientId
                    + ", REFRESH_TOKEN:" + refreshToken + ",ERROR_MSG: " + sb.toString());
        }

        getTokenConnection.disconnect();
    } catch (MalformedURLException mue) {
        ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + mue.getMessage());
    } catch (IOException ioe) {
        ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + ioe.getMessage());
    } finally {
        if (null != getTokenConnection) {
            getTokenConnection.disconnect();
        }
    }

    return tokenJson;
}

From source file:eu.faircode.netguard.ServiceJob.java

@Override
public boolean onStartJob(JobParameters params) {
    Log.i(TAG, "Start job=" + params.getJobId());

    new AsyncTask<JobParameters, Object, Object>() {

        @Override/*ww  w .  j  a v  a  2 s .c o m*/
        protected JobParameters doInBackground(JobParameters... params) {
            Log.i(TAG, "Executing job=" + params[0].getJobId());

            HttpsURLConnection urlConnection = null;
            try {
                String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
                JSONObject json = new JSONObject();

                json.put("device", Util.sha256(android_id, ""));
                json.put("product", Build.DEVICE);
                json.put("sdk", Build.VERSION.SDK_INT);
                json.put("country", Locale.getDefault().getCountry());

                json.put("netguard", Util.getSelfVersionCode(ServiceJob.this));
                try {
                    json.put("store", getPackageManager().getInstallerPackageName(getPackageName()));
                } catch (Throwable ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    json.put("store", null);
                }

                for (String name : params[0].getExtras().keySet())
                    json.put(name, params[0].getExtras().get(name));

                urlConnection = (HttpsURLConnection) new URL(cUrl).openConnection();
                urlConnection.setConnectTimeout(cTimeOutMs);
                urlConnection.setReadTimeout(cTimeOutMs);
                urlConnection.setRequestProperty("Accept", "application/json");
                urlConnection.setRequestProperty("Content-type", "application/json");
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);

                OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
                out.write(json.toString().getBytes()); // UTF-8
                out.flush();

                int code = urlConnection.getResponseCode();
                if (code != HttpsURLConnection.HTTP_OK)
                    throw new IOException("HTTP " + code);

                InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
                Log.i(TAG, "Response=" + Util.readString(isr).toString());

                jobFinished(params[0], false);

                if ("rule".equals(params[0].getExtras().getString("type"))) {
                    SharedPreferences history = getSharedPreferences("history", Context.MODE_PRIVATE);
                    history.edit().putLong(params[0].getExtras().getString("package") + ":submitted",
                            new Date().getTime()).apply();
                }

            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                jobFinished(params[0], true);

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

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {
                }
            }

            return null;
        }
    }.execute(params);

    return true;
}

From source file:TestHTTPSource.java

public void doTestHttps(String protocol) throws Exception {
    Type listType = new TypeToken<List<JSONEvent>>() {
    }.getType();/*from  www.  ja  v a 2  s  .  co  m*/
    List<JSONEvent> events = Lists.newArrayList();
    Random rand = new Random();
    for (int i = 0; i < 10; i++) {
        Map<String, String> input = Maps.newHashMap();
        for (int j = 0; j < 10; j++) {
            input.put(String.valueOf(i) + String.valueOf(j), String.valueOf(i));
        }
        input.put("MsgNum", String.valueOf(i));
        JSONEvent e = new JSONEvent();
        e.setHeaders(input);
        e.setBody(String.valueOf(rand.nextGaussian()).getBytes("UTF-8"));
        events.add(e);
    }
    Gson gson = new Gson();
    String json = gson.toJson(events, listType);
    HttpsURLConnection httpsURLConnection = null;
    try {
        TrustManager[] trustAllCerts = { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
                // noop
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
                // noop
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        SSLContext sc = null;
        javax.net.ssl.SSLSocketFactory factory = null;
        if (System.getProperty("java.vendor").contains("IBM")) {
            sc = SSLContext.getInstance("SSL_TLS");
        } else {
            sc = SSLContext.getInstance("SSL");
        }

        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };
        sc.init(null, trustAllCerts, new SecureRandom());

        if (protocol != null) {
            factory = new DisabledProtocolsSocketFactory(sc.getSocketFactory(), protocol);
        } else {
            factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(factory);
        HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        URL sslUrl = new URL("https://0.0.0.0:" + sslPort);
        httpsURLConnection = (HttpsURLConnection) sslUrl.openConnection();
        httpsURLConnection.setDoInput(true);
        httpsURLConnection.setDoOutput(true);
        httpsURLConnection.setRequestMethod("POST");
        httpsURLConnection.getOutputStream().write(json.getBytes());

        int statusCode = httpsURLConnection.getResponseCode();
        Assert.assertEquals(200, statusCode);

        Transaction transaction = channel.getTransaction();
        transaction.begin();
        for (int i = 0; i < 10; i++) {
            Event e = channel.take();
            Assert.assertNotNull(e);
            Assert.assertEquals(String.valueOf(i), e.getHeaders().get("MsgNum"));
        }

        transaction.commit();
        transaction.close();
    } finally {
        httpsURLConnection.disconnect();
    }
}

From source file:ovh.tgrhavoc.aibot.auth.YggdrasilAuthService.java

private JSONObject post(String targetURL, JSONObject request, ProxyData proxy) throws IOException {
    Proxy wrappedProxy = wrapProxy(proxy);
    String requestValue = request.toJSONString();
    HttpsURLConnection connection = null;
    try {//from ww  w .ja v  a2  s.  c  om
        URL url = new URL(targetURL);
        if (wrappedProxy != null)
            connection = (HttpsURLConnection) url.openConnection(wrappedProxy);
        else
            connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        connection.setRequestProperty("Content-Length", Integer.toString(requestValue.length()));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setReadTimeout(3000);
        connection.setConnectTimeout(3000);

        connection.connect();

        /*Certificate[] certs = connection.getServerCertificates();
                
        byte[] bytes = new byte[294];
        DataInputStream dis = new DataInputStream(Session.class.getResourceAsStream("/minecraft.key"));
        dis.readFully(bytes);
        dis.close();
                
        Certificate c = certs[0];
        PublicKey pk = c.getPublicKey();
        byte[] data = pk.getEncoded();
                
        for(int i = 0; i < data.length; i++)
           if(data[i] != bytes[i])
              throw new RuntimeException("Public key mismatch");*/

        try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) {
            out.writeBytes(requestValue);
            out.flush();
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            StringBuffer response = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                if (response.length() > 0)
                    response.append('\n');
                response.append(line);
            }
            if (response.toString().trim().isEmpty())
                return null;
            try {
                JSONParser parser = new JSONParser();
                Object responseObject = parser.parse(response.toString());
                if (!(responseObject instanceof JSONObject))
                    throw new IOException("Response not type of JSONObject: " + response);
                return (JSONObject) responseObject;
            } catch (ParseException exception) {
                throw new IOException("Response not valid JSON: " + response, exception);
            }
        }
    } catch (IOException exception) {
        throw exception;
    } catch (Exception exception) {
        throw new IOException("Error connecting", exception);
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

From source file:com.flipzu.flipzu.FlipInterface.java

String postViaHttpsConnection(String path, String params) throws IOException {
    HttpsURLConnection c = null;
    InputStream is = null;//from  w  w w .j  av a2  s . co m
    OutputStream os = null;
    String respString = null;
    int rc;

    // String url = WSServerSecure + path;
    URL url = new URL(WSServerSecure + path);

    try {
        trustAllHosts();
        c = (HttpsURLConnection) url.openConnection();
        c.setHostnameVerifier(DO_NOT_VERIFY);

        c.setDoOutput(true);
        // Set the request method and headers
        c.setRequestMethod("POST");
        c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
        c.setRequestProperty("Content-Language", "en-US");
        c.setRequestProperty("Accept-Encoding", "identity");

        // Getting the output stream may flush the headers
        os = c.getOutputStream();
        os.write(params.getBytes());
        os.flush();

        // Getting the response code will open the connection,
        // send the request, and read the HTTP response headers.
        // The headers are stored until requested.
        rc = c.getResponseCode();
        if (rc != HttpURLConnection.HTTP_OK) {
            throw new IOException("HTTP response code: " + rc);
        }

        is = c.getInputStream();

        // Get the length and process the data
        int len = (int) c.getContentLength();
        if (len > 0) {
            int actual = 0;
            int bytesread = 0;
            byte[] data = new byte[len];
            while ((bytesread != len) && (actual != -1)) {
                actual = is.read(data, bytesread, len - bytesread);
                bytesread += actual;
            }
            respString = new String(data);

        } else {
            byte[] data = new byte[8192];
            int ch;
            int i = 0;
            while ((ch = is.read()) != -1) {
                if (i < data.length)
                    data[i] = ((byte) ch);
                i++;
            }
            respString = new String(data);
        }

    } catch (ClassCastException e) {
        debug.logW(TAG, "Not an HTTP URL");
        throw new IllegalArgumentException("Not an HTTP URL");
    } finally {
        if (is != null)
            is.close();
        if (os != null)
            os.close();
        if (c != null)
            c.disconnect();
    }

    return respString;
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * {@code connect} is for forming the secure connection between server and
 * android, sending and receiving of the data.
 * //w  w  w  .  j  av  a 2s.  c o  m
 * @param arg0
 *            data which is to be sent to server.
 * 
 * @return data in string format, received from the server.
 */
public String connect(String... arg0) {

    int nrOfDataToSendToServer = arg0.length;
    nrOfDataToSendToServer = nrOfDataToSendToServer - 1;
    boolean valid = false;
    String dataFromServer = "unverified", serverPublicKeySigStr, serverDataSig;

    try {
        //Creating the server certificate
        Certificate serverCertificate = getServerCertificate();

        KeyStore keyStore = getKeyStore(serverCertificate);

        TrustManagerFactory tmf = getTrustManager(keyStore);

        SSLContext sslContext = getSSLContext(tmf);

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

        HttpsURLConnection urlConnection = getURLConnection(sslContext, hostnameVerifier);

        // Converting the data into JSONObject
        JSONObject obj = new JSONObject();
        for (int i = 0; i <= nrOfDataToSendToServer; i++) {
            obj.put("param" + i, arg0[i]);
        }

        // Converting the JSONObject into string
        String dataToSend = obj.toString();

        KeyPairGenerator keyGen = getKeyPairGenerator();

        KeyPair keyPair = keyGen.generateKeyPair();
        //Public key for verifying the digital signature
        PublicKey clientPublicKeySig = keyPair.getPublic();
        //Private key for signing the data
        PrivateKey clientPrivateKeySig = keyPair.getPrivate();

        // Get signed data
        String sigData = getDataSig(clientPrivateKeySig, dataToSend);

        // Creating URL Format
        String urlData = URLEncoder.encode("clientPublicKeySig", "UTF-8") + "=" + URLEncoder
                .encode(Base64.encodeToString(clientPublicKeySig.getEncoded(), Base64.DEFAULT), "UTF-8");
        urlData += "&" + URLEncoder.encode("clientData", "UTF-8") + "="
                + URLEncoder.encode(dataToSend, "UTF-8");
        urlData += "&" + URLEncoder.encode("clientDataSig", "UTF-8") + "="
                + URLEncoder.encode(sigData, "UTF-8");

        // Sending the data to the server
        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(urlData);
        wr.flush();
        wr.close();

        // Receiving the data from server
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
            // sb.append(line);
        }
        String text = sb.toString();
        reader.close();

        // Extracting the data, public key and signature received from
        // server
        Vector<String> storeExtractedValues = new Vector<String>();

        storeExtractedValues = extractDataFromJson(text, "data");
        dataFromServer = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverPublicKeySig");
        serverPublicKeySigStr = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverDataSig");
        serverDataSig = storeExtractedValues.get(0);

        // Converting the Server Public key format to Java compatible from
        PublicKey serverPublicKeySig = getServerPublicKey(serverPublicKeySigStr);

        // Verify the received data
        valid = getDataValidity(serverPublicKeySig, dataFromServer, serverDataSig);

        // Disconnect the url connection
        urlConnection.disconnect();

        if (dataFromServer.equalsIgnoreCase("unverified")) {
            CExceptionHandling.ExceptionState = ExceptionSet.SENT_DATA_UNVERIFIED;
            return "-1";
        } else if (valid == false) {
            CExceptionHandling.ExceptionState = ExceptionSet.RECEIVED_DATA_UNVERIFIED;
            return "-1";
        } else {
            return dataFromServer;
        }

    } catch (Exception e) {
        CExceptionHandling.ExceptionMsg = e.getMessage();

        if (e.toString().equals("java.net.SocketException: Network unreachable")) {
            CExceptionHandling.ExceptionState = ExceptionSet.NO_DATA_CONNECTION;
        } else if (e.toString().equals(
                "java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 443) after 10000ms")) {
            CExceptionHandling.ExceptionState = ExceptionSet.CONNECTION_TIMEOUT;
        } else {
            CExceptionHandling.ExceptionState = ExceptionSet.OTHER_EXCEPTIONS;
        }
        return "-1";
    }

}

From source file:org.appspot.apprtc.util.AsyncHttpURLConnection.java

private void sendHttpMessage() {
    if (mIsBitmap) {
        Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url);

        if (bitmap != null) {
            events.onHttpComplete(bitmap);
            return;
        }/*from   w  ww.  jav a2s  .  com*/
    }

    X509TrustManager trustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // NOTE : This is where we can calculate the certificate's fingerprint,
            // show it to the user and throw an exception in case he doesn't like it
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };

    //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
    // Create a trust manager that does not validate certificate chains
    X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager };

    // Install the all-trusting trust manager
    SSLSocketFactory noSSLv3Factory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom());
        } else {
            noSSLv3Factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory);
    } catch (GeneralSecurityException e) {
    }

    HttpsURLConnection connection = null;
    try {
        URL urlObj = new URL(url);
        connection = (HttpsURLConnection) urlObj.openConnection();
        connection.setSSLSocketFactory(noSSLv3Factory);

        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        connection.setHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        byte[] postData = new byte[0];
        if (message != null) {
            postData = message.getBytes("UTF-8");
        }

        if (msCookieManager.getCookieStore().getCookies().size() > 0) {
            // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
            connection.setRequestProperty("Cookie",
                    TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
        }

        /*if (method.equals("PATCH")) {
          connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
          connection.setRequestMethod("POST");
        }
        else {*/
        connection.setRequestMethod(method);
        //}

        if (authorization.length() != 0) {
            connection.setRequestProperty("Authorization", authorization);
        }
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setConnectTimeout(HTTP_TIMEOUT_MS);
        connection.setReadTimeout(HTTP_TIMEOUT_MS);
        // TODO(glaznev) - query request origin from pref_room_server_url_key preferences.
        //connection.addRequestProperty("origin", HTTP_ORIGIN);
        boolean doOutput = false;
        if (method.equals("POST") || method.equals("PATCH")) {
            doOutput = true;
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(postData.length);
        }
        if (contentType == null) {
            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        } else {
            connection.setRequestProperty("Content-Type", contentType);
        }

        // Send POST request.
        if (doOutput && postData.length > 0) {
            OutputStream outStream = connection.getOutputStream();
            outStream.write(postData);
            outStream.close();
        }

        // Get response.
        int responseCode = 200;
        try {
            connection.getResponseCode();
        } catch (IOException e) {

        }
        getCookies(connection);
        InputStream responseStream;

        if (responseCode > 400) {
            responseStream = connection.getErrorStream();
        } else {
            responseStream = connection.getInputStream();
        }

        String responseType = connection.getContentType();
        if (responseType.startsWith("image/")) {
            Bitmap bitmap = BitmapFactory.decodeStream(responseStream);
            if (mIsBitmap && bitmap != null) {
                ThumbnailsCacheManager.addBitmapToCache(url, bitmap);
            }
            events.onHttpComplete(bitmap);
        } else {
            String response = drainStream(responseStream);
            events.onHttpComplete(response);
        }
        responseStream.close();
        connection.disconnect();
    } catch (SocketTimeoutException e) {
        events.onHttpError("HTTP " + method + " to " + url + " timeout");
    } catch (IOException e) {
        if (connection != null) {
            connection.disconnect();
        }
        events.onHttpError("HTTP " + method + " to " + url + " error: " + e.getMessage());
    } catch (ClassCastException e) {
        e.printStackTrace();
    }
}

From source file:com.pearson.pdn.learningstudio.core.AbstractService.java

/**
 * Performs HTTP operations using the selected authentication method
 * // ww  w. j av a  2 s . c o  m
 * @param extraHeaders   Extra headers to include in the request
 * @param method   The HTTP Method to user
 * @param relativeUrl   The URL after .com (/me)
 * @param body   The body of the message
 * @return Output in the preferred data format
 * @throws IOException
 */
protected Response doMethod(Map<String, String> extraHeaders, HttpMethod method, String relativeUrl,
        String body) throws IOException {

    if (body == null) {
        body = "";
    }

    // append .xml extension when XML data format enabled.
    if (dataFormat == DataFormat.XML) {
        logger.debug("Using XML extension on route");

        String queryString = "";
        int queryStringIndex = relativeUrl.indexOf('?');
        if (queryStringIndex != -1) {
            queryString = relativeUrl.substring(queryStringIndex);
            relativeUrl = relativeUrl.substring(0, queryStringIndex);
        }

        String compareUrl = relativeUrl.toLowerCase();

        if (!compareUrl.endsWith(".xml")) {
            relativeUrl += ".xml";
        }

        if (queryStringIndex != -1) {
            relativeUrl += queryString;
        }
    }

    final String fullUrl = API_DOMAIN + relativeUrl;

    if (logger.isDebugEnabled()) {
        logger.debug("REQUEST - Method: " + method.name() + ", URL: " + fullUrl + ", Body: " + body);
    }

    URL url = new URL(fullUrl);
    Map<String, String> oauthHeaders = getOAuthHeaders(method, url, body);

    if (oauthHeaders == null) {
        throw new RuntimeException("Authentication method not selected. SEE useOAuth# methods");
    }

    if (extraHeaders != null) {
        for (String key : extraHeaders.keySet()) {
            if (!oauthHeaders.containsKey(key)) {
                oauthHeaders.put(key, extraHeaders.get(key));
            } else {
                throw new RuntimeException("Extra headers can not include OAuth headers");
            }
        }
    }

    HttpsURLConnection request = (HttpsURLConnection) url.openConnection();
    try {
        request.setRequestMethod(method.toString());

        Set<String> oauthHeaderKeys = oauthHeaders.keySet();
        for (String oauthHeaderKey : oauthHeaderKeys) {
            request.addRequestProperty(oauthHeaderKey, oauthHeaders.get(oauthHeaderKey));
        }

        request.addRequestProperty("User-Agent", getServiceIdentifier());

        if ((method == HttpMethod.POST || method == HttpMethod.PUT) && body.length() > 0) {
            if (dataFormat == DataFormat.XML) {
                request.setRequestProperty("Content-Type", "application/xml");
            } else {
                request.setRequestProperty("Content-Type", "application/json");
            }

            request.setRequestProperty("Content-Length", String.valueOf(body.getBytes("UTF-8").length));
            request.setDoOutput(true);

            DataOutputStream out = new DataOutputStream(request.getOutputStream());
            try {
                out.writeBytes(body);
                out.flush();
            } finally {
                out.close();
            }
        }

        Response response = new Response();
        response.setMethod(method.toString());
        response.setUrl(url.toString());
        response.setStatusCode(request.getResponseCode());
        response.setStatusMessage(request.getResponseMessage());
        response.setHeaders(request.getHeaderFields());

        InputStream inputStream = null;
        if (response.getStatusCode() < ResponseStatus.BAD_REQUEST.code()) {
            inputStream = request.getInputStream();
        } else {
            inputStream = request.getErrorStream();
        }

        boolean isBinary = false;
        if (inputStream != null) {
            StringBuilder responseBody = new StringBuilder();

            String contentType = request.getContentType();
            if (contentType != null) {
                if (!contentType.startsWith("text/") && !contentType.startsWith("application/xml")
                        && !contentType.startsWith("application/json")) { // assume binary
                    isBinary = true;
                    inputStream = new Base64InputStream(inputStream, true); // base64 encode
                }
            }

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            try {
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    responseBody.append(line);
                }
            } finally {
                bufferedReader.close();
            }

            response.setContentType(contentType);

            if (isBinary) {
                String content = responseBody.toString();
                if (content.length() == 0) {
                    response.setBinaryContent(new byte[0]);
                } else {
                    response.setBinaryContent(Base64.decodeBase64(responseBody.toString()));
                }
            } else {
                response.setContent(responseBody.toString());
            }
        }

        if (logger.isDebugEnabled()) {
            if (isBinary) {
                logger.debug("RESPONSE - binary response omitted");
            } else {
                logger.debug("RESPONSE - " + response.toString());
            }
        }

        return response;
    } finally {
        request.disconnect();
    }

}

From source file:de.thingweb.client.security.Security4NicePlugfest.java

public String requestASToken(Registration registration, String[] adds) throws IOException {
    String asToken = null;/*from   w ww.j a  va 2s  .  c o  m*/

    // Token Acquisition
    // Create a HTTP request as in the following prototype and send
    // it via TLS to the AM
    //
    // Token Acquisition
    // Create a HTTP request as in the following prototype and send
    // it via TLS to the AM
    // Request
    // POST /iam-services/0.1/oidc/am/token HTTP/1.1
    URL urlTokenAcquisition = new URL(HTTPS_PREFIX + HOST + REQUEST_TOKEN_AQUISITION);

    HttpsURLConnection httpConTokenAcquisition = (HttpsURLConnection) urlTokenAcquisition.openConnection();
    httpConTokenAcquisition.setDoOutput(true);
    httpConTokenAcquisition.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConTokenAcquisition.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    httpConTokenAcquisition.setRequestProperty("Accept", "application/json");
    // httpConTokenAcquisition.setRequestProperty("Authorization",
    // "Basic Base64(<c_id>:<c_secret>");
    String auth = registration.c_id + ":" + registration.c_secret;
    String authb = "Basic " + new String(Base64.getEncoder().encode(auth.getBytes()));
    httpConTokenAcquisition.setRequestProperty("Authorization", authb);
    httpConTokenAcquisition.setRequestMethod("POST");

    String requestBodyTokenAcquisition = "grant_type=client_credentials";
    if (adds == null || adds.length == 0) {
        // no additions
    } else {
        if (adds.length % 2 == 0) {
            for (int i = 0; i < (adds.length - 1); i += 2) {
                requestBodyTokenAcquisition += "&";
                requestBodyTokenAcquisition += URLEncoder.encode(adds[i], "UTF-8");
                requestBodyTokenAcquisition += "=";
                requestBodyTokenAcquisition += URLEncoder.encode(adds[i + 1], "UTF-8");
            }
        } else {
            log.warn(
                    "Additional information for token not used! Not a multiple of 2: " + Arrays.toString(adds));
        }
    }

    OutputStream outTokenAcquisition = httpConTokenAcquisition.getOutputStream();
    outTokenAcquisition.write(requestBodyTokenAcquisition.getBytes());
    outTokenAcquisition.close();

    int responseCodeoutTokenAcquisition = httpConTokenAcquisition.getResponseCode();
    log.info("responseCode TokenAcquisition for " + urlTokenAcquisition + ": "
            + responseCodeoutTokenAcquisition);

    if (responseCodeoutTokenAcquisition == 200) {
        // everything ok
        InputStream isTA = httpConTokenAcquisition.getInputStream();
        byte[] bisTA = getBytesFromInputStream(isTA);
        String jsonResponseTA = new String(bisTA);
        log.info(jsonResponseTA);

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(bisTA);
        JsonNode actualObj = mapper.readTree(jp);

        JsonNode access_token = actualObj.get("access_token");
        if (access_token == null || access_token.getNodeType() != JsonNodeType.STRING) {
            log.error("access_token: " + access_token);
        } else {
            // ok so far
            // access_token provides a JWT structure
            // see Understanding JWT
            // https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html

            log.info("access_token: " + access_token);
            // http://jwt.io/

            // TODO verify signature (e.g., use Jose4J)

            // Note: currently we assume signature is fine.. we just fetch
            // "as_token"
            String[] decAT = access_token.textValue().split("\\.");
            if (decAT == null || decAT.length != 3) {
                log.error("Cannot build JWT tripple structure for " + access_token);
            } else {
                assert (decAT.length == 3);
                // JWT structure
                // decAT[0]; // header
                // decAT[1]; // payload
                // decAT[2]; // signature
                String decAT1 = new String(Base64.getDecoder().decode(decAT[1]));
                JsonParser jpas = factory.createParser(decAT1);
                JsonNode payload = mapper.readTree(jpas);
                JsonNode as_token = payload.get("as_token");
                if (as_token == null || as_token.getNodeType() != JsonNodeType.STRING) {
                    log.error("as_token: " + as_token);
                } else {
                    log.info("as_token: " + as_token);
                    asToken = as_token.textValue();
                }
            }
        }

    } else {
        // error
        InputStream error = httpConTokenAcquisition.getErrorStream();
        byte[] berror = getBytesFromInputStream(error);
        log.error(new String(berror));
    }

    httpConTokenAcquisition.disconnect();

    return asToken;
}

From source file:io.teak.sdk.Request.java

@Override
public void run() {
    HttpsURLConnection connection = null;
    SecretKeySpec keySpec = new SecretKeySpec(this.session.appConfiguration.apiKey.getBytes(), "HmacSHA256");
    String requestBody;/*w  ww  .j  a  v a2s . c  o m*/

    String hostnameForEndpoint = this.hostname;
    if (hostnameForEndpoint == null) {
        hostnameForEndpoint = this.session.remoteConfiguration.getHostnameForEndpoint(this.endpoint);
    }

    try {
        ArrayList<String> payloadKeys = new ArrayList<>(this.payload.keySet());
        Collections.sort(payloadKeys);

        StringBuilder builder = new StringBuilder();
        for (String key : payloadKeys) {
            Object value = this.payload.get(key);
            if (value != null) {
                String valueString;
                if (value instanceof Map) {
                    valueString = new JSONObject((Map) value).toString();
                } else if (value instanceof Array) {
                    valueString = new JSONArray(Collections.singletonList(value)).toString();
                } else if (value instanceof Collection) {
                    valueString = new JSONArray((Collection) value).toString();
                } else {
                    valueString = value.toString();
                }
                builder.append(key).append("=").append(valueString).append("&");
            } else {
                Log.e(LOG_TAG, "Value for key: " + key + " is null.");
            }
        }
        builder.deleteCharAt(builder.length() - 1);

        String stringToSign = "POST\n" + hostnameForEndpoint + "\n" + this.endpoint + "\n" + builder.toString();
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(keySpec);
        byte[] result = mac.doFinal(stringToSign.getBytes());

        builder = new StringBuilder();
        for (String key : payloadKeys) {
            Object value = this.payload.get(key);
            String valueString;
            if (value instanceof Map) {
                valueString = new JSONObject((Map) value).toString();
            } else if (value instanceof Array) {
                valueString = new JSONArray(Collections.singletonList(value)).toString();
            } else if (value instanceof Collection) {
                valueString = new JSONArray((Collection) value).toString();
            } else {
                valueString = value.toString();
            }
            builder.append(key).append("=").append(URLEncoder.encode(valueString, "UTF-8")).append("&");
        }
        builder.append("sig=")
                .append(URLEncoder.encode(Base64.encodeToString(result, Base64.NO_WRAP), "UTF-8"));

        requestBody = builder.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error signing payload: " + Log.getStackTraceString(e));
        return;
    }

    try {
        if (Teak.isDebug) {
            Log.d(LOG_TAG, "Submitting request to '" + this.endpoint + "': "
                    + new JSONObject(this.payload).toString(2));
        }

        URL url = new URL("https://" + hostnameForEndpoint + this.endpoint);
        connection = (HttpsURLConnection) url.openConnection();

        connection.setRequestProperty("Accept-Charset", "UTF-8");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(requestBody.getBytes().length));

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(requestBody);
        wr.flush();
        wr.close();

        // Get Response
        InputStream is;
        if (connection.getResponseCode() < 400) {
            is = connection.getInputStream();
        } else {
            is = connection.getErrorStream();
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();

        if (Teak.isDebug) {
            String responseText = response.toString();
            try {
                responseText = new JSONObject(response.toString()).toString(2);
            } catch (Exception ignored) {
            }
            Log.d(LOG_TAG, "Reply from '" + this.endpoint + "': " + responseText);
        }

        // For extending classes
        done(connection.getResponseCode(), response.toString());
    } catch (Exception e) {
        Log.e(LOG_TAG, Log.getStackTraceString(e));
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}