direct_x_34
direct_x_34
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 11/22/2024 in #java-help
Docker Issue in Spring Boot with Couchbase
I try to run my app as Spring Boot with Couchbase on Docker Here is my docker-compose.yml
version: '3.9'
services:
couchbase:
image: couchbase:latest
container_name: couchbase
ports:
- 8091:8091
- 8092:8092
- 8093:8093
- 8094:8094
- 11210:11210
environment:
COUCHBASE_ADMINISTRATOR_USERNAME: ${COUCHBASE_USERNAME:-Administrator}
COUCHBASE_ADMINISTRATOR_PASSWORD: ${COUCHBASE_PASSWORD:-123456}
COUCHBASE_BUCKET: ${COUCHBASE_BUCKET:-todo_list}
COUCHBASE_AUTO_INDEX: true
volumes:
- ~/couchbase/node1:/opt/couchbase/var
healthcheck:
test: [ "CMD", "curl", "-f", "http://localhost:8091/ui/index.html" ]
interval: 30s
timeout: 10s
retries: 5
networks:
- my_network

todowithcouchbase:
build: .
container_name: todowithcouchbase
ports:
- 2323:2323
depends_on:
couchbase:
condition: service_healthy
environment:
COUCHBASE_BUCKET: ${COUCHBASE_BUCKET:-todo_list}
COUCHBASE_USER: ${COUCHBASE_USERNAME:-Administrator}
COUCHBASE_PASSWORD: ${COUCHBASE_PASSWORD:-123456}
COUCHBASE_PORT: 8091
COUCHBASE_HOST: "couchbase"
networks:
- my_network

networks:
my_network:
driver: bridge
version: '3.9'
services:
couchbase:
image: couchbase:latest
container_name: couchbase
ports:
- 8091:8091
- 8092:8092
- 8093:8093
- 8094:8094
- 11210:11210
environment:
COUCHBASE_ADMINISTRATOR_USERNAME: ${COUCHBASE_USERNAME:-Administrator}
COUCHBASE_ADMINISTRATOR_PASSWORD: ${COUCHBASE_PASSWORD:-123456}
COUCHBASE_BUCKET: ${COUCHBASE_BUCKET:-todo_list}
COUCHBASE_AUTO_INDEX: true
volumes:
- ~/couchbase/node1:/opt/couchbase/var
healthcheck:
test: [ "CMD", "curl", "-f", "http://localhost:8091/ui/index.html" ]
interval: 30s
timeout: 10s
retries: 5
networks:
- my_network

todowithcouchbase:
build: .
container_name: todowithcouchbase
ports:
- 2323:2323
depends_on:
couchbase:
condition: service_healthy
environment:
COUCHBASE_BUCKET: ${COUCHBASE_BUCKET:-todo_list}
COUCHBASE_USER: ${COUCHBASE_USERNAME:-Administrator}
COUCHBASE_PASSWORD: ${COUCHBASE_PASSWORD:-123456}
COUCHBASE_PORT: 8091
COUCHBASE_HOST: "couchbase"
networks:
- my_network

networks:
my_network:
driver: bridge
I already install couchbase in my local computer. I got this error shown below
This is expected if the there is no DNS SRV record associated with the hostname in the connection string. Will now try to bootstrap directly from the given hostname. To suppress this message, specify an IP address instead of a hostname (for example: 127.0.0.1 instead of localhost), specify more than one hostname, or set the `io.enableDnsSrv` client setting to false.
This is expected if the there is no DNS SRV record associated with the hostname in the connection string. Will now try to bootstrap directly from the given hostname. To suppress this message, specify an IP address instead of a hostname (for example: 127.0.0.1 instead of localhost), specify more than one hostname, or set the `io.enableDnsSrv` client setting to false.
How can I fix it?
57 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 11/9/2024 in #java-help
Spring Boot with Couchbase running as TestContainer Issue
Can you help me how to fix the issue?
6 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 9/24/2024 in #java-help
Spring Boot - PrePersist and PreUpdate for Couchbase
I try to implement an example of Spring Boot with the usage Couchbase I have no idea how to implement PrePersist and PreUpdate for Couchbase Here are my codes shown below
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Document
public class BaseEntity {

@Id
private String id;

@Field(name = "createdAt")
private LocalDateTime createdAt;

@Field(name = "createdBy")
private String createdBy;

@Field(name = "updatedAt")
private LocalDateTime updatedAt;

@Field(name = "updatedBy")
private String updatedBy;

@PrePersist
public void prePersist() {
this.createdBy = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::getPrincipal)
.filter(user -> !"anonymousUser".equals(user))
.map(Jwt.class::cast)
.map(jwt -> jwt.getClaim(TokenClaims.USER_EMAIL.getValue()).toString())
.orElse("anonymousUser");
this.createdAt = LocalDateTime.now();
}

@PreUpdate
public void preUpdate() {
this.updatedBy = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::getPrincipal)
.filter(user -> !"anonymousUser".equals(user))
.map(Jwt.class::cast)
.map(jwt -> jwt.getClaim(TokenClaims.USER_EMAIL.getValue()).toString())
.orElse("anonymousUser");
this.updatedAt = LocalDateTime.now();
}

}
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Document
public class BaseEntity {

@Id
private String id;

@Field(name = "createdAt")
private LocalDateTime createdAt;

@Field(name = "createdBy")
private String createdBy;

@Field(name = "updatedAt")
private LocalDateTime updatedAt;

@Field(name = "updatedBy")
private String updatedBy;

@PrePersist
public void prePersist() {
this.createdBy = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::getPrincipal)
.filter(user -> !"anonymousUser".equals(user))
.map(Jwt.class::cast)
.map(jwt -> jwt.getClaim(TokenClaims.USER_EMAIL.getValue()).toString())
.orElse("anonymousUser");
this.createdAt = LocalDateTime.now();
}

@PreUpdate
public void preUpdate() {
this.updatedBy = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::getPrincipal)
.filter(user -> !"anonymousUser".equals(user))
.map(Jwt.class::cast)
.map(jwt -> jwt.getClaim(TokenClaims.USER_EMAIL.getValue()).toString())
.orElse("anonymousUser");
this.updatedAt = LocalDateTime.now();
}

}
4 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 8/10/2024 in #java-help
Spring Boot Cache - Cannot Get the value
Here is my application yaml file
exchange-api:
cache-name: exchanges
cache-ttl: 10000 # 10 seconds
exchange-api:
cache-name: exchanges
cache-ttl: 10000 # 10 seconds
Here is the method
@CacheEvict(allEntries = true, cacheNames = "${exchange-api.cache-name}")
@PostConstruct
@Scheduled(fixedRateString = "${exchange-api.cache-ttl}")
public void clearCache() {
logger.info("Caches are cleared");
}
@CacheEvict(allEntries = true, cacheNames = "${exchange-api.cache-name}")
@PostConstruct
@Scheduled(fixedRateString = "${exchange-api.cache-ttl}")
public void clearCache() {
logger.info("Caches are cleared");
}
Here is the error
java.lang.IllegalArgumentException: Cannot find cache named '${exchange-api.cache-name}' for Builder[public void com.example.demo.controller.Controller.clearCache()] caches=[${exchange-api.cache-name}] | key='' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='',true,false
Here is the error
java.lang.IllegalArgumentException: Cannot find cache named '${exchange-api.cache-name}' for Builder[public void com.example.demo.controller.Controller.clearCache()] caches=[${exchange-api.cache-name}] | key='' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='',true,false
How can I fix it as I get the value as ${exchange-api.cache-name} from application.yaml file? I hope you can help me?
4 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 7/16/2024 in #java-help
Spring Boot Microservices with JWT Issues
I try to implement an example of Spring Boot Microservices with JWT. I have some problems following: 1 ) I cannot run all integration tests of product service even if I defined bearer token 2 ) After login and get access token, I cannot send any request to product service. I got 500 Internal Server Error. How can I fix it? I hope you can help me? Here is the repo : https://github.com/Rapter1990/springbootmicroserviceswithsecurity
140 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 3/20/2024 in #java-help
Spring Security - Cannot run logout Integration Test returns 404
No description
4 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 3/11/2024 in #java-help
Cannot set any value LocalDateTime in Entity of Spring Boot Example
I have a problem to set LocalDateTime.now to the entity of Spring Boot Example Here is the entity shown below
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "PARK")
public class ParkEntity extends BaseEntity {

...

@Column(name = "CHECK_IN")
private LocalDateTime checkIn;


....
}
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "PARK")
public class ParkEntity extends BaseEntity {

...

@Column(name = "CHECK_IN")
private LocalDateTime checkIn;


....
}
Here is the BaseEntity shown below
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@MappedSuperclass
public abstract class BaseEntity {

@Column(name = "CREATED_USER")
protected String createdUser;

@Column(name = "CREATED_AT")
protected LocalDateTime createdAt;

@Column(name = "UPDATED_USER")
protected String updatedUser;

@Column(name = "UPDATED_AT")
protected LocalDateTime updatedAt;

@PrePersist
public void prePersist() {
this.createdUser = getUsernameFromAuthentication();
this.createdAt = LocalDateTime.now();
}

@PreUpdate
public void preUpdate() {
this.updatedUser = getUsernameFromAuthentication();
this.updatedAt = LocalDateTime.now();
}

...
}
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@MappedSuperclass
public abstract class BaseEntity {

@Column(name = "CREATED_USER")
protected String createdUser;

@Column(name = "CREATED_AT")
protected LocalDateTime createdAt;

@Column(name = "UPDATED_USER")
protected String updatedUser;

@Column(name = "UPDATED_AT")
protected LocalDateTime updatedAt;

@PrePersist
public void prePersist() {
this.createdUser = getUsernameFromAuthentication();
this.createdAt = LocalDateTime.now();
}

@PreUpdate
public void preUpdate() {
this.updatedUser = getUsernameFromAuthentication();
this.updatedAt = LocalDateTime.now();
}

...
}
Here is the method shown below
private Park parkMethod(....) {
ParkEntity parkEntity = ....
parkEntity.setCheckIn(LocalDateTime.now());
ParkEntity savedPark = parkRepository.save(parkEntity);
return parkEntityToParkMapper.map(savedPark);
}
private Park parkMethod(....) {
ParkEntity parkEntity = ....
parkEntity.setCheckIn(LocalDateTime.now());
ParkEntity savedPark = parkRepository.save(parkEntity);
return parkEntityToParkMapper.map(savedPark);
}
I have also other entities extending from BaseEntity. I get null value in checkIn of savedPark . I have to manually set the LocalDateTime.now() instead of using @Builder.Default How can I do that?
6 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 3/10/2024 in #java-help
Cannot set any value LocalDateTime in Entity of Spring Boot Example
I have a problem to set LocalDateTime.now to the entity of Spring Boot Example Here is the entity shown below
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "PARK")
public class ParkEntity extends BaseEntity {

...

@Column(name = "CHECK_IN")
private LocalDateTime checkIn;


....
}
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "PARK")
public class ParkEntity extends BaseEntity {

...

@Column(name = "CHECK_IN")
private LocalDateTime checkIn;


....
}
Here is the method shown below
private Park parkMethod(....) {
ParkEntity parkEntity = ....
parkEntity.setCheckIn(LocalDateTime.now());
ParkEntity savedPark = parkRepository.save(parkEntity);
return parkEntityToParkMapper.map(savedPark);
}
private Park parkMethod(....) {
ParkEntity parkEntity = ....
parkEntity.setCheckIn(LocalDateTime.now());
ParkEntity savedPark = parkRepository.save(parkEntity);
return parkEntityToParkMapper.map(savedPark);
}
I get null value in checkIn of savedPark . I have to manually set the LocalDateTime.now() instead of using @Builder.Default How can I do that?
12 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 2/20/2024 in #java-help
How to get array info from column in Spring Boot JPA (exception Dialect mapping for JDBC type Error)
I have a problem to get ["role1","role2","role3"] from roles column. Here is the entity shown below
@Entity
public class User {
//...

@Column(columnDefinition = "text[]")
@Type(type = "com.baeldung.hibernate.arraymapping.CustomStringArrayType")
private String[] roles;

// getters and setters
}
@Entity
public class User {
//...

@Column(columnDefinition = "text[]")
@Type(type = "com.baeldung.hibernate.arraymapping.CustomStringArrayType")
private String[] roles;

// getters and setters
}
Here is the JPARepository shown below
public interface UserRepository extends JpaRepository<User, Long> {

@Query(value = "SELECT DISTINCT unnest(u.roles)::text FROM User u", nativeQuery = true)
List<String> findDistinctRoles();
}
public interface UserRepository extends JpaRepository<User, Long> {

@Query(value = "SELECT DISTINCT unnest(u.roles)::text FROM User u", nativeQuery = true)
List<String> findDistinctRoles();
}
I got nested exception Dialect mapping for JDBC type? How can I fix it?
15 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 12/29/2023 in #java-help
Spring Boot with Kubernetes Java Client API - Edit Namespace
Here is the EditNamespaceRequest shown below
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class EditNamespaceRequest {
private String name;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class EditNamespaceRequest {
private String name;
}
Here is the updateNamespace method of my Service
public V1Namespace updateNamespace(String currentName, EditNamespaceRequest editNamespaceRequest) throws ApiException {

try {
// Retrieve the existing namespace
V1Namespace existingNamespace = coreV1Api.readNamespace(currentName, null);

// Update the existing namespace with the new values
existingNamespace.metadata(new V1ObjectMeta().name(editNamespaceRequest.getName()));

// Perform the update
coreV1Api.replaceNamespace(currentName, existingNamespace, null, null, null,null);

return existingNamespace;
} catch (ApiException e) {
// Handle API exception (e.g., namespace not found, permission issues, etc.)
throw new RuntimeException("Failed to update namespace: " + e.getResponseBody(), e);
}

}
public V1Namespace updateNamespace(String currentName, EditNamespaceRequest editNamespaceRequest) throws ApiException {

try {
// Retrieve the existing namespace
V1Namespace existingNamespace = coreV1Api.readNamespace(currentName, null);

// Update the existing namespace with the new values
existingNamespace.metadata(new V1ObjectMeta().name(editNamespaceRequest.getName()));

// Perform the update
coreV1Api.replaceNamespace(currentName, existingNamespace, null, null, null,null);

return existingNamespace;
} catch (ApiException e) {
// Handle API exception (e.g., namespace not found, permission issues, etc.)
throw new RuntimeException("Failed to update namespace: " + e.getResponseBody(), e);
}

}
I have a problem to update Namespace by name through Kubernetes Java Client API. this error message is shown below when I run
{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"the name of the object (kupeteer-namespace-update) does not match the name on the URL (kupeteer-namespace-new)","reason":"BadRequest","code":400}
{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"the name of the object (kupeteer-namespace-update) does not match the name on the URL (kupeteer-namespace-new)","reason":"BadRequest","code":400}
How can I fix it?
4 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 12/5/2023 in #java-help
How to use OAuth2 in Spring Cloud Gateway as a best practise
I've done some research on the topic. After connecting to the Kubernetes environment with a token and URL, I thought I could integrate OAuth2 with Spring Cloud Gateway directly. What is the best practice for this? Should I structure it as an Auth Service, User Service, and Gateway to progress more easily? Do you know any resources related to this?
4 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 12/1/2023 in #java-help
Spring Cloud OAuth2 with Kubernetes
Hi, How's it going? I have a question to you if you can help me. I'm using the Kubernetes Java Client API to connect to your company's Kubernetes environment. I have URL and token information in that connection. I want to manage authentication and authorization using Spring OAuth2 Server in a microservices-based application. How can I achieve this?
5 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 11/30/2023 in #java-help
Spring Cloud with OAuth2 in Kubernetes
Hi, How's it going? I have a question to you if you can help me. I'm using the Kubernetes Java Client API to connect to your company's Kubernetes environment. I have URL and token information in that connection. I want to manage authentication and authorization using Spring OAuth2 Server in a microservices-based application. How can I achieve this?
10 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 5/21/2023 in #java-help
Cannot detect API key from .env in my Spring Boot App
I want to create an app to use API Layer for currency exchange. I used a API key of Exchange Rates Data API in apilayer.com. When I send a request to Get Rates defined in postman_collection in my repo. I get this error message shown below
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "message" (class com.exchangeapi.currencyexchange.exception.RestTemplateError), not marked as ignorable (4 known properties: "error", "status", "path", "timestamp"]) at [Source: (String)"{"message":"No API key found in request"}"; line: 1, column: 42] (through reference chain: com.exchangeapi.currencyexchange.exception.RestTemplateError["message"])
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "message" (class com.exchangeapi.currencyexchange.exception.RestTemplateError), not marked as ignorable (4 known properties: "error", "status", "path", "timestamp"]) at [Source: (String)"{"message":"No API key found in request"}"; line: 1, column: 42] (through reference chain: com.exchangeapi.currencyexchange.exception.RestTemplateError["message"])
Here is the link : https://stackoverflow.com/questions/76300394/cannot-detect-api-key-from-env-in-my-spring-boot-app How can I fix it?
4 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 5/19/2023 in #java-help
Cannot invoke "org.springframework.data.domain.Page.getContent()" for Junit Test with the usage of S
4 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 5/4/2023 in #java-help
How to write Integration Test with the usage of Bearer Token in Spring Boot (throw An Authentication
I have a problem to write Integration Test in my Spring Boot example. In my UserController class, every methods are defined with PreAuthorize with roles. Here is the link : https://stackoverflow.com/questions/76172699/how-to-write-integration-test-with-the-usage-of-bearer-token-in-spring-boot-thr
6 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 5/4/2023 in #java-help
How to write Integration Test with the usage of Bearer Token in Spring Boot (throw An Authentication
I have a problem to write Integration Test in my Spring Boot example. In my UserController class, every methods are defined with PreAuthorize with roles. Here is the link : https://stackoverflow.com/questions/76172699/how-to-write-integration-test-with-the-usage-of-bearer-token-in-spring-boot-thr
4 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 4/1/2023 in #java-help
com.google.zxing.NotFoundException Spring Boot QR Code Example JUnit Tests
I tried to implement an example of QR Code Generator in Spring Boot. I have a problem in Service Test and Controller Test. In Service Test, I cannot decode the byte values in QRCodeReader().decode(binaryBitmap) I get this error message shown below when I run any test method com.google.zxing.NotFoundException In Controller Test, I get this error message shown below when I run any test method
MockHttpServletResponse:
Status = 400
Error message = null
Headers = [Content-Type:"application/problem+json"]
Content type = application/problem+json
Body = {"type":"about:blank","title":"Bad Request","status":400,"detail":"Required part 'text' is not present.","instance":"/api/v1/qr-generator"}
Forwarded URL = null
Redirected URL = null
Cookies = []

java.lang.AssertionError: Status expected:<201> but was:<400>
Expected :201
Actual :400
MockHttpServletResponse:
Status = 400
Error message = null
Headers = [Content-Type:"application/problem+json"]
Content type = application/problem+json
Body = {"type":"about:blank","title":"Bad Request","status":400,"detail":"Required part 'text' is not present.","instance":"/api/v1/qr-generator"}
Forwarded URL = null
Redirected URL = null
Cookies = []

java.lang.AssertionError: Status expected:<201> but was:<400>
Expected :201
Actual :400
How can I fix it? Here is the link : https://github.com/Rapter1990/qr-generator-example
5 replies
JCHJava Community | Help. Code. Learn.
Created by direct_x_34 on 3/31/2023 in #java-help
Cannot send requestbody and Multipartfile in Controller of Spring Boot from Postman
6 replies