Example usage for java.net HttpURLConnection HTTP_UNAUTHORIZED

List of usage examples for java.net HttpURLConnection HTTP_UNAUTHORIZED

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_UNAUTHORIZED.

Prototype

int HTTP_UNAUTHORIZED

To view the source code for java.net HttpURLConnection HTTP_UNAUTHORIZED.

Click Source Link

Document

HTTP Status-Code 401: Unauthorized.

Usage

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

private double getAvail(int code) {
    // There are too many options to list everything that is
    // successful. So, instead we are going to call out the
    // things that should be considered failure, everything else
    // is OK.//from w  w  w.  ja  va 2 s  . com
    switch (code) {
    case HttpURLConnection.HTTP_BAD_REQUEST:
    case HttpURLConnection.HTTP_FORBIDDEN:
    case HttpURLConnection.HTTP_NOT_FOUND:
    case HttpURLConnection.HTTP_BAD_METHOD:
    case HttpURLConnection.HTTP_CLIENT_TIMEOUT:
    case HttpURLConnection.HTTP_CONFLICT:
    case HttpURLConnection.HTTP_PRECON_FAILED:
    case HttpURLConnection.HTTP_ENTITY_TOO_LARGE:
    case HttpURLConnection.HTTP_REQ_TOO_LONG:
    case HttpURLConnection.HTTP_INTERNAL_ERROR:
    case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
    case HttpURLConnection.HTTP_UNAVAILABLE:
    case HttpURLConnection.HTTP_VERSION:
    case HttpURLConnection.HTTP_BAD_GATEWAY:
    case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
        return Metric.AVAIL_DOWN;
    default:
    }

    if (hasCredentials()) {
        if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            return Metric.AVAIL_DOWN;
        }
    }

    return Metric.AVAIL_UP;
}

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

/**
 * Execute an operation against the domain api. This method is doing the
 * real work by talking to the remote server and sending JSON data, that
 * is obtained by serializing the operation.
 *
 * Please do not use this API , but execute()
 * @return JsonNode that describes the result
 * @param operation an Operation that should be run on the domain controller
 * @see #execute(org.rhq.modules.plugins.jbossas7.json.Operation)
 * @see #execute(org.rhq.modules.plugins.jbossas7.json.Operation, boolean)
 * @see #executeComplex(org.rhq.modules.plugins.jbossas7.json.Operation)
 *///  w w w. j  a va2s  .c o m
public JsonNode executeRaw(Operation operation) {

    InputStream inputStream = null;
    BufferedReader br = null;
    InputStream es = null;
    HttpURLConnection conn = null;
    long t1 = System.currentTimeMillis();
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Content-Type", "application/json");
        conn.addRequestProperty("Accept", "application/json");
        conn.setConnectTimeout(10 * 1000); // 10s
        conn.setReadTimeout(10 * 1000); // 10s

        if (conn.getReadTimeout() != 10 * 1000)
            log.warn("JRE uses a broken timeout mechanism - nothing we can do");

        OutputStream out = conn.getOutputStream();

        String json_to_send = mapper.writeValueAsString(operation);

        //check for spaces in the path which the AS7 server will reject. Log verbose error and
        // generate failure indicator.
        if ((operation != null) && (operation.getAddress() != null)
                && operation.getAddress().getPath() != null) {
            if (containsSpaces(operation.getAddress().getPath())) {
                Result noResult = new Result();
                String outcome = "- Path '" + operation.getAddress().getPath()
                        + "' in invalid as it cannot contain spaces -";
                if (verbose) {
                    log.error(outcome);
                }
                noResult.setFailureDescription(outcome);
                noResult.setOutcome("failure");
                JsonNode invalidPathResult = mapper.valueToTree(noResult);
                return invalidPathResult;
            }
        }

        if (verbose) {
            log.info("Json to send: " + json_to_send);
        }

        mapper.writeValue(out, operation);

        out.flush();
        out.close();

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }

        if (inputStream != null) {

            br = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }

            String outcome;
            JsonNode operationResult;
            if (builder.length() > 0) {
                outcome = builder.toString();
                operationResult = mapper.readTree(outcome);
                if (verbose) {
                    ObjectMapper om2 = new ObjectMapper();
                    om2.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
                    String tmp = om2.writeValueAsString(operationResult);
                    log.info(tmp);
                }
            } else {
                outcome = "- no response from server -";
                Result noResult = new Result();
                noResult.setFailureDescription(outcome);
                noResult.setOutcome("failure");
                operationResult = mapper.valueToTree(noResult);
            }
            return operationResult;
        } else {
            //if not properly authorized sends plugin exception for visual indicator in the ui.
            if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED
                    || responseCode == HttpURLConnection.HTTP_BAD_METHOD) {
                if (log.isDebugEnabled()) {
                    log.debug("[" + url + "] Response was empty and response code was " + responseCode + " "
                            + conn.getResponseMessage() + ".");
                }
                throw new InvalidPluginConfigurationException(
                        "Credentials for plugin to connect to AS7 management interface are invalid. Update Connection Settings with valid credentials.");
            } else {
                log.error("[" + url + "] Response was empty and response code was " + responseCode + " "
                        + conn.getResponseMessage() + ".");
            }
        }
    } catch (IllegalArgumentException iae) {
        log.error("Illegal argument " + iae);
        log.error("  for input " + operation);
    } catch (SocketTimeoutException ste) {
        log.error("Request to AS timed out " + ste.getMessage());
        conn.disconnect();
        Result failure = new Result();
        failure.setFailureDescription(ste.getMessage());
        failure.setOutcome("failure");
        failure.setRhqThrowable(ste);

        JsonNode ret = mapper.valueToTree(failure);
        return ret;

    } catch (IOException e) {
        log.error("Failed to get data: " + e.getMessage());

        //the following code is in place to help keep-alive http connection re-use to occur.
        if (conn != null) {//on error conditions it's still necessary to read the response so JDK knows can reuse
            //the http connections behind the scenes.
            es = conn.getErrorStream();
            if (es != null) {
                BufferedReader dr = new BufferedReader(new InputStreamReader(es));
                String ignore = null;
                try {
                    while ((ignore = dr.readLine()) != null) {
                        //already reported error. just empty stream.
                    }
                    es.close();
                } catch (IOException e1) {
                    // ignore
                }
            }
        }

        Result failure = new Result();
        failure.setFailureDescription(e.getMessage());
        failure.setOutcome("failure");
        failure.setRhqThrowable(e);

        JsonNode ret = mapper.valueToTree(failure);
        return ret;

    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        if (es != null) {
            try {
                es.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        long t2 = System.currentTimeMillis();
        PluginStats stats = PluginStats.getInstance();
        stats.incrementRequestCount();
        stats.addRequestTime(t2 - t1);
    }

    return null;
}

From source file:org.eclipse.hono.service.auth.device.CredentialsApiAuthProvider.java

@Override
public final void authenticate(final DeviceCredentials deviceCredentials,
        final Handler<AsyncResult<Device>> resultHandler) {

    Objects.requireNonNull(deviceCredentials);
    Objects.requireNonNull(resultHandler);
    Future<Device> validationResult = Future.future();
    validationResult.setHandler(resultHandler);

    getCredentialsForDevice(deviceCredentials).recover(t -> {
        final ServiceInvocationException e = (ServiceInvocationException) t;
        if (e.getErrorCode() == HttpURLConnection.HTTP_NOT_FOUND) {
            return Future.failedFuture(
                    new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "bad credentials"));
        } else {/*from ww  w. j a v a  2 s .  c  o  m*/
            return Future.failedFuture(t);
        }
    }).map(credentialsOnRecord -> {
        if (deviceCredentials.validate(credentialsOnRecord)) {
            return new Device(deviceCredentials.getTenantId(), credentialsOnRecord.getDeviceId());
        } else {
            throw new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "invalid credentials");
        }
    }).setHandler(resultHandler);
}

From source file:org.sofun.core.security.oauth.OAuthSofunProvider.java

protected OAuthSofunConsumer _getConsumer(String consumerKey) throws OAuthException {

    OAuthSofunConsumer ret = getStorage().getConsumer(consumerKey);

    if (ret == null)
        throw new OAuthException(HttpURLConnection.HTTP_UNAUTHORIZED, "No such consumer key " + consumerKey);
    return ret;/*from   www . ja v a2s .  c om*/
}

From source file:io.tehtotalpwnage.musicphp_android.NavigationActivity.java

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    // Handle navigation view item clicks here.

    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Everything after this point is actually my code.
        StringRequest req = new StringRequest(Request.Method.GET, UrlGenerator.getServerUrl(this) + "/api/user",
                new Response.Listener<String>() {
                    @Override/*from w  ww  . ja  v a  2  s  .co  m*/
                    public void onResponse(String response) {
                        TextView view = new TextView(getApplicationContext());
                        view.setText(response);
                        FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame);
                        layout.removeAllViews();
                        layout.addView(view);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.v(TAG, "Connection error");
                        TextView view = new TextView(getApplicationContext());
                        view.setText(getResources().getString(R.string.error_connection));
                        FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame);
                        layout.removeAllViews();
                        layout.addView(view);
                        NetworkResponse networkResponse = error.networkResponse;
                        if (networkResponse != null
                                && networkResponse.statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                            Log.v(TAG, "Request was unauthorized, meaning that a new token is needed");
                            AccountManager manager = AccountManager.get(getApplicationContext());
                            manager.invalidateAuthToken(MusicPhpAccount.ACCOUNT_TYPE,
                                    getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
                            Intent intent = new Intent(NavigationActivity.this, MainActivity.class);
                            startActivity(intent);
                        }
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Accept", "application/json");
                params.put("Authorization",
                        "Bearer " + getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
                return params;
            }
        };
        VolleySingleton.getInstance(this).addToRequestQueue(req);
    } else if (id == R.id.nav_gallery) {
        final Context context = this;
        getListing(Item.albums, 0, new VolleyCallback() {
            @Override
            public void onSuccess(JSONArray result) {
                Log.d(TAG, "Volley callback reached");
                String albums[][] = new String[result.length()][3];
                for (int i = 0; i < result.length(); i++) {
                    try {
                        JSONObject object = result.getJSONObject(i);
                        albums[i][0] = object.getString("name");
                        albums[i][1] = object.getJSONObject("artist").getString("name");
                        albums[i][2] = object.getString("id");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                AlbumListingAdapter adapter = new AlbumListingAdapter(context, albums,
                        getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
                GridView view = new GridView(context);
                view.setLayoutParams(new DrawerLayout.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT));
                view.setNumColumns(GridView.AUTO_FIT);
                view.setColumnWidth((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 148,
                        getResources().getDisplayMetrics()));
                view.setStretchMode(GridView.STRETCH_SPACING_UNIFORM);
                view.setAdapter(adapter);
                view.setVerticalSpacing((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8,
                        getResources().getDisplayMetrics()));
                FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame);
                layout.removeAllViews();
                layout.addView(view);
                Log.d(TAG, "Adapter setup complete");
            }
        });
    } else if (id == R.id.nav_slideshow) {
        getListing(Item.artists, 0, new VolleyCallback() {
            @Override
            public void onSuccess(JSONArray result) {

            }
        });
    } else if (id == R.id.nav_manage) {
        getListing(Item.tracks, 0, new VolleyCallback() {
            @Override
            public void onSuccess(JSONArray result) {
            }
        });
    } else if (id == R.id.nav_share) {
        Log.d(TAG, "Queue contains " + queue.size() + " items. Displaying queue...");
        ListView view = new ListView(this);
        view.setLayoutParams(new DrawerLayout.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        String tracks[][] = new String[queue.size()][2];
        for (int i = 0; i < queue.size(); i++) {
            MediaSessionCompat.QueueItem queueItem = queue.get(i);
            tracks[i][0] = queueItem.getDescription().getMediaId();
            tracks[i][1] = (String) queueItem.getDescription().getTitle();
        }
        AlbumAdapter adapter = new AlbumAdapter(this, tracks,
                getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN), this);
        view.setAdapter(adapter);
        view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //                    String sAddress = getApplicationContext().getSharedPreferences("Prefs", 0).getString("server", null);
                //                    Bundle bundle = new Bundle();
                //                    bundle.putString("Authorization", "Bearer " + token);
                //                    bundle.putString("Title", tracks[position][1]);
                //                    bundle.putString("art", getIntent().getStringExtra("art"));
                //                    bundle.putString("ID", tracks[position][0]);
                //                    MediaControllerCompat.getMediaController(AlbumActivity.this).getTransportControls().playFromUri(Uri.parse(sAddress + "/api/tracks/" + tracks[position][0] + "/audio"), bundle);
            }
        });
        FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame);
        layout.removeAllViews();
        layout.addView(view);
    } else if (id == R.id.nav_send) {
        String sAddress = getSharedPreferences("Prefs", 0).getString("server", null);
        StringRequest request = new StringRequest(Request.Method.POST, sAddress + "/api/logout",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject object = new JSONObject(response);
                            if (object.getString("status").equals("OK")) {
                                Log.v(TAG, "Logged out successfully. Now redirecting to MainActivity...");
                                AccountManager manager = AccountManager.get(getApplicationContext());
                                Account accounts[] = manager.getAccountsByType(MusicPhpAccount.ACCOUNT_TYPE);
                                int account = 0;
                                for (int i = 0; i < accounts.length; i++) {
                                    if (accounts[i].name.equals(
                                            getIntent().getStringExtra(AccountManager.KEY_ACCOUNT_NAME))) {
                                        account = i;
                                        break;
                                    }
                                }

                                final AccountManagerFuture future;

                                if (Build.VERSION.SDK_INT >= 22) {
                                    future = manager.removeAccount(accounts[account], NavigationActivity.this,
                                            new AccountManagerCallback<Bundle>() {
                                                @Override
                                                public void run(AccountManagerFuture<Bundle> future) {

                                                }
                                            }, null);
                                } else {
                                    future = manager.removeAccount(accounts[account],
                                            new AccountManagerCallback<Boolean>() {
                                                @Override
                                                public void run(AccountManagerFuture<Boolean> future) {

                                                }
                                            }, null);
                                }

                                AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
                                    @Override
                                    protected Void doInBackground(Void... params) {
                                        try {
                                            future.getResult();
                                            Intent intent = new Intent(NavigationActivity.this,
                                                    MainActivity.class);
                                            startActivity(intent);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        return null;
                                    }
                                };
                                task.execute();
                            } else {
                                Log.v(TAG, "Issue with logging out...");
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, "Issue with parsing JSON...");
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Error on logging out...");
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() {
                Map<String, String> params = new HashMap<>();
                params.put("Accept", "application/json");
                params.put("Authorization",
                        "Bearer " + getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
                return params;
            }
        };
        VolleySingleton.getInstance(this).addToRequestQueue(request);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

    return true;
}

From source file:org.apache.hadoop.fs.http.server.TestHttpFSServer.java

@Test
@TestDir//from ww  w. ja  v a  2 s .  c  o m
@TestJetty
@TestHdfs
public void instrumentation() throws Exception {
    createHttpFSServer(false);

    URL url = new URL(TestJettyHelper.getJettyURL(),
            MessageFormat.format("/webhdfs/v1?user.name={0}&op=instrumentation", "nobody"));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_UNAUTHORIZED);

    url = new URL(TestJettyHelper.getJettyURL(), MessageFormat.format(
            "/webhdfs/v1?user.name={0}&op=instrumentation", HadoopUsersConfTestHelper.getHadoopUsers()[0]));
    conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK);
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = reader.readLine();
    reader.close();
    Assert.assertTrue(line.contains("\"counters\":{"));

    url = new URL(TestJettyHelper.getJettyURL(), MessageFormat.format(
            "/webhdfs/v1/foo?user.name={0}&op=instrumentation", HadoopUsersConfTestHelper.getHadoopUsers()[0]));
    conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_BAD_REQUEST);
}

From source file:org.apache.hadoop.mapred.TestWebUIAuthorization.java

/**
 * Validates the given jsp/servlet against different user names who
 * can(or cannot) modify the job./*from w  ww  .  jav a2s  . com*/
 * (1) jobSubmitter, mrOwner, qAdmin and mrAdmin can modify the job.
 *     But we are not validating this in this method. Let the caller
 *     explicitly validate this, if needed.
 * (2) user mentioned in job-view-acl but not in job-modify-acl cannot
 *     modify the job
 * (3) user mentioned in job-modify-acl (irrespective of job-view-acl)
 *     can modify the job
 * (4) other unauthorized users cannot modify the job
 */
private void validateModifyJob(String url, String method) throws IOException {
    assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, getHttpStatusCode(url, viewColleague, method));
    assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, getHttpStatusCode(url, unauthorizedUser, method));
    assertEquals(HttpURLConnection.HTTP_OK, getHttpStatusCode(url, modifyColleague, method));
}

From source file:co.cask.cdap.client.rest.RestStreamClientTest.java

@Test
public void testNotAuthorizedSetTTL() throws IOException {
    try {/* www .j a  v  a 2  s  .  co m*/
        streamClient.setTTL(TestUtils.AUTH_STREAM_NAME, STREAM_TTL);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode());
    }
}

From source file:org.jboss.as.test.integration.security.perimeter.WebConsoleSecurityTestCase.java

@Test
public void testGet() throws Exception {
    getConnection().setRequestMethod(HttpGet.METHOD_NAME);
    getConnection().connect();/*from w ww.j av  a 2 s. c o  m*/
    assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, getConnection().getResponseCode());
}