Skip to content

Commit

Permalink
Merge pull request #53 from AhmedMohamedAbdelaty/checkstyle
Browse files Browse the repository at this point in the history
Add Checkstyle for code style enforcement
  • Loading branch information
AhmedFatthy1040 authored Nov 1, 2024
2 parents 9bb1a23 + 41a4aed commit 92385bd
Show file tree
Hide file tree
Showing 14 changed files with 180 additions and 69 deletions.
76 changes: 38 additions & 38 deletions .github/workflows/gradle.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: Java CI with Gradle

on: [push, pull_request]
on: [ push, pull_request ]

permissions:
contents: read
Expand All @@ -10,40 +10,40 @@ jobs:
runs-on: ubuntu-latest

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Set up JDK 21
uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'temurin'
cache: gradle

- name: Grant execute permission for gradlew
run: chmod +x gradlew

- name: Build with Gradle
run: ./gradlew build -x test

- name: Run tests
run: ./gradlew test

- name: Publish Test Results
uses: actions/upload-artifact@v4
if: always()
with:
name: test-results
path: |
build/reports/tests/test/
build/test-results/test/
- name: Update status check
if: success()
run: echo "Tests passed" > status.txt || echo "Tests failed" > status.txt

- name: Upload status check
uses: actions/upload-artifact@v4
with:
name: status-check
path: status.txt
- name: Checkout repository
uses: actions/checkout@v4

- name: Set up JDK 21
uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'temurin'
cache: gradle

- name: Grant execute permission for gradlew
run: chmod +x gradlew

- name: Run Checkstyle
run: ./gradlew checkstyleMain checkstyleTest

- name: Build with Gradle
run: ./gradlew build -x test

- name: Run tests
run: ./gradlew test

- name: Publish Test Results
uses: actions/upload-artifact@v4
if: always()
with:
name: test-results
path: |
build/reports/tests/test/
build/test-results/test/
- name: Publish Checkstyle Results
uses: actions/upload-artifact@v4
if: always()
with:
name: checkstyle-results
path: build/reports/checkstyle/
14 changes: 14 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@ plugins {
id 'org.springframework.boot' version '3.3.4'
id 'io.spring.dependency-management' version '1.1.6'
id 'org.flywaydb.flyway' version "10.18.0"
id 'checkstyle'
}

checkstyle {
toolVersion = "10.8.0"
configFile = file("config/checkstyle/checkstyle.xml")
maxWarnings = 0
}

tasks.withType(Checkstyle).configureEach {
reports {
xml.required = false
html.required = true
}
}

group = 'com.activecourses'
Expand Down
61 changes: 61 additions & 0 deletions config/checkstyle/checkstyle.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">

<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="warning"/>
<property name="fileExtensions" value="java, properties, xml"/>

<!-- Checks for whitespace -->
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>

<module name="LineLength">
<property name="max" value="120"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>

<module name="TreeWalker">
<!-- Checks for Indentation -->
<module name="Indentation">
<property name="basicOffset" value="4"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="4"/>
<property name="throwsIndent" value="4"/>
<property name="lineWrappingIndentation" value="8"/>
<property name="arrayInitIndent" value="4"/>
</module>

<!-- Checks for whitespace -->
<module name="EmptyForIteratorPad"/>
<module name="GenericWhitespace"/>
<module name="MethodParamPad"/>
<module name="NoWhitespaceAfter"/>
<module name="NoWhitespaceBefore"/>
<module name="OperatorWrap"/>
<module name="ParenPad"/>
<module name="TypecastParenPad"/>
<module name="WhitespaceAfter"/>
<module name="WhitespaceAround"/>

<!-- Modifier Checks -->
<module name="ModifierOrder"/>

<!-- Checks for blocks -->
<module name="EmptyBlock"/>
<module name="LeftCurly"/>
<module name="NeedBraces"/>
<module name="RightCurly"/>

<!-- Checks for common coding problems -->
<module name="EmptyStatement"/>
<module name="MultipleVariableDeclarations"/>

<!-- Miscellaneous other checks -->
<module name="ArrayTypeStyle"/>
<module name="UpperEll"/>
</module>
</module>
9 changes: 3 additions & 6 deletions src/main/java/com/activecourses/upwork/UpworkApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,8 @@

@SpringBootApplication
@EnableJpaAuditing

public class UpworkApplication {

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

public static void main(String[] args) {
SpringApplication.run(UpworkApplication.class, args);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ public class AuthEntryPointJwt implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException)
throws IOException, ServletException {
logger.error("Unauthorized error: {}", authException.getMessage());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ public class AuthTokenFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);

@Override
protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
protected void doFilterInternal(@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain)
throws ServletException, IOException {

try {
String jwt = jwtService.getJwtFromCookies(request);
if (jwt != null && jwtService.validateJwtToken(jwt)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,11 @@ public ResponseCookie getCleanJwtCookie() {
}

public ResponseCookie getCleanJwtRefreshCookie() {
return ResponseCookie.from(jwtRefreshCookie, "").path("/api/auth/refresh-token").maxAge(0).httpOnly(true).build();
return ResponseCookie.from(jwtRefreshCookie, "")
.path("/api/auth/refresh-token")
.maxAge(0)
.httpOnly(true)
.build();
}

public String generateAccessToken(UserDetails userDetails) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,10 @@ public ResponseEntity<ResponseDto> assignRolesToUser(@PathVariable int id, @Requ
: buildResponseEntity(HttpStatus.NOT_FOUND, false, null, "User not found.");
}

private ResponseEntity<ResponseDto> buildResponseEntity(HttpStatus status, boolean success, Object data, Object error) {
private ResponseEntity<ResponseDto> buildResponseEntity(HttpStatus status,
boolean success,
Object data,
Object error) {
return ResponseEntity
.status(status)
.body(ResponseDto
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,18 @@ public class UserController {
@Operation(summary = "Get all users",
description = "Retrieve a paginated list of all users. Only accessible by users with the ROLE_ADMIN role.",
parameters = {
@Parameter(name = "pageNo", in = ParameterIn.QUERY, description = "Page number", schema = @Schema(type = "integer", defaultValue = "0")),
@Parameter(name = "pageSize", in = ParameterIn.QUERY, description = "Page size", schema = @Schema(type = "integer", defaultValue = "10")),
@Parameter(name = "sortBy", in = ParameterIn.QUERY, description = "Sort by", schema = @Schema(type = "string", defaultValue = "id")),
@Parameter(name = "sortDir", in = ParameterIn.QUERY, description = "Sort direction", schema = @Schema(type = "string", defaultValue = "asc"))
@Parameter(name = "pageNo", in = ParameterIn.QUERY,
description = "Page number",
schema = @Schema(type = "integer", defaultValue = "0")),
@Parameter(name = "pageSize", in = ParameterIn.QUERY,
description = "Page size",
schema = @Schema(type = "integer", defaultValue = "10")),
@Parameter(name = "sortBy", in = ParameterIn.QUERY,
description = "Sort by",
schema = @Schema(type = "string", defaultValue = "id")),
@Parameter(name = "sortDir", in = ParameterIn.QUERY,
description = "Sort direction",
schema = @Schema(type = "string", defaultValue = "asc"))
}
)
@PreAuthorize("hasRole('ROLE_ADMIN')")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,12 @@ public class LoginRequestDto {
@Size(min = 6, message = "Password must be at least 6 characters long")
private String password;

public LoginRequestDto(@Email(message = "Email is not valid") @NotEmpty(message = "Email is required") @NotNull(message = "Email is required") String email,
@NotEmpty(message = "Password is required") @NotNull(message = "Password is required") @Size(min = 6, message = "Password must be at least 6 characters long") String password) {
public LoginRequestDto(@Email(message = "Email is not valid")
@NotEmpty(message = "Email is required")
@NotNull(message = "Email is required") String email,
@NotEmpty(message = "Password is required")
@NotNull(message = "Password is required")
@Size(min = 6, message = "Password must be at least 6 characters long") String password) {
this.email = email;
this.password = password;
}
Expand Down
10 changes: 5 additions & 5 deletions src/main/java/com/activecourses/upwork/model/RefreshToken.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ public class RefreshToken {

@Override
public String toString() {
return "RefreshToken{" +
"id=" + id +
", token='" + token + '\'' +
", expiryDate=" + expiryDate +
'}';
return "RefreshToken{"
+ "id=" + id
+ ", token='" + token + '\''
+ ", expiryDate=" + expiryDate
+ '}';
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/activecourses/upwork/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public class User implements UserDetails, Principal {

@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, optional = true)
private RefreshToken refreshToken;
@OneToOne(mappedBy = "user",cascade = CascadeType.ALL)
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private UserProfile userProfile;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ public class RefreshTokenService {
private final UserRepository userRepository;
private final JwtService jwtService;

public RefreshTokenService(RefreshTokenRepository refreshTokenRepository, UserRepository userRepository, JwtService jwtService) {
public RefreshTokenService(RefreshTokenRepository refreshTokenRepository,
UserRepository userRepository,
JwtService jwtService) {
this.refreshTokenRepository = refreshTokenRepository;
this.userRepository = userRepository;
this.jwtService = jwtService;
Expand Down Expand Up @@ -119,7 +121,9 @@ public RefreshToken createRefreshToken(int userId) {
public void verifyExpiration(RefreshToken token) {
if (token.getExpiryDate().compareTo(Instant.now()) < 0) {
refreshTokenRepository.delete(token);
throw new TokenRefreshException(token.getToken(), "Refresh token was expired. Please sign in again to obtain a new refresh token.");
throw new TokenRefreshException(token.getToken(),
"Refresh token was expired. "
+ "Please sign in again to obtain a new refresh token.");
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,19 +92,24 @@ public ResponseDto login(LoginRequestDto loginRequestDto) {
}

Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(loginRequestDto.getEmail(), loginRequestDto.getPassword()));
.authenticate(new UsernamePasswordAuthenticationToken(
loginRequestDto.getEmail(),
loginRequestDto.getPassword()
));

SecurityContextHolder.getContext().setAuthentication(authentication);

UserDetails userDetails = customUserDetailsService.loadUserByUsername(loginRequestDto.getEmail());
UserDetails userDetails = customUserDetailsService
.loadUserByUsername(loginRequestDto.getEmail());

ResponseCookie jwtCookie = jwtService.generateJwtCookie(userDetails);

int userId = ((User) userDetails).getId();

RefreshToken refreshToken = refreshTokenService.createRefreshToken(userId);

ResponseCookie refreshJwtCookie = jwtService.generateRefreshJwtCookie(refreshToken.getToken());
ResponseCookie refreshJwtCookie = jwtService
.generateRefreshJwtCookie(refreshToken.getToken());

return ResponseDto
.builder()
Expand All @@ -117,7 +122,8 @@ public ResponseDto login(LoginRequestDto loginRequestDto) {
@Override
public ResponseEntity<ResponseDto> logout() {
logger.info("User logout attempt");
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Object principal = SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
if (!principal.toString().equals("anonymousUser")) {
int userId = ((User) principal).getId();
refreshTokenService.deleteByUserId(userId);
Expand Down Expand Up @@ -166,7 +172,8 @@ public User findByEmail(String email) {
@Override
public void sendVerificationEmail(User user) {
logger.info("Sending verification email to: {}", user.getEmail());
String verificationLink = "http://localhost:8080/api/users/verify?token=" + user.getVerificationToken();
String verificationLink = "http://localhost:8080/api/users/verify?token="
+ user.getVerificationToken();

SimpleMailMessage message = new SimpleMailMessage();
message.setTo(user.getEmail());
Expand Down Expand Up @@ -196,7 +203,10 @@ public boolean reactivateUser(int userId) {
}

static User unwrapUser(Optional<User> entity) {
if (entity.isPresent()) return entity.get();
else throw new UnsupportedOperationException("Unimplemented method 'unwrapUser'");
if (entity.isPresent()) {
return entity.get();
} else {
throw new UnsupportedOperationException("Unimplemented method 'unwrapUser'");
}
}
}

0 comments on commit 92385bd

Please sign in to comment.