org.springframework.http.MediaType#APPLICATION_JSON_VALUE源码实例Demo

下面列出了org.springframework.http.MediaType#APPLICATION_JSON_VALUE 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * Web service endpoint to fetch the Quote of the day.
 * 
 * If found, the Quote is returned as JSON with HTTP status 200.
 * 
 * If not found, the service returns an empty response body with HTTP status
 * 404.
 * 
 * @return A ResponseEntity containing a single Quote object, if found, and
 *         a HTTP status code as described in the method comment.
 */
@RequestMapping(
        value = "/api/quotes/daily",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Quote> getQuoteOfTheDay() {
    logger.info("> getQuoteOfTheDay");

    Quote quote = quoteService.getDaily(QuoteService.CATEGORY_INSPIRATIONAL);

    if (quote == null) {
        return new ResponseEntity<Quote>(HttpStatus.NOT_FOUND);
    }
    logger.info("< getQuoteOfTheDay");
    return new ResponseEntity<Quote>(quote, HttpStatus.OK);
}
 
源代码2 项目: NFVO   文件: RestUsers.java
/**
 * Updates the User
 *
 * @param new_user : The User to be updated
 * @return User The User updated
 */
@ApiOperation(
    value = "Update a User",
    notes =
        "Updates a user based on the username specified in the url and the updated user body in the request")
@RequestMapping(
    value = "{username}",
    method = RequestMethod.PUT,
    consumes = MediaType.APPLICATION_JSON_VALUE,
    produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.ACCEPTED)
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public User update(@RequestBody @Valid User new_user)
    throws NotAllowedException, BadRequestException, NotFoundException {
  return userManagement.update(new_user);
}
 
源代码3 项目: springdoc-openapi   文件: HelloController.java
@Operation(description = "List all persons")
@ApiResponse(responseCode = "200", description = "", content = @Content(array = @ArraySchema(schema = @Schema(implementation = PersonDTO.class))))
@GetMapping(path = "/listTwo", consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public List<PersonDTO> listTwo() {
	PersonDTO person = new PersonDTO();
	person.setFirstName("Nass");
	return Collections.singletonList(person);
}
 
源代码4 项目: jhipster-ribbon-hystrix   文件: UserResource.java
/**
 * PUT  /users : Updates an existing User.
 *
 * @param managedUserDTO the user to update
 * @return the ResponseEntity with status 200 (OK) and with body the updated user,
 * or with status 400 (Bad Request) if the login or email is already in use,
 * or with status 500 (Internal Server Error) if the user couldnt be updated
 */
@RequestMapping(value = "/users",
    method = RequestMethod.PUT,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity<ManagedUserDTO> updateUser(@RequestBody ManagedUserDTO managedUserDTO) {
    log.debug("REST request to update User : {}", managedUserDTO);
    Optional<User> existingUser = userRepository.findOneByEmail(managedUserDTO.getEmail());
    if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserDTO.getId()))) {
        return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("userManagement", "emailexists", "E-mail already in use")).body(null);
    }
    existingUser = userRepository.findOneByLogin(managedUserDTO.getLogin());
    if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserDTO.getId()))) {
        return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("userManagement", "userexists", "Login already in use")).body(null);
    }
    return userRepository
        .findOneById(managedUserDTO.getId())
        .map(user -> {
            user.setLogin(managedUserDTO.getLogin());
            user.setFirstName(managedUserDTO.getFirstName());
            user.setLastName(managedUserDTO.getLastName());
            user.setEmail(managedUserDTO.getEmail());
            user.setActivated(managedUserDTO.isActivated());
            user.setLangKey(managedUserDTO.getLangKey());
            Set<Authority> authorities = user.getAuthorities();
            authorities.clear();
            managedUserDTO.getAuthorities().stream().forEach(
                authority -> authorities.add(authorityRepository.findOne(authority))
            );
            return ResponseEntity.ok()
                .headers(HeaderUtil.createAlert("userManagement.updated", managedUserDTO.getLogin()))
                .body(new ManagedUserDTO(userRepository
                    .findOne(managedUserDTO.getId())));
        })
        .orElseGet(() -> new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));

}
 
源代码5 项目: spring-cloud-openfeign   文件: InvoiceResource.java
@RequestMapping(value = "invoicesPaged", method = RequestMethod.GET,
		produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Page<Invoice>> getInvoicesPaged(
		org.springframework.data.domain.Pageable pageable) {
	Page<Invoice> page = new PageImpl<>(createInvoiceList(pageable.getPageSize()),
			pageable, 100);
	return ResponseEntity.ok(page);
}
 
源代码6 项目: entando-core   文件: WidgetController.java
@RestAccessControl(permission = Permission.MANAGE_PAGES)
@RequestMapping(value = "/widgets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<PagedRestResponse<WidgetDto>> getWidgets(RestListRequest requestList) {
    logger.trace("get widget list {}", requestList);
    this.getWidgetValidator().validateRestListRequest(requestList, WidgetDto.class);
    PagedMetadata<WidgetDto> result = this.widgetService.getWidgets(requestList);
    this.getWidgetValidator().validateRestListResult(requestList, result);
    return new ResponseEntity<>(new PagedRestResponse<>(result), HttpStatus.OK);
}
 
@Override
@PostMapping(value = "/{applicationname}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public JobConfiguration add(@RequestBody final JobConfiguration jobConfiguration, @PathVariable(name = "applicationname") final String applicationName) {
    this.validateJobConfigurationBody(jobConfiguration);
    jobConfiguration.validateForSave();
    return this.jobConfigurationRepository.add(jobConfiguration, applicationName);
}
 
源代码8 项目: dhis2-core   文件: DataSetController.java
@RequestMapping( value = "/{uid}/form", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE )
@ApiVersion( value = DhisApiVersion.ALL )
@ResponseStatus( HttpStatus.NO_CONTENT )
public void updateCustomDataEntryFormJson( @PathVariable( "uid" ) String uid, HttpServletRequest request ) throws WebMessageException
{
    DataSet dataSet = dataSetService.getDataSet( uid );

    if ( dataSet == null )
    {
        throw new WebMessageException( WebMessageUtils.notFound( "DataSet not found for uid: " + uid ) );
    }

    DataEntryForm form = dataSet.getDataEntryForm();
    DataEntryForm newForm;

    try
    {
        newForm = renderService.fromJson( request.getInputStream(), DataEntryForm.class );
    }
    catch ( IOException e )
    {
        throw new WebMessageException( WebMessageUtils.badRequest( "Failed to parse request", e.getMessage() ) );
    }

    if ( form == null )
    {
        if ( !newForm.hasForm() )
        {
            throw new WebMessageException( WebMessageUtils.badRequest( "Missing required parameter 'htmlCode'" ) );
        }

        newForm.setName( dataSet.getName() );
        dataEntryFormService.addDataEntryForm( newForm );
        dataSet.setDataEntryForm( newForm );
    }
    else
    {
        if ( newForm.getHtmlCode() != null )
        {
            form.setHtmlCode( dataEntryFormService.prepareDataEntryFormForSave( newForm.getHtmlCode() ) );
        }

        if ( newForm.getStyle() != null )
        {
            form.setStyle( newForm.getStyle() );
        }

        dataEntryFormService.updateDataEntryForm( form );
    }

    dataSet.increaseVersion();
    dataSetService.updateDataSet( dataSet );
}
 
源代码9 项目: kafdrop   文件: MessageController.java
/**
 * Return a JSON list of all partition offset info for the given topic. If specific partition
 * and offset parameters are given, then this returns actual kafka messages from that partition
 * (if the offsets are valid; if invalid offsets are passed then the message list is empty).
 * @param topicName Name of topic.
 * @return Offset or message data.
 */
@ApiOperation(value = "getPartitionOrMessages", notes = "Get offset or message data for a topic. Without query params returns all partitions with offset data. With query params, returns actual messages (if valid offsets are provided).")
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "Success", response = List.class),
    @ApiResponse(code = 404, message = "Invalid topic name")
})
@RequestMapping(method = RequestMethod.GET, value = "/topic/{name:.+}/messages", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
List<Object> getPartitionOrMessages(
    @PathVariable("name") String topicName,
    @RequestParam(name = "partition", required = false) Integer partition,
    @RequestParam(name = "offset", required = false) Long offset,
    @RequestParam(name = "count", required = false) Integer count,
    @RequestParam(name = "format", required = false) String format,
    @RequestParam(name = "keyFormat", required = false) String keyFormat,
    @RequestParam(name = "descFile", required = false) String descFile,
    @RequestParam(name = "msgTypeName", required = false) String msgTypeName
) {
  if (partition == null || offset == null || count == null) {
    final TopicVO topic = kafkaMonitor.getTopic(topicName)
        .orElseThrow(() -> new TopicNotFoundException(topicName));

    List<Object> partitionList = new ArrayList<>();
    topic.getPartitions().forEach(vo -> partitionList.add(new PartitionOffsetInfo(vo.getId(), vo.getFirstOffset(), vo.getSize())));

    return partitionList;
  } else {

    final var deserializers = new Deserializers(
            getDeserializer(topicName, getSelectedMessageFormat(keyFormat), descFile, msgTypeName),
            getDeserializer(topicName, getSelectedMessageFormat(format), descFile, msgTypeName));

    List<Object> messages = new ArrayList<>();
    List<MessageVO> vos = messageInspector.getMessages(
        topicName,
        partition,
        offset,
        count,
        deserializers);

    if (vos != null) {
      messages.addAll(vos);
    }

    return messages;
  }
}
 
源代码10 项目: dhis2-core   文件: DataAnalysisController.java
@RequestMapping( value = "/validationRules", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE )
@ResponseStatus( HttpStatus.OK )
public @ResponseBody
List<ValidationResultView> performValidationRulesAnalysis(
    @RequestBody ValidationRulesAnalysisParams validationRulesAnalysisParams, HttpSession session )
    throws WebMessageException
{
    I18nFormat format = i18nManager.getI18nFormat();

    ValidationRuleGroup group = null;
    if ( validationRulesAnalysisParams.getVrg() != null )
    {
        group = validationRuleService
            .getValidationRuleGroup( validationRulesAnalysisParams.getVrg() );
    }

    OrganisationUnit organisationUnit = organisationUnitService
        .getOrganisationUnit( validationRulesAnalysisParams.getOu() );
    if ( organisationUnit == null )
    {
        throw new WebMessageException( WebMessageUtils.badRequest( "No organisation unit defined" ) );
    }

    ValidationAnalysisParams params = validationService.newParamsBuilder( group, organisationUnit,
        format.parseDate( validationRulesAnalysisParams.getStartDate() ),
        format.parseDate( validationRulesAnalysisParams.getEndDate() ) )
        .withIncludeOrgUnitDescendants( true )
        .withPersistResults( validationRulesAnalysisParams.isPersist() )
        .withSendNotifications( validationRulesAnalysisParams.isNotification() )
        .withMaxResults( ValidationService.MAX_INTERACTIVE_ALERTS )
        .build();

    List<ValidationResult> validationResults = new ArrayList<>( validationService.validationAnalysis( params ) );

    validationResults.sort( new ValidationResultComparator() );

    session.setAttribute( KEY_VALIDATION_RESULT, validationResults );
    session.setAttribute( KEY_ORG_UNIT, organisationUnit );

    return validationResultsListToResponse( validationResults );
}
 
@GetMapping(value="/selectDept/{id}", produces= MediaType.APPLICATION_JSON_VALUE)
public Department blockDepartment(@PathVariable("id") Integer id) {
	return departmentServiceImpl.findDeptByid(id);
}
 
源代码12 项目: metacat   文件: MetacatController.java
/**
 * Update table.
 *
 * @param catalogName  catalog name
 * @param databaseName database name
 * @param tableName    table name
 * @param table        table
 * @return table
 */
@RequestMapping(
    method = RequestMethod.PUT,
    path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}",
    consumes = MediaType.APPLICATION_JSON_VALUE
)
@ApiOperation(
    position = 3,
    value = "Update table",
    notes = "Updates the given table"
)
@ApiResponses(
    {
        @ApiResponse(
            code = HttpURLConnection.HTTP_OK,
            message = "Table successfully updated"
        ),
        @ApiResponse(
            code = HttpURLConnection.HTTP_NOT_FOUND,
            message = "The requested catalog or database or table cannot be located"
        )
    }
)
@Override
public TableDto updateTable(
    @ApiParam(value = "The name of the catalog", required = true)
    @PathVariable("catalog-name") final String catalogName,
    @ApiParam(value = "The name of the database", required = true)
    @PathVariable("database-name") final String databaseName,
    @ApiParam(value = "The name of the table", required = true)
    @PathVariable("table-name") final String tableName,
    @ApiParam(value = "The table information", required = true)
    @RequestBody final TableDto table
) {
    final QualifiedName name = this.requestWrapper.qualifyName(
        () -> QualifiedName.ofTable(catalogName, databaseName, tableName)
    );
    return this.requestWrapper.processRequest(
        name,
        "updateTable",
        () -> {
            Preconditions.checkArgument(table.getName() != null
                    && tableName.equalsIgnoreCase(table.getName().getTableName()
                ),
                "Table name does not match the name in the table"
            );
            return this.tableService.updateAndReturn(name, table);
        }
    );
}
 
源代码13 项目: yes-cart   文件: PromotionController.java
/**
 * Interface: GET /promotions/{id}
 * <p>
 * <p>
 * Display promotion details.
 * <p>
 * <p>
 * <h3>Headers for operation</h3><p>
 * <table border="1">
 *     <tr><td>Accept</td><td>application/json</td></tr>
 *     <tr><td>yc</td><td>token uuid (optional)</td></tr>
 * </table>
 * <p>
 * <p>
 * <h3>Parameters for operation</h3><p>
 * <table border="1">
 *     <tr><td>ids</td><td>Promotion codes separated by comma (',')</td></tr>
 * </table>
 * <p>
 * <p>
 * <h3>Output</h3><p>
 * <table border="1">
 *     <tr><td>JSON example</td><td>
 * <pre><code>
 * 	[
 * 	     {
 * 	     	     "action" : "P",
 *	      	     "originalCode" : "SHOP10EURITEMQTY20P",
 *	      	     "activeTo" : null,
 *	      	     "code" : "SHOP10EURITEMQTY20P",
 *	      	     "couponCode" : null,
 *	      	     "context" : "20",
 *	      	     "type" : "I",
 *	      	     "description" : {},
 *	      	     "name" : {
 *	     	      	     "uk" : "Знижка 20% при покупці більше 20 одиниц",
 *	     	      	     "ru" : "Скидка 20% при покупке свыше 20 единиц",
 *	     	      	     "en" : "20% off when buying 20 or more items"
 *	      	     },
 *	      	     "activeFrom" : null
 * 	     }
 * ]
 * </code></pre>
 *     </td></tr>
 * </table>
 *
 * @param promotions codes comma separated list
 * @param request request
 * @param response response
 *
 * @return promotions
 */
@ApiOperation(value = "Display promotion details.")
@RequestMapping(
        value = "/promotions/{codes}",
        method = RequestMethod.GET,
        produces = { MediaType.APPLICATION_JSON_VALUE }
)
public @ResponseBody
List<PromotionRO> viewProducts(final @ApiParam(value = "Request token") @RequestHeader(value = "yc", required = false) String requestToken,
                               final @ApiParam(value = "CSV of promotion codes") @PathVariable(value = "codes") String promotions,
                               final HttpServletRequest request,
                               final HttpServletResponse response) {

    cartMixin.throwSecurityExceptionIfRequireLoggedIn();
    cartMixin.persistShoppingCart(request, response);
    return viewPromotionsInternal(promotions);

}
 
源代码14 项目: carts   文件: CartsController.java
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/{customerId}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public Cart get(@PathVariable String customerId) {
    return new CartResource(cartDAO, customerId).value().get();
}
 
源代码15 项目: telekom-workflow-engine   文件: RestController.java
/**
 * Notifies all waiting signal work items of the given workflow instance and the given signal name.
 * 
 * Technically, sets the work item's result value and updates the status to EXECUTED.
 * 
 * <pre>
 * Request:  POST /workflowInstance/1/signal/invoice {argument: {refNum:3, invoiceAmount: "10 Euro"}}
 * Response: NO_CONTENT
 * </pre>
 */
@RequestMapping(method = RequestMethod.POST, value = "/workflowInstance/{woinRefNum}/signal/{signal}",
        produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_XML_VALUE})
public ResponseEntity<Void> sendSignal( @PathVariable long woinRefNum, @PathVariable String signal, @RequestBody String argument ){
    facade.sendSignalToWorkflowInstance( woinRefNum, signal, JsonUtil.deserialize( argument ) );
    return new ResponseEntity<>( HttpStatus.NO_CONTENT );
}
 
@PostMapping(path = "/fluxAddEmp", consumes = MediaType.APPLICATION_JSON_VALUE) 
public void addMonoEmp(@RequestBody Mono<Employee> employee){
	
}
 
源代码17 项目: xmfcn-spring-cloud   文件: PhotoService.java
/**
 * getWxPhoto:(查询微信照片单个实体数据)
 * @Author rufei.cn
 * @return
 */
@RequestMapping(value = "getWxPhoto", consumes = MediaType.APPLICATION_JSON_VALUE)
public Photo getWxPhoto(@RequestBody Photo photo);
 
源代码18 项目: data-prep   文件: MockDataSetProvider.java
/**
 * This request mapping must follow the dataset request mapping
 *
 * @param lookupId
 * @return
 * @throws IOException
 */
@RequestMapping(value = "/datasets/{id}/content", method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
public String getSampleRemoteFile(@PathVariable(value = "id") String lookupId) throws IOException {
    return IOUtils.toString(this.getClass().getResourceAsStream(lookupId + ".json"), UTF_8);
}
 
源代码19 项目: hawkbit   文件: MgmtDistributionSetTypeRestApi.java
/**
 * Handles the POST request for adding an optional software module type to a
 * distribution set type.
 *
 * @param distributionSetTypeId
 *            of the DistributionSetType.
 * @param smtId
 *            of the SoftwareModuleType to add
 *
 * @return OK if the request was successful
 */
@PostMapping(value = "/{distributionSetTypeId}/"
        + MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_OPTIONAL_MODULE_TYPES, consumes = { MediaTypes.HAL_JSON_VALUE,
                MediaType.APPLICATION_JSON_VALUE })
ResponseEntity<Void> addOptionalModule(@PathVariable("distributionSetTypeId") Long distributionSetTypeId,
        MgmtId smtId);
 
源代码20 项目: xmfcn-spring-cloud   文件: UserPrizeService.java
/**
 * getUserPrize:(查询奖品信息单个实体数据)
 * @Author rufei.cn
 * @return
 */
@RequestMapping(value = "getUserPrize", consumes = MediaType.APPLICATION_JSON_VALUE)
public UserPrize getUserPrize(@RequestBody UserPrize userPrize);