forked from anomalyco/opencode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme-test.java
More file actions
461 lines (384 loc) · 14.9 KB
/
theme-test.java
File metadata and controls
461 lines (384 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package com.example.theme;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.stream.*;
import java.time.*;
import java.time.format.*;
import java.net.*;
import java.io.*;
import java.nio.file.*;
import java.sql.*;
import java.lang.annotation.*;
import java.math.BigDecimal;
import java.math.BigInteger;
// Enum definition
public enum LogLevel {
DEBUG(0, "Debug"),
INFO(1, "Info"),
WARN(2, "Warning"),
ERROR(3, "Error");
private final int level;
private final String description;
LogLevel(int level, String description) {
this.level = level;
this.description = description;
}
public int getLevel() { return level; }
public String getDescription() { return description; }
}
// Interface with generics
public interface Repository<T extends Entity> {
Optional<T> findById(Long id);
List<T> findAll();
T save(T entity);
void delete(Long id);
Stream<T> stream();
@FunctionalInterface
interface Predicate<T> {
boolean test(T t);
}
}
// Abstract class
public abstract class AbstractService<T extends Entity> implements Repository<T> {
protected final Map<Long, T> cache = new ConcurrentHashMap<>();
protected volatile boolean initialized = false;
@Override
public Optional<T> findById(Long id) {
return Optional.ofNullable(cache.get(id));
}
@Override
public List<T> findAll() {
return new ArrayList<>(cache.values());
}
@Override
public Stream<T> stream() {
return cache.values().stream();
}
protected abstract void validate(T entity) throws ValidationException;
}
// Annotation definition
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Service {
String value() default "";
boolean transactional() default true;
Class<?>[] exceptions() = {};
}
// Record class (Java 14+)
public record User(
Long id,
String username,
String email,
@Deprecated String fullName,
LocalDateTime createdAt,
boolean active
) implements Entity {
public User {
Objects.requireNonNull(username, "Username cannot be null");
Objects.requireNonNull(email, "Email cannot be null");
Objects.requireNonNull(createdAt, "Created date cannot be null");
}
public static User of(String username, String email) {
return new User(null, username, email, null, LocalDateTime.now(), true);
}
public User withId(Long id) {
return new User(id, username, email, fullName, createdAt, active);
}
}
// Exception classes
public class ValidationException extends RuntimeException {
private final List<String> errors;
public ValidationException(String message) {
super(message);
this.errors = List.of(message);
}
public ValidationException(List<String> errors) {
super(String.join(", ", errors));
this.errors = Collections.unmodifiableList(errors);
}
public List<String> getErrors() { return errors; }
}
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String resource, Long id) {
super(String.format("%s with id %d not found", resource, id));
}
}
// Service implementation
@Service(value = "userService", transactional = true)
public class UserService extends AbstractService<User> {
private static final Logger logger = LoggerFactory.getLogger(UserService.class);
private static final int MAX_RETRY_ATTEMPTS = 3;
private static final Duration TIMEOUT = Duration.ofSeconds(30);
private final EmailService emailService;
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
@Inject
public UserService(EmailService emailService,
UserRepository userRepository,
PasswordEncoder passwordEncoder) {
this.emailService = emailService;
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
@Override
protected void validate(User user) throws ValidationException {
List<String> errors = new ArrayList<>();
if (user.username() == null || user.username().trim().isEmpty()) {
errors.add("Username is required");
} else if (!user.username().matches("^[a-zA-Z0-9_]{3,20}$")) {
errors.add("Username must be 3-20 characters, alphanumeric and underscore only");
}
if (user.email() == null || !user.email().matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
errors.add("Valid email is required");
}
if (!errors.isEmpty()) {
throw new ValidationException(errors);
}
}
@Transactional
public User createUser(CreateUserRequest request) throws ValidationException {
logger.info("Creating new user: {}", request.username());
// Check if user already exists
if (userRepository.findByUsername(request.username()).isPresent()) {
throw new ValidationException("Username already exists");
}
if (userRepository.findByEmail(request.email()).isPresent()) {
throw new ValidationException("Email already exists");
}
// Create new user
User user = User.of(request.username(), request.email())
.withId(generateId());
validate(user);
try {
User savedUser = userRepository.save(user);
cache.put(savedUser.id(), savedUser);
// Send welcome email asynchronously
CompletableFuture.runAsync(() ->
emailService.sendWelcomeEmail(savedUser)
).exceptionally(throwable -> {
logger.error("Failed to send welcome email to user {}", savedUser.id(), throwable);
return null;
});
logger.info("Successfully created user with ID: {}", savedUser.id());
return savedUser;
} catch (DataAccessException e) {
logger.error("Database error while creating user", e);
throw new ServiceException("Failed to create user", e);
}
}
public Optional<User> findByUsername(String username) {
return cache.values().stream()
.filter(user -> user.username().equals(username))
.findFirst();
}
public List<User> findActiveUsers() {
return cache.values().stream()
.filter(User::active)
.sorted(Comparator.comparing(User::createdAt).reversed())
.collect(Collectors.toList());
}
@Retry(maxAttempts = MAX_RETRY_ATTEMPTS, backoff = @Backoff(delay = 1000))
public User updateUser(Long id, UpdateUserRequest request) {
User existingUser = findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User", id));
User updatedUser = new User(
id,
request.username() != null ? request.username() : existingUser.username(),
request.email() != null ? request.email() : existingUser.email(),
existingUser.fullName(),
existingUser.createdAt(),
request.active() != null ? request.active() : existingUser.active()
);
validate(updatedUser);
try {
User savedUser = userRepository.save(updatedUser);
cache.put(id, savedUser);
return savedUser;
} catch (DataAccessException e) {
logger.error("Failed to update user with ID: {}", id, e);
throw new ServiceException("Failed to update user", e);
}
}
@Async
public CompletableFuture<Void> deleteUser(Long id) {
return CompletableFuture.runAsync(() -> {
try {
userRepository.deleteById(id);
cache.remove(id);
logger.info("Successfully deleted user with ID: {}", id);
} catch (DataAccessException e) {
logger.error("Failed to delete user with ID: {}", id, e);
throw new ServiceException("Failed to delete user", e);
}
});
}
private Long generateId() {
return System.currentTimeMillis() + (long)(Math.random() * 1000);
}
}
// Utility class
public final class DateUtils {
private DateUtils() {
// Utility class - prevent instantiation
}
private static final DateTimeFormatter ISO_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
public static String formatIsoDateTime(LocalDateTime dateTime) {
return dateTime.atZone(ZoneId.systemDefault()).format(ISO_FORMATTER);
}
public static LocalDateTime parseIsoDateTime(String isoString) {
return LocalDateTime.parse(isoString, ISO_FORMATTER);
}
public static boolean isWithinLastDays(LocalDateTime dateTime, int days) {
return dateTime.isAfter(LocalDateTime.now().minusDays(days));
}
}
// Builder pattern
public class UserQueryBuilder {
private String username;
private String email;
private Boolean active;
private LocalDateTime createdAfter;
private LocalDateTime createdBefore;
private SortOrder sortOrder = SortOrder.ASC;
private String sortBy = "createdAt";
private int limit = 100;
private int offset = 0;
public UserQueryBuilder withUsername(String username) {
this.username = username;
return this;
}
public UserQueryBuilder withEmail(String email) {
this.email = email;
return this;
}
public UserQueryBuilder activeOnly(boolean active) {
this.active = active;
return this;
}
public UserQueryBuilder createdAfter(LocalDateTime date) {
this.createdAfter = date;
return this;
}
public UserQueryBuilder createdBefore(LocalDateTime date) {
this.createdBefore = date;
return this;
}
public UserQueryBuilder sortBy(String field, SortOrder order) {
this.sortBy = field;
this.sortOrder = order;
return this;
}
public UserQueryBuilder limit(int limit) {
this.limit = Math.max(1, Math.min(limit, 1000));
return this;
}
public UserQueryBuilder offset(int offset) {
this.offset = Math.max(0, offset);
return this;
}
public UserQuery build() {
return new UserQuery(username, email, active, createdAfter, createdBefore,
sortBy, sortOrder, limit, offset);
}
}
// Lambda expressions and streams
public class StreamProcessor {
private static final Map<String, Function<String, Object>> TYPE_CONVERTERS = Map.of(
"string", s -> s,
"int", Integer::parseInt,
"double", Double::parseDouble,
"boolean", Boolean::parseBoolean,
"bigdecimal", BigDecimal::new,
"bigint", BigInteger::new
);
public Map<String, Object> processConfig(Properties properties) {
return properties.entrySet().stream()
.filter(entry -> entry.getKey() instanceof String)
.filter(entry -> entry.getValue() != null)
.collect(Collectors.toMap(
entry -> (String) entry.getKey(),
entry -> convertValue((String) entry.getKey(), (String) entry.getValue())
));
}
private Object convertValue(String key, String value) {
String type = determineType(key, value);
return TYPE_CONVERTERS.getOrDefault(type, Function.identity()).apply(value);
}
private String determineType(String key, String value) {
if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) {
return "boolean";
} else if (value.matches("-?\\d+")) {
return "int";
} else if (value.matches("-?\\d*\\.\\d+")) {
return "double";
} else if (key.toLowerCase().contains("amount") || key.toLowerCase().contains("price")) {
return "bigdecimal";
}
return "string";
}
public List<String> validateEmails(List<String> emails) {
return emails.stream()
.filter(Objects::nonNull)
.map(String::trim)
.filter(email -> !email.isEmpty())
.filter(email -> email.matches("^[A-Za-z0-9+_.-]+@(.+)$"))
.distinct()
.collect(Collectors.toList());
}
public CompletableFuture<List<User>> processUsersAsync(List<User> users) {
return CompletableFuture.supplyAsync(() ->
users.parallelStream()
.filter(User::active)
.filter(user -> user.createdAt().isAfter(LocalDateTime.now().minusYears(1)))
.sorted(Comparator.comparing(User::username))
.collect(Collectors.toList())
);
}
}
// Main class for testing
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
try {
// Initialize application context
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// Get service bean
UserService userService = context.getBean(UserService.class);
// Create test users
List<User> users = Arrays.asList(
User.of("john_doe", "john@example.com"),
User.of("jane_smith", "jane@example.com"),
User.of("bob_wilson", "bob@example.com")
);
// Process users
List<CompletableFuture<User>> futures = users.stream()
.map(user -> {
try {
return CompletableFuture.completedFuture(userService.createUser(
new CreateUserRequest(user.username(), user.email())
));
} catch (ValidationException e) {
logger.error("Failed to create user: {}", user.username(), e);
return CompletableFuture.<User>failedFuture(e);
}
})
.collect(Collectors.toList());
// Wait for all to complete
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenRun(() -> {
logger.info("All users created successfully");
System.out.println("Application started successfully!");
})
.exceptionally(throwable -> {
logger.error("Failed to initialize users", throwable);
System.err.println("Application startup failed!");
return null;
});
} catch (Exception e) {
logger.error("Application startup failed", e);
System.exit(1);
}
}
}