write a backend in java that holds users posts/messages, like how twitter works
- User
write a backend in java that holds users posts/messages, like how twitter works
Assistant
Twitter-like Backend in Java
Here's a basic implementation of a Twitter-like backend in Java using Spring Boot. This includes user management, posting messages, and retrieving posts.
Project Structure
src/main/java/com/example/twitterclone/ ├── config/ (Security configurations) ├── controller/ │ ├── AuthController.java │ ├── PostController.java │ ├── UserController.java ├── dto/ │ ├── LoginRequest.java │ ├── PostDto.java │ ├── RegisterRequest.java │ ├── UserDto.java ├── exception/ │ ├── CustomException.java │ ├── GlobalExceptionHandler.java ├── model/ │ ├── Post.java │ ├── User.java ├── repository/ │ ├── PostRepository.java │ ├── UserRepository.java ├── security/ │ ├── JwtAuthenticationFilter.java │ ├── JwtProvider.java │ ├── UserPrincipal.java ├── service/ │ ├── AuthService.java │ ├── PostService.java │ ├── UserService.java └── TwitterCloneApplication.javaKey Components
1. Models
User.java
@Entity @Table(name = "users") @Data @NoArgsConstructor @AllArgsConstructor public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(unique = true) private String username; private String password; private String name; private String email; private Instant createdAt; @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private List<Post> posts; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "user_followers", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "follower_id")) private Set<User> followers = new HashSet<>(); @ManyToMany(mappedBy = "followers", fetch = FetchType.LAZY) private Set<User> following = new HashSet<>(); }Post.java
@Entity @Table(name = "posts") @Data @NoArgsConstructor @AllArgsConstructor public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String content; private Instant createdAt; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id", referencedColumnName = "id") private User user; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "post_likes", joinColumns = @JoinColumn(name = "post_id"), inverseJoinColumns = @JoinColumn(name = "user_id")) private Set<User> likedBy = new HashSet<>(); }2. Repositories
UserRepository.java
public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByUsername(String username); Optional<User> findByEmail(String email); Boolean existsByUsername(String username); Boolean existsByEmail(String email); }PostRepository.java
public interface PostRepository extends JpaRepository<Post, Long> { List<Post> findAllByUserOrderByCreatedAtDesc(User user); List<Post> findAllByUserInOrderByCreatedAtDesc(List<User> users); }3. Services
AuthService.java
@Service @AllArgsConstructor public class AuthService { private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; private final JwtProvider jwtProvider; private final AuthenticationManager authenticationManager; public void signup(RegisterRequest registerRequest) { User user = new User(); user.setUsername(registerRequest.getUsername()); user.setEmail(registerRequest.getEmail()); user.setPassword(passwordEncoder.encode(registerRequest.getPassword())); user.setName(registerRequest.getName()); user.setCreatedAt(Instant.now()); userRepository.save(user); } public String login(LoginRequest loginRequest) { Authentication authenticate = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( loginRequest.getUsername(), loginRequest.getPassword() ) ); SecurityContextHolder.getContext().setAuthentication(authenticate); return jwtProvider.generateToken(authenticate); } }PostService.java
@Service @AllArgsConstructor public class PostService { private final PostRepository postRepository; private final UserRepository userRepository; private final AuthService authService; public PostDto createPost(PostDto postDto) { User currentUser = authService.getCurrentUser(); Post post = new Post(); post.setContent(postDto.getContent()); post.setCreatedAt(Instant.now()); post.setUser(currentUser); Post savedPost = postRepository.save(post); return mapToDto(savedPost); } public List<PostDto> getPostsByUser(String username) { User user = userRepository.findByUsername(username) .orElseThrow(() -> new CustomException("User not found")); return postRepository.findAllByUserOrderByCreatedAtDesc(user) .stream() .map(this::mapToDto) .collect(Collectors.toList()); } public List<PostDto> getFeed() { User currentUser = authService.getCurrentUser(); List<User> following = new ArrayList<>(currentUser.getFollowing()); following.add(currentUser); // Include own posts return postRepository.findAllByUserInOrderByCreatedAtDesc(following) .stream() .map(this::mapToDto) .collect(Collectors.toList()); } private PostDto mapToDto(Post post) { return PostDto.builder() .id(post.getId()) .content(post.getContent()) .username(post.getUser().getUsername()) .createdAt(post.getCreatedAt()) .likeCount(post.getLikedBy().size()) .build(); } }4. Controllers
PostController.java
@RestController @RequestMapping("/api/posts") @AllArgsConstructor public class PostController { private final PostService postService; @PostMapping public ResponseEntity<PostDto> createPost(@RequestBody PostDto postDto) { return ResponseEntity.status(HttpStatus.CREATED) .body(postService.createPost(postDto)); } @GetMapping("/by-user/{username}") public ResponseEntity<List<PostDto>> getPostsByUser(@PathVariable String username) { return ResponseEntity.ok(postService.getPostsByUser(username)); } @GetMapping("/feed") public ResponseEntity<List<PostDto>> getFeed() { return ResponseEntity.ok(postService.getFeed()); } }AuthController.java
@RestController @RequestMapping("/api/auth") @AllArgsConstructor public class AuthController { private final AuthService authService; @PostMapping("/signup") public ResponseEntity<String> signup(@RequestBody RegisterRequest registerRequest) { authService.signup(registerRequest); return new ResponseEntity<>("User Registration Successful", HttpStatus.OK); } @PostMapping("/login") public ResponseEntity<String> login(@RequestBody LoginRequest loginRequest) { return ResponseEntity.ok(authService.login(loginRequest)); } }5. Security Configuration
SecurityConfig.java
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @AllArgsConstructor public class SecurityConfig extends WebSecurityConfigurerAdapter { private final JwtAuthenticationFilter jwtAuthenticationFilter; @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable() .authorizeRequests() .antMatchers("/api/auth/**").permitAll() .anyRequest().authenticated(); http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }Dependencies (pom.xml)
<dependencies> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot Starter Data JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- Spring Boot Starter Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- JWT --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.2</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.