早上好,我目前正在使用 Quarkus 和 Apache Camel,我正在处理器中使用 application.properties 中的变量,我尝试使用 @ConfigProperty 注释将其引入,但它给了我一个空错误,这这就是我的配置方式:
该变量称为 加密密钥
UserProfileProcessorUserIdParamReq
@ApplicationScoped
@Slf4j
public class UserProfileProcessorUserIdParamReq implements Processor {
@ConfigProperty(name="aes.encrypt.key")
String encryptionKey;
private final IValidationFieldsUserID validationFields;
public UserProfileProcessorUserIdParamReq() {
validationFields = new ValidationFieldsUserID();
}
@Override
public void process(Exchange exchange) throws Exception {
String documentType;
String documentNumber;
String userId;
String correlatorId;
String tokenInfo;
String userIdDecodedBase64;
String userIdDecrypt;
try {
correlatorId= Optional.ofNullable(exchange.getIn().getHeader("x-correlator")).map(Object::toString).orElse("");
exchange.setProperty("correlatorId",correlatorId);
userId = exchange.getIn().getHeader("user_id").toString();
tokenInfo= Optional.ofNullable(exchange.getIn().getHeader("x-token-info")).map(Object::toString).orElse("");
validationFields.validateUserId(exchange);
userId=validateUserIdValue(userId, tokenInfo);
exchange.setProperty("userIdEncrypt", userId);
userIdDecodedBase64= EncodeBase64.decrypt(userId);
log.info("userIdDecodedBase64" + userIdDecodedBase64);
userIdDecrypt= EncryptUtil.decrypt(userIdDecodedBase64,encryptionKey);
exchange.setProperty("userId", userIdDecrypt);
validateTokenInfo(exchange,userId, tokenInfo);
validateUserIdDecrypt(userIdDecrypt);
documentType = userIdDecrypt.split("-")[0];
documentNumber = userIdDecrypt.split("-")[1];
exchange.setProperty("documentType", documentType);
exchange.setProperty("documentNumber", documentNumber);
exchange.setProperty("isSearchByQueryParam","false");
} catch (RequiredValueException | NullPointerException e) {
throw new RequiredValueException(e.getMessage());
}
catch (NotFoundDataException e) {
throw new NotFoundDataException(e.getMessage());
}
catch (PermissionDeniedException e) {
throw new PermissionDeniedException(e.getMessage());
}
catch (Exception e){
if( e.getMessage().contains("Input byte array"))
throw new NotFoundDataException(e.getMessage());
throw new Exception(e.getMessage());
}
}
private static void validateTokenInfo(Exchange exchange, String userId, String tokenInfoValidated) {
if (!tokenInfoValidated.isEmpty()) {
log.info("Valor del x-token-info: {}", tokenInfoValidated);
/* Se obtiene el Objeto JSON con el valor del campo x-token-info */
JSONObject jsonObject = new JSONObject(tokenInfoValidated);
/*String subValue=jsonObject.get("sub").toString(); */
/* Mediante el optString obtenemos el valor sub si viene (token 3 patas) o no viene (token 2 patas), para este ultimo caso el valor es vacio */
String subValue = jsonObject.optString("sub");
log.info("Valor sub que esta llegando en el valor x-token-info: {}", subValue);
if (!subValue.isEmpty()) {
if(!subValue.equals(userId)) {
throw new PermissionDeniedException("Error validando el campo sub de la autenticacion en el campo x-token-info, no hace match con userId enviado");
}
}
}
}
/* Se valida que el UserId sea un valor valido para venezuela, sea enviado cifrado o no*/
private static void validateUserIdDecrypt (String userId) {
if(!Pattern.matches("^(CI|RIF|P|CD|NIT)(-).*",userId)){
throw new NotFoundDataException("UserId enviado esta en formato incorrecto");
}
}
/*Se valida el valor del campo UserId, si el mismo pudiera contener el valor de me, en este caso se debe extraer el valor de UserId del json token-info, en especifico del campo sub */
private String validateUserIdValue(String userId,String tokenInfo) {
if(userId.equals("me")){
if(!tokenInfo.isEmpty()){
JSONObject jsonObject = new JSONObject(tokenInfo);
userId = jsonObject.optString("sub");
}
else {
throw new RequiredValueException("Se requiere parametro x-token-info (autenticacion 3 patas) para campo userId=me");
}
}
return userId;
}
}
这是它给出的错误:
14:52:44 INFO traceId=2a0a8e8cd93ddb947e2ab7206ef4f25d, parentId=, spanId=394c6d08dec8d551, sampled=true [route23] (vert.x-worker-thread-0) [2024-07-01 14:52:44.0] Descripcion de la Exception: Cannot invoke "String.getBytes()" because "key" is null
这就是我的 application.properties 中的情况:
aes.encrypt.key=${AES_ENCRYPT_KEY:xxxxxxxxxxxx}
就像从 ResRoute 调用没有构造函数的处理器一样:
from("direct:usersQueryParam")
/*.removeHeaders("CamelHttp*") */
.doTry()
.process(new UserProfileProcessorQueryParamReq())
.choice()
/* code */
我该怎么做才能让它采用@ConfigProperty的值?
我认为它不起作用,因为您正在手动创建
Processor
。尝试将 encryptionKey
作为构造函数参数传递,并将 @ConfigProperty
移动到路线构建器:
UserProfileProcessorUserIdParamReq
@Slf4j
public class UserProfileProcessorUserIdParamReq implements Processor {
private String encryptionKey;
private final IValidationFieldsUserID validationFields;
public UserProfileProcessorUserIdParamReq(String encryptionKey) {
validationFields = new ValidationFieldsUserID();
this.encryptionKey = encryptionKey;
}
@Override
public void process(Exchange exchange) throws Exception {
String documentType;
String documentNumber;
String userId;
String correlatorId;
String tokenInfo;
String userIdDecodedBase64;
String userIdDecrypt;
try {
correlatorId= Optional.ofNullable(exchange.getIn().getHeader("x-correlator")).map(Object::toString).orElse("");
exchange.setProperty("correlatorId",correlatorId);
userId = exchange.getIn().getHeader("user_id").toString();
tokenInfo= Optional.ofNullable(exchange.getIn().getHeader("x-token-info")).map(Object::toString).orElse("");
validationFields.validateUserId(exchange);
userId=validateUserIdValue(userId, tokenInfo);
exchange.setProperty("userIdEncrypt", userId);
userIdDecodedBase64= EncodeBase64.decrypt(userId);
log.info("userIdDecodedBase64" + userIdDecodedBase64);
userIdDecrypt= EncryptUtil.decrypt(userIdDecodedBase64,encryptionKey);
exchange.setProperty("userId", userIdDecrypt);
validateTokenInfo(exchange,userId, tokenInfo);
validateUserIdDecrypt(userIdDecrypt);
documentType = userIdDecrypt.split("-")[0];
documentNumber = userIdDecrypt.split("-")[1];
exchange.setProperty("documentType", documentType);
exchange.setProperty("documentNumber", documentNumber);
exchange.setProperty("isSearchByQueryParam","false");
} catch (RequiredValueException | NullPointerException e) {
throw new RequiredValueException(e.getMessage());
}
catch (NotFoundDataException e) {
throw new NotFoundDataException(e.getMessage());
}
catch (PermissionDeniedException e) {
throw new PermissionDeniedException(e.getMessage());
}
catch (Exception e){
if( e.getMessage().contains("Input byte array"))
throw new NotFoundDataException(e.getMessage());
throw new Exception(e.getMessage());
}
}
private static void validateTokenInfo(Exchange exchange, String userId, String tokenInfoValidated) {
if (!tokenInfoValidated.isEmpty()) {
log.info("Valor del x-token-info: {}", tokenInfoValidated);
/* Se obtiene el Objeto JSON con el valor del campo x-token-info */
JSONObject jsonObject = new JSONObject(tokenInfoValidated);
/*String subValue=jsonObject.get("sub").toString(); */
/* Mediante el optString obtenemos el valor sub si viene (token 3 patas) o no viene (token 2 patas), para este ultimo caso el valor es vacio */
String subValue = jsonObject.optString("sub");
log.info("Valor sub que esta llegando en el valor x-token-info: {}", subValue);
if (!subValue.isEmpty()) {
if(!subValue.equals(userId)) {
throw new PermissionDeniedException("Error validando el campo sub de la autenticacion en el campo x-token-info, no hace match con userId enviado");
}
}
}
}
/* Se valida que el UserId sea un valor valido para venezuela, sea enviado cifrado o no*/
private static void validateUserIdDecrypt (String userId) {
if(!Pattern.matches("^(CI|RIF|P|CD|NIT)(-).*",userId)){
throw new NotFoundDataException("UserId enviado esta en formato incorrecto");
}
}
/*Se valida el valor del campo UserId, si el mismo pudiera contener el valor de me, en este caso se debe extraer el valor de UserId del json token-info, en especifico del campo sub */
private String validateUserIdValue(String userId,String tokenInfo) {
if(userId.equals("me")){
if(!tokenInfo.isEmpty()){
JSONObject jsonObject = new JSONObject(tokenInfo);
userId = jsonObject.optString("sub");
}
else {
throw new RequiredValueException("Se requiere parametro x-token-info (autenticacion 3 patas) para campo userId=me");
}
}
return userId;
}
}
MyRouteBuilder.java
@ApplicationScoped
public class MyRouteBuilder extends RouteBuilder {
@ConfigProperty(name="aes.encrypt.key")
private String encryptionKey;
@Override
public void configure() throws Exception {
from("direct:usersQueryParam")
/*.removeHeaders("CamelHttp*") */
.doTry()
.process(new UserProfileProcessorQueryParamReq(encryptionKey))
.choice()
/* code */
}
}