Itsurran
Itsurran
JCHJava Community | Help. Code. Learn.
Created by Itsurran on 2/4/2025 in #java-help
Websocket Postman
’’’java @PostMapping("/register")
public ResponseEntity<AuthenticationResponse> register(@RequestBody RegisterRequest request) {
return authenticationService.register(request);
}
public ResponseEntity<AuthenticationResponse> register(@RequestBody RegisterRequest request) {
return authenticationService.register(request);
}
’’’
211 replies
JCHJava Community | Help. Code. Learn.
Created by Serkan Gülbol on 1/28/2025 in #java-help
Own video streaming
What exactly do you mean with implementing video streaming?
114 replies
JCHJava Community | Help. Code. Learn.
Created by Tomás on 1/26/2025 in #java-help
authenticationManager threw StackOverFlow
@Configuration @EnableWebSecurity
public class SecurityConfigurations {

private SecurityFilter securityFilter;

public SecurityConfigurations(SecurityFilter securityFilter) {
this.securityFilter = securityFilter;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// .authorizeHttpRequests(authorize -> authorize
// .requestMatchers(HttpMethod.POST, "/auth/login").permitAll()
// .requestMatchers(HttpMethod.POST, "/auth/register").permitAll()
// .requestMatchers(HttpMethod.GET, "/swagger-ui/**").permitAll()
// .anyRequest().authenticated()
// )
// .addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
public class SecurityConfigurations {

private SecurityFilter securityFilter;

public SecurityConfigurations(SecurityFilter securityFilter) {
this.securityFilter = securityFilter;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// .authorizeHttpRequests(authorize -> authorize
// .requestMatchers(HttpMethod.POST, "/auth/login").permitAll()
// .requestMatchers(HttpMethod.POST, "/auth/register").permitAll()
// .requestMatchers(HttpMethod.GET, "/swagger-ui/**").permitAll()
// .anyRequest().authenticated()
// )
// .addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
44 replies
JCHJava Community | Help. Code. Learn.
Created by Tomás on 1/26/2025 in #java-help
authenticationManager threw StackOverFlow
@RestController @RequestMapping(value = "/auth")
public class AuthController {

private AuthenticationManager authenticationManager;
private UserRepository userRepository;
private TokenService tokenService;

public AuthController(AuthenticationManager authenticationManager, UserRepository userRepository, TokenService tokenService) {
this.authenticationManager = authenticationManager;
this.userRepository = userRepository;
this.tokenService = tokenService;
}

@PostMapping("/login")
public ResponseEntity login(@RequestBody @Valid AuthDTO data) {
var usernamePassword = new UsernamePasswordAuthenticationToken(data.email(), data.password());
var auth = authenticationManager.authenticate(usernamePassword);

var token = tokenService.generateToken((User) auth.getPrincipal());

return ResponseEntity.ok(new LoginResponseDTO(token));
}

@PostMapping("/register")
public ResponseEntity register(@RequestBody @Valid RegisterDTO data) {
if (this.userRepository.findByEmail(data.email()) != null) return ResponseEntity.badRequest().build();

String encryptedPassword = new BCryptPasswordEncoder().encode(data.password());
User newUser = new User(null, data.name(), data.email(), data.phone(), encryptedPassword, data.role());

this.userRepository.save(newUser);

return ResponseEntity.ok().build();
}
}
public class AuthController {

private AuthenticationManager authenticationManager;
private UserRepository userRepository;
private TokenService tokenService;

public AuthController(AuthenticationManager authenticationManager, UserRepository userRepository, TokenService tokenService) {
this.authenticationManager = authenticationManager;
this.userRepository = userRepository;
this.tokenService = tokenService;
}

@PostMapping("/login")
public ResponseEntity login(@RequestBody @Valid AuthDTO data) {
var usernamePassword = new UsernamePasswordAuthenticationToken(data.email(), data.password());
var auth = authenticationManager.authenticate(usernamePassword);

var token = tokenService.generateToken((User) auth.getPrincipal());

return ResponseEntity.ok(new LoginResponseDTO(token));
}

@PostMapping("/register")
public ResponseEntity register(@RequestBody @Valid RegisterDTO data) {
if (this.userRepository.findByEmail(data.email()) != null) return ResponseEntity.badRequest().build();

String encryptedPassword = new BCryptPasswordEncoder().encode(data.password());
User newUser = new User(null, data.name(), data.email(), data.phone(), encryptedPassword, data.role());

this.userRepository.save(newUser);

return ResponseEntity.ok().build();
}
}
44 replies
JCHJava Community | Help. Code. Learn.
Created by nikcho-kouhai on 1/23/2025 in #java-help
Type inference for generic parameters when calling a method
There are several approaches to work around this limitation: Explicit Type Declaration: The simplest way is to explicitly specify the type when creating the instance: java bar(new Foo<Integer>().self()); Factory Method: You can create a factory method that returns a Foo<T> with a specific type: java
public static <T> Foo<T> createFoo() {
return new Foo<>();
}

public static void main(String[] args) {
bar(createFoo());
}
Static Method for Type Inference: If you want to avoid repeating long generic types, you could define a static method that encapsulates the creation logic:
java
public static Foo<Integer> createIntegerFoo() {
return new Foo<>();
}

public static void main(String[] args) {
bar(createIntegerFoo());
}
public static <T> Foo<T> createFoo() {
return new Foo<>();
}

public static void main(String[] args) {
bar(createFoo());
}
Static Method for Type Inference: If you want to avoid repeating long generic types, you could define a static method that encapsulates the creation logic:
java
public static Foo<Integer> createIntegerFoo() {
return new Foo<>();
}

public static void main(String[] args) {
bar(createIntegerFoo());
}
These methods allow you to maintain clarity in your code while still leveraging generics effectively without cluttering your main logic with verbose type specifications. By using these techniques, you can streamline your code and avoid the verbosity of specifying long generic types repeatedly while ensuring that the compiler understands what types you are working with.
13 replies
JCHJava Community | Help. Code. Learn.
Created by °~° on 1/22/2025 in #java-help
someone explain this code (which i mostly understand
import java.util.Scanner;
public class Tax {

public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("gifts have tax rates depending on their prices, enter your gifts price to calculate the tax rate");
double tax;
int price = Integer.valueOf(scanner.nextLine());
double finalamount;

if (price >= 5000 && price <= 25000) {
tax = (double) 100 + price * 0.08;
finalamount = (double) price + tax;
System.out.println("the gift now costs " + finalamount + " due to a " + tax + " dollar tax");
}
else if(price <= 55000) {
tax = (double) 1700 + price * 0.10;
finalamount = (double) price + tax;
System.out.println("the gift now costs " + finalamount + " due to a " + tax + " dollar tax");
}
else if(price <= 200000) {
tax = (double) 4700 + price * 0.12;
finalamount = (double) price + tax;
System.out.println("the gift now costs " + finalamount + " due to a " + tax + " dollar tax");
}
else if(price <= 1000000) {
tax = (double) 22100 + price * 0.15;
finalamount = (double) price + tax;
System.out.println("the gift now costs " + finalamount + " due to a " + tax + " dollar tax");
}
}
}
public class Tax {

public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("gifts have tax rates depending on their prices, enter your gifts price to calculate the tax rate");
double tax;
int price = Integer.valueOf(scanner.nextLine());
double finalamount;

if (price >= 5000 && price <= 25000) {
tax = (double) 100 + price * 0.08;
finalamount = (double) price + tax;
System.out.println("the gift now costs " + finalamount + " due to a " + tax + " dollar tax");
}
else if(price <= 55000) {
tax = (double) 1700 + price * 0.10;
finalamount = (double) price + tax;
System.out.println("the gift now costs " + finalamount + " due to a " + tax + " dollar tax");
}
else if(price <= 200000) {
tax = (double) 4700 + price * 0.12;
finalamount = (double) price + tax;
System.out.println("the gift now costs " + finalamount + " due to a " + tax + " dollar tax");
}
else if(price <= 1000000) {
tax = (double) 22100 + price * 0.15;
finalamount = (double) price + tax;
System.out.println("the gift now costs " + finalamount + " due to a " + tax + " dollar tax");
}
}
}
Used no help
82 replies
JCHJava Community | Help. Code. Learn.
Created by °~° on 1/22/2025 in #java-help
someone explain this code (which i mostly understand
import java.util.Scanner;
public class Program {
public static void main(String[] main) {
Scanner scanner = new Scanner (System.in);


while (true) {

System.out.println("insert positive integers, 0 to stop");
int num = Integer.valueOf(scanner.nextLine());
if(num < 0) {
System.out.println("thats not a positive integer, try again!");
continue;
}
if (num == 0) {


break;
}
System.out.println("you put " + num);


}
System.out.println("thanks for adding!");
}
}
public class Program {
public static void main(String[] main) {
Scanner scanner = new Scanner (System.in);


while (true) {

System.out.println("insert positive integers, 0 to stop");
int num = Integer.valueOf(scanner.nextLine());
if(num < 0) {
System.out.println("thats not a positive integer, try again!");
continue;
}
if (num == 0) {


break;
}
System.out.println("you put " + num);


}
System.out.println("thanks for adding!");
}
}

look i made this code by my own but i dont get the one above
82 replies
JCHJava Community | Help. Code. Learn.
Created by Maxxx005 on 1/16/2025 in #java-help
production vs development
JwtProvider: package com.Config; import java.util.Date; import static java.lang.System.currentTimeMillis; import java.util.stream.Collectors; import javax.crypto.SecretKey; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Service; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.security.Keys; @Service public class JwtProvider
{
SecretKey key=Keys.hmacShaKeyFor(jwtConstant.SECRET_KEY.getBytes());
public String generateToken(Authentication auth)
{
// String authorities = auth.getAuthorities().stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.joining(","));

String authorities= auth.getAuthorities().toString();





return Jwts.builder()
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis()+86400000))
.claim("email",auth.getName())
.claim("authorities", authorities)
.signWith(key)
.compact();
}
public String getEmailFromToken(String jwt)
{
jwt=jwt.substring(7);
Claims claims=Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jwt).getBody();
String email=String.valueOf(claims.get("email"));
return email;
}


}
{
SecretKey key=Keys.hmacShaKeyFor(jwtConstant.SECRET_KEY.getBytes());
public String generateToken(Authentication auth)
{
// String authorities = auth.getAuthorities().stream()
// .map(GrantedAuthority::getAuthority)
// .collect(Collectors.joining(","));

String authorities= auth.getAuthorities().toString();





return Jwts.builder()
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis()+86400000))
.claim("email",auth.getName())
.claim("authorities", authorities)
.signWith(key)
.compact();
}
public String getEmailFromToken(String jwt)
{
jwt=jwt.substring(7);
Claims claims=Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jwt).getBody();
String email=String.valueOf(claims.get("email"));
return email;
}


}
271 replies
JCHJava Community | Help. Code. Learn.
Created by Maxxx005 on 1/16/2025 in #java-help
production vs development
Forget about everything, my code is running fine in these entity classes while development and not getting any errors but while in production i am getting this exception on render.com.
271 replies
JCHJava Community | Help. Code. Learn.
Created by Maxxx005 on 1/16/2025 in #java-help
production vs development
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();

// Allow requests from the React frontend
// configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedOrigins(Arrays.asList("https://connect-2cgoq5uvw-harsh-vyas-projects-049c37b9.vercel.app", "http://localhost:3000"));
configuration.setAllowCredentials(true);

// Allow common headers including Authorization
configuration.setAllowedHeaders(Arrays.asList(
"Authorization",
"Content-Type",
"Accept",
"X-Requested-With",
"Origin",
"Access-Control-Request-Method",
"Access-Control-Request-Headers"
));
configuration.setExposedHeaders(Arrays.asList("Authorization"));
configuration.setMaxAge(3600L); // Cache preflight requests for 1 hour

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();

// Allow requests from the React frontend
// configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedOrigins(Arrays.asList("https://connect-2cgoq5uvw-harsh-vyas-projects-049c37b9.vercel.app", "http://localhost:3000"));
configuration.setAllowCredentials(true);

// Allow common headers including Authorization
configuration.setAllowedHeaders(Arrays.asList(
"Authorization",
"Content-Type",
"Accept",
"X-Requested-With",
"Origin",
"Access-Control-Request-Method",
"Access-Control-Request-Headers"
));
configuration.setExposedHeaders(Arrays.asList("Authorization"));
configuration.setMaxAge(3600L); // Cache preflight requests for 1 hour

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
271 replies
JCHJava Community | Help. Code. Learn.
Created by Maxxx005 on 1/16/2025 in #java-help
production vs development
package hibtest.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; @Entity @Inheritance(strategy = InheritanceType.JOINED)
public class Mensagem {
protected Long id;

protected Mensagem() { }

@Id
@GeneratedValue
public Long getId() {
return id;
}

public Mensagem setId(Long id) {
this.id = id;
return this;
}
}
public class Mensagem {
protected Long id;

protected Mensagem() { }

@Id
@GeneratedValue
public Long getId() {
return id;
}

public Mensagem setId(Long id) {
this.id = id;
return this;
}
}
271 replies
JCHJava Community | Help. Code. Learn.
Created by Maxxx005 on 1/16/2025 in #java-help
production vs development
Can you show the DDL from the actual database?
271 replies
JCHJava Community | Help. Code. Learn.
Created by Hype_the_Time on 1/18/2025 in #java-help
Hotswap file not found error. Running works fine.
private CompilationUnit getSourceCU(ProcessingEnvironment processingEnv, TypeElement typeElement) {
FileObject sourceFile = null;
try {
sourceFile = processingEnv.getFiler().getResource(StandardLocation.CLASS_PATH, processingEnv.getElementUtils().getPackageOf(typeElement).toString().replace(".","/"), typeElement.getSimpleName() + ".java");
CompilationUnit cu;
try (InputStream is = new BufferedInputStream(sourceFile.openInputStream())) {
return StaticJavaParser.parse(is);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private CompilationUnit getSourceCU(ProcessingEnvironment processingEnv, TypeElement typeElement) {
FileObject sourceFile = null;
try {
sourceFile = processingEnv.getFiler().getResource(StandardLocation.CLASS_PATH, processingEnv.getElementUtils().getPackageOf(typeElement).toString().replace(".","/"), typeElement.getSimpleName() + ".java");
CompilationUnit cu;
try (InputStream is = new BufferedInputStream(sourceFile.openInputStream())) {
return StaticJavaParser.parse(is);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
312 replies
JCHJava Community | Help. Code. Learn.
Created by Hype_the_Time on 1/18/2025 in #java-help
Hotswap file not found error. Running works fine.
private CompilationUnit getSourceCU(ProcessingEnvironment processingEnv, TypeElement typeElement) {
try (InputStream inputStream = processingEnv.getFiler().getResource(StandardLocation.SOURCE_PATH, processingEnv.getElementUtils().getPackageOf(typeElement).toString(), typeElement.getSimpleName()+".java").openInputStream()) {
return StaticJavaParser.parse(inputStream);
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed to parse source file: " + e.getMessage(), typeElement);
throw new RuntimeException(e);
}
}
private CompilationUnit getSourceCU(ProcessingEnvironment processingEnv, TypeElement typeElement) {
try (InputStream inputStream = processingEnv.getFiler().getResource(StandardLocation.SOURCE_PATH, processingEnv.getElementUtils().getPackageOf(typeElement).toString(), typeElement.getSimpleName()+".java").openInputStream()) {
return StaticJavaParser.parse(inputStream);
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed to parse source file: " + e.getMessage(), typeElement);
throw new RuntimeException(e);
}
}
312 replies
JCHJava Community | Help. Code. Learn.
Created by Hype_the_Time on 1/18/2025 in #java-help
Hotswap file not found error. Running works fine.
private CompilationUnit getSourceCU(ProcessingEnvironment processingEnv, TypeElement typeElement) {
try (InputStream inputStream = processingEnv.getFiler().getResource(StandardLocation.SOURCE_PATH, processingEnv.getElementUtils().getPackageOf(typeElement).toString(), typeElement.getSimpleName()).openInputStream()) {
return StaticJavaParser.parse(inputStream);
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed to parse source file: " + e.getMessage(), typeElement);
throw new RuntimeException(e);
}
}
private CompilationUnit getSourceCU(ProcessingEnvironment processingEnv, TypeElement typeElement) {
try (InputStream inputStream = processingEnv.getFiler().getResource(StandardLocation.SOURCE_PATH, processingEnv.getElementUtils().getPackageOf(typeElement).toString(), typeElement.getSimpleName()).openInputStream()) {
return StaticJavaParser.parse(inputStream);
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed to parse source file: " + e.getMessage(), typeElement);
throw new RuntimeException(e);
}
}
312 replies
JCHJava Community | Help. Code. Learn.
Created by Ainhart on 1/14/2025 in #java-help
TestNG won't detect my test or build it
{"name":"error","attributes":{"message":"Failed to run TestNG tests","trace":"java.lang.ClassNotFoundException: testCases.LoginTest
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:528)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:578)
at java.base/java.lang.Class.forName(Class.java:557)
at com.microsoft.java.test.runner.testng.TestNGLauncher.getClassNameFromMethod(TestNGLauncher.java:57)
at com.microsoft.java.test.runner.testng.TestNGLauncher.parse(TestNGLauncher.java:43)
at com.microsoft.java.test.runner.testng.TestNGLauncher.execute(TestNGLauncher.java:32)
at com.microsoft.java.test.runner.Launcher.main(Launcher.java:57)
"}}
{"name":"error","attributes":{"message":"Failed to run TestNG tests","trace":"java.lang.ClassNotFoundException: testCases.LoginTest
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:528)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:578)
at java.base/java.lang.Class.forName(Class.java:557)
at com.microsoft.java.test.runner.testng.TestNGLauncher.getClassNameFromMethod(TestNGLauncher.java:57)
at com.microsoft.java.test.runner.testng.TestNGLauncher.parse(TestNGLauncher.java:43)
at com.microsoft.java.test.runner.testng.TestNGLauncher.execute(TestNGLauncher.java:32)
at com.microsoft.java.test.runner.Launcher.main(Launcher.java:57)
"}}
92 replies
JCHJava Community | Help. Code. Learn.
Created by nomoney4u on 1/9/2025 in #java-help
Configuring Eclipse to use explode war with Tomcat for debugging
No description
307 replies
JCHJava Community | Help. Code. Learn.
Created by nomoney4u on 1/9/2025 in #java-help
Configuring Eclipse to use explode war with Tomcat for debugging
No description
307 replies
JCHJava Community | Help. Code. Learn.
Created by Omen on 12/25/2024 in #java-help
The bot isnt responding when i run an message
C:\Users\priya\Desktop\Study\Programs\Omenize Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:136 const invalidToken = new DiscordjsError(ErrorCodes.TokenInvalid); ^ Error [TokenInvalid]: An invalid token was provided. at WebSocketManager.connect (C:\Users\priya\Desktop\Study\Programs\Omenize Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:136:26) at Client.login (C:\Users\priya\Desktop\Study\Programs\Omenize Bot\node_modules\discord.js\src\client\Client.js:228:21) at Object.<anonymous> (C:\Users\priya\Desktop\Study\Programs\Omenize Bot\src\index.js:21:8) at Module._compile (node:internal/modules/cjs/loader:1469:14) at Module._extensions..js (node:internal/modules/cjs/loader:1548:10) at Module.load (node:internal/modules/cjs/loader:1288:32) at Module._load (node:internal/modules/cjs/loader:1104:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)
at node:internal/main/run_main_module:28:49 {
code: 'TokenInvalid'
}
at node:internal/main/run_main_module:28:49 {
code: 'TokenInvalid'
}
Node.js v20.18.0 [nodemon] app crashed - waiting for file changes before starting...
13 replies