org.springframework.validation.BindException Java Examples

The following examples show how to use org.springframework.validation.BindException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CustomDepositFormControllerTest.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Test
public void testHandleHttpServletRequestHttpServletResponseObjectBindException() {
	MockHttpServletRequest request = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	ArchiveCommand comm = new ArchiveCommand();
	comm.setHarvestResultNumber(1);
	comm.setTargetInstanceID(5001);
	BindException errors = new BindException(comm, "ArchiveCommand");

	ModelAndView mav = null;;
	try {
		mav = testInstance.handle(request, response, comm, errors);
	} catch (Exception e) {
		fail(e.getMessage());
		return;
	}
	assertNotNull(mav);
	assertEquals("deposit-form-envelope", mav.getViewName());
	assertNotNull(mav.getModel().get(Constants.GBL_CMD_DATA));
	assertEquals(1, ((ArchiveCommand)mav.getModel().get(Constants.GBL_CMD_DATA)).getHarvestResultNumber());
	assertEquals(5001, ((ArchiveCommand)mav.getModel().get(Constants.GBL_CMD_DATA)).getTargetInstanceID());
	assertNull(mav.getModel().get("hasErrors"));
}
 
Example #2
Source File: FilterTool.java    From circus-train with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  // below is output *before* logging is configured so will appear on console
  logVersionInfo();

  try {
    SpringApplication
        .exit(new SpringApplicationBuilder(FilterTool.class)
            .properties("spring.config.location:${config:null}")
            .properties("spring.profiles.active:" + Modules.REPLICATION)
            .properties("instance.home:${user.home}")
            .properties("instance.name:${source-catalog.name}_${replica-catalog.name}")
            .bannerMode(Mode.OFF)
            .registerShutdownHook(true)
            .build()
            .run(args));
  } catch (BeanCreationException e) {
    Throwable mostSpecificCause = e.getMostSpecificCause();
    if (mostSpecificCause instanceof BindException) {
      printFilterToolHelp(((BindException) mostSpecificCause).getAllErrors());
    }
    throw e;
  }
}
 
Example #3
Source File: AuthenticationViaFormActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyRenewWithServiceAndBadCredentials() throws Exception {
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(c);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
    request.addParameter("renew", "true");
    request.addParameter("service", "test");

    final Credential c2 = TestUtils.getCredentialsWithDifferentUsernameAndPassword();
    context.setExternalContext(new ServletExternalContext(
        new MockServletContext(), request, new MockHttpServletResponse()));
    putCredentialInRequestScope(context, c2);
    context.getRequestScope().put(
        "org.springframework.validation.BindException.credentials",
        new BindException(c2, "credentials"));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("error", this.action.submit(context, c2, messageContext).getId());
}
 
Example #4
Source File: MemberOfHandler.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Override
public TabbedModelAndView preProcessNextTab(TabbedController tc,
		Tab nextTabID, HttpServletRequest req, HttpServletResponse res,
		Object comm, BindException errors) {
	
	// get value of page size cookie
	String currentPageSize = CookieUtils.getPageSize(req);

	MemberOfCommand command = new MemberOfCommand();
	command.setSelectedPageSize(currentPageSize);
	
	// Get the parent DTOs
	Pagination memberOfGroups = getParents(req, 0, Integer.parseInt(currentPageSize));
	
	TabbedModelAndView tmav = tc.new TabbedModelAndView();
	tmav.addObject("memberof", memberOfGroups);
	tmav.addObject("page", memberOfGroups);
	tmav.addObject("subGroupSeparator", subGroupSeparator);
	tmav.addObject(Constants.GBL_CMD_DATA, command);
	
	return tmav;
}
 
Example #5
Source File: NewAccountValidatorTest.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidationFailsOnExistingEmail() throws Exception {
    UserForm user = new UserForm();
    user.setUsername(VALID_NAME);
    user.setPassword(VALID_PASSWORD);
    user.setConfirmPassword(VALID_PASSWORD);
    user.setDefaultPageLayoutCode(VALID_PAGELAYOUT);
    user.setEmail("existing@localhost");
    Errors errors = new BindException(user, NEW_USER);

    User user1 = createMock(User.class);
    expect(mockUserService.getUserByUsername(VALID_NAME)).andReturn(null);
    expect(mockUserService.getUserByEmail("existing@localhost")).andReturn(user1);
    replay(mockUserService);

    newAccountValidator.validate(user, errors);

    assertEquals("1 Validation error", 1, errors.getErrorCount());
    assertNotNull(errors.getFieldError(FIELD_EMAIL));
}
 
Example #6
Source File: CategoryRestController.java    From wallride with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value="/{language}/categories/{id}", method=RequestMethod.POST)
public @ResponseBody DomainObjectUpdatedModel update(
		@Valid CategoryEditForm form,
		BindingResult result,
		@PathVariable long id,
		AuthorizedUser authorizedUser,
		HttpServletRequest request,
		HttpServletResponse response) throws BindException {
	form.setId(id);
	if (result.hasErrors()) {
		throw new BindException(result);
	}
	Category category = categoryService.updateCategory(form.buildCategoryUpdateRequest(), authorizedUser);
	FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
	flashMap.put("updatedCategory", category);
	RequestContextUtils.getFlashMapManager(request).saveOutputFlashMap(flashMap, request, response);
	return new DomainObjectUpdatedModel<>(category);
}
 
Example #7
Source File: FormModelMethodArgumentResolver.java    From es with Apache License 2.0 6 votes vote down vote up
protected void validateComponent(WebDataBinder binder, MethodParameter parameter) throws BindException {

        boolean validateParameter = validateParameter(parameter);
        Annotation[] annotations = binder.getTarget().getClass().getAnnotations();
        for (Annotation annot : annotations) {
            if (annot.annotationType().getSimpleName().startsWith("Valid") && validateParameter) {
                Object hints = AnnotationUtils.getValue(annot);
                binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[]{hints});
            }
        }

        if (binder.getBindingResult().hasErrors()) {
            if (isBindExceptionRequired(binder, parameter)) {
                throw new BindException(binder.getBindingResult());
            }
        }
    }
 
Example #8
Source File: ResourceServerProperties.java    From spring-security-oauth2-boot with Apache License 2.0 6 votes vote down vote up
private void doValidate() throws BindException {
	BindingResult errors = new BeanPropertyBindingResult(this, "resourceServerProperties");
	boolean jwtConfigPresent = StringUtils.hasText(this.jwt.getKeyUri())
			|| StringUtils.hasText(this.jwt.getKeyValue());
	boolean jwkConfigPresent = StringUtils.hasText(this.jwk.getKeySetUri());
	if (jwtConfigPresent && jwkConfigPresent) {
		errors.reject("ambiguous.keyUri",
				"Only one of jwt.keyUri (or jwt.keyValue) and jwk.keySetUri should" + " be configured.");
	}
	if (!jwtConfigPresent && !jwkConfigPresent) {
		if (!StringUtils.hasText(this.userInfoUri) && !StringUtils.hasText(this.tokenInfoUri)) {
			errors.rejectValue("tokenInfoUri", "missing.tokenInfoUri",
					"Missing tokenInfoUri and userInfoUri and there is no " + "JWT verifier key");
		}
		if (StringUtils.hasText(this.tokenInfoUri) && isPreferTokenInfo()) {
			if (!StringUtils.hasText(this.clientSecret)) {
				errors.rejectValue("clientSecret", "missing.clientSecret", "Missing client secret");
			}
		}
	}
	if (errors.hasErrors()) {
		throw new BindException(errors);
	}
}
 
Example #9
Source File: ExceptionHandlerConfig.java    From yue-library with Apache License 2.0 6 votes vote down vote up
/**
	 * {@linkplain Valid} 验证异常统一处理-433
	 * 
	 * @param e 验证异常
	 * @return 结果
	 */
	@Override
    @ResponseBody
    @ExceptionHandler(BindException.class)
	public Result<?> bindExceptionHandler(BindException e) {
//		ServletUtils.getResponse().setStatus(433);
//    	String uri = ServletUtils.getRequest().getRequestURI();
//    	Console.error("uri={}", uri);
		List<ObjectError> errors = e.getAllErrors();
		JSONObject paramHint = new JSONObject();
		errors.forEach(error -> {
			String str = StrUtil.subAfter(error.getArguments()[0].toString(), "[", true);
			String key = str.substring(0, str.length() - 1);
			String msg = error.getDefaultMessage();
			paramHint.put(key, msg);
			Console.error(key + " " + msg);
		});
		
		return ResultInfo.paramCheckNotPass(paramHint.toString());
	}
 
Example #10
Source File: SiteControllerTest.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Test
public final void testShowForm() {
	try
	{
		MockHttpServletRequest request = new MockHttpServletRequest();
		MockHttpServletResponse response = new MockHttpServletResponse();
		DefaultSiteCommand comm = new DefaultSiteCommand();
		comm.setEditMode(true);
		comm.setSiteOid(null);
		
		BindException aError = new BindException(new DefaultSiteCommand(), null);
		ModelAndView mav = testInstance.showForm(request, response, comm, aError);
		assertTrue(mav != null);
		assertTrue(mav.getViewName().equals("site"));
		SiteEditorContext context = testInstance.getEditorContext(request);
		assertSame(context.getSite().getOwningAgency(), AuthUtil.getRemoteUserObject().getAgency());
	}
	catch (Exception e)
	{
		String message = e.getClass().toString() + " - " + e.getMessage();
		log.debug(message);
		fail(message);
	}
}
 
Example #11
Source File: TargetInstanceStateHandler.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public ModelAndView processOther(TabbedController tc, Tab currentTab,
        HttpServletRequest req, HttpServletResponse res, Object comm,
        BindException errors) {
    TargetInstanceCommand cmd = (TargetInstanceCommand) comm;
    if (cmd.getCmd().equals(TargetInstanceCommand.ACTION_HARVEST)) {
        ModelAndView mav = new ModelAndView();            
        HashMap agents = harvestCoordinator.getHarvestAgents();
        mav.addObject(Constants.GBL_CMD_DATA, cmd);
        mav.addObject(TargetInstanceCommand.MDL_AGENTS, agents);
        mav.setViewName(Constants.VIEW_HARVEST_NOW);
        
        return mav;
    }
    else {
        throw new WCTRuntimeException("Unknown command " + cmd.getCmd() + " recieved.");
    }
}
 
Example #12
Source File: ConventionBasedSpringValidationErrorToApiErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateValidationErrorsForBindException() {
    BindingResult bindingResult = mock(BindingResult.class);

    ApiError someFieldError = testProjectApiErrors.getMissingExpectedContentApiError();
    ApiError otherFieldError = testProjectApiErrors.getTypeConversionApiError();
    ApiError notAFieldError = testProjectApiErrors.getGenericBadRequestApiError();
    List<ObjectError> errorsList = Arrays.asList(
            new FieldError("someObj", "someField", someFieldError.getName()),
            new FieldError("otherObj", "otherField", otherFieldError.getName()),
            new ObjectError("notAFieldObject", notAFieldError.getName())
    );
    when(bindingResult.getAllErrors()).thenReturn(errorsList);

    BindException ex = new BindException(bindingResult);
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    validateResponse(result, true, Arrays.asList(
        new ApiErrorWithMetadata(someFieldError, Pair.of("field", "someField")),
        new ApiErrorWithMetadata(otherFieldError, Pair.of("field", "otherField")),
        notAFieldError
    ));
    verify(bindingResult).getAllErrors();
}
 
Example #13
Source File: BandwidthRestrictionsController.java    From webcurator with Apache License 2.0 6 votes vote down vote up
/**
 * process the delete restriction action.
 * 
 * @see AbstractFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
private ModelAndView processDeleteRestriction(HttpServletRequest aReq, HttpServletResponse aResp,
		BandwidthRestrictionsCommand aCmd, BindException aErrors) throws Exception {
	if (aErrors.hasErrors()) {
		ModelAndView mav = new ModelAndView();
		mav.addObject(Constants.GBL_CMD_DATA, aErrors.getTarget());
		mav.addObject(Constants.GBL_ERRORS, aErrors);
		mav.addObject(BandwidthRestrictionsCommand.MDL_ACTION, Constants.CNTRL_MNG_BANDWIDTH);
		mav.setViewName(Constants.VIEW_EDIT_BANDWIDTH);

		return mav;
	}

	BandwidthRestriction br = harvestBandwidthManager.getBandwidthRestriction(aCmd.getOid());
	harvestBandwidthManager.delete(br);

	return createDefaultModelAndView();
}
 
Example #14
Source File: TemplateControllerTest.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Test
public final void testProcessFormSubmission_edit() {
	
	String action = TemplateCommand.ACTION_EDIT;
	
	setUpController();
	
	TemplateCommand aCmd = setUpCommand(action, 1);
	BindException aError = new BindException(aCmd, action);
	
	
	MockHttpServletRequest aReq = new MockHttpServletRequest();
	MockHttpServletResponse aRes = new MockHttpServletResponse();

	try
	{
		ModelAndView mav = testInstance.processFormSubmission(aReq, aRes, aCmd, aError);
		assertTrue(mav.getViewName().equals("add-template"));
	}
	catch(Exception e)
	{
		fail(e.getMessage());
	}
}
 
Example #15
Source File: AccessHandler.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public TabbedModelAndView preProcessNextTab(TabbedController tc,
		Tab nextTabID, HttpServletRequest req, HttpServletResponse res,
		Object comm, BindException errors) {
	
	TargetGroup aTargetGroup = getEditorContext(req).getTargetGroup();
	
   	TargetAccessCommand command = new TargetAccessCommand();
   	command.setTabType(TargetAccessCommand.GROUP_TYPE);
   	command.setDisplayTarget(aTargetGroup.isDisplayTarget());
   	command.setDisplayNote(aTargetGroup.getDisplayNote());
   	command.setDisplayChangeReason(aTargetGroup.getDisplayChangeReason());
   	command.setAccessZone(aTargetGroup.getAccessZone());
	
	TabbedModelAndView tmav = tc.new TabbedModelAndView();
	tmav.addObject(Constants.GBL_CMD_DATA, command);
	tmav.addObject("ownable", aTargetGroup);
	tmav.addObject("privleges", Privilege.MANAGE_GROUP + ";" + Privilege.CREATE_GROUP);
	tmav.addObject("editMode", getEditorContext(req).isEditMode());
	tmav.addObject("displayTarget", aTargetGroup.isDisplayTarget());
	tmav.addObject("accessZone", aTargetGroup.getAccessZone());
	tmav.addObject("displayNote", aTargetGroup.getDisplayNote());
	tmav.addObject("displayChangeReason", aTargetGroup.getDisplayChangeReason());
	
	return tmav;		
	
}
 
Example #16
Source File: TemplateControllerTest.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Test
public final void testProcessFormSubmission_new() {
	
	String action = TemplateCommand.ACTION_NEW;
	
	setUpController();
	
	TemplateCommand aCmd = setUpCommand(action, 0);
	BindException aError = new BindException(aCmd, action);
	
	
	MockHttpServletRequest aReq = new MockHttpServletRequest();
	MockHttpServletResponse aRes = new MockHttpServletResponse();

	try
	{
		ModelAndView mav = testInstance.processFormSubmission(aReq, aRes, aCmd, aError);
		assertTrue(mav.getViewName().equals("add-template"));
	}
	catch(Exception e)
	{
		fail(e.getMessage());
	}
}
 
Example #17
Source File: PostBack.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * コンストラクタ。{@code PostBack}インスタンスを生成します。
 * </p>
 * @param t ポストバックのトリガーとなった例外
 */
public PostBack(Throwable t) {
    this.t = t;
    if (t instanceof BindException) {
        BindException be = (BindException)t;
        this.exceptionType = be.getClass();
        this.modelName = be.getObjectName();
        this.model = be.getTarget();
        this.bindingResult = be.getBindingResult();
    } else {
        this.exceptionType = t.getClass();
        this.modelName = null;
        this.model = null;
        this.bindingResult = null;
    }
}
 
Example #18
Source File: LogRetrieverController.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Override
protected ModelAndView handle(HttpServletRequest req, HttpServletResponse res, Object comm, BindException errors) throws Exception {
	LogRetrieverCommand cmd = (LogRetrieverCommand) comm;
	
	TargetInstance ti = targetInstanceManager.getTargetInstance(cmd.getTargetInstanceOid());
	
	File f = null;
	
	try
	{
		f = harvestLogManager.getLogfile(ti, cmd.getLogFileName());
	}
	catch(WCTRuntimeException e)
	{
		
	}
	
	AttachmentView v = new AttachmentView(cmd.getLogFileName(), f, true);
	return new ModelAndView(v);
}
 
Example #19
Source File: GeneralValidatorTest.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateMaxTypeLength() {
	try {
		GeneralCommand cmd = new GeneralCommand();
		Errors errors = new BindException(cmd, "GeneralCommand");
		cmd.setEditMode(true);
		cmd.setName("TestName");
		cmd.setFromDate(new Date());
		cmd.setType(makeLongString(TargetGroup.MAX_TYPE_LENGTH+1, 'X'));
		cmd.setSubGroupType("Sub-Group");
		cmd.setSubGroupSeparator(" > ");
		testInstance.validate(cmd, errors);
		assertEquals("Case02: Expecting 1 errors", 1, errors.getErrorCount());
		assertEquals("Case02: Expecting error[0] for field Type", true, errors.getAllErrors().toArray()[0].toString().contains("Group Type is too long."));
	}
	catch (Exception e)
	{
		String message = e.getClass().toString() + " - " + e.getMessage();
		log.debug(message);
		fail(message);
	}
}
 
Example #20
Source File: ModifyCluster.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
                                BindException errors) throws Exception {
    ClusterForm form = (ClusterForm) command;
    ClusterDO cluster = new ClusterDO();
    cluster.setId(form.getClusterId());
    cluster.setDeployContact(form.getDeployName().trim());
    cluster.setDeployDesc(form.getDeployDesc().trim());
    cluster.setMaintContact(form.getMaintName().trim());
    cluster.setName(form.getClusterName().trim());
    cluster.setOnlineTime(form.getOnlineTime().trim());
    cluster.setSortId(form.getSortId());
    cluster.setEnv(form.getEnv());

    boolean flag = this.xmlAccesser.getClusterDAO().modifyCluster(cluster);

    if (flag) {
        return new ModelAndView("m_success", "info", "集群信息修改成功");
    } else {
        String reason = form.getClusterName() + "已经存在";
        return new ModelAndView("failure", "reason", reason);
    }
}
 
Example #21
Source File: UpdateWidgetValidatorTest.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidationFailsOnEmptyValues() {
    Widget widget = new WidgetImpl();
    Errors errors = new BindException(widget, WIDGET);

    widgetValidator.validate(widget, errors);

    assertEquals(4, errors.getErrorCount());
}
 
Example #22
Source File: SearchController.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object com, BindException errors)
        throws Exception {
    SearchCommand command = (SearchCommand) com;

    User user = securityService.getCurrentUser(request);
    UserSettings userSettings = settingsService.getUserSettings(user.getUsername());
    command.setUser(user);
    command.setPartyModeEnabled(userSettings.isPartyModeEnabled());

    List<MusicFolder> musicFolders = settingsService.getMusicFoldersForUser(user.getUsername());
    String query = StringUtils.trimToNull(command.getQuery());

    if (query != null) {

        SearchCriteria criteria = new SearchCriteria();
        criteria.setCount(MATCH_COUNT);
        criteria.setQuery(query);

        SearchResult artists = searchService.search(criteria, musicFolders, SearchService.IndexType.ARTIST);
        command.setArtists(artists.getMediaFiles());

        SearchResult albums = searchService.search(criteria, musicFolders, SearchService.IndexType.ALBUM);
        command.setAlbums(albums.getMediaFiles());

        SearchResult songs = searchService.search(criteria, musicFolders, SearchService.IndexType.SONG);
        command.setSongs(songs.getMediaFiles());

        command.setPlayer(playerService.getPlayer(request, response));
    }

    return new ModelAndView(getSuccessView(), errors.getModel());
}
 
Example #23
Source File: QaTiSummaryController.java    From webcurator with Apache License 2.0 5 votes vote down vote up
private void processDenoteReferenceCrawl(	HttpServletRequest request, 
								HttpServletResponse response, 
								TargetInstanceSummaryCommand command, 
								BindException errors) throws Exception {
					       	
	TargetInstance ti = targetInstanceManager.getTargetInstance(command.getTargetInstanceOid());
   	ti.getTarget().setReferenceCrawlOid(command.getReferenceCrawlOid());
	// save everything
	targetInstanceManager.save(ti);
}
 
Example #24
Source File: ParamValidateUtils.java    From disconf with Apache License 2.0 5 votes vote down vote up
/**
 * 从bindException中获取到参数错误类型,参数错误
 */
public static ModelAndView getParamErrors(BindException be) {

    // 构造error的映射
    Map<String, String> paramErrors = new HashMap<String, String>();
    Map<String, Object[]> paramArgusErrors = new HashMap<String, Object[]>();
    for (Object error : be.getAllErrors()) {
        if (error instanceof FieldError) {
            FieldError fe = (FieldError) error;
            String field = fe.getField();

            // 默认的message
            String message = fe.getDefaultMessage();
            try {

                contextReader.getMessage(message, fe.getArguments());

            } catch (NoSuchMessageException e) {

                // 如果有code,则从前往后遍历Code(特殊到一般),修改message为code所对应
                for (int i = fe.getCodes().length - 1; i >= 0; i--) {
                    try {
                        String code = fe.getCodes()[i];
                        String info = contextReader.getMessage(code, fe.getArguments());
                        LOG.debug(code + "\t" + info);
                        message = code;
                    } catch (NoSuchMessageException e2) {
                        LOG.debug("");
                    }
                }
            }

            // 最终的消息
            paramErrors.put(field, message);
            paramArgusErrors.put(field, fe.getArguments());
        }
    }

    return ParamValidateUtils.paramError(paramErrors, paramArgusErrors, ErrorCode.FIELD_ERROR);
}
 
Example #25
Source File: EditScheduleController.java    From webcurator with Apache License 2.0 5 votes vote down vote up
protected ModelAndView handleView(HttpServletRequest request, HttpServletResponse response, Object comm, BindException errors) throws Exception {
	TargetSchedulesCommand command = (TargetSchedulesCommand) comm;
	Schedule aSchedule = (Schedule) getEditorContext(request).getObject(Schedule.class, command.getSelectedItem());
	
	TargetSchedulesCommand newCommand = TargetSchedulesCommand.buildFromModel(aSchedule);
	
	List<Date> testResults = new LinkedList<Date>();

	ModelAndView mav = getEditView(request, response, newCommand, errors);
	mav.addObject("testResults", testResults);
	mav.addObject("viewMode", new Boolean(true));

	newCommand.setHeatMap(buildHeatMap());
	newCommand.setHeatMapThresholds(buildHeatMapThresholds());
	
	if(newCommand.getScheduleType() < 0) {
		mav.addObject("monthOptions", getMonthOptionsByType(newCommand.getScheduleType()));
	}

	try {
		CronExpression expr = new CronExpression(aSchedule.getCronPattern());
		Date d = DateUtils.latestDate(new Date(), newCommand.getStartDate());
		Date nextDate = null;
		for(int i = 0; i<10; i++) {
			nextDate = expr.getNextValidTimeAfter(d);
			if(nextDate == null || newCommand.getEndDate() != null && nextDate.after(newCommand.getEndDate())) {
				break;
			}
			testResults.add(nextDate);
			d = nextDate;
		}
	}
	catch(ParseException ex) {
		ex.printStackTrace();
	}

	return mav;
}
 
Example #26
Source File: ApiResponse.java    From j360-dubbo-app-all with Apache License 2.0 5 votes vote down vote up
/**
 * 参数绑定错误响应
 *
 * @param exception 异常
 * @return 响应
 */
public static ApiResponse createRestResponse(BindException exception, HttpServletRequest request) {
    Builder builder = newBuilder();
    if (null != exception && exception.hasErrors()) {
        StringBuilder error = new StringBuilder("");
        for (ObjectError objectError : exception.getAllErrors()) {
            error.append(objectError.getDefaultMessage() + ";");
        }
        log.error(error.toString());
        builder.status(BaseApiStatus.SYST_SERVICE_UNAVAILABLE);
        builder.error(getMessage(String.valueOf(builder.getThis().status),request));
    }
    return builder.data(null).build();
}
 
Example #27
Source File: GeneratePermissionTemplateController.java    From webcurator with Apache License 2.0 5 votes vote down vote up
@Override
protected ModelAndView showForm(HttpServletRequest aReq,
        HttpServletResponse aRes, BindException aErrors) throws Exception {
    
    String siteOid = aReq.getParameter("siteOid");
    Long oid= Long.valueOf(siteOid);
    ModelAndView mav = new ModelAndView();
    Site aSite = siteManager.getSite(oid,true);
    Set permissions = aSite.getPermissions();
    mav.addObject("permissions", permissions);
    List templates = permissionTemplateManager.getTemplates(AuthUtil.getRemoteUserObject());
    mav.addObject(GeneratePermissionTemplateCommand.MDL_TEMPLATES, templates);
    mav.setViewName("select-permission");
    return mav;
}
 
Example #28
Source File: MetadataController.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequestMapping(value = "**")
public ResponseEntity<String> getMetadata(@Valid MetadataRequestParameterBean params, BindingResult result,
    HttpServletResponse res, HttpServletRequest req) throws Exception {

  if (result.hasErrors())
    throw new BindException(result);
  String path = TdsPathUtils.extractPath(req, "metadata");

  try (GridDataset gridDataset = TdsRequestedDataset.getGridDataset(req, res, path)) {
    if (gridDataset == null)
      return null;

    NetcdfFile ncfile = gridDataset.getNetcdfFile(); // LOOK maybe gridDataset.getFileTypeId ??
    String fileTypeS = ncfile.getFileTypeId();
    ucar.nc2.constants.DataFormatType fileFormat = ucar.nc2.constants.DataFormatType.getType(fileTypeS);
    if (fileFormat != null)
      fileTypeS = fileFormat.toString(); // canonicalize

    ThreddsMetadata.VariableGroup vars = new ThreddsMetadataExtractor().extractVariables(fileTypeS, gridDataset);

    boolean wantXML = (params.getAccept() != null) && params.getAccept().equalsIgnoreCase("XML");

    HttpHeaders responseHeaders = new HttpHeaders();
    String strResponse;
    if (wantXML) {
      strResponse = writeXML(vars);
      responseHeaders.set(ContentType.HEADER, ContentType.xml.getContentHeader());
      // responseHeaders.set(Constants.Content_Disposition, Constants.setContentDispositionValue(datasetPath,
      // ".xml"));
    } else {
      strResponse = writeHTML(vars);
      responseHeaders.set(ContentType.HEADER, ContentType.html.getContentHeader());
    }
    return new ResponseEntity<>(strResponse, responseHeaders, HttpStatus.OK);
  }

}
 
Example #29
Source File: CommentRestController.java    From wallride with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public CommentSavedModel update(
		@PathVariable long id,
		@Validated CommentForm form,
		BindingResult result,
		AuthorizedUser authorizedUser) throws BindException {
	if (result.hasFieldErrors("content")) {
		throw new BindException(result);
	}
	CommentUpdateRequest request = form.toCommentUpdateRequest(id);
	Comment comment = commentService.updateComment(request, authorizedUser);
	return new CommentSavedModel(comment);
}
 
Example #30
Source File: NcssPointController.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequestMapping("**")
public void handleRequest(HttpServletRequest req, HttpServletResponse res, @Valid NcssPointParamsBean params,
    BindingResult validationResult) throws Exception {
  if (validationResult.hasErrors())
    throw new BindException(validationResult);

  String datasetPath = getDatasetPath(req);
  try (FeatureDatasetPoint fdp = TdsRequestedDataset.getPointDataset(req, res, datasetPath)) {
    if (fdp == null)
      return;

    Formatter errs = new Formatter();
    if (!params.intersectsTime(fdp.getCalendarDateRange(), errs)) {
      handleValidationErrorMessage(res, HttpServletResponse.SC_BAD_REQUEST, errs.toString());
      return;
    }

    FeatureType ft = fdp.getFeatureType();
    if (ft != FeatureType.POINT && ft != FeatureType.STATION) {
      throw new NcssException("Dataset Feature Type is " + ft.toString() + " but request is for Points or Stations");
    }

    SubsetParams ncssParams = params.makeSubset();
    SupportedFormat format = getSupportedOperation(fdp).getSupportedFormat(params.getAccept());

    DsgSubsetWriter pds =
        DsgSubsetWriterFactory.newInstance(fdp, ncssParams, ncssDiskCache, res.getOutputStream(), format);
    setResponseHeaders(res, pds.getHttpHeaders(datasetPath, format.isStream()));
    pds.respond(res, fdp, datasetPath, ncssParams, format);
  }
}