geroza
2018-11-10 10:29:12 -02:00
parent 61574b7228
commit 55c49b25f1
49 changed files with 0 additions and 0 deletions
@@ -1,23 +0,0 @@
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;
}
}
}
@@ -1,43 +0,0 @@
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;
}
}
@@ -1,18 +0,0 @@
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");
}
}
@@ -1,43 +0,0 @@
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;
}
}
@@ -1,9 +0,0 @@
package com.baeldung.customexception;
public class IncorrectFileExtensionException extends RuntimeException{
private static final long serialVersionUID = 1L;
public IncorrectFileExtensionException(String errorMessage, Throwable err) {
super(errorMessage, err);
}
}
@@ -1,9 +0,0 @@
package com.baeldung.customexception;
public class IncorrectFileNameException extends Exception {
private static final long serialVersionUID = 1L;
public IncorrectFileNameException(String errorMessage, Throwable err) {
super(errorMessage, err);
}
}
@@ -1,212 +0,0 @@
package com.baeldung.exceptionhandling;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class Exceptions {
private final static Logger logger = Logger.getLogger("ExceptionLogging");
public static List<Player> getPlayers() throws IOException {
Path path = Paths.get("players.dat");
List<String> players = Files.readAllLines(path);
return players.stream()
.map(Player::new)
.collect(Collectors.toList());
}
public List<Player> loadAllPlayers(String playersFile) throws IOException{
try {
throw new IOException();
} catch(IOException ex) {
throw new IllegalStateException();
}
}
public int getPlayerScoreThrows(String playerFile) throws FileNotFoundException {
Scanner contents = new Scanner(new File(playerFile));
return Integer.parseInt(contents.nextLine());
}
public int getPlayerScoreTryCatch(String playerFile) {
try {
Scanner contents = new Scanner(new File(playerFile));
return Integer.parseInt(contents.nextLine());
} catch (FileNotFoundException noFile) {
throw new IllegalArgumentException("File not found");
}
}
public int getPlayerScoreTryCatchRecovery(String playerFile) {
try {
Scanner contents = new Scanner(new File(playerFile));
return Integer.parseInt(contents.nextLine());
} catch ( FileNotFoundException noFile ) {
logger.warning("File not found, resetting score.");
return 0;
}
}
public int getPlayerScoreFinally(String playerFile) throws FileNotFoundException {
Scanner contents = null;
try {
contents = new Scanner(new File(playerFile));
return Integer.parseInt(contents.nextLine());
} finally {
if (contents != null) {
contents.close();
}
}
}
public int getPlayerScoreTryWithResources(String playerFile) {
try (Scanner contents = new Scanner(new File(playerFile))) {
return Integer.parseInt(contents.nextLine());
} catch (FileNotFoundException e ) {
logger.warning("File not found, resetting score.");
return 0;
}
}
public int getPlayerScoreMultipleCatchBlocks(String playerFile) {
try (Scanner contents = new Scanner(new File(playerFile))) {
return Integer.parseInt(contents.nextLine());
} catch (IOException e) {
logger.warning("Player file wouldn't load!");
return 0;
} catch (NumberFormatException e) {
logger.warning("Player file was corrupted!");
return 0;
}
}
public int getPlayerScoreMultipleCatchBlocksAlternative(String playerFile) {
try (Scanner contents = new Scanner(new File(playerFile)) ) {
return Integer.parseInt(contents.nextLine());
} catch (FileNotFoundException e) {
logger.warning("Player file not found!");
return 0;
} catch (IOException e) {
logger.warning("Player file wouldn't load!");
return 0;
} catch (NumberFormatException e) {
logger.warning("Player file was corrupted!");
return 0;
}
}
public int getPlayerScoreUnionCatchBlocks(String playerFile) {
try (Scanner contents = new Scanner(new File(playerFile))) {
return Integer.parseInt(contents.nextLine());
} catch (IOException | NumberFormatException e) {
logger.warning("Failed to load score!");
return 0;
}
}
public List<Player> loadAllPlayersThrowingChecked(String playersFile) throws TimeoutException {
boolean tooLong = true;
while (!tooLong) {
// ... potentially long operation
}
throw new TimeoutException("This operation took too long");
}
public List<Player> loadAllPlayersThrowingUnchecked(String playersFile) throws TimeoutException {
if(!isFilenameValid(playersFile)) {
throw new IllegalArgumentException("Filename isn't valid!");
}
return null;
// ...
}
public List<Player> loadAllPlayersWrapping(String playersFile) throws IOException {
try {
throw new IOException();
} catch (IOException io) {
throw io;
}
}
public List<Player> loadAllPlayersRethrowing(String playersFile) throws PlayerLoadException {
try {
throw new IOException();
} catch (IOException io) {
throw new PlayerLoadException(io);
}
}
public List<Player> loadAllPlayersThrowable(String playersFile) {
try {
throw new NullPointerException();
} catch ( Throwable t ) {
throw t;
}
}
class FewerExceptions extends Exceptions {
@Override
public List<Player> loadAllPlayers(String playersFile) { //can't add "throws MyCheckedException
return null;
// overridden
}
}
public void throwAsGotoAntiPattern() throws MyException {
try {
// bunch of code
throw new MyException();
// second bunch of code
} catch ( MyException e ) {
// third bunch of code
}
}
public int getPlayerScoreSwallowingExceptionAntiPattern(String playerFile) {
try {
// ...
} catch (Exception e) {} // <== catch and swallow
return 0;
}
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative(String playerFile) {
try {
// ...
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative2(String playerFile) throws PlayerScoreException {
try {
throw new IOException();
} catch (IOException e) {
throw new PlayerScoreException(e);
}
}
public int getPlayerScoreReturnInFinallyAntiPattern(String playerFile) {
int score = 0;
try {
throw new IOException();
} finally {
return score; // <== the IOException is dropped
}
}
private boolean isFilenameValid(String name) {
return false;
}
}
@@ -1,5 +0,0 @@
package com.baeldung.exceptionhandling;
public class MyException extends Throwable {
}
@@ -1,12 +0,0 @@
package com.baeldung.exceptionhandling;
public class Player {
public int id;
public String name;
public Player(String name) {
this.name = name;
}
}
@@ -1,11 +0,0 @@
package com.baeldung.exceptionhandling;
import java.io.IOException;
public class PlayerLoadException extends Exception {
public PlayerLoadException(IOException io) {
super(io);
}
}
@@ -1,8 +0,0 @@
package com.baeldung.exceptionhandling;
public class PlayerScoreException extends Exception {
public PlayerScoreException(Exception e) {
super(e);
}
}
@@ -1,8 +0,0 @@
package com.baeldung.exceptionhandling;
public class TimeoutException extends Exception {
public TimeoutException(String message) {
super(message);
}
}
@@ -1,18 +0,0 @@
package com.baeldung.keywords.finalize;
public class FinalizeObject {
@Override
protected void finalize() throws Throwable {
System.out.println("Execute finalize method");
super.finalize();
}
public static void main(String[] args) throws Exception {
FinalizeObject object = new FinalizeObject();
object = null;
System.gc();
Thread.sleep(1000);
}
}
@@ -1,15 +0,0 @@
package com.baeldung.keywords.finalkeyword;
public final class Child extends Parent {
@Override
void method1(int arg1, final int arg2) {
// OK
}
/* @Override
void method2() {
// Compilation error
}*/
}
@@ -1,5 +0,0 @@
package com.baeldung.keywords.finalkeyword;
/*public class GrandChild extends Child {
// Compilation error
}*/
@@ -1,23 +0,0 @@
package com.baeldung.keywords.finalkeyword;
public class Parent {
int field1 = 1;
final int field2 = 2;
Parent() {
field1 = 2; // OK
// field2 = 3; // Compilation error
}
void method1(int arg1, final int arg2) {
arg1 = 2; // OK
// arg2 = 3; // Compilation error
}
final void method2() {
final int localVar = 2; // OK
// localVar = 3; // Compilation error
}
}
@@ -1,29 +0,0 @@
package com.baeldung.keywords.finallykeyword;
public class FinallyExample {
public static void main(String args[]) throws Exception {
try {
System.out.println("Execute try block");
throw new Exception();
} catch (Exception e) {
System.out.println("Execute catch block");
} finally {
System.out.println("Execute finally block");
}
try {
System.out.println("Execute try block");
} finally {
System.out.println("Execute finally block");
}
try {
System.out.println("Execute try block");
throw new Exception();
} finally {
System.out.println("Execute finally block");
}
}
}
@@ -1,8 +0,0 @@
package com.baeldung.stackoverflowerror;
public class AccountHolder {
private String firstName;
private String lastName;
AccountHolder jointAccountHolder = new AccountHolder();
}
@@ -1,16 +0,0 @@
package com.baeldung.stackoverflowerror;
public class ClassOne {
private int oneValue;
private ClassTwo clsTwoInstance = null;
public ClassOne() {
oneValue = 0;
clsTwoInstance = new ClassTwo();
}
public ClassOne(int oneValue, ClassTwo clsTwoInstance) {
this.oneValue = oneValue;
this.clsTwoInstance = clsTwoInstance;
}
}
@@ -1,16 +0,0 @@
package com.baeldung.stackoverflowerror;
public class ClassTwo {
private int twoValue;
private ClassOne clsOneInstance = null;
public ClassTwo() {
twoValue = 10;
clsOneInstance = new ClassOne();
}
public ClassTwo(int twoValue, ClassOne clsOneInstance) {
this.twoValue = twoValue;
this.clsOneInstance = clsOneInstance;
}
}
@@ -1,7 +0,0 @@
package com.baeldung.stackoverflowerror;
public class InfiniteRecursionWithTerminationCondition {
public int calculateFactorial(final int number) {
return number == 1 ? 1 : number * calculateFactorial(number - 1);
}
}
@@ -1,7 +0,0 @@
package com.baeldung.stackoverflowerror;
public class RecursionWithCorrectTerminationCondition {
public int calculateFactorial(final int number) {
return number <= 1 ? 1 : number * calculateFactorial(number - 1);
}
}
@@ -1,7 +0,0 @@
package com.baeldung.stackoverflowerror;
public class UnintendedInfiniteRecursion {
public int calculateFactorial(int number) {
return number * calculateFactorial(number - 1);
}
}
@@ -1,70 +0,0 @@
package com.baeldung.switchstatement;
public class SwitchStatement {
public String exampleOfIF(String animal) {
String result;
if (animal.equals("DOG") || animal.equals("CAT")) {
result = "domestic animal";
} else if (animal.equals("TIGER")) {
result = "wild animal";
} else {
result = "unknown animal";
}
return result;
}
public String exampleOfSwitch(String animal) {
String result;
switch (animal) {
case "DOG":
case "CAT":
result = "domestic animal";
break;
case "TIGER":
result = "wild animal";
break;
default:
result = "unknown animal";
break;
}
return result;
}
public String forgetBreakInSwitch(String animal) {
String result;
switch (animal) {
case "DOG":
System.out.println("domestic animal");
result = "domestic animal";
default:
System.out.println("unknown animal");
result = "unknown animal";
}
return result;
}
public String constantCaseValue(String animal) {
String result = "";
final String dog = "DOG";
switch (animal) {
case dog:
result = "domestic animal";
}
return result;
}
}
@@ -1,23 +0,0 @@
package com.baeldung.synthetic;
import java.util.Comparator;
/**
* Class which contains a synthetic bridge method.
*
* @author Donato Rimenti
*
*/
public class BridgeMethodDemo implements Comparator<Integer> {
/*
* (non-Javadoc)
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Integer o1, Integer o2) {
return 0;
}
}
@@ -1,34 +0,0 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains a synthetic constructor.
*
* @author Donato Rimenti
*
*/
public class SyntheticConstructorDemo {
/**
* We need to instantiate the {@link NestedClass} using a private
* constructor from the enclosing instance in order to generate a synthetic
* constructor.
*/
private NestedClass nestedClass = new NestedClass();
/**
* Class which contains a synthetic constructor.
*
* @author Donato Rimenti
*
*/
class NestedClass {
/**
* In order to generate a synthetic constructor, this class must have a
* private constructor.
*/
private NestedClass() {
}
}
}
@@ -1,22 +0,0 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains a synthetic field reference to the outer
* class.
*
* @author Donato Rimenti
*
*/
public class SyntheticFieldDemo {
/**
* Class which contains a synthetic field reference to the outer class.
*
* @author Donato Rimenti
*
*/
class NestedClass {
}
}
@@ -1,48 +0,0 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains two synthetic methods accessors to a
* private field.
*
* @author Donato Rimenti
*
*/
public class SyntheticMethodDemo {
/**
* Class which contains two synthetic methods accessors to a private field.
*
* @author Donato Rimenti
*
*/
class NestedClass {
/**
* Field for which will be generated synthetic methods accessors. It's
* important that this field is private for this purpose.
*/
private String nestedField;
}
/**
* Gets the private nested field. We need to read the nested field in order
* to generate the synthetic getter.
*
* @return the {@link NestedClass#nestedField}
*/
public String getNestedField() {
return new NestedClass().nestedField;
}
/**
* Sets the private nested field. We need to write the nested field in order
* to generate the synthetic setter.
*
* @param nestedField
* the {@link NestedClass#nestedField}
*/
public void setNestedField(String nestedField) {
new NestedClass().nestedField = nestedField;
}
}
@@ -1,9 +0,0 @@
package com.baeldung.throwsexception;
public class DataAccessException extends RuntimeException {
public DataAccessException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -1,41 +0,0 @@
package com.baeldung.throwsexception;
import com.sun.mail.iap.ConnectionException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.SocketException;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
TryCatch tryCatch = new TryCatch();
try {
tryCatch.execute();
} catch (ConnectionException | SocketException ex) {
System.out.println("IOException");
} catch (Exception ex) {
System.out.println("General exception");
}
checkedException();
checkedExceptionWithThrows();
}
private static void checkedExceptionWithThrows() throws FileNotFoundException {
File file = new File("not_existing_file.txt");
FileInputStream stream = new FileInputStream(file);
}
private static void checkedException() {
File file = new File("not_existing_file.txt");
try {
FileInputStream stream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
@@ -1,12 +0,0 @@
package com.baeldung.throwsexception;
import java.sql.SQLException;
import java.util.List;
public class PersonRepository {
public List<String> findAll() throws SQLException {
throw new SQLException();
}
}
@@ -1,22 +0,0 @@
package com.baeldung.throwsexception;
import java.sql.SQLException;
public class SimpleService {
private PersonRepository personRepository = new PersonRepository();
public void wrappingException() {
try {
personRepository.findAll();
} catch (SQLException e) {
throw new DataAccessException("SQL Exception", e);
}
}
public void runtimeNullPointerException() {
String a = null;
a.length();
}
}
@@ -1,13 +0,0 @@
package com.baeldung.throwsexception;
import com.sun.mail.iap.ConnectionException;
import java.net.SocketException;
public class TryCatch {
public void execute() throws SocketException, ConnectionException, Exception {
//code that would throw any of: SocketException, ConnectionException, Exception
}
}