use of fi.internetix.smvc.SmvcRuntimeException in project pyramus by otavanopisto.
the class EditStudentProjectJSONRequestController method process.
public void process(JSONRequestContext jsonRequestContext) {
StaffMemberDAO staffMemberDAO = DAOFactory.getInstance().getStaffMemberDAO();
ModuleDAO moduleDAO = DAOFactory.getInstance().getModuleDAO();
CourseDAO courseDAO = DAOFactory.getInstance().getCourseDAO();
StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO();
CourseStudentDAO courseStudentDAO = DAOFactory.getInstance().getCourseStudentDAO();
StudentProjectDAO studentProjectDAO = DAOFactory.getInstance().getStudentProjectDAO();
StudentProjectModuleDAO studentProjectModuleDAO = DAOFactory.getInstance().getStudentProjectModuleDAO();
GradeDAO gradeDAO = DAOFactory.getInstance().getGradeDAO();
ProjectAssessmentDAO projectAssessmentDAO = DAOFactory.getInstance().getProjectAssessmentDAO();
EducationalTimeUnitDAO educationalTimeUnitDAO = DAOFactory.getInstance().getEducationalTimeUnitDAO();
AcademicTermDAO academicTermDAO = DAOFactory.getInstance().getAcademicTermDAO();
TagDAO tagDAO = DAOFactory.getInstance().getTagDAO();
DefaultsDAO defaultsDAO = DAOFactory.getInstance().getDefaultsDAO();
Defaults defaults = defaultsDAO.getDefaults();
// Project
Long studentProjectId = jsonRequestContext.getLong("studentProject");
StudentProject studentProject = studentProjectDAO.findById(studentProjectId);
// Version check
Long version = jsonRequestContext.getLong("version");
if (!studentProject.getVersion().equals(version))
throw new StaleObjectStateException(StudentProject.class.getName(), studentProject.getId());
String name = jsonRequestContext.getString("name");
String description = jsonRequestContext.getString("description");
StaffMember staffMember = staffMemberDAO.findById(jsonRequestContext.getLoggedUserId());
Long optionalStudiesLengthTimeUnitId = jsonRequestContext.getLong("optionalStudiesLengthTimeUnit");
EducationalTimeUnit optionalStudiesLengthTimeUnit = educationalTimeUnitDAO.findById(optionalStudiesLengthTimeUnitId);
Double optionalStudiesLength = jsonRequestContext.getDouble("optionalStudiesLength");
String tagsText = jsonRequestContext.getString("tags");
Long studentId = jsonRequestContext.getLong("student");
CourseOptionality projectOptionality = (CourseOptionality) jsonRequestContext.getEnum("projectOptionality", CourseOptionality.class);
Set<Tag> tagEntities = new HashSet<>();
if (!StringUtils.isBlank(tagsText)) {
List<String> tags = Arrays.asList(tagsText.split("[\\ ,]"));
for (String tag : tags) {
if (!StringUtils.isBlank(tag)) {
Tag tagEntity = tagDAO.findByText(tag.trim());
if (tagEntity == null)
tagEntity = tagDAO.create(tag);
tagEntities.add(tagEntity);
}
}
}
Student student = studentDAO.findById(studentId);
if (!studentProject.getStudent().equals(student)) {
studentProjectDAO.updateStudent(studentProject, student, staffMember);
}
studentProjectDAO.update(studentProject, name, description, optionalStudiesLength, optionalStudiesLengthTimeUnit, projectOptionality, staffMember);
// Tags
studentProjectDAO.updateTags(studentProject, tagEntities);
// ProjectAssessments
int rowCount = jsonRequestContext.getInteger("assessmentsTable.rowCount").intValue();
for (int i = 0; i < rowCount; i++) {
String colPrefix = "assessmentsTable." + i;
Long assessmentModified = jsonRequestContext.getLong(colPrefix + ".modified");
if ((assessmentModified != null) && (assessmentModified.intValue() == 1)) {
Long assessmentId = jsonRequestContext.getLong(colPrefix + ".assessmentId");
ProjectAssessment projectAssessment = ((assessmentId != null) && (assessmentId.intValue() != -1)) ? projectAssessmentDAO.findById(assessmentId) : null;
Long assessmentArchived = jsonRequestContext.getLong(colPrefix + ".deleted");
if ((assessmentArchived != null) && (assessmentArchived.intValue() == 1)) {
if (projectAssessment != null)
projectAssessmentDAO.archive(projectAssessment);
else
throw new SmvcRuntimeException(PyramusStatusCode.OK, "Assessment marked for delete does not exist.");
} else {
Date assessmentDate = jsonRequestContext.getDate(colPrefix + ".date");
Long assessmentGradeId = jsonRequestContext.getLong(colPrefix + ".grade");
Grade grade = assessmentGradeId != null ? gradeDAO.findById(assessmentGradeId) : null;
String verbalAssessment = projectAssessment != null ? projectAssessment.getVerbalAssessment() : null;
Long verbalAssessmentModified = jsonRequestContext.getLong(colPrefix + ".verbalModified");
if ((verbalAssessmentModified != null) && (verbalAssessmentModified.intValue() == 1))
verbalAssessment = jsonRequestContext.getString(colPrefix + ".verbalAssessment");
if (projectAssessment == null) {
projectAssessmentDAO.create(studentProject, staffMember, grade, assessmentDate, verbalAssessment);
} else {
projectAssessmentDAO.update(projectAssessment, staffMember, grade, assessmentDate, verbalAssessment);
}
}
}
}
// Student project modules
Set<Long> existingModuleIds = new HashSet<>();
rowCount = jsonRequestContext.getInteger("modulesTable.rowCount").intValue();
for (int i = 0; i < rowCount; i++) {
String colPrefix = "modulesTable." + i;
Long studentProjectModuleId = jsonRequestContext.getLong(colPrefix + ".studentProjectModuleId");
CourseOptionality optionality = (CourseOptionality) jsonRequestContext.getEnum(colPrefix + ".optionality", CourseOptionality.class);
Long studyTermId = jsonRequestContext.getLong(colPrefix + ".academicTerm");
AcademicTerm academicTerm = studyTermId == null ? null : academicTermDAO.findById(studyTermId);
if (studentProjectModuleId == -1) {
Long moduleId = jsonRequestContext.getLong(colPrefix + ".moduleId");
Module module = moduleDAO.findById(moduleId);
studentProjectModuleId = studentProjectModuleDAO.create(studentProject, module, academicTerm, optionality).getId();
} else {
studentProjectModuleDAO.update(studentProjectModuleDAO.findById(studentProjectModuleId), academicTerm, optionality);
}
existingModuleIds.add(studentProjectModuleId);
}
// Removed Student project modules
List<StudentProjectModule> studentProjectModules = studentProjectModuleDAO.listByStudentProject(studentProject);
for (StudentProjectModule studentProjectModule : studentProjectModules) {
if (!existingModuleIds.contains(studentProjectModule.getId())) {
studentProjectModuleDAO.delete(studentProjectModule);
}
}
// Student project courses
rowCount = jsonRequestContext.getInteger("coursesTable.rowCount").intValue();
for (int i = 0; i < rowCount; i++) {
String colPrefix = "coursesTable." + i;
Long courseId = jsonRequestContext.getLong(colPrefix + ".courseId");
CourseOptionality optionality = (CourseOptionality) jsonRequestContext.getEnum(colPrefix + ".optionality", CourseOptionality.class);
Course course = courseId == -1 ? null : courseDAO.findById(courseId);
CourseStudent courseStudent = courseStudentDAO.findByCourseAndStudent(course, studentProject.getStudent());
if (courseStudent == null) {
CourseEnrolmentType courseEnrolmentType = defaults.getInitialCourseEnrolmentType();
CourseParticipationType participationType = defaults.getInitialCourseParticipationType();
Date enrolmentDate = new Date(System.currentTimeMillis());
Boolean lodging = Boolean.FALSE;
String organization = null;
String additionalInfo = null;
Room room = null;
BigDecimal lodgingFee = null;
Currency lodgingFeeCurrency = null;
BigDecimal reservationFee = null;
Currency reservationFeeCurrency = null;
try {
courseStudent = courseStudentDAO.create(course, studentProject.getStudent(), courseEnrolmentType, participationType, enrolmentDate, lodging, optionality, null, organization, additionalInfo, room, lodgingFee, lodgingFeeCurrency, reservationFee, reservationFeeCurrency, Boolean.FALSE);
} catch (DuplicateCourseStudentException dcse) {
Locale locale = jsonRequestContext.getRequest().getLocale();
throw new SmvcRuntimeException(PyramusStatusCode.UNDEFINED, Messages.getInstance().getText(locale, "generic.errors.duplicateCourseStudent", new Object[] { student.getFullName() }));
}
} else {
courseStudentDAO.updateOptionality(courseStudent, optionality);
}
}
jsonRequestContext.setRedirectURL(jsonRequestContext.getReferer(true));
}
use of fi.internetix.smvc.SmvcRuntimeException in project pyramus by otavanopisto.
the class EditCourseJSONRequestController method processSignupStudentGroups.
private void processSignupStudentGroups(JSONRequestContext requestContext, Course course, StaffMember loggedUser) {
CourseSignupStudentGroupDAO courseSignupStudentGroupDAO = DAOFactory.getInstance().getCourseSignupStudentGroupDAO();
StudentGroupDAO studentGroupDAO = DAOFactory.getInstance().getStudentGroupDAO();
List<CourseSignupStudentGroup> signupStudentGroups = courseSignupStudentGroupDAO.listByCourse(course);
Integer studentGroupsRowCount = requestContext.getInteger("signupStudentGroupsTable.rowCount");
if (studentGroupsRowCount != null) {
Set<Long> studentGroupIdsPresent = new HashSet<>();
for (int i = 0; i < studentGroupsRowCount; i++) {
Long studentGroupId = requestContext.getLong(String.format("signupStudentGroupsTable.%d.studentGroupId", i));
if (studentGroupId != null) {
studentGroupIdsPresent.add(studentGroupId);
}
}
// Create missing groups
studentGroupIdsPresent.forEach(studentGroupId -> {
if (signupStudentGroups.stream().noneMatch(signupStudentGroup -> Objects.equals(signupStudentGroup.getStudentGroup().getId(), studentGroupId))) {
StudentGroup studentGroup = studentGroupDAO.findById(studentGroupId);
if ((studentGroup != null) && UserUtils.canAccessOrganization(loggedUser, studentGroup.getOrganization())) {
courseSignupStudentGroupDAO.create(course, studentGroup);
} else {
throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "Invalid organization.");
}
}
});
// Remove groups that don't exist anymore
signupStudentGroups.stream().filter(signupStudentGroup -> !studentGroupIdsPresent.contains(signupStudentGroup.getStudentGroup().getId())).forEach(signupStudentGroup -> {
if (UserUtils.canAccessOrganization(loggedUser, signupStudentGroup.getStudentGroup().getOrganization())) {
courseSignupStudentGroupDAO.delete(signupStudentGroup);
} else {
throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "Invalid organization.");
}
});
}
}
use of fi.internetix.smvc.SmvcRuntimeException in project pyramus by otavanopisto.
the class OpenIDAuthorizationStrategy method performDiscovery.
public void performDiscovery(RequestContext requestContext) {
try {
HttpSession session = requestContext.getRequest().getSession();
// perform discovery on the user-supplied identifier
List<?> discoveries = consumerManager.discover(System.getProperty("authentication.OpenID.identifier"));
// attempt to associate with the OpenID provider
// and retrieve one service endpoint for authentication
DiscoveryInformation discovered = consumerManager.associate(discoveries);
// store the discovery information in the user's session for later use
session.setAttribute("discovered", discovered);
// Construct a path back to users/externallogin.page in Pyramus
String currentURL = requestContext.getRequest().getRequestURL().toString();
String pathInfo = requestContext.getRequest().getRequestURI();
String baseURL = currentURL.substring(0, currentURL.length() - pathInfo.length());
StringBuilder returnURL = new StringBuilder(baseURL).append(requestContext.getRequest().getContextPath()).append("/users/externallogin.page");
// obtain a AuthRequest message to be sent to the OpenID provider
AuthRequest authReq = consumerManager.authenticate(discovered, returnURL.toString());
// Attribute Exchange example: fetching the 'email' attribute
FetchRequest fetch = FetchRequest.createFetchRequest();
fetch.addAttribute("email", // type URI
"http://schema.openid.net/contact/email", // required
true);
// attach the extension to the authentication request
authReq.addExtension(fetch);
requestContext.setRedirectURL(authReq.getDestinationUrl(true));
} catch (DiscoveryException e) {
throw new SmvcRuntimeException(e);
} catch (MessageException e) {
throw new SmvcRuntimeException(e);
} catch (ConsumerException e) {
throw new SmvcRuntimeException(e);
}
}
use of fi.internetix.smvc.SmvcRuntimeException in project pyramus by otavanopisto.
the class OpenIDAuthorizationStrategy method processResponse.
@SuppressWarnings("unchecked")
public User processResponse(RequestContext requestContext) throws AuthenticationException {
UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
try {
HttpSession session = requestContext.getRequest().getSession();
// extract the parameters from the authentication response
// (which comes in as a HTTP request from the OpenID provider)
ParameterList openidResp = new ParameterList(requestContext.getRequest().getParameterMap());
// retrieve the previously stored discovery information
DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute("discovered");
// extract the receiving URL from the HTTP request
StringBuffer receivingURL = requestContext.getRequest().getRequestURL();
String queryString = requestContext.getRequest().getQueryString();
if (queryString != null && queryString.length() > 0) {
receivingURL.append("?").append(requestContext.getRequest().getQueryString());
}
// verify the response
VerificationResult verification = consumerManager.verify(receivingURL.toString(), openidResp, discovered);
// examine the verification result and extract the verified identifier
Identifier verified = verification.getVerifiedId();
if (verified != null) {
AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
List<String> emails = null;
if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
emails = fetchResp.getAttributeValues("email");
}
UserVariableDAO userVariableDAO = DAOFactory.getInstance().getUserVariableDAO();
User user = userDAO.findByExternalIdAndAuthProvider(verified.getIdentifier(), getName());
if (user == null) {
user = userDAO.findByEmail(emails.get(0));
if (user != null) {
String expectedLoginServer = userVariableDAO.findByUserAndKey(user, "openid.expectedlogin");
String loginServer = verification.getAuthResponse().getParameterValue("openid.op_endpoint");
if (!StringUtils.isBlank(expectedLoginServer) && expectedLoginServer.equals(loginServer)) {
userVariableDAO.setUserVariable(user, "openid.expectedlogin", null);
userDAO.updateExternalId(user, verified.getIdentifier());
} else {
throw new AuthenticationException(AuthenticationException.LOCAL_USER_MISSING);
}
} else {
throw new AuthenticationException(AuthenticationException.LOCAL_USER_MISSING);
}
}
return user;
} else {
return null;
}
} catch (MessageException e) {
throw new SmvcRuntimeException(e);
} catch (DiscoveryException e) {
throw new SmvcRuntimeException(e);
} catch (AssociationException e) {
throw new SmvcRuntimeException(e);
}
}
use of fi.internetix.smvc.SmvcRuntimeException in project pyramus by otavanopisto.
the class LDAPAuthorizationStrategy method getUser.
/**
* Returns the user corresponding to the given credentials. If no user cannot be found, returns
* <code>null</code>.
*
* @param username The username
* @param password The password
*
* @return The user corresponding to the given credentials, or <code>null</code> if not found
* @throws AuthenticationException
*/
public User getUser(String username, String password) throws AuthenticationException {
UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
LDAPConnection connection;
try {
connection = LDAPUtils.getLDAPConnection();
final String searchFilter = "(" + System.getProperty("authentication.ldap.usernameAttr") + "=" + username + ")";
final LDAPSearchResults searchResults = connection.search(System.getProperty("authentication.ldap.authdn"), LDAPConnection.SCOPE_SUB, searchFilter, null, false);
if (searchResults != null && searchResults.hasMore()) {
LDAPEntry entry = searchResults.next();
try {
String uniqueIdAttr = System.getProperty("authentication.ldap.uniqueIdAttr");
boolean idEncoded = "1".equals(System.getProperty("authentication.ldap.uniqueIdEncoded"));
connection.bind(Integer.parseInt(System.getProperty("authentication.ldap.version")), entry.getDN(), password.getBytes("UTF8"));
String id = idEncoded ? LDAPUtils.getAttributeBinaryValue(entry.getAttribute(uniqueIdAttr)) : entry.getAttribute(uniqueIdAttr).getStringValue();
User user = userDAO.findByExternalIdAndAuthProvider(id, getName());
if (user == null)
throw new AuthenticationException(AuthenticationException.LOCAL_USER_MISSING);
return user;
} catch (UnsupportedEncodingException e) {
throw new LDAPException();
}
}
} catch (LDAPException e) {
throw new SmvcRuntimeException(e);
}
return null;
}
Aggregations