Java Code Examples for org.springframework.http.MediaType#APPLICATION_JSON_VALUE

The following examples show how to use org.springframework.http.MediaType#APPLICATION_JSON_VALUE . 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: RestUsers.java    From NFVO with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 2
Source File: QuoteController.java    From spring-boot-fundamentals with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 3
Source File: WidgetController.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example 4
Source File: JobConfigurationRepositoryController.java    From spring-batch-lightmin with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 5
Source File: HelloController.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 6
Source File: InvoiceResource.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 7
Source File: UserResource.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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));

}
 
Example 8
Source File: MessageController.java    From kafdrop with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
  }
}
 
Example 9
Source File: DataAnalysisController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@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 );
}
 
Example 10
Source File: DeptBlockingController.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
@GetMapping(value="/selectDept/{id}", produces= MediaType.APPLICATION_JSON_VALUE)
public Department blockDepartment(@PathVariable("id") Integer id) {
	return departmentServiceImpl.findDeptByid(id);
}
 
Example 11
Source File: MetacatController.java    From metacat with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
        }
    );
}
 
Example 12
Source File: DataSetController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@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 );
}
 
Example 13
Source File: PromotionController.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
/**
 * 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);

}
 
Example 14
Source File: CartsController.java    From carts with Apache License 2.0 4 votes vote down vote up
@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();
}
 
Example 15
Source File: RestController.java    From telekom-workflow-engine with MIT License 3 votes vote down vote up
/**
 * 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 );
}
 
Example 16
Source File: PhotoService.java    From xmfcn-spring-cloud with Apache License 2.0 2 votes vote down vote up
/**
 * getWxPhoto:(查询微信照片单个实体数据)
 * @Author rufei.cn
 * @return
 */
@RequestMapping(value = "getWxPhoto", consumes = MediaType.APPLICATION_JSON_VALUE)
public Photo getWxPhoto(@RequestBody Photo photo);
 
Example 17
Source File: RestServiceController.java    From Spring-5.0-Cookbook with MIT License 2 votes vote down vote up
@PostMapping(path = "/fluxAddEmp", consumes = MediaType.APPLICATION_JSON_VALUE) 
public void addMonoEmp(@RequestBody Mono<Employee> employee){
	
}
 
Example 18
Source File: MockDataSetProvider.java    From data-prep with Apache License 2.0 2 votes vote down vote up
/**
 * 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);
}
 
Example 19
Source File: MgmtDistributionSetTypeRestApi.java    From hawkbit with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * 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);
 
Example 20
Source File: UserPrizeService.java    From xmfcn-spring-cloud with Apache License 2.0 2 votes vote down vote up
/**
 * getUserPrize:(查询奖品信息单个实体数据)
 * @Author rufei.cn
 * @return
 */
@RequestMapping(value = "getUserPrize", consumes = MediaType.APPLICATION_JSON_VALUE)
public UserPrize getUserPrize(@RequestBody UserPrize userPrize);