AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-10461625

PatPanda's questions

Martin Hope
PatPanda
Asked: 2025-04-17 05:39:54 +0800 CST

使用 Spring 发送请求时,枚举字段具有小写值

  • 5

我想发送具有小写值的 http 请求,其中在路径变量中,该值取自具有大写值的枚举。

非常简单的代码:

@HttpExchange(accept = "application/json")
public interface FooHttpExchange {
    
    @GetExchange("/api/1.1/{day}/dosomething")
    String doSomethingWithDayOfWeek(@PathVariable("day") Day day);

使用枚举:

public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

如您所见,枚举的所有值都是大写的,以遵守 Java 枚举的约定。

但我也确实从第三方库中获取了枚举。我无法更改枚举的内容。

我希望将其作为请求发送(以星期一为例):

http://example.com/api/1.1/monday/dosomething

不幸的是,它发送的是这个:

http://example.com/api/1.1/MONDAY/dosomething

在服务器端,有一个解析过程,也就是说,它期望内容是小写的。

请求失败

如果我将枚举改为完全小写,我就可以确认请求正在起作用。

有时,我直接从第三方库中获取枚举,在那里我无法更改代码。

然而,这违反了 Java 枚举约定,即在代码中将它们设为大写。

如何将 Java 枚举设为大写,但在发送 http 请求时能够将其发送为小写?

java
  • 2 个回答
  • 62 Views
Martin Hope
PatPanda
Asked: 2025-04-15 06:04:36 +0800 CST

Maven 站点“Maven 坐标”页面也指示了要从中下载的私有存储库

  • 4
  • 我想要实现的目标:

在 maven 生成的站点页面中,特别是“Maven 坐标”页面,我想添加私有存储库的信息以下载工件。

  • 显示一些代码:

这是我的 pom 文件的片段:

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-site-plugin</artifactId>
                <version>3.21.0</version>
            </plugin>
        </plugins>
    </build>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>taglist-maven-plugin</artifactId>
                <version>3.2.1</version>
                <configuration>
                    <tagListOptions>
                        <tagClasses>
                            <tagClass>
                                <tags>
                                    <tag>
                                        <matchString>todo</matchString>
                                        <matchType>ignoreCase</matchType>
                                    </tag>
                                </tags>
                            </tagClass>
                        </tagClasses>
                    </tagListOptions>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>3.9.0</version>
            </plugin>
        </plugins>
    </reporting>

    <distributionManagement>
        <repository>
            <id>private-repository-release</id>
            <url>https://private.repository.com/artifactory/private-repository-release</url>
        </repository>
    </distributionManagement>

如您所见,此 jar 将被部署到私有存储库(在我的示例中为https://private.repository.com/artifactory/private-repository-release)

为了回答这个问题,我们假设这个私有存储库不需要身份验证。

  • 描述实际结果:

当mvn site在上面运行时,我确实得到了生成的 maven 网站(正在运行),但它看起来像这样(见图)

在此处输入图片描述

  • 问题

此页面缺少关于要下载的私有仓库的信息。我希望能够在网站上的 pom 文件中指明所需的仓库。

  • 描述预期结果:

我希望得到这样的结果:

在此处输入图片描述

为了告诉这个 jar 的用户,需要将存储库代码块添加到站点页面。

  <repositories>
        <repository>
            <id>private-repository-release</id>
            <url>https://private.repository.com/artifactory/private-repository-release</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>deleteme-kafka</artifactId>
            <version>2.2</version>
        </dependency>
  • 描述一下我尝试过的方法:

我尝试在 pom 中添加块,但没有成功,网站没有在“Maven 坐标”中指示所需的私有存储库。

虽然“分发管理”页面确实显示了一些有关私有存储库的信息,但它并没有告诉这个 jar 的用户如何配置 pom 来下载这个“私有 jar”。

  • 问题:

如何在“Maven 坐标”页面中添加存储库部分?

maven
  • 1 个回答
  • 22 Views
Martin Hope
PatPanda
Asked: 2025-04-06 19:42:36 +0800 CST

Jackson 反序列化枚举不区分大小写

  • 5

我想解码 Java Enum 中的普通值和数组中的小写和大写值。

我试过这段代码:

public enum FooBarEnum {
    FOO,
    BAR
}

以下 POJO 来反序列化事物:

public record Aaa(String something, FooBarEnum foobar)

public record Bbb(String something, List<FooBarEnum> foobarList)

尝试通过 HTTP 请求获取对象时:

@GetExchange("/api/test1")
Aaa getAaa(@PathVariable int key);

为此,它是有效的,无论服务器是否响应带有 FOO、foo、BAR 或 bar 的对象,它都是有效的。

但是,我有这个:

@GetExchange("/api/test2")
Bbb getBbb(@PathVariable int key);

当它是小写时,我会遇到这个异常:

JSON decoding error: Cannot deserialize value of type `com.FooBarEnum` from String "foo": not one of the values accepted for Enum class: [FOO, BAR]

[...]
Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `com.FooBarEnum` from String "foo": not one of the values accepted for Enum class: [FOO, BAR]

 at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); line: 1, column: 996] (through reference chain: com.Bbb["fooBarList"]-java.util.ArrayList[0])
    at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67) ~[jackson-databind-2.18.3.jar:2.18.3]

我甚至尝试添加

@JsonFormat(with = {JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_VALUES})

但没有运气。

有没有办法处理数组的忽略大小写?

java
  • 1 个回答
  • 60 Views
Martin Hope
PatPanda
Asked: 2025-04-03 03:34:16 +0800 CST

mvn deploy:在现有的正确 jar 上进行部署会导致artifactory 中的 jar 损坏

  • 5

我想上传并部署现有的 jar 到artifactory。

有一个来自第三方的管道,我无法控制第 1 步将构建 jar。然后将 jar 放在主机上的文件目录中。同样,我无法控制作业本身。

但是当我手动进入主机时,我可以通过执行以下命令看到 jar 是正确的jar xf thejar.jar。提取的内容将包含所有正确的类文件。

现在,我的部分,第 2 步,我正在尝试将这个 jar 上传到artifactory 中。

我知道有一个运行的选项mvn deploy,但这将运行 Maven 生命周期的所有先前步骤。由于 jar 是正确的,我想避免这种重复(运行 Maven 生命周期的所有先前步骤)并只上传 jar。

到目前为止我遇到了两个解决方案:

  1. 运行mvn deploy:deploy似乎这个解决方案不会重新运行所有内容,而只是尝试上传 jar

  2. 运行mvn jar:jar deploy:deploy相同,看来这个解决方案不会重新运行所有内容,而只是尝试上传 jar

然而,解决方案 1 会产生以下问题:

[INFO] ----------------------< com.example:mavendeploy >-----------------------
[INFO] Building mavendeploy 4.3
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- deploy:3.1.2:deploy (default-cli) @ mavendeploy ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.329 s
[INFO] Finished at: 2025-T19:26:20Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:3.1.2:deploy (default-cli) on project mavendeploy: The packaging plugin for project mavendeploy did not assign a file to the build artifact -> [Help 1]

看起来它甚至没有检测到罐子。

而第二种解决方案也会产生这个问题。

[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- jar:3.4.1:jar (default-cli) @ mavendeploy ---
[WARNING] JAR will be empty - no content was marked for inclusion!
[INFO] Building jar: /builds/path/to/jar/mavendeploy-4.3.jar
[INFO] 
[INFO] --- deploy:3.1.2:deploy (default-cli) @ mavendeploy ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

虽然它似乎可以正确检测到正确的 jar,但还是出现了这个警告,JAR will be empty而且,虽然 jar 似乎确实已上传到artifactory,但从artifactory 下载的 jar 不包含任何类文件。为什么?

将现有 jar 上传到artifactory 的正确方法是什么mvn deploy(希望不需要重新运行整个 maven 生命周期,因为 jar 已经存在)?

我在解决方案 1 或解决方案 2 中做错了什么?

java
  • 1 个回答
  • 45 Views
Martin Hope
PatPanda
Asked: 2025-02-15 03:17:00 +0800 CST

ArchUnit - 检查叶包中的文件(类、接口等)是否少于 N 个的规则

  • 4

我想要实现的是编写一个 ArchUnit 规则来确保我们的包足够小。

例如,假设这样:

natural
 ├─ goodpackage
 │  ├─ apple
 │  ├─ banana
 │  ├─ mango
 ├─ badpackage
 │  ├─ file1
 │  ├─ file2
 │  ├─ ...
 │  ├─ file10

对于此示例,假设超过 9 个文件太多,而最多 8 个文件足够小。

这也仅适用于叶包,即最底层的包(如果此包中有文件,但也有子包,则测试应针对子包)

我尝试使用该类com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes并希望找到一种在包内进行迭代的方法。但没有运气。

我还搜索了是否可以直接从 ArchUnit 获取软件包,例如:

    @Test
    void leafPackagesShouldNotHaveMoreThan9Files() {   }
        packages().that().areInSubPackages().shouldNot().have(moreThan9Files()).check(importedClasses);
    }

但也是不可能的。

如何使用 ArchUnit 检查叶包中的文件数量是否少于 N 个?

java
  • 1 个回答
  • 17 Views
Martin Hope
PatPanda
Asked: 2025-02-12 05:08:59 +0800 CST

根据属性而不是配置文件更改 Spring Security SecurityFilterChain Bean

  • 5

我想根据可配置属性来配置实际使用的 SecurityFilterChain Bean。

我们有一个相同的应用程序,它支持不同类型的安全性。

@Configuration
@EnableWebSecurity
class SecurityConfiguration {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll()).csrf(AbstractHttpConfigurer::disable);
        return httpSecurity.build();
    }

    @Bean
    public SecurityFilterChain securityFilterChainX509(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .x509()
                .subjectPrincipalRegex("CN=(.*?)(?:,|$)");
        return httpSecurity.build();
    }

    @Bean
    public SecurityFilterChain securityFilterChainJWT(HttpSecurity httpSecurity) throws Exception {
        
    }
    
    [...]

}

我在这里仅粘贴了一个示例,但请想象这个文件充满了具有多种身份验证类型的 SecurityFilterChain bean,让我们想象有 50 种。

用例是同一个应用程序的每个实例都有自己的安全配置。

例如,部署在美国的应用程序需要检查客户端证书,因此需要使用 securityFilterChainX509 bean,而部署在法国的相同应用程序需要检查用户名密码,而部署在日本的应用程序则需要另一种类型的身份验证,等等。

到目前为止,我们正在使用一种相当“奇怪”的方法,即基于配置文件的方法。

我的意思是:

    @Bean
    @Profile({"canada", "brazil"})
    SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll()).csrf(AbstractHttpConfigurer::disable);
        return httpSecurity.build();
    }

    @Bean
    @Profile({"usa", "egypt"})
    public SecurityFilterChain securityFilterChainX509(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .x509()
                .subjectPrincipalRegex("CN=(.*?)(?:,|$)");
        return httpSecurity.build();
    }

    @Bean
    @Profile({"germany"})
    public SecurityFilterChain securityFilterChainJWT(HttpSecurity httpSecurity) throws Exception {

    }

虽然这种方法有效,但也存在缺点,它要求我们:

  • 维护许多 application-profile.properties,只是为了获取正确的 bean。
  • 当我们需要改变时(今天,巴西使用不安全的,明天,它需要 JWT),我们也需要改变代码。

(如果可能的话,真的想避免使用个人资料)

问题:

有没有一种方法,没有配置文件,但具有可配置的属性,例如

@Value("${the.security.bean.to.use}")
private String configuredSecurityBeanToUse;

配置要使用的实际 SecurityFilterChain bean?

java
  • 1 个回答
  • 38 Views
Martin Hope
PatPanda
Asked: 2025-02-11 16:33:01 +0800 CST

如何创建 ArchUnit 规则来测试字段在包中是否是私有的

  • 6

我想创建一个 ArchUnit 规则,检查类是否通过公开公共字段来破坏封装。

唯一允许的公共字段应该是一个常量,类似于public static final int MAX_USERS = 100;

其他字段不应公开

我去尝试了下面的代码:

@Test
void fieldShouldAllBePrivateToProtectEncapsulation() {
    fields().should().bePrivate().check(importedClasses);
}

不幸的是,这并不起作用。

例如,它将此类标记为不好:

enum Device {
    IOS,
    LAPTOP

如何在 ArchUnit 中编写测试以确保除常量之外没有字段是公共的?

java
  • 1 个回答
  • 27 Views
Martin Hope
PatPanda
Asked: 2025-02-11 03:32:51 +0800 CST

如何排除针对接口的 ArchUnit 规则以影响 @interface(注释)

  • 4

我想编写一个 ArchUnit 测试,其内容如下:

“作为接口的类应该有一个以 Interface 结尾的名称,但不应该是@interface(它们是注释)”。

例如,这应该是可以的:

// Interface definition
interface AnimalInterface {
void animalSound(); // abstract method
void sleep(); // abstract method
}

但这不应该

// Interface definition
interface Animal {
void animalSound(); // abstract method
void sleep(); // abstract method
}

但同时(这也是我遇到问题的部分):

import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Constraint(validatedBy = SomethingValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidSomething {
    String message() default "Invalid request data";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

在本测试中不应考虑,因为它是@interface,不是interface。

我尝试通过编写以下代码来实现这一点:

@Test
void interfacesShouldHaveNamesEndingWithTheWordInterface() {
    classes().that().areInterfaces().should().haveNameMatching(".*Interface").check(importedClasses);
}

但这对于该@interface部分来说会失败。

如何增强测试以“忽略”“过滤掉”注释?

java
  • 1 个回答
  • 30 Views
Martin Hope
PatPanda
Asked: 2025-02-04 22:58:05 +0800 CST

SpringBoot @Valid 在一个字段上,基于另一个字段的值

  • 6

我想使用 SpringBoot @Valid 来验证 http 请求字段,但基于同一个 http 请求的另一个字段。

我有以下代码:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.4.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <artifactId>question</artifactId>

    <properties>
        <maven.compiler.source>23</maven.compiler.source>
        <maven.compiler.target>23</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
class FieldValidationApplication {

    public static void main(String[] args) {
        SpringApplication.run(FieldValidationApplication.class, args);
    }

}
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
class FieldValidationController {

    @PostMapping("/validate")
    String question(@Valid @RequestBody SomeRequest someRequest) {
        return "please validate the field";
    }

}

record SomeRequest(int score,
                   String fieldPositive,
                   String fieldZeroAndNegative
                   ) 
{ }

验证规则非常简单:

请求负载包含字段 score。如果字段 score 的值严格为正数,则我需要检查字段 fieldPositive 是否为有效字符串,以及 fieldZeroAndNegative 是否为 null。

例如:

{
  "score": 1,
  "fieldPositive": "thisisok"
}

但那些不是:

{
  "score": 1
}

{
  "score": 1,
  "fieldPositive": ""
}

{
  "score": 1,
  "fieldPositive": "below fieldZeroAndNegative should be null",
  "fieldZeroAndNegative": "not ok"
}

其他字段的规则类似(代码就在下面)。

这是我尝试过的,我创建了自定义注释:

record SomeRequest(int score,
                   @ValidateThisFieldOnlyIfScoreIsPositive String fieldPositive,
                   @ValidateThisFieldOnlyIfScoreIsZeroOrNegative String fieldZeroAndNegative
                   ) 
{ }

import jakarta.validation.Constraint;
import jakarta.validation.Payload;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Constraint(validatedBy = ValidateThisFieldOnlyIfScoreIsPositiveValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface ValidateThisFieldOnlyIfScoreIsPositive
{
    String message() default "Field is invalid";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}


import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

class ValidateThisFieldOnlyIfScoreIsPositiveValidator implements ConstraintValidator<ValidateThisFieldOnlyIfScoreIsPositive, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        System.out.println("hello, the value of the field fieldPositive is " + value);
        System.out.println("However, I cannot get the value of the field score");
        if (" SomeRequest score " > 0) { //how to get the value of the field score here?
            return value != null && !value.isEmpty() && value.length() > 3;
        }
        if (" SomeRequest score"  <= 0) {
            return value == null;
        }
        ...
    }

}

import jakarta.validation.Constraint;
import jakarta.validation.Payload;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Constraint(validatedBy = ValidateThisFieldOnlyIfScoreIsZeroOrNegativeValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface ValidateThisFieldOnlyIfScoreIsZeroOrNegative
{
    String message() default "Field is invalid";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

class ValidateThisFieldOnlyIfScoreIsZeroOrNegativeValidator implements ConstraintValidator<ValidateThisFieldOnlyIfScoreIsZeroOrNegative, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        System.out.println("hello, the value of the field fieldZeroAndNegative is " + value);
        System.out.println("However, I cannot get the value of the field score");
        if (" SomeRequest score " <= 0) { //how to get the value of the field score here?
            return value != null && !value.isEmpty() && value.length() > 3;
        }
        if (" SomeRequest score" > 0) {
            return value == null;
        }

    }

}

我不确定每个字段使用一个注释是否是可行的方法。

问题:

如何在验证器中获取同一请求的两个字段(或多个字段)?

java
  • 1 个回答
  • 49 Views
Martin Hope
PatPanda
Asked: 2025-01-14 05:59:10 +0800 CST

使用 spring-boot-starter-oauth2-client 将令牌传递给 Spring Framework release 6 HttpInterface @HttpExchange @GetExchange

  • 5

我正在尝试将 spring-boot-starter-oauth2-client 与新的 Spring Framework 版本 6 HttpInterface 一起使用

@Configuration
public class RestClientConfig {

    @Bean
    public RestClient restClient(OAuth2AuthorizedClientManager authorizedClientManager, RestClient.Builder restClientBuilder) {
        OAuth2ClientHttpRequestInterceptor interceptor = new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
        return restClientBuilder
                .requestInterceptor(interceptor)
                .build();
    }

}
@RestController
public class LessonsController {

    private final RestClient restClient;

    public LessonsController(RestClient restClient) {
        this.restClient = restClient;
    }

    @GetMapping("/lessons")
    public String fetchLessons() {
        return restClient.get()
                .uri("https://someserver.om/someprotectedresource")
                .attributes(clientRegistrationId("my-client"))
                .retrieve()
                .body(String.class);
    }
}
spring:
  application:
    name: client-application
  security:
    oauth2:
      client:
        registration:
          my-client:
            provider: my-provider
            client-id: ididid
            client-secret: secretsecret
            authorization-grant-type: client_credentials
            scope: download
        provider:
          my-provider:
            token-uri: https://provider.com/token

以上操作有效。我们从令牌提供商处获得了令牌确认,并从资源服务器处获得了资源并传递了令牌。这两个步骤都运行良好,很开心。

https://www.youtube.com/watch?v=aR580OCEp7w 我们现在想用新的 Spring Framework 版本 6 HttpInterface 做同样的事情

执行此操作时:

@Configuration
public class UserClientConfig {

    private final RestClient restClient;

    public UserClientConfig(OAuth2AuthorizedClientManager authorizedClientManager, RestClient.Builder restClientBuilder) {
        OAuth2ClientHttpRequestInterceptor interceptor = new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
        this.restClient = restClientBuilder
                .requestInterceptor(interceptor)
                .baseUrl("https://host.com")
                .build();
    }

    @Bean
    public UserClient userClient() {
        RestClientAdapter adapter = RestClientAdapter.create(restClient);
        return HttpServiceProxyFactory.builderFor(adapter)
                .build()
                .createClient(UserClient.class);
    }

}
@HttpExchange(
        url = "/v1",
        accept = MediaType.APPLICATION_JSON_VALUE)
public interface UserClient {

    @GetExchange("/protectedresource/full")
    public User getUserById(@RequestParam Map<String, String> key value);

}
    @GetMapping("/lessons")
    public User fetchLessons() {
        return userClient.getUserById(Map.of("foo", "bar"));
    }

使用 HttpInterface 时,这不起作用。首先不会获取令牌。可能是因为缺少 @H​​ttpExchange @GetExchange 的 .attributes(clientRegistrationId("id")),但不确定。

问题:如何将 Http 接口与 spring-boot-starter-oauth2-client token 结合?

spring-boot
  • 1 个回答
  • 45 Views
Martin Hope
PatPanda
Asked: 2025-01-09 01:33:12 +0800 CST

使用 spring-boot-starter-oauth2-client 和 RestClient 发送 grant_type 的问题

  • 4

我正在尝试使用spring-boot-starter-oauth2-client来获取承载令牌,其中服务正在接受grant_type=client_credentials但不能authorization-grant-type。

curl -s -X POST -H "Content-Type: application/x-www-form-urlencoded" -u theusername:thepassword  "https://thirdpartyservice.com/token?scope=resolve+download&grant_type=client_credentials" | jq -r '.access_token'

这会起作用,我们能够获得令牌。

按照 Spring Security 的文档,我正在配置:

spring:
  application:
    name: client-application
  security:
    oauth2:
      client:
        registration:
          my-client:
            provider: the-provider
            client-id: theusername
            client-secret: thepassword
            authorization-grant-type: client_credentials
            #grant_type: client_credentials
            scope: resolve+download
        provider:
          the-provider:
            token-uri: https://thirdpartyservice.com/token
logging:
  level:
    root: DEBUG
@Configuration
public class RestClientConfig {

    @Bean
    public RestClient restClient(OAuth2AuthorizedClientManager authorizedClientManager) {
        OAuth2ClientHttpRequestInterceptor interceptor = new OAuth2ClientHttpRequestInterceptor(authorizedClientManager);
        return RestClient.builder()
                .requestInterceptor(interceptor)
                .build();
    }

}
return restClient.get()
                .uri("https://resource...")
                .attributes(clientRegistrationId("my-client"))
                .retrieve()
                .body(String.class);

不幸的是,这不起作用,令牌提供者返回 400 错误,因为它是预期的grant_type(授予下划线类型)。

但似乎 Spring Security 只提供“授权授予类型”

如何grant_type使用RestClient和传递spring-boot-starter-oauth2-client?

java
  • 1 个回答
  • 37 Views
Martin Hope
PatPanda
Asked: 2024-12-06 06:08:03 +0800 CST

IntelliJ - 将 mvn clean install 变成一个按钮

  • 5

我正在使用 IntelliJ 开发 java maven 项目。

为了编译项目及其依赖项,我使用了很多mvn clean install

每次,我都会单击此图标上的 UI,然后单击重新加载(请参阅屏幕截图)

我尝试将此操作绑定到键盘或鼠标上的按钮。

但是,我找不到它是哪一个动作。

我能找到最接近的方法是绑定“运行配置”,但是,这并没有考虑到所有内容(屏幕截图中的所有步骤)

在此处输入图片描述

问题:

如何绑定mvn clean install到按钮?

maven
  • 1 个回答
  • 20 Views
Martin Hope
PatPanda
Asked: 2024-12-03 06:23:08 +0800 CST

SpringBoot Enum Class WebApplicationType 的用途是什么

  • 5

Spring 有一份关于 WebApplicationType 的官方文档

https://docs.spring.io/spring-boot/api/java/org/springframework/boot/WebApplicationType.html

应用层可以选择设置:

NONE
The application should not run as a web application and should not start an embedded web server.
REACTIVE
The application should run as a reactive web application and should start an embedded reactive web server.
SERVLET
The application should run as a servlet-based web application and should start an embedded servlet web server.

我无意中忘记设置spring.main.web-application-type=reactive我的 spring webflux 应用程序。

我还无意中忘记设置spring.main.web-application-type=servlet我的 spring mvc 应用程序。

但是,它们都能够处理请求,应用程序正常运行,一切似乎都很好。

因此,我有一个疑问,这个 WebApplicationType 的目的是什么?它似乎什么也没做

spring
  • 1 个回答
  • 27 Views
Martin Hope
PatPanda
Asked: 2024-11-05 05:34:11 +0800 CST

如何使用 Reactor Kafka KafkaSender API 将消息发送到两个不同的主题(位于两个不同的 Kafka 集群中)?

  • 5

我正在尝试使用 Reactor Kafka 的 KafkaSender 向两个不同的 kafka 主题发送消息。

我所说的两个不同的 kafka 主题是指:集群 kafka-first-broker.com:9092 中有一个名为“first_topic”的主题,然后,在另一个集群中,有另一个名为“another_topic”的主题,与上面的不一样,名为 kafka-another-broker-not-the-same-as-above.com:9093

但是,似乎sendReactor Kafka 的方法仅支持一个目的地

我尝试使用发送方法发送以逗号分隔的列表(两个主题)

SenderRecord.create(new ProducerRecord<>("first_topic,another_topic", null, mymessage), mymessage)

我原本期望将其发送到两个不同的主题,但它只能发送到一个。

如何利用 Reactor Kafka KafkaSender API 将消息发送到位于两个不同 Kafka 集群中的两个不同主题?

java
  • 1 个回答
  • 16 Views
Martin Hope
PatPanda
Asked: 2024-07-15 17:30:56 +0800 CST

问题重构 if-else-if string.contains(“X”) 以切换大小写(或更好)

  • 4
  • 包括有关您的目标的详细信息:

我想重构if-else-if string.contains("X")Java 中的语句来切换大小写或 Map。

  • 显示一些代码:

我有一段代码,非常简单,如下所示:

     public String question(String sentence) {
        if (sentence.contains("eat")) {
            return getFoodFromSentence(sentence);
        } else if (sentence.contains("drink")) {
            return getBeverageFromSentence(sentence);
        } else if (sentence.contains("drive")) {
            return getVehicleFromSentence(sentence);
        } else if (sentence.contains("travel")) {
            return getDestinationFromSentence(sentence);
    [...
        many many other else if
    ...]
        } else {
            return "sentence with unknown verb";
        }
    }

    private String getDestinationFromSentence(String sentence) {
        return ""; //some complex code to extract some info from the sentence
    }

    private String getVehicleFromSentence(String sentence) {
        return ""; //some complex code to extract some info from the sentence
    }
[... all the other actual handling methods ]

我希望使用 switch case 来重构它:

  • 描述一下我的尝试:

使用 switch case:

   public String question(String sentence) {
        switch (???) { //issue here, I am not able to come up with the expression
            case (sentence.contains("eat")): // issue here, I am not able to have the cases representing the if
                return getFoodFromSentence(sentence);
            case (sentence.contains("drink")):
                return getBeverageFromSentence(sentence);
            case (sentence.contains("drive")):
                return getVehicleFromSentence(sentence);
            case (sentence.contains("travel")):
                return getDestinationFromSentence(sentence);
        [ ... the other case conditions ... ]
            default:
                return "sentence with unknown verb";
        }
    }

我也尝试使用 Map 模式,例如:

 public String question(String sentence) {
        Map<Predicate<String>, Function<String, String>> map =
                Map.of(s -> s.contains("eat"), s -> getFoodFromSentence(s),
                        s -> s.contains("drink"), s -> getBeverageFromSentence(s),
                        s -> s.contains("drive"), s -> getVehicleFromSentence(s),
                        s -> s.contains("travel"), s -> getDestinationFromSentence(s));
        return map.get(???).apply(sentence); // issue here, how to get the correct key of the map?
    }
  • 问题:

请问使用 switch case 的问题该如何解决?

或者也许如何解决地图问题?

还有其他技术可以重构这个吗 if-else-if string.contains("X")?

java
  • 3 个回答
  • 85 Views
Martin Hope
PatPanda
Asked: 2024-04-12 08:10:53 +0800 CST

如何让 stageB 中的一个 jobB 仅在 stageA 中的所有作业完成后才运行

  • 5
  • 包括有关您的目标的详细信息:

我希望仅当 stageA 中的所有作业都完成时,stageB 中的一个 jobB 才能运行。

stageA  stageB
job01A  jobB
job02A
...
job58A
  • 我尝试了什么:

为了实现这个结果,我目前使用关键字“needs”,它正在工作,但是 gitlab ci yml 现在看起来像这样:

jobB
  stage: stageB
  needs:
    - job: job01A
    - job: job02A
       ...
    - job: job58A

这个列表或者数组都很长。

  • 问题:

我怎样才能编写一些东西来告诉 jobB 仅当 stageA 中的所有作业都完成时才运行,而不需要显式地编写每个作业?就像是:

jobB
  stage: stageB
  needs:
    - all jobs from stageA
  • 1 个回答
  • 13 Views
Martin Hope
PatPanda
Asked: 2023-12-20 22:17:05 +0800 CST

构建 Loki 仪表板以进行日志计数

  • 5

我正在尝试构建代表 Loki(而不是 Prometheus)中信息日志数量的 Grafana 仪表板。基本上,我想实现这一目标:

在此输入图像描述

我四处搜索,似乎可以使用 Prometheus 的指标来构建那些具有 Prometheus指标的logback_events指标。

实际上,上面的仪表板使用的是 Prometheus 数据,而logback_events不是 Loki 数据。

然而,我的应用程序没有发送任何指标,只是记录到 Loki。因此,我不能依赖类型指标logback_events来构建此仪表板。

示例日志如下所示:

{
"name": "mycoolapp"
"pid": "1",
"level": "INFO",
"thread": "somethread",
"class": "SomeClass",
"traceId": "6170ea9877f59d050a13feaffc145d88"
"spanId": "6729eec142171c8f"
"message": "somecoolmessage"
}

有没有办法从 Loki 获取信息、错误、警告和调试日志的数量?如何使用 Loki(而不是 Prometheus)数据构建类似的仪表板?

grafana
  • 1 个回答
  • 55 Views
Martin Hope
PatPanda
Asked: 2023-12-12 00:12:29 +0800 CST

警告:带有 javadoc 的 java 21 中的字段没有 @param

  • 6
  • 我想要实现的目标:

为非常简单的 java 21 记录生成 javadoc。

  • 我尝试了什么:

我有这么简单的记录:

/**
 * The type Some record.
 */
public record SomeRecord(String someField) {
}

和这个pom:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <configuration>
        <outputDirectory>target/javadoc</outputDirectory>
        <reportOutputDirectory>target/javadoc</reportOutputDirectory>
        <javadocExecutable>${java.home}/bin/javadoc</javadocExecutable>
    </configuration>
</plugin>

我正在运行这个 Maven 命令:

mvn clean install site -U javadoc:javadoc
  • 问题:

100% 可重复,我明白了:

SomeRecord.java:6: warning: no @param for someField
[WARNING] public record SomeRecord(String someField) {
[WARNING] ^
  • 问题:

这段代码有什么问题?这是什么@param?我记得Spring的@Param,但是@param(小写?)如何在没有javadoc的情况下正确生成?

java
  • 1 个回答
  • 30 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve