Example CodeFeaturedJavaProgrammingTutorials

10 Useful Code Snippets for Java Developers

2 Mins read
Streamline Your Work: 10 Essential Java Snippets for Professionals

Java Developer’s Cheat Sheet: 10 Handy Code Snippets for Real-World Problems

Enterprise Java development often involves solving recurring challenges efficiently. Whether it’s managing databases, handling exceptions, or working with large data, having practical code snippets handy can save time and reduce errors. Here are 10 essential Java snippets tailored for common enterprise scenarios.

1. Database Connection Pooling with HikariCP

Efficient database connection management is crucial for performance in enterprise applications:

HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
config.setUsername("user");
config.setPassword("password");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

HikariDataSource dataSource = new HikariDataSource(config);

try (Connection conn = dataSource.getConnection()) {
    PreparedStatement stmt = conn.prepareStatement("SELECT * FROM employees");
    ResultSet rs = stmt.executeQuery();
    while (rs.next()) {
        System.out.println(rs.getString("name"));
    }
}

2. Read and Write JSON Using Jackson

JSON handling is ubiquitous in enterprise apps for APIs and configuration:

ObjectMapper mapper = new ObjectMapper();

// Serialize object to JSON
Employee emp = new Employee(1, "John Doe", "IT");
String jsonString = mapper.writeValueAsString(emp);
System.out.println(jsonString);

// Deserialize JSON to object
Employee empFromJson = mapper.readValue(jsonString, Employee.class);
System.out.println(empFromJson);

3. Centralized Exception Handling in Spring Boot

Streamline error responses with a global exception handler:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(EntityNotFoundException.class)
    public ResponseEntity<String> handleEntityNotFound(EntityNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGenericException(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + ex.getMessage());
    }
}

4. Paginate Results Using JPA

Pagination is vital for handling large datasets efficiently:

Pageable pageable = PageRequest.of(0, 10, Sort.by("name").ascending());
Page<Employee> employees = employeeRepository.findAll(pageable);

employees.forEach(emp -> System.out.println(emp.getName()));

5. Encrypt and Decrypt Sensitive Data

Secure sensitive information with AES encryption:

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES");

// Encrypt
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encrypted = cipher.doFinal("SensitiveData".getBytes());
System.out.println(Base64.getEncoder().encodeToString(encrypted));

// Decrypt
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decrypted = cipher.doFinal(encrypted);
System.out.println(new String(decrypted));

6. Cache Data Using Ehcache

Enhance performance by caching frequently accessed data:

CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .withCache("preConfigured",
            CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
                ResourcePoolsBuilder.heap(100)))
        .build(true);

Cache<String, String> cache = cacheManager.getCache("preConfigured", String.class, String.class);
cache.put("key1", "value1");
System.out.println(cache.get("key1"));

7. Send Emails with JavaMail

Automate email notifications using JavaMail:

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");

Session session = Session.getInstance(props, new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("user@example.com", "password");
    }
});

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("user@example.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com"));
message.setSubject("Test Email");
message.setText("This is a test email.");

Transport.send(message);
System.out.println("Email sent successfully");

8. Handle Large Files with Streaming

Process large files efficiently without loading them into memory:

try (BufferedReader br = new BufferedReader(new FileReader("largefile.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

9. Generate UUIDs for Unique Identifiers

Generate unique IDs for entities easily:

String uuid = UUID.randomUUID().toString();
System.out.println("Generated UUID: " + uuid);

10. Retry Logic for Resilient API Calls

Implement retry logic for unstable external services:

RetryPolicy<Object> retryPolicy = new RetryPolicy<>()
    .handle(Exception.class)
    .withDelay(Duration.ofSeconds(2))
    .withMaxRetries(3);

Failsafe.with(retryPolicy).run(() -> {
    // Your API call or operation
    System.out.println("Attempting operation...");
    if (new Random().nextBoolean()) {
        throw new RuntimeException("Simulated failure");
    }
    System.out.println("Operation succeeded");
});

Conclusion

These practical Java code snippets address real-world enterprise development needs. Keep this cheat sheet handy to boost productivity, reduce repetitive tasks, and streamline your workflow. Whether it’s handling JSON, caching data, or securing sensitive information, these snippets are indispensable for any Java developer.

Leave a Reply

Your email address will not be published. Required fields are marked *