[BAEL-13505] Move articles out of core-java part 1

This commit is contained in:
Sjmillington
2019-09-05 17:44:52 +01:00
parent 434bfc980e
commit 3e155818d5
36 changed files with 28 additions and 0 deletions

View File

@@ -1,29 +0,0 @@
package com.baeldung.curltojava;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JavaCurlExamples {
public static String inputStreamToString(InputStream inputStream) {
final int bufferSize = 8 * 1024;
byte[] buffer = new byte[bufferSize];
final StringBuilder builder = new StringBuilder();
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, bufferSize)) {
while (bufferedInputStream.read(buffer) != -1) {
builder.append(new String(buffer));
}
} catch (IOException ex) {
Logger.getLogger(JavaCurlExamples.class.getName()).log(Level.SEVERE, null, ex);
}
return builder.toString();
}
public static void consumeInputStream(InputStream inputStream) {
inputStreamToString(inputStream);
}
}

View File

@@ -1,20 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Arithmetic {
private static Logger LOGGER = LoggerFactory.getLogger(Arithmetic.class);
public static void main(String[] args) {
try {
int result = 30 / 0; // Trying to divide by zero
} catch (ArithmeticException e) {
LOGGER.error("ArithmeticException caught!");
}
}
}

View File

@@ -1,24 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ArrayIndexOutOfBounds {
private static Logger LOGGER = LoggerFactory.getLogger(ArrayIndexOutOfBounds.class);
public static void main(String[] args) {
int[] nums = new int[] { 1, 2, 3 };
try {
int numFromNegativeIndex = nums[-1]; // Trying to access at negative index
int numFromGreaterIndex = nums[4]; // Trying to access at greater index
int numFromLengthIndex = nums[3]; // Trying to access at index equal to size of the array
} catch (ArrayIndexOutOfBoundsException e) {
LOGGER.error("ArrayIndexOutOfBoundsException caught");
}
}
}

View File

@@ -1,36 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class Animal {
}
class Dog extends Animal {
}
class Lion extends Animal {
}
public class ClassCast {
private static Logger LOGGER = LoggerFactory.getLogger(ClassCast.class);
public static void main(String[] args) {
try {
Animal animalOne = new Dog(); // At runtime the instance is dog
Dog bruno = (Dog) animalOne; // Downcasting
Animal animalTwo = new Lion(); // At runtime the instance is animal
Dog tommy = (Dog) animalTwo; // Downcasting
} catch (ClassCastException e) {
LOGGER.error("ClassCastException caught!");
}
}
}

View File

@@ -1,25 +0,0 @@
package com.baeldung.exceptions;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileNotFound {
private static Logger LOGGER = LoggerFactory.getLogger(FileNotFound.class);
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File("/invalid/file/location")));
} catch (FileNotFoundException e) {
LOGGER.error("FileNotFoundException caught!");
}
}
}

View File

@@ -1,28 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GlobalExceptionHandler {
public static void main(String[] args) {
Handler globalExceptionHandler = new Handler();
Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler);
new GlobalExceptionHandler().performArithmeticOperation(10, 0);
}
public int performArithmeticOperation(int num1, int num2) {
return num1/num2;
}
}
class Handler implements Thread.UncaughtExceptionHandler {
private static Logger LOGGER = LoggerFactory.getLogger(Handler.class);
public void uncaughtException(Thread t, Throwable e) {
LOGGER.info("Unhandled exception caught!");
}
}

View File

@@ -1,18 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IllegalArgument {
private static Logger LOGGER = LoggerFactory.getLogger(IllegalArgument.class);
public static void main(String[] args) {
try {
Thread.sleep(-1000);
} catch (InterruptedException e) {
LOGGER.error("IllegalArgumentException caught!");
}
}
}

View File

@@ -1,32 +0,0 @@
package com.baeldung.exceptions;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IllegalState {
private static Logger LOGGER = LoggerFactory.getLogger(IllegalState.class);
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
intList.add(i);
}
Iterator<Integer> intListIterator = intList.iterator(); // Initialized with index at -1
try {
intListIterator.remove(); // IllegalStateException
} catch (IllegalStateException e) {
LOGGER.error("IllegalStateException caught!");
}
}
}

View File

@@ -1,28 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class ChildThread extends Thread {
private static Logger LOGGER = LoggerFactory.getLogger(ChildThread.class);
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LOGGER.error("InterruptedException caught!");
}
}
}
public class InterruptedExceptionExample {
public static void main(String[] args) throws InterruptedException {
ChildThread childThread = new ChildThread();
childThread.start();
childThread.interrupt();
}
}

View File

@@ -1,25 +0,0 @@
package com.baeldung.exceptions;
import java.net.MalformedURLException;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MalformedURL {
private static Logger LOGGER = LoggerFactory.getLogger(MalformedURL.class);
public static void main(String[] args) {
URL baeldungURL = null;
try {
baeldungURL = new URL("malformedurl");
} catch (MalformedURLException e) {
LOGGER.error("MalformedURLException caught!");
}
}
}

View File

@@ -1,36 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NullPointer {
private static Logger LOGGER = LoggerFactory.getLogger(NullPointer.class);
public static void main(String[] args) {
Person personObj = null;
try {
String name = personObj.personName; // Accessing the field of a null object
personObj.personName = "Jon Doe"; // Modifying the field of a null object
} catch (NullPointerException e) {
LOGGER.error("NullPointerException caught!");
}
}
}
class Person {
public String personName;
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
}

View File

@@ -1,23 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NumberFormat {
private static Logger LOGGER = LoggerFactory.getLogger(NumberFormat.class);
public static void main(String[] args) {
String str1 = "100ABCD";
try {
int x = Integer.parseInt(str1); // Converting string with inappropriate format
int y = Integer.valueOf(str1);
} catch (NumberFormatException e) {
LOGGER.error("NumberFormatException caught!");
}
}
}

View File

@@ -1,25 +0,0 @@
package com.baeldung.exceptions;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ParseExceptionExample {
private static Logger LOGGER = LoggerFactory.getLogger(ParseExceptionExample.class);
public static void main(String[] args) {
DateFormat format = new SimpleDateFormat("MM, dd, yyyy");
try {
format.parse("01, , 2010");
} catch (ParseException e) {
LOGGER.error("ParseException caught!");
}
}
}

View File

@@ -1,30 +0,0 @@
package com.baeldung.exceptions;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceToString {
public static void main(String[] args) {
// Convert a StackTrace to String using core java
try {
throw new NullPointerException();
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
System.out.println(sw.toString());
}
// Convert a StackTrace to String using Apache Commons
try {
throw new IndexOutOfBoundsException();
} catch (Exception e) {
System.out.println(ExceptionUtils.getStackTrace(e));
}
}
}

View File

@@ -1,23 +0,0 @@
package com.baeldung.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StringIndexOutOfBounds {
private static Logger LOGGER = LoggerFactory.getLogger(StringIndexOutOfBounds.class);
public static void main(String[] args) {
String str = "Hello World";
try {
char charAtNegativeIndex = str.charAt(-1); // Trying to access at negative index
char charAtLengthIndex = str.charAt(11); // Trying to access at index equal to size of the string
} catch (StringIndexOutOfBoundsException e) {
LOGGER.error("StringIndexOutOfBoundsException caught");
}
}
}

View File

@@ -1,39 +0,0 @@
package com.baeldung.reflection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
class BaeldungReflectionUtils {
private static final Logger LOG = LoggerFactory.getLogger(BaeldungReflectionUtils.class);
static List<String> getNullPropertiesList(Customer customer) throws Exception {
PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
return Arrays.stream(propDescArr)
.filter(nulls(customer))
.map(PropertyDescriptor::getName)
.collect(Collectors.toList());
}
private static Predicate<PropertyDescriptor> nulls(Customer customer) {
return pd -> {
boolean result = false;
try {
Method getterMethod = pd.getReadMethod();
result = (getterMethod != null && getterMethod.invoke(customer) == null);
} catch (Exception e) {
LOG.error("error invoking getter method");
}
return result;
};
}
}

View File

@@ -1,56 +0,0 @@
package com.baeldung.reflection;
public class Customer {
private Integer id;
private String name;
private String emailId;
private Long phoneNumber;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", emailId=" + emailId + ", phoneNumber=" +
phoneNumber + "]";
}
Customer(Integer id, String name, String emailId, Long phoneNumber) {
super();
this.id = id;
this.name = name;
this.emailId = emailId;
this.phoneNumber = phoneNumber;
}
public Long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
}
}

View File

@@ -1,7 +0,0 @@
package com.baeldung.reflection;
public class Employee extends Person {
public int employeeId;
}

View File

@@ -1,7 +0,0 @@
package com.baeldung.reflection;
public class MonthEmployee extends Employee {
protected double reward;
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.reflection;
public class Person {
protected String lastName;
private String firstName;
}

View File

@@ -1,46 +0,0 @@
package com.baeldung.urlconnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostJSONWithHttpURLConnection {
public static void main (String []args) throws IOException{
//Change the URL with any other publicly accessible POST resource, which accepts JSON request body
URL url = new URL ("https://reqres.in/api/users");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
//JSON String need to be constructed for the specific resource.
//We may construct complex JSON using any third-party JSON libraries such as jackson or org.json
String jsonInputString = "{\"name\": \"Upendra\", \"job\": \"Programmer\"}";
try(OutputStream os = con.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int code = con.getResponseCode();
System.out.println(code);
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
}

View File

@@ -1,50 +0,0 @@
package com.baeldung.curltojava;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Assert;
import org.junit.Test;
public class JavaCurlExamplesLiveTest {
@Test
public void givenCommand_whenCalled_thenProduceZeroExitCode() throws IOException {
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
processBuilder.directory(new File("/home/"));
Process process = processBuilder.start();
InputStream inputStream = process.getInputStream();
// Consume the inputStream so the process can exit
JavaCurlExamples.consumeInputStream(inputStream);
int exitCode = process.exitValue();
Assert.assertEquals(0, exitCode);
}
@Test
public void givenNewCommands_whenCalled_thenCheckIfIsAlive() throws IOException {
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
processBuilder.directory(new File("/home/"));
Process process = processBuilder.start();
// Re-use processBuilder
processBuilder.command(new String[]{"newCommand", "arguments"});
Assert.assertEquals(true, process.isAlive());
}
@Test
public void whenRequestPost_thenCheckIfReturnContent() throws IOException {
String command = "curl -X POST https://postman-echo.com/post --data foo1=bar1&foo2=bar2";
Process process = Runtime.getRuntime().exec(command);
// Get the POST result
String content = JavaCurlExamples.inputStreamToString(process.getInputStream());
Assert.assertTrue(null != content && !content.isEmpty());
}
}

View File

@@ -1,64 +0,0 @@
package com.baeldung.exceptions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class GlobalExceptionHandlerUnitTest {
@Mock
private Appender<ILoggingEvent> mockAppender;
@Captor
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
@Before
public void setup() {
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.addAppender(mockAppender);
Handler globalExceptionHandler = new Handler();
Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler);
}
@After
public void teardown() {
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.detachAppender(mockAppender);
}
@Test
public void whenArithmeticException_thenUseUncaughtExceptionHandler() throws InterruptedException {
Thread globalExceptionHandlerThread = new Thread() {
public void run() {
GlobalExceptionHandler globalExceptionHandlerObj = new GlobalExceptionHandler();
globalExceptionHandlerObj.performArithmeticOperation(99, 0);
}
};
globalExceptionHandlerThread.start();
globalExceptionHandlerThread.join();
verify(mockAppender).doAppend(captorLoggingEvent.capture());
LoggingEvent loggingEvent = captorLoggingEvent.getValue();
assertThat(loggingEvent.getLevel()).isEqualTo(Level.INFO);
assertThat(loggingEvent.getFormattedMessage()).isEqualTo("Unhandled exception caught!");
}
}

View File

@@ -1,24 +0,0 @@
package com.baeldung.reflection;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertTrue;
public class BaeldungReflectionUtilsUnitTest {
@Test
public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception {
Customer customer = new Customer(1, "Himanshu", null, null);
List<String> result = BaeldungReflectionUtils.getNullPropertiesList(customer);
List<String> expectedFieldNames = Arrays.asList("emailId", "phoneNumber");
assertTrue(result.size() == expectedFieldNames.size());
assertTrue(result.containsAll(expectedFieldNames));
}
}

View File

@@ -1,150 +0,0 @@
package com.baeldung.reflection;
import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.*;
public class PersonAndEmployeeReflectionUnitTest {
// Fields names
private static final String LAST_NAME_FIELD = "lastName";
private static final String FIRST_NAME_FIELD = "firstName";
private static final String EMPLOYEE_ID_FIELD = "employeeId";
private static final String MONTH_EMPLOYEE_REWARD_FIELD = "reward";
@Test
public void givenPersonClass_whenGetDeclaredFields_thenTwoFields() {
// When
Field[] allFields = Person.class.getDeclaredFields();
// Then
assertEquals(2, allFields.length);
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(LAST_NAME_FIELD)
&& field.getType().equals(String.class))
);
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(FIRST_NAME_FIELD)
&& field.getType().equals(String.class))
);
}
@Test
public void givenEmployeeClass_whenGetDeclaredFields_thenOneField() {
// When
Field[] allFields = Employee.class.getDeclaredFields();
// Then
assertEquals(1, allFields.length);
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(EMPLOYEE_ID_FIELD)
&& field.getType().equals(int.class))
);
}
@Test
public void givenEmployeeClass_whenSuperClassGetDeclaredFields_thenOneField() {
// When
Field[] allFields = Employee.class.getSuperclass().getDeclaredFields();
// Then
assertEquals(2, allFields.length);
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(LAST_NAME_FIELD)
&& field.getType().equals(String.class))
);
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(FIRST_NAME_FIELD)
&& field.getType().equals(String.class))
);
}
@Test
public void givenEmployeeClass_whenGetDeclaredFieldsOnBothClasses_thenThreeFields() {
// When
Field[] personFields = Employee.class.getSuperclass().getDeclaredFields();
Field[] employeeFields = Employee.class.getDeclaredFields();
Field[] allFields = new Field[employeeFields.length + personFields.length];
Arrays.setAll(allFields, i -> (i < personFields.length ? personFields[i] : employeeFields[i - personFields.length]));
// Then
assertEquals(3, allFields.length);
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(LAST_NAME_FIELD)
&& field.getType().equals(String.class))
);
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(FIRST_NAME_FIELD)
&& field.getType().equals(String.class))
);
assertTrue(Arrays.stream(allFields).anyMatch(field ->
field.getName().equals(EMPLOYEE_ID_FIELD)
&& field.getType().equals(int.class))
);
}
@Test
public void givenEmployeeClass_whenGetDeclaredFieldsOnEmployeeSuperclassWithModifiersFilter_thenOneFields() {
// When
List<Field> personFields = Arrays.stream(Employee.class.getSuperclass().getDeclaredFields())
.filter(f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers()))
.collect(Collectors.toList());
// Then
assertEquals(1, personFields.size());
assertTrue(personFields.stream().anyMatch(field ->
field.getName().equals(LAST_NAME_FIELD)
&& field.getType().equals(String.class))
);
}
@Test
public void givenMonthEmployeeClass_whenGetAllFields_thenThreeFields() {
// When
List<Field> allFields = getAllFields(MonthEmployee.class);
// Then
assertEquals(3, allFields.size());
assertTrue(allFields.stream().anyMatch(field ->
field.getName().equals(LAST_NAME_FIELD)
&& field.getType().equals(String.class))
);
assertTrue(allFields.stream().anyMatch(field ->
field.getName().equals(EMPLOYEE_ID_FIELD)
&& field.getType().equals(int.class))
);
assertTrue(allFields.stream().anyMatch(field ->
field.getName().equals(MONTH_EMPLOYEE_REWARD_FIELD)
&& field.getType().equals(double.class))
);
}
public List<Field> getAllFields(Class clazz) {
if (clazz == null) {
return Collections.emptyList();
}
List<Field> result = new ArrayList<>(getAllFields(clazz.getSuperclass()));
List<Field> filteredFields = Arrays.stream(clazz.getDeclaredFields())
.filter(f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers()))
.collect(Collectors.toList());
result.addAll(filteredFields);
return result;
}
}