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:com.streamsets.datacollector.http.TestWebServerTaskHttpHttps.java

@Test
public void testAuthorizationConstraints() throws Exception {
    WebAppProvider webAppProvider = new WebAppProvider() {
        @Override/*from   w ww . j  a v  a 2s.c o  m*/
        public ServletContextHandler get() {
            ServletContextHandler handler = new ServletContextHandler();
            handler.setContextPath("/webapp");
            handler.addServlet(new ServletHolder(new PingServlet()), "/ping");
            handler.addServlet(new ServletHolder(new PingServlet()), "/rest/v1/ping");
            handler.addServlet(new ServletHolder(new PingServlet()), "/public-rest/v1/ping");
            return handler;
        }

        @Override
        public void postStart() {
        }
    };
    Configuration conf = new Configuration();
    int httpPort = getRandomPort();
    conf.set(WebServerTask.AUTHENTICATION_KEY, "basic");
    conf.set(WebServerTask.HTTP_PORT_KEY, httpPort);
    String confDir = createTestDir();
    File realmFile = new File(confDir, "basic-realm.properties");
    try (InputStream is = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("basic-realm.properties"); OutputStream os = new FileOutputStream(realmFile)) {
        IOUtils.copy(is, os);
    }
    Set<PosixFilePermission> set = new HashSet<>();
    set.add(PosixFilePermission.OWNER_EXECUTE);
    set.add(PosixFilePermission.OWNER_READ);
    set.add(PosixFilePermission.OWNER_WRITE);
    Files.setPosixFilePermissions(realmFile.toPath(), set);

    final WebServerTask ws = createWebServerTask(confDir, conf, ImmutableSet.of(webAppProvider));
    try {
        ws.initTask();
        new Thread() {
            @Override
            public void run() {
                ws.runTask();
            }
        }.start();
        Thread.sleep(1000);

        String baseUrl = "http://127.0.0.1:" + httpPort;

        // root app
        HttpURLConnection conn = (HttpURLConnection) new URL(baseUrl + "/ping").openConnection();
        conn.setRequestProperty(CsrfProtectionFilter.HEADER_NAME, "CSRF");
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        conn = (HttpURLConnection) openWithBasicAuth(new URL(baseUrl + "/ping"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        conn = (HttpURLConnection) new URL(baseUrl + "/rest/v1/ping").openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());
        conn = (HttpURLConnection) openWithBasicAuth(new URL(baseUrl + "/rest/v1/ping"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        conn = (HttpURLConnection) new URL(baseUrl + "/public-rest/v1/ping").openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        conn = (HttpURLConnection) openWithBasicAuth(new URL(baseUrl + "/public-rest/v1/ping"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        // web app
        conn = (HttpURLConnection) new URL(baseUrl + "/webapp/ping").openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        conn = (HttpURLConnection) openWithBasicAuth(new URL(baseUrl + "/webapp/ping"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        conn = (HttpURLConnection) new URL(baseUrl + "/webapp/rest/v1/ping").openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());
        conn = (HttpURLConnection) openWithBasicAuth(new URL(baseUrl + "/webapp/rest/v1/ping"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        conn = (HttpURLConnection) new URL(baseUrl + "/webapp/public-rest/v1/ping").openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        conn = (HttpURLConnection) openWithBasicAuth(new URL(baseUrl + "/webapp/public-rest/v1/ping"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

    } finally {
        ws.stopTask();
    }
}

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

/**
 * Update an action//from   w  w w. j a  v  a2 s  .  c om
 * @param appId applicationId
 * @param actionId actionId
 * @param formData form data
 * @param contentType content type
 * @return HttpResponse returned as JSON object
 */
@PUT
@Path("/{appId}/{actionId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Action Updated"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Error occured"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad request"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "Update an action", notes = "A method to update an action with details (action ID, action name, action description, action point value")
public HttpResponse updateAction(
        @ApiParam(value = "Application ID to store an updated action", required = true) @PathParam("appId") String appId,
        @PathParam("actionId") String actionId,
        @ApiParam(value = "action detail in multiple/form-data type", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
        @ContentParam byte[] formData) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "PUT " + "gamification/actions/" + appId + "/" + actionId);
    long randomLong = new Random().nextLong(); //To be able to match 

    // parse given multipart form data
    JSONObject objResponse = new JSONObject();
    logger.info(actionId);
    String actionname = null;
    String actiondesc = null;
    int actionpointvalue = 0;

    //boolean actionnotifcheck = false;
    String actionnotifmessage = null;
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_18, "" + randomLong);

        Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType);

        if (actionId == null) {
            logger.info("action ID cannot be null >> ");
            objResponse.put("message", "action ID cannot be null");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }
        try {
            if (!actionAccess.isAppIdExist(conn, appId)) {
                logger.info("App not found >> ");
                objResponse.put("message", "App not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }

            ActionModel action = actionAccess.getActionWithId(conn, appId, actionId);

            if (action == null) {
                // action is null
                logger.info("action not found in database >> ");
                objResponse.put("message", "action not found in database");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }

            FormDataPart partName = parts.get("actionname");
            if (partName != null) {
                actionname = partName.getContent();

                if (actionname != null) {
                    action.setName(actionname);
                }
            }
            FormDataPart partDesc = parts.get("actiondesc");
            if (partDesc != null) {
                // optional description text input form element
                actiondesc = partDesc.getContent();
                if (actiondesc != null) {
                    action.setDescription(actiondesc);
                }
            }
            FormDataPart partPV = parts.get("actionpointvalue");
            if (partPV != null) {
                // optional description text input form element
                actionpointvalue = Integer.parseInt(partPV.getContent());
                if (actionpointvalue != 0) {
                    action.setPointValue(actionpointvalue);
                }
            }
            FormDataPart partNotificationCheck = parts.get("actionnotificationcheck");
            if (partNotificationCheck != null) {
                // checkbox is checked
                action.useNotification(true);
            } else {
                action.useNotification(false);
            }
            FormDataPart partNotificationMsg = parts.get("actionnotificationmessage");
            if (partNotificationMsg != null) {
                actionnotifmessage = partNotificationMsg.getContent();
                if (actionnotifmessage == null) {
                    action.setNotificationMessage(actionnotifmessage);
                }
            }
            actionAccess.updateAction(conn, appId, action);
            logger.info("action updated >> ");
            objResponse.put("message", "action updated");
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_19, "" + randomLong);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_28, "" + name);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_29, "" + appId);
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            logger.info("SQLException >> " + e.getMessage());
            objResponse.put("message", "Cannot connect to database");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }

    } catch (MalformedStreamException e) {
        // the stream failed to follow required syntax
        logger.log(Level.SEVERE, e.getMessage(), e);
        logger.info("MalformedStreamException >> ");
        objResponse.put("message", "Failed to upload " + actionId + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
    } catch (IOException e) {
        // a read or write error occurred
        logger.log(Level.SEVERE, e.getMessage(), e);
        logger.info("IOException >> ");
        objResponse.put("message", "Failed to upload " + actionId + ".");
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (SQLException e) {
        e.printStackTrace();
        System.out.println(e.getMessage());
        logger.info("SQLException >> " + e.getMessage());
        objResponse.put("message", "Cannot connect to database");
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }

}

From source file:com.baracuda.piepet.nexusrelease.nexus.StageClient.java

/**
 * Retrieve and parse an XML file from the given URL.
 * //w  w  w.  j  a  va  2s  .  com
 * @param url the URL where the XML document can be obtained.
 * @return the parsed Document.
 * @throws StageException if there was an issue obtaining or parsing the document.
 */
protected Document getDocument(URL url) throws StageException {
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        addAuthHeader(conn);
        conn.setRequestProperty("Accept", "application/xml");
        int status = conn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(conn.getInputStream());
            conn.disconnect();
            return doc;
        } else {
            drainOutput(conn);
            if (status == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new IOException("Incorrect username / password supplied.");
            } else if (status == HttpURLConnection.HTTP_NOT_FOUND) {
                throw new IOException("Document not found - is this a Nexus server?");
            } else {
                throw new IOException("Server returned error code " + status + " for " + url.toString());
            }
        }
    } catch (IOException ex) {
        throw createStageExceptionForIOException(nexusURL, ex);
    } catch (ParserConfigurationException ex) {
        throw new StageException(ex);
    } catch (SAXException ex) {
        throw new StageException(ex);
    }

}

From source file:org.projectbuendia.client.ui.OdkActivityLauncher.java

private static void handleFetchError(VolleyError error) {
    FetchXformFailedEvent.Reason reason = FetchXformFailedEvent.Reason.SERVER_UNKNOWN;
    if (error.networkResponse != null) {
        switch (error.networkResponse.statusCode) {
        case HttpURLConnection.HTTP_FORBIDDEN:
        case HttpURLConnection.HTTP_UNAUTHORIZED:
            reason = FetchXformFailedEvent.Reason.SERVER_AUTH;
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            reason = FetchXformFailedEvent.Reason.SERVER_BAD_ENDPOINT;
            break;
        case HttpURLConnection.HTTP_INTERNAL_ERROR:
        default://from  w  w w  . j a  v  a2 s .  c  o  m
            reason = FetchXformFailedEvent.Reason.SERVER_UNKNOWN;
        }
    }
    EventBus.getDefault().post(new FetchXformFailedEvent(reason, error));
}

From source file:com.connectsdk.service.AirPlayService.java

@Override
public void sendCommand(final ServiceCommand<?> serviceCommand) {
    Util.runInBackground(new Runnable() {
        @Override/*from   w  w w . j a  v a2s. c om*/
        public void run() {
            try {
                StringBuilder sb = new StringBuilder();
                sb.append("http://").append(serviceDescription.getIpAddress()).append(":")
                        .append(serviceDescription.getPort());
                sb.append(serviceCommand.getTarget());

                HttpConnection connection = HttpConnection.newInstance(URI.create(sb.toString()));
                connection.setHeader(HTTP.USER_AGENT, "ConnectSDK MediaControl/1.0");
                connection.setHeader(X_APPLE_SESSION_ID, mSessionId);
                if (password != null) {
                    String authorization = getAuthenticate(serviceCommand.getHttpMethod(),
                            serviceCommand.getTarget(), authenticate);
                    connection.setHeader("Authorization", authorization);
                }
                Object payload = serviceCommand.getPayload();
                if (serviceCommand.getHttpMethod().equalsIgnoreCase(ServiceCommand.TYPE_POST)
                        || serviceCommand.getHttpMethod().equalsIgnoreCase(ServiceCommand.TYPE_PUT)) {
                    if (payload != null) {
                        if (payload instanceof String) {
                            connection.setHeader(HttpMessage.CONTENT_TYPE_HEADER,
                                    HttpMessage.CONTENT_TYPE_APPLICATION_PLIST);
                            connection.setPayload(payload.toString());
                        } else if (payload instanceof byte[]) {
                            connection.setPayload((byte[]) payload);
                        }
                    }
                }
                if (serviceCommand.getHttpMethod().equalsIgnoreCase(ServiceCommand.TYPE_POST)) {
                    connection.setMethod(HttpConnection.Method.POST);
                } else if (serviceCommand.getHttpMethod().equalsIgnoreCase(ServiceCommand.TYPE_PUT)) {
                    connection.setMethod(HttpConnection.Method.PUT);
                } else {
                    connection.setHeader("Content-Length", "0");
                }
                connection.execute();
                int code = connection.getResponseCode();
                if (code == HttpURLConnection.HTTP_OK) {
                    Util.postSuccess(serviceCommand.getResponseListener(), connection.getResponseString());
                } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    authenticate = connection.getResponseHeader("WWW-Authenticate");
                    pendingCommand = serviceCommand;
                    Util.runOnUI(new Runnable() {
                        @Override
                        public void run() {
                            if (listener != null) {
                                listener.onPairingRequired(AirPlayService.this, pairingType, null);
                            }
                        }
                    });
                } else {
                    Util.postError(serviceCommand.getResponseListener(), ServiceCommandError.getError(code));
                }
            } catch (IOException e) {
                e.printStackTrace();
                Util.postError(serviceCommand.getResponseListener(),
                        new ServiceCommandError(0, e.getMessage(), null));
            }
        }
    });
}

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

/**
 * Update an achievement/*from  w w  w.j  av a  2 s .co  m*/
 * @param appId applicationId
 * @param achievementId achievementId
 * @param formData form data
 * @param contentType content type
 * @return HttpResponse returned as JSON object
 */
@PUT
@Path("/{appId}/{achievementId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Achievement Updated"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Error occured"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad request"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "updateAchievement", notes = "A method to update an achievement with details (achievement ID, achievement name, achievement description, achievement point value, achievement point id, achievement badge id")
public HttpResponse updateAchievement(
        @ApiParam(value = "Application ID to update an achievement", required = true) @PathParam("appId") String appId,
        @PathParam("achievementId") String achievementId,
        @ApiParam(value = "Achievement data in multiple/form-data type", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
        @ContentParam byte[] formData) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "PUT " + "gamification/achievements/" + appId + "/" + achievementId);
    long randomLong = new Random().nextLong(); //To be able to match 

    // parse given multipart form data
    JSONObject objResponse = new JSONObject();

    String achievementname = null;
    String achievementdesc = null;
    int achievementpointvalue = 0;
    String achievementbadgeid = null;

    String achievementnotifmessage = null;
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_18, "" + randomLong);

        Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType);

        if (achievementId == null) {
            objResponse.put("message", "Cannot update achievement. Achievement ID cannot be null");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }

        try {
            try {
                if (!achievementAccess.isAppIdExist(conn, appId)) {
                    objResponse.put("message", "Cannot update achievement. App not found");
                    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
                objResponse.put("message",
                        "Cannot update achievement. Cannot check whether application ID exist or not. Database error. "
                                + e1.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
            if (!achievementAccess.isAchievementIdExist(conn, appId, achievementId)) {
                objResponse.put("message", "Cannot update achievement. Achievement not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }

            AchievementModel currentAchievement = achievementAccess.getAchievementWithId(conn, appId,
                    achievementId);

            if (currentAchievement == null) {
                // currentAchievement is null
                objResponse.put("message", "Cannot update achievement. Achievement not found in database");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }

            FormDataPart partName = parts.get("achievementname");
            if (partName != null) {
                achievementname = partName.getContent();

                if (achievementname != null) {
                    currentAchievement.setName(achievementname);
                }
            }
            FormDataPart partDesc = parts.get("achievementdesc");
            if (partDesc != null) {
                // optional description text input form element
                achievementdesc = partDesc.getContent();
                if (achievementdesc != null) {
                    currentAchievement.setDescription(achievementdesc);
                }
            }
            FormDataPart partPV = parts.get("achievementpointvalue");
            if (partPV != null) {
                // optional description text input form element
                achievementpointvalue = Integer.parseInt(partPV.getContent());
                if (achievementpointvalue != 0) {
                    currentAchievement.setPointValue(achievementpointvalue);
                }
            }

            FormDataPart partBID = parts.get("achievementbadgeid");
            if (partBID != null) {
                // optional description text input form element
                achievementbadgeid = partBID.getContent();

                logger.info(achievementbadgeid);
                if (achievementbadgeid != null) {
                    if (achievementbadgeid.equals("")) {
                        achievementbadgeid = null;
                    }
                    currentAchievement.setBadgeId(achievementbadgeid);
                }
            }
            FormDataPart partNotificationCheck = parts.get("achievementnotificationcheck");
            if (partNotificationCheck != null) {
                // checkbox is checked
                currentAchievement.useNotification(true);
            } else {
                currentAchievement.useNotification(false);
            }

            FormDataPart partNotificationMsg = parts.get("achievementnotificationmessage");
            if (partNotificationMsg != null) {
                achievementnotifmessage = partNotificationMsg.getContent();
                if (achievementnotifmessage != null) {
                    currentAchievement.setNotificationMessage(achievementnotifmessage);
                }
            }
            achievementAccess.updateAchievement(conn, appId, currentAchievement);
            objResponse.put("message", "Achievement updated");
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_19, "" + randomLong);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_28, "" + name);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_29, "" + appId);

            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

        } catch (SQLException e) {
            e.printStackTrace();
            objResponse.put("message", "Cannot update achievement. DB Error. " + e.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

        }

    } catch (MalformedStreamException e) {
        // the stream failed to follow required syntax
        objResponse.put("message",
                "Cannot update achievement. Failed to upload " + achievementId + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
    } catch (IOException e) {
        // a read or write error occurred
        objResponse.put("message", "Cannot update achievement. Failed to upload " + achievementId + ".");
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot update achievement. DB Error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }

}

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

/**
 * Starts a sleep job and tries to kill the job using jobdetails.jsp as
 * (1) viewColleague (2) unauthorizedUser (3) modifyColleague
 * (4) viewAndModifyColleague (5) mrOwner (6) mrAdmin and
 * (7) jobSubmitter//from  ww w  . java 2s . co  m
 *
 * Validates the given jsp/servlet against different user names who
 * can(or cannot) do both view and modify on the job.
 * (1) jobSubmitter, mrOwner and mrAdmin can do both view and modify
 *     on 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-acls and job-modify-acls can do this
 * (3) user mentioned in job-view-acls but not in job-modify-acls cannot
 *     do this
 * (4) user mentioned in job-modify-acls but not in job-view-acls cannot
 *     do this
 * (5) qAdmin cannot do this because he doesn't have view access to the job
 * (6) other unauthorized users cannot do this
 *
 * @throws Exception
 */
private void validateJobDetailsJSPKillJob(MiniMRCluster cluster, JobConf clusterConf, String jtURL)
        throws Exception {

    JobConf conf = new JobConf(cluster.createJobConf());
    conf.set(JobContext.JOB_ACL_VIEW_JOB, viewColleague + " group3");

    // Let us add group1 and group3 to modify-job-acl. So modifyColleague and
    // viewAndModifyColleague will be able to modify the job
    conf.set(JobContext.JOB_ACL_MODIFY_JOB, " group1,group3");

    String jobTrackerJSP = jtURL + "/jobtracker.jsp?a=b";
    RunningJob job = startSleepJobAsUser(jobSubmitter, conf, cluster);
    org.apache.hadoop.mapreduce.JobID jobid = job.getID();
    // jobDetailsJSPKillJobAction url
    String url = jtURL + "/jobdetails.jsp?" + "action=kill&jobid=" + jobid.toString();
    try {
        assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, getHttpStatusCode(url, viewColleague, "POST"));
        assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, getHttpStatusCode(url, unauthorizedUser, "POST"));
        assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, getHttpStatusCode(url, modifyColleague, "POST"));

        assertEquals(HttpURLConnection.HTTP_OK, getHttpStatusCode(url, viewAndModifyColleague, "POST"));
        waitForKillJobToFinish(job);
        assertTrue("killJob using jobdetails.jsp failed for a job for which "
                + "user has job-view and job-modify permissions", job.isComplete());
    } finally {
        if (!job.isComplete()) {
            LOG.info("Killing job " + jobid + " from finally block");
            assertEquals(HttpURLConnection.HTTP_OK, getHttpStatusCode(
                    jobTrackerJSP + "&killJobs=true&jobCheckBox=" + jobid.toString(), jobSubmitter, "GET"));
        }
    }

    // check if jobSubmitter, mrOwner and mrAdmin can do
    // killJob using jobdetails.jsp url
    confirmJobDetailsJSPKillJobAsUser(cluster, conf, jtURL, jobTrackerJSP, jobSubmitter);
    confirmJobDetailsJSPKillJobAsUser(cluster, conf, jtURL, jobTrackerJSP, mrOwner);
    confirmJobDetailsJSPKillJobAsUser(cluster, conf, jtURL, jobTrackerJSP, mrAdminUser);
    confirmJobDetailsJSPKillJobAsUser(cluster, conf, jtURL, jobTrackerJSP, mrAdminGroupMember);
    confirmJobDetailsJSPKillJobAsUser(cluster, conf, jtURL, jobTrackerJSP, qAdmin);
}

From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java

private GetMethod connectInternal(String serverURL)
        throws MarshalException, ValidationException, HttpException, FogBugzClientException, IOException {
    WebClientUtil.setupHttpClient(httpClient, proxy, serverURL, null, null);

    for (int attempt = 0; attempt < 2; attempt++) {
        // force authentication
        if (!authenticated && hasAuthenticationCredentials()) {
            authenticate();/* w ww .  j  a va2s  .c  o m*/
        }
        String requestUrl = WebClientUtil.getRequestPath(serverURL + "&token=" + token);
        GetMethod method = new GetMethod(requestUrl);
        method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        int code;
        try {
            code = httpClient.executeMethod(method);
        } catch (IOException e) {
            method.releaseConnection();
            e.printStackTrace();
            throw e;
        }

        if (code == HttpURLConnection.HTTP_OK) {
            return method;
        } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) {
            // login or re-authenticate due to an expired session
            method.releaseConnection();
            authenticated = false;
            authenticate();
        } else {
            throw new FogBugzClientException("code = " + code);
        }
    }

    throw new FogBugzClientException("Session might have expired!");
}

From source file:com.microsoft.aad.adal.Oauth2.java

/**
 * extract AuthenticationResult object from response body if available
 * /*from w  w w. j a va 2  s  .  c  o  m*/
 * @param webResponse
 * @return
 */
private AuthenticationResult processTokenResponse(HttpWebResponse webResponse) throws AuthenticationException {
    AuthenticationResult result;
    String correlationIdInHeader = null;
    if (webResponse.getResponseHeaders() != null
            && webResponse.getResponseHeaders().containsKey(AuthenticationConstants.AAD.CLIENT_REQUEST_ID)) {
        // headers are returning as a list
        List<String> listOfHeaders = webResponse.getResponseHeaders()
                .get(AuthenticationConstants.AAD.CLIENT_REQUEST_ID);
        if (listOfHeaders != null && listOfHeaders.size() > 0) {
            correlationIdInHeader = listOfHeaders.get(0);
        }
    }

    final int statusCode = webResponse.getStatusCode();
    switch (statusCode) {
    case HttpURLConnection.HTTP_OK:
    case HttpURLConnection.HTTP_BAD_REQUEST:
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        try {
            result = parseJsonResponse(webResponse.getBody());
        } catch (final JSONException jsonException) {
            throw new AuthenticationException(ADALError.SERVER_INVALID_JSON_RESPONSE,
                    "Can't parse server response " + webResponse.getBody(), jsonException);
        }

        break;
    default:
        throw new AuthenticationException(ADALError.SERVER_ERROR,
                "Unexpected server response " + webResponse.getBody());
    }

    // Set correlationId in the result
    if (correlationIdInHeader != null && !correlationIdInHeader.isEmpty()) {
        try {
            UUID correlation = UUID.fromString(correlationIdInHeader);
            if (!correlation.equals(mRequest.getCorrelationId())) {
                Logger.w(TAG, "CorrelationId is not matching", "",
                        ADALError.CORRELATION_ID_NOT_MATCHING_REQUEST_RESPONSE);
            }

            Logger.v(TAG, "Response correlationId:" + correlationIdInHeader);
        } catch (IllegalArgumentException ex) {
            Logger.e(TAG, "Wrong format of the correlation ID:" + correlationIdInHeader, "",
                    ADALError.CORRELATION_ID_FORMAT, ex);
        }
    }

    return result;
}