Merge branch 'master' of https://github.com/ahmedtawila/tutorials
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.bytebuddy;
|
||||
|
||||
import net.bytebuddy.implementation.bind.annotation.BindingPriority;
|
||||
|
||||
public class Bar {
|
||||
|
||||
@BindingPriority(3)
|
||||
public static String sayHelloBar() { return "Holla in Bar!"; }
|
||||
|
||||
@BindingPriority(2)
|
||||
public static String sayBar() { return "bar"; }
|
||||
|
||||
public String bar() { return Bar.class.getSimpleName() + " - Bar"; }
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.bytebuddy;
|
||||
|
||||
public class Foo {
|
||||
|
||||
public String sayHelloFoo() { return "Hello in Foo!"; }
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.chronicle.queue;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import net.openhft.chronicle.Chronicle;
|
||||
import net.openhft.chronicle.ExcerptAppender;
|
||||
|
||||
public class ChronicleQueue {
|
||||
|
||||
public static void writeToQueue(
|
||||
Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue)
|
||||
throws IOException {
|
||||
ExcerptAppender appender = chronicle.createAppender();
|
||||
appender.startExcerpt();
|
||||
appender.writeUTF(stringValue);
|
||||
appender.writeInt(intValue);
|
||||
appender.writeLong(longValue);
|
||||
appender.writeDouble(doubleValue);
|
||||
appender.finish();
|
||||
appender.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,38 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,11 @@ import org.eclipse.jetty.server.ServerConnector;
|
||||
import org.eclipse.jetty.servlet.ServletHandler;
|
||||
import org.eclipse.jetty.util.thread.QueuedThreadPool;
|
||||
|
||||
public class JettyServer {
|
||||
class JettyServer {
|
||||
|
||||
private Server server;
|
||||
|
||||
public void start() throws Exception {
|
||||
void start() throws Exception {
|
||||
|
||||
int maxThreads = 100;
|
||||
int minThreads = 10;
|
||||
@@ -33,7 +33,7 @@ public class JettyServer {
|
||||
|
||||
}
|
||||
|
||||
public void stop() throws Exception {
|
||||
void stop() throws Exception {
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package com.baeldung.junitparams;
|
||||
|
||||
public class SafeAdditionUtil {
|
||||
class SafeAdditionUtil {
|
||||
|
||||
public int safeAdd(int a, int b) {
|
||||
int safeAdd(int a, int b) {
|
||||
long result = ((long) a) + b;
|
||||
if (result > Integer.MAX_VALUE) {
|
||||
return Integer.MAX_VALUE;
|
||||
|
||||
@@ -13,7 +13,7 @@ public class NettyServer {
|
||||
|
||||
private int port;
|
||||
|
||||
public NettyServer(int port) {
|
||||
private NettyServer(int port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ public class NettyServer {
|
||||
new NettyServer(port).run();
|
||||
}
|
||||
|
||||
public void run() throws Exception {
|
||||
private void run() throws Exception {
|
||||
EventLoopGroup bossGroup = new NioEventLoopGroup();
|
||||
EventLoopGroup workerGroup = new NioEventLoopGroup();
|
||||
try {
|
||||
|
||||
@@ -4,27 +4,27 @@ public class RequestData {
|
||||
private int intValue;
|
||||
private String stringValue;
|
||||
|
||||
public int getIntValue() {
|
||||
int getIntValue() {
|
||||
return intValue;
|
||||
}
|
||||
|
||||
public void setIntValue(int intValue) {
|
||||
void setIntValue(int intValue) {
|
||||
this.intValue = intValue;
|
||||
}
|
||||
|
||||
public String getStringValue() {
|
||||
String getStringValue() {
|
||||
return stringValue;
|
||||
}
|
||||
|
||||
public void setStringValue(String stringValue) {
|
||||
void setStringValue(String stringValue) {
|
||||
this.stringValue = stringValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "RequestData{" +
|
||||
"intValue=" + intValue +
|
||||
", stringValue='" + stringValue + '\'' +
|
||||
'}';
|
||||
"intValue=" + intValue +
|
||||
", stringValue='" + stringValue + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,11 +3,11 @@ package com.baeldung.netty;
|
||||
public class ResponseData {
|
||||
private int intValue;
|
||||
|
||||
public int getIntValue() {
|
||||
int getIntValue() {
|
||||
return intValue;
|
||||
}
|
||||
|
||||
public void setIntValue(int intValue) {
|
||||
void setIntValue(int intValue) {
|
||||
this.intValue = intValue;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package com.baeldung.netty;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.handler.codec.ReplayingDecoder;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ResponseDataDecoder extends ReplayingDecoder<ResponseData> {
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.neuroph;
|
||||
|
||||
import org.neuroph.core.Layer;
|
||||
import org.neuroph.core.NeuralNetwork;
|
||||
import org.neuroph.core.Neuron;
|
||||
import org.neuroph.core.data.DataSet;
|
||||
import org.neuroph.core.data.DataSetRow;
|
||||
import org.neuroph.nnet.learning.BackPropagation;
|
||||
import org.neuroph.util.ConnectionFactory;
|
||||
import org.neuroph.util.NeuralNetworkType;
|
||||
|
||||
public class NeurophXOR {
|
||||
|
||||
public static NeuralNetwork assembleNeuralNetwork() {
|
||||
|
||||
Layer inputLayer = new Layer();
|
||||
inputLayer.addNeuron(new Neuron());
|
||||
inputLayer.addNeuron(new Neuron());
|
||||
|
||||
Layer hiddenLayerOne = new Layer();
|
||||
hiddenLayerOne.addNeuron(new Neuron());
|
||||
hiddenLayerOne.addNeuron(new Neuron());
|
||||
hiddenLayerOne.addNeuron(new Neuron());
|
||||
hiddenLayerOne.addNeuron(new Neuron());
|
||||
|
||||
Layer hiddenLayerTwo = new Layer();
|
||||
hiddenLayerTwo.addNeuron(new Neuron());
|
||||
hiddenLayerTwo.addNeuron(new Neuron());
|
||||
hiddenLayerTwo.addNeuron(new Neuron());
|
||||
hiddenLayerTwo.addNeuron(new Neuron());
|
||||
|
||||
Layer outputLayer = new Layer();
|
||||
outputLayer.addNeuron(new Neuron());
|
||||
|
||||
NeuralNetwork ann = new NeuralNetwork();
|
||||
|
||||
ann.addLayer(0, inputLayer);
|
||||
ann.addLayer(1, hiddenLayerOne);
|
||||
ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(1));
|
||||
ann.addLayer(2, hiddenLayerTwo);
|
||||
ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2));
|
||||
ann.addLayer(3, outputLayer);
|
||||
ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3));
|
||||
ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount()-1), false);
|
||||
|
||||
ann.setInputNeurons(inputLayer.getNeurons());
|
||||
ann.setOutputNeurons(outputLayer.getNeurons());
|
||||
|
||||
ann.setNetworkType(NeuralNetworkType.MULTI_LAYER_PERCEPTRON);
|
||||
return ann;
|
||||
}
|
||||
|
||||
public static NeuralNetwork trainNeuralNetwork(NeuralNetwork ann) {
|
||||
int inputSize = 2;
|
||||
int outputSize = 1;
|
||||
DataSet ds = new DataSet(inputSize, outputSize);
|
||||
|
||||
DataSetRow rOne = new DataSetRow(new double[] {0, 1}, new double[] {1});
|
||||
ds.addRow(rOne);
|
||||
DataSetRow rTwo = new DataSetRow(new double[] {1, 1}, new double[] {0});
|
||||
ds.addRow(rTwo);
|
||||
DataSetRow rThree = new DataSetRow(new double[] {0, 0}, new double[] {0});
|
||||
ds.addRow(rThree);
|
||||
DataSetRow rFour = new DataSetRow(new double[] {1, 0}, new double[] {1});
|
||||
ds.addRow(rFour);
|
||||
|
||||
BackPropagation backPropagation = new BackPropagation();
|
||||
backPropagation.setMaxIterations(1000);
|
||||
|
||||
ann.learn(ds, backPropagation);
|
||||
return ann;
|
||||
}
|
||||
}
|
||||
@@ -20,44 +20,44 @@ public class QuartzExample {
|
||||
Scheduler sched = schedFact.getScheduler();
|
||||
|
||||
JobDetail job = JobBuilder.newJob(SimpleJob.class)
|
||||
.withIdentity("myJob", "group1")
|
||||
.usingJobData("jobSays", "Hello World!")
|
||||
.usingJobData("myFloatValue", 3.141f)
|
||||
.build();
|
||||
.withIdentity("myJob", "group1")
|
||||
.usingJobData("jobSays", "Hello World!")
|
||||
.usingJobData("myFloatValue", 3.141f)
|
||||
.build();
|
||||
|
||||
Trigger trigger = TriggerBuilder.newTrigger()
|
||||
.withIdentity("myTrigger", "group1")
|
||||
.startNow()
|
||||
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
|
||||
.withIntervalInSeconds(40)
|
||||
.repeatForever())
|
||||
.build();
|
||||
|
||||
.withIdentity("myTrigger", "group1")
|
||||
.startNow()
|
||||
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
|
||||
.withIntervalInSeconds(40)
|
||||
.repeatForever())
|
||||
.build();
|
||||
|
||||
JobDetail jobA = JobBuilder.newJob(JobA.class)
|
||||
.withIdentity("jobA", "group2")
|
||||
.build();
|
||||
|
||||
.withIdentity("jobA", "group2")
|
||||
.build();
|
||||
|
||||
JobDetail jobB = JobBuilder.newJob(JobB.class)
|
||||
.withIdentity("jobB", "group2")
|
||||
.build();
|
||||
|
||||
.withIdentity("jobB", "group2")
|
||||
.build();
|
||||
|
||||
Trigger triggerA = TriggerBuilder.newTrigger()
|
||||
.withIdentity("triggerA", "group2")
|
||||
.startNow()
|
||||
.withPriority(15)
|
||||
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
|
||||
.withIntervalInSeconds(40)
|
||||
.repeatForever())
|
||||
.build();
|
||||
|
||||
Trigger triggerB = TriggerBuilder.newTrigger()
|
||||
.withIdentity("triggerB", "group2")
|
||||
.startNow()
|
||||
.withPriority(10)
|
||||
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
|
||||
.withIntervalInSeconds(20)
|
||||
.repeatForever())
|
||||
.build();
|
||||
.withIdentity("triggerA", "group2")
|
||||
.startNow()
|
||||
.withPriority(15)
|
||||
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
|
||||
.withIntervalInSeconds(40)
|
||||
.repeatForever())
|
||||
.build();
|
||||
|
||||
Trigger triggerB = TriggerBuilder.newTrigger()
|
||||
.withIdentity("triggerB", "group2")
|
||||
.startNow()
|
||||
.withPriority(10)
|
||||
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
|
||||
.withIntervalInSeconds(20)
|
||||
.repeatForever())
|
||||
.build();
|
||||
|
||||
sched.scheduleJob(job, trigger);
|
||||
sched.scheduleJob(jobA, triggerA);
|
||||
|
||||
@@ -9,13 +9,11 @@ public class SimpleJob implements Job {
|
||||
|
||||
public void execute(JobExecutionContext context) throws JobExecutionException {
|
||||
JobDataMap dataMap = context.getJobDetail()
|
||||
.getJobDataMap();
|
||||
.getJobDataMap();
|
||||
|
||||
String jobSays = dataMap.getString("jobSays");
|
||||
float myFloatValue = dataMap.getFloat("myFloatValue");
|
||||
|
||||
System.out.println("Job says: " + jobSays + ", and val is: " + myFloatValue);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,20 +10,20 @@ public class Account {
|
||||
private final TxnLong lastUpdate;
|
||||
private final TxnInteger balance;
|
||||
|
||||
public Account(final int balance) {
|
||||
Account(final int balance) {
|
||||
this.lastUpdate = StmUtils.newTxnLong(System.currentTimeMillis());
|
||||
this.balance = StmUtils.newTxnInteger(balance);
|
||||
}
|
||||
|
||||
public Integer getBalance() {
|
||||
Integer getBalance() {
|
||||
return balance.atomicGet();
|
||||
}
|
||||
|
||||
public void adjustBy(final int amount) {
|
||||
void adjustBy(final int amount) {
|
||||
adjustBy(amount, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public void adjustBy(final int amount, final long date) {
|
||||
private void adjustBy(final int amount, final long date) {
|
||||
StmUtils.atomic(() -> {
|
||||
balance.increment(amount);
|
||||
lastUpdate.set(date);
|
||||
@@ -34,7 +34,7 @@ public class Account {
|
||||
});
|
||||
}
|
||||
|
||||
public void transferTo(final Account other, final int amount) {
|
||||
void transferTo(final Account other, final int amount) {
|
||||
StmUtils.atomic(() -> {
|
||||
final long date = System.currentTimeMillis();
|
||||
adjustBy(-amount, date);
|
||||
@@ -45,6 +45,6 @@ public class Account {
|
||||
@Override
|
||||
public String toString() {
|
||||
return StmUtils.atomic((TxnCallable<String>)
|
||||
txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn));
|
||||
txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn));
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package com.baeldung.zip;
|
||||
|
||||
import com.google.common.collect.Streams;
|
||||
import org.jooq.lambda.Seq;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class ZipCollectionExample {
|
||||
static List<String> names = Arrays.asList("John", "Jane", "Jack", "Dennis");
|
||||
|
||||
static List<Integer> ages = Arrays.asList(24, 25, 27);
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Using Streams API from Guava 21
|
||||
Streams
|
||||
.zip(names.stream(), ages.stream(), (name, age) -> name + ":" + age)
|
||||
.forEach(System.out::println);
|
||||
|
||||
// Using native Java 8 Int Stream
|
||||
IntStream
|
||||
.range(0, Math.min(names.size(), ages.size()))
|
||||
.mapToObj(i -> names.get(i) + ":" + ages.get(i))
|
||||
.forEach(System.out::println);
|
||||
|
||||
// Using jOOL
|
||||
Seq
|
||||
.of("John", "Jane", "Dennis")
|
||||
.zip(Seq.of(24, 25, 27));
|
||||
|
||||
Seq
|
||||
.of("John", "Jane", "Dennis")
|
||||
.zip(Seq.of(24, 25, 27), (x, y) -> x + ":" + y);
|
||||
|
||||
Seq
|
||||
.of("a", "b", "c")
|
||||
.zipWithIndex();
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package com.baeldung.awaitility;
|
||||
import org.awaitility.Awaitility;
|
||||
import org.awaitility.Duration;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.baeldung.bytebuddy;
|
||||
|
||||
import net.bytebuddy.ByteBuddy;
|
||||
import net.bytebuddy.agent.ByteBuddyAgent;
|
||||
import net.bytebuddy.dynamic.DynamicType;
|
||||
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
|
||||
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
|
||||
import net.bytebuddy.implementation.FixedValue;
|
||||
import net.bytebuddy.implementation.MethodDelegation;
|
||||
import net.bytebuddy.matcher.ElementMatchers;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
|
||||
import static net.bytebuddy.matcher.ElementMatchers.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class ByteBuddyUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException {
|
||||
DynamicType.Unloaded unloadedType = new ByteBuddy()
|
||||
.subclass(Object.class)
|
||||
.method(ElementMatchers.isToString())
|
||||
.intercept(FixedValue.value("Hello World ByteBuddy!"))
|
||||
.make();
|
||||
|
||||
Class<?> dynamicType = unloadedType.load(getClass().getClassLoader())
|
||||
.getLoaded();
|
||||
|
||||
assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception {
|
||||
ByteBuddyAgent.install();
|
||||
new ByteBuddy()
|
||||
.redefine(Foo.class)
|
||||
.method(named("sayHelloFoo"))
|
||||
.intercept(FixedValue.value("Hello Foo Redefined"))
|
||||
.make()
|
||||
.load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
|
||||
Foo f = new Foo();
|
||||
assertEquals(f.sayHelloFoo(), "Hello Foo Redefined");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException {
|
||||
|
||||
String r = new ByteBuddy()
|
||||
.subclass(Foo.class)
|
||||
.method(
|
||||
named("sayHelloFoo")
|
||||
.and(isDeclaredBy(Foo.class)
|
||||
.and(returns(String.class)))
|
||||
)
|
||||
.intercept(MethodDelegation.to(Bar.class))
|
||||
.make()
|
||||
.load(getClass().getClassLoader())
|
||||
.getLoaded()
|
||||
.newInstance()
|
||||
.sayHelloFoo();
|
||||
|
||||
assertEquals(r, Bar.sayHelloBar());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception {
|
||||
Class<?> type = new ByteBuddy()
|
||||
.subclass(Object.class)
|
||||
.name("MyClassName")
|
||||
.defineMethod("custom", String.class, Modifier.PUBLIC)
|
||||
.intercept(MethodDelegation.to(Bar.class))
|
||||
.defineField("x", String.class, Modifier.PUBLIC)
|
||||
.make()
|
||||
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
|
||||
.getLoaded();
|
||||
|
||||
Method m = type.getDeclaredMethod("custom", null);
|
||||
|
||||
assertEquals(m.invoke(type.newInstance()), Bar.sayHelloBar());
|
||||
assertNotNull(type.getDeclaredField("x"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -19,14 +19,14 @@ public class BeanGeneratorIntegrationTest {
|
||||
beanGenerator.addProperty("name", String.class);
|
||||
Object myBean = beanGenerator.create();
|
||||
Method setter = myBean
|
||||
.getClass()
|
||||
.getMethod("setName", String.class);
|
||||
.getClass()
|
||||
.getMethod("setName", String.class);
|
||||
setter.invoke(myBean, "some string value set by a cglib");
|
||||
|
||||
//then
|
||||
Method getter = myBean
|
||||
.getClass()
|
||||
.getMethod("getName");
|
||||
.getClass()
|
||||
.getMethod("getName");
|
||||
assertEquals("some string value set by a cglib", getter.invoke(myBean));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package com.baeldung.cglib.proxy;
|
||||
|
||||
import com.baeldung.cglib.mixin.*;
|
||||
import com.baeldung.cglib.mixin.Class1;
|
||||
import com.baeldung.cglib.mixin.Class2;
|
||||
import com.baeldung.cglib.mixin.Interface1;
|
||||
import com.baeldung.cglib.mixin.Interface2;
|
||||
import com.baeldung.cglib.mixin.MixinInterface;
|
||||
import net.sf.cglib.proxy.Mixin;
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -12,8 +16,8 @@ public class MixinUnitTest {
|
||||
public void givenTwoClasses_whenMixedIntoOne_thenMixinShouldHaveMethodsFromBothClasses() throws Exception {
|
||||
//when
|
||||
Mixin mixin = Mixin.create(
|
||||
new Class[]{Interface1.class, Interface2.class, MixinInterface.class},
|
||||
new Object[]{new Class1(), new Class2()}
|
||||
new Class[]{Interface1.class, Interface2.class, MixinInterface.class},
|
||||
new Object[]{new Class1(), new Class2()}
|
||||
);
|
||||
MixinInterface mixinDelegate = (MixinInterface) mixin;
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.chronicle.queue;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import net.openhft.chronicle.Chronicle;
|
||||
import net.openhft.chronicle.ChronicleQueueBuilder;
|
||||
import net.openhft.chronicle.ExcerptTailer;
|
||||
import net.openhft.chronicle.tools.ChronicleTools;
|
||||
|
||||
public class ChronicleQueueTest {
|
||||
|
||||
@Test
|
||||
public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException {
|
||||
File queueDir = Files.createTempDirectory("chronicle-queue").toFile();
|
||||
ChronicleTools.deleteOnExit(queueDir.getPath());
|
||||
|
||||
Chronicle chronicle = ChronicleQueueBuilder.indexed(queueDir).build();
|
||||
String stringVal = "Hello World";
|
||||
int intVal = 101;
|
||||
long longVal = System.currentTimeMillis();
|
||||
double doubleVal = 90.00192091d;
|
||||
|
||||
ChronicleQueue.writeToQueue(chronicle, stringVal, intVal, longVal, doubleVal);
|
||||
|
||||
ExcerptTailer tailer = chronicle.createTailer();
|
||||
while (tailer.nextIndex()) {
|
||||
assertEquals(stringVal, tailer.readUTF());
|
||||
assertEquals(intVal, tailer.readInt());
|
||||
assertEquals(longVal, tailer.readLong());
|
||||
assertEquals((Double) doubleVal, (Double) tailer.readDouble());
|
||||
}
|
||||
tailer.finish();
|
||||
tailer.close();
|
||||
chronicle.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 CircularFifoQueueTest {
|
||||
|
||||
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,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 AtmChainTest {
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,12 @@ package com.baeldung.commons.collections;
|
||||
|
||||
import org.apache.commons.collections4.BidiMap;
|
||||
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
|
||||
import org.apache.commons.collections4.bidimap.DualLinkedHashBidiMap;
|
||||
import org.apache.commons.collections4.bidimap.DualTreeBidiMap;
|
||||
import org.apache.commons.collections4.bidimap.TreeBidiMap;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* Created by smatt on 03/07/2017.
|
||||
*/
|
||||
public class BidiMapUnitTest {
|
||||
|
||||
@Test
|
||||
|
||||
+19
-16
@@ -3,14 +3,17 @@ package com.baeldung.commons.collections;
|
||||
|
||||
import com.baeldung.commons.collectionutil.Address;
|
||||
import com.baeldung.commons.collectionutil.Customer;
|
||||
import org.apache.commons.collections4.Closure;
|
||||
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.*;
|
||||
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;
|
||||
@@ -36,13 +39,13 @@ public class CollectionUtilsGuideTest {
|
||||
|
||||
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);
|
||||
@@ -51,7 +54,7 @@ public class CollectionUtilsGuideTest {
|
||||
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>() {
|
||||
@@ -59,61 +62,61 @@ public class CollectionUtilsGuideTest {
|
||||
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());
|
||||
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,132 @@
|
||||
package com.baeldung.commons.collections;
|
||||
|
||||
import org.apache.commons.collections4.MapIterator;
|
||||
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.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
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;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class MapUtilsTest {
|
||||
|
||||
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)));
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,6 @@ import java.util.Set;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* Created by smatt on 21/06/2017.
|
||||
*/
|
||||
public class SetUtilsUnitTest {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
@@ -27,33 +24,33 @@ public class SetUtilsUnitTest {
|
||||
|
||||
@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));
|
||||
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));
|
||||
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));
|
||||
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 );
|
||||
Set<Integer> a = SetUtils.transformedSet(new HashSet<>(), (e) -> e * 2);
|
||||
a.add(2);
|
||||
assertEquals(a.toArray()[0], 4);
|
||||
|
||||
@@ -65,19 +62,19 @@ public class SetUtilsUnitTest {
|
||||
|
||||
@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));
|
||||
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));
|
||||
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));
|
||||
orderedSet.addAll(Arrays.asList(10, 1, 5));
|
||||
System.out.println("ordered set = " + orderedSet);
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -1,10 +1,5 @@
|
||||
package com.baeldung.commons.collections.orderedmap;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.collections4.OrderedMap;
|
||||
import org.apache.commons.collections4.OrderedMapIterator;
|
||||
import org.apache.commons.collections4.map.LinkedMap;
|
||||
@@ -12,6 +7,11 @@ 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"};
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,9 +2,10 @@ 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.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class StringUtilsUnitTest {
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class HikariCPUnitTest {
|
||||
public class HikariCPIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenConnection_thenFetchDbData() {
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.hll;
|
||||
|
||||
|
||||
import com.google.common.hash.HashFunction;
|
||||
import com.google.common.hash.Hashing;
|
||||
import net.agkn.hll.HLL;
|
||||
import org.assertj.core.data.Offset;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.stream.LongStream;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
|
||||
|
||||
public class HLLUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() {
|
||||
//given
|
||||
long numberOfElements = 100_000_000;
|
||||
long toleratedDifference = 1_000_000;
|
||||
HashFunction hashFunction = Hashing.murmur3_128();
|
||||
HLL hll = new HLL(14, 5);
|
||||
|
||||
//when
|
||||
LongStream.range(0, numberOfElements).forEach(element -> {
|
||||
long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong();
|
||||
hll.addRaw(hashedValue);
|
||||
}
|
||||
);
|
||||
|
||||
//then
|
||||
long cardinality = hll.cardinality();
|
||||
assertThat(cardinality).isCloseTo(numberOfElements, Offset.offset(toleratedDifference));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoHLLs_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinalityForUnionOfHLLs() {
|
||||
//given
|
||||
long numberOfElements = 100_000_000;
|
||||
long toleratedDifference = 1_000_000;
|
||||
HashFunction hashFunction = Hashing.murmur3_128();
|
||||
HLL firstHll = new HLL(15, 5);
|
||||
HLL secondHLL = new HLL(15, 5);
|
||||
|
||||
//when
|
||||
LongStream.range(0, numberOfElements).forEach(element -> {
|
||||
long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong();
|
||||
firstHll.addRaw(hashedValue);
|
||||
}
|
||||
);
|
||||
|
||||
LongStream.range(numberOfElements, numberOfElements * 2).forEach(element -> {
|
||||
long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong();
|
||||
secondHLL.addRaw(hashedValue);
|
||||
}
|
||||
);
|
||||
|
||||
//then
|
||||
firstHll.union(secondHLL);
|
||||
long cardinality = firstHll.cardinality();
|
||||
assertThat(cardinality).isCloseTo(numberOfElements * 2, Offset.offset(toleratedDifference * 2));
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,9 @@ import org.jasypt.util.text.BasicTextEncryptor;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.Assert.*;
|
||||
import static junit.framework.Assert.assertFalse;
|
||||
import static junit.framework.Assert.assertNotSame;
|
||||
import static junit.framework.Assert.assertTrue;
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class JasyptUnitTest {
|
||||
@@ -30,7 +32,7 @@ public class JasyptUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTextPassword_whenOneWayEncryption_thenCompareEncryptedPasswordsShouldBeSame(){
|
||||
public void givenTextPassword_whenOneWayEncryption_thenCompareEncryptedPasswordsShouldBeSame() {
|
||||
String password = "secret-pass";
|
||||
BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
|
||||
String encryptedPassword = passwordEncryptor.encryptPassword(password);
|
||||
@@ -43,7 +45,7 @@ public class JasyptUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTextPassword_whenOneWayEncryption_thenCompareEncryptedPasswordsShouldNotBeSame(){
|
||||
public void givenTextPassword_whenOneWayEncryption_thenCompareEncryptedPasswordsShouldNotBeSame() {
|
||||
String password = "secret-pass";
|
||||
BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
|
||||
String encryptedPassword = passwordEncryptor.encryptPassword(password);
|
||||
@@ -56,7 +58,6 @@ public class JasyptUnitTest {
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
@Ignore("should have installed local_policy.jar")
|
||||
public void givenTextPrivateData_whenDecrypt_thenCompareToEncryptedWithCustomAlgorithm() {
|
||||
@@ -77,7 +78,7 @@ public class JasyptUnitTest {
|
||||
|
||||
@Test
|
||||
@Ignore("should have installed local_policy.jar")
|
||||
public void givenTextPrivateData_whenDecryptOnHighPerformance_thenDecrypt(){
|
||||
public void givenTextPrivateData_whenDecryptOnHighPerformance_thenDecrypt() {
|
||||
//given
|
||||
String privateData = "secret-data";
|
||||
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
|
||||
|
||||
@@ -8,7 +8,6 @@ import javax.jdo.PersistenceManager;
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
import javax.jdo.Query;
|
||||
import javax.jdo.Transaction;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.neuroph;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.neuroph.core.NeuralNetwork;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class XORTest {
|
||||
private NeuralNetwork ann = null;
|
||||
|
||||
@Before
|
||||
public void annInit() {
|
||||
ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void leftDisjunctTest() {
|
||||
ann.setInput(0, 1);
|
||||
ann.calculate();
|
||||
assertEquals(ann.getOutput()[0], 1.0,0.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rightDisjunctTest() {
|
||||
ann.setInput(1, 0);
|
||||
ann.calculate();
|
||||
assertEquals(ann.getOutput()[0], 1.0,0.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bothFalseConjunctTest() {
|
||||
ann.setInput(0, 0);
|
||||
ann.calculate();
|
||||
assertEquals(ann.getOutput()[0], 0.0,0.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bothTrueConjunctTest() {
|
||||
ann.setInput(1, 1);
|
||||
ann.calculate();
|
||||
assertEquals(ann.getOutput()[0], 0.0,0.0);
|
||||
}
|
||||
|
||||
@After
|
||||
public void annClose() {
|
||||
ann = null;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,11 @@ import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
|
||||
import au.com.dius.pact.model.RequestResponsePact;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -20,7 +24,7 @@ public class PactConsumerDrivenContractUnitTest {
|
||||
|
||||
@Rule
|
||||
public PactProviderRuleMk2 mockProvider
|
||||
= new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
|
||||
= new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
|
||||
|
||||
@Pact(consumer = "test_consumer")
|
||||
public RequestResponsePact createPact(PactDslWithProvider builder) {
|
||||
@@ -28,25 +32,25 @@ public class PactConsumerDrivenContractUnitTest {
|
||||
headers.put("Content-Type", "application/json");
|
||||
|
||||
return builder
|
||||
.given("test GET ")
|
||||
.uponReceiving("GET REQUEST")
|
||||
.path("/")
|
||||
.method("GET")
|
||||
.willRespondWith()
|
||||
.status(200)
|
||||
.headers(headers)
|
||||
.body("{\"condition\": true, \"name\": \"tom\"}")
|
||||
.given("test POST")
|
||||
.uponReceiving("POST REQUEST")
|
||||
.method("POST")
|
||||
.headers(headers)
|
||||
.body("{\"name\": \"Michael\"}")
|
||||
.path("/create")
|
||||
.willRespondWith()
|
||||
.status(201)
|
||||
.headers(headers)
|
||||
.body("")
|
||||
.toPact();
|
||||
.given("test GET ")
|
||||
.uponReceiving("GET REQUEST")
|
||||
.path("/")
|
||||
.method("GET")
|
||||
.willRespondWith()
|
||||
.status(200)
|
||||
.headers(headers)
|
||||
.body("{\"condition\": true, \"name\": \"tom\"}")
|
||||
.given("test POST")
|
||||
.uponReceiving("POST REQUEST")
|
||||
.method("POST")
|
||||
.headers(headers)
|
||||
.body("{\"name\": \"Michael\"}")
|
||||
.path("/create")
|
||||
.willRespondWith()
|
||||
.status(201)
|
||||
.headers(headers)
|
||||
.body("")
|
||||
.toPact();
|
||||
}
|
||||
|
||||
|
||||
@@ -55,7 +59,7 @@ public class PactConsumerDrivenContractUnitTest {
|
||||
public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
|
||||
//when
|
||||
ResponseEntity<String> response
|
||||
= new RestTemplate().getForEntity(mockProvider.getUrl(), String.class);
|
||||
= new RestTemplate().getForEntity(mockProvider.getUrl(), String.class);
|
||||
|
||||
//then
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(200);
|
||||
@@ -69,10 +73,10 @@ public class PactConsumerDrivenContractUnitTest {
|
||||
|
||||
//when
|
||||
ResponseEntity<String> postResponse = new RestTemplate().exchange(
|
||||
mockProvider.getUrl() + "/create",
|
||||
HttpMethod.POST,
|
||||
new HttpEntity<>(jsonBody, httpHeaders),
|
||||
String.class
|
||||
mockProvider.getUrl() + "/create",
|
||||
HttpMethod.POST,
|
||||
new HttpEntity<>(jsonBody, httpHeaders),
|
||||
String.class
|
||||
);
|
||||
|
||||
//then
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.baeldung.pcollections;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.pcollections.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PCollectionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenEmpty_thenCreateEmptyHashPMap() {
|
||||
HashPMap<String, String> pmap = HashTreePMap.empty();
|
||||
assertEquals(pmap.size(), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenKeyValue_whenSingleton_thenCreateNonEmptyHashPMap() {
|
||||
HashPMap<String, String> pmap1 = HashTreePMap.singleton("key1", "value1");
|
||||
assertEquals(pmap1.size(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingHashMap_whenFrom_thenCreateHashPMap() {
|
||||
Map map = new HashMap();
|
||||
map.put("mkey1", "mval1");
|
||||
map.put("mkey2", "mval2");
|
||||
|
||||
HashPMap<String, String> pmap2 = HashTreePMap.from(map);
|
||||
assertEquals(pmap2.size(), 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHashPMapMethods_thenPerformOperations() {
|
||||
|
||||
HashPMap<String, String> pmap = HashTreePMap.empty();
|
||||
HashPMap<String, String> pmap0 = pmap.plus("key1", "value1");
|
||||
|
||||
Map map = new HashMap();
|
||||
map.put("key2", "val2");
|
||||
map.put("key3", "val3");
|
||||
|
||||
HashPMap<String, String> pmap1 = pmap0.plusAll(map);
|
||||
HashPMap<String, String> pmap2 = pmap1.minus("key1");
|
||||
HashPMap<String, String> pmap3 = pmap2.minusAll(map.keySet());
|
||||
|
||||
assertEquals(pmap0.size(), 1);
|
||||
assertEquals(pmap1.size(), 3);
|
||||
assertFalse(pmap2.containsKey("key1"));
|
||||
assertEquals(pmap3.size(), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTreePVectorMethods_thenPerformOperations() {
|
||||
TreePVector pVector = TreePVector.empty();
|
||||
|
||||
TreePVector pV1 = pVector.plus("e1");
|
||||
TreePVector pV2 = pV1.plusAll(Arrays.asList("e2", "e3", "e4"));
|
||||
assertEquals(1, pV1.size());
|
||||
assertEquals(4, pV2.size());
|
||||
|
||||
TreePVector pV3 = pV2.minus("e1");
|
||||
TreePVector pV4 = pV3.minusAll(Arrays.asList("e2", "e3", "e4"));
|
||||
assertEquals(pV3.size(), 3);
|
||||
assertEquals(pV4.size(), 0);
|
||||
|
||||
TreePVector pSub = pV2.subList(0, 2);
|
||||
assertTrue(pSub.contains("e1") && pSub.contains("e2"));
|
||||
|
||||
TreePVector pVW = (TreePVector) pV2.with(0, "e10");
|
||||
assertEquals(pVW.get(0), "e10");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMapPSetMethods_thenPerformOperations() {
|
||||
|
||||
MapPSet pSet = HashTreePSet.empty()
|
||||
.plusAll(Arrays.asList("e1","e2","e3","e4"));
|
||||
assertEquals(pSet.size(), 4);
|
||||
|
||||
MapPSet pSet1 = pSet.minus("e4");
|
||||
assertFalse(pSet1.contains("e4"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -13,11 +13,11 @@ public class WordUtilsTest {
|
||||
|
||||
Assert.assertEquals("To Be Capitalized!", result);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenContainsWords_thenCorrect() {
|
||||
boolean containsWords = WordUtils.containsAllWords("String to search", "to", "search");
|
||||
|
||||
|
||||
Assert.assertTrue(containsWords);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
package com.baeldung.zip;
|
||||
|
||||
import com.google.common.collect.Streams;
|
||||
import org.jooq.lambda.Seq;
|
||||
import org.jooq.lambda.tuple.Tuple2;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ZipCollectionTest {
|
||||
|
||||
List<String> names;
|
||||
List<Integer> ages;
|
||||
List<String> expectedOutput;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
names = Arrays.asList("John", "Jane", "Jack", "Dennis");
|
||||
ages = Arrays.asList(24, 25, 27);
|
||||
expectedOutput = Arrays.asList("John:24", "Jane:25", "Jack:27");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zipCollectionUsingGuava21() {
|
||||
List<String> output = Streams
|
||||
.zip(names.stream(), ages.stream(), (name, age) -> name + ":" + age)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(output, expectedOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zipCollectionUsingIntStream() {
|
||||
List<String> output = IntStream
|
||||
.range(0, Math.min(names.size(), ages.size()))
|
||||
.mapToObj(i -> names.get(i) + ":" + ages.get(i))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(output, expectedOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zipCollectionUsingJool() {
|
||||
Seq<String> output = Seq
|
||||
.of("John", "Jane", "Jack")
|
||||
.zip(Seq.of(24, 25, 27), (x, y) -> x + ":" + y);
|
||||
|
||||
assertEquals(output.toList(), expectedOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zipCollectionUsingJoolTuple() {
|
||||
Seq<Tuple2<String, Integer>> output = Seq
|
||||
.of("John", "Jane", "Dennis")
|
||||
.zip(Seq.of(24, 25, 27));
|
||||
|
||||
Tuple2<String, Integer> element1 = new Tuple2<String, Integer>("John", 24);
|
||||
Tuple2<String, Integer> element2 = new Tuple2<String, Integer>("Jane", 25);
|
||||
Tuple2<String, Integer> element3 = new Tuple2<String, Integer>("Dennis", 27);
|
||||
|
||||
List<Tuple2> expectedOutput = Arrays.asList(element1, element2, element3);
|
||||
assertEquals(output.collect(Collectors.toList()), expectedOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zipCollectionUsingJoolWithIndex() {
|
||||
Seq<Tuple2<String, Long>> output = Seq
|
||||
.of("John", "Jane", "Dennis")
|
||||
.zipWithIndex();
|
||||
|
||||
Tuple2<String, Long> element1 = new Tuple2<>("John", 0L);
|
||||
Tuple2<String, Long> element2 = new Tuple2<>("Jane", 1L);
|
||||
Tuple2<String, Long> element3 = new Tuple2<>("Dennis", 2L);
|
||||
|
||||
List<Tuple2> expectedOutput = Arrays.asList(element1, element2, element3);
|
||||
assertEquals(output.collect(Collectors.toList()), expectedOutput);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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');
|
||||
Reference in New Issue
Block a user