/** * Pulls the remote IP from the current HttpServletRequest, or grabs the value * for the specified alternative attribute (say, for proxied requests). Falls * back to providing the "normal" remote address if no value can be retrieved * from the specified alternative header value. * @param context the context * @return the remote ip */ private String getRemoteIp(@NotNull final RequestContext context) { final HttpServletRequest request = WebUtils.getHttpServletRequest(context); String userAddress = request.getRemoteAddr(); logger.debug("Remote Address = {}", userAddress); if (StringUtils.isNotBlank(this.alternativeRemoteHostAttribute)) { userAddress = request.getHeader(this.alternativeRemoteHostAttribute); logger.debug("Header Attribute [{}] = [{}]", this.alternativeRemoteHostAttribute, userAddress); if (StringUtils.isBlank(userAddress)) { userAddress = request.getRemoteAddr(); logger.warn("No value could be retrieved from the header [{}]. Falling back to [{}].", this.alternativeRemoteHostAttribute, userAddress); } } return userAddress; }
@GET @Path("/{job-id}/stderr") @ApiOperation( value = "Get the job's standard error", notes = "Get the job's standard error, if available. A job that has not yet starrted will not have a standard error and, " + "therefore, this method will return a 404. There is no guarantee that all running/finished jobs will have standard " + "error data. This is because administrative and cleanup routines may dequeue a job's output in order to save space on " + "the server.") @Produces(DEFAULT_BINARY_MIME_TYPE) @PermitAll public Response fetchJobStderrById( @Context SecurityContext context, @ApiParam(value = "ID of the job to get stderr for") @PathParam("job-id") @NotNull JobId jobId) { if (jobId == null) throw new WebApplicationException("Job ID cannot be null", 400); return generateBinaryDataResponse(jobId, jobDAO.getStderr(jobId)); }
@GET @Path("/uuid/{id}") @Produces(MediaType.APPLICATION_JSON) @ApiOperation( value = "Retrieve a Fact by its UUID.", notes = "This operation returns a Fact identified by its UUID. The result includes the Objects directly " + "linked to the requested Fact. The request will be rejected with a 403 if a user does not have " + "access to the requested Fact.\n\n" + "If the accessMode is 'Public' the Fact will be available to everyone. If the accessMode is " + "'Explicit' only users in the Fact's ACL will have access to the Fact. If the accessMode is " + "'RoleBased' (the default mode) a user must be either in the Fact's ACL or have general role-based " + "access to the Organization owning the Fact. A user who created a Fact will always have access to it.", response = Fact.class ) @ApiResponses({ @ApiResponse(code = 401, message = "User could not be authenticated."), @ApiResponse(code = 403, message = "User is not allowed to perform this operation."), @ApiResponse(code = 404, message = "Requested Fact does not exist."), @ApiResponse(code = 412, message = "Any parameter has an invalid format.") }) public Response getFactById( @PathParam("id") @ApiParam(value = "UUID of the requested Fact.") @NotNull @Valid UUID id ) throws AccessDeniedException, AuthenticationFailedException, InvalidArgumentException, ObjectNotFoundException { return buildResponse(service.getFact(getHeader(), new GetFactByIdRequest().setId(id))); }
@NotNull @Override public final LastOperation getLastOperation(final LastOperationQuery lastOperationQuery) throws ServiceBrokerException { Objects.requireNonNull(lastOperationQuery, () -> "lastOperationQuery must not be null"); LastOperation returnValue = null; final String serviceId = lastOperationQuery.getServiceId(); if (serviceId != null) { ServiceBroker serviceBroker = null; try { this.serviceBrokerAssociationLock.readLock().lock(); serviceBroker = this.getServiceBrokerForServiceId(serviceId); } finally { this.serviceBrokerAssociationLock.readLock().unlock(); } if (serviceBroker != null) { returnValue = serviceBroker.getLastOperation(lastOperationQuery); } } if (returnValue == null) { throw new InvalidServiceBrokerQueryException(lastOperationQuery); } return returnValue; }
/** * {@inheritDoc} */ @Override public void updateReview( @NotNull @Valid final Review review, @Min(1) final Long reviewId, @NotNull final MovieEntity movie ) throws ResourceConflictException { log.info("Called with review {}, reviewId {}, movie {}", review, reviewId, movie); this.existsReview(movie.getReviews() .stream() .filter(r -> r.getStatus() == DataStatus.ACCEPTED) .collect(Collectors.toList()), review); final MovieReviewEntity movieReview = this.entityManager.find(MovieReviewEntity.class, reviewId); movieReview.setTitle(review.getTitle()); movieReview.setReview(review.getReview()); }
@Test public void jsr349SimpleInvalid() { try { validationInInterceptor.handleValidation(MESSAGE, INSTANCE, fromName("jsr349Simple"), Arrays.asList(new Object[] { null })); Assert.fail("Expected validation errors"); } catch (final ConstraintViolationException cve) { // Check all expected errors are there. final Set<ConstraintViolation<?>> constraintViolations = cve.getConstraintViolations(); Assert.assertNotNull(constraintViolations); Assert.assertEquals(1, constraintViolations.size()); // Check expected errors final ConstraintViolation<?> error1 = constraintViolations.iterator().next(); Assert.assertEquals(NotNull.class, error1.getConstraintDescriptor().getAnnotation().annotationType()); Assert.assertEquals("jsr349Simple.param", error1.getPropertyPath().toString()); } }
@NotNull @Override public ProvisionServiceInstanceCommand.Response execute(@NotNull final ProvisionServiceInstanceCommand command) throws ServiceBrokerException { Objects.requireNonNull(command, () -> "command must not be null"); ProvisionServiceInstanceCommand.Response returnValue = null; final String serviceId = command.getServiceId(); if (serviceId != null) { ServiceBroker serviceBroker = null; try { this.serviceBrokerAssociationLock.readLock().lock(); serviceBroker = this.getServiceBrokerForServiceId(serviceId); } finally { this.serviceBrokerAssociationLock.readLock().unlock(); } if (serviceBroker != null) { returnValue = serviceBroker.execute(command); } } if (returnValue == null) { throw new InvalidServiceBrokerCommandException(command); } return returnValue; }
@RequestMapping(method = RequestMethod.GET, path = "/createCell") public void createCell(@NotNull @RequestParam String name, @NotNull @RequestParam CellType cellType) throws ExecutionException, InterruptedException { JSONObject cell = new JSONObject(); cell.put("name", name); cell.put("type", cellType); ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(topic, cell.toString()); future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() { @Override public void onSuccess(SendResult<String, String> result) { System.out.println("success"); } @Override public void onFailure(Throwable ex) { System.out.println("failed"); } }); }
/** * Constructor. * * @param id The movie ID * @param title The title of the movie * @param type The type of the movie * @param rating The movie rating */ @JsonCreator public MovieSearchResult( @NotNull @JsonProperty("id") final Long id, @NotBlank @JsonProperty("title") final String title, @NotNull @JsonProperty("type") final MovieType type, @NotNull @JsonProperty("rating") final Float rating ) { super(id.toString()); this.title = title; this.type = type; this.rating = rating; }
/** * Creates a new instance with required parameters. * * @param service Service principal. * @param registeredService Registered service corresponding to given service. */ public ServiceContext(@NotNull final Service service, @NotNull final RegisteredService registeredService) { this.service = service; this.registeredService = registeredService; if (!registeredService.matches(service)) { throw new IllegalArgumentException("Registered service does not match given service."); } }
/** * Gets the attribute values if more than one, otherwise an empty list. * * @param entry the entry * @param attrName the attr name * @return the collection of attribute values */ private Collection<String> getMultiValuedAttributeValues(@NotNull final LdapEntry entry, @NotNull final String attrName) { final LdapAttribute attrs = entry.getAttribute(attrName); if (attrs != null) { return attrs.getStringValues(); } return Collections.emptyList(); }
@ApiOperation(value = "问题获取", notes = "问题获取", response = ResultDTO.class, tags = { "ZhihuQuestion", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "返回问题对象", response = ResultDTO.class), @ApiResponse(code = 200, message = "返回错误信息", response = ResultDTO.class) }) @RequestMapping(value = "/question/get", produces = { "application/json" }, method = RequestMethod.GET) ResponseEntity<ResultDTO> questionGetGet( @NotNull @ApiParam(value = "问题id", required = true, defaultValue = "0213f784cdd9493aab7d44683b0bbb1d") @RequestParam(value = "id", required = true) String id);
public DseGraphHealthCheck( @NotNull DseSession session, @NotNull String validationQuery, @NotNull Duration validationTimeout) { this.session = session; this.validationQuery = validationQuery; this.validationTimeout = validationTimeout; }
/** * Get logstashPort * @return logstashPort **/ @JsonProperty("logstash_port") @ApiModelProperty(example = "5044", required = true, value = "") @NotNull public String getLogstashPort() { return logstashPort; }
@Override public void onMessage(@NotNull final Message msg, @NotNull final ActorLifecycleMessage lifecycleMessage) { requireNonNull(msg); requireNonNull(lifecycleMessage); lifecycleMessage.sendTo(actorsListener); }
@Override void parseProperty(@NotNull ArrayGenerator generator, @NotNull JsonArrayProperty property, @NotNull JsonNode node) { switch (property) { case ITEMS: if (node.isArray()) { Iterator<JsonNode> nodeIterator = node.elements(); while (nodeIterator.hasNext()) { addItem(generator, nodeIterator.next()); } } else { addItem(generator, node); } break; case ADDITIONAL_ITEMS: generator.setAdditionalItems(node.booleanValue()); break; case MAX_ITEMS: generator.setMaxItems(node.intValue()); break; case MIN_ITEMS: generator.setMinItems(node.intValue()); break; case UNIQUE_ITEMS: generator.setUniqueItems(node.booleanValue()); break; } }
/** * Gets credential from the context. * * @param context the context * @return the credential, or null if it cant be found in the context or if it has no id. */ public static Credential getCredential(@NotNull final RequestContext context) { final Credential cFromRequest = (Credential) context.getRequestScope().get("credential"); final Credential cFromFlow = (Credential) context.getFlowScope().get("credential"); final Credential credential = cFromRequest != null ? cFromRequest : cFromFlow; if (credential != null && StringUtils.isBlank(credential.getId())) { return null; } return credential; }
@PUT public Response put(@Context Request request, @NotNull ClimateDto climate) { synchronized (transactionLock) { ClimateDto currentClimate = stockholmClimateRepository.get(); EntityTag currentETag = eTagGenerator.eTagFor(currentClimate); Optional<Response> preconditionFailedResponse = evaluateETagPrecondition(request, currentETag); if (preconditionFailedResponse.isPresent()) return preconditionFailedResponse.get(); stockholmClimateRepository.save(climate); } EntityTag eTag = eTagGenerator.eTagFor(climate); return Response.noContent().tag(eTag).build(); }
public void voteFor(@NotNull String userId, long postId) { Post post = em.find(Post.class, postId, LockModeType.PESSIMISTIC_WRITE); if (post == null) { throw new IllegalArgumentException(post.getClass().getSimpleName() + " does not exist: " + postId); } if (post.getVotesFor().contains(userId)) { throw new IllegalArgumentException("User " + userId + " already voted for this post"); } post.getVotesFor().add(userId); post.getVotesAgainst().remove(userId); }
public Create( @NotNull T data, @NotNull String localPart, @NotNull ExecuteRestCall sender, @NotNull YamlPrinter printer, @NotNull String templateName ) { super(data, localPart, sender); this.printer = printer; this.templateName = templateName; }
private static Class<?> loadClass(@NotNull final String className) throws ValidationException { try { return Class.forName(className); // NOSONAR } catch (ClassNotFoundException e) { throw ValidationException.create(String.format(LOAD_MSG, className), e); } }
private static Config parseClusterConfig(@NotNull final String jsonConfig) throws ValidationException { try { return ConfigFactory.parseString(jsonConfig, Constants.CONFIG_PARSE_OPTIONS); } catch (ConfigException e) { throw ValidationException.create("Cluster configuration error for " + jsonConfig, e); } }
public ProvisionServiceInstanceCommand(final String instanceId, @NotNull /* @NotEmpty */ final String serviceId, @NotNull /* @NotEmpty */ final String planId, final Map<? extends String, ?> parameters, @NotNull /* @NotEmpty */ final String organizationGuid, @NotNull /* @NotEmpty */ final String spaceGuid) { this(instanceId, serviceId, planId, null, false, organizationGuid, spaceGuid, parameters); }
/** * Constructor. * * @param id The contribution ID * @param field The movie field * @param date The creation date */ @JsonCreator public ContributionSearchResult( @NotNull @JsonProperty("id") final Long id, @NotNull @JsonProperty("field") final MovieField field, @NotNull @JsonProperty("date") final Date date ) { super(id.toString()); this.field = field; this.date = date; }
@Override public Credential fromRequestBody(@NotNull final MultiValueMap<String, String> requestBody) { final String username = requestBody.getFirst("username"); final String password = requestBody.getFirst("password"); if(username == null || password == null) { throw new BadRequestException("Invalid payload. 'username' and 'password' form fields are required."); } return new UsernamePasswordCredential(requestBody.getFirst("username"), requestBody.getFirst("password")); }
@Override public synchronized void onActorCloseRequest(@NotNull final ActorKey actor) { requireNonNull(actor); ManagedActor found = actors.remove(actor); if (found == null) { log.warn("{} Could not find {} to close.", this, actor); } else { log.info("{} Closing {}...", this, actor); found.close(); log.info("{} Closed {}.", this, actor); } }
@Size(min = 0, max = 0) @NotNull @Override public String getDatabasePrefix() { // primary is always empty return EMPTY_PREFIX; }
@Path("second/{name}") @GET public String sayHello1( final Session session, @NotNull @PathParam("name") final String lang, @NotNull(message = "limit参数不可为空") @QueryParam("limit") final Integer limit) { System.out.println(session.data()); Params.start(this.getClass()).monitor(lang).monitor(limit).end(); return lang; }
/** * {@inheritDoc} */ @Override public void updateGenreContribution( @NotNull @Valid final ContributionUpdate<Genre> contribution, @Min(1) final Long contributionId, @NotBlank final String userId ) throws ResourceNotFoundException, ResourceConflictException { log.info("Called with contribution {}, contributionId {}, userId {}", contribution, contributionId, userId); final UserEntity user = this.findUser(userId); final ContributionEntity contributionEntity = this.findContribution(contributionId, DataStatus.WAITING, user, MovieField.GENRE); this.validIds(contributionEntity, contribution); this.cleanUp(contributionEntity, contribution, contributionEntity.getMovie().getGenres()); contribution.getElementsToAdd().forEach((key, value) -> { this.moviePersistenceService.updateGenre(value, key, contributionEntity.getMovie()); }); contribution.getElementsToUpdate().forEach((key, value) -> { this.moviePersistenceService.updateGenre(value, key, contributionEntity.getMovie()); }); contribution.getNewElementsToAdd() .forEach(genre -> { final Long id = this.moviePersistenceService.createGenre(genre, contributionEntity.getMovie()); contributionEntity.getIdsToAdd().add(id); }); contributionEntity.setSources(contribution.getSources()); Optional.ofNullable(contribution.getComment()).ifPresent(contributionEntity::setUserComment); }
@Override public void onMessage(@NotNull final String from, @NotNull final String message) throws ReactorException { if (message.equals(PRODUCE_METRICS_MSG)) { metrics.sinkFor(DUMMY_METRIC_A).add(10); metrics.sinkFor(DUMMY_METRIC_B).timed(1); } super.onMessage(from, message); }
/** * * 获取json传 K-V 的V值只适应于获取叶子节点的V值 * 注意:如果{"a":"b","c":{"d":"d1","e":{"f","f1"}}} * 当 path为c时候,返回:{"d":"d1","e":{"f","f1"}} * @param json * @param paths * * @return */ public static String getString(@NotNull String json, @Nullable String... paths) { JsonNode jsonNode = parseJsonNode(json, paths); if (Check.isNull(jsonNode)) { return null; } if(jsonNode.isValueNode()){ return jsonNode.textValue(); } return toJsonString(jsonNode); }
/** * {@inheritDoc} */ @Override public void updateLanguageContribution( @NotNull @Valid final ContributionUpdate<Language> contribution, @Min(1) final Long contributionId, @NotBlank final String userId ) throws ResourceNotFoundException, ResourceConflictException { log.info("Called with contribution {}, contributionId {}, userId {}", contribution, contributionId, userId); final UserEntity user = this.findUser(userId); final ContributionEntity contributionEntity = this.findContribution(contributionId, DataStatus.WAITING, user, MovieField.LANGUAGE); this.validIds(contributionEntity, contribution); this.cleanUp(contributionEntity, contribution, contributionEntity.getMovie().getLanguages()); contribution.getElementsToAdd().forEach((key, value) -> { this.moviePersistenceService.updateLanguage(value, key, contributionEntity.getMovie()); }); contribution.getElementsToUpdate().forEach((key, value) -> { this.moviePersistenceService.updateLanguage(value, key, contributionEntity.getMovie()); }); contribution.getNewElementsToAdd() .forEach(language -> { final Long id = this.moviePersistenceService.createLanguage(language, contributionEntity.getMovie()); contributionEntity.getIdsToAdd().add(id); }); contributionEntity.setSources(contribution.getSources()); Optional.ofNullable(contribution.getComment()).ifPresent(contributionEntity::setUserComment); }
@POST @Produces(MediaType.APPLICATION_JSON) @Consumes("application/json") default T create(@Context SecurityContext sec, @NotNull @Valid T obj) { return getDataManager().create(obj); }
@PUT @Path(value = "/{id}") @Consumes("application/json") default void update(@NotNull @PathParam("id") @ApiParam(required = true) String id, @NotNull @Valid T obj) { getDataManager().update(obj); }
@NotNull ActorRegistryClusterClient createForActorRegistry();
@PreAuthorize("hasAuthority('role_write')") RoleEntity saveRole(@NotNull @Valid RoleEntity role);
@Override public AgentRegistryClusterClient createForAgentRegistry(@NotNull final AgentRegistry agentRegistry) { return null; }
@PreAuthorize("hasAuthority('user_write')") UserEntity saveUser(@NotNull @Valid UserEntity userEntity);
@NotNull @Schema(required = true, description = "date when note was created", example = "2017-12-15T01:27:39.258") LocalDateTime getCreatedWhen();
@SuppressWarnings("unchecked") public static <T extends Annotation> MinijaxConstraintDescriptor<T> build(final AnnotatedType annotatedType, final T annotation) { final Constraint constraint = annotation.annotationType().getAnnotation(Constraint.class); if (constraint == null) { return null; } final Class<?> valueClass = ReflectionUtils.getRawType(annotatedType); final Class<?> annotationClass = annotation.annotationType(); if (constraint.validatedBy().length > 0) { return buildDeclaredValidator(annotation, constraint.validatedBy()[0]); } else if (annotationClass == AssertFalse.class) { return (MinijaxConstraintDescriptor<T>) buildAssertFalseValidator((AssertFalse) annotation, valueClass); } else if (annotationClass == AssertTrue.class) { return (MinijaxConstraintDescriptor<T>) buildAssertTrueValidator((AssertTrue) annotation, valueClass); } else if (annotationClass == Max.class) { return (MinijaxConstraintDescriptor<T>) buildMaxValidator((Max) annotation, valueClass); } else if (annotationClass == Min.class) { return (MinijaxConstraintDescriptor<T>) buildMinValidator((Min) annotation, valueClass); } else if (annotationClass == NotBlank.class) { return (MinijaxConstraintDescriptor<T>) buildNotBlankValidator((NotBlank) annotation, valueClass); } else if (annotationClass == NotEmpty.class) { return (MinijaxConstraintDescriptor<T>) buildNotEmptyValidator((NotEmpty) annotation, valueClass); } else if (annotationClass == NotNull.class) { return (MinijaxConstraintDescriptor<T>) buildNotNullValidator((NotNull) annotation); } else if (annotationClass == Pattern.class) { return (MinijaxConstraintDescriptor<T>) buildPatternValidator((Pattern) annotation, valueClass); } else if (annotationClass == Size.class) { return (MinijaxConstraintDescriptor<T>) buildSizeValidator((Size) annotation, valueClass); } else { throw new ValidationException("Unrecognized constraint annotation: " + annotation); } }