/**
   * Form to edit the main data of a KPI value definition.
   *
   * @param kpiValueDefinitionId the KPI value definition
   * @param valueType the value type (main, additional1, additional2)
   */
  public Result editValue(Long kpiValueDefinitionId, String valueType) {

    // get the KPI value
    KpiValueDefinition kpiValueDefinition = KpiValueDefinition.getById(kpiValueDefinitionId);

    // get the KPI
    KpiDefinition kpiDefinition = KpiDefinition.getById(kpiValueDefinition.getKpiDefinition().id);
    Kpi kpi = new Kpi(kpiDefinition, getKpiService());

    Form<KpiValueDefinitionFormData> form = null;

    if (kpiDefinition.isStandard) {
      form =
          standardKpiValueDefinitionFormTemplate.fill(
              new KpiValueDefinitionFormData(kpiValueDefinition, getI18nMessagesPlugin()));
    } else {
      form =
          customKpiValueDefinitionFormTemplate.fill(
              new KpiValueDefinitionFormData(kpiValueDefinition, getI18nMessagesPlugin()));
    }

    return ok(
        views.html.admin.kpi.editValue.render(
            kpiDefinition,
            kpi,
            kpiValueDefinition,
            valueType,
            form,
            getRenderTypesAsValueHolderCollection()));
  }
  /** 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));
  }
  /**
   * Returns the player profile page with the submitted info.
   *
   * @return The player profile page, which was just created/edited
   */
  @Security.Authenticated(Secured.class)
  public static Result playerManageSubmit() {
    // adds the new player from the PlayerForm page to the database.
    Form<PlayerFormData> data = Form.form(PlayerFormData.class).bindFromRequest();

    SearchFormData data2 = new SearchFormData();
    Form<SearchFormData> dataForm = Form.form(SearchFormData.class).fill(data2);
    Page<Player> playerPage = Player.find("name asc", 0);
    User user = Secured.getUserInfo(ctx());

    if (data.hasErrors()) {
      Map<String, Boolean> playerSkillMap = PlayerFields.getSkill();
      Map<String, Boolean> playerPosition = PlayerFields.getPosition();
      return badRequest(
          PlayerForm.render(
              "Bad Player Form", data, playerSkillMap, playerPosition, Secured.isLoggedIn(ctx())));
    } else {
      PlayerFormData formData = data.get();
      if (Player.getPlayer(user.getId()) == null) {
        // Player.addPlayer(formData);
      } else {
        Player.updatePlayer(formData, user.getId());
      }

      return ok(
          PlayerList.render(
              playerPage,
              "PlayerList",
              dataForm,
              "none",
              "none",
              Secured.isLoggedIn(ctx()),
              Secured.getUserInfo(ctx())));
    }
  }
  public static Result detallesRecorridos() {

    RecorridoDAO recorridoDAO = new RecorridoDAO();
    // ojo ajustar
    List<Recorrido> lstRecorridos = recorridoDAO.listarRecorridos();

    Form<FormularioConsultaRecorrido> form =
        Form.form(FormularioConsultaRecorrido.class).bindFromRequest();

    if (form.hasErrors()) {
      flash("error", "Se encontraron errores al consultar el recorrido.");
      return badRequest(
          views.html.recorridosConsulta.render(
              Form.form(FormularioConsultaRecorrido.class), lstRecorridos, null, null));

    } else {
      FormularioConsultaRecorrido formularioConsultaRecorrido = form.get();

      Recorrido recorrido =
          recorridoDAO.consultarRecorridoPorId(formularioConsultaRecorrido.idRecorrido);
      FormularioRecorrido formRecorrido = new FormularioRecorrido();
      formRecorrido.tipoRecorrido = String.valueOf(recorrido.getTipo());
      formRecorrido.nombre = recorrido.getNombre();
      formRecorrido.descripcion = recorrido.getDescripcion();
      formRecorrido.horaFrecuente = recorrido.getHoraFrecuente();

      String diasFrecuentes = recorrido.getDiaFrecuente();
      formRecorrido.diaFrecuente = new ArrayList<String>();
      if (diasFrecuentes != null) {
        String[] arrDias = diasFrecuentes.split(",");
        for (int i = 0; i < arrDias.length; i++) {
          formRecorrido.diaFrecuente.add(arrDias[i]);
        }
      }

      formRecorrido.fechaInicioRuta =
          String.valueOf(recorrido.getLstRuta().get(0).getFechaInicioRuta());
      formRecorrido.fechaFinRuta = String.valueOf(recorrido.getLstRuta().get(0).getFechaFinRuta());
      formRecorrido.latitudInicio =
          String.valueOf(recorrido.getLstRuta().get(0).getLatitudInicio());
      formRecorrido.longitudInicio =
          String.valueOf(recorrido.getLstRuta().get(0).getLongitudInicio());
      formRecorrido.latitudFin = String.valueOf(recorrido.getLstRuta().get(0).getLatitudFin());
      formRecorrido.longitudFin = String.valueOf(recorrido.getLstRuta().get(0).getLongitudFin());
      formRecorrido.lugarInicio = recorrido.getLstRuta().get(0).getLugarInicio();
      formRecorrido.lugarFin = recorrido.getLstRuta().get(0).getLugarFin();
      formRecorrido.lstAmigos = new ArrayList<String>();

      Boolean existe = false;
      User usuario = Application.getLocalUser(session());
      for (UsuarioXRecorrido usuarioRecorrido : recorrido.getLstUsuarioXRecorrido()) {
        formRecorrido.lstAmigos.add(usuarioRecorrido.getUsuario().name);
        if (usuario.id == usuarioRecorrido.getUsuario().id) existe = true;
      }

      formRecorrido.idRecorrido = recorrido.getIdRecorrido();

      return ok(views.html.recorridosDetalle.render(formRecorrido, existe));
    }
  }
Exemplo n.º 5
0
  @Test
  public void registerFormatter() {
    // #register-formatter
    Formatters.register(
        LocalTime.class,
        new SimpleFormatter<LocalTime>() {

          private Pattern timePattern = Pattern.compile("([012]?\\d)(?:[\\s:\\._\\-]+([0-5]\\d))?");

          @Override
          public LocalTime parse(String input, Locale l) throws ParseException {
            Matcher m = timePattern.matcher(input);
            if (!m.find()) throw new ParseException("No valid Input", 0);
            int hour = Integer.valueOf(m.group(1));
            int min = m.group(2) == null ? 0 : Integer.valueOf(m.group(2));
            return new LocalTime(hour, min);
          }

          @Override
          public String print(LocalTime localTime, Locale l) {
            return localTime.toString("HH:mm");
          }
        });
    // #register-formatter

    Form<WithLocalTime> form = Form.form(WithLocalTime.class);
    WithLocalTime obj = form.bind(ImmutableMap.of("time", "23:45")).get();
    assertThat(obj.time, equalTo(new LocalTime(23, 45)));
    assertThat(form.fill(obj).field("time").value(), equalTo("23:45"));
  }
Exemplo n.º 6
0
  /**
   * {@code posting}에 {@code original} 정보를 채우고 갱신한다.
   *
   * <p>when: 게시물이나 이슈를 수정할 떄 사용한다.
   *
   * @param original
   * @param posting
   * @param postingForm
   * @param redirectTo
   * @param updatePosting
   * @return
   */
  protected static Result editPosting(
      AbstractPosting original,
      AbstractPosting posting,
      Form<? extends AbstractPosting> postingForm,
      Call redirectTo,
      Callback updatePosting) {
    if (postingForm.hasErrors()) {
      return badRequest(postingForm.errors().toString());
    }

    if (!AccessControl.isAllowed(UserApp.currentUser(), original.asResource(), Operation.UPDATE)) {
      return forbidden(views.html.error.forbidden.render(original.project));
    }

    posting.id = original.id;
    posting.createdDate = original.createdDate;
    posting.authorId = original.authorId;
    posting.authorLoginId = original.authorLoginId;
    posting.authorName = original.authorName;
    posting.project = original.project;
    updatePosting.run();
    posting.update();

    // Attach the files in the current user's temporary storage.
    Attachment.moveAll(UserApp.currentUser().asResource(), original.asResource());

    return redirect(redirectTo);
  }
Exemplo n.º 7
0
  /**
   * This handles the login form submission for the Web IDE.
   *
   * @return The result of rendering the page.
   */
  @AddCSRFToken
  @RequireCSRFCheck
  @Transactional
  public CompletionStage<Result> login() {
    Form<LoginForm> userForm = myFormFactory.form(LoginForm.class).bindFromRequest();

    // Perform the basic validation checks.
    if (userForm.hasErrors()) {
      // Render the page with the login form with the errors fields
      String token = CSRF.getToken(request()).map(t -> t.value()).orElse("no token");
      return CompletableFuture.supplyAsync(
          () -> badRequest(index.render(userForm, token)), myHttpExecutionContext.current());
    } else {
      LoginForm form = userForm.get();

      // Check for a registered user with the same email.
      // Note that "connect" expects a JPA entity manager,
      // which is not present if we don't wrap the call using
      // "withTransaction()".
      User user = myJpaApi.withTransaction(() -> User.connect(form.getEmail(), form.getPassword()));
      if (user != null) {
        // Check to see if this account has been authenticated or not.
        boolean hasAuthenticated =
            myJpaApi.withTransaction(() -> User.hasAuthenticated(form.getEmail()));
        if (hasAuthenticated) {
          // Update the login date
          final User updatedUser = myJpaApi.withTransaction(() -> User.lastLogin(form.getEmail()));

          // Add a new user event
          myJpaApi.withTransaction(() -> UserEvent.addRegularEvent("login", "", updatedUser));

          // Stores the email as session value
          session("connected", form.getEmail());

          // Obtain the http context from the configuration file
          String context = myConfiguration.getString("play.http.context");
          if (context == null) {
            context = "";
          }

          // Redirect back to the home page
          final String finalContext = context;
          return CompletableFuture.supplyAsync(
              () -> redirect(finalContext + "/"), myHttpExecutionContext.current());
        } else {
          // Render the not authenticated page
          return CompletableFuture.supplyAsync(
              () -> ok(notAuthenticated.render(form.getEmail())), myHttpExecutionContext.current());
        }
      } else {
        // The email and/or password does not match, so we add a new validation error.
        userForm.reject(new ValidationError("loginError", "Could not login."));

        // Render the page with the login form with the errors fields
        String token = CSRF.getToken(request()).map(t -> t.value()).orElse("no token");
        return CompletableFuture.supplyAsync(
            () -> badRequest(index.render(userForm, token)), myHttpExecutionContext.current());
      }
    }
  }
  /** 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));
  }
Exemplo n.º 9
0
  /**
   * 로그인 처리 시스템 설정에서 가입승인 기능이 활성화 되어 있고 사용자 상태가 잠금상태(미승인?)라면 계정이 잠겼다는 메시지를 노출하고 로그인 폼으로 돌아감 시스템 설정에서
   * 가입승인 기능이 활성화 되어 있지 않다면, 사용자 상태가 잠금상태라도 로그인이 가능하다 (스펙확인 필요) 요청의 정보로 사용자 인증에 성공하면 로그인쿠키를 생성하고
   * 로그인유지하기가 선택되었다면, 로그인유지를 위한 쿠키를 별도로 생성한다 인증에 실패하면 관련된 메시지를 노출하고 로그인 폼으로 돌아간다
   *
   * @return
   */
  public static Result login() {
    Form<User> userForm = form(User.class).bindFromRequest();
    if (userForm.hasErrors()) {
      return badRequest(login.render("title.login", userForm));
    }
    User sourceUser = form(User.class).bindFromRequest().get();

    if (isUseSignUpConfirm()) {
      if (User.findByLoginId(sourceUser.loginId).state == UserState.LOCKED) {
        flash(Constants.WARNING, "user.locked");
        return redirect(routes.UserApp.loginForm());
      }
    }

    if (User.findByLoginId(sourceUser.loginId).state == UserState.DELETED) {
      flash(Constants.WARNING, "user.deleted");
      return redirect(routes.UserApp.loginForm());
    }

    User authenticate = authenticateWithPlainPassword(sourceUser.loginId, sourceUser.password);

    if (authenticate != null) {
      addUserInfoToSession(authenticate);
      if (sourceUser.rememberMe) {
        setupRememberMe(authenticate);
      }
      return redirect(routes.Application.index());
    }

    flash(Constants.WARNING, "user.login.failed");
    return redirect(routes.UserApp.loginForm());
  }
Exemplo n.º 10
0
  @Authenticated(value = {LoggedIn.class, HasRole.class})
  @Authorized(value = "admin")
  @Transactional
  @RequireCSRFCheck
  public Result postCreateArchive() {
    Form<ArchiveUpsertForm> archiveUpsertForm =
        Form.form(ArchiveUpsertForm.class).bindFromRequest();

    if (formHasErrors(archiveUpsertForm)) {
      return showCreateArchive(0, archiveUpsertForm);
    }

    ArchiveUpsertForm archiveUpsertData = archiveUpsertForm.get();
    if (!archiveUpsertData.parentJid.isEmpty()
        && !archiveService.archiveExistsByJid(archiveUpsertData.parentJid)) {
      archiveUpsertForm.reject(Messages.get("error.archive.notExist"));

      return showCreateArchive(0, archiveUpsertForm);
    }

    long archiveId =
        archiveService.createArchive(
            archiveUpsertData.parentJid,
            archiveUpsertData.name,
            archiveUpsertData.description,
            IdentityUtils.getUserJid(),
            IdentityUtils.getIpAddress());

    return redirect(routes.ArchiveController.viewArchives(archiveId));
  }
Exemplo n.º 11
0
  /**
   * Responds to a request to add an issue label category for the specified project.
   *
   * <p>Adds an issue label category created with values taken from {@link
   * Form#bindFromRequest(java.util.Map, String...)} in the project specified by the {@code
   * ownerName} and {@code projectName}. But if there has already been the same issue label category
   * in name, then this method returns an empty 204 No Content response.
   *
   * <p>When a new category is added, this method encodes the category's fields: {@link
   * IssueLabelCategory#id}, {@link IssueLabelCategory#name}, {@link
   * IssueLabelCategory#isExclusive}, and includes them in the body of the 201 Created response. But
   * if the client cannot accept {@code application/json}, it returns the 201 Created with no
   * response body.
   *
   * @param ownerName the name of a project owner
   * @param projectName the name of a project
   * @return the response to the request to add a new issue label category
   */
  @IsCreatable(ResourceType.ISSUE_LABEL_CATEGORY)
  public static Result newCategory(String ownerName, String projectName) {
    Form<IssueLabelCategory> form = new Form<>(IssueLabelCategory.class).bindFromRequest();

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

    IssueLabelCategory category = form.get();

    category.project = Project.findByOwnerAndProjectName(ownerName, projectName);

    if (category.exists()) {
      return noContent();
    }

    category.save();

    if (!request().accepts("application/json")) {
      return created();
    }

    Map<String, String> categoryPropertyMap = new HashMap<>();
    categoryPropertyMap.put("id", "" + category.id);
    categoryPropertyMap.put("name", category.name);
    categoryPropertyMap.put("isExclusive", "" + category.isExclusive);

    return created(toJson(categoryPropertyMap)).as("application/json");
  }
Exemplo n.º 12
0
  @AccessLevel(level = 2)
  public Result create() {
    Form<ActivityChoice> choiceForm = Form.form(ActivityChoice.class).bindFromRequest();

    if (choiceForm.hasErrors()) {
      return status(
          ErrDefinition.E_ACTIVITY_CHOICE_FORM_HASERROR, Messages.get("activitychoice.failure"));
    }

    try {
      ActivityChoice choice = choiceForm.get();

      choice.id = CodeGenerator.GenerateUUId();

      choice.content = new ActivityContent();
      choice.content.id = choice.id;

      Ebean.save(choice);

      return ok(Json.toJson(choice));
    } catch (Throwable e) {
      return status(
          ErrDefinition.E_ACTIVITY_CHOICE_CREATE_FAILED, Messages.get("activitychoice.failure"));
    }
  }
Exemplo n.º 13
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);
    }
  }
Exemplo n.º 14
0
  @Test
  public void testReservedWords() {
    Form<Model> form = new Form<>(Model.class);
    Model model = form.bind(newMap("name10")).get();

    assertThat(model.name).isEqualTo("name10");
  }
Exemplo n.º 15
0
  /**
   * 이메일 추가
   *
   * @return
   */
  @Transactional
  public static Result addEmail() {
    Form<Email> emailForm = form(Email.class).bindFromRequest();
    String newEmail = emailForm.data().get("email");

    if (emailForm.hasErrors()) {
      flash(Constants.WARNING, emailForm.error("email").message());
      return redirect(routes.UserApp.editUserInfoForm());
    }

    User currentUser = currentUser();
    if (currentUser == null || currentUser.isAnonymous()) {
      return forbidden(ErrorViews.NotFound.render());
    }

    if (User.isEmailExist(newEmail) || Email.exists(newEmail, true) || currentUser.has(newEmail)) {
      flash(Constants.WARNING, Messages.get("user.email.duplicate"));
      return redirect(routes.UserApp.editUserInfoForm());
    }

    Email email = new Email();
    User user = currentUser();
    email.user = user;
    email.email = newEmail;
    email.valid = false;

    user.addEmail(email);

    return redirect(routes.UserApp.editUserInfoForm());
  }
Exemplo n.º 16
0
  /*
   * 사용자 가입 입력 폼 유효성 체크
   */
  private static void validate(Form<User> newUserForm) {
    // loginId가 빈 값이 들어오면 안된다.
    if (newUserForm.field("loginId").value().trim().isEmpty()) {
      newUserForm.reject("loginId", "user.wrongloginId.alert");
    }

    if (newUserForm.field("loginId").value().contains(" ")) {
      newUserForm.reject("loginId", "user.wrongloginId.alert");
    }

    // password가 빈 값이 들어오면 안된다.
    if (newUserForm.field("password").value().trim().isEmpty()) {
      newUserForm.reject("password", "user.wrongPassword.alert");
    }

    // 중복된 loginId로 가입할 수 없다.
    if (User.isLoginIdExist(newUserForm.field("loginId").value())) {
      newUserForm.reject("loginId", "user.loginId.duplicate");
    }

    // 중복된 email로 가입할 수 없다.
    if (User.isEmailExist(newUserForm.field("email").value())) {
      newUserForm.reject("email", "user.email.duplicate");
    }
  }
Exemplo n.º 17
0
  /**
   * 사용자 비밀번호 변경 비밀번호 변경에 성공하면 로그인 화면으로 이동 비밀번호 변경에 실패하면 수정화면으로 돌아간다
   *
   * @return
   */
  @Transactional
  public static Result resetUserPassword() {
    Form<User> userForm = form(User.class).bindFromRequest();

    if (userForm.hasErrors()) {
      return badRequest(ErrorViews.BadRequest.render("error.badrequest"));
    }

    User currentUser = currentUser();
    User user = userForm.get();

    if (!isValidPassword(currentUser, user.oldPassword)) {
      Form<User> currentUserForm = new Form<>(User.class);
      currentUserForm = currentUserForm.fill(currentUser);

      flash(Constants.WARNING, "user.wrongPassword.alert");
      return badRequest(edit.render(currentUserForm, currentUser));
    }

    resetPassword(currentUser, user.password);

    // go to login page
    processLogout();
    flash(Constants.WARNING, "user.loginWithNewPassword");
    return redirect(routes.UserApp.loginForm());
  }
Exemplo n.º 18
0
 /**
  * 사용자 정보 수정 폼으로 이동 현재 로그인된 사용자 기준
  *
  * @return
  */
 @With(AnonymousCheckAction.class)
 public static Result editUserInfoForm() {
   User user = UserApp.currentUser();
   Form<User> userForm = new Form<>(User.class);
   userForm = userForm.fill(user);
   return ok(edit.render(userForm, user));
 }
Exemplo n.º 19
0
  /** Handle the 'new quantity form' submission */
  public static Result save() {
    Form<Quantity> form = form(Quantity.class).bindFromRequest();
    form.get().save();

    flash("success", "quantity  has been created");
    return list(0, "name", "asc", "", form.get().getProfileId());
  }
Exemplo n.º 20
0
  public static Result guardar() {

    Form<Economia> formREconomia = form(Economia.class).bindFromRequest();
    formREconomia.get().save();
    flash("exito", "Solicitud registrada exitosamente!");
    return Inicio;
  }
Exemplo n.º 21
0
  // src: 1 = viewAdvertisements
  // src: 2 = viewMyOwnAdvertisements
  @Security.Authenticated(Secured.class)
  public static Result changeStudAdvertisementForm(Long adId, Long src) {

    Form<StudentAdvertisementForm> adForm =
        Form.form(StudentAdvertisementForm.class).bindFromRequest();
    String description = adForm.get().description;
    String studies = adForm.get().studies;
    boolean testAd = adForm.get().test;

    StudentAdvertisement.create(
        Student.find.byId(request().username()), studies, description, adId, testAd);

    if (adForm.hasErrors()) {
      return badRequest(
          changeStudentAdvertisement.render(
              Student.find.byId(request().username()), adForm, null, src));
    } else {
      if (src == 1) {
        return ok(
            viewAdvertisements.render(
                Student.find.byId(request().username()),
                StudentAdvertisement.find.all(),
                TutorAdvertisement.find.all()));
      } else {
        return ok(
            viewOwnAdvertisements.render(
                Student.find.byId(request().username()),
                StudentAdvertisement.find.all(),
                TutorAdvertisement.find.all()));
      }
    }
  }
  /** 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());
    }
  }
Exemplo n.º 23
0
  public static Result submit() {
    District dis = District.find.byId(1L);

    if (dis == null) {
      return redirect("/setup");
    }

    Form<LoginForm> mForm = Form.form(LoginForm.class).bindFromRequest();

    if (mForm.hasErrors())
      return badRequest(
          views.html.login.render(
              "Please enter the username and password provided by your school", dis, mForm));

    LoginForm lForm = mForm.get();

    // TODO: Hash passwords

    List<LoginUser> lookingFor =
        LoginUser.finder
            .where()
            .eq("USER_NAME", lForm.username)
            .eq("PASS_HASH", lForm.password)
            .findList();

    if (lookingFor.size() != 1)
      return badRequest(
          views.html.login.render(
              "Please enter the username and password provided by your school", dis, mForm));

    return ok(views.html.login.render("Logged in!", dis, Form.form(LoginForm.class)));
  }
Exemplo n.º 24
0
  public Result create() {
    Form<Profit> form = Form.form(Profit.class).bindFromRequest();

    if (form.hasErrors()) {
      return badRequest(form.errorsAsJson());
    }

    Profit profit = form.get();

    if (Profit.existsProfitWithId(profit.getIdProfit())) {
      return Results.status(409, "already exists");
    }

    Integer idAdvisedUser = RequestUtils.getIntegerFromBody(request(), "idAdvisedUser");

    if (idAdvisedUser == null) {
      return badRequest("You need to add the id of the adviseduser");
    }

    AdvisedUser advisedUser = AdvisedUser.findAdvisedUserWithId(idAdvisedUser);

    if (advisedUser == null) {
      return Results.status(409, "there is no adviseduser with this id");
    }

    profit.setUser(advisedUser);

    profit.save();

    return created();
  }
Exemplo n.º 25
0
  @Dynamic("editor")
  public static Result publish() {
    Form<utils.Forms.PublicationBinder> bindedForm =
        form(utils.Forms.PublicationBinder.class).bindFromRequest();

    Long l = bindedForm.get().location;
    Long i = bindedForm.get().interest;

    if (i != null && l != null) {
      final User u = Mupi.getLocalUser(session());
      final models.Profile p = u.profile;

      String safeBody =
          Jsoup.clean(
              bindedForm.get().body,
              Whitelist.basicWithImages()
                  .addEnforcedAttribute("a", "target", "_blank")
                  .addTags("h1", "h2"));

      Publication.create(
          p,
          models.Location.find.byId(l),
          models.Interest.find.byId(i),
          PubType.get(bindedForm.get().pub_typ),
          safeBody);
    }
    return selectFeed(getLocalInterest(), getLocalLocation());
  }
Exemplo n.º 26
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());
  }
Exemplo n.º 27
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());
    }
  }
Exemplo n.º 28
0
 public static Result edit() {
   Form<User> userForm =
       new Form(User.class)
           .fill(User.findById.byId(Long.valueOf(session(Application.USER_KEY_ID))));
   // clean the sha1 password
   userForm.get().password = null;
   return ok(myAccount.render(userForm));
 }
Exemplo n.º 29
0
 public static Result registerNewUser() {
   Form<Register> regForm = Form.form(Register.class).bindFromRequest();
   if (regForm.hasErrors()) {
     return badRequest(register.render(regForm));
   } else {
     return redirect(routes.Application.login());
   }
 }
Exemplo n.º 30
0
  public static Result salvar() {
    Form<Pedido> form = form(Pedido.class).bindFromRequest();
    Pedido pedido = form.get();
    pedido.save();

    flash("sucesso", "Salvo com sucesso");
    return ok(index.render());
  }