Search in sources :

Example 21 with HttpURLConnection

use of java.net.HttpURLConnection in project che by eclipse.

the class GitHubKeyUploader method uploadKey.

@Override
public void uploadKey(String publicKey) throws IOException, UnauthorizedException {
    final OAuthToken token = tokenProvider.getToken("github", EnvironmentContext.getCurrent().getSubject().getUserId());
    if (token == null || token.getToken() == null) {
        LOG.debug("Token not found, user need to authorize to upload key.");
        throw new UnauthorizedException("To upload SSH key you need to authorize.");
    }
    StringBuilder answer = new StringBuilder();
    final String url = String.format("https://api.github.com/user/keys?access_token=%s", token.getToken());
    final List<GitHubKey> gitHubUserPublicKeys = getUserPublicKeys(url, answer);
    for (GitHubKey gitHubUserPublicKey : gitHubUserPublicKeys) {
        if (publicKey.startsWith(gitHubUserPublicKey.getKey())) {
            return;
        }
    }
    final Map<String, String> postParams = new HashMap<>(2);
    postParams.put("title", "IDE SSH Key (" + new SimpleDateFormat().format(new Date()) + ")");
    postParams.put("key", new String(publicKey.getBytes()));
    final String postBody = JsonHelper.toJson(postParams);
    LOG.debug("Upload public key: {}", postBody);
    int responseCode;
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod(HttpMethod.POST);
        conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
        conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        conn.setRequestProperty(HttpHeaders.CONTENT_LENGTH, String.valueOf(postBody.length()));
        conn.setDoOutput(true);
        try (OutputStream out = conn.getOutputStream()) {
            out.write(postBody.getBytes());
        }
        responseCode = conn.getResponseCode();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    LOG.debug("Upload key response code: {}", responseCode);
    if (responseCode != HttpURLConnection.HTTP_CREATED) {
        throw new IOException(String.format("%d: Failed to upload public key to https://github.com/", responseCode));
    }
}
Also used : HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Date(java.util.Date) URL(java.net.URL) OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) HttpURLConnection(java.net.HttpURLConnection) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) GitHubKey(org.eclipse.che.plugin.github.shared.GitHubKey) SimpleDateFormat(java.text.SimpleDateFormat)

Example 22 with HttpURLConnection

use of java.net.HttpURLConnection in project che by eclipse.

the class GitHubKeyUploader method getUserPublicKeys.

private List<GitHubKey> getUserPublicKeys(String url, StringBuilder answer) {
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod(HttpMethod.GET);
        conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    answer.append(line).append('\n');
                }
            }
            if (conn.getHeaderFields().containsKey("Link")) {
                String strForParsing = conn.getHeaderFields().get("Link").get(0);
                int indexNext = strForParsing.indexOf("rel=\"next\"");
                if (indexNext != -1) {
                    String nextSubStr = strForParsing.substring(0, indexNext);
                    String nextPageLink = nextSubStr.substring(nextSubStr.indexOf("<") + 1, nextSubStr.indexOf(">"));
                    getUserPublicKeys(nextPageLink, answer);
                }
                int indexToReplace;
                while ((indexToReplace = answer.indexOf("]\n[")) != -1) {
                    answer.replace(indexToReplace, indexToReplace + 3, ",");
                }
            }
            return DtoFactory.getInstance().createListDtoFromJson(answer.toString(), GitHubKey.class);
        }
        return Collections.emptyList();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        return Collections.emptyList();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) URL(java.net.URL)

Example 23 with HttpURLConnection

use of java.net.HttpURLConnection in project che by eclipse.

the class GitHubOAuthAuthenticator method getJson2.

protected <O> O getJson2(String getUserUrl, Class<O> userClass, Type type) throws OAuthAuthenticationException {
    HttpURLConnection urlConnection = null;
    InputStream urlInputStream = null;
    try {
        urlConnection = (HttpURLConnection) new URL(getUserUrl).openConnection();
        urlConnection.setRequestProperty("Accept", "application/vnd.github.v3.html+json");
        urlInputStream = urlConnection.getInputStream();
        return JsonHelper.fromJson(urlInputStream, userClass, type);
    } catch (JsonParseException | IOException e) {
        throw new OAuthAuthenticationException(e.getMessage(), e);
    } finally {
        if (urlInputStream != null) {
            try {
                urlInputStream.close();
            } catch (IOException ignored) {
            }
        }
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InputStream(java.io.InputStream) IOException(java.io.IOException) JsonParseException(org.eclipse.che.commons.json.JsonParseException) URL(java.net.URL)

Example 24 with HttpURLConnection

use of java.net.HttpURLConnection in project che by eclipse.

the class GitHubOAuthAuthenticator method getToken.

@Override
public OAuthToken getToken(String userId) throws IOException {
    final OAuthToken token = super.getToken(userId);
    if (!(token == null || token.getToken() == null || token.getToken().isEmpty())) {
        // Need to check if token which stored is valid for requests, then if valid - we returns it to caller
        String tokenVerifyUrl = "https://api.github.com/?access_token=" + token.getToken();
        HttpURLConnection http = null;
        try {
            http = (HttpURLConnection) new URL(tokenVerifyUrl).openConnection();
            http.setInstanceFollowRedirects(false);
            http.setRequestMethod("GET");
            http.setRequestProperty("Accept", "application/json");
            if (http.getResponseCode() == 401) {
                return null;
            }
        } finally {
            if (http != null) {
                http.disconnect();
            }
        }
        return token;
    }
    return null;
}
Also used : OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) HttpURLConnection(java.net.HttpURLConnection) URL(java.net.URL)

Example 25 with HttpURLConnection

use of java.net.HttpURLConnection in project whirr by apache.

the class FirewallSettings method getOriginatingIp.

/**
   * @return the IP address of the client on which this code is running.
   * @throws IOException
   */
public static String getOriginatingIp() throws IOException {
    URL url = new URL("http://checkip.amazonaws.com/");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.connect();
    return IOUtils.toString(connection.getInputStream()).trim() + "/32";
}
Also used : HttpURLConnection(java.net.HttpURLConnection) URL(java.net.URL)

Aggregations

HttpURLConnection (java.net.HttpURLConnection)3831 URL (java.net.URL)2447 IOException (java.io.IOException)1634 InputStream (java.io.InputStream)1082 InputStreamReader (java.io.InputStreamReader)692 Test (org.junit.Test)650 BufferedReader (java.io.BufferedReader)573 OutputStream (java.io.OutputStream)466 MalformedURLException (java.net.MalformedURLException)372 URLConnection (java.net.URLConnection)248 HashMap (java.util.HashMap)216 OutputStreamWriter (java.io.OutputStreamWriter)208 Map (java.util.Map)199 Gson (com.google.gson.Gson)190 ByteArrayOutputStream (java.io.ByteArrayOutputStream)186 ArrayList (java.util.ArrayList)168 ExecutionException (java.util.concurrent.ExecutionException)161 File (java.io.File)159 AsyncTask (android.os.AsyncTask)158 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)157