Example usage for javax.servlet.http HttpServletResponse SC_NOT_ACCEPTABLE

List of usage examples for javax.servlet.http HttpServletResponse SC_NOT_ACCEPTABLE

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_NOT_ACCEPTABLE.

Prototype

int SC_NOT_ACCEPTABLE

To view the source code for javax.servlet.http HttpServletResponse SC_NOT_ACCEPTABLE.

Click Source Link

Document

Status code (406) indicating that the resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

Usage

From source file:org.dspace.rdf.negotiation.Negotiator.java

public static boolean sendRedirect(HttpServletResponse response, String handle, String extraPathInfo,
        int serialization, boolean redirectHTML) throws IOException {
    if (extraPathInfo == null)
        extraPathInfo = "";

    StringBuilder urlBuilder = new StringBuilder();
    String lang = null;//  ww w . j a  va2  s. co m
    switch (serialization) {
    case (Negotiator.UNSPECIFIED):
    case (Negotiator.WILDCARD): {
        lang = DEFAULT_LANG;
        break;
    }
    case (Negotiator.HTML): {
        lang = "html";
        break;
    }
    case (Negotiator.RDFXML): {
        lang = "rdf";
        break;
    }
    case (Negotiator.TURTLE): {
        lang = "turtle";
        break;
    }
    case (Negotiator.N3): {
        lang = "n3";
        break;
    }
    default: {
        lang = DEFAULT_LANG;
        break;
    }
    }
    assert (lang != null);

    if (StringUtils.isEmpty(handle)) {
        log.warn("Handle is empty, set it to Site Handle.");
        handle = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("handle.prefix")
                + "/0";
    }

    // don't redirect if HTML is requested and content negotiation is done
    // in a ServletFilter, as the ServletFilter should just let the request
    // pass.
    if ("html".equals(lang) && !redirectHTML) {
        return false;
    }

    // as we do content negotiation and we'll redirect the request, we 
    // should send a vary caching so browsers can adopt their caching strategy
    response.setHeader("Vary", "Accept");

    // if html is requested we have to forward to the repositories webui.
    if ("html".equals(lang)) {
        urlBuilder.append(
                DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.url"));
        if (!handle.equals(
                DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("handle.prefix")
                        + "/0")) {
            urlBuilder.append("/handle/");
            urlBuilder.append(handle).append("/").append(extraPathInfo);
        }
        String url = urlBuilder.toString();

        log.debug("Will forward to '" + url + "'.");
        response.setStatus(HttpServletResponse.SC_SEE_OTHER);
        response.setHeader("Location", url);
        response.flushBuffer();
        return true;
    }

    // currently we cannot serve statistics as rdf
    if ("statistics".equals(extraPathInfo)) {
        log.info("Cannot send statistics as RDF yet. => 406 Not Acceptable.");
        response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
        response.flushBuffer();
        return true;
    }

    // load the URI of the dspace-rdf module.
    urlBuilder.append(DSpaceServicesFactory.getInstance().getConfigurationService()
            .getProperty(RDFUtil.CONTEXT_PATH_KEY));
    if (urlBuilder.length() == 0) {
        log.error("Cannot load URL of dspace-rdf module. " + "=> 500 Internal Server Error");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.flushBuffer();
        return true;
    }
    // and build the uri to the DataProviderServlet
    urlBuilder.append("/handle/").append(handle);
    urlBuilder.append("/").append(lang);
    String url = urlBuilder.toString();
    log.debug("Will forward to '" + url + "'.");
    response.setStatus(HttpServletResponse.SC_SEE_OTHER);
    response.setHeader("Location", url);
    response.flushBuffer();
    return true;
}

From source file:com.homesnap.webserver.ControllerRestAPITest.java

@Test
public void test11DeleteControllerByGroup() {
    // Test impossible to create an existing controller
    deleteRequestJSONObject(urn_groups + "/1/controller?id=17", HttpServletResponse.SC_OK);
    deleteRequestJSONObject(urn_groups + "/1/17", HttpServletResponse.SC_NOT_ACCEPTABLE);

    JSONObject jo = deleteRequestJSONObject(urn_groups + "/1/16", HttpServletResponse.SC_OK);
    testController16(jo);/* w  w  w  . j  a v  a 2  s  .  com*/
    jo = getRequestJSONObject("/house/controllers/16");
    Assert.assertNull(jo);
    jo = getRequestJSONObject(urn_labels + "/ch1/16");
    Assert.assertNull(jo);

    jo = deleteRequestJSONObject(urn_groups + "/1/11", HttpServletResponse.SC_OK);
    testController11(jo);
}

From source file:org.apache.flink.client.web.JobsServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // check, if we are doing the right request
    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;//from   w w  w .  ja  va2  s .c o  m
    }

    // create the disk file factory, limiting the file size to 20 MB
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    fileItemFactory.setSizeThreshold(20 * 1024 * 1024); // 20 MB
    fileItemFactory.setRepository(tmpDir);

    String filename = null;

    // parse the request
    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        Iterator<FileItem> itr = ((List<FileItem>) uploadHandler.parseRequest(req)).iterator();

        // go over the form fields and look for our file
        while (itr.hasNext()) {
            FileItem item = itr.next();
            if (!item.isFormField()) {
                if (item.getFieldName().equals("upload_jar_file")) {

                    // found the file, store it to the specified location
                    filename = item.getName();
                    File file = new File(destinationDir, filename);
                    item.write(file);
                    break;
                }
            }
        }
    } catch (FileUploadException ex) {
        resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Invalid Fileupload.");
        return;
    } catch (Exception ex) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An unknown error occurred during the file upload.");
        return;
    }

    // write the okay message
    resp.sendRedirect(targetPage);
}

From source file:org.wso2.carbon.analytics.servlet.AnalyticsTableProcessor.java

/**
 * create table// w  ww .  jav  a  2 s.  c  o  m
 *
 * @param req HttpRequest which has the required parameters to do the operation.
 * @param resp HttpResponse which returns the result of the intended operation.
 * @throws ServletException
 * @throws IOException
 */
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String sessionId = req.getHeader(AnalyticsAPIConstants.SESSION_ID);
    if (sessionId == null || sessionId.trim().isEmpty()) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
    } else {
        try {
            ServiceHolder.getAuthenticator().validateSessionId(sessionId);
        } catch (AnalyticsAPIAuthenticationException e) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
        }
        String operation = req.getParameter(AnalyticsAPIConstants.OPERATION);
        boolean securityEnabled = Boolean
                .parseBoolean(req.getParameter(AnalyticsAPIConstants.ENABLE_SECURITY_PARAM));
        int tenantId = MultitenantConstants.INVALID_TENANT_ID;
        if (!securityEnabled)
            tenantId = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.TENANT_ID_PARAM));
        String userName = req.getParameter(AnalyticsAPIConstants.USERNAME_PARAM);
        if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.CREATE_TABLE_OPERATION)) {
            String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
            String recordStoreName = req.getParameter(AnalyticsAPIConstants.RECORD_STORE_NAME_PARAM);
            try {
                if (!securityEnabled) {
                    if (recordStoreName == null) {
                        ServiceHolder.getAnalyticsDataService().createTable(tenantId, tableName);
                    } else {
                        ServiceHolder.getAnalyticsDataService().createTable(tenantId, recordStoreName,
                                tableName);
                    }
                } else {
                    if (recordStoreName == null) {
                        ServiceHolder.getSecureAnalyticsDataService().createTable(userName, tableName);
                    } else {
                        ServiceHolder.getSecureAnalyticsDataService().createTable(userName, recordStoreName,
                                tableName);
                    }
                }
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else if (operation != null && operation.trim()
                .equalsIgnoreCase(AnalyticsAPIConstants.CREATE_IF_NOT_EXISTS_TABLE_OPERATION)) {
            String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
            String recordStoreName = req.getParameter(AnalyticsAPIConstants.RECORD_STORE_NAME_PARAM);
            try {
                if (!securityEnabled) {
                    ServiceHolder.getAnalyticsDataService().createTableIfNotExists(tenantId, recordStoreName,
                            tableName);
                } else {
                    ServiceHolder.getSecureAnalyticsDataService().createTableIfNotExists(userName,
                            recordStoreName, tableName);
                }
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "unsupported operation performed with post request!");
            log.error("unsupported operation performed : " + operation + " with post request!");
        }
    }
}

From source file:org.apache.hadoop.hdfs.qjournal.server.UploadImageServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        OutputStream os = null;//from  ww w . j  a v  a  2 s . c  o  m
        SessionDescriptor sd = null;
        try {
            byte buf[] = new byte[BUFFER_SIZE];

            // parse upload parameters
            UploadImageParam params = new UploadImageParam(request);

            ServletContext context = getServletContext();
            // obtain session descriptor
            if (params.segmentId == 0) {
                // new upload
                sd = startImageUpload(params, context);
            } else {
                // resumed upload
                sd = resumeImageUpload(params, context);
            }

            os = sd.os;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            List<?> items = upload.parseRequest(request);
            if (items.size() != 1) {
                throwIOException("Should have one item in the multipart contents.");
            }
            FileItem item = (FileItem) items.get(0);

            // write to the local output stream
            if (!item.isFormField()) {
                InputStream is = item.getInputStream();
                int num = 1;
                while (num > 0) {
                    num = is.read(buf);
                    if (num <= 0) {
                        break;
                    }
                    os.write(buf, 0, num);
                }
            }

            // close if needed
            if (params.completed) {
                os.flush();
                sessions.remove(sd.sessionId);
                MD5Hash hash = new MD5Hash(sd.digester.digest());
                os.close();
                InjectionHandler.processEventIO(InjectionEvent.UPLOADIMAGESERVLET_COMPLETE, context, hash);
                // store hash to compare it when rolling the image
                sd.journal.setCheckpointImageDigest(sd.txid, hash);
            }

            // pass the sessionId in the response
            response.setHeader("sessionId", Long.toString(sd.sessionId));
        } catch (Exception e) {
            // cleanup this session
            IOUtils.cleanup(LOG, os);
            sessions.remove(sd != null ? sd.sessionId : -1);
            LOG.error("Error when serving request", e);
            response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, e.toString());
        }
    } else {
        LOG.error("Error when serving request, not multipart content.");
    }
}

From source file:edu.umd.cs.submitServer.servlets.ReportTestOutcomes.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // will be set by MultipartRequestFilter
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);

    Timestamp now = new Timestamp(System.currentTimeMillis());

    // Insert test outcomes into database,
    // create new TestRun
    // and update submission as having been tested.
    Connection conn = null;//from www  . ja v  a  2 s .com
    boolean transactionSuccess = false;
    try {
        // Get submission pk and the submission
        @Submission.PK
        int submissionPK = Submission.asPK(multipartRequest.getIntParameter("submissionPK"));

        String courses = multipartRequest.getStringParameter("courses");

        // Get the testSetupPK
        int testSetupPK = multipartRequest.getIntParameter("testSetupPK");
        boolean newTestSetup = multipartRequest.getBooleanParameter("newTestSetup");
        boolean isBackgroundRetest = multipartRequest.getBooleanParameter("isBackgroundRetest");
        String load = multipartRequest.getOptionalStringParameter("load");

        if (load == null)
            load = "unknown";
        String kindString = multipartRequest.getOptionalStringParameter("kind");
        Kind kind = Kind.UNKNOWN;
        if (kindString != null) {
            try {
                kind = Kind.valueOf(kindString);
            } catch (RuntimeException e) {
                // ignore
            }

        }

        String remoteHost = SubmitServerFilter.getRemoteHost(request);
        // Get test machine (if specified)
        String testMachine = multipartRequest.getOptionalStringParameter("hostname");
        if (testMachine == null)
            testMachine = multipartRequest.getOptionalStringParameter("testMachine");
        if (testMachine == null)
            testMachine = "unknown";

        CodeMetrics codeMetrics = getCodeMetrics(multipartRequest);
        int testDurationsMillis = multipartRequest.getIntegerParameter("testDurationsMillis", 0);

        // Read into TestOutcomeCollection in memory
        TestOutcomeCollection testOutcomeCollection = TestOutcomeCollection
                .deserialize(getfileItemDataAndDelete(multipartRequest));

        logHotspotErrors(submissionPK, testSetupPK, testMachine, testOutcomeCollection);

        conn = getConnection();

        Submission submission = Submission.lookupBySubmissionPK(submissionPK, conn);

        if (submission == null) {
            throw new ServletException(
                    "submissionPK " + submissionPK + " does not refer to a submission in the database");
        }

        StudentRegistration studentRegistration = StudentRegistration
                .lookupByStudentRegistrationPK(submission.getStudentRegistrationPK(), conn);
        @Student.PK
        Integer studentPK = studentRegistration.getStudentPK();
        Project project = Project.getByProjectPK(submission.getProjectPK(), conn);

        TestSetup testSetup = TestSetup.lookupByTestSetupPK(testSetupPK, conn);
        Integer canonicalTestRunPK = testSetup.getTestRunPK();
        if (newTestSetup && (testSetup.getStatus() == TestSetup.Status.TESTED
                || testSetup.getStatus() == TestSetup.Status.ACTIVE)) {
            newTestSetup = false;
        }
        BuildServer.insertOrUpdateSuccess(conn, testMachine, remoteHost, now, load, submission);

        // Validate buildserver
        Collection<Integer> allowedCourses = RequestSubmission.getCourses(conn, courses);

        if (allowedCourses.isEmpty()) {
            ServerError.insert(conn, ServerError.Kind.BAD_AUTHENTICATION, studentPK, studentPK,
                    project.getCoursePK(), project.getProjectPK(), submission.getSubmissionPK(), "",
                    "Build server " + testMachine
                            + " reporting outcome but does not provide any valid credentials",
                    "", this.getClass().getSimpleName(), "", "", remoteHost, "", "", null);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authorized");
            return;
        }

        if (!allowedCourses.contains(project.getCoursePK())) {
            ServerError.insert(conn, ServerError.Kind.BAD_AUTHENTICATION, studentPK, studentPK,
                    project.getCoursePK(), project.getProjectPK(), submission.getSubmissionPK(), "",
                    "Build server " + testMachine
                            + " reporting outcome for course it is not authorized to do so",
                    "", this.getClass().getSimpleName(), "", "", remoteHost, "", "", null);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authorized");
            return;
        }

        TestRun canonicalTestRun = TestRun.lookupByTestRunPK(canonicalTestRunPK, conn);
        if (!newTestSetup) {
            if (canonicalTestRun == null || canonicalTestRun.getTestSetupPK() != testSetupPK) {
                ServerError.insert(conn, ServerError.Kind.UNKNOWN, studentPK, studentPK, project.getCoursePK(),
                        project.getProjectPK(), submission.getSubmissionPK(), "",
                        "Discarding stale build server result", "", this.getClass().getSimpleName(), "", "",
                        remoteHost, "", "", null);
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "not current test setup");
                return;
            }

            // Set point totals

            TestOutcomeCollection canonicalTestOutcomeCollection = TestOutcomeCollection
                    .lookupByTestRunPK(canonicalTestRun.getTestRunPK(), conn);
            Map<String, TestOutcome> canonicalTestOutcomeMap = new HashMap<String, TestOutcome>();
            for (TestOutcome testOutcome : canonicalTestOutcomeCollection.getAllOutcomes()) {
                if (testOutcome.isCardinalTestType())
                    canonicalTestOutcomeMap.put(testOutcome.getTestName(), testOutcome);
            }

            for (TestOutcome testOutcome : testOutcomeCollection.getAllOutcomes())
                if (testOutcome.isCardinalTestType()
                        && !testOutcome.getOutcome().equals(TestOutcome.COULD_NOT_RUN)) {
                    TestOutcome canonicalTestOutcome = canonicalTestOutcomeMap.get(testOutcome.getTestName());
                    if (canonicalTestOutcome == null
                            || !canonicalTestOutcome.getTestType().equals(testOutcome.getTestType())) {
                        String message = "Did not find matching canonical test outcome for "
                                + testOutcome.getTestName() + " with outcome " + testOutcome.getOutcome();
                        ServerError.insert(conn, ServerError.Kind.UNKNOWN, studentPK, studentPK,
                                project.getCoursePK(), project.getProjectPK(), submission.getSubmissionPK(), "",
                                message, "", this.getClass().getSimpleName(), "", "", remoteHost, "", "", null);
                        response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, message);
                        return;
                    }

                    testOutcome.setPointValue(canonicalTestOutcome.getPointValue());

                }
        } else {

            // new test setup

            // set all point values to 1
            for (TestOutcome testOutcome : testOutcomeCollection) {
                testOutcome.setPointValue(1);
            }
        }

        getSubmitServerServletLog().info("Reporting test outcome for submissionPK = " + submissionPK
                + ", testSetupPK = " + testSetupPK + " performed by " + testMachine + ", kind = " + kind);

        // Background Retests:
        // If this was a background re-test, then we need to take special
        // steps.
        // This was a background-retest if:
        // 1) The BuildServer says that this was a background retest
        // 2) or the status has been left as "complete" or has been
        // explicitly marked "background"
        if (isBackgroundRetest
                || !newTestSetup && submission.getBuildStatus().equals(Submission.BuildStatus.COMPLETE)) {

            // Look up current testOutcomeCollection
            TestOutcomeCollection currentTestOutcomeCollection = TestOutcomeCollection
                    .lookupByTestRunPK(submission.getCurrentTestRunPK(), conn);

            // Look up the testRun for the current TestOutcomeCollection
            TestRun currentTestRun = TestRun.lookupByTestRunPK(submission.getCurrentTestRunPK(), conn);
            if (currentTestRun == null)
                getSubmitServerServletLog().warn("Unable to find test run " + submission.getCurrentTestRunPK());
            if (currentTestRun == null || currentTestRun.getTestSetupPK() != testSetupPK) {
                // Retest was against a different jarfile than the current
                // one;
                // for now just ignore this run.

                return;
            }

            // Compare the cardinal test outcomes from the two
            // outcomeCollections
            String differences = compareCardinalOutcomes(currentTestOutcomeCollection, testOutcomeCollection,
                    submissionPK, testSetupPK, testMachine);

            if (differences == null) {
                // If the results are the same, great! We have more
                // confidence that this result is correct.
                submission.incrementNumSuccessfulBackgroundRetests();

                getSuccessfulBackgroundRetestLog().info("Corroborating run for submissionPK = " + submissionPK
                        + ", testSetupPK = " + testSetupPK + " performed by " + testMachine);
            } else if (differences.equals("skip")) {
                // There may have been differences but we don't care
                // We don't re-test "could_not_run" results
                return;
            } else {
                // If the results differ, log which test cases were
                // different
                submission.incrementNumFailedBackgroundRetests();
                // TODO: RSS feed
                getFailedBackgroundRetestLog().warn(differences);
                // XXX Should I insert differing outcomes into the database
                // as re-tests?
                if (currentTestOutcomeCollection.getValuePassedOverall() < testOutcomeCollection
                        .getValuePassedOverall())
                    isBackgroundRetest = false;

            }
            submission.update(conn);

            // If there were no differences, commit what we've done and
            // exit.
            if (differences == null)
                return;
        } // isBackgroundRetest

        conn = switchToTransaction(conn);

        // * Create new TestRun row
        // * increment numTestOutcomes in submissions table
        // * set currentTestRunPK in submissions table
        // * set testRunPK in all the testOutcomes
        // * write the testoutcomes to the disk

        // Create new TestRun row.
        TestRun testRun = createTestRun(submissionPK, testSetupPK, testMachine, testOutcomeCollection,
                codeMetrics, now, testDurationsMillis);

        // perform insert
        testRun.insert(conn);
        BuildServer.updateLastTestRun(conn, testMachine, testRun);

        // Insert a new codeMetrics row if we have codeMetrics data to
        // insert
        // codeMetrics data is keyed to the testRunPK
        if (codeMetrics.getCodeSegmentSize() > 0) {
            codeMetrics.setTestRunPK(testRun.getTestRunPK());
            codeMetrics.insert(conn);
        }

        // update the testRunPK of the testOutcomes we've been sent from the
        // BuildServer
        // with the testRunPK of the row we just inserted
        testOutcomeCollection.updateTestRunPK(testRun.getTestRunPK());

        // increment the number of test outcomes
        submission.setNumTestRuns(submission.getNumTestRuns() + 1);

        // Next, insert the test outcomes
        testOutcomeCollection.insert(conn);

        // if this was a new project jarfile being tested against the
        // canonical account
        if (newTestSetup) {
            getSubmitServerServletLog().info("Ran new test setup, submissionPK = " + submissionPK
                    + ", testSetupPK = " + testSetupPK + " performed by " + testMachine + ", kind = " + kind);

            // lookup the pending project

            testSetup.setValueTotalTests(testOutcomeCollection.getValuePassedOverall());
            testSetup.setValuePublicTests(testOutcomeCollection.getValuePublicTests());
            testSetup.setValueReleaseTests(testOutcomeCollection.getValueReleaseTests());
            testSetup.setValueSecretTests(testOutcomeCollection.getValueSecretTests());

            testSetup.setTestRunPK(testRun.getTestRunPK());

            if (!testOutcomeCollection.isCompileSuccessful() || testOutcomeCollection.getNumFailedOverall() > 0
                    || testOutcomeCollection.getCouldNotRunAnyCardinalTests()) {
                // If any tests have failed, then set status to failed
                testSetup.setStatus(TestSetup.Status.FAILED);
            } else {
                testSetup.setStatus(TestSetup.Status.TESTED);
            }
            getSubmitServerServletLog().info("Ran new test setup, submissionPK = " + submissionPK
                    + ", testSetupPK = " + testSetupPK + " performed by " + testMachine + ", kind = " + kind
                    + ", status = " + testSetup.getStatus());

            // update pending testSetup to reflect the changes just
            // made
            testSetup.update(conn);
        }

        // Only change information about the current test_run if this
        // run used the most recent testSetup
        if (!isBackgroundRetest && (newTestSetup || testRun.getTestSetupPK() == project.getTestSetupPK())) {
            // update the pass/fail/warning stats
            submission.setCurrentTestRunPK(testRun.getTestRunPK());

            // Ensure that submission is not release eligible if the
            // student_submit_status.can_release_test is false
            StudentSubmitStatus submitStatus = StudentSubmitStatus.lookupByStudentRegistrationPKAndProjectPK(
                    submission.getStudentRegistrationPK(), submission.getProjectPK(), conn);
            boolean canReleaseTest = (submitStatus == null) || submitStatus.getCanReleaseTest();
            submission.setReleaseEligible(testOutcomeCollection.isReleaseEligible() && canReleaseTest);

            // if project's release policy is anytime, then make it release
            // eligible
            if (Project.ANYTIME.equals(project.getReleasePolicy()))
                submission.setReleaseEligible(canReleaseTest);

            submission.setValuePassedOverall(testOutcomeCollection.getValuePassedOverall());
            submission.setCompileSuccessful(testOutcomeCollection.isCompileSuccessful());
            submission.setValuePublicTestsPassed(testOutcomeCollection.getValuePublicTestsPassed());
            submission.setValueReleaseTestsPassed(testOutcomeCollection.getValueReleaseTestsPassed());
            submission.setValueSecretTestsPassed(testOutcomeCollection.getValueSecretTestsPassed());
            submission.setNumFindBugsWarnings(testOutcomeCollection.getNumFindBugsWarnings());

            // If we're re-setting the currentTestRunPK, then find any
            // existing
            // backgroundRetests and clear them. Background re-tests are
            // always compared
            // to the current set of testOutcomes.
            submission.setNumFailedBackgroundRetests(0);
            submission.setNumSuccessfulBackgroundRetests(0);
            submission.setNumPendingBuildRequests(0);

        }
        // perform update
        // Update the status of the submission
        submission.setBuildStatus(Submission.BuildStatus.COMPLETE);
        submission.update(conn);
        getSubmitServerServletLog().info("Completed testing submissionPK = " + submissionPK + ", testSetupPK = "
                + testSetupPK + " performed by " + testMachine + ", kind = " + kind + ", status = "
                + testSetup.getStatus());

        conn.commit();
        transactionSuccess = true;
    } catch (InvalidRequiredParameterException e) {
        throw new ServletException(e);
    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn);
    }
}

From source file:org.dataconservancy.ui.api.FileController.java

boolean failAcceptHeader(HttpServletRequest request, HttpServletResponse response, String acceptMimeType,
        String fileMimeType) throws IOException {
    if (acceptMimeType == null || fileMimeType == null) {
        return false;
    }/*from  ww w . j a va  2 s.  com*/
    if (MimeTypeComparator.isAcceptableMimeType(acceptMimeType, fileMimeType)) {
        return false;
    }
    response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
            String.format(
                    "File with id matching %s"
                            + " did not have an acceptable mime type (%s) as specified by the request header",
                    requestUtil.buildRequestUrl(request), acceptMimeType));
    return true;
}

From source file:org.wso2.carbon.analytics.servlet.AnalyticsSearchProcessor.java

/**
 * Search the table//from   www  .j av  a2s  .  co  m
 *
 * @param req  HttpRequest which has the required parameters to do the operation.
 * @param resp HttpResponse which returns the result of the intended operation.
 * @throws ServletException
 * @throws IOException
 */
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String sessionId = req.getHeader(AnalyticsAPIConstants.SESSION_ID);
    if (sessionId == null || sessionId.trim().isEmpty()) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
    } else {
        try {
            ServiceHolder.getAuthenticator().validateSessionId(sessionId);
        } catch (AnalyticsAPIAuthenticationException e) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
        }
        String operation = req.getParameter(AnalyticsAPIConstants.OPERATION);
        boolean securityEnabled = Boolean
                .parseBoolean(req.getParameter(AnalyticsAPIConstants.ENABLE_SECURITY_PARAM));
        int tenantIdParam = MultitenantConstants.INVALID_TENANT_ID;
        if (!securityEnabled)
            tenantIdParam = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.TENANT_ID_PARAM));
        String userName = req.getParameter(AnalyticsAPIConstants.USERNAME_PARAM);
        String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
        String query = req.getParameter(AnalyticsAPIConstants.QUERY);
        if (operation != null && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.SEARCH_OPERATION)) {
            int start = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.START_PARAM));
            int count = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.COUNT_PARAM));
            Type sortByFieldType = new TypeToken<List<SortByField>>() {
            }.getType();
            Gson gson = new Gson();
            List<SortByField> sortByFields = gson
                    .fromJson(req.getParameter(AnalyticsAPIConstants.SORT_BY_FIELDS_PARAM), sortByFieldType);
            try {
                List<SearchResultEntry> searchResult;
                if (!securityEnabled)
                    searchResult = ServiceHolder.getAnalyticsDataService().search(tenantIdParam, tableName,
                            query, start, count, sortByFields);
                else
                    searchResult = ServiceHolder.getSecureAnalyticsDataService().search(userName, tableName,
                            query, start, count, sortByFields);
                //Have to do this because there is possibility of getting sublist which cannot be serialized
                searchResult = new ArrayList<>(searchResult);
                resp.getOutputStream().write(GenericUtils.serializeObject(searchResult));
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.SEARCH_COUNT_OPERATION)) {
            try {
                int count;
                if (!securityEnabled)
                    count = ServiceHolder.getAnalyticsDataService().searchCount(tenantIdParam, tableName,
                            query);
                else
                    count = ServiceHolder.getSecureAnalyticsDataService().searchCount(userName, tableName,
                            query);
                PrintWriter output = resp.getWriter();
                output.append(AnalyticsAPIConstants.SEARCH_COUNT).append(AnalyticsAPIConstants.SEPARATOR)
                        .append(String.valueOf(count));
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.SEARCH_WITH_AGGREGATES_OPERATION)) {
            try {
                Gson gson = new Gson();
                AnalyticsIterator<Record> iterator;
                String groupByField = req.getParameter(AnalyticsAPIConstants.GROUP_BY_FIELD_PARAM);
                Type aggregateFieldsMapType = new TypeToken<List<AggregateField>>() {
                }.getType();
                List<AggregateField> fields = gson.fromJson(
                        req.getParameter(AnalyticsAPIConstants.AGGREGATING_FIELDS), aggregateFieldsMapType);
                String parentPathAsString = req.getParameter(AnalyticsAPIConstants.AGGREGATE_PARENT_PATH);
                Type aggregateParentPath = new TypeToken<List<String>>() {
                }.getType();
                List<String> parentPath = gson.fromJson(parentPathAsString, aggregateParentPath);
                int aggregateLevel = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.AGGREGATE_LEVEL));
                int noOfRecords = Integer
                        .parseInt(req.getParameter(AnalyticsAPIConstants.AGGREGATE_NO_OF_RECORDS));
                AggregateRequest aggregateRequest = new AggregateRequest();
                aggregateRequest.setTableName(tableName);
                aggregateRequest.setQuery(query);
                aggregateRequest.setFields(fields);
                aggregateRequest.setGroupByField(groupByField);
                aggregateRequest.setAggregateLevel(aggregateLevel);
                aggregateRequest.setParentPath(parentPath);
                aggregateRequest.setNoOfRecords(noOfRecords);
                if (!securityEnabled)
                    iterator = ServiceHolder.getAnalyticsDataService().searchWithAggregates(tenantIdParam,
                            aggregateRequest);
                else
                    iterator = ServiceHolder.getSecureAnalyticsDataService().searchWithAggregates(userName,
                            aggregateRequest);
                while (iterator.hasNext()) {
                    Record record = iterator.next();
                    GenericUtils.serializeObject(record, resp.getOutputStream());
                }
                iterator.close();
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "unsupported operation performed with get request!");
            log.error("unsupported operation performed : " + operation + " with get request!");
        }
    }
}

From source file:org.wso2.carbon.analytics.servlet.AnalyticsIndexProcessor.java

/**
 * Re-index the records in the given timestamp period.
 *
 * @param req  HttpRequest which has the required parameters to do the operation.
 * @param resp HttpResponse which returns the result of the intended operation.
 * @throws ServletException// ww  w  .  j  ava2  s . c o  m
 * @throws IOException
 */

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String sessionId = req.getHeader(AnalyticsAPIConstants.SESSION_ID);
    if (sessionId == null || sessionId.trim().isEmpty()) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
    } else {
        try {
            ServiceHolder.getAuthenticator().validateSessionId(sessionId);
        } catch (AnalyticsAPIAuthenticationException e) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
        }
        String operation = req.getParameter(AnalyticsAPIConstants.OPERATION);
        boolean securityEnabled = Boolean
                .parseBoolean(req.getParameter(AnalyticsAPIConstants.ENABLE_SECURITY_PARAM));
        if (operation != null && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.REINDEX_OPERATION)) {
            int tenantIdParam = MultitenantConstants.INVALID_TENANT_ID;
            if (!securityEnabled)
                tenantIdParam = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.TENANT_ID_PARAM));
            String userName = req.getParameter(AnalyticsAPIConstants.USERNAME_PARAM);
            String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
            long timeFrom = Long.parseLong(req.getParameter(AnalyticsAPIConstants.TIME_FROM_PARAM));
            long timeTo = Long.parseLong(req.getParameter(AnalyticsAPIConstants.TIME_TO_PARAM));
            try {
                if (!securityEnabled)
                    ServiceHolder.getAnalyticsDataService().reIndex(tenantIdParam, tableName, timeFrom, timeTo);
                else
                    ServiceHolder.getSecureAnalyticsDataService().reIndex(userName, tableName, timeFrom,
                            timeTo);
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "unsupported operation performed with get request!");
            log.error("unsupported operation performed : " + operation + " with get request!");
        }
    }
}

From source file:org.accada.epcis.repository.capture.CaptureOperationsServlet.java

/**
 * Implements the EPCIS capture operation. Takes HTTP POST request, extracts
 * the payload into an XML document, validates the document against the
 * EPCIS schema, and captures the EPCIS events given in the document. Errors
 * are caught and returned as simple plaintext messages via HTTP.
 * //ww  w.j  av  a2  s  .co  m
 * @param req
 *            The HttpServletRequest.
 * @param rsp
 *            The HttpServletResponse.
 * @throws IOException
 *             If an error occurred while validating the request or writing
 *             the response.
 */
public void doPost(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException {
    LOG.info("EPCIS Capture Interface invoked.");
    rsp.setContentType("text/plain");
    final PrintWriter out = rsp.getWriter();

    InputStream is = null;
    // check if we have a POST request with form parameters
    if ("application/x-www-form-urlencoded".equalsIgnoreCase(req.getContentType())) {
        // check if the 'event' or 'dbReset' form parameter are given
        String event = req.getParameter("event");
        String dbReset = req.getParameter("dbReset");
        if (event != null) {
            LOG.info("Found deprecated 'event=' parameter. Refusing to process request.");
            String msg = "Starting from version 0.2.2, the EPCIS repository does not accept the EPCISDocument in the HTTP POST form parameter 'event' anymore. Please provide the EPCISDocument as HTTP POST payload instead.";
            rsp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            out.println(msg);
        } else if (dbReset != null && dbReset.equalsIgnoreCase("true")) {
            LOG.debug("Found 'dbReset' parameter set to 'true'.");
            rsp.setContentType("text/plain");
            try {
                captureOperationsModule.doDbReset();
                String msg = "db reset successfull";
                LOG.info(msg);
                rsp.setStatus(HttpServletResponse.SC_OK);
                out.println(msg);
            } catch (SQLException e) {
                String msg = "An error involving the database occurred";
                LOG.error(msg, e);
                rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.println(msg);
            } catch (IOException e) {
                String msg = "An unexpected error occurred";
                LOG.error(msg, e);
                rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.println(msg);
            } catch (UnsupportedOperationException e) {
                String msg = "'dbReset' operation not allowed!";
                LOG.info(msg);
                rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
                out.println(msg);
            }
        }
        out.flush();
        out.close();
        return;
    } else {
        is = req.getInputStream();
        try {
            captureOperationsModule.doCapture(is, req.getUserPrincipal());
            rsp.setStatus(HttpServletResponse.SC_OK);
            out.println("Capture request succeeded.");
        } catch (SAXException e) {
            String msg = "An error processing the XML document occurred";
            LOG.error(msg, e);
            rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println(msg);
        } catch (InvalidFormatException e) {
            String msg = "An error parsing the XML contents occurred";
            LOG.error(msg, e);
            rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println(msg);
        } catch (final Exception e) {
            String msg = "An unexpected error occurred";
            LOG.error(msg, e);
            rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.println(msg);
        }

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