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.debux.webmotion.shiro.Shiro.java

/**
 * Check if the current user has role.// ww  w .  j  a  v  a 2s. co  m
 * 
 * @param role
 * @return 
 */
public Render hasRole(HttpContext context, Call call) {
    FilterRule rule = (FilterRule) call.getCurrentRule();
    Map<String, String[]> defaultParameters = rule.getDefaultParameters();

    String[] values = defaultParameters.get("role");
    List<String> roles = Arrays.asList(values);

    Subject currentUser = getSubject(context);
    if (currentUser.isAuthenticated()) {

        boolean[] hasRoles = currentUser.hasRoles(roles);
        if (BooleanUtils.and(hasRoles)) {
            doProcess();
            return null;
        } else {
            return renderError(HttpURLConnection.HTTP_FORBIDDEN);
        }

    } else {
        return renderError(HttpURLConnection.HTTP_UNAUTHORIZED);
    }
}

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

@Test
@TestDir/*w  w w  . j  a v  a  2s .  c  o  m*/
@TestJetty
@TestHdfs
public void testInvalidadHttpFSAccess() throws Exception {
    createHttpFSServer();

    URL url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETHOMEDIRECTORY");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_UNAUTHORIZED);
}

From source file:co.cask.cdap.client.util.RESTClient.java

public HttpResponse upload(HttpRequest request, AccessToken accessToken, int... allowedErrorCodes)
        throws IOException, UnauthorizedException, DisconnectedException {

    HttpResponse response = HttpRequests.execute(
            HttpRequest.builder(request).addHeaders(getAuthHeaders(accessToken)).build(),
            clientConfig.getUploadRequestConfig());
    int responseCode = response.getResponseCode();
    if (!isSuccessful(responseCode) && !ArrayUtils.contains(allowedErrorCodes, responseCode)) {
        if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new UnauthorizedException("Unauthorized status code received from the server.");
        }//from   w w  w.  j a va 2s .co m
        throw new IOException(response.getResponseBodyAsString());
    }
    return response;
}

From source file:org.ScripterRon.JavaBitcoin.RpcHandler.java

/**
 * Handle an HTTP request//  w  w w . j  a v a 2s.  c  om
 *
 * @param       exchange            HTTP exchange
 * @throws      IOException         Error detected while handling the request
 */
@Override
public void handle(HttpExchange exchange) throws IOException {
    try {
        int responseCode;
        String responseBody;
        //
        // Get the HTTP request
        //
        InetSocketAddress requestAddress = exchange.getRemoteAddress();
        String requestMethod = exchange.getRequestMethod();
        Headers requestHeaders = exchange.getRequestHeaders();
        String contentType = requestHeaders.getFirst("Content-Type");
        Headers responseHeaders = exchange.getResponseHeaders();
        log.debug(String.format("%s request received from %s", requestMethod, requestAddress.getAddress()));
        if (!rpcAllowIp.contains(requestAddress.getAddress())) {
            responseCode = HttpURLConnection.HTTP_UNAUTHORIZED;
            responseBody = "Your IP address is not authorized to access this server";
            responseHeaders.set("Content-Type", "text/plain");
        } else if (!exchange.getRequestMethod().equals("POST")) {
            responseCode = HttpURLConnection.HTTP_BAD_METHOD;
            responseBody = String.format("%s requests are not supported", exchange.getRequestMethod());
            responseHeaders.set("Content-Type", "text/plain");
        } else if (contentType == null || !contentType.equals("application/json-rpc")) {
            responseCode = HttpURLConnection.HTTP_BAD_REQUEST;
            responseBody = "Content type must be application/json-rpc";
            responseHeaders.set("Content-Type", "text/plain");
        } else {
            responseBody = processRequest(exchange);
            responseCode = HttpURLConnection.HTTP_OK;
            responseHeaders.set("Content-Type", "application/json-rpc");
        }
        //
        // Return the HTTP response
        //
        responseHeaders.set("Cache-Control", "no-cache, no-store, must-revalidate, private");
        responseHeaders.set("Server", "JavaBitcoin");
        byte[] responseBytes = responseBody.getBytes("UTF-8");
        exchange.sendResponseHeaders(responseCode, responseBytes.length);
        try (OutputStream out = exchange.getResponseBody()) {
            out.write(responseBytes);
        }
        log.debug(String.format("RPC request from %s completed", requestAddress.getAddress()));
    } catch (IOException exc) {
        log.error("Unable to process RPC request", exc);
        throw exc;
    }
}

From source file:i5.las2peer.services.gamificationActionService.GamificationActionService.java

/**
 * Function to return http unauthorized message
 * @return HTTP response unauthorized//from  w  w  w. j  av a 2  s  . c om
 */
private HttpResponse unauthorizedMessage() {
    JSONObject objResponse = new JSONObject();
    logger.info("You are not authorized >> ");
    objResponse.put("message", "You are not authorized");
    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_UNAUTHORIZED);

}

From source file:org.codinjutsu.tools.jenkins.security.DefaultSecurityClient.java

protected void checkResponse(int statusCode, String responseBody) throws AuthenticationException {
    if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) {
        throw new AuthenticationException("Not found");
    }//from   w  ww .  jav a2  s. c  o m

    if (statusCode == HttpURLConnection.HTTP_FORBIDDEN || statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        if (StringUtils.containsIgnoreCase(responseBody, BAD_CRUMB_DATA)) {
            throw new AuthenticationException("CSRF enabled -> Missing or bad crumb data");
        }

        throw new AuthenticationException("Unauthorized -> Missing or bad credentials", responseBody);
    }

    if (HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) {
        throw new AuthenticationException("Server Internal Error: Server unavailable");
    }
}

From source file:i5.las2peer.services.servicePackage.TemplateService.java

/**
 * Example method that returns a phrase containing the received input.
 * //ww  w .  jav  a 2 s . c  o m
 * @param myInput
 * 
 */
@POST
@Path("/myResourcePath/{input}")
@Produces(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Input Phrase"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "Sample Resource", notes = "Example method that returns a phrase containing the received input.")
public HttpResponse exampleMethod(@PathParam("input") String myInput) {
    String returnString = "";
    returnString += "You have entered " + myInput + "!";

    return new HttpResponse(returnString, HttpURLConnection.HTTP_OK);
}

From source file:i5.las2peer.services.gamificationAchievementService.GamificationAchievementService.java

/**
 * Function to return http unauthorized message
 * @return HTTP response unauthorized//  www  . j  a  va2 s  . c o m
 */
private HttpResponse unauthorizedMessage() {
    JSONObject objResponse = new JSONObject();
    objResponse.put("message", "You are not authorized");
    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_UNAUTHORIZED);

}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerRestClient.java

public boolean pushFile(String sessionId, String space, String path, String fileName, InputStream fileContent)
        throws Exception {
    String uriTmpl = (new StringBuilder(restEndpointURL)).append(addSlashIfMissing(restEndpointURL))
            .append("scheduler/dataspace/").append(space).append(URLEncoder.encode(path, "UTF-8")).toString();

    ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(providerFactory)
            .build();/*w ww.  j  a  va 2s .c  om*/
    ResteasyWebTarget target = client.target(uriTmpl);

    MultipartFormDataOutput formData = new MultipartFormDataOutput();
    formData.addFormData("fileName", fileName, MediaType.TEXT_PLAIN_TYPE);
    formData.addFormData("fileContent", fileContent, MediaType.APPLICATION_OCTET_STREAM_TYPE);

    GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(formData) {
    };

    Response response = target.request().header("sessionid", sessionId)
            .post(Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE));

    if (response.getStatus() != HttpURLConnection.HTTP_OK) {
        if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new NotConnectedRestException("User not authenticated or session timeout.");
        } else {
            throwException(String.format("File upload failed. Status code: %d", response.getStatus()),
                    response);
        }
    }
    return response.readEntity(Boolean.class);
}

From source file:com.mobicage.rogerthat.CallbackApiServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json-rpc; charset=utf-8");

    // Validate incomming request
    final String contentType = req.getHeader("Content-type");
    if (contentType == null || !contentType.startsWith("application/json-rpc")) {
        resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
        return;/*from  w  w  w.ja va2s .  com*/
    }
    final String sikKey = req.getHeader("X-Nuntiuz-Service-Key");
    if (!validateSIK(sikKey)) {
        resp.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
        return;
    }

    // Parse
    final InputStream is = req.getInputStream();
    final JSONObject request;
    try {
        request = (JSONObject) JSONValue.parse(new BufferedReader(new InputStreamReader(is, "UTF-8")));
    } finally {
        is.close();
    }

    if (logTraffic)
        log.info(String.format("Incoming Rogerthat API Callback.\nSIK: %s\n\n%s", sikKey,
                request.toJSONString()));

    final String id = (String) request.get("id");

    if (callbackDedup != null) {
        byte[] response = callbackDedup.getResponse(id);
        if (response != null) {
            ServletOutputStream outputStream = resp.getOutputStream();
            outputStream.write(response);
            outputStream.flush();
            return;
        }
    }

    final JSONObject result = new JSONObject();
    final RequestContext requestContext = new RequestContext(id, sikKey);
    try {
        processor.process(request, result, requestContext);
    } finally {
        String jsonString = result.toJSONString();
        if (logTraffic)
            log.info("Returning result:\n" + jsonString);

        byte[] response = jsonString.getBytes("UTF-8");
        if (callbackDedup != null) {
            callbackDedup.storeResponse(id, response);
        }

        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(response);
        outputStream.flush();
    }
}