[BAEL-10840] - Create a libraries-apache-commons module
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.commons.beanutils;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class Course {
|
||||
private String name;
|
||||
private List<String> codes;
|
||||
private Map<String, Student> enrolledStudent = new HashMap<String, Student>();
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<String> getCodes() {
|
||||
return codes;
|
||||
}
|
||||
|
||||
public void setCodes(List<String> codes) {
|
||||
this.codes = codes;
|
||||
}
|
||||
|
||||
public void setEnrolledStudent(String enrolledId, Student student) {
|
||||
enrolledStudent.put(enrolledId, student);
|
||||
}
|
||||
|
||||
public Student getEnrolledStudent(String enrolledId) {
|
||||
return enrolledStudent.get(enrolledId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.commons.beanutils;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class CourseEntity {
|
||||
private String name;
|
||||
private List<String> codes;
|
||||
private Map<String, Student> students = new HashMap<String, Student>();
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<String> getCodes() {
|
||||
return codes;
|
||||
}
|
||||
|
||||
public void setCodes(List<String> codes) {
|
||||
this.codes = codes;
|
||||
}
|
||||
|
||||
public void setStudent(String id, Student student) {
|
||||
students.put(id, student);
|
||||
}
|
||||
|
||||
public Student getStudent(String enrolledId) {
|
||||
return students.get(enrolledId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.commons.beanutils;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.beanutils.BeanUtils;
|
||||
import org.apache.commons.beanutils.PropertyUtils;
|
||||
|
||||
public class CourseService {
|
||||
|
||||
public static void setValues(Course course, String name, List<String> codes) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
// Setting the simple properties
|
||||
PropertyUtils.setSimpleProperty(course, "name", name);
|
||||
PropertyUtils.setSimpleProperty(course, "codes", codes);
|
||||
}
|
||||
|
||||
public static void setIndexedValue(Course course, int codeIndex, String code) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
// Setting the indexed properties
|
||||
PropertyUtils.setIndexedProperty(course, "codes[" + codeIndex + "]", code);
|
||||
}
|
||||
|
||||
public static void setMappedValue(Course course, String enrollId, Student student) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
// Setting the mapped properties
|
||||
PropertyUtils.setMappedProperty(course, "enrolledStudent(" + enrollId + ")", student);
|
||||
}
|
||||
|
||||
public static String getNestedValue(Course course, String enrollId, String nestedPropertyName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
return (String) PropertyUtils.getNestedProperty(course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName);
|
||||
}
|
||||
|
||||
public static void copyProperties(Course course, CourseEntity courseEntity) throws IllegalAccessException, InvocationTargetException {
|
||||
BeanUtils.copyProperties(course, courseEntity);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.commons.beanutils;
|
||||
|
||||
public class Student {
|
||||
private String name;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.commons.chain;
|
||||
|
||||
import org.apache.commons.chain.Command;
|
||||
import org.apache.commons.chain.Context;
|
||||
|
||||
import static com.baeldung.commons.chain.AtmConstants.AMOUNT_LEFT_TO_BE_WITHDRAWN;
|
||||
|
||||
public abstract class AbstractDenominationDispenser implements Command {
|
||||
|
||||
@Override
|
||||
public boolean execute(Context context) throws Exception {
|
||||
int amountLeftToBeWithdrawn = (int) context.get(AMOUNT_LEFT_TO_BE_WITHDRAWN);
|
||||
if (amountLeftToBeWithdrawn >= getDenominationValue()) {
|
||||
context.put(getDenominationString(), amountLeftToBeWithdrawn / getDenominationValue());
|
||||
context.put(AMOUNT_LEFT_TO_BE_WITHDRAWN, amountLeftToBeWithdrawn % getDenominationValue());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
protected abstract String getDenominationString();
|
||||
|
||||
protected abstract int getDenominationValue();
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.commons.chain;
|
||||
|
||||
import org.apache.commons.chain.impl.CatalogBase;
|
||||
|
||||
import static com.baeldung.commons.chain.AtmConstants.ATM_WITHDRAWAL_CHAIN;
|
||||
|
||||
public class AtmCatalog extends CatalogBase {
|
||||
|
||||
public AtmCatalog() {
|
||||
super();
|
||||
addCommand(ATM_WITHDRAWAL_CHAIN, new AtmWithdrawalChain());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.commons.chain;
|
||||
|
||||
public class AtmConstants {
|
||||
public static final String TOTAL_AMOUNT_TO_BE_WITHDRAWN = "totalAmountToBeWithdrawn";
|
||||
public static final String AMOUNT_LEFT_TO_BE_WITHDRAWN = "amountLeftToBeWithdrawn";
|
||||
public static final String NO_OF_HUNDREDS_DISPENSED = "noOfHundredsDispensed";
|
||||
public static final String NO_OF_FIFTIES_DISPENSED = "noOfFiftiesDispensed";
|
||||
public static final String NO_OF_TENS_DISPENSED = "noOfTensDispensed";
|
||||
public static final String ATM_WITHDRAWAL_CHAIN = "atmWithdrawalChain";
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.commons.chain;
|
||||
|
||||
import org.apache.commons.chain.impl.ContextBase;
|
||||
|
||||
public class AtmRequestContext extends ContextBase {
|
||||
|
||||
int totalAmountToBeWithdrawn;
|
||||
int noOfHundredsDispensed;
|
||||
int noOfFiftiesDispensed;
|
||||
int noOfTensDispensed;
|
||||
int amountLeftToBeWithdrawn;
|
||||
|
||||
public int getTotalAmountToBeWithdrawn() {
|
||||
return totalAmountToBeWithdrawn;
|
||||
}
|
||||
|
||||
public void setTotalAmountToBeWithdrawn(int totalAmountToBeWithdrawn) {
|
||||
this.totalAmountToBeWithdrawn = totalAmountToBeWithdrawn;
|
||||
}
|
||||
|
||||
public int getNoOfHundredsDispensed() {
|
||||
return noOfHundredsDispensed;
|
||||
}
|
||||
|
||||
public void setNoOfHundredsDispensed(int noOfHundredsDispensed) {
|
||||
this.noOfHundredsDispensed = noOfHundredsDispensed;
|
||||
}
|
||||
|
||||
public int getNoOfFiftiesDispensed() {
|
||||
return noOfFiftiesDispensed;
|
||||
}
|
||||
|
||||
public void setNoOfFiftiesDispensed(int noOfFiftiesDispensed) {
|
||||
this.noOfFiftiesDispensed = noOfFiftiesDispensed;
|
||||
}
|
||||
|
||||
public int getNoOfTensDispensed() {
|
||||
return noOfTensDispensed;
|
||||
}
|
||||
|
||||
public void setNoOfTensDispensed(int noOfTensDispensed) {
|
||||
this.noOfTensDispensed = noOfTensDispensed;
|
||||
}
|
||||
|
||||
public int getAmountLeftToBeWithdrawn() {
|
||||
return amountLeftToBeWithdrawn;
|
||||
}
|
||||
|
||||
public void setAmountLeftToBeWithdrawn(int amountLeftToBeWithdrawn) {
|
||||
this.amountLeftToBeWithdrawn = amountLeftToBeWithdrawn;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.commons.chain;
|
||||
|
||||
import org.apache.commons.chain.impl.ChainBase;
|
||||
|
||||
public class AtmWithdrawalChain extends ChainBase {
|
||||
|
||||
public AtmWithdrawalChain() {
|
||||
super();
|
||||
addCommand(new HundredDenominationDispenser());
|
||||
addCommand(new FiftyDenominationDispenser());
|
||||
addCommand(new TenDenominationDispenser());
|
||||
addCommand(new AuditFilter());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.commons.chain;
|
||||
|
||||
import org.apache.commons.chain.Context;
|
||||
import org.apache.commons.chain.Filter;
|
||||
|
||||
public class AuditFilter implements Filter {
|
||||
|
||||
@Override
|
||||
public boolean postprocess(Context context, Exception exception) {
|
||||
// Send notification to customer & bank.
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean execute(Context context) throws Exception {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.commons.chain;
|
||||
|
||||
import static com.baeldung.commons.chain.AtmConstants.NO_OF_FIFTIES_DISPENSED;
|
||||
|
||||
public class FiftyDenominationDispenser extends AbstractDenominationDispenser {
|
||||
@Override
|
||||
protected String getDenominationString() {
|
||||
return NO_OF_FIFTIES_DISPENSED;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getDenominationValue() {
|
||||
return 50;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.commons.chain;
|
||||
|
||||
import static com.baeldung.commons.chain.AtmConstants.NO_OF_HUNDREDS_DISPENSED;
|
||||
|
||||
public class HundredDenominationDispenser extends AbstractDenominationDispenser {
|
||||
@Override
|
||||
protected String getDenominationString() {
|
||||
return NO_OF_HUNDREDS_DISPENSED;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getDenominationValue() {
|
||||
return 100;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.commons.chain;
|
||||
|
||||
import static com.baeldung.commons.chain.AtmConstants.NO_OF_TENS_DISPENSED;
|
||||
|
||||
public class TenDenominationDispenser extends AbstractDenominationDispenser {
|
||||
@Override
|
||||
protected String getDenominationString() {
|
||||
return NO_OF_TENS_DISPENSED;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getDenominationValue() {
|
||||
return 10;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.commons.collectionutil;
|
||||
|
||||
public class Address {
|
||||
|
||||
private String locality;
|
||||
private String city;
|
||||
private String zip;
|
||||
|
||||
public String getLocality() {
|
||||
return locality;
|
||||
}
|
||||
|
||||
public void setLocality(String locality) {
|
||||
this.locality = locality;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getZip() {
|
||||
return zip;
|
||||
}
|
||||
|
||||
public void setZip(String zip) {
|
||||
this.zip = zip;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("Address [locality=").append(locality).append(", city=").append(city).append(", zip=").append(zip).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public Address(String locality, String city, String zip) {
|
||||
super();
|
||||
this.locality = locality;
|
||||
this.city = city;
|
||||
this.zip = zip;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.baeldung.commons.collectionutil;
|
||||
|
||||
public class Customer implements Comparable<Customer> {
|
||||
|
||||
private Integer id;
|
||||
private String name;
|
||||
private Long phone;
|
||||
private String locality;
|
||||
private String city;
|
||||
private String zip;
|
||||
|
||||
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 Long getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(Long phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
public String getLocality() {
|
||||
return locality;
|
||||
}
|
||||
|
||||
public void setLocality(String locality) {
|
||||
this.locality = locality;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getZip() {
|
||||
return zip;
|
||||
}
|
||||
|
||||
public void setZip(String zip) {
|
||||
this.zip = zip;
|
||||
}
|
||||
|
||||
public Customer(Integer id, String name, Long phone, String locality, String city, String zip) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.phone = phone;
|
||||
this.locality = locality;
|
||||
this.city = city;
|
||||
this.zip = zip;
|
||||
}
|
||||
|
||||
public Customer(Integer id, String name, Long phone) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
public Customer(String name) {
|
||||
super();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Customer other = (Customer) obj;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public int compareTo(Customer o) {
|
||||
return this.name.compareTo(o.getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("Customer [id=").append(id).append(", name=").append(name).append(", phone=").append(phone).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.commons.dbutils;
|
||||
|
||||
public class Email {
|
||||
private Integer id;
|
||||
private Integer employeeId;
|
||||
private String address;
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Integer getEmployeeId() {
|
||||
return employeeId;
|
||||
}
|
||||
|
||||
public void setEmployeeId(Integer employeeId) {
|
||||
this.employeeId = employeeId;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Email{" + "id=" + id + ", address=" + address + '}';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.commons.dbutils;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
public class Employee {
|
||||
private Integer id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private Double salary;
|
||||
private Date hiredDate;
|
||||
private List<Email> emails;
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Double getSalary() {
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void setSalary(Double salary) {
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
public Date getHiredDate() {
|
||||
return hiredDate;
|
||||
}
|
||||
|
||||
public void setHiredDate(Date hiredDate) {
|
||||
this.hiredDate = hiredDate;
|
||||
}
|
||||
|
||||
public List<Email> getEmails() {
|
||||
return emails;
|
||||
}
|
||||
|
||||
public void setEmails(List<Email> emails) {
|
||||
this.emails = emails;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Employee{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", salary=" + salary + ", hiredDate=" + hiredDate + '}';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.commons.dbutils;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.apache.commons.dbutils.BasicRowProcessor;
|
||||
import org.apache.commons.dbutils.BeanProcessor;
|
||||
|
||||
import org.apache.commons.dbutils.QueryRunner;
|
||||
import org.apache.commons.dbutils.handlers.BeanListHandler;
|
||||
|
||||
public class EmployeeHandler extends BeanListHandler<Employee> {
|
||||
|
||||
private Connection connection;
|
||||
|
||||
public EmployeeHandler(Connection con) {
|
||||
super(Employee.class, new BasicRowProcessor(new BeanProcessor(getColumnsToFieldsMap())));
|
||||
this.connection = con;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Employee> handle(ResultSet rs) throws SQLException {
|
||||
List<Employee> employees = super.handle(rs);
|
||||
|
||||
QueryRunner runner = new QueryRunner();
|
||||
BeanListHandler<Email> handler = new BeanListHandler<>(Email.class);
|
||||
String query = "SELECT * FROM email WHERE employeeid = ?";
|
||||
for (Employee employee : employees) {
|
||||
List<Email> emails = runner.query(connection, query, handler, employee.getId());
|
||||
employee.setEmails(emails);
|
||||
}
|
||||
return employees;
|
||||
}
|
||||
|
||||
public static Map<String, String> getColumnsToFieldsMap() {
|
||||
Map<String, String> columnsToFieldsMap = new HashMap<>();
|
||||
columnsToFieldsMap.put("FIRST_NAME", "firstName");
|
||||
columnsToFieldsMap.put("LAST_NAME", "lastName");
|
||||
columnsToFieldsMap.put("HIRED_DATE", "hiredDate");
|
||||
return columnsToFieldsMap;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.commons.io;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.monitor.FileAlterationListener;
|
||||
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
|
||||
import org.apache.commons.io.monitor.FileAlterationMonitor;
|
||||
import org.apache.commons.io.monitor.FileAlterationObserver;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class FileMonitor {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
File folder = FileUtils.getTempDirectory();
|
||||
startFileMonitor(folder);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param folder
|
||||
* @throws Exception
|
||||
*/
|
||||
public static void startFileMonitor(File folder) throws Exception {
|
||||
FileAlterationObserver observer = new FileAlterationObserver(folder);
|
||||
FileAlterationMonitor monitor = new FileAlterationMonitor(5000);
|
||||
|
||||
FileAlterationListener fal = new FileAlterationListenerAdaptor() {
|
||||
|
||||
@Override
|
||||
public void onFileCreate(File file) {
|
||||
// on create action
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFileDelete(File file) {
|
||||
// on delete action
|
||||
}
|
||||
};
|
||||
|
||||
observer.addListener(fal);
|
||||
monitor.addObserver(observer);
|
||||
monitor.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.baeldung.commons.lang3;
|
||||
|
||||
import org.apache.commons.lang3.builder.EqualsBuilder;
|
||||
import org.apache.commons.lang3.builder.HashCodeBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentException;
|
||||
import org.apache.commons.lang3.concurrent.BackgroundInitializer;
|
||||
|
||||
public class BuilderMethods {
|
||||
|
||||
private final int intValue;
|
||||
private final String strSample;
|
||||
|
||||
public BuilderMethods(final int newId, final String newName) {
|
||||
this.intValue = newId;
|
||||
this.strSample = newName;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return this.intValue;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.strSample;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return new HashCodeBuilder().append(this.intValue).append(this.strSample).toHashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof BuilderMethods == false) {
|
||||
return false;
|
||||
}
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
final BuilderMethods otherObject = (BuilderMethods) obj;
|
||||
|
||||
return new EqualsBuilder().append(this.intValue, otherObject.intValue).append(this.strSample, otherObject.strSample).isEquals();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new ToStringBuilder(this).append("INTVALUE", this.intValue).append("STRINGVALUE", this.strSample).toString();
|
||||
}
|
||||
|
||||
public static void main(final String[] arguments) {
|
||||
final BuilderMethods simple1 = new BuilderMethods(1, "The First One");
|
||||
System.out.println(simple1.getName());
|
||||
System.out.println(simple1.hashCode());
|
||||
System.out.println(simple1.toString());
|
||||
|
||||
SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer();
|
||||
|
||||
try {
|
||||
sampleLazyInitializer.get();
|
||||
} catch (ConcurrentException e1) {
|
||||
// TODO Auto-generated catch block
|
||||
e1.printStackTrace();
|
||||
}
|
||||
|
||||
SampleBackgroundInitializer sampleBackgroundInitializer = new SampleBackgroundInitializer();
|
||||
sampleBackgroundInitializer.start();
|
||||
|
||||
// Proceed with other tasks instead of waiting for the SampleBackgroundInitializer task to finish.
|
||||
|
||||
try {
|
||||
Object result = sampleBackgroundInitializer.get();
|
||||
} catch (ConcurrentException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SampleBackgroundInitializer extends BackgroundInitializer<String> {
|
||||
|
||||
@Override
|
||||
protected String initialize() throws Exception {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Any complex task that takes some time
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.commons.lang3;
|
||||
|
||||
import org.apache.commons.lang3.concurrent.LazyInitializer;
|
||||
|
||||
public class SampleLazyInitializer extends LazyInitializer<SampleObject> {
|
||||
|
||||
@Override
|
||||
protected SampleObject initialize() {
|
||||
return new SampleObject();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.commons.lang3;
|
||||
|
||||
public class SampleObject {
|
||||
|
||||
// Ignored
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.commons.lang3.application;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.commons.lang3.beans;
|
||||
|
||||
public class User {
|
||||
|
||||
private final String name;
|
||||
private final String email;
|
||||
|
||||
public User(String name, String email) {
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "name=" + name + ", email=" + email + '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.commons.lang3.beans;
|
||||
|
||||
import org.apache.commons.lang3.concurrent.LazyInitializer;
|
||||
|
||||
public class UserInitializer extends LazyInitializer<User> {
|
||||
|
||||
@Override
|
||||
protected User initialize() {
|
||||
return new User("John", "john@domain.com");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.baeldung.commons.math3;
|
||||
|
||||
import org.apache.commons.math3.stat.Frequency;
|
||||
import org.knowm.xchart.CategoryChart;
|
||||
import org.knowm.xchart.CategoryChartBuilder;
|
||||
import org.knowm.xchart.SwingWrapper;
|
||||
import org.knowm.xchart.style.Styler;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class Histogram {
|
||||
|
||||
private Map distributionMap;
|
||||
private int classWidth;
|
||||
|
||||
public Histogram() {
|
||||
|
||||
distributionMap = new TreeMap();
|
||||
classWidth = 10;
|
||||
Map distributionMap = processRawData();
|
||||
List yData = new ArrayList();
|
||||
yData.addAll(distributionMap.values());
|
||||
List xData = Arrays.asList(distributionMap.keySet().toArray());
|
||||
|
||||
CategoryChart chart = buildChart(xData, yData);
|
||||
new SwingWrapper<>(chart).displayChart();
|
||||
|
||||
}
|
||||
|
||||
private CategoryChart buildChart(List xData, List yData) {
|
||||
|
||||
// Create Chart
|
||||
CategoryChart chart = new CategoryChartBuilder().width(800).height(600)
|
||||
.title("Age Distribution")
|
||||
.xAxisTitle("Age Group")
|
||||
.yAxisTitle("Frequency")
|
||||
.build();
|
||||
|
||||
chart.getStyler().setLegendPosition(Styler.LegendPosition.InsideNW);
|
||||
chart.getStyler().setAvailableSpaceFill(0.99);
|
||||
chart.getStyler().setOverlapped(true);
|
||||
|
||||
chart.addSeries("age group", xData, yData);
|
||||
|
||||
return chart;
|
||||
}
|
||||
|
||||
private Map processRawData() {
|
||||
|
||||
List<Integer> datasetList = Arrays.asList(
|
||||
36, 25, 38, 46, 55, 68, 72,
|
||||
55, 36, 38, 67, 45, 22, 48,
|
||||
91, 46, 52, 61, 58, 55);
|
||||
Frequency frequency = new Frequency();
|
||||
datasetList.forEach(d -> frequency.addValue(Double.parseDouble(d.toString())));
|
||||
|
||||
datasetList.stream()
|
||||
.map(d -> Double.parseDouble(d.toString()))
|
||||
.distinct()
|
||||
.forEach(observation -> {
|
||||
long observationFrequency = frequency.getCount(observation);
|
||||
int upperBoundary = (observation > classWidth)
|
||||
? Math.multiplyExact( (int) Math.ceil(observation / classWidth), classWidth)
|
||||
: classWidth;
|
||||
int lowerBoundary = (upperBoundary > classWidth)
|
||||
? Math.subtractExact(upperBoundary, classWidth)
|
||||
: 0;
|
||||
String bin = lowerBoundary + "-" + upperBoundary;
|
||||
|
||||
updateDistributionMap(lowerBoundary, bin, observationFrequency);
|
||||
|
||||
});
|
||||
|
||||
return distributionMap;
|
||||
}
|
||||
|
||||
private void updateDistributionMap(int lowerBoundary, String bin, long observationFrequency) {
|
||||
|
||||
int prevLowerBoundary = (lowerBoundary > classWidth) ? lowerBoundary - classWidth : 0;
|
||||
String prevBin = prevLowerBoundary + "-" + lowerBoundary;
|
||||
if(!distributionMap.containsKey(prevBin))
|
||||
distributionMap.put(prevBin, 0);
|
||||
|
||||
if(!distributionMap.containsKey(bin)) {
|
||||
distributionMap.put(bin, observationFrequency);
|
||||
}
|
||||
else {
|
||||
long oldFrequency = Long.parseLong(distributionMap.get(bin).toString());
|
||||
distributionMap.replace(bin, oldFrequency + observationFrequency);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
new Histogram();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.ftp;
|
||||
|
||||
import org.apache.commons.net.PrintCommandListener;
|
||||
import org.apache.commons.net.ftp.FTPClient;
|
||||
import org.apache.commons.net.ftp.FTPFile;
|
||||
import org.apache.commons.net.ftp.FTPReply;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
class FtpClient {
|
||||
|
||||
private final String server;
|
||||
private final int port;
|
||||
private final String user;
|
||||
private final String password;
|
||||
private FTPClient ftp;
|
||||
|
||||
FtpClient(String server, int port, String user, String password) {
|
||||
this.server = server;
|
||||
this.port = port;
|
||||
this.user = user;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
void open() throws IOException {
|
||||
ftp = new FTPClient();
|
||||
|
||||
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
|
||||
|
||||
ftp.connect(server, port);
|
||||
int reply = ftp.getReplyCode();
|
||||
if (!FTPReply.isPositiveCompletion(reply)) {
|
||||
ftp.disconnect();
|
||||
throw new IOException("Exception in connecting to FTP Server");
|
||||
}
|
||||
|
||||
ftp.login(user, password);
|
||||
}
|
||||
|
||||
void close() throws IOException {
|
||||
ftp.disconnect();
|
||||
}
|
||||
|
||||
Collection<String> listFiles(String path) throws IOException {
|
||||
FTPFile[] files = ftp.listFiles(path);
|
||||
|
||||
return Arrays.stream(files)
|
||||
.map(FTPFile::getName)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
void putFileToPath(File file, String path) throws IOException {
|
||||
ftp.storeFile(path, new FileInputStream(file));
|
||||
}
|
||||
|
||||
void downloadFile(String source, String destination) throws IOException {
|
||||
FileOutputStream out = new FileOutputStream(destination);
|
||||
ftp.retrieveFile(source, out);
|
||||
}
|
||||
}
|
||||
13
libraries-apache-commons/src/main/resources/logback.xml
Normal file
13
libraries-apache-commons/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,159 @@
|
||||
package com.baeldung.circularfifoqueue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.collections4.queue.CircularFifoQueue;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CircularFifoQueueUnitTest {
|
||||
|
||||
private static final int DEFAULT_SIZE = 32;
|
||||
|
||||
private static final int FIXED_SIZE = 5;
|
||||
|
||||
private static final int COLLECTION_SIZE = 7;
|
||||
|
||||
private static final String TEST_COLOR = "Red";
|
||||
|
||||
private static final String TEST_COLOR_BY_INDEX = "Blue";
|
||||
|
||||
@Test
|
||||
public void whenUsingDefualtConstructor_correctSizeQueue() {
|
||||
CircularFifoQueue<String> bits = new CircularFifoQueue<>();
|
||||
|
||||
Assert.assertEquals(DEFAULT_SIZE, bits.maxSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAddElements_whenUsingIntConstructor_correctSizeQueue() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(FIXED_SIZE, colors.maxSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCollectionConstructor_correctSizeQueue() {
|
||||
List<String> days = new ArrayList<>();
|
||||
days.add("Monday");
|
||||
days.add("Tuesday");
|
||||
days.add("Wednesday");
|
||||
days.add("Thursday");
|
||||
days.add("Friday");
|
||||
days.add("Saturday");
|
||||
days.add("Sunday");
|
||||
|
||||
CircularFifoQueue<String> daysOfWeek = new CircularFifoQueue<>(days);
|
||||
|
||||
Assert.assertEquals(COLLECTION_SIZE, daysOfWeek.maxSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAddElements_whenGetElement_correctElement() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(TEST_COLOR_BY_INDEX, colors.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAddElements_whenPollElement_correctElement() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(TEST_COLOR, colors.poll());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAddElements_whenPeekQueue_correctElement() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(TEST_COLOR, colors.peek());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAddElements_whenElementQueue_correctElement() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(TEST_COLOR, colors.element());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAddElements_whenRemoveElement_correctElement() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(TEST_COLOR, colors.remove());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFullQueue_whenClearQueue_getIsEmpty() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
colors.clear();
|
||||
|
||||
Assert.assertEquals(true, colors.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFullQueue_whenCheckFull_getIsFull() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(false, colors.isFull());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFullQueue_whenAddMoreElements_getIsAtFullCapacity() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
colors.add("Orange");
|
||||
colors.add("Violet");
|
||||
colors.add("Pink");
|
||||
|
||||
Assert.assertEquals(true, colors.isAtFullCapacity());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.commons.beanutils;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CourseServiceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
Course course = new Course();
|
||||
String name = "Computer Science";
|
||||
List<String> codes = Arrays.asList("CS", "CS01");
|
||||
CourseService.setValues(course, name, codes);
|
||||
|
||||
Assert.assertEquals(name, course.getName());
|
||||
Assert.assertEquals(2, course.getCodes().size());
|
||||
Assert.assertEquals("CS", course.getCodes().get(0));
|
||||
|
||||
CourseService.setIndexedValue(course, 1, "CS02");
|
||||
Assert.assertEquals("CS02", course.getCodes().get(1));
|
||||
|
||||
Student student = new Student();
|
||||
String studentName = "Joe";
|
||||
student.setName(studentName);
|
||||
|
||||
CourseService.setMappedValue(course, "ST-1", student);
|
||||
Assert.assertEquals(student, course.getEnrolledStudent("ST-1"));
|
||||
|
||||
String accessedStudentName = CourseService.getNestedValue(course, "ST-1", "name");
|
||||
Assert.assertEquals(studentName, accessedStudentName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWithSameName() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
||||
Course course = new Course();
|
||||
course.setName("Computer Science");
|
||||
course.setCodes(Arrays.asList("CS"));
|
||||
course.setEnrolledStudent("ST-1", new Student());
|
||||
|
||||
CourseEntity courseEntity = new CourseEntity();
|
||||
|
||||
CourseService.copyProperties(course, courseEntity);
|
||||
Assert.assertEquals(course.getName(), courseEntity.getName());
|
||||
Assert.assertEquals(course.getCodes(), courseEntity.getCodes());
|
||||
Assert.assertNull(courseEntity.getStudent("ST-1"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.commons.chain;
|
||||
|
||||
import org.apache.commons.chain.Catalog;
|
||||
import org.apache.commons.chain.Command;
|
||||
import org.apache.commons.chain.Context;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.baeldung.commons.chain.AtmConstants.*;
|
||||
|
||||
public class AtmChainUnitTest {
|
||||
|
||||
public static final int EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN = 460;
|
||||
public static final int EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN = 0;
|
||||
public static final int EXPECTED_NO_OF_HUNDREDS_DISPENSED = 4;
|
||||
public static final int EXPECTED_NO_OF_FIFTIES_DISPENSED = 1;
|
||||
public static final int EXPECTED_NO_OF_TENS_DISPENSED = 1;
|
||||
|
||||
@Test
|
||||
public void givenInputsToContext_whenAppliedChain_thenExpectedContext() {
|
||||
Context context = new AtmRequestContext();
|
||||
context.put(TOTAL_AMOUNT_TO_BE_WITHDRAWN, 460);
|
||||
context.put(AMOUNT_LEFT_TO_BE_WITHDRAWN, 460);
|
||||
Catalog catalog = new AtmCatalog();
|
||||
Command atmWithdrawalChain = catalog.getCommand(ATM_WITHDRAWAL_CHAIN);
|
||||
try {
|
||||
atmWithdrawalChain.execute(context);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
Assert.assertEquals(EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN, (int) context.get(TOTAL_AMOUNT_TO_BE_WITHDRAWN));
|
||||
Assert.assertEquals(EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN, (int) context.get(AMOUNT_LEFT_TO_BE_WITHDRAWN));
|
||||
Assert.assertEquals(EXPECTED_NO_OF_HUNDREDS_DISPENSED, (int) context.get(NO_OF_HUNDREDS_DISPENSED));
|
||||
Assert.assertEquals(EXPECTED_NO_OF_FIFTIES_DISPENSED, (int) context.get(NO_OF_FIFTIES_DISPENSED));
|
||||
Assert.assertEquals(EXPECTED_NO_OF_TENS_DISPENSED, (int) context.get(NO_OF_TENS_DISPENSED));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.commons.collections;
|
||||
|
||||
import org.apache.commons.collections4.BidiMap;
|
||||
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class BidiMapUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenKeyValue_whenPut_thenAddEntryToMap() {
|
||||
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value2");
|
||||
assertEquals(map.size(), 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInverseBidiMap_thenInverseKeyValue() {
|
||||
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value2");
|
||||
BidiMap<String, String> rMap = map.inverseBidiMap();
|
||||
assertTrue(rMap.containsKey("value1") && rMap.containsKey("value2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValue_whenRemoveValue_thenRemoveMatchingMapEntry() {
|
||||
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value2");
|
||||
map.removeValue("value2");
|
||||
assertFalse(map.containsKey("key2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValue_whenGetKey_thenMappedKey() {
|
||||
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||
map.put("key1", "value1");
|
||||
assertEquals(map.getKey("value1"), "key1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenKeyValue_whenAddValue_thenReplaceFirstKey() {
|
||||
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value1");
|
||||
assertEquals(map.size(), 1);
|
||||
assertFalse(map.containsKey("key1"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.baeldung.commons.collections;
|
||||
|
||||
import com.baeldung.commons.collectionutil.Address;
|
||||
import com.baeldung.commons.collectionutil.Customer;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.apache.commons.collections4.Predicate;
|
||||
import org.apache.commons.collections4.Transformer;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CollectionUtilsGuideUnitTest {
|
||||
|
||||
Customer customer1 = new Customer(1, "Daniel", 123456l, "locality1", "city1", "1234");
|
||||
Customer customer4 = new Customer(4, "Bob", 456789l, "locality4", "city4", "4567");
|
||||
List<Customer> list1, list2, list3, linkedList1;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
Customer customer2 = new Customer(2, "Fredrik", 234567l, "locality2", "city2", "2345");
|
||||
Customer customer3 = new Customer(3, "Kyle", 345678l, "locality3", "city3", "3456");
|
||||
Customer customer5 = new Customer(5, "Cat", 567890l, "locality5", "city5", "5678");
|
||||
Customer customer6 = new Customer(6, "John", 678901l, "locality6", "city6", "6789");
|
||||
|
||||
list1 = Arrays.asList(customer1, customer2, customer3);
|
||||
list2 = Arrays.asList(customer4, customer5, customer6);
|
||||
list3 = Arrays.asList(customer1, customer2);
|
||||
|
||||
linkedList1 = new LinkedList<>(list1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenAddIgnoreNull_thenNoNullAdded() {
|
||||
CollectionUtils.addIgnoreNull(list1, null);
|
||||
assertFalse(list1.contains(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSortedLists_whenCollated_thenSorted() {
|
||||
List<Customer> sortedList = CollectionUtils.collate(list1, list2);
|
||||
|
||||
assertEquals(6, sortedList.size());
|
||||
assertTrue(sortedList.get(0).getName().equals("Bob"));
|
||||
assertTrue(sortedList.get(2).getName().equals("Daniel"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenTransformed_thenListOfAddress() {
|
||||
Collection<Address> addressCol = CollectionUtils.collect(list1, new Transformer<Customer, Address>() {
|
||||
public Address transform(Customer customer) {
|
||||
return new Address(customer.getLocality(), customer.getCity(), customer.getZip());
|
||||
}
|
||||
});
|
||||
|
||||
List<Address> addressList = new ArrayList<>(addressCol);
|
||||
assertTrue(addressList.size() == 3);
|
||||
assertTrue(addressList.get(0).getLocality().equals("locality1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomerList_whenFiltered_thenCorrectSize() {
|
||||
|
||||
boolean isModified = CollectionUtils.filter(linkedList1, new Predicate<Customer>() {
|
||||
public boolean evaluate(Customer customer) {
|
||||
return Arrays.asList("Daniel", "Kyle").contains(customer.getName());
|
||||
}
|
||||
});
|
||||
|
||||
// filterInverse does the opposite. It removes the element from the list if the Predicate returns true
|
||||
// select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection
|
||||
|
||||
assertTrue(isModified && linkedList1.size() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonEmptyList_whenCheckedIsNotEmpty_thenTrue() {
|
||||
List<Customer> emptyList = new ArrayList<>();
|
||||
List<Customer> nullList = null;
|
||||
|
||||
// Very handy at times where we want to check if a collection is not null and not empty too.
|
||||
// isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading
|
||||
assertTrue(CollectionUtils.isNotEmpty(list1));
|
||||
assertTrue(CollectionUtils.isEmpty(nullList));
|
||||
assertTrue(CollectionUtils.isEmpty(emptyList));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomerListAndASubcollection_whenChecked_thenTrue() {
|
||||
assertTrue(CollectionUtils.isSubCollection(list3, list1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoLists_whenIntersected_thenCheckSize() {
|
||||
Collection<Customer> intersection = CollectionUtils.intersection(list1, list3);
|
||||
assertTrue(intersection.size() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoLists_whenSubtracted_thenCheckElementNotPresentInA() {
|
||||
Collection<Customer> result = CollectionUtils.subtract(list1, list3);
|
||||
assertFalse(result.contains(customer1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoLists_whenUnioned_thenCheckElementPresentInResult() {
|
||||
Collection<Customer> union = CollectionUtils.union(list1, list2);
|
||||
assertTrue(union.contains(customer1));
|
||||
assertTrue(union.contains(customer4));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.baeldung.commons.collections;
|
||||
|
||||
import org.apache.commons.collections4.MapUtils;
|
||||
import org.apache.commons.collections4.PredicateUtils;
|
||||
import org.apache.commons.collections4.TransformerUtils;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.collection.IsMapContaining.hasEntry;
|
||||
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
|
||||
import static org.hamcrest.collection.IsMapWithSize.anEmptyMap;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class MapUtilsUnitTest {
|
||||
|
||||
private String[][] color2DArray = new String[][] { { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } };
|
||||
private String[] color1DArray = new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF" };
|
||||
private Map<String, String> colorMap;
|
||||
|
||||
@Before
|
||||
public void createMap() {
|
||||
this.colorMap = MapUtils.putAll(new HashMap<String, String>(), this.color2DArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateMapFrom2DArray_theMapIsCreated() {
|
||||
this.colorMap = MapUtils.putAll(new HashMap<String, String>(), this.color2DArray);
|
||||
|
||||
assertThat(this.colorMap, is(aMapWithSize(this.color2DArray.length)));
|
||||
|
||||
assertThat(this.colorMap, hasEntry("RED", "#FF0000"));
|
||||
assertThat(this.colorMap, hasEntry("GREEN", "#00FF00"));
|
||||
assertThat(this.colorMap, hasEntry("BLUE", "#0000FF"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateMapFrom1DArray_theMapIsCreated() {
|
||||
this.colorMap = MapUtils.putAll(new HashMap<String, String>(), this.color1DArray);
|
||||
|
||||
assertThat(this.colorMap, is(aMapWithSize(this.color1DArray.length / 2)));
|
||||
|
||||
assertThat(this.colorMap, hasEntry("RED", "#FF0000"));
|
||||
assertThat(this.colorMap, hasEntry("GREEN", "#00FF00"));
|
||||
assertThat(this.colorMap, hasEntry("BLUE", "#0000FF"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerbosePrintMap_thenMustPrintFormattedMap() {
|
||||
MapUtils.verbosePrint(System.out, "Optional Label", this.colorMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetKeyNotPresent_thenMustReturnDefaultValue() {
|
||||
String defaultColorStr = "COLOR_NOT_FOUND";
|
||||
String color = MapUtils.getString(this.colorMap, "BLACK", defaultColorStr);
|
||||
|
||||
assertEquals(color, defaultColorStr);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetOnNullMap_thenMustReturnDefaultValue() {
|
||||
String defaultColorStr = "COLOR_NOT_FOUND";
|
||||
String color = MapUtils.getString(null, "RED", defaultColorStr);
|
||||
|
||||
assertEquals(color, defaultColorStr);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInvertMap_thenMustReturnInvertedMap() {
|
||||
Map<String, String> invColorMap = MapUtils.invertMap(this.colorMap);
|
||||
|
||||
int size = invColorMap.size();
|
||||
Assertions.assertThat(invColorMap).hasSameSizeAs(colorMap).containsKeys(this.colorMap.values().toArray(new String[size])).containsValues(this.colorMap.keySet().toArray(new String[size]));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() {
|
||||
Map<String, String> rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll(new HashMap<String, String>(), this.color1DArray));
|
||||
|
||||
rgbMap.put("ORANGE", "#FFA500");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() {
|
||||
Map<String, String> uniqValuesMap = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate());
|
||||
|
||||
uniqValuesMap.put("NEW_RED", "#FF0000");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateLazyMap_theMapIsCreated() {
|
||||
Map<Integer, String> intStrMap = MapUtils.lazyMap(new HashMap<Integer, String>(), TransformerUtils.stringValueTransformer());
|
||||
|
||||
assertThat(intStrMap, is(anEmptyMap()));
|
||||
|
||||
intStrMap.get(1);
|
||||
intStrMap.get(2);
|
||||
intStrMap.get(3);
|
||||
|
||||
assertThat(intStrMap, is(aMapWithSize(3)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.commons.collections;
|
||||
|
||||
import org.apache.commons.collections4.SetUtils;
|
||||
import org.apache.commons.collections4.set.TransformedSet;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class SetUtilsUnitTest {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenSetAndPredicate_whenPredicatedSet_thenValidateSet_and_throw_IllegalArgumentException() {
|
||||
Set<String> sourceSet = new HashSet<>();
|
||||
sourceSet.addAll(Arrays.asList("London", "Lagos", "Err Source1"));
|
||||
Set<String> validatingSet = SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L"));
|
||||
validatingSet.add("Err Source2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_whenDifference_thenSetView() {
|
||||
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5));
|
||||
Set<Integer> b = new HashSet<>(Arrays.asList(1, 2));
|
||||
SetUtils.SetView<Integer> result = SetUtils.difference(a, b);
|
||||
assertTrue(result.size() == 1 && result.contains(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_whenUnion_thenUnionResult() {
|
||||
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5));
|
||||
Set<Integer> b = new HashSet<>(Arrays.asList(1, 2));
|
||||
Set<Integer> expected = new HashSet<>(Arrays.asList(1, 2, 5));
|
||||
SetUtils.SetView<Integer> union = SetUtils.union(a, b);
|
||||
assertTrue(SetUtils.isEqualSet(expected, union));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_whenIntersection_thenIntersectionResult() {
|
||||
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5));
|
||||
Set<Integer> b = new HashSet<>(Arrays.asList(1, 2));
|
||||
Set<Integer> expected = new HashSet<>(Arrays.asList(1, 2));
|
||||
SetUtils.SetView<Integer> intersect = SetUtils.intersection(a, b);
|
||||
assertTrue(SetUtils.isEqualSet(expected, intersect));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_whenTransformedSet_thenTransformedResult() {
|
||||
Set<Integer> a = SetUtils.transformedSet(new HashSet<>(), (e) -> e * 2);
|
||||
a.add(2);
|
||||
assertEquals(a.toArray()[0], 4);
|
||||
|
||||
Set<Integer> source = new HashSet<>(Arrays.asList(1));
|
||||
Set<Integer> newSet = TransformedSet.transformedSet(source, (e) -> e * 2);
|
||||
assertEquals(newSet.toArray()[0], 2);
|
||||
assertEquals(source.toArray()[0], 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSet_whenDisjunction_thenDisjunctionSet() {
|
||||
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5));
|
||||
Set<Integer> b = new HashSet<>(Arrays.asList(1, 2, 3));
|
||||
SetUtils.SetView<Integer> result = SetUtils.disjunction(a, b);
|
||||
assertTrue(result.toSet().contains(5) && result.toSet().contains(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_when_OrderedSet_thenMaintainElementOrder() {
|
||||
Set<Integer> set = new HashSet<>(Arrays.asList(10, 1, 5));
|
||||
System.out.println("unordered set: " + set);
|
||||
|
||||
Set<Integer> orderedSet = SetUtils.orderedSet(new HashSet<>());
|
||||
orderedSet.addAll(Arrays.asList(10, 1, 5));
|
||||
System.out.println("ordered set = " + orderedSet);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package com.baeldung.commons.collections.orderedmap;
|
||||
|
||||
import org.apache.commons.collections4.OrderedMap;
|
||||
import org.apache.commons.collections4.OrderedMapIterator;
|
||||
import org.apache.commons.collections4.map.LinkedMap;
|
||||
import org.apache.commons.collections4.map.ListOrderedMap;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class OrderedMapUnitTest {
|
||||
|
||||
private String[] names = { "Emily", "Mathew", "Rose", "John", "Anna" };
|
||||
private Integer[] ages = { 37, 28, 40, 36, 21 };
|
||||
|
||||
private int RUNNERS_COUNT = names.length;
|
||||
|
||||
private OrderedMap<String, Integer> runnersLinkedMap;
|
||||
private OrderedMap<String, Integer> runnersListOrderedMap;
|
||||
|
||||
@Before
|
||||
public void createRunners() {
|
||||
// First implementation: ListOrderedMap
|
||||
this.runnersListOrderedMap = new ListOrderedMap<>();
|
||||
this.loadOrderedMapOfRunners(this.runnersListOrderedMap);
|
||||
|
||||
// Second implementation: LinkedMap
|
||||
this.runnersLinkedMap = new LinkedMap<>();
|
||||
this.loadOrderedMapOfRunners(this.runnersLinkedMap);
|
||||
}
|
||||
|
||||
private void loadOrderedMapOfRunners(OrderedMap<String, Integer> runners) {
|
||||
for (int i = 0; i < RUNNERS_COUNT; i++) {
|
||||
runners.put(this.names[i], this.ages[i]);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenIteratedWithMapIterator_thenPreservesOrder() {
|
||||
// Tests that the order in map iterator is the same
|
||||
// as defined in the constant arrays of names and ages:
|
||||
|
||||
OrderedMapIterator<String, Integer> runnersIterator = this.runnersLinkedMap.mapIterator();
|
||||
int i = 0;
|
||||
while (runnersIterator.hasNext()) {
|
||||
runnersIterator.next();
|
||||
assertEquals(runnersIterator.getKey(), this.names[i]);
|
||||
assertEquals(runnersIterator.getValue(), this.ages[i]);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenIteratedWithMapIterator_thenPreservesOrder() {
|
||||
// Tests that the order in map iterator is the same
|
||||
// as defined in the constant arrays of names and ages:
|
||||
|
||||
OrderedMapIterator<String, Integer> runnersIterator = this.runnersListOrderedMap.mapIterator();
|
||||
int i = 0;
|
||||
while (runnersIterator.hasNext()) {
|
||||
runnersIterator.next();
|
||||
assertEquals(runnersIterator.getKey(), this.names[i]);
|
||||
assertEquals(runnersIterator.getValue(), this.ages[i]);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenIteratedForwards_thenPreservesOrder() {
|
||||
// Tests that the order in the forward iteration is the same
|
||||
// as defined in the constant arrays of names and ages
|
||||
|
||||
String name = this.runnersLinkedMap.firstKey();
|
||||
int i = 0;
|
||||
while (name != null) {
|
||||
assertEquals(name, this.names[i]);
|
||||
name = this.runnersLinkedMap.nextKey(name);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenIteratedForwards_thenPreservesOrder() {
|
||||
// Tests that the order in the forward iteration is the same
|
||||
// as defined in the constant arrays of names and ages
|
||||
|
||||
String name = this.runnersListOrderedMap.firstKey();
|
||||
int i = 0;
|
||||
while (name != null) {
|
||||
assertEquals(name, this.names[i]);
|
||||
name = this.runnersListOrderedMap.nextKey(name);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenIteratedBackwards_thenPreservesOrder() {
|
||||
// Tests that the order in the backwards iteration is the same
|
||||
// as defined in the constant arrays of names and ages
|
||||
|
||||
String name = this.runnersLinkedMap.lastKey();
|
||||
int i = RUNNERS_COUNT - 1;
|
||||
while (name != null) {
|
||||
assertEquals(name, this.names[i]);
|
||||
name = this.runnersLinkedMap.previousKey(name);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenIteratedBackwards_thenPreservesOrder() {
|
||||
// Tests that the order in the backwards iteration is the same
|
||||
// as defined in the constant arrays of names and ages
|
||||
|
||||
String name = this.runnersListOrderedMap.lastKey();
|
||||
int i = RUNNERS_COUNT - 1;
|
||||
while (name != null) {
|
||||
assertEquals(name, this.names[i]);
|
||||
name = this.runnersListOrderedMap.previousKey(name);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenObjectIsSearched_thenMatchesConstantArray() {
|
||||
assertEquals(ages[4], this.runnersLinkedMap.get("Anna"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenConvertedToList_thenMatchesKeySet() {
|
||||
// Casting the OrderedMap to a LinkedMap we can use asList() method
|
||||
|
||||
LinkedMap<String, Integer> lmap = (LinkedMap<String, Integer>) this.runnersLinkedMap;
|
||||
List<String> listKeys = new ArrayList<>();
|
||||
listKeys.addAll(this.runnersLinkedMap.keySet());
|
||||
List<String> linkedMap = lmap.asList();
|
||||
assertEquals(listKeys, linkedMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenSearchByIndexIsUsed_thenMatchesConstantArray() {
|
||||
LinkedMap<String, Integer> lmap = (LinkedMap<String, Integer>) this.runnersLinkedMap;
|
||||
|
||||
for (int i = 0; i < RUNNERS_COUNT; i++) {
|
||||
// accessed by index:
|
||||
String name = lmap.get(i);
|
||||
assertEquals(name, this.names[i]);
|
||||
|
||||
// index of key concides with position in array
|
||||
assertEquals(lmap.indexOf(this.names[i]), i);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenElementRemoved_thenSizeDecrease() {
|
||||
LinkedMap<String, Integer> lmap = (LinkedMap<String, Integer>) this.runnersLinkedMap;
|
||||
Integer johnAge = lmap.remove("John");// by object
|
||||
assertEquals(johnAge, new Integer(36));
|
||||
assertEquals(lmap.size(), RUNNERS_COUNT - 1);
|
||||
|
||||
Integer emilyAge = lmap.remove(0);// by index
|
||||
assertEquals(emilyAge, new Integer(37));
|
||||
assertEquals(lmap.size(), RUNNERS_COUNT - 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenObjectIsSearched_thenMatchesConstantArray() {
|
||||
assertEquals(ages[4], this.runnersListOrderedMap.get("Anna"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenConvertedToList_thenMatchesKeySet() {
|
||||
ListOrderedMap<String, Integer> lomap = (ListOrderedMap<String, Integer>) this.runnersListOrderedMap;
|
||||
List<String> listKeys = new ArrayList<>();
|
||||
listKeys.addAll(this.runnersListOrderedMap.keySet());
|
||||
List<String> lomapList = lomap.asList();
|
||||
assertEquals(listKeys, lomapList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenSearchByIndexIsUsed_thenMatchesConstantArray() {
|
||||
ListOrderedMap<String, Integer> lomap = (ListOrderedMap<String, Integer>) this.runnersListOrderedMap;
|
||||
|
||||
for (int i = 0; i < RUNNERS_COUNT; i++) {
|
||||
// accessed by index:
|
||||
String name = lomap.get(i);
|
||||
assertEquals(name, this.names[i]);
|
||||
|
||||
// index of key concides with position in array
|
||||
assertEquals(lomap.indexOf(this.names[i]), i);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenElementRemoved_thenSizeDecrease() {
|
||||
ListOrderedMap<String, Integer> lomap = (ListOrderedMap<String, Integer>) this.runnersListOrderedMap;
|
||||
|
||||
Integer johnAge = lomap.remove("John");// by object
|
||||
|
||||
assertEquals(johnAge, new Integer(36));
|
||||
assertEquals(lomap.size(), RUNNERS_COUNT - 1);
|
||||
|
||||
Integer emilyAge = lomap.remove(0);// by index
|
||||
assertEquals(emilyAge, new Integer(37));
|
||||
assertEquals(lomap.size(), RUNNERS_COUNT - 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.baeldung.commons.collections4;
|
||||
|
||||
import org.apache.commons.collections4.Bag;
|
||||
import org.apache.commons.collections4.SortedBag;
|
||||
import org.apache.commons.collections4.bag.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
|
||||
public class BagUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMultipleCopies_whenAdded_theCountIsKept() {
|
||||
Bag<Integer> bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
|
||||
|
||||
assertThat(bag.getCount(1), equalTo(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() {
|
||||
Collection<Integer> collection = new ArrayList<>();
|
||||
|
||||
// Collection contract defines that add() should return true
|
||||
assertThat(collection.add(9), is(true));
|
||||
|
||||
// Even when element is already in the collection
|
||||
collection.add(1);
|
||||
assertThat(collection.add(1), is(true));
|
||||
|
||||
Bag<Integer> bag = new HashBag<>();
|
||||
|
||||
// Bag returns true on adding a new element
|
||||
assertThat(bag.add(9), is(true));
|
||||
|
||||
bag.add(1);
|
||||
// But breaks the contract with false when it has to increment the count
|
||||
assertThat(bag.add(1), is(not(true)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() {
|
||||
Bag<Integer> bag = CollectionBag.collectionBag(new HashBag<>());
|
||||
|
||||
bag.add(1);
|
||||
// This time the behavior is compliant to the Java Collection
|
||||
assertThat(bag.add(1), is((true)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() {
|
||||
Bag<Integer> bag = new HashBag<>();
|
||||
|
||||
// Adding 1 for 5 times
|
||||
bag.add(1, 5);
|
||||
assertThat(bag.getCount(1), equalTo(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleCopies_whenRemove_allAreRemoved() {
|
||||
Bag<Integer> bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
|
||||
|
||||
// From 3 we delete 1, 2 remain
|
||||
bag.remove(3, 1);
|
||||
assertThat(bag.getCount(3), equalTo(2));
|
||||
|
||||
// From 2 we delete all
|
||||
bag.remove(1);
|
||||
assertThat(bag.getCount(1), equalTo(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTree_whenDuplicateElementsAdded_thenSort() {
|
||||
TreeBag<Integer> bag = new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }));
|
||||
|
||||
assertThat(bag.first(), equalTo(1));
|
||||
assertThat(bag.getCount(bag.first()), equalTo(2));
|
||||
assertThat(bag.last(), equalTo(7));
|
||||
assertThat(bag.getCount(bag.last()), equalTo(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() {
|
||||
SortedBag<Integer> bag = CollectionSortedBag.collectionSortedBag(new TreeBag<>());
|
||||
|
||||
bag.add(1);
|
||||
assertThat(bag.add(1), is((true)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedBag_whenDuplicateElementsAdded_thenSort() {
|
||||
SynchronizedSortedBag<Integer> bag = SynchronizedSortedBag.synchronizedSortedBag(new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })));
|
||||
|
||||
assertThat(bag.first(), equalTo(1));
|
||||
assertThat(bag.getCount(bag.first()), equalTo(2));
|
||||
assertThat(bag.last(), equalTo(7));
|
||||
assertThat(bag.getCount(bag.last()), equalTo(3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.commons.csv;
|
||||
|
||||
import org.apache.commons.csv.CSVFormat;
|
||||
import org.apache.commons.csv.CSVPrinter;
|
||||
import org.apache.commons.csv.CSVRecord;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.io.StringWriter;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CSVReaderWriterUnitTest {
|
||||
|
||||
public static final Map<String, String> AUTHOR_BOOK_MAP = Collections.unmodifiableMap(new LinkedHashMap<String, String>() {
|
||||
{
|
||||
put("Dan Simmons", "Hyperion");
|
||||
put("Douglas Adams", "The Hitchhiker's Guide to the Galaxy");
|
||||
}
|
||||
});
|
||||
public static final String[] HEADERS = { "author", "title" };
|
||||
public static final String EXPECTED_FILESTREAM = "author,title\r\n" + "Dan Simmons,Hyperion\r\n" + "Douglas Adams,The Hitchhiker's Guide to the Galaxy";
|
||||
|
||||
@Test
|
||||
public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException {
|
||||
Reader in = new FileReader("src/test/resources/book.csv");
|
||||
Iterable<CSVRecord> records = CSVFormat.DEFAULT.withHeader(HEADERS).withFirstRecordAsHeader().parse(in);
|
||||
for (CSVRecord record : records) {
|
||||
String author = record.get("author");
|
||||
String title = record.get("title");
|
||||
assertEquals(AUTHOR_BOOK_MAP.get(author), title);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException {
|
||||
StringWriter sw = new StringWriter();
|
||||
try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(HEADERS))) {
|
||||
AUTHOR_BOOK_MAP.forEach((author, title) -> {
|
||||
try {
|
||||
printer.printRecord(author, title);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
}
|
||||
assertEquals(EXPECTED_FILESTREAM, sw.toString().trim());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.baeldung.commons.dbutils;
|
||||
|
||||
import org.apache.commons.dbutils.AsyncQueryRunner;
|
||||
import org.apache.commons.dbutils.DbUtils;
|
||||
import org.apache.commons.dbutils.QueryRunner;
|
||||
import org.apache.commons.dbutils.handlers.BeanListHandler;
|
||||
import org.apache.commons.dbutils.handlers.MapListHandler;
|
||||
import org.apache.commons.dbutils.handlers.ScalarHandler;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class DbUtilsUnitTest {
|
||||
|
||||
private Connection connection;
|
||||
|
||||
@Before
|
||||
public void setupDB() throws Exception {
|
||||
Class.forName("org.h2.Driver");
|
||||
String db = "jdbc:h2:mem:;INIT=runscript from 'classpath:/employees.sql'";
|
||||
connection = DriverManager.getConnection(db);
|
||||
}
|
||||
|
||||
@After
|
||||
public void closeBD() {
|
||||
DbUtils.closeQuietly(connection);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResultHandler_whenExecutingQuery_thenExpectedList() throws SQLException {
|
||||
MapListHandler beanListHandler = new MapListHandler();
|
||||
|
||||
QueryRunner runner = new QueryRunner();
|
||||
List<Map<String, Object>> list = runner.query(connection, "SELECT * FROM employee", beanListHandler);
|
||||
|
||||
assertEquals(list.size(), 5);
|
||||
assertEquals(list.get(0).get("firstname"), "John");
|
||||
assertEquals(list.get(4).get("firstname"), "Christian");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResultHandler_whenExecutingQuery_thenEmployeeList() throws SQLException {
|
||||
BeanListHandler<Employee> beanListHandler = new BeanListHandler<>(Employee.class);
|
||||
|
||||
QueryRunner runner = new QueryRunner();
|
||||
List<Employee> employeeList = runner.query(connection, "SELECT * FROM employee", beanListHandler);
|
||||
|
||||
assertEquals(employeeList.size(), 5);
|
||||
assertEquals(employeeList.get(0).getFirstName(), "John");
|
||||
assertEquals(employeeList.get(4).getFirstName(), "Christian");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResultHandler_whenExecutingQuery_thenExpectedScalar() throws SQLException {
|
||||
ScalarHandler<Long> scalarHandler = new ScalarHandler<>();
|
||||
|
||||
QueryRunner runner = new QueryRunner();
|
||||
String query = "SELECT COUNT(*) FROM employee";
|
||||
long count = runner.query(connection, query, scalarHandler);
|
||||
|
||||
assertEquals(count, 5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResultHandler_whenExecutingQuery_thenEmailsSetted() throws SQLException {
|
||||
EmployeeHandler employeeHandler = new EmployeeHandler(connection);
|
||||
|
||||
QueryRunner runner = new QueryRunner();
|
||||
List<Employee> employees = runner.query(connection, "SELECT * FROM employee", employeeHandler);
|
||||
|
||||
assertEquals(employees.get(0).getEmails().size(), 2);
|
||||
assertEquals(employees.get(2).getEmails().size(), 3);
|
||||
assertNotNull(employees.get(0).getEmails().get(0).getEmployeeId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResultHandler_whenExecutingQuery_thenAllPropertiesSetted() throws SQLException {
|
||||
EmployeeHandler employeeHandler = new EmployeeHandler(connection);
|
||||
|
||||
QueryRunner runner = new QueryRunner();
|
||||
String query = "SELECT * FROM employee_legacy";
|
||||
List<Employee> employees = runner.query(connection, query, employeeHandler);
|
||||
|
||||
assertEquals((int) employees.get(0).getId(), 1);
|
||||
assertEquals(employees.get(0).getFirstName(), "John");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInserting_thenInserted() throws SQLException {
|
||||
QueryRunner runner = new QueryRunner();
|
||||
String insertSQL = "INSERT INTO employee (firstname,lastname,salary, hireddate) VALUES (?, ?, ?, ?)";
|
||||
|
||||
int numRowsInserted = runner.update(connection, insertSQL, "Leia", "Kane", 60000.60, new Date());
|
||||
|
||||
assertEquals(numRowsInserted, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHandler_whenInserting_thenExpectedId() throws SQLException {
|
||||
ScalarHandler<Integer> scalarHandler = new ScalarHandler<>();
|
||||
|
||||
QueryRunner runner = new QueryRunner();
|
||||
String insertSQL = "INSERT INTO employee (firstname,lastname,salary, hireddate) VALUES (?, ?, ?, ?)";
|
||||
|
||||
int newId = runner.insert(connection, insertSQL, scalarHandler, "Jenny", "Medici", 60000.60, new Date());
|
||||
|
||||
assertEquals(newId, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSalary_whenUpdating_thenUpdated() throws SQLException {
|
||||
double salary = 35000;
|
||||
|
||||
QueryRunner runner = new QueryRunner();
|
||||
String updateSQL = "UPDATE employee SET salary = salary * 1.1 WHERE salary <= ?";
|
||||
int numRowsUpdated = runner.update(connection, updateSQL, salary);
|
||||
|
||||
assertEquals(numRowsUpdated, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeletingRecord_thenDeleted() throws SQLException {
|
||||
QueryRunner runner = new QueryRunner();
|
||||
String deleteSQL = "DELETE FROM employee WHERE id = ?";
|
||||
int numRowsDeleted = runner.update(connection, deleteSQL, 3);
|
||||
|
||||
assertEquals(numRowsDeleted, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAsyncRunner_whenExecutingQuery_thenExpectedList() throws Exception {
|
||||
AsyncQueryRunner runner = new AsyncQueryRunner(Executors.newCachedThreadPool());
|
||||
|
||||
EmployeeHandler employeeHandler = new EmployeeHandler(connection);
|
||||
String query = "SELECT * FROM employee";
|
||||
Future<List<Employee>> future = runner.query(connection, query, employeeHandler);
|
||||
List<Employee> employeeList = future.get(10, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(employeeList.size(), 5);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.baeldung.commons.io;
|
||||
|
||||
import org.apache.commons.io.FileSystemUtils;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.apache.commons.io.IOCase;
|
||||
import org.apache.commons.io.comparator.PathFileComparator;
|
||||
import org.apache.commons.io.comparator.SizeFileComparator;
|
||||
import org.apache.commons.io.filefilter.AndFileFilter;
|
||||
import org.apache.commons.io.filefilter.NameFileFilter;
|
||||
import org.apache.commons.io.filefilter.SuffixFileFilter;
|
||||
import org.apache.commons.io.filefilter.WildcardFileFilter;
|
||||
import org.apache.commons.io.input.TeeInputStream;
|
||||
import org.apache.commons.io.output.TeeOutputStream;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FilterOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
public class CommonsIOUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCopyANDReadFileTesttxt_thenMatchExpectedData() throws IOException {
|
||||
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
File file = FileUtils.getFile(getClass().getClassLoader().getResource("fileTest.txt").getPath());
|
||||
File tempDir = FileUtils.getTempDirectory();
|
||||
FileUtils.copyFileToDirectory(file, tempDir);
|
||||
File newTempFile = FileUtils.getFile(tempDir, file.getName());
|
||||
String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset());
|
||||
|
||||
Assert.assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFileNameUtils_thenshowdifferentFileOperations() throws IOException {
|
||||
|
||||
String path = getClass().getClassLoader().getResource("fileTest.txt").getPath();
|
||||
|
||||
String fullPath = FilenameUtils.getFullPath(path);
|
||||
String extension = FilenameUtils.getExtension(path);
|
||||
String baseName = FilenameUtils.getBaseName(path);
|
||||
|
||||
System.out.println("full path" + fullPath);
|
||||
System.out.println("Extension" + extension);
|
||||
System.out.println("Base name" + baseName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFileSystemUtils_thenDriveFreeSpace() throws IOException {
|
||||
|
||||
long freeSpace = FileSystemUtils.freeSpaceKb("/");
|
||||
}
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
@Test
|
||||
public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams() throws IOException {
|
||||
|
||||
final String str = "Hello World.";
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
|
||||
ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
|
||||
ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
|
||||
|
||||
FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);
|
||||
new TeeInputStream(inputStream, teeOutputStream, true).read(new byte[str.length()]);
|
||||
|
||||
Assert.assertEquals(str, String.valueOf(outputStream1));
|
||||
Assert.assertEquals(str, String.valueOf(outputStream2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFilewithNameFileFilter_thenFindfileTesttxt() throws IOException {
|
||||
|
||||
final String testFile = "fileTest.txt";
|
||||
|
||||
String path = getClass().getClassLoader().getResource(testFile).getPath();
|
||||
File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));
|
||||
|
||||
String[] possibleNames = { "NotThisOne", testFile };
|
||||
|
||||
Assert.assertEquals(testFile, dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFilewith_ANDFileFilter_thenFindsampletxt() throws IOException {
|
||||
|
||||
String path = getClass().getClassLoader().getResource("fileTest.txt").getPath();
|
||||
File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));
|
||||
|
||||
Assert.assertEquals("sample.txt", dir.list(new AndFileFilter(new WildcardFileFilter("*ple*", IOCase.INSENSITIVE), new SuffixFileFilter("txt")))[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSortDirWithPathFileComparator_thenFirstFileaaatxt() throws IOException {
|
||||
|
||||
PathFileComparator pathFileComparator = new PathFileComparator(IOCase.INSENSITIVE);
|
||||
String path = FilenameUtils.getFullPath(getClass().getClassLoader().getResource("fileTest.txt").getPath());
|
||||
File dir = new File(path);
|
||||
File[] files = dir.listFiles();
|
||||
|
||||
pathFileComparator.sort(files);
|
||||
|
||||
Assert.assertEquals("aaa.txt", files[0].getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSizeFileComparator_thenLargerFile() throws IOException {
|
||||
|
||||
SizeFileComparator sizeFileComparator = new SizeFileComparator();
|
||||
File largerFile = FileUtils.getFile(getClass().getClassLoader().getResource("fileTest.txt").getPath());
|
||||
File smallerFile = FileUtils.getFile(getClass().getClassLoader().getResource("sample.txt").getPath());
|
||||
|
||||
int i = sizeFileComparator.compare(largerFile, smallerFile);
|
||||
|
||||
Assert.assertTrue(i > 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.baeldung.commons.lang3;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ArrayUtilsUnitTest {
|
||||
@Test
|
||||
public void givenArray_whenAddingElementAtSpecifiedPosition_thenCorrect() {
|
||||
int[] oldArray = { 2, 3, 4, 5 };
|
||||
int[] newArray = ArrayUtils.add(oldArray, 0, 1);
|
||||
int[] expectedArray = { 1, 2, 3, 4, 5 };
|
||||
assertArrayEquals(expectedArray, newArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenAddingElementAtTheEnd_thenCorrect() {
|
||||
int[] oldArray = { 2, 3, 4, 5 };
|
||||
int[] newArray = ArrayUtils.add(oldArray, 1);
|
||||
int[] expectedArray = { 2, 3, 4, 5, 1 };
|
||||
assertArrayEquals(expectedArray, newArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenAddingAllElementsAtTheEnd_thenCorrect() {
|
||||
int[] oldArray = { 0, 1, 2 };
|
||||
int[] newArray = ArrayUtils.addAll(oldArray, 3, 4, 5);
|
||||
int[] expectedArray = { 0, 1, 2, 3, 4, 5 };
|
||||
assertArrayEquals(expectedArray, newArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenRemovingElementAtSpecifiedPosition_thenCorrect() {
|
||||
int[] oldArray = { 1, 2, 3, 4, 5 };
|
||||
int[] newArray = ArrayUtils.remove(oldArray, 1);
|
||||
int[] expectedArray = { 1, 3, 4, 5 };
|
||||
assertArrayEquals(expectedArray, newArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenRemovingAllElementsAtSpecifiedPositions_thenCorrect() {
|
||||
int[] oldArray = { 1, 2, 3, 4, 5 };
|
||||
int[] newArray = ArrayUtils.removeAll(oldArray, 1, 3);
|
||||
int[] expectedArray = { 1, 3, 5 };
|
||||
assertArrayEquals(expectedArray, newArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenRemovingAnElement_thenCorrect() {
|
||||
int[] oldArray = { 1, 2, 3, 3, 4 };
|
||||
int[] newArray = ArrayUtils.removeElement(oldArray, 3);
|
||||
int[] expectedArray = { 1, 2, 3, 4 };
|
||||
assertArrayEquals(expectedArray, newArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenRemovingElements_thenCorrect() {
|
||||
int[] oldArray = { 1, 2, 3, 3, 4 };
|
||||
int[] newArray = ArrayUtils.removeElements(oldArray, 2, 3, 5);
|
||||
int[] expectedArray = { 1, 3, 4 };
|
||||
assertArrayEquals(expectedArray, newArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenRemovingAllElementOccurences_thenCorrect() {
|
||||
int[] oldArray = { 1, 2, 2, 2, 3 };
|
||||
int[] newArray = ArrayUtils.removeAllOccurences(oldArray, 2);
|
||||
int[] expectedArray = { 1, 3 };
|
||||
assertArrayEquals(expectedArray, newArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenCheckingExistingElement_thenCorrect() {
|
||||
int[] array = { 1, 3, 5, 7, 9 };
|
||||
boolean evenContained = ArrayUtils.contains(array, 2);
|
||||
boolean oddContained = ArrayUtils.contains(array, 7);
|
||||
assertEquals(false, evenContained);
|
||||
assertEquals(true, oddContained);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenReversingElementsWithinARange_thenCorrect() {
|
||||
int[] originalArray = { 1, 2, 3, 4, 5 };
|
||||
ArrayUtils.reverse(originalArray, 1, 4);
|
||||
int[] expectedArray = { 1, 4, 3, 2, 5 };
|
||||
assertArrayEquals(expectedArray, originalArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenReversingAllElements_thenCorrect() {
|
||||
int[] originalArray = { 1, 2, 3, 4, 5 };
|
||||
ArrayUtils.reverse(originalArray);
|
||||
int[] expectedArray = { 5, 4, 3, 2, 1 };
|
||||
assertArrayEquals(expectedArray, originalArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenShiftingElementsWithinARange_thenCorrect() {
|
||||
int[] originalArray = { 1, 2, 3, 4, 5 };
|
||||
ArrayUtils.shift(originalArray, 1, 4, 1);
|
||||
int[] expectedArray = { 1, 4, 2, 3, 5 };
|
||||
assertArrayEquals(expectedArray, originalArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenShiftingAllElements_thenCorrect() {
|
||||
int[] originalArray = { 1, 2, 3, 4, 5 };
|
||||
ArrayUtils.shift(originalArray, 1);
|
||||
int[] expectedArray = { 5, 1, 2, 3, 4 };
|
||||
assertArrayEquals(expectedArray, originalArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenExtractingElements_thenCorrect() {
|
||||
int[] oldArray = { 1, 2, 3, 4, 5 };
|
||||
int[] newArray = ArrayUtils.subarray(oldArray, 2, 7);
|
||||
int[] expectedArray = { 3, 4, 5 };
|
||||
assertArrayEquals(expectedArray, newArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenSwapingElementsWithinARange_thenCorrect() {
|
||||
int[] originalArray = { 1, 2, 3, 4, 5 };
|
||||
ArrayUtils.swap(originalArray, 0, 3, 2);
|
||||
int[] expectedArray = { 4, 5, 3, 1, 2 };
|
||||
assertArrayEquals(expectedArray, originalArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenSwapingElementsAtSpecifiedPositions_thenCorrect() {
|
||||
int[] originalArray = { 1, 2, 3, 4, 5 };
|
||||
ArrayUtils.swap(originalArray, 0, 3);
|
||||
int[] expectedArray = { 4, 2, 3, 1, 5 };
|
||||
assertArrayEquals(expectedArray, originalArray);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.baeldung.commons.lang3;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNotSame;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.beans.PropertyChangeEvent;
|
||||
import java.beans.PropertyChangeListener;
|
||||
import java.io.File;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import org.apache.commons.lang3.ArchUtils;
|
||||
import org.apache.commons.lang3.BooleanUtils;
|
||||
import org.apache.commons.lang3.SystemUtils;
|
||||
import org.apache.commons.lang3.arch.Processor;
|
||||
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentException;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentRuntimeException;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentUtils;
|
||||
import org.apache.commons.lang3.event.EventUtils;
|
||||
import org.apache.commons.lang3.reflect.FieldUtils;
|
||||
import org.apache.commons.lang3.time.FastDateFormat;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class Lang3UtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void test_to_Boolean_fromString() {
|
||||
assertFalse(BooleanUtils.toBoolean("off"));
|
||||
assertTrue(BooleanUtils.toBoolean("true"));
|
||||
assertTrue(BooleanUtils.toBoolean("tRue"));
|
||||
assertFalse(BooleanUtils.toBoolean("no"));
|
||||
assertFalse(BooleanUtils.isTrue(Boolean.FALSE));
|
||||
assertFalse(BooleanUtils.isTrue(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetUserHome() {
|
||||
final File dir = SystemUtils.getUserHome();
|
||||
Assert.assertNotNull(dir);
|
||||
Assert.assertTrue(dir.exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetJavaHome() {
|
||||
final File dir = SystemUtils.getJavaHome();
|
||||
Assert.assertNotNull(dir);
|
||||
Assert.assertTrue(dir.exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessorArchType() {
|
||||
Processor processor = ArchUtils.getProcessor("x86");
|
||||
assertTrue(processor.is32Bit());
|
||||
assertFalse(processor.is64Bit());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessorArchType64Bit() {
|
||||
Processor processor = ArchUtils.getProcessor("x86_64");
|
||||
assertFalse(processor.is32Bit());
|
||||
assertTrue(processor.is64Bit());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testConcurrentRuntimeExceptionCauseError() {
|
||||
new ConcurrentRuntimeException("An error", new Error());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConstantFuture_Integer() throws Exception {
|
||||
Future<Integer> test = ConcurrentUtils.constantFuture(5);
|
||||
assertTrue(test.isDone());
|
||||
assertSame(5, test.get());
|
||||
assertFalse(test.isCancelled());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFieldUtilsGetAllFields() {
|
||||
final Field[] fieldsNumber = Number.class.getDeclaredFields();
|
||||
assertArrayEquals(fieldsNumber, FieldUtils.getAllFields(Number.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_getInstance_String_Locale() {
|
||||
final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.US);
|
||||
final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
|
||||
|
||||
assertNotSame(format1, format3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddEventListenerThrowsException() {
|
||||
final ExceptionEventSource src = new ExceptionEventSource();
|
||||
try {
|
||||
EventUtils.addEventListener(src, PropertyChangeListener.class, (PropertyChangeEvent e) -> {
|
||||
/* Change event*/});
|
||||
fail("Add method should have thrown an exception, so method should fail.");
|
||||
} catch (final RuntimeException e) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ConcurrentExceptionSample() throws ConcurrentException {
|
||||
final Error err = new AssertionError("Test");
|
||||
try {
|
||||
ConcurrentUtils.handleCause(new ExecutionException(err));
|
||||
fail("Error not thrown!");
|
||||
} catch (final Error e) {
|
||||
assertEquals("Wrong error", err, e);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ExceptionEventSource {
|
||||
public void addPropertyChangeListener(final PropertyChangeListener listener) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLazyInitializer() throws Exception {
|
||||
SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer();
|
||||
SampleObject sampleObjectOne = sampleLazyInitializer.get();
|
||||
SampleObject sampleObjectTwo = sampleLazyInitializer.get();
|
||||
assertEquals(sampleObjectOne, sampleObjectTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildDefaults() {
|
||||
BasicThreadFactory.Builder builder = new BasicThreadFactory.Builder();
|
||||
BasicThreadFactory factory = builder.build();
|
||||
assertNull("No naming pattern set Yet", factory.getNamingPattern());
|
||||
BasicThreadFactory factory2 = builder.namingPattern("sampleNamingPattern").daemon(true).priority(Thread.MIN_PRIORITY).build();
|
||||
assertNotNull("Got a naming pattern", factory2.getNamingPattern());
|
||||
assertEquals("sampleNamingPattern", factory2.getNamingPattern());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.baeldung.commons.lang3;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class StringUtilsUnitTest {
|
||||
@Test
|
||||
public void givenString_whenCheckingContainsAny_thenCorrect() {
|
||||
String string = "baeldung.com";
|
||||
boolean contained1 = StringUtils.containsAny(string, 'a', 'b', 'c');
|
||||
boolean contained2 = StringUtils.containsAny(string, 'x', 'y', 'z');
|
||||
boolean contained3 = StringUtils.containsAny(string, "abc");
|
||||
boolean contained4 = StringUtils.containsAny(string, "xyz");
|
||||
assertTrue(contained1);
|
||||
assertFalse(contained2);
|
||||
assertTrue(contained3);
|
||||
assertFalse(contained4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenCheckingContainsIgnoreCase_thenCorrect() {
|
||||
String string = "baeldung.com";
|
||||
boolean contained = StringUtils.containsIgnoreCase(string, "BAELDUNG");
|
||||
assertTrue(contained);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenCountingMatches_thenCorrect() {
|
||||
String string = "welcome to www.baeldung.com";
|
||||
int charNum = StringUtils.countMatches(string, 'w');
|
||||
int stringNum = StringUtils.countMatches(string, "com");
|
||||
assertEquals(4, charNum);
|
||||
assertEquals(2, stringNum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenAppendingAndPrependingIfMissing_thenCorrect() {
|
||||
String string = "baeldung.com";
|
||||
String stringWithSuffix = StringUtils.appendIfMissing(string, ".com");
|
||||
String stringWithPrefix = StringUtils.prependIfMissing(string, "www.");
|
||||
assertEquals("baeldung.com", stringWithSuffix);
|
||||
assertEquals("www.baeldung.com", stringWithPrefix);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenSwappingCase_thenCorrect() {
|
||||
String originalString = "baeldung.COM";
|
||||
String swappedString = StringUtils.swapCase(originalString);
|
||||
assertEquals("BAELDUNG.com", swappedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenCapitalizing_thenCorrect() {
|
||||
String originalString = "baeldung";
|
||||
String capitalizedString = StringUtils.capitalize(originalString);
|
||||
assertEquals("Baeldung", capitalizedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUncapitalizing_thenCorrect() {
|
||||
String originalString = "Baeldung";
|
||||
String uncapitalizedString = StringUtils.uncapitalize(originalString);
|
||||
assertEquals("baeldung", uncapitalizedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenReversingCharacters_thenCorrect() {
|
||||
String originalString = "baeldung";
|
||||
String reversedString = StringUtils.reverse(originalString);
|
||||
assertEquals("gnudleab", reversedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenReversingWithDelimiter_thenCorrect() {
|
||||
String originalString = "www.baeldung.com";
|
||||
String reversedString = StringUtils.reverseDelimited(originalString, '.');
|
||||
assertEquals("com.baeldung.www", reversedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenRotatingTwoPositions_thenCorrect() {
|
||||
String originalString = "baeldung";
|
||||
String rotatedString = StringUtils.rotate(originalString, 4);
|
||||
assertEquals("dungbael", rotatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStrings_whenComparing_thenCorrect() {
|
||||
String tutorials = "Baeldung Tutorials";
|
||||
String courses = "Baeldung Courses";
|
||||
String diff1 = StringUtils.difference(tutorials, courses);
|
||||
String diff2 = StringUtils.difference(courses, tutorials);
|
||||
assertEquals("Courses", diff1);
|
||||
assertEquals("Tutorials", diff2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ArrayUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenArrayUtilsClass_whenCalledtoString_thenCorrect() {
|
||||
String[] array = {"a", "b", "c"};
|
||||
assertThat(ArrayUtils.toString(array)).isEqualTo("{a,b,c}");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayUtilsClass_whenCalledtoStringIfArrayisNull_thenCorrect() {
|
||||
String[] array = null;
|
||||
assertThat(ArrayUtils.toString(array, "Array is null")).isEqualTo("Array is null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayUtilsClass_whenCalledhashCode_thenCorrect() {
|
||||
String[] array = {"a", "b", "c"};
|
||||
assertThat(ArrayUtils.hashCode(array)).isEqualTo(997619);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayUtilsClass_whenCalledtoMap_thenCorrect() {
|
||||
String[][] array = {{"1", "one", }, {"2", "two", }, {"3", "three"}};
|
||||
Map map = new HashMap();
|
||||
map.put("1", "one");
|
||||
map.put("2", "two");
|
||||
map.put("3", "three");
|
||||
assertThat(ArrayUtils.toMap(array)).isEqualTo(map);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayUtilsClass_whenCallednullToEmptyStringArray_thenCorrect() {
|
||||
String[] array = null;
|
||||
assertThat(ArrayUtils.nullToEmpty(array)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayUtilsClass_whenCallednullToEmptyObjectArray_thenCorrect() {
|
||||
Object[] array = null;
|
||||
assertThat(ArrayUtils.nullToEmpty(array)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayUtilsClass_whenCalledsubarray_thenCorrect() {
|
||||
int[] array = {1, 2, 3};
|
||||
int[] expected = {1};
|
||||
assertThat(ArrayUtils.subarray(array, 0, 1)).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayUtilsClass_whenCalledisSameLength_thenCorrect() {
|
||||
int[] array1 = {1, 2, 3};
|
||||
int[] array2 = {1, 2, 3};
|
||||
assertThat(ArrayUtils.isSameLength(array1, array2)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayUtilsClass_whenCalledreverse_thenCorrect() {
|
||||
int[] array1 = {1, 2, 3};
|
||||
int[] array2 = {3, 2, 1};
|
||||
ArrayUtils.reverse(array1);
|
||||
assertThat(array1).isEqualTo(array2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayUtilsClass_whenCalledIndexOf_thenCorrect() {
|
||||
int[] array = {1, 2, 3};
|
||||
assertThat(ArrayUtils.indexOf(array, 1, 0)).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayUtilsClass_whenCalledcontains_thenCorrect() {
|
||||
int[] array = {1, 2, 3};
|
||||
assertThat(ArrayUtils.contains(array, 1)).isTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class BasicThreadFactoryUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenBasicThreadFactoryInstance_whenCalledBuilder_thenCorrect() {
|
||||
BasicThreadFactory factory = new BasicThreadFactory.Builder()
|
||||
.namingPattern("workerthread-%d")
|
||||
.daemon(true)
|
||||
.priority(Thread.MAX_PRIORITY)
|
||||
.build();
|
||||
assertThat(factory).isInstanceOf(BasicThreadFactory.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import com.baeldung.commons.lang3.beans.User;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import org.apache.commons.lang3.reflect.ConstructorUtils;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ConstructorUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenConstructorUtilsClass_whenCalledgetAccessibleConstructor_thenCorrect() {
|
||||
assertThat(ConstructorUtils.getAccessibleConstructor(User.class, String.class, String.class)).isInstanceOf(Constructor.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConstructorUtilsClass_whenCalledinvokeConstructor_thenCorrect() throws Exception {
|
||||
assertThat(ConstructorUtils.invokeConstructor(User.class, "name", "email")).isInstanceOf(User.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConstructorUtilsClass_whenCalledinvokeExactConstructor_thenCorrect() throws Exception {
|
||||
String[] args = {"name", "email"};
|
||||
Class[] parameterTypes= {String.class, String.class};
|
||||
assertThat(ConstructorUtils.invokeExactConstructor(User.class, args, parameterTypes)).isInstanceOf(User.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import com.baeldung.commons.lang3.beans.User;
|
||||
import org.apache.commons.lang3.reflect.FieldUtils;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FieldUtilsUnitTest {
|
||||
|
||||
private static User user;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpUserInstance() {
|
||||
user = new User("Julie", "julie@domain.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFieldUtilsClass_whenCalledgetField_thenCorrect() {
|
||||
assertThat(FieldUtils.getField(User.class, "name", true).getName()).isEqualTo("name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFieldUtilsClass_whenCalledgetFieldForceAccess_thenCorrect() {
|
||||
assertThat(FieldUtils.getField(User.class, "name", true).getName()).isEqualTo("name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFieldUtilsClass_whenCalledgetDeclaredFieldForceAccess_thenCorrect() {
|
||||
assertThat(FieldUtils.getDeclaredField(User.class, "name", true).getName()).isEqualTo("name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFieldUtilsClass_whenCalledgetAllField_thenCorrect() {
|
||||
assertThat(FieldUtils.getAllFields(User.class).length).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFieldUtilsClass_whenCalledreadField_thenCorrect() throws IllegalAccessException {
|
||||
assertThat(FieldUtils.readField(user, "name", true)).isEqualTo("Julie");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFieldUtilsClass_whenCalledreadDeclaredField_thenCorrect() throws IllegalAccessException {
|
||||
assertThat(FieldUtils.readDeclaredField(user, "name", true)).isEqualTo("Julie");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFieldUtilsClass_whenCalledwriteField_thenCorrect() throws IllegalAccessException {
|
||||
FieldUtils.writeField(user, "name", "Julie", true);
|
||||
assertThat(FieldUtils.readField(user, "name", true)).isEqualTo("Julie");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFieldUtilsClass_whenCalledwriteDeclaredField_thenCorrect() throws IllegalAccessException {
|
||||
FieldUtils.writeDeclaredField(user, "name", "Julie", true);
|
||||
assertThat(FieldUtils.readField(user, "name", true)).isEqualTo("Julie");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import org.apache.commons.lang3.math.Fraction;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FractionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenFractionClass_whenCalledgetFraction_thenCorrect() {
|
||||
assertThat(Fraction.getFraction(5, 6)).isInstanceOf(Fraction.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoFractionInstances_whenCalledadd_thenCorrect() {
|
||||
Fraction fraction1 = Fraction.getFraction(1, 4);
|
||||
Fraction fraction2 = Fraction.getFraction(3, 4);
|
||||
assertThat(fraction1.add(fraction2).toString()).isEqualTo("1/1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoFractionInstances_whenCalledsubstract_thenCorrect() {
|
||||
Fraction fraction1 = Fraction.getFraction(3, 4);
|
||||
Fraction fraction2 = Fraction.getFraction(1, 4);
|
||||
assertThat(fraction1.subtract(fraction2).toString()).isEqualTo("1/2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoFractionInstances_whenCalledmultiply_thenCorrect() {
|
||||
Fraction fraction1 = Fraction.getFraction(3, 4);
|
||||
Fraction fraction2 = Fraction.getFraction(1, 4);
|
||||
assertThat(fraction1.multiplyBy(fraction2).toString()).isEqualTo("3/16");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import org.apache.commons.lang3.builder.HashCodeBuilder;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class HashCodeBuilderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenHashCodeBuilderInstance_whenCalledtoHashCode_thenCorrect() {
|
||||
int hashcode = new HashCodeBuilder(17, 37)
|
||||
.append("John")
|
||||
.append("john@domain.com")
|
||||
.toHashCode();
|
||||
assertThat(hashcode).isEqualTo(1269178828);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import org.apache.commons.lang3.tuple.ImmutablePair;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ImmutablePairUnitTest {
|
||||
|
||||
private static ImmutablePair<String, String> immutablePair;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpImmutablePairInstance() {
|
||||
immutablePair = new ImmutablePair<>("leftElement", "rightElement");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImmutablePairInstance_whenCalledgetLeft_thenCorrect() {
|
||||
assertThat(immutablePair.getLeft()).isEqualTo("leftElement");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImmutablePairInstance_whenCalledgetRight_thenCorrect() {
|
||||
assertThat(immutablePair.getRight()).isEqualTo("rightElement");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImmutablePairInstance_whenCalledof_thenCorrect() {
|
||||
assertThat(ImmutablePair.of("leftElement", "rightElement")).isInstanceOf(ImmutablePair.class);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void givenImmutablePairInstance_whenCalledSetValue_thenThrowUnsupportedOperationException() {
|
||||
immutablePair.setValue("newValue");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import org.apache.commons.lang3.tuple.ImmutableTriple;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ImmutableTripleUnitTest {
|
||||
|
||||
private static ImmutableTriple<String, String, String> immutableTriple;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpImmutableTripleInstance() {
|
||||
immutableTriple = new ImmutableTriple<>("leftElement", "middleElement", "rightElement");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImmutableTripleInstance_whenCalledgetLeft_thenCorrect() {
|
||||
assertThat(immutableTriple.getLeft()).isEqualTo("leftElement");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImmutableTripleInstance_whenCalledgetMiddle_thenCorrect() {
|
||||
assertThat(immutableTriple.getMiddle()).isEqualTo("middleElement");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImmutableInstance_whenCalledgetRight_thenCorrect() {
|
||||
assertThat(immutableTriple.getRight()).isEqualTo("rightElement");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import com.baeldung.commons.lang3.beans.User;
|
||||
import com.baeldung.commons.lang3.beans.UserInitializer;
|
||||
import org.apache.commons.lang3.concurrent.ConcurrentException;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LazyInitializerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLazyInitializerInstance_whenCalledget_thenCorrect() throws ConcurrentException {
|
||||
UserInitializer userInitializer = new UserInitializer();
|
||||
assertThat(userInitializer.get()).isInstanceOf(User.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import com.baeldung.commons.lang3.beans.User;
|
||||
import java.lang.reflect.Method;
|
||||
import org.apache.commons.lang3.reflect.MethodUtils;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class MethodUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMethodUtilsClass_whenCalledgetAccessibleMethod_thenCorrect() {
|
||||
assertThat(MethodUtils.getAccessibleMethod(User.class, "getName")).isInstanceOf(Method.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import org.apache.commons.lang3.mutable.MutableObject;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class MutableObjectUnitTest {
|
||||
|
||||
private static MutableObject mutableObject;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpMutableObject() {
|
||||
mutableObject = new MutableObject("Initial value");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMutableObject_whenCalledgetValue_thenCorrect() {
|
||||
assertThat(mutableObject.getValue()).isInstanceOf(String.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMutableObject_whenCalledsetValue_thenCorrect() {
|
||||
mutableObject.setValue("Another value");
|
||||
assertThat(mutableObject.getValue()).isEqualTo("Another value");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMutableObject_whenCalledtoString_thenCorrect() {
|
||||
assertThat(mutableObject.toString()).isEqualTo("Another value");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import org.apache.commons.lang3.tuple.MutablePair;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class MutablePairUnitTest {
|
||||
|
||||
private static MutablePair<String, String> mutablePair;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpMutablePairInstance() {
|
||||
mutablePair = new MutablePair<>("leftElement", "rightElement");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMutablePairInstance_whenCalledgetLeft_thenCorrect() {
|
||||
assertThat(mutablePair.getLeft()).isEqualTo("leftElement");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMutablePairInstance_whenCalledgetRight_thenCorrect() {
|
||||
assertThat(mutablePair.getRight()).isEqualTo("rightElement");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMutablePairInstance_whenCalledsetLeft_thenCorrect() {
|
||||
mutablePair.setLeft("newLeftElement");
|
||||
assertThat(mutablePair.getLeft()).isEqualTo("newLeftElement");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NumberUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalledcompareWithIntegers_thenCorrect() {
|
||||
assertThat(NumberUtils.compare(1, 1)).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalledcompareWithLongs_thenCorrect() {
|
||||
assertThat(NumberUtils.compare(1L, 1L)).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalledcreateNumber_thenCorrect() {
|
||||
assertThat(NumberUtils.createNumber("123456")).isEqualTo(123456);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalledisDigits_thenCorrect() {
|
||||
assertThat(NumberUtils.isDigits("123456")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCallemaxwithIntegerArray_thenCorrect() {
|
||||
int[] array = {1, 2, 3, 4, 5, 6};
|
||||
assertThat(NumberUtils.max(array)).isEqualTo(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalleminwithIntegerArray_thenCorrect() {
|
||||
int[] array = {1, 2, 3, 4, 5, 6};
|
||||
assertThat(NumberUtils.min(array)).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalleminwithByteArray_thenCorrect() {
|
||||
byte[] array = {1, 2, 3, 4, 5, 6};
|
||||
assertThat(NumberUtils.min(array)).isEqualTo((byte) 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStringUtilsClass_whenCalledisBlank_thenCorrect() {
|
||||
assertThat(StringUtils.isBlank(" ")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringUtilsClass_whenCalledisEmpty_thenCorrect() {
|
||||
assertThat(StringUtils.isEmpty("")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringUtilsClass_whenCalledisAllLowerCase_thenCorrect() {
|
||||
assertThat(StringUtils.isAllLowerCase("abd")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringUtilsClass_whenCalledisAllUpperCase_thenCorrect() {
|
||||
assertThat(StringUtils.isAllUpperCase("ABC")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringUtilsClass_whenCalledisMixedCase_thenCorrect() {
|
||||
assertThat(StringUtils.isMixedCase("abC")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringUtilsClass_whenCalledisAlpha_thenCorrect() {
|
||||
assertThat(StringUtils.isAlpha("abc")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringUtilsClass_whenCalledisAlphanumeric_thenCorrect() {
|
||||
assertThat(StringUtils.isAlphanumeric("abc123")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringUtilsClass_whenCalledcontains_thenCorrect() {
|
||||
assertThat(StringUtils.contains("abc", "ab")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringUtilsClass_whenCalledcontainsAny_thenCorrect() {
|
||||
assertThat(StringUtils.containsAny("abc", 'a', 'b', 'c')).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringUtilsClass_whenCalledcontainsIgnoreCase_thenCorrect() {
|
||||
assertThat(StringUtils.containsIgnoreCase("abc", "ABC")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringUtilsClass_whenCalledswapCase_thenCorrect() {
|
||||
assertThat(StringUtils.swapCase("abc")).isEqualTo("ABC");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringUtilsClass_whenCalledreverse_thenCorrect() {
|
||||
assertThat(StringUtils.reverse("abc")).isEqualTo("cba");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringUtilsClass_whenCalleddifference_thenCorrect() {
|
||||
assertThat(StringUtils.difference("abc", "abd")).isEqualTo("d");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import java.io.File;
|
||||
import org.apache.commons.lang3.JavaVersion;
|
||||
import org.apache.commons.lang3.SystemUtils;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SystemsUtilsManualTest {
|
||||
|
||||
// the paths depend on the OS and installed version of Java
|
||||
|
||||
@Test
|
||||
public void givenSystemUtilsClass_whenCalledgetJavaHome_thenCorrect() {
|
||||
assertThat(SystemUtils.getJavaHome()).isEqualTo(new File("/usr/lib/jvm/java-8-oracle/jre"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSystemUtilsClass_whenCalledgetUserHome_thenCorrect() {
|
||||
assertThat(SystemUtils.getUserHome()).isEqualTo(new File("/home/travis"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSystemUtilsClass_whenCalledisJavaVersionAtLeast_thenCorrect() {
|
||||
assertThat(SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_RECENT)).isTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.commons.lang3.test;
|
||||
|
||||
import org.apache.commons.lang3.tuple.Triple;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TripleUnitTest {
|
||||
|
||||
private static Triple<String, String, String> triple;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpTripleInstance() {
|
||||
triple = Triple.of("leftElement", "middleElement", "rightElement");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTripleInstance_whenCalledgetLeft_thenCorrect() {
|
||||
assertThat(triple.getLeft()).isEqualTo("leftElement");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTripleInstance_whenCalledgetMiddle_thenCorrect() {
|
||||
assertThat(triple.getMiddle()).isEqualTo("middleElement");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTripleInstance_whenCalledgetRight_thenCorrect() {
|
||||
assertThat(triple.getRight()).isEqualTo("rightElement");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.commons.math;
|
||||
|
||||
import org.apache.commons.math3.complex.Complex;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ComplexUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenComplexPow_thenCorrect() {
|
||||
Complex first = new Complex(1.0, 3.0);
|
||||
Complex second = new Complex(2.0, 5.0);
|
||||
|
||||
Complex power = first.pow(second);
|
||||
|
||||
Assert.assertEquals(-0.007563724861696302, power.getReal(), 1e-7);
|
||||
Assert.assertEquals(0.01786136835085382, power.getImaginary(), 1e-7);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.commons.math;
|
||||
|
||||
import org.apache.commons.math3.fraction.Fraction;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FractionUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenFractionAdd_thenCorrect() {
|
||||
Fraction lhs = new Fraction(1, 3);
|
||||
Fraction rhs = new Fraction(2, 5);
|
||||
Fraction sum = lhs.add(rhs);
|
||||
|
||||
Assert.assertEquals(11, sum.getNumerator());
|
||||
Assert.assertEquals(15, sum.getDenominator());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.commons.math;
|
||||
|
||||
import org.apache.commons.math3.geometry.euclidean.twod.Line;
|
||||
import org.apache.commons.math3.geometry.euclidean.twod.Vector2D;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GeometryUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenLineIntersection_thenCorrect() {
|
||||
Line l1 = new Line(new Vector2D(0, 0), new Vector2D(1, 1), 0);
|
||||
Line l2 = new Line(new Vector2D(0, 1), new Vector2D(1, 1.5), 0);
|
||||
|
||||
Vector2D intersection = l1.intersection(l2);
|
||||
|
||||
Assert.assertEquals(2, intersection.getX(), 1e-7);
|
||||
Assert.assertEquals(2, intersection.getY(), 1e-7);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.commons.math;
|
||||
|
||||
import org.apache.commons.math3.linear.*;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LinearAlgebraUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenDecompositionSolverSolve_thenCorrect() {
|
||||
RealMatrix a = new Array2DRowRealMatrix(new double[][] { { 2, 3, -2 }, { -1, 7, 6 }, { 4, -3, -5 } }, false);
|
||||
RealVector b = new ArrayRealVector(new double[] { 1, -2, 1 }, false);
|
||||
|
||||
DecompositionSolver solver = new LUDecomposition(a).getSolver();
|
||||
|
||||
RealVector solution = solver.solve(b);
|
||||
|
||||
Assert.assertEquals(-0.3698630137, solution.getEntry(0), 1e-7);
|
||||
Assert.assertEquals(0.1780821918, solution.getEntry(1), 1e-7);
|
||||
Assert.assertEquals(-0.602739726, solution.getEntry(2), 1e-7);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.commons.math;
|
||||
|
||||
import org.apache.commons.math3.distribution.NormalDistribution;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ProbabilitiesUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenNormalDistributionSample_thenSuccess() {
|
||||
final NormalDistribution normalDistribution = new NormalDistribution(10, 3);
|
||||
|
||||
System.out.println(normalDistribution.sample());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.commons.math;
|
||||
|
||||
import org.apache.commons.math3.analysis.UnivariateFunction;
|
||||
import org.apache.commons.math3.analysis.solvers.BracketingNthOrderBrentSolver;
|
||||
import org.apache.commons.math3.analysis.solvers.UnivariateSolver;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class RootFindingUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUnivariateSolverSolver_thenCorrect() {
|
||||
final UnivariateFunction function = v -> Math.pow(v, 2) - 2;
|
||||
UnivariateSolver solver = new BracketingNthOrderBrentSolver(1.0e-12, 1.0e-8, 5);
|
||||
double c = solver.solve(100, function, -10.0, 10.0, 0);
|
||||
|
||||
Assert.assertEquals(-Math.sqrt(2), c, 1e-7);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.commons.math;
|
||||
|
||||
import org.apache.commons.math3.analysis.UnivariateFunction;
|
||||
import org.apache.commons.math3.analysis.integration.SimpsonIntegrator;
|
||||
import org.apache.commons.math3.analysis.integration.UnivariateIntegrator;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SimpsonIntegratorUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUnivariateIntegratorIntegrate_thenCorrect() {
|
||||
final UnivariateFunction function = v -> v;
|
||||
final UnivariateIntegrator integrator = new SimpsonIntegrator(1.0e-12, 1.0e-8, 1, 32);
|
||||
|
||||
final double i = integrator.integrate(100, function, 0, 10);
|
||||
|
||||
Assert.assertEquals(16 + 2d / 3d, i, 1e-7);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.commons.math;
|
||||
|
||||
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StatisticsUnitTest {
|
||||
|
||||
private double[] values;
|
||||
private DescriptiveStatistics descriptiveStatistics;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
values = new double[] { 65, 51, 16, 11, 6519, 191, 0, 98, 19854, 1, 32 };
|
||||
|
||||
descriptiveStatistics = new DescriptiveStatistics();
|
||||
for (double v : values) {
|
||||
descriptiveStatistics.addValue(v);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDescriptiveStatisticsGetMean_thenCorrect() {
|
||||
Assert.assertEquals(2439.8181818181815, descriptiveStatistics.getMean(), 1e-7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDescriptiveStatisticsGetMedian_thenCorrect() {
|
||||
Assert.assertEquals(51, descriptiveStatistics.getPercentile(50), 1e-7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDescriptiveStatisticsGetStandardDeviation_thenCorrect() {
|
||||
Assert.assertEquals(6093.054649651221, descriptiveStatistics.getStandardDeviation(), 1e-7);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.ftp;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockftpserver.fake.FakeFtpServer;
|
||||
import org.mockftpserver.fake.UserAccount;
|
||||
import org.mockftpserver.fake.filesystem.DirectoryEntry;
|
||||
import org.mockftpserver.fake.filesystem.FileEntry;
|
||||
import org.mockftpserver.fake.filesystem.FileSystem;
|
||||
import org.mockftpserver.fake.filesystem.UnixFakeFileSystem;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.Collection;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class FtpClientIntegrationTest {
|
||||
|
||||
private FakeFtpServer fakeFtpServer;
|
||||
|
||||
private FtpClient ftpClient;
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException {
|
||||
fakeFtpServer = new FakeFtpServer();
|
||||
fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data"));
|
||||
|
||||
FileSystem fileSystem = new UnixFakeFileSystem();
|
||||
fileSystem.add(new DirectoryEntry("/data"));
|
||||
fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890"));
|
||||
fakeFtpServer.setFileSystem(fileSystem);
|
||||
fakeFtpServer.setServerControlPort(0);
|
||||
|
||||
fakeFtpServer.start();
|
||||
|
||||
ftpClient = new FtpClient("localhost", fakeFtpServer.getServerControlPort(), "user", "password");
|
||||
ftpClient.open();
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() throws IOException {
|
||||
ftpClient.close();
|
||||
fakeFtpServer.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRemoteFile_whenListingRemoteFiles_thenItIsContainedInList() throws IOException {
|
||||
Collection<String> files = ftpClient.listFiles("");
|
||||
|
||||
assertThat(files).contains("foobar.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException {
|
||||
ftpClient.downloadFile("/foobar.txt", "downloaded_buz.txt");
|
||||
|
||||
assertThat(new File("downloaded_buz.txt")).exists();
|
||||
new File("downloaded_buz.txt").delete(); // cleanup
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalFile_whenUploadingIt_thenItExistsOnRemoteLocation() throws URISyntaxException, IOException {
|
||||
File file = new File(getClass().getClassLoader().getResource("ftp/baz.txt").toURI());
|
||||
|
||||
ftpClient.putFileToPath(file, "/buz.txt");
|
||||
|
||||
assertThat(fakeFtpServer.getFileSystem().exists("/buz.txt")).isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.ftp;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockftpserver.fake.FakeFtpServer;
|
||||
import org.mockftpserver.fake.UserAccount;
|
||||
import org.mockftpserver.fake.filesystem.DirectoryEntry;
|
||||
import org.mockftpserver.fake.filesystem.FileEntry;
|
||||
import org.mockftpserver.fake.filesystem.FileSystem;
|
||||
import org.mockftpserver.fake.filesystem.UnixFakeFileSystem;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Collection;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class JdkFtpClientIntegrationTest {
|
||||
|
||||
private FakeFtpServer fakeFtpServer;
|
||||
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException {
|
||||
fakeFtpServer = new FakeFtpServer();
|
||||
fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data"));
|
||||
|
||||
FileSystem fileSystem = new UnixFakeFileSystem();
|
||||
fileSystem.add(new DirectoryEntry("/data"));
|
||||
fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890"));
|
||||
fakeFtpServer.setFileSystem(fileSystem);
|
||||
fakeFtpServer.setServerControlPort(0);
|
||||
|
||||
fakeFtpServer.start();
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() throws IOException {
|
||||
fakeFtpServer.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException {
|
||||
String ftpUrl = String.format("ftp://user:password@localhost:%d/foobar.txt", fakeFtpServer.getServerControlPort());
|
||||
|
||||
URLConnection urlConnection = new URL(ftpUrl).openConnection();
|
||||
InputStream inputStream = urlConnection.getInputStream();
|
||||
Files.copy(inputStream, new File("downloaded_buz.txt").toPath());
|
||||
inputStream.close();
|
||||
|
||||
assertThat(new File("downloaded_buz.txt")).exists();
|
||||
|
||||
new File("downloaded_buz.txt").delete(); // cleanup
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.text;
|
||||
|
||||
import org.apache.commons.text.diff.EditScript;
|
||||
import org.apache.commons.text.diff.StringsComparator;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DiffUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenEditScript_thenCorrect() {
|
||||
StringsComparator cmp = new StringsComparator("ABCFGH", "BCDEFG");
|
||||
EditScript<Character> script = cmp.getScript();
|
||||
int mod = script.getModifications();
|
||||
|
||||
Assert.assertEquals(4, mod);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.text;
|
||||
|
||||
import org.apache.commons.text.similarity.LongestCommonSubsequence;
|
||||
import org.apache.commons.text.similarity.LongestCommonSubsequenceDistance;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LongestCommonSubsequenceUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCompare_thenCorrect() {
|
||||
LongestCommonSubsequence lcs = new LongestCommonSubsequence();
|
||||
int countLcs = lcs.apply("New York", "New Hampshire");
|
||||
|
||||
Assert.assertEquals(5, countLcs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculateDistance_thenCorrect() {
|
||||
LongestCommonSubsequenceDistance lcsd = new LongestCommonSubsequenceDistance();
|
||||
int countLcsd = lcsd.apply("New York", "New Hampshire");
|
||||
|
||||
Assert.assertEquals(11, countLcsd);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.text;
|
||||
|
||||
import org.apache.commons.text.StrBuilder;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StrBuilderUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReplaced_thenCorrect() {
|
||||
StrBuilder strBuilder = new StrBuilder("example StrBuilder!");
|
||||
strBuilder.replaceAll("example", "new");
|
||||
|
||||
Assert.assertEquals(new StrBuilder("new StrBuilder!"), strBuilder);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCleared_thenEmpty() {
|
||||
StrBuilder strBuilder = new StrBuilder("example StrBuilder!");
|
||||
strBuilder.clear();
|
||||
|
||||
Assert.assertEquals(new StrBuilder(""), strBuilder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.text;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.text.StrSubstitutor;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StrSubstitutorUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenSubstituted_thenCorrect() {
|
||||
Map<String, String> substitutes = new HashMap<>();
|
||||
substitutes.put("name", "John");
|
||||
substitutes.put("college", "University of Stanford");
|
||||
String templateString = "My name is ${name} and I am a student at the ${college}.";
|
||||
StrSubstitutor sub = new StrSubstitutor(substitutes);
|
||||
String result = sub.replace(templateString);
|
||||
|
||||
Assert.assertEquals("My name is John and I am a student at the University of Stanford.", result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.text;
|
||||
|
||||
import org.apache.commons.text.translate.UnicodeEscaper;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UnicodeEscaperUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenTranslate_thenCorrect() {
|
||||
UnicodeEscaper ue = UnicodeEscaper.above(0);
|
||||
String result = ue.translate("ABCD");
|
||||
|
||||
Assert.assertEquals("\\u0041\\u0042\\u0043\\u0044", result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.text;
|
||||
|
||||
import org.apache.commons.text.WordUtils;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class WordUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCapitalized_thenCorrect() {
|
||||
String toBeCapitalized = "to be capitalized!";
|
||||
String result = WordUtils.capitalize(toBeCapitalized);
|
||||
|
||||
Assert.assertEquals("To Be Capitalized!", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenContainsWords_thenCorrect() {
|
||||
boolean containsWords = WordUtils.containsAllWords("String to search", "to", "search");
|
||||
|
||||
Assert.assertTrue(containsWords);
|
||||
}
|
||||
}
|
||||
1
libraries-apache-commons/src/test/resources/aaa.txt
Normal file
1
libraries-apache-commons/src/test/resources/aaa.txt
Normal file
@@ -0,0 +1 @@
|
||||
Hello World from aaa.txt!!!
|
||||
3
libraries-apache-commons/src/test/resources/book.csv
Normal file
3
libraries-apache-commons/src/test/resources/book.csv
Normal file
@@ -0,0 +1,3 @@
|
||||
author,title
|
||||
Dan Simmons,Hyperion
|
||||
Douglas Adams,The Hitchhiker's Guide to the Galaxy
|
||||
|
43
libraries-apache-commons/src/test/resources/employees.sql
Normal file
43
libraries-apache-commons/src/test/resources/employees.sql
Normal file
@@ -0,0 +1,43 @@
|
||||
CREATE TABLE employee(
|
||||
id int NOT NULL PRIMARY KEY auto_increment,
|
||||
firstname varchar(255),
|
||||
lastname varchar(255),
|
||||
salary double,
|
||||
hireddate date
|
||||
);
|
||||
|
||||
CREATE TABLE email(
|
||||
id int NOT NULL PRIMARY KEY auto_increment,
|
||||
employeeid int,
|
||||
address varchar(255)
|
||||
);
|
||||
|
||||
CREATE TABLE employee_legacy(
|
||||
id int NOT NULL PRIMARY KEY auto_increment,
|
||||
first_name varchar(255),
|
||||
last_name varchar(255),
|
||||
salary double,
|
||||
hired_date date
|
||||
);
|
||||
|
||||
|
||||
INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('John', 'Doe', 10000.10, to_date('01-01-2001','dd-mm-yyyy'));
|
||||
INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('Kevin', 'Smith', 20000.20, to_date('02-02-2002','dd-mm-yyyy'));
|
||||
INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('Kim', 'Smith', 30000.30, to_date('03-03-2003','dd-mm-yyyy'));
|
||||
INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('Stephen', 'Torvalds', 40000.40, to_date('04-04-2004','dd-mm-yyyy'));
|
||||
INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('Christian', 'Reynolds', 50000.50, to_date('05-05-2005','dd-mm-yyyy'));
|
||||
|
||||
INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('John', 'Doe', 10000.10, to_date('01-01-2001','dd-mm-yyyy'));
|
||||
INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('Kevin', 'Smith', 20000.20, to_date('02-02-2002','dd-mm-yyyy'));
|
||||
INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('Kim', 'Smith', 30000.30, to_date('03-03-2003','dd-mm-yyyy'));
|
||||
INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('Stephen', 'Torvalds', 40000.40, to_date('04-04-2004','dd-mm-yyyy'));
|
||||
INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('Christian', 'Reynolds', 50000.50, to_date('05-05-2005','dd-mm-yyyy'));
|
||||
|
||||
INSERT INTO email (employeeid,address) VALUES (1, 'john@baeldung.com');
|
||||
INSERT INTO email (employeeid,address) VALUES (1, 'john@gmail.com');
|
||||
INSERT INTO email (employeeid,address) VALUES (2, 'kevin@baeldung.com');
|
||||
INSERT INTO email (employeeid,address) VALUES (3, 'kim@baeldung.com');
|
||||
INSERT INTO email (employeeid,address) VALUES (3, 'kim@gmail.com');
|
||||
INSERT INTO email (employeeid,address) VALUES (3, 'kim@outlook.com');
|
||||
INSERT INTO email (employeeid,address) VALUES (4, 'stephen@baeldung.com');
|
||||
INSERT INTO email (employeeid,address) VALUES (5, 'christian@gmail.com');
|
||||
1
libraries-apache-commons/src/test/resources/fileTest.txt
Normal file
1
libraries-apache-commons/src/test/resources/fileTest.txt
Normal file
@@ -0,0 +1 @@
|
||||
Hello World from fileTest.txt!!!
|
||||
2
libraries-apache-commons/src/test/resources/sample.txt
Normal file
2
libraries-apache-commons/src/test/resources/sample.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
line 1
|
||||
a second line
|
||||
Reference in New Issue
Block a user