[BAEL-9555] - Created a core-java-modules folder
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.assertion;
|
||||
|
||||
/**
|
||||
* Simple demonstration of using Java assert keyword.
|
||||
*/
|
||||
public class Assertion {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Assertion assertion = new Assertion();
|
||||
assertion.setup();
|
||||
}
|
||||
|
||||
public void setup() {
|
||||
Object conn = getConnection();
|
||||
assert conn != null : "Connection is null";
|
||||
|
||||
// continue with other setup ...
|
||||
}
|
||||
|
||||
// Simulate failure to get a connection; using Object
|
||||
// to avoid dependencies on JDBC or some other heavy
|
||||
// 3rd party library
|
||||
public Object getConnection() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.binding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 25-07-2018.
|
||||
*/
|
||||
public class Animal {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(Animal.class);
|
||||
|
||||
public void makeNoise() {
|
||||
logger.info("generic animal noise");
|
||||
}
|
||||
|
||||
public void makeNoise(Integer repetitions) {
|
||||
while(repetitions != 0) {
|
||||
logger.info("generic animal noise countdown " + repetitions);
|
||||
repetitions -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.binding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 25-07-2018.
|
||||
*/
|
||||
public class AnimalActivity {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(AnimalActivity.class);
|
||||
|
||||
|
||||
public static void sleep(Animal animal) {
|
||||
logger.info("Animal is sleeping");
|
||||
}
|
||||
|
||||
public static void sleep(Cat cat) {
|
||||
logger.info("Cat is sleeping");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Animal animal = new Animal();
|
||||
|
||||
//calling methods of animal object
|
||||
animal.makeNoise();
|
||||
|
||||
animal.makeNoise(3);
|
||||
|
||||
|
||||
//assigning a dog object to reference of type Animal
|
||||
Animal catAnimal = new Cat();
|
||||
|
||||
catAnimal.makeNoise();
|
||||
|
||||
// calling static function
|
||||
AnimalActivity.sleep(catAnimal);
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.binding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 25-07-2018.
|
||||
*/
|
||||
public class Cat extends Animal {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(Cat.class);
|
||||
|
||||
public void makeNoise() {
|
||||
|
||||
logger.info("meow");
|
||||
}
|
||||
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.chainedexception;
|
||||
|
||||
import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
|
||||
import com.baeldung.chainedexception.exceptions.ManagerUpsetException;
|
||||
import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException;
|
||||
import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException;
|
||||
|
||||
public class LogWithChain {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
getLeave();
|
||||
}
|
||||
|
||||
private static void getLeave() throws NoLeaveGrantedException {
|
||||
try {
|
||||
howIsTeamLead();
|
||||
} catch (TeamLeadUpsetException e) {
|
||||
throw new NoLeaveGrantedException("Leave not sanctioned.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsTeamLead() throws TeamLeadUpsetException {
|
||||
try {
|
||||
howIsManager();
|
||||
} catch (ManagerUpsetException e) {
|
||||
throw new TeamLeadUpsetException("Team lead is not in good mood", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsManager() throws ManagerUpsetException {
|
||||
try {
|
||||
howIsGirlFriendOfManager();
|
||||
} catch (GirlFriendOfManagerUpsetException e) {
|
||||
throw new ManagerUpsetException("Manager is in bad mood", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.chainedexception;
|
||||
|
||||
import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
|
||||
import com.baeldung.chainedexception.exceptions.ManagerUpsetException;
|
||||
import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException;
|
||||
import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException;
|
||||
|
||||
public class LogWithoutChain {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
getLeave();
|
||||
}
|
||||
|
||||
private static void getLeave() throws NoLeaveGrantedException {
|
||||
try {
|
||||
howIsTeamLead();
|
||||
} catch (TeamLeadUpsetException e) {
|
||||
e.printStackTrace();
|
||||
throw new NoLeaveGrantedException("Leave not sanctioned.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsTeamLead() throws TeamLeadUpsetException {
|
||||
try {
|
||||
howIsManager();
|
||||
} catch (ManagerUpsetException e) {
|
||||
e.printStackTrace();
|
||||
throw new TeamLeadUpsetException("Team lead is not in good mood");
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsManager() throws ManagerUpsetException {
|
||||
try {
|
||||
howIsGirlFriendOfManager();
|
||||
} catch (GirlFriendOfManagerUpsetException e) {
|
||||
e.printStackTrace();
|
||||
throw new ManagerUpsetException("Manager is in bad mood");
|
||||
}
|
||||
}
|
||||
|
||||
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.chainedexception.exceptions;
|
||||
|
||||
public class GirlFriendOfManagerUpsetException extends Exception {
|
||||
|
||||
public GirlFriendOfManagerUpsetException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public GirlFriendOfManagerUpsetException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.chainedexception.exceptions;
|
||||
|
||||
public class ManagerUpsetException extends Exception {
|
||||
|
||||
public ManagerUpsetException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public ManagerUpsetException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.chainedexception.exceptions;
|
||||
|
||||
public class NoLeaveGrantedException extends Exception {
|
||||
|
||||
public NoLeaveGrantedException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public NoLeaveGrantedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.chainedexception.exceptions;
|
||||
|
||||
public class TeamLeadUpsetException extends Exception {
|
||||
|
||||
public TeamLeadUpsetException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public TeamLeadUpsetException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.className;
|
||||
|
||||
public class RetrievingClassName {
|
||||
|
||||
public class InnerClass {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.comparable;
|
||||
|
||||
public class Player implements Comparable<Player> {
|
||||
|
||||
private int ranking;
|
||||
|
||||
private String name;
|
||||
|
||||
private int age;
|
||||
|
||||
public Player(int ranking, String name, int age) {
|
||||
this.ranking = ranking;
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public int getRanking() {
|
||||
return ranking;
|
||||
}
|
||||
|
||||
public void setRanking(int ranking) {
|
||||
this.ranking = ranking;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Player otherPlayer) {
|
||||
return (this.getRanking() - otherPlayer.getRanking());
|
||||
}
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.comparable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class PlayerSorter {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
List<Player> footballTeam = new ArrayList<Player>();
|
||||
Player player1 = new Player(59, "John", 20);
|
||||
Player player2 = new Player(67, "Roger", 22);
|
||||
Player player3 = new Player(45, "Steven", 24);
|
||||
footballTeam.add(player1);
|
||||
footballTeam.add(player2);
|
||||
footballTeam.add(player3);
|
||||
|
||||
System.out.println("Before Sorting : " + footballTeam);
|
||||
Collections.sort(footballTeam);
|
||||
System.out.println("After Sorting : " + footballTeam);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.comparator;
|
||||
|
||||
public class Player {
|
||||
|
||||
private int ranking;
|
||||
|
||||
private String name;
|
||||
|
||||
private int age;
|
||||
|
||||
public Player(int ranking, String name, int age) {
|
||||
this.ranking = ranking;
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public int getRanking() {
|
||||
return ranking;
|
||||
}
|
||||
|
||||
public void setRanking(int ranking) {
|
||||
this.ranking = ranking;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.comparator;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
public class PlayerAgeComparator implements Comparator<Player> {
|
||||
|
||||
@Override
|
||||
public int compare(Player firstPlayer, Player secondPlayer) {
|
||||
return (firstPlayer.getAge() - secondPlayer.getAge());
|
||||
}
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.comparator;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class PlayerAgeSorter {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
List<Player> footballTeam = new ArrayList<Player>();
|
||||
Player player1 = new Player(59, "John", 22);
|
||||
Player player2 = new Player(67, "Roger", 20);
|
||||
Player player3 = new Player(45, "Steven", 24);
|
||||
footballTeam.add(player1);
|
||||
footballTeam.add(player2);
|
||||
footballTeam.add(player3);
|
||||
|
||||
System.out.println("Before Sorting : " + footballTeam);
|
||||
//Instance of PlayerAgeComparator
|
||||
PlayerAgeComparator playerComparator = new PlayerAgeComparator();
|
||||
Collections.sort(footballTeam, playerComparator);
|
||||
System.out.println("After Sorting by age : " + footballTeam);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.comparator;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
public class PlayerRankingComparator implements Comparator<Player> {
|
||||
|
||||
@Override
|
||||
public int compare(Player firstPlayer, Player secondPlayer) {
|
||||
return (firstPlayer.getRanking() - secondPlayer.getRanking());
|
||||
}
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.comparator;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class PlayerRankingSorter {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
List<Player> footballTeam = new ArrayList<Player>();
|
||||
Player player1 = new Player(59, "John", 22);
|
||||
Player player2 = new Player(67, "Roger", 20);
|
||||
Player player3 = new Player(45, "Steven", 40);
|
||||
footballTeam.add(player1);
|
||||
footballTeam.add(player2);
|
||||
footballTeam.add(player3);
|
||||
|
||||
System.out.println("Before Sorting : " + footballTeam);
|
||||
//Instance of PlayerRankingComparator
|
||||
PlayerRankingComparator playerComparator = new PlayerRankingComparator();
|
||||
Collections.sort(footballTeam, playerComparator);
|
||||
System.out.println("After Sorting by ranking : " + footballTeam);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.controlstructures;
|
||||
|
||||
public class ConditionalBranches {
|
||||
|
||||
/**
|
||||
* Multiple if/else/else if statements examples. Shows different syntax usage.
|
||||
*/
|
||||
public static void ifElseStatementsExamples() {
|
||||
int count = 2; // Initial count value.
|
||||
|
||||
// Basic syntax. Only one statement follows. No brace usage.
|
||||
if (count > 1)
|
||||
System.out.println("Count is higher than 1");
|
||||
|
||||
// Basic syntax. More than one statement can be included. Braces are used (recommended syntax).
|
||||
if (count > 1) {
|
||||
System.out.println("Count is higher than 1");
|
||||
System.out.println("Count is equal to: " + count);
|
||||
}
|
||||
|
||||
// If/Else syntax. Two different courses of action can be included.
|
||||
if (count > 2) {
|
||||
System.out.println("Count is higher than 2");
|
||||
} else {
|
||||
System.out.println("Count is lower or equal than 2");
|
||||
}
|
||||
|
||||
// If/Else/Else If syntax. Three or more courses of action can be included.
|
||||
if (count > 2) {
|
||||
System.out.println("Count is higher than 2");
|
||||
} else if (count <= 0) {
|
||||
System.out.println("Count is less or equal than zero");
|
||||
} else {
|
||||
System.out.println("Count is either equal to one, or two");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ternary Operator example.
|
||||
* @see ConditionalBranches#ifElseStatementsExamples()
|
||||
*/
|
||||
public static void ternaryExample() {
|
||||
int count = 2;
|
||||
System.out.println(count > 2 ? "Count is higher than 2" : "Count is lower or equal than 2");
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch structure example. Shows how to replace multiple if/else statements with one structure.
|
||||
*/
|
||||
public static void switchExample() {
|
||||
int count = 3;
|
||||
switch (count) {
|
||||
case 0:
|
||||
System.out.println("Count is equal to 0");
|
||||
break;
|
||||
case 1:
|
||||
System.out.println("Count is equal to 1");
|
||||
break;
|
||||
case 2:
|
||||
System.out.println("Count is equal to 2");
|
||||
break;
|
||||
default:
|
||||
System.out.println("Count is either negative, or higher than 2");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package com.baeldung.controlstructures;
|
||||
|
||||
public class Loops {
|
||||
|
||||
/**
|
||||
* Dummy method. Only prints a generic message.
|
||||
*/
|
||||
private static void methodToRepeat() {
|
||||
System.out.println("Dummy method.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows how to iterate 50 times with 3 different method/control structures.
|
||||
*/
|
||||
public static void repetitionTo50Examples() {
|
||||
for (int i = 1; i <= 50; i++) {
|
||||
methodToRepeat();
|
||||
}
|
||||
|
||||
int whileCounter = 1;
|
||||
while (whileCounter <= 50) {
|
||||
methodToRepeat();
|
||||
whileCounter++;
|
||||
}
|
||||
|
||||
int count = 1;
|
||||
do {
|
||||
methodToRepeat();
|
||||
count++;
|
||||
} while (count < 50);
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a sentence in words, and prints each word in a new line.
|
||||
* @param sentence Sentence to print as independent words.
|
||||
*/
|
||||
public static void printWordByWord(String sentence) {
|
||||
for (String word : sentence.split(" ")) {
|
||||
System.out.println(word);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints text an N amount of times. Shows usage of the {@code break} branching statement.
|
||||
* @param textToPrint Text to repeatedly print.
|
||||
* @param times Amount to times to print received text.
|
||||
*/
|
||||
public static void printTextNTimes(String textToPrint, int times) {
|
||||
int counter = 1;
|
||||
while (true) {
|
||||
System.out.println(textToPrint);
|
||||
if (counter == times) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints text an N amount of times, up to 50. Shows usage of the {@code break} branching statement.
|
||||
* @param textToPrint Text to repeatedly print.
|
||||
* @param times Amount to times to print received text. If times is higher than 50, textToPrint will only be printed 50 times.
|
||||
*/
|
||||
public static void printTextNTimesUpTo50(String textToPrint, int times) {
|
||||
int counter = 1;
|
||||
while (counter < 50) {
|
||||
System.out.println(textToPrint);
|
||||
if (counter == times) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the index of {@code name} in a list
|
||||
* @param name The name to look for
|
||||
* @param names The list of names
|
||||
* @return The index where the name was found or -1 otherwise
|
||||
*/
|
||||
public static int findFirstInstanceOfName(String name, String[] names) {
|
||||
int index = 0;
|
||||
for ( ; index < names.length; index++) {
|
||||
if (names[index].equals(name)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return index == names.length ? -1 : index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes several names and makes a list, skipping the specified {@code name}.
|
||||
*
|
||||
* @param name The name to skip
|
||||
* @param names The list of names
|
||||
* @return The list of names as a single string, missing the specified {@code name}.
|
||||
*/
|
||||
public static String makeListSkippingName(String name, String[] names) {
|
||||
String list = "";
|
||||
for (int i = 0; i < names.length; i++) {
|
||||
if (names[i].equals(name)) {
|
||||
continue;
|
||||
}
|
||||
list += names[i];
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints an specified amount of even numbers. Shows usage of both {@code break} and {@code continue} branching statements.
|
||||
* @param amountToPrint Amount of even numbers to print.
|
||||
*/
|
||||
public static void printEvenNumbers(int amountToPrint) {
|
||||
if (amountToPrint <= 0) { // Invalid input
|
||||
return;
|
||||
}
|
||||
int iterator = 0;
|
||||
int amountPrinted = 0;
|
||||
while (true) {
|
||||
if (iterator % 2 == 0) { // Is an even number
|
||||
System.out.println(iterator);
|
||||
amountPrinted++;
|
||||
iterator++;
|
||||
} else {
|
||||
iterator++;
|
||||
continue; // Won't print
|
||||
}
|
||||
if (amountPrinted == amountToPrint) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints an specified amount of even numbers, up to 100. Shows usage of both {@code break} and {@code continue} branching statements.
|
||||
* @param amountToPrint Amount of even numbers to print.
|
||||
*/
|
||||
public static void printEvenNumbersToAMaxOf100(int amountToPrint) {
|
||||
if (amountToPrint <= 0) { // Invalid input
|
||||
return;
|
||||
}
|
||||
int iterator = 0;
|
||||
int amountPrinted = 0;
|
||||
while (amountPrinted < 100) {
|
||||
if (iterator % 2 == 0) { // Is an even number
|
||||
System.out.println(iterator);
|
||||
amountPrinted++;
|
||||
iterator++;
|
||||
} else {
|
||||
iterator++;
|
||||
continue; // Won't print
|
||||
}
|
||||
if (amountPrinted == amountToPrint) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.customexception;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class FileManager {
|
||||
|
||||
public static String getFirstLine(String fileName) throws IncorrectFileNameException {
|
||||
try (Scanner file = new Scanner(new File(fileName))) {
|
||||
if (file.hasNextLine()) {
|
||||
return file.nextLine();
|
||||
} else {
|
||||
throw new IllegalArgumentException("Non readable file");
|
||||
}
|
||||
} catch (FileNotFoundException err) {
|
||||
if (!isCorrectFileName(fileName)) {
|
||||
throw new IncorrectFileNameException("Incorrect filename : " + fileName, err);
|
||||
}
|
||||
// Logging etc
|
||||
} catch (IllegalArgumentException err) {
|
||||
if (!containsExtension(fileName)) {
|
||||
throw new IncorrectFileExtensionException("Filename does not contain extension : " + fileName, err);
|
||||
}
|
||||
// Other error cases and logging
|
||||
}
|
||||
return "Default First Line";
|
||||
}
|
||||
|
||||
private static boolean containsExtension(String fileName) {
|
||||
if (fileName.contains(".txt") || fileName.contains(".doc"))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isCorrectFileName(String fileName) {
|
||||
if (fileName.equals("wrongFileName.txt"))
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.customexception;
|
||||
|
||||
public class IncorrectFileExtensionException extends RuntimeException{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileExtensionException(String errorMessage, Throwable err) {
|
||||
super(errorMessage, err);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.customexception;
|
||||
|
||||
public class IncorrectFileNameException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileNameException(String errorMessage, Throwable err) {
|
||||
super(errorMessage, err);
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.doubles;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class SplitFloatingPointNumbers {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
double doubleNumber = 24.04;
|
||||
splitUsingFloatingTypes(doubleNumber);
|
||||
splitUsingString(doubleNumber);
|
||||
splitUsingBigDecimal(doubleNumber);
|
||||
}
|
||||
|
||||
private static void splitUsingFloatingTypes(double doubleNumber) {
|
||||
System.out.println("Using Floating Point Arithmetics:");
|
||||
int intPart = (int) doubleNumber;
|
||||
System.out.println("Double Number: "+doubleNumber);
|
||||
System.out.println("Integer Part: "+ intPart);
|
||||
System.out.println("Decimal Part: "+ (doubleNumber - intPart));
|
||||
}
|
||||
|
||||
private static void splitUsingString(double doubleNumber) {
|
||||
System.out.println("Using String Operations:");
|
||||
String doubleAsString = String.valueOf(doubleNumber);
|
||||
int indexOfDecimal = doubleAsString.indexOf(".");
|
||||
System.out.println("Double Number: "+doubleNumber);
|
||||
System.out.println("Integer Part: "+ doubleAsString.substring(0, indexOfDecimal));
|
||||
System.out.println("Decimal Part: "+ doubleAsString.substring(indexOfDecimal));
|
||||
}
|
||||
|
||||
private static void splitUsingBigDecimal(double doubleNumber) {
|
||||
System.out.println("Using BigDecimal Operations:");
|
||||
BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubleNumber));
|
||||
int intValue = bigDecimal.intValue();
|
||||
System.out.println("Double Number: "+bigDecimal.toPlainString());
|
||||
System.out.println("Integer Part: "+intValue);
|
||||
System.out.println("Decimal Part: "+bigDecimal.subtract(new BigDecimal(intValue)).toPlainString());
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.dynamicproxy;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class DynamicInvocationHandler implements InvocationHandler {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(DynamicInvocationHandler.class);
|
||||
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
LOGGER.info("Invoked method: {}", method.getName());
|
||||
|
||||
return 42;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.dynamicproxy;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class TimingDynamicInvocationHandler implements InvocationHandler {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(TimingDynamicInvocationHandler.class);
|
||||
private final Map<String, Method> methods = new HashMap<>();
|
||||
|
||||
private Object target;
|
||||
|
||||
TimingDynamicInvocationHandler(Object target) {
|
||||
this.target = target;
|
||||
|
||||
for(Method method: target.getClass().getDeclaredMethods()) {
|
||||
this.methods.put(method.getName(), method);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
long start = System.nanoTime();
|
||||
Object result = methods.get(method.getName()).invoke(target, args);
|
||||
long elapsed = System.nanoTime() - start;
|
||||
|
||||
LOGGER.info("Executing {} finished in {} ns", method.getName(), elapsed);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.enums.values;
|
||||
|
||||
/**
|
||||
* This is a simple enum of periodic table elements
|
||||
*/
|
||||
public enum Element1 {
|
||||
H,
|
||||
HE,
|
||||
LI,
|
||||
BE,
|
||||
B,
|
||||
C,
|
||||
N,
|
||||
O,
|
||||
F,
|
||||
NE
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.enums.values;
|
||||
|
||||
/**
|
||||
* The simple enum has been enhanced to add the name of the element.
|
||||
*/
|
||||
public enum Element2 {
|
||||
H("Hydrogen"),
|
||||
HE("Helium"),
|
||||
LI("Lithium"),
|
||||
BE("Beryllium"),
|
||||
B("Boron"),
|
||||
C("Carbon"),
|
||||
N("Nitrogen"),
|
||||
O("Oxygen"),
|
||||
F("Flourine"),
|
||||
NE("Neon");
|
||||
|
||||
/** a final variable to store the label, which can't be changed */
|
||||
public final String label;
|
||||
|
||||
/**
|
||||
* A private constructor that sets the label.
|
||||
* @param label
|
||||
*/
|
||||
private Element2(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up Element2 instances by the label field. This implementation iterates through
|
||||
* the values() list to find the label.
|
||||
* @param label The label to look up
|
||||
* @return The Element2 instance with the label, or null if not found.
|
||||
*/
|
||||
public static Element2 valueOfLabel(String label) {
|
||||
for (Element2 e2 : values()) {
|
||||
if (e2.label.equals(label)) {
|
||||
return e2;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Override the toString() method to return the label instead of the declared name.
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.label;
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.enums.values;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A Map has been added to cache labels for faster lookup.
|
||||
*/
|
||||
public enum Element3 {
|
||||
H("Hydrogen"),
|
||||
HE("Helium"),
|
||||
LI("Lithium"),
|
||||
BE("Beryllium"),
|
||||
B("Boron"),
|
||||
C("Carbon"),
|
||||
N("Nitrogen"),
|
||||
O("Oxygen"),
|
||||
F("Flourine"),
|
||||
NE("Neon");
|
||||
|
||||
/**
|
||||
* A map to cache labels and their associated Element3 instances.
|
||||
* Note that this only works if the labels are all unique!
|
||||
*/
|
||||
private static final Map<String, Element3> BY_LABEL = new HashMap<>();
|
||||
|
||||
/** populate the BY_LABEL cache */
|
||||
static {
|
||||
for (Element3 e3 : values()) {
|
||||
BY_LABEL.put(e3.label, e3);
|
||||
}
|
||||
}
|
||||
|
||||
/** a final variable to store the label, which can't be changed */
|
||||
public final String label;
|
||||
|
||||
/**
|
||||
* A private constructor that sets the label.
|
||||
* @param label
|
||||
*/
|
||||
private Element3(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up Element2 instances by the label field. This implementation finds the
|
||||
* label in the BY_LABEL cache.
|
||||
* @param label The label to look up
|
||||
* @return The Element3 instance with the label, or null if not found.
|
||||
*/
|
||||
public static Element3 valueOfLabel(String label) {
|
||||
return BY_LABEL.get(label);
|
||||
}
|
||||
|
||||
/**
|
||||
* Override the toString() method to return the label instead of the declared name.
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.label;
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package com.baeldung.enums.values;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Multiple fields have been added and the Labeled interface is implemented.
|
||||
*/
|
||||
public enum Element4 implements Labeled {
|
||||
H("Hydrogen", 1, 1.008f),
|
||||
HE("Helium", 2, 4.0026f),
|
||||
LI("Lithium", 3, 6.94f),
|
||||
BE("Beryllium", 4, 9.01722f),
|
||||
B("Boron", 5, 10.81f),
|
||||
C("Carbon", 6, 12.011f),
|
||||
N("Nitrogen", 7, 14.007f),
|
||||
O("Oxygen", 8, 15.999f),
|
||||
F("Flourine", 9, 18.998f),
|
||||
NE("Neon", 10, 20.180f);
|
||||
/**
|
||||
* Maps cache labels and their associated Element3 instances.
|
||||
* Note that this only works if the values are all unique!
|
||||
*/
|
||||
private static final Map<String, Element4> BY_LABEL = new HashMap<>();
|
||||
private static final Map<Integer, Element4> BY_ATOMIC_NUMBER = new HashMap<>();
|
||||
private static final Map<Float, Element4> BY_ATOMIC_WEIGHT = new HashMap<>();
|
||||
|
||||
/** populate the caches */
|
||||
static {
|
||||
for (Element4 e4 : values()) {
|
||||
BY_LABEL.put(e4.label, e4);
|
||||
BY_ATOMIC_NUMBER.put(e4.atomicNumber, e4);
|
||||
BY_ATOMIC_WEIGHT.put(e4.atomicWeight, e4);
|
||||
}
|
||||
}
|
||||
|
||||
/** final variables to store the values, which can't be changed */
|
||||
public final String label;
|
||||
public final int atomicNumber;
|
||||
public final float atomicWeight;
|
||||
|
||||
private Element4(String label, int atomicNumber, float atomicWeight) {
|
||||
this.label = label;
|
||||
this.atomicNumber = atomicNumber;
|
||||
this.atomicWeight = atomicWeight;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implement the Labeled interface.
|
||||
* @return the label value
|
||||
*/
|
||||
@Override
|
||||
public String label() {
|
||||
return label;
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up Element2 instances by the label field. This implementation finds the
|
||||
* label in the BY_LABEL cache.
|
||||
* @param label The label to look up
|
||||
* @return The Element4 instance with the label, or null if not found.
|
||||
*/
|
||||
public static Element4 valueOfLabel(String label) {
|
||||
return BY_LABEL.get(label);
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up Element2 instances by the atomicNumber field. This implementation finds the
|
||||
* atomicNUmber in the cache.
|
||||
* @param number The atomicNumber to look up
|
||||
* @return The Element4 instance with the label, or null if not found.
|
||||
*/
|
||||
public static Element4 valueOfAtomicNumber(int number) {
|
||||
return BY_ATOMIC_NUMBER.get(number);
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up Element2 instances by the atomicWeight field. This implementation finds the
|
||||
* atomic weight in the cache.
|
||||
* @param weight the atomic weight to look up
|
||||
* @return The Element4 instance with the label, or null if not found.
|
||||
*/
|
||||
public static Element4 valueOfAtomicWeight(float weight) {
|
||||
return BY_ATOMIC_WEIGHT.get(weight);
|
||||
}
|
||||
|
||||
/**
|
||||
* Override the toString() method to return the label instead of the declared name.
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.label;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user