public Problem[] getProblemsForUser(Course course, int userId)
      throws CloudCoderAuthenticationException {
    // Make sure user is authenticated
    User user = Database.getInstance().getUserGivenId(userId);

    List<Problem> resultList =
        Database.getInstance().getProblemsInCourse(user, course).getProblemList();
    for (Problem p : resultList) {
      logger.warn(p.getTestname() + " - " + p.getBriefDescription());
    }

    return resultList.toArray(new Problem[resultList.size()]);
  }
  @Override
  public Problem[] getProblems(Course course) throws CloudCoderAuthenticationException {
    // Make sure user is authenticated
    User user =
        ServletUtil.checkClientIsAuthenticated(
            getThreadLocalRequest(), GetCoursesAndProblemsServiceImpl.class);

    List<Problem> resultList =
        Database.getInstance().getProblemsInCourse(user, course).getProblemList();
    for (Problem p : resultList) {
      logger.info(p.getTestname() + " - " + p.getBriefDescription());
    }

    return resultList.toArray(new Problem[resultList.size()]);
  }
    @Override
    public void activate(final Session session, final SubscriptionRegistrar subscriptionRegistrar) {
      // Add a ProblemSubmissionHistory object to the session.
      ProblemSubmissionHistory history = new ProblemSubmissionHistory();
      session.add(history);

      // FIXME: for now, subscribe the page directly to the ProblemSubmissionHistory
      // Eventually, only the various views should be subscribed
      history.subscribe(
          ProblemSubmissionHistory.Event.SET_SUBMISSION_RECEIPT_LIST, this, subscriptionRegistrar);
      history.subscribe(ProblemSubmissionHistory.Event.SET_SELECTED, this, subscriptionRegistrar);

      // FIXME: also subscribe to session add object events
      session.subscribe(Session.Event.ADDED_OBJECT, this, subscriptionRegistrar);

      // Show username, problem name and description
      Problem problem = session.get(Problem.class);
      UserSelection userSelection = session.get(UserSelection.class);
      usernameAndProblemLabel.setText(
          userSelection.getUser().getUsername() + ", " + problem.toNiceString());

      // Activate views
      pageNavPanel.setBackHandler(new PageBackHandler(session));
      pageNavPanel.setLogoutHandler(new LogoutHandler(session));
      sliderView.activate(session, subscriptionRegistrar);
      problemTextView.activate(session, subscriptionRegistrar);
      statusMessageView.activate(session, subscriptionRegistrar);
      testOutcomeSummaryView.activate(session, subscriptionRegistrar);
      testResultListView.activate(session, subscriptionRegistrar);

      // Get all SubmissionReceipts for this user on this problem
      RPC.getCoursesAndProblemsService.getAllSubmissionReceiptsForUser(
          problem,
          userSelection.getUser(),
          new AsyncCallback<SubmissionReceipt[]>() {
            @Override
            public void onSuccess(SubmissionReceipt[] result) {
              onLoadSubmissionReceipts(result);
            }

            @Override
            public void onFailure(Throwable caught) {
              session.add(StatusMessage.error("Could not get submission receipts", caught));
            }
          });
    }
  @Override
  public void submit(int problemId, String programText)
      throws CloudCoderAuthenticationException, SubmissionException {
    // Make sure that client is authenticated and has permission to edit the given problem
    User user = ServletUtil.checkClientIsAuthenticated(getThreadLocalRequest());

    HttpSession session = getThreadLocalRequest().getSession();

    // The Problem should be stored in the user's session
    Problem problem = (Problem) session.getAttribute(SessionAttributeKeys.PROBLEM_KEY);
    if (problem == null || problem.getProblemId() != problemId) {
      throw new CloudCoderAuthenticationException();
    }

    // Insert a full-text change into the database.
    Change fullTextChange =
        new Change(
            ChangeType.FULL_TEXT,
            0,
            0,
            0,
            0,
            System.currentTimeMillis(),
            user.getId(),
            problem.getProblemId(),
            programText);
    Database.getInstance().storeChanges(new Change[] {fullTextChange});

    // Get test cases.  (TODO: cache them?)
    List<TestCase> testCaseList = Database.getInstance().getTestCasesForProblem(problemId);

    ISubmitService submitService = DefaultSubmitService.getInstance();

    logger.info("Passing submission to submit service...");
    IFutureSubmissionResult future = submitService.submitAsync(problem, testCaseList, programText);

    // Put the full-text Change and IFutureSubmissionResult in the user's session.
    addSessionObjects(session, fullTextChange, future);
  }
Example #5
0
  private void onProblemSelected(Problem selectedProblem) {
    ProblemAndSubmissionReceipt[] data = page.getSession().get(ProblemAndSubmissionReceipt[].class);
    SingleSelectionModel<? super ProblemAndSubmissionReceipt> sm =
        (SingleSelectionModel<? super ProblemAndSubmissionReceipt>) cellTable.getSelectionModel();
    for (ProblemAndSubmissionReceipt p : data) {
      if (p.getProblem().getProblemId().equals(selectedProblem.getProblemId())) {
        // Found the selected problem, so change the selected row
        sm.clear();
        sm.setSelected(p, true);
        return;
      }
    }

    // The selected problem isn't being viewed currently,
    // so just clear the selection
    sm.clear();
  }
  @Override
  public SubmissionReceipt[] getAllSubmissionReceiptsForUser(Problem problem, User user)
      throws CloudCoderAuthenticationException {
    // Make sure user is authenticated
    User authenticatedUser =
        ServletUtil.checkClientIsAuthenticated(
            getThreadLocalRequest(), GetCoursesAndProblemsServiceImpl.class);

    // Make sure authenticated user is an instructor
    CourseRegistrationList regList =
        Database.getInstance().findCourseRegistrations(authenticatedUser, problem.getCourseId());
    if (!regList.isInstructor()) {
      return new SubmissionReceipt[0];
    }

    return Database.getInstance().getAllSubmissionReceiptsForUser(problem, user);
  }
  @Override
  public ShareExercisesResult submitExercises(
      Problem[] problems, String repoUsername, String repoPassword)
      throws CloudCoderAuthenticationException {
    logger.warn("Sharing " + problems.length + " exercises");

    // create the result place holder
    ShareExercisesResult result = new ShareExercisesResult(problems.length);

    if (problems.length == 0) {
      result.failAll("No problems to be shared!");
      return result;
    }

    // Only a course instructor may share an exercise.
    User authenticatedUser =
        ServletUtil.checkClientIsAuthenticated(
            getThreadLocalRequest(), GetCoursesAndProblemsServiceImpl.class);
    Course course = new Course();
    course.setId(problems[0].getCourseId());
    Database.getInstance().reloadModelObject(course);
    CourseRegistrationList regList =
        Database.getInstance().findCourseRegistrations(authenticatedUser, course);
    if (!regList.isInstructor()) {
      result.failAll("You must be an instructor to share an exercise");
      return result;
    }

    // Get the exercise repository URL
    ConfigurationSetting repoUrlSetting =
        Database.getInstance().getConfigurationSetting(ConfigurationSettingName.PUB_REPOSITORY_URL);
    if (repoUrlSetting == null) {
      result.failAll("URL of exercise repository is not configured");
      return result;
    }
    String repoUrl = repoUrlSetting.getValue();
    if (repoUrl.endsWith("/")) {
      repoUrl = repoUrl.substring(0, repoUrl.length() - 1);
    }

    HttpPost post = new HttpPost(repoUrl + "/exercisedata");

    // Encode an Authorization header using the provided repository username and password.
    String authHeaderValue =
        "Basic "
            + DatatypeConverter.printBase64Binary(
                (repoUsername + ":" + repoPassword).getBytes(Charset.forName("UTF-8")));
    // System.out.println("Authorization: " + authHeaderValue);
    post.addHeader("Authorization", authHeaderValue);

    // Now go through and upload each problem
    // For now, we do this one at a time
    // In the future we could send problems and test cases
    // to the repo in bulk, and add a new web service to handle it

    for (Problem p : problems) {
      // Look up the test cases
      List<TestCase> testCaseList = Database.getInstance().getTestCasesForProblem(p.getProblemId());
      ProblemAndTestCaseList exercise = new ProblemAndTestCaseList();
      exercise.setProblem(p);
      exercise.setTestCaseList(testCaseList);

      // Convert the exercise to a JSON string
      StringEntity entity;
      StringWriter sw = new StringWriter();
      try {
        JSONConversion.writeProblemAndTestCaseData(exercise, sw);
        entity = new StringEntity(sw.toString(), ContentType.create("application/json", "UTF-8"));
      } catch (IOException e) {
        // fail remaining test cases and return our results thus far
        // some exercises may have been successfully shared
        result.failRemaining("Could not convert exercise to JSON: " + e.getMessage());
        return result;
      }
      post.setEntity(entity);

      // POST the exercise to the repository
      HttpClient client = new DefaultHttpClient();
      try {
        HttpResponse response = client.execute(post);

        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
          // Update the exercise's shared flag so we have a record that it was shared.
          exercise.getProblem().setShared(true);
          exercise.getProblem().setProblemAuthorship(ProblemAuthorship.IMPORTED);
          Database.getInstance().storeProblemAndTestCaseList(exercise, course, authenticatedUser);
          result.success();
        } else if (statusLine.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
          result.failRemaining(
              "Authentication with repository failed - incorrect username/password?");
          return result;
        } else {
          result.failRemaining(
              "Failed to publish exercise to repository: " + statusLine.getReasonPhrase());
          return result;
        }
      } catch (ClientProtocolException e) {
        result.failRemaining("Error sending exercise to repository: " + e.getMessage());
        return result;
      } catch (IOException e) {
        result.failRemaining("Error sending exercise to repository: " + e.getMessage());
        return result;
      } finally {
        client.getConnectionManager().shutdown();
      }
    }
    result.allSucceeded(
        "Successfully uploaded " + problems.length + " exercise to repository.  Thanks!");
    return result;
  }