Tomasm21
Tomasm21
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 9/27/2024 in #java-help
Cannot host Spring web app war on Tomcat using Jenkins plugin
No description
13 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 9/23/2024 in #java-help
Jenkins build step doesn't execute as it should.
I try to download my project from GitHub repository using Jenkins and then to build. Later I will join tomcat server and automatically host on localhost or aws. Currently something is wrong. I have this script:
@echo off
SETLOCAL

echo Removing old resources...
cd Maitinimas-back\src\main\resources\public
del /Q *.*

echo Building react app...
cd ..\..\..\..\..\Maitinimas-front\

echo Checking Node.js version...
node -v
IF ERRORLEVEL 1 (
echo Node.js is not installed or not found in PATH. Exiting...
exit /B 1
)

echo Checking npm version...
npm -v
IF ERRORLEVEL 1 (
echo npm is not installed or not found in PATH. Exiting...
exit /B 1
)

echo Installing dependencies...
npm install
IF ERRORLEVEL 1 (
echo Npm install failed. Exiting...
exit /B 1
)

npm run build
IF ERRORLEVEL 1 (
echo Npm build failed. Exiting...
exit /B 1
) ELSE (
echo Npm build completed successfully.
)

echo Copying build to target...
cd ..\Maitinimas-back\src\main\resources\public\
xcopy /E /Y ..\..\..\..\..\Maitinimas-front\build\* .\

echo Maven clean package...
cd ..\..\..\..
mvn clean package
IF ERRORLEVEL 1 (
echo Maven clean package failed. Exiting...
exit /B 1
)

echo Build script completed successfully.
ENDLOCAL
@echo off
SETLOCAL

echo Removing old resources...
cd Maitinimas-back\src\main\resources\public
del /Q *.*

echo Building react app...
cd ..\..\..\..\..\Maitinimas-front\

echo Checking Node.js version...
node -v
IF ERRORLEVEL 1 (
echo Node.js is not installed or not found in PATH. Exiting...
exit /B 1
)

echo Checking npm version...
npm -v
IF ERRORLEVEL 1 (
echo npm is not installed or not found in PATH. Exiting...
exit /B 1
)

echo Installing dependencies...
npm install
IF ERRORLEVEL 1 (
echo Npm install failed. Exiting...
exit /B 1
)

npm run build
IF ERRORLEVEL 1 (
echo Npm build failed. Exiting...
exit /B 1
) ELSE (
echo Npm build completed successfully.
)

echo Copying build to target...
cd ..\Maitinimas-back\src\main\resources\public\
xcopy /E /Y ..\..\..\..\..\Maitinimas-front\build\* .\

echo Maven clean package...
cd ..\..\..\..
mvn clean package
IF ERRORLEVEL 1 (
echo Maven clean package failed. Exiting...
exit /B 1
)

echo Build script completed successfully.
ENDLOCAL
I call it using call build-script.bat in Jenkins step Execute Windows batch command. But Instead of executing all the script Jenkins finishes it prematurely:
76 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 9/13/2024 in #java-help
I try to write JUnit integration test and to test whether service method works well. It isn't.
This is the service class:
163 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 7/22/2024 in #java-help
Spring app doesn't read environmental variables from .env
I have .env file in my project root folder along with pom.xml. Contents:
APP_PASSWORD=my-app-password
DATABASE_PASSWORD=Tomasm21-xi
DATABASE_USERNAME=Tomasm21
APP_PASSWORD=my-app-password
DATABASE_PASSWORD=Tomasm21-xi
DATABASE_USERNAME=Tomasm21
and in application properties I use these values:
# Database Configuration
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/myDB
spring.datasource.username=${DATABASE_USERNAME}
spring.datasource.password=${DATABASE_PASSWORD}
//....
spring.mail.username=${MAIL_USERNAME}
spring.mail.password=${APP_PASSWORD}
# Database Configuration
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/myDB
spring.datasource.username=${DATABASE_USERNAME}
spring.datasource.password=${DATABASE_PASSWORD}
//....
spring.mail.username=${MAIL_USERNAME}
spring.mail.password=${APP_PASSWORD}
I even added Dotenv Dependency:
<!-- https://mvnrepository.com/artifact/io.github.cdimascio/java-dotenv -->
<dependency>
<groupId>io.github.cdimascio</groupId>
<artifactId>java-dotenv</artifactId>
<version>5.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.github.cdimascio/java-dotenv -->
<dependency>
<groupId>io.github.cdimascio</groupId>
<artifactId>java-dotenv</artifactId>
<version>5.2.2</version>
</dependency>
and configured it:
import io.github.cdimascio.dotenv.Dotenv;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DotenvConfig {
@Bean
public Dotenv dotenv() {
return Dotenv.configure().ignoreIfMissing().load();
}
}
import io.github.cdimascio.dotenv.Dotenv;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DotenvConfig {
@Bean
public Dotenv dotenv() {
return Dotenv.configure().ignoreIfMissing().load();
}
}
This class should set the system properties using the values from the Dotenv bean:
@Configuration
public class AppConfig {
private final Dotenv dotenv;

@Autowired
public AppConfig(Dotenv dotenv) {
this.dotenv = dotenv;
System.setProperty("DATABASE_USERNAME", dotenv.get("DATABASE_USERNAME"));
System.setProperty("DATABASE_PASSWORD", dotenv.get("DATABASE_PASSWORD"));
System.setProperty("MAIL_USERNAME", dotenv.get("MAIL_USERNAME"));
System.setProperty("APP_PASSWORD", dotenv.get("APP_PASSWORD"));
}
}
@Configuration
public class AppConfig {
private final Dotenv dotenv;

@Autowired
public AppConfig(Dotenv dotenv) {
this.dotenv = dotenv;
System.setProperty("DATABASE_USERNAME", dotenv.get("DATABASE_USERNAME"));
System.setProperty("DATABASE_PASSWORD", dotenv.get("DATABASE_PASSWORD"));
System.setProperty("MAIL_USERNAME", dotenv.get("MAIL_USERNAME"));
System.setProperty("APP_PASSWORD", dotenv.get("APP_PASSWORD"));
}
}
But actually it doesn't work and I get an exception when I launch my application. I'm on Windows 10.
13 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 5/6/2024 in #java-help
Help to define Jsonfactory
@dan1st | Daniel Can you help me to write JsonFactory bean? I got this error:
Error starting ApplicationContext.
Description:

Parameter 1 of constructor in coms.configuration.BloggerServiceConfiguration required a bean of type 'com.google.api.client.json.JsonFactory' that could not be found.


Action:

Consider defining a bean of type 'com.google.api.client.json.JsonFactory' in your configuration.
Error starting ApplicationContext.
Description:

Parameter 1 of constructor in coms.configuration.BloggerServiceConfiguration required a bean of type 'com.google.api.client.json.JsonFactory' that could not be found.


Action:

Consider defining a bean of type 'com.google.api.client.json.JsonFactory' in your configuration.
The BloggerServiceConfiguration is:
@Configuration
public class BloggerServiceConfiguration {
@Value("${GOOGLE_CLIENT_ID}")
private String googleClientId;

private final HttpTransport httpTransport;
private final JsonFactory jsonFactory;
private final OAuth2AuthorizedClientService authorizedClientService;

public BloggerServiceConfiguration(HttpTransport httpTransport,
JsonFactory jsonFactory,
OAuth2AuthorizedClientService authorizedClientService,
@Value("${GOOGLE_CLIENT_ID}") String googleClientId) {
this.httpTransport = httpTransport;
this.jsonFactory = jsonFactory;
this.authorizedClientService = authorizedClientService;
this.googleClientId = googleClientId;
}

@Bean
public Blogger bloggerService() {
//....
@Configuration
public class BloggerServiceConfiguration {
@Value("${GOOGLE_CLIENT_ID}")
private String googleClientId;

private final HttpTransport httpTransport;
private final JsonFactory jsonFactory;
private final OAuth2AuthorizedClientService authorizedClientService;

public BloggerServiceConfiguration(HttpTransport httpTransport,
JsonFactory jsonFactory,
OAuth2AuthorizedClientService authorizedClientService,
@Value("${GOOGLE_CLIENT_ID}") String googleClientId) {
this.httpTransport = httpTransport;
this.jsonFactory = jsonFactory;
this.authorizedClientService = authorizedClientService;
this.googleClientId = googleClientId;
}

@Bean
public Blogger bloggerService() {
//....
I try to define the JsonFactory:
@Configuration
public class GoogleApiConfiguration {
@Bean
public HttpTransport httpTransport() {
return new NetHttpTransport();
}

@Bean
public JsonFactory jsonFactory() {
return JacksonFactory.getDefaultInstance();
}
}
@Configuration
public class GoogleApiConfiguration {
@Bean
public HttpTransport httpTransport() {
return new NetHttpTransport();
}

@Bean
public JsonFactory jsonFactory() {
return JacksonFactory.getDefaultInstance();
}
}
But JacksonFactory is underlined in red - JacksonFactory cannot be resolved The com.google.api.client.json.jackson2.. is obsolete. Now jackson comes from:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
But how to use it in bean?
169 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 5/2/2024 in #java-help
Cannot start the backup Spring project
I deleted corrupted Spring boot directory. Then to the root of the project I pasted the backup Spring boot directory from backups folder. But everytime I try to launch the app it starts to create tempDir in C:\WINDOWS\:




I don't know what to do. How to fix this?
10 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 4/1/2024 in #java-help
Failed to run SB using Eclipse IDE run command using environment variables in application properties
No description
10 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 2/23/2024 in #java-help
Swagger 2 is not launching. Keep getting 401 Unauthorized error
No description
6 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 11/19/2023 in #java-help
Is it correct sql query inside jpa repository interface method annotation?
No description
4 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 5/31/2023 in #java-help
Cannot get inputStream from web url. Why?
I'm trying to create a book with an image in JUnit test using MockMultipartFile. But for unknown reasons the stream cannot be taken. Why?
@Test
@Order(2)
void testCreateBookWithAnImage() {
BookRequestDTO bookDto = new BookRequestDTO();
bookDto.setTitle("New Book With Image");
bookDto.setAuthor("Name Surname");
bookDto.setSummary("Instructions how to add an image and asociate it with the Book object");
bookDto.setIsbn("555556666");
bookDto.setYear(2023);
bookDto.setPages(20);
bookDto.setCirculation(3);
bookDto.setCategory("Novel");

MultipartFile file = null;

try {
file = createMultipartFileFromURL("https://cdn.pixabay.com/photo/2014/09/05/18/32/old-books-436498_1280.jpg");
// file = createMultipartFileFromURL("https://pngimg.com/uploads/pineapple/pineapple_PNG2755.png");
} catch (IOException e) {
e.printStackTrace();
}

try {
Book createdBook = bookService.addNewBookWithImage(bookDto, file);
assertEquals("New Book With Image", createdBook.getTitle());
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
@Order(2)
void testCreateBookWithAnImage() {
BookRequestDTO bookDto = new BookRequestDTO();
bookDto.setTitle("New Book With Image");
bookDto.setAuthor("Name Surname");
bookDto.setSummary("Instructions how to add an image and asociate it with the Book object");
bookDto.setIsbn("555556666");
bookDto.setYear(2023);
bookDto.setPages(20);
bookDto.setCirculation(3);
bookDto.setCategory("Novel");

MultipartFile file = null;

try {
file = createMultipartFileFromURL("https://cdn.pixabay.com/photo/2014/09/05/18/32/old-books-436498_1280.jpg");
// file = createMultipartFileFromURL("https://pngimg.com/uploads/pineapple/pineapple_PNG2755.png");
} catch (IOException e) {
e.printStackTrace();
}

try {
Book createdBook = bookService.addNewBookWithImage(bookDto, file);
assertEquals("New Book With Image", createdBook.getTitle());
} catch (IOException e) {
e.printStackTrace();
}
}
13 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 5/26/2023 in #java-help
Why new entity is saved with null field value when annotation tells that the value cannot be null?
No description
9 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 4/19/2023 in #java-help
Hibernate doesn't save a list of authorities of a user to table as separate rows. It saves only one.
I need help to save several roles of a user to database. Using Spring Boot JPA. User can have many roles. A role belongs to one user. I tried to create three users - an admin, a user and a manager. Admin has admin role, user has user role. Manager has both - admin and user roles. I have Authority class that has a role. The problem is that for the manager hibernate creates only last role - USER. And I expected that it will have both roles. In database I see that manager has only 1 row. And it should have 2 rows. What am I doing wrong? User:
@Entity
@Table(uniqueConstraints= {@UniqueConstraint(columnNames="username")}, name = "Users")
public class User implements UserDetails{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NonNull
private String username;
@NonNull
private String password;
@NonNull
private String email;
@OneToMany(mappedBy = "user")
private List<Authority> authorities = new ArrayList<>();
//...
@Entity
@Table(uniqueConstraints= {@UniqueConstraint(columnNames="username")}, name = "Users")
public class User implements UserDetails{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NonNull
private String username;
@NonNull
private String password;
@NonNull
private String email;
@OneToMany(mappedBy = "user")
private List<Authority> authorities = new ArrayList<>();
//...
Authority:
@Entity
public class Authority implements GrantedAuthority {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Enumerated(EnumType.STRING)
private Role authority;
@JsonIgnore
@ManyToOne(optional = false)
private User user;
//...
@Entity
public class Authority implements GrantedAuthority {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Enumerated(EnumType.STRING)
private Role authority;
@JsonIgnore
@ManyToOne(optional = false)
private User user;
//...
42 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 4/13/2023 in #java-help
Java Spring Security Cors error
I'm trying to enable cors between browser and server api because website shows cors error. I try to add further bean:
// Used by Spring Security if CORS is enabled.
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source =
new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
// Used by Spring Security if CORS is enabled.
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source =
new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
But then I get an error:
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:516) ~[spring-web-6.0.7.jar:6.0.7]
at org.springframework.web.cors.CorsConfiguration.checkOrigin(CorsConfiguration.java:620) ~[spring-web-6.0.7.jar:6.0.7]
//...
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:516) ~[spring-web-6.0.7.jar:6.0.7]
at org.springframework.web.cors.CorsConfiguration.checkOrigin(CorsConfiguration.java:620) ~[spring-web-6.0.7.jar:6.0.7]
//...
How to solve this? Should I remove config.addAllowedOrigin("*"); line? Or should I ask exact url to my UI: "http://localhost:3000/" What if this url will be changed in production?
9 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 11/21/2022 in #java-help
How do you get a list of entities in JQuery if entity field property has specific column name?
Lets say you have Orders entity:
@Entity
public class Orders {
//...

@NotEmpty
@Column(name="`User`")
private String username;
//...
@Entity
public class Orders {
//...

@NotEmpty
@Column(name="`User`")
private String username;
//...
And in Orders Data Access Object you get the list of orders for that specific user. How jQuery query should look? This way:
public interface OrderDAO extends JpaRepository<Orders, Integer> {

@Query("SELECT u from Orders WHERE u.User ?= 1")
public List<Orders> findOrderByUsername (String username);
}
public interface OrderDAO extends JpaRepository<Orders, Integer> {

@Query("SELECT u from Orders WHERE u.User ?= 1")
public List<Orders> findOrderByUsername (String username);
}
or like this:
public interface OrderDAO extends JpaRepository<Orders, Integer> {

@Query("SELECT u from Orders WHERE u.username ?= 1")
public List<Orders> findOrderByUsername (String username);
}
public interface OrderDAO extends JpaRepository<Orders, Integer> {

@Query("SELECT u from Orders WHERE u.username ?= 1")
public List<Orders> findOrderByUsername (String username);
}
? Does column name impact the way how you should access entity property inside jQuery?
5 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 11/17/2022 in #java-help
What is an order in e-commerce application and how to control it. How is it related with user cart?
I'm training to create my first Food ordering from catering establishments application. I created administrator and his ability to add, edit and delete catering establishments - canteens, cafes, bars etc. Also to add various menu types and dishes into it. To edit it and to delete it. I have also created cart for users to add dishes from menus., edit quantity or to removes products from cart. But now I have to create an order. I kinda know what it is, but I don't know how exactly is it related with other entities. I know that each order should be for each user's cart at that exact time when he presses Checkout or order button. Then in the database there should be an order and all related information about the user and his ordered goods - dishes, quantities, price etc. What is relation between order and cart. For example my cart entity is this:
@Entity
@Table(name="cart_items")
public class CartItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@ManyToOne
@JoinColumn(name = "dish_id")
private Dish dish;

@ManyToOne
@JoinColumn(name = "user_id")
private User user;

private Integer quantity;

public CartItem() {}

public CartItem(Dish dish, User user, Integer quantity) {
super();
this.dish = dish;
this.user = user;
this.quantity = quantity;
}
@Entity
@Table(name="cart_items")
public class CartItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@ManyToOne
@JoinColumn(name = "dish_id")
private Dish dish;

@ManyToOne
@JoinColumn(name = "user_id")
private User user;

private Integer quantity;

public CartItem() {}

public CartItem(Dish dish, User user, Integer quantity) {
super();
this.dish = dish;
this.user = user;
this.quantity = quantity;
}
Manager or admin should be able to confirm or cancel the order. I think for the order I will use enum with values such as submitted, approved, withdrawn
47 replies
JCHJava Community | Help. Code. Learn.
Created by Tomasm21 on 11/8/2022 in #java-help
Question about SecurityContextHolder from Spring Boot Security
Speaking about Spring Boot RestController... - can I extract a username from SecurityContextHolder only once outside of all methods and then use that string username in any methods as a class scope variable or a constant? Or should the username acquiring be only inside any particular method that has @Secured({"..."}) and mapping annotations? Can the SecurityContextHolder be in a service?
13 replies