io.micrometer.core.instrument.util.StringUtils Java Examples

The following examples show how to use io.micrometer.core.instrument.util.StringUtils. 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: FeignBasicAuthRequestInterceptor.java    From mogu_blog_v2 with Apache License 2.0 7 votes vote down vote up
@Override
public void apply(RequestTemplate requestTemplate) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    // 获取token,放入到feign的请求头
    String token = request.getParameter("token");

    if(StringUtils.isNotEmpty(token)){
        // 如果带有?说明还带有其它参数,我们只截取到token即可
        if(token.indexOf("?") != -1) {
            String [] params = token.split("\\?url=");
            token = params[0];
        }
        requestTemplate.header("pictureToken", token);
    }
}
 
Example #2
Source File: ApplicationController.java    From Moss with Apache License 2.0 6 votes vote down vote up
/**
 * 得到应用的flux 实例
 * @return
 */
private Flux<MossApplication> applicationFlux(String appName){
    Flux<Instance> instanceFlux=null;
    /**
     * 当应用名不为空进行过滤分页
     */
    if(StringUtils.isNotEmpty(appName)){
        //因为注册到Eureka上的服务为大写
        instanceFlux=registry.getInstances(appName);
    }else {
        instanceFlux=registry.getInstances();
    }
    String registerSource = this.getRegisterSource();
    if(StringUtils.isNotEmpty(registerSource)){
        instanceFlux=instanceFlux.filter(instance->registerSource.equalsIgnoreCase(instance.getRegistration().getSource()));
    }
    return instanceFlux.filter(Instance::isRegistered)
            .groupBy(instance -> instance.getRegistration().getName())
            .flatMap(grouped -> toApplication(grouped.key(), grouped));
}
 
Example #3
Source File: ManageAudienceController.java    From line-bot-sdk-java with Apache License 2.0 6 votes vote down vote up
@PostMapping("/manage_audience/upload")
public CompletableFuture<RedirectView> postUpload(
        @RequestParam String description,
        @RequestParam Boolean isIfaAudience,
        @RequestParam(required = false) String uploadDescription,
        @RequestParam String audiences
) {
    List<Audience> audiencesList = Arrays.stream(audiences.split("\r?\n"))
                                         .map(it -> it.replaceAll("\\s", ""))
                                         .filter(StringUtils::isNotBlank)
                                         .map(Audience::new)
                                         .collect(Collectors.toList());

    CreateAudienceGroupRequest request = CreateAudienceGroupRequest.builder()
                                                                   .description(description)
                                                                   .isIfaAudience(isIfaAudience)
                                                                   .uploadDescription(uploadDescription)
                                                                   .audiences(audiencesList)
                                                                   .build();
    return client.createAudienceGroup(request)
                 .thenApply(
                         response -> new RedirectView("/manage_audience/" + response.getAudienceGroupId()));
}
 
Example #4
Source File: StackdriverConfig.java    From micrometer with Apache License 2.0 6 votes vote down vote up
/**
 * Return {@link CredentialsProvider} to use.
 *
 * @return {@code CredentialsProvider} to use
 * @since 1.4.0
 */
default CredentialsProvider credentials() {
    return getString(this, "credentials")
            .flatMap((credentials, valid) -> {
                if (StringUtils.isBlank(credentials)) {
                    return Validated.valid(valid.getProperty(), MetricServiceSettings.defaultCredentialsProviderBuilder().build());
                }

                try {
                    FixedCredentialsProvider provider = FixedCredentialsProvider.create(
                            GoogleCredentials.fromStream(new FileInputStream(credentials))
                                    .createScoped(MetricServiceSettings.getDefaultServiceScopes())
                    );
                    return Validated.valid(valid.getProperty(), provider);
                } catch (IOException t) {
                    return Validated.invalid(valid.getProperty(), credentials, "cannot read credentials file", InvalidReason.MALFORMED, t);
                }
            })
            .get();
}
 
Example #5
Source File: SignalFxNamingConvention.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Override
public String tagKey(String key) {
    String conventionKey = delegate.tagKey(key);

    conventionKey = START_UNDERSCORE_PATTERN.matcher(conventionKey).replaceAll(""); // 2
    conventionKey = SF_PATTERN.matcher(conventionKey).replaceAll(""); // 2

    conventionKey = PATTERN_TAG_KEY_BLACKLISTED_CHARS.matcher(conventionKey).replaceAll("_");
    if (!START_LETTERS_PATTERN.matcher(conventionKey).matches()) { // 3
        conventionKey = "a" + conventionKey;
    }
    if (PATTERN_TAG_KEY_BLACKLISTED_PREFIX.matcher(conventionKey).matches()) {
        logger.log("'" + conventionKey + "' (original name: '" + key + "') is not a valid tag key. "
                + "Must not start with any of these prefixes: aws_, gcp_, or azure_. "
                + "Please rename it to conform to the constraints. "
                + "If it comes from a third party, please use MeterFilter to rename it.");
    }
    return StringUtils.truncate(conventionKey, KEY_MAX_LENGTH); // 1
}
 
Example #6
Source File: DynatraceMetricDefinition.java    From micrometer with Apache License 2.0 6 votes vote down vote up
String asJson() {
    String displayName = description == null ? metricId : StringEscapeUtils.escapeJson(description);
    String body = "{\"displayName\":\"" + StringUtils.truncate(displayName, MAX_DISPLAY_NAME) + "\"";

    if (StringUtils.isNotBlank(group))
        body += ",\"group\":\"" + StringUtils.truncate(group, MAX_GROUP_NAME) + "\"";

    if (unit != null)
        body += ",\"unit\":\"" + unit + "\"";

    if (dimensions != null && !dimensions.isEmpty())
        body += ",\"dimensions\":[" + dimensions.stream()
                .map(d -> "\"" + d + "\"")
                .collect(Collectors.joining(",")) + "]";

    body += ",\"types\":[" +
            stream(technologyTypes).map(type -> "\"" + type + "\"").collect(Collectors.joining(",")) +
            "]";

    body += "}";
    return body;
}
 
Example #7
Source File: AzureMonitorMeterRegistry.java    From micrometer with Apache License 2.0 6 votes vote down vote up
private AzureMonitorMeterRegistry(AzureMonitorConfig config, Clock clock,
                                  TelemetryConfiguration telemetryConfiguration,
                                  ThreadFactory threadFactory) {
    super(config, clock);

    config().namingConvention(new AzureMonitorNamingConvention());
    if (StringUtils.isEmpty(telemetryConfiguration.getInstrumentationKey())) {
        checkRequired("instrumentationKey", AzureMonitorConfig::instrumentationKey).apply(config).orThrow();
        telemetryConfiguration.setInstrumentationKey(config.instrumentationKey());
    }

    client = new TelemetryClient(telemetryConfiguration);
    client.getContext().getInternal().setSdkVersion(SDK_VERSION);

    start(threadFactory);
}
 
Example #8
Source File: NamingConvention.java    From micrometer with Apache License 2.0 6 votes vote down vote up
private String toCamelCase(String value) {
    String[] parts = value.split("\\.");
    StringBuilder conventionName = new StringBuilder(value.length());
    for (int i = 0; i < parts.length; i++) {
        String str = parts[i];
        if (StringUtils.isEmpty(str))
            continue;

        if (i == 0) {
            conventionName.append(str);
        } else {
            final char firstChar = str.charAt(0);
            if (Character.isUpperCase(firstChar)) {
                conventionName.append(str); // already capitalized
            } else {
                conventionName.append(Character.toUpperCase(firstChar)).append(str, 1, str.length());
            }
        }
    }
    return conventionName.toString();
}
 
Example #9
Source File: SlackController.java    From mirrorgate with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/channels",
    method = GET,
    produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, String>> getDashboardChannels(
    final @RequestParam("dashboard") String dashboardId,
    final @RequestParam("token") String token
) {

    if (StringUtils.isBlank(token)) {
        return ResponseEntity.badRequest().build();
    }

    final DashboardDTO dashboard = dashboardService.getDashboard(dashboardId);

    if (dashboard == null) {
        return ResponseEntity.badRequest().build();
    }

    if (dashboard.getSlackToken() == null) {
        return ResponseEntity.status(HttpStatus.PRECONDITION_FAILED).build();
    }

    return ResponseEntity.ok(slackService.getChannelList(dashboard.getSlackToken()));
}
 
Example #10
Source File: StringToDurationConverter.java    From foremast with Apache License 2.0 6 votes vote down vote up
@Nullable
private static Duration simpleParse(@Nullable String rawTime) {
    if (StringUtils.isEmpty(rawTime))
        return null;
    if (!Character.isDigit(rawTime.charAt(0)))
        return null;

    String time = rawTime.toLowerCase();
    return tryParse(time, "ns", Duration::ofNanos)
        .orElseGet(() -> tryParse(time, "ms", Duration::ofMillis)
            .orElseGet(() -> tryParse(time, "s", Duration::ofSeconds)
                .orElseGet(() -> tryParse(time, "m", Duration::ofMinutes)
                    .orElseGet(() -> tryParse(time, "h", Duration::ofHours)
                        .orElseGet(() -> tryParse(time, "d", Duration::ofDays)
                            .orElse(null))))));
}
 
Example #11
Source File: StringToDurationConverter.java    From foremast with Apache License 2.0 6 votes vote down vote up
@Nullable
private static Duration simpleParse(@Nullable String rawTime) {
    if (StringUtils.isEmpty(rawTime))
        return null;
    if (!Character.isDigit(rawTime.charAt(0)))
        return null;

    String time = rawTime.toLowerCase();
    return tryParse(time, "ns", Duration::ofNanos)
        .orElseGet(() -> tryParse(time, "ms", Duration::ofMillis)
            .orElseGet(() -> tryParse(time, "s", Duration::ofSeconds)
                .orElseGet(() -> tryParse(time, "m", Duration::ofMinutes)
                    .orElseGet(() -> tryParse(time, "h", Duration::ofHours)
                        .orElseGet(() -> tryParse(time, "d", Duration::ofDays)
                            .orElse(null))))));
}
 
Example #12
Source File: UploadController.java    From spring-admin-vue with Apache License 2.0 6 votes vote down vote up
/**
 * 图片上传
 *
 * @param file
 * @return java.io.File
 * @throws IOException
 * @author Wang Chen Chen<[email protected]>
 * @date 2019/12/13 23:03
 */
@ApiOperation(value = "图片上传", notes = "普通的图片上传:500px * 500px")
@PostMapping("/image")
public JsonResult uploadImages(MultipartFile file) throws IOException {
    if (file.isEmpty() || StringUtils.isEmpty(file.getOriginalFilename())) {
        JsonResult.fail("图片不能为空");
    }
    String contentType = file.getContentType();
    if (!contentType.contains("")) {
        JsonResult.fail("图片格式不能为空");
    }
    String reg = ".+(.JPEG|.jpeg|.JPG|.jpg|.png|.PNG)$";
    Matcher matcher = Pattern.compile(reg).matcher(file.getOriginalFilename());
    // 校验 图片的后缀名 是否符合要求
    if (matcher.find()) {
        Map<String, String> map = uploadFile(file, 500, 500);
        return JsonResult.success(map);
    }
    return JsonResult.fail("图片格式不正确,只可以上传[ JPG , JPEG , PNG ]中的一种");
}
 
Example #13
Source File: UploadController.java    From spring-admin-vue with Apache License 2.0 6 votes vote down vote up
/**
 * 用户头像上传
 *
 * @param file
 * @return java.io.File
 * @throws IOException
 * @author Wang Chen Chen<[email protected]>
 * @date 2019/12/13 23:03
 */
@ApiOperation(value = "头像上传", notes = "普通的图片上传:200px * 200px")
@PostMapping("/avatar")
public JsonResult uploadAvatar(MultipartFile file) throws IOException {
    if (file.isEmpty() || StringUtils.isEmpty(file.getOriginalFilename())) {
        JsonResult.fail("头像不能为空");
    }
    String contentType = file.getContentType();
    if (!contentType.contains("")) {
        JsonResult.fail("头像格式不能为空");
    }
    String reg = ".+(.JPEG|.jpeg|.JPG|.jpg|.png|.PNG)$";
    Matcher matcher = Pattern.compile(reg).matcher(file.getOriginalFilename());
    // 校验 图片的后缀名 是否符合要求
    if (matcher.find()) {
        Map<String, String> map = uploadFile(file, 200, 200);
        return JsonResult.success(map);
    }
    return JsonResult.fail("头像格式不正确,只可以上传[ JPG , JPEG , PNG ]中的一种");
}
 
Example #14
Source File: TestGradleGeneration.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
@Ignore
    @Test
    public void testDockerImageGeneration() throws Exception {

        Pipeline p = SequencePipeline.builder()
                .add(new DL4JStep("file:///some/model/path.zip", null, null))
                .build();

        File dir = testDir.newFolder();
//        File dir = new File("C:/Temp/Gradle");
        File jsonF = new File(dir, "pipeline.json");
        FileUtils.writeStringToFile(jsonF, p.toJson(), StandardCharsets.UTF_8);

        File gradleDir = new File(dir, "gradle");
        File imageDir = new File(dir, "image");

        val deployment = new DockerDeployment().imageName("myrepo:1.0.0");
        //deployment.setImageName("ks");
        Config c = new Config()
                .pipelinePath(jsonF.getAbsolutePath())
                .target(Target.LINUX_X86)
                .serving(Serving.HTTP)
                .deployments(deployment);

        GradleBuild.generateGradleBuildFiles(gradleDir, c);

        //Check for build.gradle.kts
        File buildGradle = new File(gradleDir, "build.gradle.kts");
        assertTrue(buildGradle.exists());

        //Actually run the build
        //TODO this might not be doable in a unit test (unless all modules have been installed to local maven repo first)
        GradleBuild.runGradleBuild(gradleDir, c);
        assertTrue(StringUtils.isNotEmpty(deployment.imageId()));
        assertTrue(deployment.outputString().contains(deployment.imageId()));
    }
 
Example #15
Source File: MessageHelper.java    From line-bot-sdk-java with Apache License 2.0 5 votes vote down vote up
public List<Message> buildMessages(String[] messages) {
    return Arrays.stream(messages)
                 .filter(StringUtils::isNotBlank)
                 .map(it -> {
                     try {
                         return objectMapper.readValue(it, Message.class);
                     } catch (JsonProcessingException e) {
                         throw new RuntimeException(e);
                     }
                 }).collect(Collectors.toList());
}
 
Example #16
Source File: MulticastController.java    From line-bot-sdk-java with Apache License 2.0 5 votes vote down vote up
@PostMapping("/message/multicast")
public CompletableFuture<RedirectView> postMulticast(@RequestParam String to,
                                                     @RequestParam String[] messages,
                                                     @RequestParam Boolean notificationDisabled)
        throws ExecutionException, InterruptedException {
    Set<String> toList = Arrays.stream(to.split("\r?\n"))
                               .filter(StringUtils::isNotBlank)
                               .collect(Collectors.toSet());

    List<Message> messageList = messageHelper.buildMessages(messages);
    return client.multicast(
            new Multicast(toList, messageList, notificationDisabled))
                 .thenApply(response -> new RedirectView("/message/multicast/" + response.getRequestId()));
}
 
Example #17
Source File: PrometheusSample.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(@NonNull Javalin app) {
    Server server = app.server().server();

    app.exception(Exception.class, EXCEPTION_HANDLER);

    server.insertHandler(new TimedHandler(registry, tags, new DefaultHttpServletRequestTagsProvider() {
        @Override
        public Iterable<Tag> getTags(HttpServletRequest request, HttpServletResponse response) {
            String exceptionName = response.getHeader(EXCEPTION_HEADER);
            response.setHeader(EXCEPTION_HEADER, null);

            String uri = app.servlet().getMatcher()
                    .findEntries(HandlerType.valueOf(request.getMethod()), request.getPathInfo())
                    .stream()
                    .findAny()
                    .map(HandlerEntry::getPath)
                    .map(path -> path.equals("/") || StringUtils.isBlank(path) ? "root" : path)
                    .map(path -> response.getStatus() >= 300 && response.getStatus() < 400 ? "REDIRECTION" : path)
                    .map(path -> response.getStatus() == 404 ? "NOT_FOUND" : path)
                    .orElse("unknown");

            return Tags.concat(
                    super.getTags(request, response),
                    "uri", uri,
                    "exception", exceptionName == null ? "None" : exceptionName
            );
        }
    }));

    new JettyServerThreadPoolMetrics(server.getThreadPool(), tags).bindTo(registry);
    new JettyConnectionMetrics(registry, tags);
}
 
Example #18
Source File: CustomAuthenticationSuccessHandler.java    From oauth2-client with MIT License 5 votes vote down vote up
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
                                    HttpServletResponse response, Authentication authentication)
    throws IOException, ServletException {

    String redirectUrl = "";
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null && StringUtils.isNotEmpty(savedRequest.getRedirectUrl())) {
        redirectUrl = savedRequest.getRedirectUrl();
    }


    // 根据需要设置 cookie,js携带token直接访问api接口等
    if (authentication instanceof OAuth2AuthenticationToken) {
        OAuth2AuthorizedClient client = authorizedClientService
            .loadAuthorizedClient(
                ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId(),
                authentication.getName());
        String token = client.getAccessToken().getTokenValue();
        Cookie tokenCookie = new Cookie("access_token", token);
        tokenCookie.setHttpOnly(true);
        tokenCookie.setDomain(cookieDomain);
        tokenCookie.setPath("/");
        response.addCookie(tokenCookie);
    }

    //设置回调成功的页面,
    if (StringUtils.isNotEmpty(redirectUrl)) {
        super.onAuthenticationSuccess(request, response, authentication);
    } else {
        response.sendRedirect("/");
    }

}
 
Example #19
Source File: CloudWatchMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private boolean isAcceptableTag(Tag tag) {
    if (StringUtils.isBlank(tag.getValue())) {
        warnThenDebugLogger.log("Dropping a tag with key '" + tag.getKey() + "' because its value is blank.");
        return false;
    }
    return true;
}
 
Example #20
Source File: DynatraceMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
List<DynatraceBatchedPayload> createPostMessages(String type, String group, List<DynatraceTimeSeries> timeSeries) {
    final String header = "{\"type\":\"" + type + '\"'
            + (StringUtils.isNotBlank(group) ? ",\"group\":\"" + group + '\"' : "")
            + ",\"series\":[";
    final String footer = "]}";
    final int headerFooterBytes = header.getBytes(UTF_8).length + footer.getBytes(UTF_8).length;
    final int maxMessageSize = MAX_MESSAGE_SIZE - headerFooterBytes;
    List<DynatraceBatchedPayload> payloadBodies = createPostMessageBodies(timeSeries, maxMessageSize);
    return payloadBodies.stream().map(body -> {
        String message = header + body.payload + footer;
        return new DynatraceBatchedPayload(message, body.metricCount);
    }).collect(Collectors.toList());
}
 
Example #21
Source File: UploadController.java    From spring-admin-vue with Apache License 2.0 5 votes vote down vote up
/**
 * 删除图片
 *
 * @param url
 * @return java.io.File
 * @throws IOException
 * @author Wang Chen Chen<[email protected]>
 * @date 2019/12/13 23:03
 */
@ApiOperation(value = "图片删除", notes = "根据url 删除图片")
@DeleteMapping("/delete")
public JsonResult deleteImages(String url) throws IOException {
    if (StringUtils.isNotEmpty(url)) {
        String fileKey = url.substring((url.lastIndexOf("/") + 1), url.length());
        log.info("deleteImages url: {}  fileKey: {}", url, fileKey);
        qiniuUtils.delete(fileKey);
    }
    return JsonResult.success();
}
 
Example #22
Source File: ExecutorServiceMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private static String sanitizePrefix(String metricPrefix) {
    if (StringUtils.isBlank(metricPrefix))
        return "";
    if (!metricPrefix.endsWith("."))
        return metricPrefix + ".";
    return metricPrefix;
}
 
Example #23
Source File: JooqExecuteListener.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private void stopTimerIfStillRunning(ExecuteContext ctx) {
    Iterable<Tag> queryTags = queryTagsSupplier.get();
    if (queryTags == null) return;

    Timer.Sample sample;
    synchronized (sampleLock) {
        sample = sampleByExecuteContext.remove(ctx);
    }
    if (sample == null) return;

    String exceptionName = "none";
    String exceptionSubclass = "none";

    Exception exception = ctx.exception();
    if (exception != null) {
        if (exception instanceof DataAccessException) {
            DataAccessException dae = (DataAccessException) exception;
            exceptionName = dae.sqlStateClass().name().toLowerCase().replace('_', ' ');
            exceptionSubclass = dae.sqlStateSubclass().name().toLowerCase().replace('_', ' ');
            if (exceptionSubclass.contains("no subclass")) {
                exceptionSubclass = "none";
            }
        } else {
            String simpleName = exception.getClass().getSimpleName();
            exceptionName = StringUtils.isNotBlank(simpleName) ? simpleName : exception.getClass().getName();
        }
    }

    //noinspection unchecked
    sample.stop(Timer.builder("jooq.query")
            .description("Execution time of a SQL query performed with JOOQ")
            .tags(queryTags)
            .tag("type", ctx.type().name().toLowerCase())
            .tag("exception", exceptionName)
            .tag("exception.subclass", exceptionSubclass)
            .tags(tags)
            .register(registry));
}
 
Example #24
Source File: ElasticMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance with given parameters.
 *
 * @param config configuration to use
 * @param clock clock to use
 * @param threadFactory thread factory to use
 * @param httpClient http client to use
 * @since 1.2.1
 */
protected ElasticMeterRegistry(ElasticConfig config, Clock clock, ThreadFactory threadFactory, HttpSender httpClient) {
    super(config, clock);
    config().namingConvention(new ElasticNamingConvention());
    this.config = config;
    indexDateFormatter = DateTimeFormatter.ofPattern(config.indexDateFormat());
    this.httpClient = httpClient;
    if (StringUtils.isNotEmpty(config.pipeline())) {
        indexLine = "{ \"index\" : {\"pipeline\":\"" + config.pipeline() + "\"} }\n";
    } else {
        indexLine = "{ \"index\" : {} }\n";
    }

    start(threadFactory);
}
 
Example #25
Source File: HttpSender.java    From micrometer with Apache License 2.0 5 votes vote down vote up
/**
 * If user and password are non-empty, set basic authentication on the request.
 *
 * @param user     A user name, if available.
 * @param password A password, if available.
 * @return This request builder.
 */
public final Builder withBasicAuthentication(@Nullable String user, @Nullable String password) {
    if (user != null && StringUtils.isNotBlank(user)) {
        String encoded = Base64.getEncoder().encodeToString((user.trim() + ":" + (password == null ? "" : password.trim()))
                .getBytes(StandardCharsets.UTF_8));
        withHeader("Authorization", "Basic " + encoded);
    }
    return this;
}
 
Example #26
Source File: CloudWatchMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private boolean isAcceptableTag(Tag tag) {
    if (StringUtils.isBlank(tag.getValue())) {
        warnThenDebugLogger.log("Dropping a tag with key '" + tag.getKey() + "' because its value is blank.");
        return false;
    }
    return true;
}
 
Example #27
Source File: NewRelicConfig.java    From micrometer with Apache License 2.0 5 votes vote down vote up
default Validated<?> validateForInsightsApi() {
    return checkAll(this,
            c -> validate(),
            check("uri", NewRelicConfig::uri)
                    .andThen(v -> v.invalidateWhen(StringUtils::isBlank, "is required when publishing to Insights API",
                            InvalidReason.MISSING)),
            check("apiKey", NewRelicConfig::apiKey)
                    .andThen(v -> v.invalidateWhen(StringUtils::isBlank, "is required when publishing to Insights API",
                            InvalidReason.MISSING)),
            check("accountId", NewRelicConfig::accountId)
                    .andThen(v -> v.invalidateWhen(StringUtils::isBlank, "is required when publishing to Insights API",
                            InvalidReason.MISSING))
    );
}
 
Example #28
Source File: CloudWatchNamingConvention.java    From micrometer with Apache License 2.0 4 votes vote down vote up
@Override
public String tagKey(String key) {
    return StringUtils.truncate(delegate.tagKey(key), MAX_TAG_KEY_LENGTH);
}
 
Example #29
Source File: NarrowcastController.java    From line-bot-sdk-java with Apache License 2.0 4 votes vote down vote up
@PostMapping("/message/narrowcast")
public CompletableFuture<RedirectView> pushNarrowcast(
        @RequestParam String[] messages,
        @RequestParam(required = false) String gender,
        @RequestParam(required = false) String ageGte,
        @RequestParam(required = false) String ageLt,
        @RequestParam(required = false) String appType,
        @RequestParam(required = false) String[] areaCode,
        @RequestParam(required = false) Integer maxLimit,
        @RequestParam(required = false) String recipient,
        @RequestParam Boolean notificationDisabled
) throws JsonProcessingException {
    List<Message> messageList = messageHelper.buildMessages(messages);

    List<DemographicFilter> condition = new ArrayList<>();

    if (gender != null) {
        condition.add(GenderDemographicFilter.builder()
                                             .oneOf(singletonList(Gender.valueOf(gender)))
                                             .build());
    }
    if (StringUtils.isNotBlank(ageGte) || StringUtils.isNotBlank(ageLt)) {
        log.info("ageGte={} ageLt={}", ageGte, ageLt);
        AgeDemographicFilter filter = AgeDemographicFilter
                .builder()
                .gte(StringUtils.isBlank(ageGte) ? null : Age.valueOf(ageGte))
                .lt(StringUtils.isBlank(ageLt) ? null : Age.valueOf(ageLt))
                .build();
        condition.add(filter);
    }
    if (StringUtils.isNotBlank(appType)) {
        condition.add(AppTypeDemographicFilter.builder()
                                              .oneOf(singletonList(AppType.valueOf(appType)))
                                              .build());
    }
    if (areaCode != null && areaCode.length > 0) {
        condition.add(
                AreaDemographicFilter
                        .builder()
                        .oneOf(
                                Arrays.stream(areaCode)
                                      .map(AreaCode::valueOf)
                                      .collect(Collectors.toList())
                        ).build()
        );
    }
    Recipient recipientObject = recipient != null
                                ? objectMapper.readValue(recipient, Recipient.class)
                                : null;

    Narrowcast narrowcast = new Narrowcast(
            messageList,
            recipientObject,
            Filter.builder()
                  .demographic(
                          OperatorDemographicFilter.builder()
                                                   .and(condition)
                                                   .build()
                  ).build(),
            maxLimit == null ? null : Limit.builder().max(maxLimit).build(),
            notificationDisabled
    );
    return messagingClient.narrowcast(narrowcast).thenApply(
            response -> new RedirectView("/message/narrowcast/" + response.getRequestId())
    );
}
 
Example #30
Source File: Validated.java    From micrometer with Apache License 2.0 4 votes vote down vote up
default Validated<T> nonBlank() {
    return invalidateWhen(t -> StringUtils.isBlank(t.toString()), "cannot be blank", InvalidReason.MISSING);
}