org.springframework.http.ResponseEntity Java Examples

The following examples show how to use org.springframework.http.ResponseEntity. 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: PaymentApiController.java    From alf.io with GNU General Public License v3.0 7 votes vote down vote up
@PostMapping("/api/events/{eventName}/reservation/{reservationId}/payment/{method}/init")
public ResponseEntity<TransactionInitializationToken> initTransaction(@PathVariable("eventName") String eventName,
                                                                      @PathVariable("reservationId") String reservationId,
                                                                      @PathVariable("method") String paymentMethodStr,
                                                                      @RequestParam MultiValueMap<String, String> allParams) {

    var paymentMethod = PaymentMethod.safeParse(paymentMethodStr);
    if (paymentMethod == null) {
        return ResponseEntity.badRequest().build();
    }

    return getEventReservationPair(eventName, reservationId)
        .flatMap(pair -> ticketReservationManager.initTransaction(pair.getLeft(), reservationId, paymentMethod, allParams))
        .map(ResponseEntity::ok)
        .orElseGet(() -> ResponseEntity.notFound().build());
}
 
Example #2
Source File: FakeClassnameTestApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * PATCH /fake_classname_test : To test class name in snake case
 * To test class name in snake case
 *
 * @param body client model (required)
 * @return successful operation (status code 200)
 */
@ApiVirtual
@ApiOperation(value = "To test class name in snake case", nickname = "testClassname", notes = "To test class name in snake case", response = Client.class, authorizations = {
    @Authorization(value = "api_key_query")
}, tags={ "fake_classname_tags 123#$%^", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "successful operation", response = Client.class) })
@RequestMapping(value = "/fake_classname_test",
    produces = { "application/json" }, 
    consumes = { "application/json" },
    method = RequestMethod.PATCH)
default ResponseEntity<Client> testClassname(@ApiParam(value = "client model" ,required=true )  @Valid @RequestBody Client body) {
    getRequest().ifPresent(request -> {
        for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
            if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
                String exampleString = "{ \"client\" : \"client\" }";
                ApiUtil.setExampleResponse(request, "application/json", exampleString);
                break;
            }
        }
    });
    return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);

}
 
Example #3
Source File: IMSController.java    From blue-marlin with Apache License 2.0 6 votes vote down vote up
/**
 * This end-point returns hourly traffic (number of impressions) for a targeting channel.
 *
 * @param payload
 * @return
 * @throws JSONException
 */
@RequestMapping(value = "/api/chart", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity chart(@RequestBody IMSRequestQuery payload) throws JSONException
{
    DayImpression result;
    try
    {
        result = inventoryEstimateService.getInventoryDateEstimate(payload.getTargetingChannel());
    }
    catch (Exception e)
    {
        LOGGER.error(e.getMessage());
        return ResponseBuilder.buildError(e);
    }
    return ResponseBuilder.build(result, HTTP_OK_CODE);
}
 
Example #4
Source File: JdbcQueryWs.java    From poli with MIT License 6 votes vote down vote up
@RequestMapping(
        value = "/component/{id}",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<QueryResult> queryComponent(
        @PathVariable("id") long componentId,
        @RequestBody List<FilterParameter> filterParams,
        HttpServletRequest request
) {
    Component component = componentDao.findById(componentId);
    if (component.getJdbcDataSourceId() == 0) {
        return new ResponseEntity(QueryResult.ofError(Constants.ERROR_NO_DATA_SOURCE_FOUND), HttpStatus.OK);
    }

    boolean isAccessValid = isComponentAccessValid(component, request);
    if (isAccessValid) {
        String sql = component.getSqlQuery();
        DataSource dataSource = jdbcDataSourceService.getDataSource(component.getJdbcDataSourceId());
        User user = (User) request.getAttribute(Constants.HTTP_REQUEST_ATTR_USER);
        List<FilterParameter> newFilterParams = addUserAttributesToFilterParams(user.getUserAttributes(), filterParams);
        QueryResult queryResult = jdbcQueryService.queryByParams(dataSource, sql, newFilterParams, Constants.QUERY_RESULT_NOLIMIT);
        return new ResponseEntity(queryResult, HttpStatus.OK);
    }

    return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
 
Example #5
Source File: Siorg.java    From portal-de-servicos with MIT License 6 votes vote down vote up
@Cacheable("unidades-siorg")
public Unidade findUnidade(String unsafeId) {
    long orgaoId = orgaoUtils.obterId(unsafeId);

    String url = BASE_URL + orgaoId;

    ResponseEntity<Orgao> entity = restTemplate.getForEntity(url, Orgao.class);
    Orgao body = entity.getBody();

    if (body.getServico().getCodigoErro() > 0) {
        String msg = String.format("Erro ao acessar Siorg: %s", body.getServico().getMensagem());
        throw new RuntimeException(msg);
    }

    return body.getUnidade();
}
 
Example #6
Source File: AssetDetailController.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetches the details from a particular data source for a particular resource for given assetGroup
 * 
 * @param ag name of the asset group
 * @param resourceType type of the resource
 * @param resourceId id of the resource
 * 
 * @return details of ec2 resource
 */

@ApiOperation(httpMethod = "GET", value = "Get the details from a particular data source for a particular  resource")
@GetMapping(value = "v1/{assetGroup}/{resourceType}/{resourceId}/details")
public ResponseEntity<Object> getEc2ResourceDetail(@PathVariable(name = "assetGroup", required = true) String ag,
        @PathVariable(name = "resourceType", required = true) String resourceType,
        @PathVariable(name = "resourceId", required = true) String resourceId) {
    Map<String, Object> assetDetail;

    try {
        if ("ec2".equals(resourceType)) {
            assetDetail = assetService.getEc2ResourceDetail(ag, resourceId);
        } else {
            assetDetail = assetService.getGenericResourceDetail(ag, resourceType, resourceId);
        }
    } catch (Exception e) {
        LOGGER.error("Error in getEc2ResourceDetail ",e);
        assetDetail = new HashMap<>();
    }
    return ResponseUtils.buildSucessResponse(assetDetail);
}
 
Example #7
Source File: ConfluentSchemaRegistryClient.java    From schema-evolution-samples with Apache License 2.0 6 votes vote down vote up
@Override
public Integer register(Schema schema) {
	String path = String.format("/subjects/%s/versions",schema.getFullName());
	HttpHeaders headers = new HttpHeaders();
	headers.put("Accept", Arrays.asList("application/vnd.schemaregistry.v1+json","application/vnd.schemaregistry+json","application/json"));
	headers.add("Content-Type","application/json");
	Integer id = null;
	try {
		String payload = mapper.writeValueAsString(Collections.singletonMap("schema",schema.toString()));
		HttpEntity<String> request = new HttpEntity<>(payload,headers);
		ResponseEntity<Map> response = template.exchange(endpoint+path, HttpMethod.POST,request, Map.class);
		id = (Integer)response.getBody().get("id");
	}
	catch (JsonProcessingException e) {
		e.printStackTrace();
	}
	return id;
}
 
Example #8
Source File: PetControllerExceptionHandler.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * The handleMethodArgumentNotValid method creates a response with a list of messages that contains the fields with errors
 *
 * @param exception MethodArgumentNotValidException
 * @return 400 and a list of messages with invalid fields
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiMessageView> handleMethodArgumentNotValid(MethodArgumentNotValidException exception) {
    List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
    List<Object[]> messages = new ArrayList<>();

    for (FieldError fieldError : fieldErrors) {
        Object[] messageFields = new Object[3];
        messageFields[0] = fieldError.getField();
        messageFields[1] = fieldError.getRejectedValue();
        messageFields[2] = fieldError.getDefaultMessage();
        messages.add(messageFields);
    }

    List<ApiMessage> listApiMessage = messageService
        .createMessage("org.zowe.apiml.sampleservice.api.petMethodArgumentNotValid", messages)
        .stream()
        .map(Message::mapToApiMessage)
        .collect(Collectors.toList());

    return ResponseEntity
        .status(HttpStatus.BAD_REQUEST)
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .body(new ApiMessageView(listApiMessage));
}
 
Example #9
Source File: RestApiSecurityApplicationTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
public void testIdmRestApiIntegrationWithAuthentication() {
    String processDefinitionsUrl = "http://localhost:" + serverPort + "/idm-api/groups";

    HttpEntity<?> request = new HttpEntity<>(createHeaders("filiphr", "password"));
    ResponseEntity<DataResponse<GroupResponse>> response = restTemplate
        .exchange(processDefinitionsUrl, HttpMethod.GET, request, new ParameterizedTypeReference<DataResponse<GroupResponse>>() {
        });

    assertThat(response.getStatusCode())
        .as("Status code")
        .isEqualTo(HttpStatus.OK);
    DataResponse<GroupResponse> groups = response.getBody();
    assertThat(groups).isNotNull();
    assertThat(groups.getData())
        .extracting(GroupResponse::getId, GroupResponse::getType, GroupResponse::getName, GroupResponse::getUrl)
        .containsExactlyInAnyOrder(
            tuple("user", "security-role", "users", null),
            tuple("admin", "security-role", "admin", null)
        );
    assertThat(groups.getTotal()).isEqualTo(2);
}
 
Example #10
Source File: Log4JController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Sets the.
 *
 * @param name
 *        the name
 * @param level
 *        the level
 * @return the response entity
 */
@RequestMapping(value = "set/{name}/{level}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> set(@PathVariable("name")
final String name, @PathVariable("level")
final Level level) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    synchronized (ctx) {
        final Configuration config = ctx.getConfiguration();
        LoggerConfig loggerConfig = config.getLoggerConfig(name);
        if (name.equalsIgnoreCase(loggerConfig.getName())) {
            loggerConfig.setLevel(level);
        } else {
            LoggerConfig newloggerConfig = new LoggerConfig(name, level, true);
            config.addLogger(name, newloggerConfig);
        }
        ctx.updateLoggers();
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example #11
Source File: DynamicMockRestController.java    From microcks with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/{service}/{version}/{resource}", method = RequestMethod.GET)
public ResponseEntity<String> findResources(
      @PathVariable("service") String serviceName,
      @PathVariable("version") String version,
      @PathVariable("resource") String resource,
      @RequestParam(value = "page", required = false, defaultValue = "0") int page,
      @RequestParam(value = "size", required = false, defaultValue = "20") int size,
      @RequestParam(value="delay", required=false) Long delay,
      @RequestBody(required=false) String body
) {
   log.debug("Find resources '{}' for service '{}-{}'", resource, serviceName, version);
   long startTime = System.currentTimeMillis();

   serviceName = sanitizeServiceName(serviceName);

   MockContext mockContext = getMockContext(serviceName, version, "GET /" + resource);
   if (mockContext != null) {

      List<GenericResource> genericResources = null;
      if (body == null) {
         genericResources = genericResourceRepository.findByServiceId(mockContext.service.getId(), PageRequest.of(page, size));
      } else {
         genericResources = genericResourceRepository.findByServiceIdAndJSONQuery(mockContext.service.getId(), body);
      }

      // Transform and collect resources.
      List<String> resources = genericResources.stream()
            .map(genericResource -> transformToResourceJSON(genericResource))
            .collect(Collectors.toList());

      // Wait if specified before returning.
      waitForDelay(startTime, delay, mockContext);
      return new ResponseEntity<>(formatToJSONArray(resources), HttpStatus.OK);
   }
   // Return a 400 code : bad request.
   return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
 
Example #12
Source File: UniformHandler.java    From Milkomeda with MIT License 5 votes vote down vote up
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<Object> constraintViolationException(ConstraintViolationException e) {
    ConstraintViolation<?> constraintViolation = e.getConstraintViolations().iterator().next();
    String value = String.valueOf(constraintViolation.getInvalidValue());
    String message = WebContext.getRequest().getRequestURI() +
            " [" + constraintViolation.getPropertyPath() + "=" + value + "] " + constraintViolation.getMessage();
    log.warn("Hydrogen uniform valid response exception with msg: {} ", message);
    ResponseEntity<Object> responseEntity = handleExceptionResponse(e, HttpStatus.BAD_REQUEST.value(), message);
    return responseEntity == null ? ResponseEntity.status(HttpStatus.BAD_REQUEST.value()).body(null) : responseEntity;
}
 
Example #13
Source File: AuthorizationService.java    From full-teaching with Apache License 2.0 5 votes vote down vote up
public ResponseEntity<Object> checkBackendLogged(){
	if (!user.isLoggedUser()) {
		System.out.println("Not user logged");
		return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
	}
	return null; 
}
 
Example #14
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * PUT /fake/body-with-file-schema
 * For this test, the body for this request much reference a schema named &#x60;File&#x60;.
 *
 * @param body  (required)
 * @return Success (status code 200)
 */
@ApiOperation(value = "", nickname = "testBodyWithFileSchema", notes = "For this test, the body for this request much reference a schema named `File`.", tags={ "fake", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "Success") })
@RequestMapping(value = "/fake/body-with-file-schema",
    consumes = { "application/json" },
    method = RequestMethod.PUT)
default CompletableFuture<ResponseEntity<Void>> testBodyWithFileSchema(@ApiParam(value = "" ,required=true )  @Valid @RequestBody FileSchemaTestClass body) {
    return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED));

}
 
Example #15
Source File: RaceNormalResource.java    From gpmr with Apache License 2.0 5 votes vote down vote up
/**
 * GET  /race-normals-all : get all the raceNormals.
 *
 * @return the ResponseEntity with status 200 (OK) and the list of raceNormals in body
 * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
 */
@RequestMapping(value = "/race-normals-all",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<RaceNormal>> getAllRaceNormals()
    throws URISyntaxException {
    log.debug("REST request to get all RaceNormals");
    List<RaceNormal> normals = raceNormalRepository.findAll();
    return new ResponseEntity<>(normals, HttpStatus.OK);
}
 
Example #16
Source File: FooResource.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * DELETE  /foos/:id : delete the "id" foo.
 *
 * @param id the id of the foo to delete
 * @return the ResponseEntity with status 200 (OK)
 */
@RequestMapping(value = "/foos/{id}",
    method = RequestMethod.DELETE,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Void> deleteFoo(@PathVariable Long id) {
    log.debug("REST request to delete Foo : {}", id);
    fooRepository.delete(id);
    return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("foo", id.toString())).build();
}
 
Example #17
Source File: FileRestController.java    From nimrod with MIT License 5 votes vote down vote up
/**
 * 指定文件 id,获取文件
 *
 * @param id 文件 id
 * @return ResponseEntity<FileEntity>
 */
@OperationLog(value = "指定文件 id,获取文件", type = OperationLogType.API)
@PreAuthorize("hasRole('" + SYSTEM_ADMIN + "') OR hasAuthority('" + FILE + "/ONE')")
@GetMapping(value = "/one/{id}")
public ResponseEntity<FileEntity> getOne(@PathVariable Long id) {
    return new ResponseEntity<>(fileService.getOne(id), HttpStatus.OK);
}
 
Example #18
Source File: MgmtTargetFilterQueryResource.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ResponseEntity<MgmtTargetFilterQuery> getFilter(@PathVariable("filterId") final Long filterId) {
    final TargetFilterQuery findTarget = findFilterWithExceptionIfNotFound(filterId);
    // to single response include poll status
    final MgmtTargetFilterQuery response = MgmtTargetFilterQueryMapper.toResponse(findTarget);
    MgmtTargetFilterQueryMapper.addLinks(response);

    return ResponseEntity.ok(response);
}
 
Example #19
Source File: UserController.java    From pivotal-bank-demo with Apache License 2.0 5 votes vote down vote up
/**
 * REST call to save the user provided in the request body.
 * 
 * @param userRequest
 *            The user to save.
 * @param builder
 * @return
 */
@RequestMapping(value = "/users", method = RequestMethod.POST)
public ResponseEntity<String> save(@RequestBody User userRequest, UriComponentsBuilder builder) {

	logger.debug("UserController.save: userId=" + userRequest.getUserid());

	Integer accountProfileId = this.service.saveUser(userRequest);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setLocation(builder.path("/users/{id}").buildAndExpand(accountProfileId).toUri());
	return new ResponseEntity<String>(responseHeaders, HttpStatus.CREATED);
}
 
Example #20
Source File: UserServiceImpl.java    From agile-service-old with Apache License 2.0 5 votes vote down vote up
@Override
public List<UserVO> queryUsersByNameAndProjectId(Long projectId, String name) {
    ResponseEntity<PageInfo<UserVO>> userList = iamFeignClient.list(projectId, name);
    if (userList != null) {
        return userList.getBody().getList();
    } else {
        return new ArrayList<>();
    }
}
 
Example #21
Source File: ItemController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@PreAuthorize(value = "@permissionValidator.hasModifyNamespacePermission(#appId, #namespaceName, #env)")
@PostMapping(value = "/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/syntax-check", consumes = {
    "application/json"})
public ResponseEntity<Void> syntaxCheckText(@PathVariable String appId, @PathVariable String env,
    @PathVariable String clusterName, @PathVariable String namespaceName, @RequestBody NamespaceTextModel model) {

  doSyntaxCheck(model);

  return ResponseEntity.ok().build();
}
 
Example #22
Source File: ComposerService.java    From cubeai with Apache License 2.0 5 votes vote down vote up
private ResponseEntity<String> apiGateway(String url, String requestBody, MultiValueMap<String,String> requestHeader) {
    logger.debug("Start API forwarding");

    try {
        HttpEntity<String> httpEntity = new HttpEntity<>(requestBody, requestHeader);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); // 直接使用RestTemplate的POST方法时,字符串默认使用“ISO-8859-1”编码,需要转换
        ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
        return ResponseEntity.status(response.getStatusCodeValue()).body(response.getBody());
    } catch(HttpClientErrorException e) {
        return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
    }
}
 
Example #23
Source File: BoardColumnController.java    From agile-service-old with Apache License 2.0 5 votes vote down vote up
@Permission(type = ResourceType.PROJECT, roles = {InitRoleCode.PROJECT_OWNER})
@ApiOperation("根据id更新最大最小值")
@PostMapping(value = "/{columnId}/column_contraint")
public ResponseEntity<BoardColumnVO> updateColumnContraint(@ApiParam(value = "项目id", required = true)
                                                            @PathVariable(name = "project_id") Long projectId,
                                                           @ApiParam(value = "column id", required = true)
                                                            @PathVariable Long columnId,
                                                           @ApiParam(value = "ColumnWithMaxMinNumVO", required = true)
                                                            @RequestBody ColumnWithMaxMinNumVO columnWithMaxMinNumVO) {
    return Optional.ofNullable(boardColumnService.updateColumnContraint(projectId, columnId, columnWithMaxMinNumVO))
            .map(result -> new ResponseEntity<>(result, HttpStatus.CREATED))
            .orElseThrow(() -> new CommonException("error.MaxAndMinNum.update"));
}
 
Example #24
Source File: GlobalExceptionHandler.java    From EosProxyServer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@ExceptionHandler(value = ExceptionsChain.class)
public ResponseEntity<MessageResult> handleServiceException(ExceptionsChain exception) {
    Integer code = exception.getErrorCode().getMsg_id();
    String msg = ErrorCodeEnumChain.getMsgById(code);
    String data = exception.getMessage();
    log.info("X--->{code:" + code + ",msg:" + msg + ",what:" + data + "}");
    return new ResponseEntity(new MessageResult(msg, code, data), HttpStatus.BAD_REQUEST);
}
 
Example #25
Source File: SolaceController.java    From solace-samples-cloudfoundry-java with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/subscription/{subscriptionName}", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteSubscription(@PathVariable("subscriptionName") String subscriptionTopic) {
    final Topic topic = JCSMPFactory.onlyInstance().createTopic(subscriptionTopic);
    logger.info("Deleting a subscription to topic: " + subscriptionTopic);

    try {
        boolean waitForConfirm = true;
        session.removeSubscription(topic, waitForConfirm);
    } catch (JCSMPException e) {
        logger.error("Service Creation failed.", e);
        return new ResponseEntity<>("{'description': '" + e.getMessage() + "'}", HttpStatus.BAD_REQUEST);
    }
    logger.info("Finished Deleting a subscription to topic: " + subscriptionTopic);
    return new ResponseEntity<>("{}", HttpStatus.OK);
}
 
Example #26
Source File: RoomServiceSMOImpl.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseEntity<String> exitRoom(IPageData pd) {

    validateExitRoom(pd);
    //校验员工是否有权限操作
    super.checkUserHasPrivilege(pd, restTemplate, PrivilegeCodeConstant.PRIVILEGE_OWNER_ROOM);

    JSONObject paramIn = JSONObject.parseObject(pd.getReqData());
    String communityId = paramIn.getString("communityId");
    ResponseEntity responseEntity = super.getStoreInfo(pd, restTemplate);
    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        return responseEntity;
    }
    Assert.jsonObjectHaveKey(responseEntity.getBody().toString(), "storeId", "根据用户ID查询商户ID失败,未包含storeId节点");
    Assert.jsonObjectHaveKey(responseEntity.getBody().toString(), "storeTypeCd", "根据用户ID查询商户类型失败,未包含storeTypeCd节点");

    String storeId = JSONObject.parseObject(responseEntity.getBody().toString()).getString("storeId");
    String storeTypeCd = JSONObject.parseObject(responseEntity.getBody().toString()).getString("storeTypeCd");
    //数据校验是否 商户是否入驻该小区
    super.checkStoreEnterCommunity(pd, storeId, storeTypeCd, communityId, restTemplate);
    paramIn.put("userId", pd.getUserId());
    paramIn.put("storeId", storeId);
    responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(),
            ServiceConstant.SERVICE_API_URL + "/api/room.exitRoom",
            HttpMethod.POST);

    return responseEntity;

}
 
Example #27
Source File: FileBrowserController.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RestAccessControl(permission = Permission.SUPERUSER)
@RequestMapping(value = "/file", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<RestResponse<Map, Map>> getFile(@RequestParam(value = "currentPath", required = false, defaultValue = "") String currentPath,
        @RequestParam(value = "protectedFolder", required = false, defaultValue = "false") Boolean protectedFolder) {
    logger.debug("required file {} - protected {}", currentPath, protectedFolder);
    byte[] base64 = this.getFileBrowserService().getFileStream(currentPath, protectedFolder);
    Map<String, Object> result = new HashMap<>();
    result.put("protectedFolder", protectedFolder);
    result.put("path", currentPath);
    result.put("filename", this.getFilename(currentPath));
    result.put("base64", base64);
    Map<String, Object> metadata = new HashMap<>();
    metadata.put("prevPath", this.getPrevFolderName(currentPath));
    return new ResponseEntity<>(new RestResponse<>(result, metadata), HttpStatus.OK);
}
 
Example #28
Source File: GitHub.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
/**
 * Apply a {@link Predicate callback} with GitHub paging starting at {@code endpointUri}. The given
 * {@link Predicate#test(Object)} outcome controls whether paging continues by returning {@literal true} or stops.
 *
 * @param endpointUri
 * @param method
 * @param parameters
 * @param entity
 * @param type
 * @param callbackContinue
 * @param <T>
 */
private <T> void doWithPaging(String endpointUri, HttpMethod method, Map<String, Object> parameters,
		HttpEntity<?> entity, ParameterizedTypeReference<T> type, Predicate<T> callbackContinue) {

	ResponseEntity<T> exchange = operations.exchange(endpointUri, method, entity, type, parameters);

	Pattern pattern = Pattern.compile("<([^ ]*)>; rel=\"(\\w+)\"");

	while (true) {

		if (!callbackContinue.test(exchange.getBody())) {
			return;
		}

		HttpHeaders responseHeaders = exchange.getHeaders();
		List<String> links = responseHeaders.getValuesAsList("Link");

		if (links.isEmpty()) {
			return;
		}

		String nextLink = null;
		for (String link : links) {

			Matcher matcher = pattern.matcher(link);
			if (matcher.find()) {
				if (matcher.group(2).equals("next")) {
					nextLink = matcher.group(1);
					break;
				}
			}
		}

		if (nextLink == null) {
			return;
		}

		exchange = operations.exchange(nextLink, method, entity, type, parameters);
	}
}
 
Example #29
Source File: ApplicationServletPathTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Test
public void adminLoads() {
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

	@SuppressWarnings("rawtypes")
	ResponseEntity<Map> entity = new TestRestTemplate().exchange(
			"http://localhost:" + this.port + "/servlet" + BASE_PATH + "/env",
			HttpMethod.GET, new HttpEntity<>("parameters", headers), Map.class);
	assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
 
Example #30
Source File: CustomerController.java    From POC with Apache License 2.0 5 votes vote down vote up
/**
 * deletes All Users.
 * @return a {@link org.springframework.http.ResponseEntity} object.
 */
@DeleteMapping
public ResponseEntity<Customer> deleteAllUsers() {
	log.info("Deleting All Users");

	this.customerService.deleteAllCustomers();
	return ResponseEntity.noContent().build();
}