List of usage examples for javax.persistence EntityManager getTransaction
public EntityTransaction getTransaction();
EntityTransaction
object. From source file:gov.osti.services.Metadata.java
/** * Perform SAVE workflow on indicated METADATA. * * @param json the JSON String containing the metadata to SAVE * @param file a FILE associated with this record if any * @param fileInfo the FILE disposition information if any * @param container a CONTAINER IMAGE associated with this record if any * @param containerInfo the CONTAINER IMAGE disposition of information if any * @return a Response containing the JSON of the saved record if successful, * or error information if not//from w ww . j a v a 2 s. c o m */ private Response doSave(String json, InputStream file, FormDataContentDisposition fileInfo, InputStream container, FormDataContentDisposition containerInfo) { EntityManager em = DoeServletContextListener.createEntityManager(); Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); try { validateUploads(fileInfo, containerInfo); DOECodeMetadata md = DOECodeMetadata.parseJson(new StringReader(json)); em.getTransaction().begin(); performDataNormalization(md); md.setWorkflowStatus(Status.Saved); // default to this md.setOwner(user.getEmail()); // this User should OWN it md.setSiteOwnershipCode(user.getSiteId()); store(em, md, user); // re-attach metadata to transaction in order to store any changes beyond this point md = em.find(DOECodeMetadata.class, md.getCodeId()); // if there's a FILE associated here, store it if (null != file && null != fileInfo) { try { String fileName = writeFile(file, md.getCodeId(), fileInfo.getFileName(), FILE_UPLOADS); md.setFileName(fileName); } catch (IOException e) { log.error("File Upload Failed: " + e.getMessage()); return ErrorResponse.internalServerError("File upload failed.").build(); } } // if there's a CONTAINER IMAGE associated here, store it if (null != container && null != containerInfo) { try { String containerName = writeFile(container, md.getCodeId(), containerInfo.getFileName(), CONTAINER_UPLOADS); md.setContainerName(containerName); } catch (IOException e) { log.error("Container Image Upload Failed: " + e.getMessage()); return ErrorResponse.internalServerError("Container Image upload failed.").build(); } } // we're done here em.getTransaction().commit(); return Response.status(200) .entity(mapper.createObjectNode().putPOJO("metadata", md.toJson()).toString()).build(); } catch (BadRequestException e) { return e.getResponse(); } catch (NotFoundException e) { return ErrorResponse.notFound(e.getMessage()).build(); } catch (IllegalAccessException e) { log.warn("Persistence Error: Invalid update attempt from " + user.getEmail()); log.warn("Message: " + e.getMessage()); return ErrorResponse.forbidden("Unable to persist update for indicated record.").build(); } catch (ValidationException e) { log.warn("Validation Error: " + e.getMessage()); return ErrorResponse.badRequest(e.getMessage()).build(); } catch (IOException | InvocationTargetException e) { if (em.getTransaction().isActive()) em.getTransaction().rollback(); log.warn("Persistence Error: " + e.getMessage()); return ErrorResponse.internalServerError("Save IO Error: " + e.getMessage()).build(); } finally { em.close(); } }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
@Override public TransactionContext createTransactionalContext() { EntityManager em = getEntityManager(); switch (this.type) { case LOCAL://from w w w .ja v a 2 s. c o m return new TransactionContext(new LocalTransaction(em.getTransaction()), em); default: return new TransactionContext(tx, em); } }
From source file:gov.osti.services.Metadata.java
/** * Perform ANNOUNCE workflow operation, optionally with associated file uploads. * * @param json String containing JSON of the Metadata to ANNOUNCE * @param file the FILE (if any) to attach to this metadata * @param fileInfo file disposition information if FILE present * @return a Response containing the JSON of the submitted record if successful, or * error information if not//from www . j a va 2 s .c o m */ private Response doAnnounce(String json, InputStream file, FormDataContentDisposition fileInfo, InputStream container, FormDataContentDisposition containerInfo) { EntityManager em = DoeServletContextListener.createEntityManager(); Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); try { validateUploads(fileInfo, containerInfo); DOECodeMetadata md = DOECodeMetadata.parseJson(new StringReader(json)); Long currentCodeId = md.getCodeId(); boolean previouslySaved = false; if (currentCodeId != null) { DOECodeMetadata emd = em.find(DOECodeMetadata.class, currentCodeId); if (emd != null) previouslySaved = Status.Saved.equals(emd.getWorkflowStatus()); } em.getTransaction().begin(); performDataNormalization(md); // set the OWNER md.setOwner(user.getEmail()); // set the WORKFLOW STATUS md.setWorkflowStatus(Status.Announced); // set the SITE md.setSiteOwnershipCode(user.getSiteId()); // if there is NO DOI set, get one if (StringUtils.isEmpty(md.getDoi())) { DoiReservation reservation = getReservedDoi(); if (null == reservation) throw new IOException("DOI reservation failure."); // set it md.setDoi(reservation.getReservedDoi()); } // persist this to the database store(em, md, user); // re-attach metadata to transaction in order to store any changes beyond this point md = em.find(DOECodeMetadata.class, md.getCodeId()); // if there's a FILE associated here, store it String fullFileName = ""; if (null != file && null != fileInfo) { try { fullFileName = writeFile(file, md.getCodeId(), fileInfo.getFileName(), FILE_UPLOADS); md.setFileName(fullFileName); } catch (IOException e) { log.error("File Upload Failed: " + e.getMessage()); return ErrorResponse.internalServerError("File upload failed.").build(); } } // if there's a CONTAINER IMAGE associated here, store it String fullContainerName = ""; if (null != container && null != containerInfo) { try { fullContainerName = writeFile(container, md.getCodeId(), containerInfo.getFileName(), CONTAINER_UPLOADS); md.setContainerName(fullContainerName); } catch (IOException e) { log.error("Container Image Upload Failed: " + e.getMessage()); return ErrorResponse.internalServerError("Container Image upload failed.").build(); } } // check validations List<String> errors = validateAnnounce(md); if (!errors.isEmpty()) { return ErrorResponse.badRequest(errors).build(); } // create OSTI Hosted project, as needed try { // process local GitLab, if needed processOSTIGitLab(md); } catch (Exception e) { log.error("OSTI GitLab failure: " + e.getMessage()); return ErrorResponse.internalServerError("Unable to create OSTI Hosted project: " + e.getMessage()) .build(); } // send this file upload along to archiver if configured try { // if no file/container, but previously Saved with a file/container, we need to attach to those streams and send to Archiver if (previouslySaved) { if (null == file && !StringUtils.isBlank(md.getFileName())) { java.nio.file.Path destination = Paths.get(FILE_UPLOADS, String.valueOf(md.getCodeId()), md.getFileName()); fullFileName = destination.toString(); file = Files.newInputStream(destination); } if (null == container && !StringUtils.isBlank(md.getContainerName())) { java.nio.file.Path destination = Paths.get(CONTAINER_UPLOADS, String.valueOf(md.getCodeId()), md.getContainerName()); fullContainerName = destination.toString(); container = Files.newInputStream(destination); } } // if a FILE or CONTAINER was sent, create a File Object from it File archiveFile = (null == file) ? null : new File(fullFileName); File archiveContainer = null; //(null==container) ? null : new File(fullContainerName); if (DOECodeMetadata.Accessibility.CO.equals(md.getAccessibility())) // if CO project type, no need to archive the repo because it is local GitLab sendToArchiver(md.getCodeId(), null, archiveFile, archiveContainer); else sendToArchiver(md.getCodeId(), md.getRepositoryLink(), archiveFile, archiveContainer); } catch (IOException e) { log.error("Archiver call failure: " + e.getMessage()); return ErrorResponse.internalServerError("Unable to archive project.").build(); } // send any updates to DataCite as well (if RELEASE DATE is set) if (StringUtils.isNotEmpty(md.getDoi()) && null != md.getReleaseDate()) { try { DataCite.register(md); } catch (IOException e) { // if DataCite registration failed, say why log.warn("DataCite ERROR: " + e.getMessage()); return ErrorResponse.internalServerError( "The DOI registration service is currently unavailable, please try to submit your record later. If the issue persists, please contact doecode@osti.gov.") .build(); } } // store the snapshot copy of Metadata in SPECIAL STATUS MetadataSnapshot snapshot = new MetadataSnapshot(); snapshot.getSnapshotKey().setCodeId(md.getCodeId()); snapshot.getSnapshotKey().setSnapshotStatus(md.getWorkflowStatus()); snapshot.setDoi(md.getDoi()); snapshot.setDoiIsMinted(md.getReleaseDate() != null); snapshot.setJson(md.toJson().toString()); em.merge(snapshot); // if we make it this far, go ahead and commit the transaction em.getTransaction().commit(); // send NOTIFICATION if configured sendStatusNotification(md); // and we're happy return Response.ok().entity(mapper.createObjectNode().putPOJO("metadata", md.toJson()).toString()) .build(); } catch (BadRequestException e) { return e.getResponse(); } catch (NotFoundException e) { return ErrorResponse.notFound(e.getMessage()).build(); } catch (IllegalAccessException e) { log.warn("Persistence Error: Invalid owner update attempt: " + user.getEmail()); log.warn("Message: " + e.getMessage()); return ErrorResponse.forbidden("Invalid Access: Unable to edit indicated record.").build(); } catch (ValidationException e) { log.warn("Validation Error: " + e.getMessage()); return ErrorResponse.badRequest(e.getMessage()).build(); } catch (IOException | InvocationTargetException e) { if (em.getTransaction().isActive()) em.getTransaction().rollback(); log.warn("Persistence Error: " + e.getMessage()); return ErrorResponse.internalServerError("IO Error announcing record.").build(); } finally { em.close(); } }
From source file:mil.navy.med.dzreg.dao.RegistriesManagerDAO.java
/** * Register a new registry profile.//from www . jav a2 s. c o m * @param profile * @return * @throws Exception */ public AckType register(PersonRegistryProfileType profile) { EntityManager em = null; PersistentServiceFactory psf = null; StringBuffer exceptionMsg = new StringBuffer(); AckType ack = new AckType(); ack.setResponseCode(_APPLICATION_ERROR); if (profile != null && profile.getPerson() != null && profile.getRegistry() != null && !profile.getRegistry().isEmpty() && profile.getDataSource() != null) { //------------------------------------------------------------------------ // Registry type must be valid. //------------------------------------------------------------------------ Map<Integer, DzType> toBeRegisterDzTypes = Collections.synchronizedMap(new HashMap<Integer, DzType>()); for (RegistryType r : profile.getRegistry()) { try { DzType dzType = this.validRegistryType(r); if (dzType != null) { toBeRegisterDzTypes.put(Integer.valueOf(dzType.getDztypeId()), dzType); } else { exceptionMsg.append("Invalid/Unknown registy type specified - " + r.getRegistryId() + ";"); } } catch (Exception ex) { exceptionMsg.append(ex.getMessage() + ";"); } } //---------------------------------------------------------------------- // Person info must have following elements: // 1. Identifer // 2. Name // 3. Date of birth // 4. Data Source //---------------------------------------------------------------------- PersonType person = profile.getPerson(); if (person.getName() == null || person.getName().isEmpty() || (person.getDataSource() == null && profile.getDataSource() == null)) { ack.setDetectedIssueText("Missing required metadata (person identifier or name or data source);"); return ack; } //------------------------------------------------------------------------ // Check to see if this person already registered. //------------------------------------------------------------------------ DzPatients registeredPatient = null; try { registeredPatient = validPerson(person); } catch (javax.persistence.NoResultException nre) { } catch (Exception ex) { ack.setDetectedIssueText("Failed to register patient - " + ex.getMessage()); return ack; } try { psf = PersistentServiceFactory.getInstance(REGISTRY_MANAGER_PU); em = psf.getEntityManager(); em.getTransaction().begin(); // Get the date today using Calendar object. Calendar cal = Calendar.getInstance(); Timestamp today = new Timestamp(cal.getTimeInMillis()); //---------------------------------------------------------------------- // If yes, only need to add a record to table DZ_REG for each new // registry type. //---------------------------------------------------------------------- if (registeredPatient != null) { // remove any registry type (from request) that is already assigned to // this person Collection<DzReg> registries = registeredPatient.getDzRegCollection(); for (DzReg r : registries) { Integer intDzTypeId = Integer.valueOf(r.getDzType().getDztypeId()); if (toBeRegisterDzTypes.containsKey(intDzTypeId)) { toBeRegisterDzTypes.remove(intDzTypeId); log.debug("Already registered in Registry " + intDzTypeId + "!"); exceptionMsg.append("Already registered in Registry " + intDzTypeId + ";"); } } // what we have left is new registry type to be add to person registry // profile Collection<DzType> toBeRegisterColl = toBeRegisterDzTypes.values(); for (DzType d : toBeRegisterColl) { // only need to add a record to table DZ_REG DzRegPK pk = new DzRegPK(person.getId(), d.getDztypeId()); DzReg newDzreg = new DzReg(); newDzreg.setDzRegPK(pk); newDzreg.setActive(_ACTIVE); newDzreg.setDataSource(person.getDataSource()); newDzreg.setRegisteredDt(today); newDzreg.setInsertedDt(today); em.persist(newDzreg); } } //---------------------------------------------------------------------- // If no, need to insert a new record in DZ_PATIENTS table and a new // record in table DZ_REG for each new registry type. //---------------------------------------------------------------------- else { DzPatients newDzPatient = map(person); newDzPatient.setInsertedDt(today); newDzPatient.setUpdatedDt(today); if (person.getDataSource() == null) { if (profile.getDataSource() != null) { newDzPatient.setDataSource(profile.getDataSource()); } else { // cannot insert record throw new Exception("Missing required metadata (data source);"); } } else { newDzPatient.setDataSource(profile.getDataSource()); } Collection<DzType> dzTypes = toBeRegisterDzTypes.values(); Collection<DzReg> newDzregList = new ArrayList<DzReg>(dzTypes.size()); for (DzType dzType : dzTypes) { DzRegPK pk = new DzRegPK(person.getId(), dzType.getDztypeId()); DzReg newDzreg = new DzReg(); newDzreg.setDzRegPK(pk); newDzreg.setActive(_ACTIVE); newDzreg.setRegisteredDt(today); newDzreg.setInsertedDt(today); if (person.getDataSource() == null) { newDzreg.setDataSource(profile.getDataSource()); } else { newDzreg.setDataSource(person.getDataSource()); } newDzregList.add(newDzreg); } newDzPatient.setDzRegCollection(newDzregList); em.persist(newDzPatient); } em.getTransaction().commit(); ack.setResponseCode(_OK); ack.setDetectedIssueText(exceptionMsg.toString()); return ack; } catch (Exception ex) { ex.printStackTrace(); em.getTransaction().rollback(); log.error("Failed to create new records in table DZ_PATIENTS/DZ_REG for profile=" + profile); ack.setDetectedIssueText( "Failed to register patient " + profile.getPerson().getId() + "-" + ex.getMessage()); return ack; } finally { em.close(); } } else { ack.setDetectedIssueText("Invalid registry profile"); return ack; } }
From source file:com.gigglinggnus.controllers.StudentMakeAppointmentController.java
/** * * @param request servlet request// w ww.ja va 2 s. c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { EntityManager em = (EntityManager) request.getSession().getAttribute("em"); String msg = request.getParameter("msg"); User user = (User) (request.getSession().getAttribute("user")); Clock clk = (Clock) (request.getSession().getAttribute("clock")); if (msg.equals("lookup_student")) { String studId = request.getParameter("studentId"); List<Exam> exams = user.getRegistrableExams(); JSONObject json = new JSONObject(); json.put("students_idNumber", studId); json.put("firstName", user.getFirstName()); json.put("lastName", user.getLastName()); JSONArray jExams = new JSONArray(); for (Exam exam : exams) { JSONObject elem = new JSONObject(); String examId = exam.getExamId(); String termId = exam.getTerm().getTermId(); String start = exam.getInterval().getStart().atZone(ZoneId.systemDefault()).toLocalDate() .toString(); String end = exam.getInterval().getEnd().atZone(ZoneId.systemDefault()).toLocalDate().toString(); elem.put("examId", examId); elem.put("termId", termId); if (exam instanceof CourseExam) { String courseId = ((CourseExam) exam).getCourse().getCourseId(); elem.put("courseId", courseId); elem.put("examType", "Course"); } else { elem.put("courseId", "N/A"); elem.put("examType", "AdHoc"); } elem.put("start", start); elem.put("end", end); jExams.put(elem); } json.put("exams", jExams); response.getWriter().write(json.toString()); } else if (msg.equals("exam_available_timeslots")) { String examId = request.getParameter("examId"); String dateStr = request.getParameter("date"); Exam exam = em.find(Exam.class, examId); LocalDate apptDate = LocalDate.parse(dateStr); List<LocalTime> timeslots = exam.getTimeslotsForDay(apptDate); JSONObject json = new JSONObject(); json.put("examId", examId); JSONArray jTimeSlots = new JSONArray(); for (LocalTime timeslot : timeslots) { String start = timeslot.toString(); String end = timeslot.plus(exam.getDuration()).toString(); JSONObject elem = new JSONObject(); elem.put("start", start); elem.put("end", end); jTimeSlots.put(elem); } json.put("timeSlots", jTimeSlots); response.getWriter().write(json.toString()); } else if (msg.equals("submit-appointment")) { String studId = request.getParameter("studentId"); String examId = request.getParameter("examId"); String stDate = request.getParameter("examDate"); String stTime = request.getParameter("startTime") + ":00"; String stSeat = request.getParameter("seatType"); Exam exam = em.find(Exam.class, examId); LocalDate lDate = LocalDate.parse(stDate); LocalTime lTime = LocalTime.parse(stTime); Instant inst = ZonedDateTime.of(lDate, lTime, ZoneId.systemDefault()).toInstant(); JSONObject json = new JSONObject(); try { em.getTransaction().begin(); user.makeAppointment(exam, inst, clk); em.getTransaction().commit(); json.put("success", "Appointment Made!"); response.getWriter().write(json.toString()); } catch (Exception e) { em.getTransaction().rollback(); json.put("error", e.toString()); response.getWriter().write(json.toString()); } } else { JSONObject json = new JSONObject(); json.put("error", msg); response.getWriter().write(json.toString()); } }
From source file:de.egore911.opengate.services.PilotService.java
@POST @Path("/register") @Produces("application/json") @Documentation("Register a new pilot. This will at first verify the login and email are " + "unique and the email is valid. After this it will register the pilot and send " + "and email to him to verify the address. The 'verify' will finalize the registration. " + "This method returns a JSON object containing a status field, i.e. {status: 'failed', " + "details: '...'} in case of an error and {status: 'ok', id: ...}. If an internal " + "error occured an HTTP 500 will be sent.") public Response performRegister(@FormParam("login") String login, @FormParam("email") String email, @FormParam("faction_id") @Documentation("ID of the faction this pilot will be working for") long factionId) { JSONObject jsonObject = new JSONObject(); EntityManager em = EntityManagerFilter.getEntityManager(); Number n = (Number) em .createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.login = (:login)") .setParameter("login", login).getSingleResult(); if (n.intValue() > 0) { try {/*from w ww. j a va 2 s . co m*/ StatusHelper.failed(jsonObject, "Duplicate login"); return Response.ok(jsonObject.toString()).build(); } catch (JSONException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } n = (Number) em.createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.email = (:email)") .setParameter("email", email).getSingleResult(); if (n.intValue() > 0) { try { StatusHelper.failed(jsonObject, "Duplicate email"); return Response.ok(jsonObject.toString()).build(); } catch (JSONException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } InternetAddress recipient; try { recipient = new InternetAddress(email, login); } catch (UnsupportedEncodingException e1) { try { StatusHelper.failed(jsonObject, "Invalid email"); return Response.ok(jsonObject.toString()).build(); } catch (JSONException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } Faction faction; try { faction = em.find(Faction.class, factionId); } catch (NoResultException e) { try { StatusHelper.failed(jsonObject, "Invalid faction"); return Response.ok(jsonObject.toString()).build(); } catch (JSONException e1) { LOG.log(Level.SEVERE, e.getMessage(), e1); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } Vessel vessel; try { vessel = (Vessel) em .createQuery("select vessel from Vessel vessel " + "where vessel.faction = :faction " + "order by vessel.techLevel asc") .setParameter("faction", faction).setMaxResults(1).getSingleResult(); // TODO assign initical equipment as well } catch (NoResultException e) { try { StatusHelper.failed(jsonObject, "Faction has no vessel"); return Response.ok(jsonObject.toString()).build(); } catch (JSONException e1) { LOG.log(Level.SEVERE, e.getMessage(), e1); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } String passwordHash; String password = randomText(); try { passwordHash = hashPassword(password); } catch (NoSuchAlgorithmException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } em.getTransaction().begin(); try { Pilot pilot = new Pilot(); pilot.setLogin(login); pilot.setCreated(new Date()); pilot.setPasswordHash(passwordHash); pilot.setEmail(email); pilot.setFaction(faction); pilot.setVessel(vessel); pilot.setVerificationCode(randomText()); em.persist(pilot); em.getTransaction().commit(); try { // send e-mail to registered user containing the new password Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); String msgBody = "Welcome to opengate!\n\nSomeone, propably you, registered the user " + pilot.getLogin() + " with your e-mail adress. The following credentials can be used for your account:\n" + " login : " + pilot.getLogin() + "\n" + " password : " + password + "\n\n" + "To log into the game you need to verify your account using the following link: http://opengate-meta.appspot.com/services/pilot/verify/" + pilot.getLogin() + "?verification=" + pilot.getVerificationCode(); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("egore911@gmail.com", "Opengate administration")); msg.addRecipient(Message.RecipientType.TO, recipient); msg.setSubject("Your Example.com account has been activated"); msg.setText(msgBody); Transport.send(msg); } catch (AddressException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } catch (MessagingException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } catch (UnsupportedEncodingException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } StatusHelper.ok(jsonObject); jsonObject.put("id", pilot.getKey().getId()); jsonObject.put("vessel_id", pilot.getVessel().getKey().getId()); // TODO properly wrap the vessel and its equipment/cargo return Response.ok(jsonObject.toString()).build(); } catch (JSONException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } catch (NoResultException e) { return Response.status(Status.FORBIDDEN).build(); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } } }
From source file:com.gigglinggnus.controllers.AdminMakeAppointmentController.java
/** * * @param request servlet request//from w w w .j a v a 2 s .com * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { EntityManager em = (EntityManager) request.getSession().getAttribute("em"); String msg = request.getParameter("msg"); User user = (User) (request.getSession().getAttribute("user")); Clock clk = (Clock) (request.getSession().getAttribute("clock")); if (msg.equals("lookup_student")) { String studId = request.getParameter("studentId"); User student = em.find(User.class, studId); List<Exam> exams = student.getRegistrableExams(); JSONObject json = new JSONObject(); json.put("students_idNumber", studId); json.put("firstName", student.getFirstName()); json.put("lastName", student.getLastName()); JSONArray jExams = new JSONArray(); for (Exam exam : exams) { JSONObject elem = new JSONObject(); String examId = exam.getExamId(); String termId = exam.getTerm().getTermId(); String start = exam.getInterval().getStart().atZone(ZoneId.systemDefault()).toLocalDate() .toString(); String end = exam.getInterval().getEnd().atZone(ZoneId.systemDefault()).toLocalDate().toString(); elem.put("examId", examId); elem.put("termId", termId); if (exam instanceof CourseExam) { String courseId = ((CourseExam) exam).getCourse().getCourseId(); elem.put("courseId", courseId); elem.put("examType", "Course"); } else { elem.put("courseId", "N/A"); elem.put("examType", "AdHoc"); } elem.put("start", start); elem.put("end", end); jExams.put(elem); } json.put("exams", jExams); response.getWriter().write(json.toString()); } else if (msg.equals("exam_available_timeslots")) { String examId = request.getParameter("examId"); String dateStr = request.getParameter("date"); Exam exam = em.find(Exam.class, examId); LocalDate apptDate = LocalDate.parse(dateStr); List<LocalTime> timeslots = exam.getTimeslotsForDay(apptDate); JSONObject json = new JSONObject(); json.put("examId", examId); JSONArray jTimeSlots = new JSONArray(); for (LocalTime timeslot : timeslots) { String start = timeslot.toString(); String end = timeslot.plus(exam.getDuration()).toString(); JSONObject elem = new JSONObject(); elem.put("start", start); elem.put("end", end); jTimeSlots.put(elem); } json.put("timeSlots", jTimeSlots); response.getWriter().write(json.toString()); } else if (msg.equals("submit-appointment")) { String studId = request.getParameter("studentId"); String examId = request.getParameter("examId"); String stDate = request.getParameter("examDate"); String stTime = request.getParameter("startTime") + ":00"; String stSeat = request.getParameter("seatType"); User student = em.find(User.class, studId); Exam exam = em.find(Exam.class, examId); LocalDate lDate = LocalDate.parse(stDate); LocalTime lTime = LocalTime.parse(stTime); Instant inst = ZonedDateTime.of(lDate, lTime, ZoneId.systemDefault()).toInstant(); JSONObject json = new JSONObject(); try { em.getTransaction().begin(); if (stSeat.equals("normal")) { user.makeAppointment(student, Seating.NORMAL, exam, inst, clk); em.getTransaction().commit(); json.put("success", "Appointment Made!"); response.getWriter().write(json.toString()); } else if (stSeat.equals("setaside")) { user.makeAppointment(student, Seating.SETASIDE, exam, inst, clk); em.getTransaction().commit(); json.put("success", "Appointment Made!"); response.getWriter().write(json.toString()); } else { em.getTransaction().rollback(); json.put("error", "invalid choice of seating"); response.getWriter().write(json.toString()); } } catch (Exception e) { em.getTransaction().rollback(); json.put("error", e.toString()); response.getWriter().write(json.toString()); } } else { JSONObject json = new JSONObject(); json.put("error", msg); response.getWriter().write(json.toString()); } }
From source file:gov.osti.services.Metadata.java
/** * APPROVE endpoint; sends the Metadata of a targeted project to Index. * * Will return a FORBIDDEN response if the OWNER logged in does not match * the record's OWNER.//from w ww . java2s. com * * @param codeId the CODE ID of the record to APPROVE. * @return a Response containing the JSON of the approved record if successful, or * error information if not * @throws InternalServerErrorException on JSON parsing or other IO errors */ @GET @Path("/approve/{codeId}") @Produces(MediaType.APPLICATION_JSON) @RequiresAuthentication @RequiresRoles("OSTI") public Response approve(@PathParam("codeId") Long codeId) { EntityManager em = DoeServletContextListener.createEntityManager(); Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); try { DOECodeMetadata md = em.find(DOECodeMetadata.class, codeId); if (null == md) return ErrorResponse.notFound("Code ID not on file.").build(); // make sure this is Submitted or Announced if (!DOECodeMetadata.Status.Submitted.equals(md.getWorkflowStatus()) && !DOECodeMetadata.Status.Announced.equals(md.getWorkflowStatus())) return ErrorResponse.badRequest("Metadata is not in the Submitted/Announced workflow state.") .build(); // move Approved Container to downloadable path try { approveContainerUpload(md); } catch (IOException e) { log.error("Container move failure: " + e.getMessage()); return ErrorResponse.internalServerError(e.getMessage()).build(); } // if approving announced, send this to OSTI if (DOECodeMetadata.Status.Announced.equals(md.getWorkflowStatus())) { sendToOsti(em, md); } em.getTransaction().begin(); // set the WORKFLOW STATUS md.setWorkflowStatus(Status.Approved); // persist this to the database, as validations should already be complete at this stage. store(em, md, user); // prior to updating snapshot, gather RI List for backfilling List<RelatedIdentifier> previousRiList = getPreviousRiList(em, md); // store the snapshot copy of Metadata MetadataSnapshot snapshot = new MetadataSnapshot(); snapshot.getSnapshotKey().setCodeId(md.getCodeId()); snapshot.getSnapshotKey().setSnapshotStatus(md.getWorkflowStatus()); snapshot.setDoi(md.getDoi()); snapshot.setDoiIsMinted(md.getReleaseDate() != null); snapshot.setJson(md.toJson().toString()); em.merge(snapshot); // perform RI backfilling backfillProjects(em, md, previousRiList); // if we make it this far, go ahead and commit the transaction em.getTransaction().commit(); // send it to the indexer sendToIndex(em, md); // send APPROVAL NOTIFICATION to OWNER sendApprovalNotification(md); sendPOCNotification(md); // and we're happy return Response.status(Response.Status.OK) .entity(mapper.createObjectNode().putPOJO("metadata", md.toJson()).toString()).build(); } catch (BadRequestException e) { return e.getResponse(); } catch (NotFoundException e) { return ErrorResponse.status(Response.Status.NOT_FOUND, e.getMessage()).build(); } catch (IllegalAccessException e) { log.warn("Persistence Error: Invalid owner update attempt: " + user.getEmail()); log.warn("Message: " + e.getMessage()); return ErrorResponse .status(Response.Status.FORBIDDEN, "Invalid Access: Unable to edit indicated record.").build(); } catch (IOException | InvocationTargetException e) { if (em.getTransaction().isActive()) em.getTransaction().rollback(); log.warn("Persistence Error: " + e.getMessage()); return ErrorResponse .status(Response.Status.INTERNAL_SERVER_ERROR, "IO Error approving record: " + e.getMessage()) .build(); } finally { em.close(); } }
From source file:gov.osti.services.Metadata.java
/** * Handle SUBMIT workflow logic./*from www.j av a 2 s.c om*/ * * @param json JSON String containing the METADATA object to SUBMIT * @param file (optional) a FILE associated with this METADATA * @param fileInfo (optional) the FILE disposition information, if any * @param container (optional) a CONTAINER IMAGE associated with this METADATA * @param containerInfo (optional) the CONTAINER IMAGE disposition information, if any * @return an appropriate Response object to the caller */ private Response doSubmit(String json, InputStream file, FormDataContentDisposition fileInfo, InputStream container, FormDataContentDisposition containerInfo) { EntityManager em = DoeServletContextListener.createEntityManager(); Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); try { validateUploads(fileInfo, containerInfo); DOECodeMetadata md = DOECodeMetadata.parseJson(new StringReader(json)); Long currentCodeId = md.getCodeId(); boolean previouslySaved = false; if (currentCodeId != null) { DOECodeMetadata emd = em.find(DOECodeMetadata.class, currentCodeId); if (emd != null) previouslySaved = Status.Saved.equals(emd.getWorkflowStatus()); } // lookup Announced Snapshot status TypedQuery<MetadataSnapshot> querySnapshot = em .createNamedQuery("MetadataSnapshot.findByCodeIdAndStatus", MetadataSnapshot.class) .setParameter("codeId", currentCodeId).setParameter("status", DOECodeMetadata.Status.Announced); List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList(); if (results.size() > 0) { log.error("Cannot Submit, Previously Announced: " + currentCodeId); return ErrorResponse.internalServerError( "This record was previously Announced to E-Link, if you need to update the metadata, please change your endpoint to \"/announce.\"") .build(); } em.getTransaction().begin(); performDataNormalization(md); // set the ownership and workflow status md.setOwner(user.getEmail()); md.setWorkflowStatus(Status.Submitted); md.setSiteOwnershipCode(user.getSiteId()); // store it store(em, md, user); // re-attach metadata to transaction in order to store any changes beyond this point md = em.find(DOECodeMetadata.class, md.getCodeId()); // if there's a FILE associated here, store it String fullFileName = ""; if (null != file && null != fileInfo) { try { fullFileName = writeFile(file, md.getCodeId(), fileInfo.getFileName(), FILE_UPLOADS); md.setFileName(fullFileName); } catch (IOException e) { log.error("File Upload Failed: " + e.getMessage()); return ErrorResponse.internalServerError("File upload failed.").build(); } } // if there's a CONTAINER IMAGE associated here, store it String fullContainerName = ""; if (null != container && null != containerInfo) { try { fullContainerName = writeFile(container, md.getCodeId(), containerInfo.getFileName(), CONTAINER_UPLOADS); md.setContainerName(fullContainerName); } catch (IOException e) { log.error("Container Image Upload Failed: " + e.getMessage()); return ErrorResponse.internalServerError("Container Image upload failed.").build(); } } // check validations for Submitted workflow List<String> errors = validateSubmit(md); if (!errors.isEmpty()) { // generate a JSONAPI errors object return ErrorResponse.badRequest(errors).build(); } // create OSTI Hosted project, as needed try { // process local GitLab, if needed processOSTIGitLab(md); } catch (Exception e) { log.error("OSTI GitLab failure: " + e.getMessage()); return ErrorResponse.internalServerError("Unable to create OSTI Hosted project: " + e.getMessage()) .build(); } // send this file upload along to archiver if configured try { // if no file/container, but previously Saved with a file/container, we need to attach to those streams and send to Archiver if (previouslySaved) { if (null == file && !StringUtils.isBlank(md.getFileName())) { java.nio.file.Path destination = Paths.get(FILE_UPLOADS, String.valueOf(md.getCodeId()), md.getFileName()); fullFileName = destination.toString(); file = Files.newInputStream(destination); } if (null == container && !StringUtils.isBlank(md.getContainerName())) { java.nio.file.Path destination = Paths.get(CONTAINER_UPLOADS, String.valueOf(md.getCodeId()), md.getContainerName()); fullContainerName = destination.toString(); container = Files.newInputStream(destination); } } // if a FILE or CONTAINER was sent, create a File Object from it File archiveFile = (null == file) ? null : new File(fullFileName); File archiveContainer = null; //(null==container) ? null : new File(fullContainerName); if (DOECodeMetadata.Accessibility.CO.equals(md.getAccessibility())) // if CO project type, no need to archive the repo because it is local GitLab sendToArchiver(md.getCodeId(), null, archiveFile, archiveContainer); else sendToArchiver(md.getCodeId(), md.getRepositoryLink(), archiveFile, archiveContainer); } catch (IOException e) { log.error("Archiver call failure: " + e.getMessage()); return ErrorResponse.internalServerError("Unable to archive project.").build(); } // send to DataCite if needed (and there is a RELEASE DATE set) if (null != md.getDoi() && null != md.getReleaseDate()) { try { DataCite.register(md); } catch (IOException e) { // tell why the DataCite registration failed log.warn("DataCite ERROR: " + e.getMessage()); return ErrorResponse.internalServerError( "The DOI registration service is currently unavailable, please try to submit your record later. If the issue persists, please contact doecode@osti.gov.") .build(); } } // store the snapshot copy of Metadata MetadataSnapshot snapshot = new MetadataSnapshot(); snapshot.getSnapshotKey().setCodeId(md.getCodeId()); snapshot.getSnapshotKey().setSnapshotStatus(md.getWorkflowStatus()); snapshot.setDoi(md.getDoi()); snapshot.setDoiIsMinted(md.getReleaseDate() != null); snapshot.setJson(md.toJson().toString()); em.merge(snapshot); // commit it em.getTransaction().commit(); // send NOTIFICATION if configured to do so sendStatusNotification(md); // we are done here return Response.ok().entity(mapper.createObjectNode().putPOJO("metadata", md.toJson()).toString()) .build(); } catch (BadRequestException e) { return e.getResponse(); } catch (NotFoundException e) { return ErrorResponse.notFound(e.getMessage()).build(); } catch (IllegalAccessException e) { log.warn("Persistence Error: Unable to update record, invalid owner: " + user.getEmail()); log.warn("Message: " + e.getMessage()); return ErrorResponse.forbidden("Logged in User is not allowed to modify this record.").build(); } catch (ValidationException e) { log.warn("Validation Error: " + e.getMessage()); return ErrorResponse.badRequest(e.getMessage()).build(); } catch (IOException | InvocationTargetException e) { if (em.getTransaction().isActive()) em.getTransaction().rollback(); log.warn("Persistence Error Submitting: " + e.getMessage()); return ErrorResponse.internalServerError("Persistence error submitting record.").build(); } finally { em.close(); } }