Java Code Examples for org.springframework.web.context.request.WebRequest

The following are top voted examples for showing how to use org.springframework.web.context.request.WebRequest. 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: xm-uaa   File: SocialController.java   View source code 6 votes vote down vote up
@GetMapping("/signup")
public RedirectView signUp(WebRequest webRequest,
    @CookieValue(name = "NG_TRANSLATE_LANG_KEY", required = false, defaultValue = "\"en\"") String langKey) {
    String providerId = null;
    try {
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(webRequest);
        providerId = connection.getKey().getProviderId();
        socialService.createSocialUser(connection, langKey.replace("\"", ""));
        return redirect(URIBuilder
                        .fromUri(TenantUtil.getApplicationUrl() + "/social-register/"
                                        + connection.getKey().getProviderId())
                        .queryParam("success", "true").build().toString());
    } catch (Exception e) {
        log.error("Exception creating social user: ", e);
        return redirectOnError(providerId);
    }
}
 
Example 2
Project: spring-rest-sample   File: GlobalExceptionHandler.java   View source code 6 votes vote down vote up
/**
 * 处理JPA的异常
 *
 * @param ex
 * @param request
 * @return
 */
@ExceptionHandler(value = {JpaSystemException.class})
public ResponseEntity<ErrorResponse> handleJpaException(Exception ex, WebRequest request) {

    if (log.isDebugEnabled()) {
        log.debug("handling exception ==> " + request.getDescription(true));
    }

    RestException rex = new RestException(PARAMS_RESOLUTION_ERROR, ex.getLocalizedMessage());
    ErrorResponse res = new ErrorResponse(rex);

    return new ResponseEntity<>(res, rex.getHttpStatus());
}
 
Example 3
Project: amv-access-api-poc   File: AmvAccessRestExceptionHandlerAdvice.java   View source code 6 votes vote down vote up
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body,
                                                         HttpHeaders headers, HttpStatus status, WebRequest request) {
    log.error("", ex);

    Exception e = unwrapIfNecessary(ex);

    ErrorInfoDto errorInfoDto = ErrorInfoDto.builder()
            .title(e.getClass().getSimpleName())
            .detail(e.getMessage())
            .build();

    ErrorResponseDto errorResponseDto = ErrorResponseDto.builder()
            .addError(errorInfoDto)
            .build();

    return new ResponseEntity<>(errorResponseDto, headers, status);
}
 
Example 4
Project: xxproject   File: CustomRestExceptionHandler.java   View source code 6 votes vote down vote up
@Override
protected ResponseEntity<Object> handleTypeMismatch(final TypeMismatchException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final String error = ex.getValue() + " value for " + ex.getPropertyName() + " should be of type " + ex.getRequiredType();

    final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
 
Example 5
Project: openfleet   File: EmployeeBuilderTest.java   View source code 6 votes vote down vote up
@BeforeClass
public static void init(){
    locationService = LocationSupplier.getMockProvider();
    employeeBuilder = new EmployeeBuilder(locationService);

    mockedWebRequest = Mockito.mock(WebRequest.class);
    Mockito.when(mockedWebRequest.getParameter("id")).thenReturn("1");
    Mockito.when(mockedWebRequest.getParameter("firstName")).thenReturn("John");
    Mockito.when(mockedWebRequest.getParameter("lastName")).thenReturn("Shepard");
    Mockito.when(mockedWebRequest.getParameter("dateOfBirth")).thenReturn("1993-01-01");
    Mockito.when(mockedWebRequest.getParameter("placeOfBirth")).thenReturn("1");
    Mockito.when(mockedWebRequest.getParameter("socialInsuranceNo")).thenReturn("1");
    Mockito.when(mockedWebRequest.getParameter("taxNo")).thenReturn("1");
    Mockito.when(mockedWebRequest.getParameter("mothersName")).thenReturn("Jane Doe");
    Mockito.when(mockedWebRequest.getParameter("driversCardNo")).thenReturn("2");
    Mockito.when(mockedWebRequest.getParameter("placeOfLiving")).thenReturn("1");
    Mockito.when(mockedWebRequest.getParameter("employmentDate")).thenReturn("2017-05-18");
}
 
Example 6
Project: openfleet   File: TransportBuilderTest.java   View source code 6 votes vote down vote up
private static WebRequest setupWebRequest(){
    WebRequest request = Mockito.mock(WebRequest.class);
    Mockito.when(request.getParameter("id")).thenReturn("1");
    Mockito.when(request.getParameter("tractor")).thenReturn("1");
    Mockito.when(request.getParameter("trailer")).thenReturn("1");
    Mockito.when(request.getParameter("employee")).thenReturn("1");
    Mockito.when(request.getParameter("cargo_count")).thenReturn("1");
    Mockito.when(request.getParameter("cargo_weight")).thenReturn("1");
    Mockito.when(request.getParameter("cargo_name")).thenReturn("Sample Cargo");
    Mockito.when(request.getParameter("place_of_load")).thenReturn("1");
    Mockito.when(request.getParameter("place_of_unload")).thenReturn("1");
    Mockito.when(request.getParameter("time_of_load")).thenReturn("2017-05-01T08:00");
    Mockito.when(request.getParameter("time_of_unload")).thenReturn("2017-05-10T08:00");
    Mockito.when(request.getParameter("start")).thenReturn("2017-05-01T08:00");
    Mockito.when(request.getParameter("finish")).thenReturn("2017-05-10T08:00");
    return request;
}
 
Example 7
Project: open-kilda   File: NorthboundExceptionHandler.java   View source code 6 votes vote down vote up
/**
 * Handles NorthboundException exception.
 *
 * @param exception the NorthboundException instance
 * @param request   the WebRequest caused exception
 * @return the ResponseEntity object instance
 */
@ExceptionHandler(MessageException.class)
protected ResponseEntity<Object> handleMessageException(MessageException exception, WebRequest request) {
    HttpStatus status;

    switch (exception.getErrorType()) {
        case NOT_FOUND:
            status = HttpStatus.NOT_FOUND;
            break;
        case DATA_INVALID:
        case PARAMETERS_INVALID:
            status = HttpStatus.BAD_REQUEST;
            break;
        case ALREADY_EXISTS:
            status = HttpStatus.CONFLICT;
            break;
        case AUTH_FAILED:
            status = HttpStatus.UNAUTHORIZED;
            break;
        case OPERATION_TIMED_OUT:
        case INTERNAL_ERROR:
        default:
            status = HttpStatus.INTERNAL_SERVER_ERROR;
            break;
    }

    MessageError error = new MessageError(request.getHeader(CORRELATION_ID), exception.getTimestamp(),
            exception.getErrorType().toString(), exception.getMessage(), exception.getErrorDescription());
    return super.handleExceptionInternal(exception, error, new HttpHeaders(), status, request);
}
 
Example 8
Project: theskeleton   File: RegistrationController.java   View source code 6 votes vote down vote up
@PostMapping
public String register(@Valid RegistrationForm registrationForm, BindingResult bindingResult, WebRequest request) {
	if (bindingResult.hasErrors())
		return registrationView(registrationForm, request);
	try {
		UserEntity user = registrationService.registerUser(registrationForm);
		if (user != null && user.getId() != null) {
			tokenStoreService.sendTokenNotification(TokenStoreType.USER_ACTIVATION, user);
			providerSignInUtils.doPostSignUp(user.getId(), request);
		}
	} catch (RegistrationException e) {
		bindingResult.rejectValue("username", "error.registrationForm", e.getMessage());
		return registrationView(registrationForm, request);
	}
	return REGISTRATION_CONFIRMATION;
}
 
Example 9
Project: spring-ddd-bank   File: ApplicationController.java   View source code 6 votes vote down vote up
@GetMapping(path="/bank/client")
  public ResponseEntity<ClientResource[]> findClients(
  		@RequestParam(name="fromBirth", defaultValue="") final String fromBirth,
  		@RequestParam(name="minBalance", defaultValue="") final String minBalance,
  		final HttpMethod method, final WebRequest request
  		){
_print(method, request);
  	final List<Client> clients;
  	if("".equals(fromBirth) && "".equals(minBalance)) {
  	    clients = bankService.findAllClients();
  	}else if("".equals(minBalance)) { //only fromBirth given
      	final LocalDate fromBirthLocalDate = LocalDate.parse(fromBirth, Util.MEDIUM_DATE_FORMATTER);
  		clients = bankService.findYoungClients(fromBirthLocalDate);
  	}else if(fromBirth.equals("")) { //only minBalance given
      	final double minBalanceDouble = Double.parseDouble(minBalance);
      	final Amount minBalanceAmount = new Amount(minBalanceDouble);
  		clients = bankService.findRichClients(minBalanceAmount);
  	}else {
  		throw new Exc("Must not provide both parameters: fromBirth and minBalance!");
  	}
      return _clientsToResources(clients);
  }
 
Example 10
Project: nixmash-blog   File: UserController.java   View source code 6 votes vote down vote up
@RequestMapping(value = "/signup", method = RequestMethod.GET)
public String signupForm(@ModelAttribute SocialUserDTO socialUserDTO, WebRequest request, Model model) {
    if (request.getUserPrincipal() != null)
        return "redirect:/";
    else {
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(request);
        request.setAttribute("connectionSubheader",
                webUI.parameterizedMessage(MESSAGE_KEY_SOCIAL_SIGNUP,
                        StringUtils.capitalize(connection.getKey().getProviderId())),
                RequestAttributes.SCOPE_REQUEST);

        socialUserDTO = createSocialUserDTO(request, connection);

        ConnectionData connectionData = connection.createData();
        SignInUtils.setUserConnection(request, connectionData);

        model.addAttribute(MODEL_ATTRIBUTE_SOCIALUSER, socialUserDTO);
        return SIGNUP_VIEW;
    }
}
 
Example 11
Project: nixmash-blog   File: UserController.java   View source code 6 votes vote down vote up
@RequestMapping(value = "/signup", method = POST)
public String signup(@Valid @ModelAttribute("socialUserDTO") SocialUserDTO socialUserDTO, BindingResult result,
                     WebRequest request, RedirectAttributes redirectAttributes) {
    if (result.hasErrors()) {
        return SIGNUP_VIEW;
    }

    UserDTO userDTO = createUserDTO(socialUserDTO);
    User user = userService.create(userDTO);

    providerSignInUtils.doPostSignUp(userDTO.getUsername(), request);
    UserConnection userConnection =
            userService.getUserConnectionByUserId(userDTO.getUsername());
    if (userConnection.getImageUrl() != null) {
        try {
            webUI.processProfileImage(userConnection.getImageUrl(), user.getUserKey());
            userService.updateHasAvatar(user.getId(), true);
        } catch (IOException e) {
            logger.error("ImageUrl IOException for username: {0}", user.getUsername());
        }
    }
    SignInUtils.authorizeUser(user);

    redirectAttributes.addFlashAttribute("connectionWelcomeMessage", true);
    return "redirect:/";
}
 
Example 12
Project: xxproject   File: CustomRestExceptionHandler.java   View source code 6 votes vote down vote up
@Override
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(final HttpRequestMethodNotSupportedException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final StringBuilder builder = new StringBuilder();
    builder.append(ex.getMethod());
    builder.append(" method is not supported for this request. Supported methods are ");
    ex.getSupportedHttpMethods().forEach(t -> builder.append(t + " "));

    final ApiError apiError = new ApiError(HttpStatus.METHOD_NOT_ALLOWED, ex.getLocalizedMessage(), builder.toString());
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
 
Example 13
Project: monarch   File: DataCommandsController.java   View source code 6 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = "/regions/data/query")
public Callable<ResponseEntity<String>> query(final WebRequest request,
    @RequestParam(CliStrings.QUERY__QUERY) final String oql,
    @RequestParam(value = CliStrings.QUERY__STEPNAME,
        defaultValue = CliStrings.QUERY__STEPNAME__DEFAULTVALUE) final String stepName,
    @RequestParam(value = CliStrings.QUERY__INTERACTIVE,
        defaultValue = "true") final Boolean interactive) {
  // logRequest(request);

  final CommandStringBuilder command = new CommandStringBuilder(CliStrings.QUERY);

  command.addOption(CliStrings.QUERY__QUERY, decode(oql));
  command.addOption(CliStrings.QUERY__STEPNAME, stepName);
  command.addOption(CliStrings.QUERY__INTERACTIVE,
      String.valueOf(Boolean.TRUE.equals(interactive)));

  return getProcessCommandCallable(command.toString());
}
 
Example 14
Project: lams   File: OpenSessionInViewInterceptor.java   View source code 6 votes vote down vote up
/**
 * Unbind the Hibernate {@code Session} from the thread and close it (in
 * single session mode), or process deferred close for all sessions that have
 * been opened during the current request (in deferred close mode).
 * @see org.springframework.transaction.support.TransactionSynchronizationManager
 */
@Override
public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
	if (!decrementParticipateCount(request)) {
		if (isSingleSession()) {
			// single session mode
			SessionHolder sessionHolder =
					(SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory());
			logger.debug("Closing single Hibernate Session in OpenSessionInViewInterceptor");
			SessionFactoryUtils.closeSession(sessionHolder.getSession());
		}
		else {
			// deferred close mode
			SessionFactoryUtils.processDeferredClose(getSessionFactory());
		}
	}
}
 
Example 15
Project: ait-platform   File: AitRestExceptionHandler.java   View source code 6 votes vote down vote up
@ExceptionHandler({ MethodArgumentTypeMismatchException.class })
public ResponseEntity<Object> handleMethodArgumentTypeMismatch(final MethodArgumentTypeMismatchException ex, final WebRequest request) {
	logger.info(ex.getClass().getName());
	//
	final String error = ex.getName() + " should be of type " + ex.getRequiredType().getName();

	final AitException AitException = new AitException(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
	return new ResponseEntity<Object>(AitException, new HttpHeaders(), AitException.getStatus());
}
 
Example 16
Project: logistimo-web-service   File: ErrorHandler.java   View source code 6 votes vote down vote up
@ExceptionHandler({HystrixBadRequestException.class})
protected ResponseEntity<Object> handleBadRequest(HystrixBadRequestException e, WebRequest request) {
  logWarning(request, e);
  String message = e.getMessage();
  String code = "[Bad Request]";
  int statusCode = 400;
  if(e.getCause() instanceof LogiException){
    message = e.getCause().getMessage();
    code = ((LogiException) e.getCause()).getCode();
    statusCode = ((LogiException) e.getCause()).getStatusCode();
    //409 is used in Logi to reload when domain Id changes, hence changing it.
    if (statusCode == 409 || statusCode == 0) {
      statusCode = 400;
    }

  }
  ErrorResource
      error =
      new ErrorResource(code, message);
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_JSON);
  return handleExceptionInternal(e, error, headers, HttpStatus.valueOf(statusCode), request);
}
 
Example 17
Project: lams   File: ConfigurableWebBindingInitializer.java   View source code 6 votes vote down vote up
@Override
public void initBinder(WebDataBinder binder, WebRequest request) {
	binder.setAutoGrowNestedPaths(this.autoGrowNestedPaths);
	if (this.directFieldAccess) {
		binder.initDirectFieldAccess();
	}
	if (this.messageCodesResolver != null) {
		binder.setMessageCodesResolver(this.messageCodesResolver);
	}
	if (this.bindingErrorProcessor != null) {
		binder.setBindingErrorProcessor(this.bindingErrorProcessor);
	}
	if (this.validator != null && binder.getTarget() != null &&
			this.validator.supports(binder.getTarget().getClass())) {
		binder.setValidator(this.validator);
	}
	if (this.conversionService != null) {
		binder.setConversionService(this.conversionService);
	}
	if (this.propertyEditorRegistrars != null) {
		for (PropertyEditorRegistrar propertyEditorRegistrar : this.propertyEditorRegistrars) {
			propertyEditorRegistrar.registerCustomEditors(binder);
		}
	}
}
 
Example 18
Project: lams   File: OpenEntityManagerInViewInterceptor.java   View source code 5 votes vote down vote up
@Override
public void preHandle(WebRequest request) throws DataAccessException {

	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applyCallableInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if (TransactionSynchronizationManager.hasResource(getEntityManagerFactory())) {
		// do not modify the EntityManager: just mark the request accordingly
		Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewInterceptor");
		try {
			EntityManager em = createEntityManager();
			EntityManagerHolder emHolder = new EntityManagerHolder(em);
			TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), emHolder);

			AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getEntityManagerFactory(), emHolder);
			asyncManager.registerCallableInterceptor(participateAttributeName, interceptor);
			asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor);
		}
		catch (PersistenceException ex) {
			throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
		}
	}
}
 
Example 19
Project: burpextender-proxyhistory-webui   File: JdbcConnectionInterceptor.java   View source code 5 votes vote down vote up
@Override
public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView mav)
        throws Exception {
    // postHandle()はcontroller内で例外が発生しても呼ばれるので安心。
    // ただしこの後にviewが呼ばれるので、viewの中からはDB接続使えないようにしておく、という意図はある。
    ServletWebRequest wr = new ServletWebRequest(req);
    Connection dbconn = (Connection) wr.getAttribute("dbconn", WebRequest.SCOPE_REQUEST);
    DataStore.closeConnection(dbconn);
}
 
Example 20
Project: spring-boot-tus   File: TusExceptionsCotroller.java   View source code 5 votes vote down vote up
@ExceptionHandler(value = { TusDBFileNotFoundException.class })
@ResponseStatus(HttpStatus.NOT_FOUND)
public TusException VideoNotFoundExceptionHandler(TusDBFileNotFoundException e, WebRequest req) {
    e.printStackTrace();

    TusException err = new TusException("not found", e);
    return err;
}
 
Example 21
Project: xxproject   File: CustomRestExceptionHandler.java   View source code 5 votes vote down vote up
@ExceptionHandler({ ConstraintViolationException.class })
public ResponseEntity<Object> handleConstraintViolation(final ConstraintViolationException ex, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final List<String> errors = new ArrayList<String>();
    for (final ConstraintViolation<?> violation : ex.getConstraintViolations()) {
        errors.add(violation.getRootBeanClass().getName() + " " + violation.getPropertyPath() + ": " + violation.getMessage());
    }

    final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errors);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
 
Example 22
Project: spring-boot-rest-example   File: AbstractRestHandler.java   View source code 5 votes vote down vote up
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(ResourceNotFoundException.class)
public @ResponseBody RestErrorInfoEntity handleResourceNotFoundException(ResourceNotFoundException ex,
		WebRequest request, HttpServletResponse response) {
	log.info("ResourceNotFoundException handler:" + ex.getMessage());

	return new RestErrorInfoEntity(ex, "Sorry, Resource does not exist");
}
 
Example 23
Project: amv-access-api-poc   File: AmvAccessRestExceptionHandlerAdvice.java   View source code 5 votes vote down vote up
@ExceptionHandler({
        Exception.class
})
public final ResponseEntity<Object> handle(Exception ex, WebRequest request) {
    HttpHeaders headers = new HttpHeaders();

    Exception e = unwrapIfNecessary(ex);

    final HttpStatus status = findHttpStatus(ex)
            .orElseGet(() -> findHttpStatus(e).orElse(HttpStatus.INTERNAL_SERVER_ERROR));

    return handleExceptionInternal(e, null, headers, status, request);
}
 
Example 24
Project: lams   File: OpenSessionInViewInterceptor.java   View source code 5 votes vote down vote up
private boolean decrementParticipateCount(WebRequest request) {
	String participateAttributeName = getParticipateAttributeName();
	Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
	if (count == null) {
		return false;
	}
	// Do not modify the Session: just clear the marker.
	if (count > 1) {
		request.setAttribute(participateAttributeName, count - 1, WebRequest.SCOPE_REQUEST);
	}
	else {
		request.removeAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
	}
	return true;
}
 
Example 25
Project: openfleet   File: TransportController.java   View source code 5 votes vote down vote up
@PostMapping("/transport/job/addCost")
public String addCost(Model model, WebRequest request){
    logger.trace("Adding Costs...");
    long id = Long.parseLong(request.getParameter("transportId"));
    logger.debug("id: {}",id);
    TransferCost cost = TransferCostBuilder.buildFromWebRequest(request);
    logger.debug("cost: {}",cost);
    Transport transport = transportService.getTransportById(id);
    transport.addCost(cost);
    logger.debug("count: {}",transport.getCosts().size());
    transportService.updateTransport(transport);
    return transportDetails(id,model);
}
 
Example 26
Project: lams   File: DefaultSessionAttributeStore.java   View source code 5 votes vote down vote up
@Override
public void storeAttribute(WebRequest request, String attributeName, Object attributeValue) {
	Assert.notNull(request, "WebRequest must not be null");
	Assert.notNull(attributeName, "Attribute name must not be null");
	Assert.notNull(attributeValue, "Attribute value must not be null");
	String storeAttributeName = getAttributeNameInSession(request, attributeName);
	request.setAttribute(storeAttributeName, attributeValue, WebRequest.SCOPE_SESSION);
}
 
Example 27
Project: openfleet   File: TrailerController.java   View source code 5 votes vote down vote up
@PostMapping("/trailer/add")
public String addTrailer(Model model, WebRequest request){
    logger.info("Starting trailer adding / updating method.");
    logger.debug("Id is: {}",request.getParameter("id"));
    trailerService.addOrUpdate(request);
    return listTrailers(model);
}
 
Example 28
Project: openfleet   File: LocationBuilder.java   View source code 5 votes vote down vote up
/**
 * Takes the parameters from the {@link org.springframework.web.context.request.WebRequest} and parses into the new {@link com.markbudai.openfleet.model.Location} object by its setter methods.
 * @param request the {@link org.springframework.web.context.request.WebRequest} containing parameters for the new {@link com.markbudai.openfleet.model.Location} object.
 * @return the parsed  {@link com.markbudai.openfleet.model.Location} object.
 * @exception com.markbudai.openfleet.exception.EmptyParameterException if any parameter is empty.
 */
public static Location buildFromWebRequest(WebRequest request){
    Location loc = new Location();
    if(!(request.getParameter("id").isEmpty())){
        loc.setId(Long.parseLong(request.getParameter("id")));
    }
    if(request.getParameter("country").isEmpty()){
        throw new EmptyParameterException("country");
    }
    loc.setCountry(request.getParameter("country"));
    if(request.getParameter("city").isEmpty()){
        throw new EmptyParameterException("city");
    }
    loc.setCity(request.getParameter("city"));
    if(request.getParameter("region").isEmpty()){
        throw new EmptyParameterException("region");
    }
    loc.setRegion(request.getParameter("region"));
    if(request.getParameter("street").isEmpty()){
        throw new EmptyParameterException("street");
    }
    loc.setStreet(request.getParameter("street"));
    if(request.getParameter("houseNo").isEmpty()){
        throw new EmptyParameterException("houseNo");
    }
    loc.setHouseNo(request.getParameter("houseNo"));
    if(request.getParameter("zipcode").isEmpty()){
        throw new EmptyParameterException("zipcode");
    }
    loc.setZipcode(request.getParameter("zipcode"));
    return loc;
}
 
Example 29
Project: openfleet   File: TractorBuilderTest.java   View source code 5 votes vote down vote up
@BeforeClass
public static void init(){
    mockedWebRequest = Mockito.mock(WebRequest.class);
    Mockito.when(mockedWebRequest.getParameter("id")).thenReturn("1");
    Mockito.when(mockedWebRequest.getParameter("type")).thenReturn("SampleV8");
    Mockito.when(mockedWebRequest.getParameter("manufacturer")).thenReturn("Sample");
    Mockito.when(mockedWebRequest.getParameter("date_of_manufacture")).thenReturn("1999-01-01");
    Mockito.when(mockedWebRequest.getParameter("date_of_acquire")).thenReturn("2017-01-01");
    Mockito.when(mockedWebRequest.getParameter("date_of_supervision")).thenReturn("2017-05-05");
    Mockito.when(mockedWebRequest.getParameter("plate_number")).thenReturn("SAM-PLE");
    Mockito.when(mockedWebRequest.getParameter("chassis_number")).thenReturn("SSSSSAMPLE");
    Mockito.when(mockedWebRequest.getParameter("fuel_norm")).thenReturn("1.0");
    Mockito.when(mockedWebRequest.getParameter("weight")).thenReturn("1");
    Mockito.when(mockedWebRequest.getParameter("max_weight")).thenReturn("1000");
}
 
Example 30
Project: xxproject   File: CustomRestExceptionHandler.java   View source code 5 votes vote down vote up
@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(final MissingServletRequestParameterException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final String error = ex.getParameterName() + " parameter is missing";
    final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
 
Example 31
Project: openfleet   File: TrailerBuilderTest.java   View source code 5 votes vote down vote up
@BeforeClass
public static void init(){
    mockedWebRequest = Mockito.mock(WebRequest.class);
    Mockito.when(mockedWebRequest.getParameter("id")).thenReturn("1");
    Mockito.when(mockedWebRequest.getParameter("type")).thenReturn("Samplerunner");
    Mockito.when(mockedWebRequest.getParameter("manufacturer")).thenReturn("Sample Co");
    Mockito.when(mockedWebRequest.getParameter("date_of_manufacture")).thenReturn("1999-01-01");
    Mockito.when(mockedWebRequest.getParameter("date_of_acquire")).thenReturn("2017-01-01");
    Mockito.when(mockedWebRequest.getParameter("date_of_supervision")).thenReturn("2017-05-05");
    Mockito.when(mockedWebRequest.getParameter("plate_number")).thenReturn("SAM-LPE");
    Mockito.when(mockedWebRequest.getParameter("chassis_number")).thenReturn("SSSAMPLE");
    Mockito.when(mockedWebRequest.getParameter("weight")).thenReturn("1");
    Mockito.when(mockedWebRequest.getParameter("max_load_weight")).thenReturn("100");
}
 
Example 32
Project: spring-boot-tus   File: TusExceptionsCotroller.java   View source code 5 votes vote down vote up
@ExceptionHandler(value = { TusBadRequestException.class })
@ResponseStatus(HttpStatus.FORBIDDEN)
public TusException TusBadRequestExceptionHandler(TusBadRequestException e, WebRequest req) {
    e.printStackTrace();

    TusException err = new TusException("bad request", e);
    return err;
}
 
Example 33
Project: spring-microservice-sample   File: UserExeceptionHandler.java   View source code 5 votes vote down vote up
@ExceptionHandler(value = {UserNotFoundException.class})
public ResponseEntity userNotFound(UserNotFoundException ex, WebRequest req) {
    Map<String, String> errorMsg = new HashMap<>();
    errorMsg.put("entity", "USER");
    errorMsg.put("id", ""+ ex.getUsername());
    errorMsg.put("code", "not_found");
    errorMsg.put("message", ex.getMessage());
    return ResponseEntity.status(HttpStatus.CONFLICT).body(ex);
}
 
Example 34
Project: spring-microservice-sample   File: AuthExeceptionHandler.java   View source code 5 votes vote down vote up
@ExceptionHandler(value = {UsernameWasTakenException.class, EmailWasTakenException.class})
public ResponseEntity signupFailed(Exception ex, WebRequest req) {
    Map<String, String> errorMsg = new HashMap<>();
    errorMsg.put("code", "conflict");
    errorMsg.put("message", ex.getMessage());
    return ResponseEntity.status(HttpStatus.CONFLICT).body(ex.getMessage());
}
 
Example 35
Project: spring-microservice-sample   File: PostExceptionHandler.java   View source code 5 votes vote down vote up
@ExceptionHandler(PostNotFoundException.class)
public ResponseEntity notFound(PostNotFoundException ex, WebRequest req) {
    Map<String, String> errors = new HashMap<>();
    errors.put("entity", "POST");
    errors.put("id", "" + ex.getSlug());
    errors.put("code", "not_found");
    errors.put("message", ex.getMessage());

    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errors);
}
 
Example 36
Project: HelloShiftLeft   File: CustomerController.java   View source code 5 votes vote down vote up
/**
     * Check if settings= is present in cookie
     * @param request
     * @return
     */
    private boolean checkCookie(WebRequest request) throws Exception {
    	try {
	return request.getHeader("Cookie").startsWith("settings=");
}
catch (Exception ex)
{
	System.out.println(ex.getMessage());
}
return false;
    }
 
Example 37
Project: devops-cstack   File: RestHandlerException.java   View source code 5 votes vote down vote up
@ExceptionHandler(value = {CheckException.class})
protected ResponseEntity<Object> handleCheckedeException(Exception ex,
                                                         WebRequest request) {
    ex.printStackTrace();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    return handleExceptionInternal(ex,
        new HttpErrorServer(ex.getLocalizedMessage()), headers,
        HttpStatus.BAD_REQUEST, request);
}
 
Example 38
Project: devops-cstack   File: RestHandlerException.java   View source code 5 votes vote down vote up
@ExceptionHandler(value = {NullPointerException.class})
protected ResponseEntity<Object> handleNullPointerException(Exception ex,
                                                            WebRequest request) {
    ex.printStackTrace();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    return handleExceptionInternal(
        ex,
        new HttpErrorServer(
            "An unkown error has occured! Server response : NullPointerException"),
        headers, HttpStatus.INTERNAL_SERVER_ERROR, request);
}
 
Example 39
Project: devops-cstack   File: RestHandlerException.java   View source code 5 votes vote down vote up
@ExceptionHandler(value = {OutOfMemoryError.class})
protected ResponseEntity<Object> handleOutOfMemoryError(Exception ex,
                                                        WebRequest request) {
    ex.printStackTrace();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    return handleExceptionInternal(
        ex,
        new HttpErrorServer(
            "An unkown error has occured! Server response : OutOfMemoryError"),
        headers, HttpStatus.INTERNAL_SERVER_ERROR, request);
}
 
Example 40
Project: devops-cstack   File: RestHandlerException.java   View source code 5 votes vote down vote up
@ExceptionHandler(value = {ClassCastException.class})
protected ResponseEntity<Object> handleClassCastException(Exception ex,
                                                          WebRequest request) {
    ex.printStackTrace();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    return handleExceptionInternal(
        ex,
        new HttpErrorServer(
            "An unkown error has occured! Server response : ClassCastException"),
        headers, HttpStatus.INTERNAL_SERVER_ERROR, request);
}