Esempio n. 1
0
  /**
   * Saves restaurant into the database. Collects all data from the form, checks if provided hotel
   * already contains a restaurant (according to project specifications, one hotel can contain only
   * one restaurant).
   *
   * @param hotelId
   * @return
   */
  @Security.Authenticated(Authenticators.SellerFilter.class)
  public Result saveRestaurant(Integer hotelId) {

    // Checking if there is a restaurant with provided
    // hotel id in the database.
    if (!Restaurant.existsInDB(hotelId)) {
      Form<Restaurant> boundForm = restaurantForm.bindFromRequest();

      Restaurant restaurant = new Restaurant();
      Form<Restaurant> restaurantForm1 = restaurantForm.bindFromRequest();

      // Collecting data from the form
      String name = restaurantForm1.field("name").value();
      String restaurantType = restaurantForm1.field("restauranType").value();
      Integer capacity = Integer.parseInt(restaurantForm1.field("capacity").value());
      String description = restaurantForm1.field("description").value();
      String open = restaurantForm1.field("restOpen").value();
      String close = restaurantForm1.field("restClose").value();
      String workingHours = open + " - " + close;

      restaurant.name = name;
      restaurant.restauranType = restaurantType;
      restaurant.capacity = capacity;
      restaurant.workingHours = workingHours;
      restaurant.description = description;

      // Finding hotel with provided hotel id
      Hotel hotel = Hotel.findHotelById(hotelId);

      // Checking if hotel with provided id exists
      if (hotel != null) {
        restaurant.hotel = hotel;
      }

      // Getting timestamp
      Calendar c = Calendar.getInstance();
      restaurant.timestamp = c.getTime();

      // Saving the restaurant into the database
      restaurant.save();

    } else {
      flash("error", "There is already added restaurant for selected hotel.");
      return ok(createRestaurant.render(hotelId));
    }

    if (session("userId") != null) {
      flash("create", "The restaurant was created!");
      return redirect(routes.Hotels.showSellerHotels());
    } else {
      return redirect(routes.Application.index());
    }
  }
Esempio n. 2
0
  public Result updateVitalsPost(int id) {

    CurrentUser currentUser = sessionService.getCurrentUserSession();

    ServiceResponse<IPatientEncounter> currentEncounterByPatientId =
        searchService.findCurrentEncounterByPatientId(id);

    UpdateVitalsModel updateVitalsModel = updateVitalsModelForm.bindFromRequest().get();

    List<? extends IPatientEncounterVital> patientEncounterVitals =
        medicalHelper.populatePatientVitals(
            updateVitalsModel,
            currentUser.getId(),
            currentEncounterByPatientId.getResponseObject().getId());
    ServiceResponse<IPatientEncounterVital> patientEncounterVitalServiceResponse;
    for (int i = 0; i < patientEncounterVitals.size(); i++) {
      if (patientEncounterVitals.get(i).getVitalValue() > 0) {
        patientEncounterVitalServiceResponse =
            triageService.createPatientEncounterVital(patientEncounterVitals.get(i));
        if (patientEncounterVitalServiceResponse.hasErrors()) {
          return internalServerError();
        }
      }
    }
    return ok("true");
  }
Esempio n. 3
0
  public Result sendMail() {
    final Form<MailMe> filledForm = FORM.bindFromRequest();
    if (filledForm.hasErrors()) {
      return badRequest(index.render(filledForm));
    } else {
      final String email = filledForm.get().email;
      final Body body =
          new Body(
              views.txt.email.body.render().toString(), views.html.email.body.render().toString());

      {
        // simple usage
        defaultMailer.sendMail("play-easymail | it works!", body, email);
      }

      {
        // advanced usage
        final Mail customMail = new Mail("play-easymail | advanced", body, new String[] {email});
        customMail.addHeader("Reply-To", email);
        customMail.addAttachment("attachment.pdf", env.getFile("conf/sample.pdf"));
        byte[] data = "data".getBytes();
        customMail.addAttachment(
            "data.txt", data, "text/plain", "A simple file", EmailAttachment.INLINE);
        defaultMailer.sendMail(customMail);
      }

      flash("message", "2 mails to '" + email + "' have been sent successfully!");
      return redirect(routes.HomeController.index());
    }
  }
  /** Process the form to create a new custom and external KPI. */
  public Result processCreate() {

    // bind the form
    Form<CustomExternalKpiFormData> boundForm = customExternalKpiFormTemplate.bindFromRequest();

    // get the object type
    String objectType = boundForm.data().get("objectType");

    if (boundForm.hasErrors()) {
      return ok(views.html.admin.kpi.create.render(objectType, boundForm));
    }

    CustomExternalKpiFormData customExternalKpiFormData = boundForm.get();

    KpiDefinition kpiDefinition = customExternalKpiFormData.constructKpiDefinition();

    kpiDefinition.mainKpiValueDefinition.save();
    kpiDefinition.additional1KpiValueDefinition.save();
    kpiDefinition.additional2KpiValueDefinition.save();
    kpiDefinition.save();

    customExternalKpiFormData.mainName.persist(getI18nMessagesPlugin());
    customExternalKpiFormData.additional1Name.persist(getI18nMessagesPlugin());
    customExternalKpiFormData.additional2Name.persist(getI18nMessagesPlugin());

    reloadKpiDefinition(kpiDefinition.uid);

    Utilities.sendSuccessFlashMessage(Msg.get("admin.kpi.create.successful"));

    return redirect(controllers.admin.routes.KpiManagerController.view(kpiDefinition.id));
  }
Esempio n. 5
0
  @Security.Authenticated(Secured.class)
  public static Result newUser() {
    User user = getCurrentUser();
    if (!user.isAdmin) return redirect(routes.Application.contacts());
    Form<User> filledForm = userForm.bindFromRequest();

    if (!filledForm.field("password").valueOr("").isEmpty()) {
      if (!filledForm
          .field("password")
          .valueOr("")
          .equals(filledForm.field("repeatPassword").value())) {
        filledForm.reject("repeatPassword", "Passwörter stimmen nicht überein");
      }
    }

    if (!filledForm.hasErrors()) {
      if (userAlreadyExists(filledForm.get().email)) {
        filledForm.reject("email", "Diese Emailadresse ist bereits vergeben");
      }
    }

    if (filledForm.hasErrors()) {
      flash("error", "Bitte korrigieren sie ihre Eingaben!");
      return badRequest(views.html.addUser.render(filledForm, getCurrentUser(), User.find.all()));
    } else {
      User.create(filledForm.get());
      flash("success", "Benutzer " + filledForm.get().email + " erstellt.");
      return redirect(routes.Application.contacts());
    }
  }
  /** Save the capacity. */
  @With(CheckActorExists.class)
  @Dynamic(IMafConstants.ACTOR_EDIT_DYNAMIC_PERMISSION)
  public Result saveCapacity() {

    // bind the form
    Form<ActorCapacityFormData> boundForm = capacityFormTemplate.bindFromRequest();

    // get the actor
    Long id = Long.valueOf(boundForm.data().get("id"));
    Actor actor = ActorDao.getActorById(id);

    // get the year
    Integer year = Integer.valueOf(boundForm.data().get("year"));

    if (boundForm.hasErrors()) {
      return ok(views.html.core.actor.actor_capacity.render(actor, year, boundForm, true));
    }

    ActorCapacityFormData capacityFormData = boundForm.get();

    for (ActorCapacity capacity : capacityFormData.getFilledCapacities()) {
      capacity.save();
    }

    Utilities.sendSuccessFlashMessage(Msg.get("core.actor.capacity.save.successful"));

    return redirect(
        controllers.core.routes.ActorController.capacity(
            capacityFormData.id, capacityFormData.year));
  }
Esempio n. 7
0
  @Dynamic("editor")
  public static Result hostMeetUp() {
    final Form<utils.Forms.MeetUpHosting> filledForm = HOST_MEETUP_FORM.bindFromRequest();
    final User u = Mupi.getLocalUser(session());
    final models.Profile p = u.getProfile();
    String lastName = p.getLastName();
    if (lastName == null) lastName = "";
    String interest = "--desconhecido--";
    String location = "--desconhecida--";

    if (getLocalInterest() != null && getLocalInterest() != -1)
      interest = models.Interest.find.byId(getLocalInterest()).getName();

    if (getLocalLocation() != null && getLocalLocation() != -1)
      location = models.Location.find.byId(getLocalLocation()).getName();

    final String subject =
        "[EventoMupi][Local] "
            + p.getFirstName()
            + " "
            + lastName
            + " quer receber encontros amiguinhos!  Yayyy!!";

    final String body =
        "O usuário "
            + p.getFirstName()
            + " "
            + lastName
            + " ("
            + u.email
            + ") "
            + "quer receber encontros da seguinte comunidade:\n"
            + "\n    Localidade - "
            + location
            + "\n    Interesse - "
            + interest
            + "\n\n Ele redigiu a seguinte descrição:\n"
            + filledForm.get().description;
    final String from = "*****@*****.**";
    final String to = MupiParams.HOST_MEETUP_EMAIL;
    final String replyTo = "*****@*****.**";

    new AssyncEmailSender(subject, body, from, replyTo, to).send();

    final String userSubject = "Receber Evento Mupi";
    final String userBody =
        "Olá "
            + p.getFirstName()
            + ",\n\n"
            + "Recebemos sua mensagem sobre o interesse em receber Eventos Mupi. Em breve entraremos em contato para os próximos passos.\n\n\n"
            + "Atenciosamente,\n"
            + "Equipe Mupi";
    final String userFrom = "*****@*****.**";
    final String userTo = u.email;
    final String userReplyTo = "*****@*****.**";

    new AssyncEmailSender(userSubject, userBody, userFrom, userReplyTo, userTo).send();

    return redirect(routes.Feed.feed());
  }
  /** Send a notification message. */
  public Result sendMessage() {

    try {
      Form<NotificationMessage> boundForm = notificationMessageForm.bindFromRequest();
      if (boundForm.hasErrors()) {

        String loggedUser = getUserSessionManagerPlugin().getUserSessionId(ctx());

        List<MessageListView> messageListViewRows = new ArrayList<>();
        List<Notification> notifications =
            getNotificationManagerPlugin().getMessagesForUid(loggedUser);
        for (Notification notification : notifications) {
          messageListViewRows.add(
              new MessageListView(this.getAccountManagerPlugin(), notification));
        }
        Table<MessageListView> messagesTables =
            this.getTableProvider().get().message.templateTable.fill(messageListViewRows);

        return ok(views.html.messaging.index.render(messagesTables, boundForm));
      }
      NotificationMessage notificationMessage = boundForm.get();
      getNotificationManagerPlugin()
          .sendMessage(
              getUserSessionManagerPlugin().getUserSessionId(ctx()),
              notificationMessage.principalUids,
              notificationMessage.title,
              notificationMessage.message);
      Utilities.sendSuccessFlashMessage(
          getI18nMessagesPlugin().get("messaging.send.success", notificationMessage.title));
      return redirect(routes.MessagingController.index());
    } catch (Exception e) {
      return ControllersUtils.logAndReturnUnexpectedError(
          e, log, getConfiguration(), getI18nMessagesPlugin());
    }
  }
Esempio n. 9
0
  @SubjectPresent
  public Result doMerge() {
    com.feth.play.module.pa.controllers.Authenticate.noCache(response());
    // this is the currently logged in user
    final AuthUser aUser = PlayAuthenticate.getUser(session());

    // this is the user that was selected for a login
    final AuthUser bUser = PlayAuthenticate.getMergeUser(session());
    if (bUser == null) {
      // user to merge with could not be found, silently redirect to login
      return redirect(routes.Application.index());
    }

    final Form<Accept> filledForm = ACCEPT_FORM.bindFromRequest();
    if (filledForm.hasErrors()) {
      // User did not select whether to merge or not merge
      return badRequest((Content) ask_merge.render("Merge Form"));
    } else {
      // User made a choice :)
      final boolean merge = filledForm.get().accept;
      if (merge) {
        flash(
            Application.FLASH_MESSAGE_KEY, Messages.get("playauthenticate.accounts.merge.success"));
      }
      return PlayAuthenticate.merge(ctx(), merge);
    }
  }
  /** Process the edit form of the scheduler of a KPI definition. */
  public Result saveScheduler() {

    // bind the form
    Form<KpiSchedulerFormData> boundForm = kpiSchedulerFormTemplate.bindFromRequest();

    // get the KPI
    Long kpiDefinitionId = Long.valueOf(boundForm.data().get("id"));
    KpiDefinition kpiDefinition = KpiDefinition.getById(kpiDefinitionId);
    Kpi kpi = new Kpi(kpiDefinition, getKpiService());

    if (boundForm.hasErrors()) {
      return ok(views.html.admin.kpi.editScheduler.render(kpiDefinition, kpi, boundForm));
    }

    KpiSchedulerFormData kpiSchedulerFormData = boundForm.get();

    kpiSchedulerFormData.fill(kpiDefinition);
    kpiDefinition.update();

    reloadKpiDefinition(kpiDefinition.uid);

    Utilities.sendSuccessFlashMessage(Msg.get("admin.kpi.editscheduler.successful"));

    return redirect(controllers.admin.routes.KpiManagerController.view(kpiDefinition.id));
  }
Esempio n. 11
0
  // TODO change to use Contact.create() method
  @Security.Authenticated(Secured.class)
  public static Result newContact() {

    Form<Contact> filledForm = contactForm.bindFromRequest();

    String name = filledForm.data().get("name");
    String firstName = filledForm.data().get("firstName");
    String title = filledForm.data().get("title");
    String email = filledForm.data().get("email");
    String street = filledForm.data().get("street");
    String appendix1 = filledForm.data().get("appendix1");
    String appendix2 = filledForm.data().get("appendix2");
    String zipcode = filledForm.data().get("zipcode");
    String country = filledForm.data().get("country");
    String city = filledForm.data().get("city");
    String phone = filledForm.data().get("phone");
    String yearbook = filledForm.data().get("yearbookSubscription");
    String memberCategory = filledForm.data().get("memberCategory");
    String membershipSince = filledForm.data().get("membershipSince");

    Contact newContact = new Contact();
    newContact.name = name;
    newContact.firstName = firstName;
    newContact.title = title;
    newContact.email = email;
    newContact.street = street;
    newContact.appendix1 = appendix1;
    newContact.appendix2 = appendix2;
    newContact.zipcode = zipcode;
    newContact.city = city;
    newContact.country = country;
    newContact.phone = phone;

    if (yearbook.equals("true")) newContact.yearbookSubscription = true;
    newContact.memberCategory = memberCategory;

    for (int j = 0; j < ContactGroup.options().size(); j++) {
      String item = "belongsTo[" + j + "]";
      if (filledForm.data().get(item) != null) {
        ContactGroup cg =
            ContactGroup.find.byId((long) Integer.parseInt(filledForm.data().get(item)));
        newContact.belongsTo.add(cg);
      }
    }

    if (newContact.belongsTo.isEmpty())
      filledForm.reject("belongsTo[]", "Keine Sektion ausgewählt");

    // TODO Check fields for errors

    if (filledForm.hasErrors()) System.out.println(filledForm.errors().toString());

    newContact.membershipSince = membershipSince;
    newContact.createdAt = new Timestamp(new Date().getTime());
    newContact.lastEditedAt = newContact.createdAt;
    newContact.save();
    flash("success", "Kontakt " + newContact + " erstellt und gespeichert.");
    return redirect(routes.Application.contacts());
  }
Esempio n. 12
0
    public static Result index() {
      Form<User> userForm = Form.form(User.class);
      // #bind-from-request
      User user = userForm.bindFromRequest().get();
      // #bind-from-request

      return ok(user.email);
    }
Esempio n. 13
0
 public static Result newTask() {
   Form<Task> filledForm = taskForm.bindFromRequest();
   if (filledForm.hasErrors()) return badRequest(views.html.task.render(Task.all(), filledForm));
   else {
     Task.createTask(filledForm.get());
     return redirect(routes.Application.getTasks());
   }
 }
Esempio n. 14
0
  /**
   * Do forgot password.
   *
   * @return the result
   */
  public static Result doForgotPassword() {
    Logger.debug("Account doForgotPassword");
    com.feth.play.module.pa.controllers.Authenticate.noCache(response());
    final Form<EmailUserIdentity> filledForm = FORGOT_PASSWORD_FORM.bindFromRequest();
    if (filledForm.hasErrors()) {
      // User did not fill in his/her email
      return badRequest(password_forgot.render(filledForm));
    } else {
      // The email address given *BY AN UNKNWON PERSON* to the form - we
      // should find out if we actually have a user with this email
      // address and whether password login is enabled for him/her. Also
      // only send if the email address of the user has been verified.
      final String email = filledForm.get().email;

      final User user = User.findByEmail(email);
      if (user == null) {
        // We don't want to expose whether a given email address is signed
        // up, so just say an email has been sent, even though it might not
        // be true - that's protecting our user privacy.
        flash(
            ControllerUtil.FLASH_WARNING_KEY,
            "Your email address doesn't match our records. Please try again.");
      } else {
        // We don't want to expose whether a given email address is signed
        // up, so just say an email has been sent, even though it might not
        // be true - that's protecting our user privacy.
        flash(
            ControllerUtil.FLASH_INFO_KEY,
            Messages.get("playauthenticate.reset_password.message.instructions_sent", email));

        // yep, we have a user with this email that is active - we do
        // not know if the user owning that account has requested this
        // reset, though.
        final EmailAuthProvider provider = EmailAuthProvider.getProvider();
        // User exists
        if (user.emailValidated) {
          provider.sendPasswordResetMailing(user, ctx());
          // In case you actually want to let (the unknown person)
          // know whether a user was found/an email was sent, use,
          // change the flash message
        } else {
          // We need to change the message here, otherwise the user
          // does not understand whats going on - we should not verify
          // with the password reset, as a "bad" user could then sign
          // up with a fake email via OAuth and get it verified by an
          // a unsuspecting user that clicks the link.
          flash(
              ControllerUtil.FLASH_INFO_KEY,
              Messages.get("playauthenticate.reset_password.message.email_not_verified"));

          // You might want to re-send the verification email here...
          provider.sendVerifyEmailMailingAfterSignup(user, ctx());
        }
      }

      return redirect(routes.Signup.login());
    }
  }
Esempio n. 15
0
  public static Result doRegistrieren() {

    Map<String, String[]> parameters = request().body().asFormUrlEncoded();

    Form<User> form = Form.form(User.class);

    form = form.bindFromRequest();

    if (form.hasErrors()) {
      return badRequest(views.html.registrieren.render("war nix. Fehler: " + form.errors()));
    } else {
      User user = form.get();

      if (!user.password.equals(parameters.get("password2")[0])) {
        return badRequest(views.html.registrieren.render("Passwörter stimmen nicht überein"));
      }
      // UserDB.init();
      //
      DBUser users = DBUser.get();
      // TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
      Date date = new Date();
      Date d = new Date();
      try {
        //  30-07-1987
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+1:00"));
        Logger.info("date from js " + parameters.get("datepicker")[0]);
        String datefromForm = parameters.get("datepicker")[0];
        // String datefromForm = "2013-05-04";
        date = sdf.parse(datefromForm);

        Logger.info(date.toString());
      } catch (Exception e) {
        Logger.info("Fehler beim Date \n" + e);
      }

      if (date == null) {
        return badRequest(views.html.registrieren.render("Date geht noch nicht...oder war leer!"));
      }

      // Date date = sdf.parse(user.date);

      User newUser =
          users.create(new User(user.email, user.password, user.nickname, user.fahrer, date));

      // +" remember: " +user.remember);
      // UserDB userDB = UserDB.get();
      // User userDB = UserDB.get().validateUser(user.email,
      // user.password);
      if (newUser != null) {

        return ok(views.html.loginform.render(""));
      } else {
        // return badRequest("falsche Angaben");
        return badRequest(views.html.registrieren.render("E-Mail existiert bereits"));
      }
    }
  }
Esempio n. 16
0
  public static Result create() throws NoSuchAlgorithmException {
    models.Person person = personForm.bindFromRequest().get();

    if (personForm.hasErrors()) {
      return badRequest();
    }

    person.save();
    return ok("Got user " + person.toString());
  }
  public static Result create_save() {
    Form<CustomerForm> filledForm = customerForm.bindFromRequest();

    if (filledForm.hasErrors()) {
      System.out.println("in error");
      return badRequest(create.render(filledForm));
    }

    CustomerForm customerForm = filledForm.get();
    if (customerForm == null) {
      System.out.println("in form");
      return badRequest(create.render(filledForm));
    }

    Customer customer = new Customer();
    formToModel(customer, customerForm);
    MultipartFormData body = request().body().asMultipartFormData();
    FilePart picture1 = body.getFile("signatureOne");
    FilePart picture2 = body.getFile("signatureTwo");
    if (picture1 != null && picture2 != null) {
      File file1 = picture1.getFile();
      File file2 = picture2.getFile();
      String path = "public/signatureimages/" + customer.accountNumber;
      File f = new File(path);
      f.mkdir();
      file1.renameTo(new File(path, customer.signatureOne));
      file2.renameTo(new File(path, customer.signatureTwo));
      System.out.println("File uploaded successfully...");
    } else {
      filledForm.reject("file", "Please select the image to uplaod");
    }

    String inputFile =
        "public/signatureimages/" + customer.accountNumber + "/" + customer.signatureOne;
    String smoothfilename =
        "public/signatureimages/" + customer.accountNumber + "/signatureOne_smooth.jpg";
    String binaryfilename =
        "public/signatureimages/" + customer.accountNumber + "/signatureOne_binary.jpg";
    String sizeNormalizeFileName =
        "public/signatureimages/" + customer.accountNumber + "/signatureOne_normalize.jpg";
    SigImgProcessingController.smoothing(inputFile, smoothfilename);
    SigImgProcessingController.binarization(smoothfilename, binaryfilename);
    SigImgProcessingController.sizeNormalization(binaryfilename, sizeNormalizeFileName);
    float[] sig1 = SigImgProcessingController.calculateAngles(sizeNormalizeFileName);
    StringBuffer angels = new StringBuffer();

    for (int i = 0; i < sig1.length; i++) {
      angels.append(sig1[i] + "|");
    }
    System.out.println("Angles: " + angels);
    customer.signOneAngles = angels.toString();

    customer.save();
    return redirect(controllers.routes.CustomerController.index());
  }
  /** Process the form to create/edit an allocation with an activity. */
  @With(CheckActorExists.class)
  @Dynamic(IMafConstants.ACTOR_EDIT_DYNAMIC_PERMISSION)
  public Result processManageAllocatedActivity() {

    // bind the form
    Form<TimesheetActivityAllocatedActorFormData> boundForm =
        allocatedActivityFormTemplate.bindFromRequest();

    // get the actor
    Long id = Long.valueOf(boundForm.data().get("id"));
    Actor actor = ActorDao.getActorById(id);

    if (boundForm.hasErrors()
        || this.getCustomAttributeManagerService()
            .validateValues(boundForm, TimesheetActivityAllocatedActor.class)) {
      return ok(views.html.core.actor.allocated_activity_manage.render(actor, boundForm));
    }

    TimesheetActivityAllocatedActorFormData allocatedActivityFormData = boundForm.get();

    TimesheetActivityAllocatedActor allocatedActivity = null;

    if (allocatedActivityFormData.allocatedActivityId == null) { // create
      // case

      allocatedActivity = new TimesheetActivityAllocatedActor();
      allocatedActivityFormData.fill(allocatedActivity);
      allocatedActivity.save();

      Utilities.sendSuccessFlashMessage(Msg.get("core.actor.allocated_activity.add.successful"));

    } else { // edit case

      allocatedActivity =
          TimesheetDao.getTimesheetActivityAllocatedActorById(
              allocatedActivityFormData.allocatedActivityId);

      // security: the actor must be related to the object
      if (!allocatedActivity.actor.id.equals(id)) {
        return forbidden(views.html.error.access_forbidden.render(""));
      }

      allocatedActivityFormData.fill(allocatedActivity);
      allocatedActivity.update();

      Utilities.sendSuccessFlashMessage(Msg.get("core.actor.allocated_activity.edit.successful"));
    }

    // save the custom attributes
    this.getCustomAttributeManagerService()
        .validateAndSaveValues(
            boundForm, TimesheetActivityAllocatedActor.class, allocatedActivity.id);

    return redirect(controllers.core.routes.ActorController.allocationDetails(id, 0, 0, false));
  }
 public Result add() {
   Form<Budget> filledForm = budgetForm.bindFromRequest();
   Result result = null;
   if (filledForm.hasErrors()) {
     result = badRequest();
   } else {
     Budget.create(filledForm.get());
     result = ok(Json.toJson(Budget.all()));
   }
   return result;
 }
Esempio n. 20
0
 public static Result create(Long produtoId) {
   Form<ItemBacklog> formAux = formItem.bindFromRequest();
   if (formAux.hasErrors()) {
     return badRequest(index.render(produtoId, formAux, listaItensBacklog(produtoId)));
   } else {
     ItemBacklog item = formAux.get();
     item.produto = Produto.find.ref(produtoId);
     item.save();
     return ok(index.render(produtoId, formItem, listaItensBacklog(produtoId)));
   }
 }
  /** Process the manage form of a KPI color rule. */
  public Result saveRule() {

    // bind the form
    Form<KpiColorRuleFormData> boundForm = kpiColorRuleFormTemplate.bindFromRequest();

    // get the KPI
    Long kpiDefinitionId = Long.valueOf(boundForm.data().get("kpiDefinitionId"));
    KpiDefinition kpiDefinition = KpiDefinition.getById(kpiDefinitionId);
    Kpi kpi = new Kpi(kpiDefinition, getKpiService());

    if (boundForm.hasErrors()) {
      return ok(
          views.html.admin.kpi.manageRule.render(
              kpiDefinition,
              kpi,
              boundForm,
              Color.getColorsAsValueHolderCollection(getI18nMessagesPlugin())));
    }

    KpiColorRuleFormData kpiColorRuleFormData = boundForm.get();

    KpiColorRule kpiColorRule = null;

    if (kpiColorRuleFormData.kpiColorRuleId == null) { // create case

      kpiColorRule = new KpiColorRule();

      kpiColorRule.kpiDefinition = kpiDefinition;
      kpiColorRule.order = KpiColorRule.getLastOrder(kpiDefinition.id) + 1;

      kpiColorRuleFormData.fill(kpiColorRule);

      kpiColorRule.save();

      Utilities.sendSuccessFlashMessage(Msg.get("admin.kpi.rule.add.successful"));

    } else { // edit case

      kpiColorRule = KpiColorRule.getById(kpiColorRuleFormData.kpiColorRuleId);

      kpiColorRuleFormData.fill(kpiColorRule);

      kpiColorRule.update();

      Utilities.sendSuccessFlashMessage(Msg.get("admin.kpi.rule.edit.successful"));
    }

    kpiColorRuleFormData.renderLabel.persist(getI18nMessagesPlugin());

    reloadKpiDefinition(kpiDefinition.uid);

    return redirect(controllers.admin.routes.KpiManagerController.view(kpiDefinition.id));
  }
Esempio n. 22
0
 public static Result update(Long id) {
   Long produtoId = ItemBacklog.find.ref(id).produto.id;
   Form<ItemBacklog> formAux = formItem.bindFromRequest();
   if (formAux.hasErrors()) {
     return badRequest(editForm.render(id, formAux));
   } else {
     ItemBacklog item = formAux.get();
     item.produto = Produto.find.ref(produtoId);
     item.update(id);
     return index(produtoId, lastOrderBy);
   }
 }
Esempio n. 23
0
  @Security.Authenticated(Secured.class)
  public static Result updateContact(Long id) {

    Form<Contact> updatedForm = contactForm.bindFromRequest();

    String name = updatedForm.data().get("name");
    String firstName = updatedForm.data().get("firstName");
    String title = updatedForm.data().get("title");
    String email = updatedForm.data().get("email");
    String street = updatedForm.data().get("street");
    String appendix1 = updatedForm.data().get("appendix1");
    String appendix2 = updatedForm.data().get("appendix2");
    String zipcode = updatedForm.data().get("zipcode");
    String country = updatedForm.data().get("country");
    String city = updatedForm.data().get("city");
    String phone = updatedForm.data().get("phone");
    String memberCategory = updatedForm.data().get("memberCategory");
    String membershipSince = updatedForm.data().get("membershipSince");
    String yearbook = updatedForm.data().get("yearbookSubscription");

    String contactGroup = "";
    for (int j = 0; j < ContactGroup.options().size(); j++) {
      String item = "belongsTo[" + j + "]";
      if (updatedForm.data().get(item) != null) {
        if (j > 0) contactGroup += "/";
        contactGroup += updatedForm.data().get(item);
      }
    }

    if (contactGroup.isEmpty()) updatedForm.reject("belongsTo[]", "Keine Sektion ausgewählt");

    Contact.find
        .byId(id)
        .update(
            title,
            name,
            firstName,
            email,
            street,
            appendix1,
            appendix2,
            zipcode,
            city,
            country,
            phone,
            membershipSince,
            memberCategory,
            yearbook,
            contactGroup);
    flash("success", "Kontakt bearbeitet und gespeichert.");
    return redirect(routes.Application.contacts());
  }
  public Result update(String id) {
    Result result = null;
    Form<Budget> filledForm = budgetForm.bindFromRequest();

    if (filledForm.hasErrors()) {
      result = badRequest();
    } else {
      Budget.update(id, filledForm.get());
      result = display(id);
    }

    return result;
  }
Esempio n. 25
0
 public static Result newTask() {
   User user = loadUser();
   Form<Task> filledForm = taskForm.bindFromRequest();
   if (filledForm.hasErrors()) {
     flash("error", "The task could not be saved.");
     return badRequest(main.render("Tasks", null, tasks.render(user.tasks, filledForm)));
   } else {
     Task task = filledForm.get();
     task.owner = user;
     task.save();
     return created(main.render("Tasks", null, tasks.render(user.tasks, taskForm)));
   }
 }
Esempio n. 26
0
  public static Result editMeal(int id) {

    String userEmail = Session.getCurrentUser(ctx()).email;

    Meal oldMeal = Meal.find(id);

    String mealName = inputForm.bindFromRequest().field("name").value();
    String mealPrice = inputForm.bindFromRequest().field("price").value();
    String mealCategory = inputForm.bindFromRequest().field("category").value();
    String mealDescription = inputForm.bindFromRequest().field("description").value();

    mealPrice = mealPrice.replace(',', '.');
    Double price = Double.parseDouble(mealPrice);

    try {
      Meal.modifyMeal(oldMeal, mealName, price, mealCategory, mealDescription);
      flash("successEdited", "You have successfully edited your meal");
      Logger.info("User " + userEmail + " just edited meal " + oldMeal.id);
    } catch (Exception e) {
      Logger.error("User " + userEmail + " failed to edit meal " + oldMeal.id);
    }
    return redirect("/restaurantOwner/" + userEmail);
  }
  /**
   * Validates fields from the registration form and either creates a new user or communicates any
   * validation errors.
   */
  public static Result submit() {
    Form<User> filledForm = signupForm.bindFromRequest();

    // Check accept conditions
    if (!"true".equals(filledForm.field("accept").value())) {
      filledForm.reject("accept", "You must accept the terms and conditions");
    }

    // Check repeated password
    if (!filledForm.field("password").valueOr("").isEmpty()) {
      if (!filledForm
          .field("password")
          .valueOr("")
          .equals(filledForm.field("repeatPassword").value())) {
        filledForm.reject("repeatPassword", "Passwords do not match");
      }
    }

    // Check if the username and email are valid
    if (!filledForm.hasErrors()) {

      String un = filledForm.get().username;
      String email = filledForm.get().email;

      if (un.equals("admin") || un.equals("guest")) {
        filledForm.reject("username", "This username is already taken");
      }

      try {
        Logger.debug("Finding user " + email);
        User.findByEmail(email);
        filledForm.reject(
            "email", "There is already an account associated with this email address.");
      } catch (Exception e) {
        // continue - the user does not exist
      }
    }

    // Return validation results to user or save user
    if (filledForm.hasErrors()) {
      return badRequest(form.render(filledForm));
    } else {
      User user = filledForm.get(); /* create an object from a form */
      User svUser =
          new User(user.username, user.email, user.password); /* recreate to get save group info */
      svUser.save();
      return ok(summary.render(svUser));
    }
  }
Esempio n. 28
0
 /*
  * POST form submission
  *
  */
 public static Result gameSubmit() throws EvrythngException, EvrythngClientException {
   answerForm.discardErrors();
   Form<Answer> filledForm = answerForm.bindFromRequest();
   if (filledForm.hasErrors()) {
     return badRequest(game.render(getThngById(session("lastThngID")), filledForm));
   } else {
     Answer ans = filledForm.get();
     Thng prevThing = getThngById(ans.prevThngID);
     if (!prevThing.getCustomFields().get("nextthng").equals(ans.nextThngID)) {
       filledForm.reject("nextThngID", "The entered ID is not valid. Try again!");
       return badRequest(game.render(getThngById(ans.prevThngID), filledForm));
     }
     return game(ans.nextThngID);
   }
 }
Esempio n. 29
0
  /**
   * Method to create meal. Use Meal.create method from models.
   *
   * @return
   */
  @Security.Authenticated(RestaurantFilter.class)
  public static Result createMeal() {
    User u = Session.getCurrentUser(ctx());
    if (!u.role.equalsIgnoreCase("RESTAURANT")) {
      return ok(views.html.admin.wrong.render("Cannot create meal if you're not reastaurant! "));
    }

    String mealName = inputForm.bindFromRequest().field("name").value();
    String mealPrice = inputForm.bindFromRequest().field("price").value();
    String mealCategory = inputForm.bindFromRequest().field("category").value();
    String mealDescription = inputForm.bindFromRequest().field("description").value();

    mealPrice = mealPrice.replace(',', '.');
    Double price = Double.parseDouble(mealPrice);
    Restaurant currentUser = u.restaurant;

    if ((Meal.create(mealName, price, mealCategory, currentUser, mealDescription)) == true) {
      Meal m =
          findM
              .where()
              .eq("name", mealName)
              .eq("price", mealPrice)
              .eq("restaurant_id", u.restaurant.id)
              .findUnique();
      String userEmail = Session.getCurrentUser(ctx()).email;
      Logger.debug(m.name);
      session("email", userEmail);
      flash("successMeal", "Succesfully created meal!");
      Logger.info("Restaurant " + currentUser.name + " just created meal");
      return ok(
          views.html.restaurant.fileUploadMeal.render("", userEmail, m, Restaurant.all(), m.image));
      // return redirect("/restaurantOwner/" + userEmail);
    }
    Logger.error("Restaurant " + currentUser.name + " failed to create meal.");
    return TODO;
  }
 /**
  * Do change password.
  *
  * @return the result
  */
 @SubjectPresent
 public static Result doChangePassword() {
   com.feth.play.module.pa.controllers.Authenticate.noCache(response());
   final Form<Account.PasswordChange> filledForm = PASSWORD_CHANGE_FORM.bindFromRequest();
   if (filledForm.hasErrors()) {
     // User did not select whether to link or not link
     return badRequest(password_change.render(filledForm));
   } else {
     final User user = ControllerUtil.getLocalUser(session());
     final String newPassword = filledForm.get().password;
     user.changePassword(new EmailAuthUser(newPassword), true);
     flash(
         ControllerUtil.FLASH_INFO_KEY, Messages.get("playauthenticate.change_password.success"));
     return redirect(routes.Application.profile());
   }
 }