Java Code Examples for play.data.DynamicForm

The following are top voted examples for showing how to use play.data.DynamicForm. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: exam   File: UserController.java   Source Code and License 6 votes vote down vote up
@Restrict({@Group("ADMIN")})
public Result grantUserPermission() {
    DynamicForm df = formFactory.form().bindFromRequest();
    String permissionString = df.get("permission");
    User user = Ebean.find(User.class, df.get("id"));
    if (user == null) {
        return notFound();
    }
    if (user.getPermissions().stream().noneMatch(p -> p.getValue().equals(permissionString))) {
        Permission.Type type;
        try {
            type = Permission.Type.valueOf(permissionString);
        } catch (IllegalArgumentException e) {
            return badRequest();
        }
        Permission permission = Ebean.find(Permission.class).where().eq("type", type).findUnique();
        user.getPermissions().add(permission);
        user.update();
    }
    return ok();
}
 
Example 2
Project: exam   File: UserController.java   Source Code and License 6 votes vote down vote up
@Restrict({@Group("ADMIN")})
public Result revokeUserPermission() {
    DynamicForm df = formFactory.form().bindFromRequest();
    String permissionString = df.get("permission");
    User user = Ebean.find(User.class, df.get("id"));
    if (user == null) {
        return notFound();
    }
    if (user.getPermissions().stream().anyMatch(p -> p.getValue().equals(permissionString))) {
        Permission permission = Ebean.find(Permission.class).where()
                .eq("type", Permission.Type.valueOf(permissionString))
                .findUnique();
        user.getPermissions().remove(permission);
        user.update();
    }
    return ok();
}
 
Example 3
Project: exam   File: LanguageInspectionController.java   Source Code and License 6 votes vote down vote up
@Restrict({@Group("ADMIN"), @Group("TEACHER")})
public Result createInspection() {
    DynamicForm df = formFactory.form().bindFromRequest();
    Long examId = Long.parseLong(df.get("examId"));
    Exam exam = Ebean.find(Exam.class, examId);
    if (exam == null) {
        return notFound("sitnet_error_exam_not_found");
    }
    if (exam.getLanguageInspection() != null) {
        return forbidden("already sent for inspection");
    }
    if (!exam.getSubjectToLanguageInspection()) {
        return forbidden("not allowed to send for inspection");
    }
    LanguageInspection inspection = new LanguageInspection();
    User user = getLoggedUser();
    AppUtil.setCreator(inspection, user);
    inspection.setExam(exam);
    inspection.save();
    return ok();
}
 
Example 4
Project: exam   File: ExamRecordController.java   Source Code and License 6 votes vote down vote up
@Restrict({@Group("TEACHER"), @Group("ADMIN")})
public Result registerExamWithoutRecord() throws IOException {
    DynamicForm df = formFactory.form().bindFromRequest();
    final Exam exam = Ebean.find(Exam.class)
            .fetch("languageInspection")
            .fetch("parent")
            .fetch("parent.creator")
            .where()
            .idEq(Long.parseLong(df.get("id"))).findUnique();
    return validateExamState(exam, false).orElseGet(() -> {
        exam.setState(Exam.State.GRADED_LOGGED);
        exam.setGrade(null);
        exam.setGradeless(true);
        exam.update();
        return ok();
    });
}
 
Example 5
Project: exam   File: StudentExamController.java   Source Code and License 6 votes vote down vote up
@ActionMethod
public Result answerEssay(String hash, Long questionId) {
    return getEnrolmentError(hash).orElseGet(() -> {
        DynamicForm df = formFactory.form().bindFromRequest();
        String essayAnswer = df.get("answer");
        ExamSectionQuestion question = Ebean.find(ExamSectionQuestion.class, questionId);
        if (question == null) {
            return forbidden();
        }
        EssayAnswer answer = question.getEssayAnswer();
        if (answer == null) {
            answer = new EssayAnswer();
        } else if (df.get("objectVersion") != null) {
            long objectVersion = Long.parseLong(df.get("objectVersion"));
            answer.setObjectVersion(objectVersion);
        }
        answer.setAnswer(essayAnswer);
        answer.save();
        question.setEssayAnswer(answer);
        question.save();
        return ok(answer);
    });
}
 
Example 6
Project: exam   File: ReviewController.java   Source Code and License 6 votes vote down vote up
@Restrict({@Group("TEACHER"), @Group("ADMIN")})
public Result scoreExamQuestion(Long id) {
    DynamicForm df = formFactory.form().bindFromRequest();
    ExamSectionQuestion essayQuestion = Ebean.find(ExamSectionQuestion.class, id);
    if (essayQuestion == null) {
        return notFound("question not found");
    }
    EssayAnswer answer = essayQuestion.getEssayAnswer();
    if (answer == null) {
        // Question was not answered at all.
        answer = new EssayAnswer();
        answer.save();
        essayQuestion.setEssayAnswer(answer);
        essayQuestion.update();
    }
    String essayScore = df.get("evaluatedScore");
    Double score = essayScore == null ? null : Double.parseDouble(essayScore);
    answer.setEvaluatedScore(round(score));
    answer.update();
    return ok(Json.toJson(essayQuestion));
}
 
Example 7
Project: exam   File: ReviewController.java   Source Code and License 6 votes vote down vote up
@Restrict({@Group("ADMIN"), @Group("TEACHER")})
public Result addInspectionComment(Long id) {
    Exam exam = Ebean.find(Exam.class, id);
    if (exam == null) {
        return notFound("Inspection not found");
    }
    DynamicForm df = formFactory.form().bindFromRequest();
    InspectionComment ic = new InspectionComment();
    User user = getLoggedUser();
    AppUtil.setCreator(ic, user);
    AppUtil.setModifier(ic, user);
    ic.setComment(df.get("comment"));
    ic.setExam(exam);
    ic.save();
    return ok(ic, PathProperties.parse("(creator(firstName, lastName, email), created, comment)"));
}
 
Example 8
Project: galaxy   File: DrawController.java   Source Code and License 6 votes vote down vote up
public Result saveShareRecord() {
    DynamicForm form = Form.form().bindFromRequest();
    String userId = form.get("userId");
    String appId = form.get("appId");
    String url = form.get("url");
    
    try {
        ShareRecord shareRecord = new ShareRecord();
        shareRecord.id = CodeGenerator.GenerateUUId();
        shareRecord.app = Application.find.byId(appId);
        shareRecord.appId = appId;
        shareRecord.account = Account.find.byId(userId);
        shareRecord.userId = userId;
        shareRecord.share_url = url;
        shareRecord.create_time = new Date();
        
        Ebean.save(shareRecord);
        return ok();
    }
    catch (Throwable e) {
        Logger.info("erroR:" + e.getMessage());
    }
    
    return ok();
}
 
Example 9
Project: galaxy   File: DrawController.java   Source Code and License 6 votes vote down vote up
public Result saveShareLog() {
    DynamicForm form = Form.form().bindFromRequest();
    String domain = form.get("domain");
    String path = form.get("path");
    String userId = form.get("userId");
    String shareBy = form.get("SharedBy");
    
    try {
        ShareLog log = new ShareLog();
        log.domain = domain;
        log.path = path;
        log.userId = userId;
        log.shareBy = shareBy;
        log.create_time = new Date();
        
        Ebean.save(log);         
    }
    catch (Throwable e) {
        
    }
    
    return ok();
}
 
Example 10
Project: galaxy   File: ActivityResultController.java   Source Code and License 6 votes vote down vote up
public Result createList() {
	
	DynamicForm form = Form.form().bindFromRequest();
	String contentId = form.data().get("contentId");
	String choiceId = form.data().get("choiceId");
	
	String[] choiceList = choiceId.split(",");
	
	Status simpleResult = null;
	for (String choice : choiceList) {
		simpleResult = (Status)saveResult(new ActivityResult(), contentId, choice);
		
		if (simpleResult.getWrappedSimpleResult().header().status() != 200) {
			return simpleResult;
		}
	}
	
	return ok();
}
 
Example 11
Project: galaxy   File: WxController.java   Source Code and License 6 votes vote down vote up
public Result login() {        
    String header = request().getHeader("Origin");
    header = (header == null ? "*" : header);
    response().setHeader("Access-Control-Allow-Origin", header);
    response().setHeader("Access-Control-Allow-Credentials", "true");
    response().setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS");
    
    DynamicForm form = Form.form().bindFromRequest();
    
    String userId = form.get("userId");
    String appId = form.get("appId");
    
    session("userId", userId);
    session("appId", appId);
    
    //Logger.info("from login: userId: " + userId + " appId: " + appId);
    
    return ok();
}
 
Example 12
Project: vos_backend   File: SimpleTest.java   Source Code and License 6 votes vote down vote up
@Test
public void errorsAsJson() {
    running(fakeApplication(), new Runnable() {
        @Override
        public void run() {
            Lang lang = new Lang(new play.api.i18n.Lang("en", ""));
            
            Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
            List<ValidationError> error = new ArrayList<ValidationError>();
            error.add(new ValidationError("foo", RequiredValidator.message, new ArrayList<Object>()));
            errors.put("foo", error);
            
            DynamicForm form = new DynamicForm(new HashMap<String, String>(), errors, F.None());
            
            JsonNode jsonErrors = form.errorsAsJson(lang);
            assertThat(jsonErrors.findPath("foo").iterator().next().asText()).isEqualTo(play.i18n.Messages.get(lang, RequiredValidator.message));
        }
    });
}
 
Example 13
Project: dr-elephant   File: Application.java   Source Code and License 6 votes vote down vote up
public static Map<String, String> getSearchParams() {
  Map<String, String> searchParams = new HashMap<String, String>();

  DynamicForm form = Form.form().bindFromRequest(request());
  String username = form.get(USERNAME);
  username = username != null ? username.trim().toLowerCase() : null;
  searchParams.put(USERNAME, username);
  String queuename = form.get(QUEUE_NAME);
  queuename = queuename != null ? queuename.trim().toLowerCase() : null;
  searchParams.put(QUEUE_NAME, queuename);
  searchParams.put(SEVERITY, form.get(SEVERITY));
  searchParams.put(JOB_TYPE, form.get(JOB_TYPE));
  searchParams.put(ANALYSIS, form.get(ANALYSIS));
  searchParams.put(FINISHED_TIME_BEGIN, form.get(FINISHED_TIME_BEGIN));
  searchParams.put(FINISHED_TIME_END, form.get(FINISHED_TIME_END));
  searchParams.put(STARTED_TIME_BEGIN, form.get(STARTED_TIME_BEGIN));
  searchParams.put(STARTED_TIME_END, form.get(STARTED_TIME_END));

  return searchParams;
}
 
Example 14
Project: dr-elephant   File: Application.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the help based on the version
 *
 * @param version The version for which help page has to be returned
 * @return The help page based on the version
 */
private static Result getHelp(Version version) {
  DynamicForm form = Form.form().bindFromRequest(request());
  String topic = form.get("topic");
  Html page = null;
  String title = "Help";
  if (topic != null && !topic.isEmpty()) {
    // check if it is a heuristic help
    page = ElephantContext.instance().getHeuristicToView().get(topic);

    // check if it is a metrics help
    if (page == null) {
      page = getMetricsNameView().get(topic);
    }

    if (page != null) {
      title = topic;
    }
  }

  if (version.equals(Version.NEW)) {
    return ok(helpPage.render(title, page));
  }
  return ok(oldHelpPage.render(title, page));
}
 
Example 15
Project: ComeAndGo   File: TimeOffController.java   Source Code and License 6 votes vote down vote up
@RequiresAuthentication(clientName = "default")
public Result createTimeOff() throws Exception {

    // Load user from session
    CommonProfile profile = getUserProfile();
    int userId = Integer.parseInt(profile.getId());

    // Bind request parameters
    DynamicForm form = Form.form().bindFromRequest();
    String comment = form.get("comment");
    TimeOffType type = TimeOffType.valueOf(form.get("type"));

    DateTime from = DateTimeUtils.stringToDateTime(form.get("from"));
    DateTime to = DateTimeUtils.endOfDay(DateTimeUtils.stringToDateTime(form.get("to")));

    // Call business logic
    createTimeOffForGivenType(userId, type, from, to, comment);
    return redirect(routes.TimeOffController.index());
}
 
Example 16
Project: Trivial1a   File: Application.java   Source Code and License 6 votes vote down vote up
public static Result clickDado() {

		DynamicForm form = Form.form().bindFromRequest();

		int x = Integer.parseInt(form.get("total"));
		posiblesMov = trivial.getPosiblesMov(x);

		builderBoard.pintarPosiblesMov(posiblesMov);

		ByteArrayInputStream input = null;
		try {
			BufferedImage img = builderBoard.getBufferedBoard();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] byteArray = {};
			ImageIO.write(img, "png", baos);
			baos.flush();
			byteArray = baos.toByteArray();
			input = new ByteArrayInputStream(byteArray);
		} catch (Exception e) {
		}
//		System.out.println("LLEGA CLICKDADO");

		return ok(input).as("image/png");
	}
 
Example 17
Project: Rasbeb   File: TeacherSchools.java   Source Code and License 6 votes vote down vote up
/**
 * Add a class to the given school
 */
@InjectContext
public static Result addClasses(int schoolId) {

    String list = new DynamicForm().bindFromRequest().get("list");
    if (list != null && !list.trim().isEmpty()) {
        String[] classes = list.trim().split("\\s*,\\s*");      // whitespace surrounded comma's
        if (classes.length != 0 && !classes[0].trim().isEmpty()) {
            for (String cl : classes) {
                // TODO: test that the combination belongs to the correct user
                DataAccess.getInjectedContext().getTeacherSchoolClassDAO().createClassInSchool(schoolId, cl);
            }
        }
    }
    return redirect(routes.TeacherSchools.homeTeacher());
}
 
Example 18
Project: WhereHows   File: Application.java   Source Code and License 6 votes vote down vote up
public static Result signUp() {
  DynamicForm loginForm = form().bindFromRequest();
  String username = loginForm.get("inputName");
  String firstName = loginForm.get("inputFirstName");
  String lastName = loginForm.get("inputLastName");
  String email = loginForm.get("inputEmail");
  String password = loginForm.get("inputPassword");
  String errorMessage = "";
  try {
    errorMessage = UserDAO.signUp(username, firstName, lastName, email, password);
    if (StringUtils.isNotBlank(errorMessage)) {
      flash("error", errorMessage);
    } else {
      flash("success", "Congratulations! Your account has been created. Please login.");
    }
  } catch (Exception e) {
    flash("error", e.getMessage());
  }

  return serveAsset("");
}
 
Example 19
Project: poseidon-rest   File: TokenController.java   Source Code and License 6 votes vote down vote up
@ResponseTimeLoggingComposition.ResponseTimeLogging
@ErrorHandlingComposition.ErrorHandling
public Result authenticate(String callback) {
  AuthMapper mapper = new AuthMapper();
  DynamicForm requestData = Form.form().bindFromRequest();
  Credentials credentials = new Credentials(requestData.data());

  logger.debug("Started authenticate to generate new token for grant_type={}", credentials.grantType);

  Authentication authentication = createAuthentication(credentials);
  auth.models.Token token = new AuthenticationManager().authenticate(authentication);

  if (token == null) {
    String msg = "Could not generate token";
    logger.debug(msg + " grant_type={}",credentials.grantType);
    throw new PoseidonException(Http.Status.UNAUTHORIZED, msg);
  } else {
    setPragmaAndCacheControlHeaders();
    //Logger.debug("Ok generation of token={} for client_id={} and grant_type={}", token.access_token, credentials.client_id, credentials.grantType);
    return ok(callback, Json.toJson(mapper.map2Token(token)));
  }

}
 
Example 20
Project: judgels-jophiel   File: ClientAPIController.java   Source Code and License 6 votes vote down vote up
@Authenticated(LoggedIn.class)
@Transactional(readOnly = true)
public Result clientAutoCompleteList() {
    response().setHeader("Access-Control-Allow-Origin", "*");

    DynamicForm form = DynamicForm.form().bindFromRequest();
    UserInfo user = userService.findUserByUserJid(IdentityUtils.getUserJid());
    String term = form.get("term");
    List<Client> clients = clientService.findAllClientByTerm(term);
    ImmutableList.Builder<AutoComplete> responseBuilder = ImmutableList.builder();

    for (Client client : clients) {
        responseBuilder.add(new AutoComplete(client.getJid(), client.getName(), client.getName()));
    }
    return ok(Json.toJson(responseBuilder.build()));
}
 
Example 21
Project: judgels-jophiel   File: ClientAPIController.java   Source Code and License 6 votes vote down vote up
@Authenticated(LoggedIn.class)
@Transactional(readOnly = true)
public Result linkedClientList() {
    response().setHeader("Access-Control-Allow-Origin", "*");
    response().setContentType("application/javascript");

    DynamicForm form = DynamicForm.form().bindFromRequest();
    String callback = form.get("callback");

    String referer = request().getHeader("Referer");
    ImmutableMap.Builder<String, String> clientMapBuilder = ImmutableMap.builder();

    if (!referer.startsWith(JophielProperties.getInstance().getJophielBaseUrl())) {
        clientMapBuilder.put(JophielProperties.getInstance().getJophielBaseUrl(), JudgelsPlayProperties.getInstance().getAppTitle());
    }
    for (int i=0;i<JophielProperties.getInstance().getJophielClientLabels().size();++i) {
        String target = JophielProperties.getInstance().getJophielClientTargets().get(i);
        String label = JophielProperties.getInstance().getJophielClientLabels().get(i);
        if (!referer.startsWith(target)) {
            clientMapBuilder.put(target, label);
        }
    }

    return ok(callback + "(" + Json.toJson(clientMapBuilder.build()).toString() + ")");
}
 
Example 22
Project: judgels-jophiel   File: UserAPIController.java   Source Code and License 6 votes vote down vote up
@Authenticated(LoggedIn.class)
@Transactional(readOnly = true)
public Result userAutoCompleteList() {
    response().setHeader("Access-Control-Allow-Origin", "*");
    response().setContentType("application/javascript");

    DynamicForm form = DynamicForm.form().bindFromRequest();
    UserInfo user = userService.findUserByUserJid(IdentityUtils.getUserJid());
    String term = form.get("term");
    List<UserInfo> users = userService.findAllUserByTerm(term);
    ImmutableList.Builder<AutoComplete> responseBuilder = ImmutableList.builder();

    for (UserInfo user1 : users) {
        responseBuilder.add(new AutoComplete(user1.getJid(), user1.getUsername(), user1.getUsername() + " (" + user1.getName() + ")"));
    }

    String callback = form.get("callback");

    return ok(callback + "(" + Json.toJson(responseBuilder.build()).toString() + ")");
}
 
Example 23
Project: judgels-jophiel   File: UserAPIController.java   Source Code and License 6 votes vote down vote up
@Transactional(readOnly = true)
public Result userInfo() {
    DynamicForm form = DynamicForm.form().bindFromRequest();
    String token;
    if ((request().getHeader("Authorization") != null) && ("Bearer".equals(request().getHeader("Authorization").split(" ")[0]))) {
        token = new String(Base64.decodeBase64(request().getHeader("Authorization").split(" ")[1]));
    } else {
        token = form.get("token");
    }

    if (clientService.isValidAccessTokenExist(token)) {
        AccessToken accessToken = clientService.findAccessTokenByAccessToken(token);
        UserInfo user = userService.findUserByUserJid(accessToken.getUserJid());
        ObjectNode result = Json.newObject();
        result.put("sub", user.getJid());
        result.put("name", user.getName());
        result.put("preferred_username", user.getUsername());
        result.put("email", user.getEmail());
        result.put("picture", user.getProfilePictureUrl().toString());
        return ok(result);
    } else {
        ObjectNode node = Json.newObject();
        node.put("error", "invalid_token");
        return unauthorized(node);
    }
}
 
Example 24
Project: htwplus   File: AdminController.java   Source Code and License 6 votes vote down vote up
@Transactional
public Result deleteAccount(Long accountId) {
    Account current = accountManager.findById(accountId);

    if (!Secured.deleteAccount(current)) {
        flash("error", messagesApi.get(Lang.defaultLang(), "profile.delete.nopermission"));
        return redirect(controllers.routes.AdminController.listAccounts());
    }

    DynamicForm df = formFactory.form().bindFromRequest();
    if (!df.get("confirmText").toLowerCase().equals("account wirklich löschen")) {
        flash("error", messagesApi.get(Lang.defaultLang(), "admin.delete_account.wrongconfirm"));
        return redirect(controllers.routes.AdminController.listAccounts());
    }

    // ACTUAL DELETION //
    Logger.info("Deleting Account[#" + current.id + "]...");
    accountManager.delete(current);

    // override logout message
    flash("success", messagesApi.get(Lang.defaultLang(), "admin.delete_account.success"));
    return redirect(routes.AdminController.listAccounts());
}
 
Example 25
Project: strawpoll   File: PollController.java   Source Code and License 6 votes vote down vote up
/**
 * Handle POST requests at `/poll`. Expects a `question` form parameter.
 * @return A SEE_OTHER redirect on success, Bad Request response otherwise.
 */
public static Result postPoll() {

    /* Parse the request and check for all required parameters. */
    DynamicForm requestData = Form.form().bindFromRequest();
    String question = requestData.get("question");
    String choicesString = requestData.get("choices");
    if (question == null || choicesString == null) {
        return badRequest();
    }

    /* Create the poll and put it in our cache. */
    List<String> choices = Arrays.asList(choicesString.split("\n"));
    Poll poll = createPoll(question, choices);
    putPollIntoCache(poll);

    return ok(Json.toJson(poll));
}
 
Example 26
Project: CS784-Data_Integration   File: EvaluationController.java   Source Code and License 6 votes vote down vote up
public static Result evaluateWithGold(String projectName)
{
	DynamicForm form = form().bindFromRequest();
	Logger.info("PARAMETERS : " + form.data().toString());
	String evaluationName = form.get("evaluation_name");
	String matchesName = form.get("matches_name_e");
	String goldName = form.get("gold_name_e");
	
	try {
		EvaluationSummary evaluationSummary =
				EvaluateDao.evaluateWithGold(evaluationName, projectName,
						matchesName, goldName);
		ProjectController.statusMessage = "Successfully evaluated Matches " +
				matchesName + " with Gold " + goldName + ".\nEvaluation summary: " + 
				evaluationSummary;
		EvaluateDao.addEvaluationSummary(projectName, evaluationSummary);
	} catch (IOException e) {
		flash("error", e.getMessage());
		ProjectController.statusMessage = "Error: " + e.getMessage();
	}
	
	return redirect(controllers.project.routes.ProjectController.showProject(projectName));
}
 
Example 27
Project: CS784-Data_Integration   File: RuleController.java   Source Code and License 6 votes vote down vote up
public static Result editRule(String name){
	DynamicForm form = form().bindFromRequest();
	Logger.info("PARAMETERS : " + form.data().toString());
	String ruleName = form.get("rule_name_e");
	String ruleString = form.get("rule_string");
	
	boolean saveToDisk = false;
	if(null != form.get("save_to_disk")){
		saveToDisk = true;
	}
	
	try{
		RuleDao.editRule(name, ruleName, ruleString, saveToDisk);
		ProjectController.statusMessage = "Successfully edited Rule " + ruleName + ".";
	}
	catch (IOException e) {
		flash("error", e.getMessage());
		ProjectController.statusMessage = "Error: " + e.getMessage();
	}

	return redirect(controllers.project.routes.ProjectController.showProject(name));
}
 
Example 28
Project: CS784-Data_Integration   File: RuleController.java   Source Code and License 6 votes vote down vote up
public static Result editMatcher(String name){
	DynamicForm form = form().bindFromRequest();
	Logger.info("PARAMETERS : " + form.data().toString());
	String matcherName = form.get("matcher_name_ed");
	String matcherString = form.get("matcher_string");
	
	boolean saveToDisk = false;
	if(null != form.get("save_to_disk")){
		saveToDisk = true;
	}
	
	try{
		RuleDao.editMatcher(name, matcherName, matcherString, saveToDisk);
		ProjectController.statusMessage = "Successfully edited Matcher " + matcherName + ".";
	}
	catch (IOException e) {
		flash("error", e.getMessage());
		ProjectController.statusMessage = "Error: " + e.getMessage();
	}

	return redirect(controllers.project.routes.ProjectController.showProject(name));
}
 
Example 29
Project: CS784-Data_Integration   File: RuleController.java   Source Code and License 6 votes vote down vote up
public static Result editFeature(String name){
	DynamicForm form = form().bindFromRequest();
	Logger.info("PARAMETERS : " + form.data().toString());
	String featureName = form.get("feature_name_ed");
	String featureString = form.get("feature_string");
	
	boolean saveToDisk = false;
	if(null != form.get("save_to_disk")){
		saveToDisk = true;
	}
	
	try{
		RuleDao.editFeature(name, featureName, featureString, saveToDisk);
		ProjectController.statusMessage = "Successfully edited Feature " + featureName + ".";
	}
	catch (IOException e) {
		flash("error", e.getMessage());
		ProjectController.statusMessage = "Error: " + e.getMessage();
	}

	return redirect(controllers.project.routes.ProjectController.showProject(name));
}
 
Example 30
Project: CS784-Data_Integration   File: ProjectController.java   Source Code and License 6 votes vote down vote up
public static Result setDefaults(String projectName){
DynamicForm form = form().bindFromRequest();
Logger.info("PARAMETERS : " + form.data().toString());
String table1Name = form.get("table1_name_sd");
String table2Name = form.get("table2_name_sd");
String candsetName = form.get("candset_name_sd");
String matchesName = form.get("matches_name_sd");
String goldName = form.get("gold_name_sd");

boolean saveToDisk = false;
if(null != form.get("save_to_disk")){
	saveToDisk = true;
}

try {
	ProjectDao.setDefaults(projectName,table1Name,table2Name,candsetName,matchesName,goldName,saveToDisk);
	statusMessage = "Successfully set the project defaults.";
} catch (IOException ioe) {
	flash("error", ioe.getMessage());
	statusMessage = "Error: " + ioe.getMessage();
}

return redirect(controllers.project.routes.ProjectController.showProject(projectName));
}
 
Example 31
Project: CS784-Data_Integration   File: BrowserController.java   Source Code and License 6 votes vote down vote up
/**** SAMPLING ****/
public static Result sample() {
	// TODO: Check if table name exists and error if so.
	// otherwise, we will be overwriting when saving.

	DynamicForm form = form().bindFromRequest();
	Logger.info("PARAMETERS : " + form.data().toString());

	String tableName = form.get("sample_table_name");
	String sampleSize = form.get("sample_size");

	// TODO: raise error if not valid.
	long size = Long.parseLong(sampleSize);
	List<Object> ids = table.getRandomSample(size);

	Table sampleTable = new Table(table, tableName, ids);

	try {
		TableDao.save(sampleTable, new HashSet<DefaultType>(), true);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	return getIndex(project.getName(), tableName, "false");
}
 
Example 32
Project: makeke   File: Student.java   Source Code and License 6 votes vote down vote up
/**
 * Attempts to log a student into the system by comparing hashed passwords.
 * 
 * @return A redirect to the Book Manager once logged in.
 */
public static Result login() {
  DynamicForm loginForm = form().bindFromRequest();
  String email = loginForm.get("email");
  byte[] hash = Password.hash(loginForm.get("password"));

  models.Student student = models.Student.find().where().eq("email", email).findUnique();
  if (student == null) {
    return ok(error.render("E-mail not found.", "Please try logging in again."));
  }

  if (Arrays.equals(hash, student.getPasswordHash())) {
    // Store this student's studentId to the session.
    session("connected", student.getStudentId());
    return redirect(routes.Book.index());
  }

  return ok(error.render("Password does not match email.", "Please try logging in again."));
}
 
Example 33
Project: w3act   File: Alerts.java   Source Code and License 6 votes vote down vote up
public static Result action() {
	Map<String, String> data = (new DynamicForm()).bindFromRequest().data();
	
	List<Alert> alerts = new ArrayList<>();
	
	for (String key : data.keySet()) {
		if (key.startsWith("action_")) {
			long alertId = Integer.parseInt(key.split("_")[1]);
			alerts.add(Alert.find.byId(alertId));
		}
	}
	
	if (data.containsKey("delete")) {
		Ebean.delete(alerts);
	} else {
		for (Alert alert : alerts) {
			alert.read = true;
			Ebean.save(alert);
		}
	}
	return redirect(routes.Alerts.list(0, "createdAt", "desc"));
}
 
Example 34
Project: w3act   File: TargetController.java   Source Code and License 6 votes vote down vote up
/**
 * This method enables searching for given URL and particular subject.
 *
 * @return
 */
public static Result searchTargetsBySubject() {

    DynamicForm form = DynamicForm.form().bindFromRequest();
    String action = form.get("action");
    String query = form.get("url");

    int pageNo = Integer.parseInt(form.get(Const.PAGE_NO));
    String sort = form.get(Const.SORT_BY);
    String order = form.get(Const.ORDER);
    String subject_url = form.get("subject_url");
    Long subjectId = Long.valueOf(subject_url);

    if(StringUtils.isEmpty(action)) {
        return badRequest("You must provide a valid action");
    }
    else {
        if(Const.SEARCH.equals(action)) {
            Logger.debug("searching " + pageNo + " " + sort + " " + order);
            return redirect(routes.TargetController.subjectTargets(pageNo, sort, order, query, subjectId));
        }
        else {
            return badRequest("This action is not allowed");
        }
    }
}
 
Example 35
Project: w3act   File: TargetController.java   Source Code and License 6 votes vote down vote up
/**
 * This method enables searching for given URL and particular organisation.
 *
 * @return
 */
public static Result searchTargetsByOrganisation() {

    DynamicForm form = DynamicForm.form().bindFromRequest();
    String action = form.get(Const.ACTION);
    String query = form.get(Const.URL);

    int pageNo = Integer.parseInt(form.get(Const.PAGE_NO));
    String sort = form.get(Const.SORT_BY);
    String order = form.get(Const.ORDER);
    String organisation_id = form.get("organisation_id");
    Long organisationId = Long.valueOf(organisation_id);

    if(StringUtils.isEmpty(action)) {
        return badRequest("You must provide a valid action");
    }
    else {
        if(Const.SEARCH.equals(action)) {
            Logger.debug("searching " + pageNo + " " + sort + " " + order);
            return redirect(routes.TargetController.organisationTargets(pageNo, sort, order, query, organisationId));
        }
        else {
            return badRequest("This action is not allowed");
        }
    }
}
 
Example 36
Project: w3act   File: TagController.java   Source Code and License 6 votes vote down vote up
public static Result save() {
	
	DynamicForm requestData = form().bindFromRequest();
	String action = requestData.get("action");

	Logger.debug("action: " + action);
	
    if (StringUtils.isNotEmpty(action)) {
    	if (action.equals("save")) {
      Form<Tag> filledForm = form(Tag.class).bindFromRequest();
      if(filledForm.hasErrors()) {
     		Logger.debug("errors: " + filledForm.errors());
          return newInfo(filledForm);
      }
      
      filledForm.get().save();
      flash("message", "Tag " + filledForm.get().name + " has been created");
      return redirect(routes.TagController.view(filledForm.get().id));
    	}
    }
    return null;    	
}
 
Example 37
Project: w3act   File: OrganisationController.java   Source Code and License 6 votes vote down vote up
public static Result save() {

        DynamicForm requestData = form().bindFromRequest();
        String action = requestData.get("action");

        Logger.debug("action: " + action);

        if (StringUtils.isNotEmpty(action)) {
            if (action.equals("save")) {
                Form<Organisation> filledForm = form(Organisation.class).bindFromRequest();
                if(filledForm.hasErrors()) {
                    Logger.debug("errors: " + filledForm.errors());
                    return newInfo(filledForm);
                }

                filledForm.get().save();
                flash("message", "Organisation " + filledForm.get().title + " has been created");
                return redirect(routes.OrganisationController.view(filledForm.get().id));
            }
        }
        return null;    	
    }
 
Example 38
Project: w3act   File: PermissionRefusalController.java   Source Code and License 6 votes vote down vote up
public static Result save() {
	
	DynamicForm requestData = form().bindFromRequest();
	String action = requestData.get("action");

	Logger.debug("action: " + action);
	
    if (StringUtils.isNotEmpty(action)) {
    	if (action.equals("save")) {
      Form<PermissionRefusal> filledForm = form(PermissionRefusal.class).bindFromRequest();
      if(filledForm.hasErrors()) {
     		Logger.debug("errors: " + filledForm.errors());
          return newInfo(filledForm);
      }
      
      filledForm.get().save();
      flash("message", "Permission Refusal " + filledForm.get().name + " has been created");
      return redirect(routes.PermissionRefusalController.view(filledForm.get().id));
    	}
    }
    return null;    	
}
 
Example 39
Project: w3act   File: LoginCredentialsController.java   Source Code and License 6 votes vote down vote up
public static Result save(Long id) {
	DynamicForm requestData = Form.form().bindFromRequest();
	Target target = Target.find.byId(id);
	target.loginPageUrl = requestData.field("loginPageUrl").value();
	target.logoutUrl    = requestData.field("logoutUrl").value();
	String username = requestData.field("username").value();
	String password = requestData.field("password").value();
	if(!target.loginPageUrl.isEmpty() && !username.isEmpty() && !password.isEmpty()) {
		LoginCredentials loginCredentials = new LoginCredentials(target.loginPageUrl, username, password);
		try {
			target.secretId = passwordManager.addLoginCredentials(Target.find.byId(id).title, loginCredentials);
			new FlashMessage(FlashMessage.Type.SUCCESS, "The credentials were successfully saved to the Secret Server.").send();
		} catch(Exception e) {
			String msg = "Can't store username and password because there is no connection to the Secret Server.";
			new FlashMessage(FlashMessage.Type.ERROR, msg).send();
			Logger.error(msg, e);
		}
	} else if (username.isEmpty() && password.isEmpty()) {
		target.secretId = null;
		FlashMessage.updateSuccess.send();
	}
	Ebean.update(target);
	return redirect(routes.LoginCredentialsController.edit(id));
}
 
Example 40
Project: w3act   File: PermissionController.java   Source Code and License 6 votes vote down vote up
public static Result save() {
	DynamicForm requestData = form().bindFromRequest();
	String action = requestData.get("action");

	Logger.debug("action: " + action);
	
    if (StringUtils.isNotEmpty(action)) {
    	if (action.equals("save")) {
      Form<Permission> filledForm = form(Permission.class).bindFromRequest();
      if(filledForm.hasErrors()) {
     		Logger.debug("errors: " + filledForm.errors());
          return newInfo(filledForm);
      }
      filledForm.get().save();
      flash("message", "Permission " + filledForm.get().name + " has been created");
      return redirect(routes.PermissionController.view(filledForm.get().id));
    	}
    }
    return null;
}