Merge remote-tracking branch 'origin/master'

This commit is contained in:
pivovarit
2017-03-03 07:49:36 +01:00
124 changed files with 3479 additions and 591 deletions
+4
View File
@@ -0,0 +1,4 @@
## Apache Solrj Tutorials Project
### Relevant Articles
- [Guide to Solr in Java with Apache Solrj](http://www.baeldung.com/apache-solrj)
@@ -0,0 +1,44 @@
package com.baeldung.solrjava;
import org.apache.solr.client.solrj.beans.Field;
public class ProductBean {
String id;
String name;
String price;
public ProductBean(String id, String name, String price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
public String getId() {
return id;
}
@Field("id")
protected void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
@Field("name")
protected void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
@Field("price")
protected void setPrice(String price) {
this.price = price;
}
}
@@ -17,6 +17,12 @@ public class SolrJavaIntegration {
solrClient.setParser(new XMLResponseParser());
}
public void addProductBean(ProductBean pBean) throws IOException, SolrServerException {
solrClient.addBean(pBean);
solrClient.commit();
}
public void addSolrDocument(String documentId, String itemName, String itemPrice) throws SolrServerException, IOException {
SolrInputDocument document = new SolrInputDocument();
@@ -27,12 +33,18 @@ public class SolrJavaIntegration {
solrClient.commit();
}
public void deleteSolrDocument(String documentId) throws SolrServerException, IOException {
public void deleteSolrDocumentById(String documentId) throws SolrServerException, IOException {
solrClient.deleteById(documentId);
solrClient.commit();
}
public void deleteSolrDocumentByQuery(String query) throws SolrServerException, IOException {
solrClient.deleteByQuery(query);
solrClient.commit();
}
protected HttpSolrClient getSolrClient() {
return solrClient;
}
@@ -40,4 +52,5 @@ public class SolrJavaIntegration {
protected void setSolrClient(HttpSolrClient solrClient) {
this.solrClient = solrClient;
}
}
@@ -24,7 +24,7 @@ public class SolrJavaIntegrationTest {
}
@Test
public void whenAdd_thenVerifyAdded() throws SolrServerException, IOException {
public void whenAdd_thenVerifyAddedByQueryOnId() throws SolrServerException, IOException {
SolrQuery query = new SolrQuery();
query.set("q", "id:123456");
@@ -33,18 +33,68 @@ public class SolrJavaIntegrationTest {
response = solrJavaIntegration.getSolrClient().query(query);
SolrDocumentList docList = response.getResults();
assertEquals(docList.getNumFound(), 1);
assertEquals(1, docList.getNumFound());
for (SolrDocument doc : docList) {
assertEquals((String) doc.getFieldValue("id"), "123456");
assertEquals((Double) doc.getFieldValue("price"), (Double) 599.99);
assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name"));
assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
}
}
@Test
public void whenDelete_thenVerifyDeleted() throws SolrServerException, IOException {
public void whenAdd_thenVerifyAddedByQueryOnPrice() throws SolrServerException, IOException {
solrJavaIntegration.deleteSolrDocument("123456");
SolrQuery query = new SolrQuery();
query.set("q", "price:599.99");
QueryResponse response = null;
response = solrJavaIntegration.getSolrClient().query(query);
SolrDocumentList docList = response.getResults();
assertEquals(1, docList.getNumFound());
for (SolrDocument doc : docList) {
assertEquals("123456", (String) doc.getFieldValue("id"));
assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
}
}
@Test
public void whenAdd_thenVerifyAddedByQuery() throws SolrServerException, IOException {
SolrDocument doc = solrJavaIntegration.getSolrClient().getById("123456");
assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name"));
assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
}
@Test
public void whenAddBean_thenVerifyAddedByQuery() throws SolrServerException, IOException {
ProductBean pBean = new ProductBean("888", "Apple iPhone 6s", "299.99");
solrJavaIntegration.addProductBean(pBean);
SolrDocument doc = solrJavaIntegration.getSolrClient().getById("888");
assertEquals("Apple iPhone 6s", (String) doc.getFieldValue("name"));
assertEquals((Double) 299.99, (Double) doc.getFieldValue("price"));
}
@Test
public void whenDeleteById_thenVerifyDeleted() throws SolrServerException, IOException {
solrJavaIntegration.deleteSolrDocumentById("123456");
SolrQuery query = new SolrQuery();
query.set("q", "id:123456");
QueryResponse response = solrJavaIntegration.getSolrClient().query(query);
SolrDocumentList docList = response.getResults();
assertEquals(0, docList.getNumFound());
}
@Test
public void whenDeleteByQuery_thenVerifyDeleted() throws SolrServerException, IOException {
solrJavaIntegration.deleteSolrDocumentByQuery("name:Kenmore Dishwasher");
SolrQuery query = new SolrQuery();
query.set("q", "id:123456");
@@ -53,6 +103,6 @@ public class SolrJavaIntegrationTest {
response = solrJavaIntegration.getSolrClient().query(query);
SolrDocumentList docList = response.getResults();
assertEquals(docList.getNumFound(), 0);
assertEquals(0, docList.getNumFound());
}
}
@@ -2,7 +2,8 @@ package com.baeldung.algorithms;
import java.util.Scanner;
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
import com.baeldung.algorithms.slope_one.SlopeOne;
@@ -14,6 +15,7 @@ public class RunAlgorithm {
System.out.println("1 - Simulated Annealing");
System.out.println("2 - Slope One");
System.out.println("3 - Simple Genetic Algorithm");
System.out.println("4 - Ant Colony");
int decision = in.nextInt();
switch (decision) {
case 1:
@@ -27,6 +29,10 @@ public class RunAlgorithm {
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
break;
case 4:
AntColonyOptimization antColony = new AntColonyOptimization(21);
antColony.startAntOptimization();
break;
default:
System.out.println("Unknown option");
break;
@@ -1,4 +1,4 @@
package com.baeldung.algorithms.annealing;
package com.baeldung.algorithms.ga.annealing;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.baeldung.algorithms.annealing;
package com.baeldung.algorithms.ga.annealing;
public class SimulatedAnnealing {
@@ -1,4 +1,4 @@
package com.baeldung.algorithms.annealing;
package com.baeldung.algorithms.ga.annealing;
import java.util.ArrayList;
import java.util.Collections;
@@ -0,0 +1,37 @@
package com.baeldung.algorithms.ga.ant_colony;
public class Ant {
protected int trailSize;
protected int trail[];
protected boolean visited[];
public Ant(int tourSize) {
this.trailSize = tourSize;
this.trail = new int[tourSize];
this.visited = new boolean[tourSize];
}
protected void visitCity(int currentIndex, int city) {
trail[currentIndex + 1] = city;
visited[city] = true;
}
protected boolean visited(int i) {
return visited[i];
}
protected double trailLength(double graph[][]) {
double length = graph[trail[trailSize - 1]][trail[0]];
for (int i = 0; i < trailSize - 1; i++) {
length += graph[trail[i]][trail[i + 1]];
}
return length;
}
protected void clear() {
for (int i = 0; i < trailSize; i++)
visited[i] = false;
}
}
@@ -0,0 +1,212 @@
package com.baeldung.algorithms.ga.ant_colony;
import java.util.Arrays;
import java.util.Random;
public class AntColonyOptimization {
private double c = 1.0;
private double alpha = 1;
private double beta = 5;
private double evaporation = 0.5;
private double Q = 500;
private double antFactor = 0.8;
private double randomFactor = 0.01;
private int maxIterations = 1000;
public int numberOfCities;
public int numberOfAnts;
private double graph[][];
private double trails[][];
private Ant ants[];
private Random random = new Random();
private double probabilities[];
private int currentIndex;
public int[] bestTourOrder;
public double bestTourLength;
public AntColonyOptimization(int noOfCities) {
graph = generateRandomMatrix(noOfCities);
numberOfCities = graph.length;
numberOfAnts = (int) (numberOfCities * antFactor);
trails = new double[numberOfCities][numberOfCities];
probabilities = new double[numberOfCities];
ants = new Ant[numberOfAnts];
for (int j = 0; j < numberOfAnts; j++) {
ants[j] = new Ant(numberOfCities);
}
}
/**
* Generate initial solution
* @param n
* @return
*/
public double[][] generateRandomMatrix(int n) {
double[][] randomMatrix = new double[n][n];
random.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Integer r = random.nextInt(100) + 1;
randomMatrix[i][j] = Math.abs(r);
}
}
return randomMatrix;
}
/**
* Perform ant optimization
* @return
*/
public int[] startAntOptimization() {
int[] finalResult = null;
for (int i = 1; i <= 3; i++) {
System.out.println("Attempt #" + i);
finalResult = solve();
}
return finalResult;
}
/**
* Use this method to run the main logic
* @return
*/
private int[] solve() {
setupAnts();
clearTrails();
int iteration = 0;
while (iteration < maxIterations) {
moveAnts();
updateTrails();
updateBest();
iteration++;
}
System.out.println("Best tour length: " + (bestTourLength - numberOfCities));
System.out.println("Best tour order: " + Arrays.toString(bestTourOrder));
return bestTourOrder.clone();
}
/**
* Prepare ants for the simulation
*/
private void setupAnts() {
currentIndex = -1;
for (int i = 0; i < numberOfAnts; i++) {
ants[i].clear();
ants[i].visitCity(currentIndex, random.nextInt(numberOfCities));
}
currentIndex++;
}
/**
* At each iteration, move ants
*/
private void moveAnts() {
while (currentIndex < numberOfCities - 1) {
for (Ant a : ants)
a.visitCity(currentIndex, selectNextCity(a));
currentIndex++;
}
}
/**
* Select next city for each ant
* @param ant
* @return
*/
private int selectNextCity(Ant ant) {
if (random.nextDouble() < randomFactor) {
int t = random.nextInt(numberOfCities - currentIndex);
int j = -1;
for (int i = 0; i < numberOfCities; i++) {
if (!ant.visited(i)) {
j++;
}
if (j == t) {
return i;
}
}
}
calculateProbabilities(ant);
double r = random.nextDouble();
double total = 0;
for (int i = 0; i < numberOfCities; i++) {
total += probabilities[i];
if (total >= r) {
return i;
}
}
throw new RuntimeException("There are no other cities");
}
/**
* Calculate the next city picks probabilites
* @param ant
*/
private void calculateProbabilities(Ant ant) {
int i = ant.trail[currentIndex];
double pheromone = 0.0;
for (int l = 0; l < numberOfCities; l++) {
if (!ant.visited(l)) {
pheromone += Math.pow(trails[i][l], alpha) * Math.pow(1.0 / graph[i][l], beta);
}
}
for (int j = 0; j < numberOfCities; j++) {
if (ant.visited(j)) {
probabilities[j] = 0.0;
} else {
double numerator = Math.pow(trails[i][j], alpha) * Math.pow(1.0 / graph[i][j], beta);
probabilities[j] = numerator / pheromone;
}
}
}
/**
* Update trails that ants used
*/
private void updateTrails() {
for (int i = 0; i < numberOfCities; i++) {
for (int j = 0; j < numberOfCities; j++) {
trails[i][j] *= evaporation;
}
}
for (Ant a : ants) {
double contribution = Q / a.trailLength(graph);
for (int i = 0; i < numberOfCities - 1; i++) {
trails[a.trail[i]][a.trail[i + 1]] += contribution;
}
trails[a.trail[numberOfCities - 1]][a.trail[0]] += contribution;
}
}
/**
* Update the best solution
*/
private void updateBest() {
if (bestTourOrder == null) {
bestTourOrder = ants[0].trail;
bestTourLength = ants[0].trailLength(graph);
}
for (Ant a : ants) {
if (a.trailLength(graph) < bestTourLength) {
bestTourLength = a.trailLength(graph);
bestTourOrder = a.trail.clone();
}
}
}
/**
* Clear trails after simulation
*/
private void clearTrails() {
for (int i = 0; i < numberOfCities; i++)
for (int j = 0; j < numberOfCities; j++)
trails[i][j] = c;
}
}
@@ -0,0 +1,22 @@
package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
public class AntColonyOptimizationTest {
@Test
public void testGenerateRandomMatrix() {
AntColonyOptimization antTSP = new AntColonyOptimization(5);
Assert.assertNotNull(antTSP.generateRandomMatrix(5));
}
@Test
public void testStartAntOptimization() {
AntColonyOptimization antTSP = new AntColonyOptimization(5);
Assert.assertNotNull(antTSP.startAntOptimization());
}
}
@@ -3,7 +3,7 @@ package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
public class SimulatedAnnealingTest {
@@ -39,7 +39,8 @@ public class ListOfListsTest {
@SuppressWarnings("unchecked")
@Test
public void givenListOfLists_whenRemovingElements_thenCheckNames() {
((ArrayList<Pencil>) listOfLists.get(1)).remove(0);
((ArrayList<Pencil>) listOfLists.get(1)).remove(0);
listOfLists.remove(1);
assertEquals("Rubber 1", ((Rubber) listOfLists.get(1)
.get(0)).getName());
@@ -47,4 +48,29 @@ public class ListOfListsTest {
assertEquals("Rubber 1", ((Rubber) listOfLists.get(0)
.get(0)).getName());
}
@Test
public void givenThreeList_whenCombineIntoOneList_thenCheckList() {
ArrayList<Pen> pens = new ArrayList<>();
pens.add(new Pen("Pen 1"));
pens.add(new Pen("Pen 2"));
ArrayList<Pencil> pencils = new ArrayList<>();
pencils.add(new Pencil("Pencil 1"));
pencils.add(new Pencil("Pencil 2"));
ArrayList<Rubber> rubbers = new ArrayList<>();
rubbers.add(new Rubber("Rubber 1"));
rubbers.add(new Rubber("Rubber 2"));
List<ArrayList<? extends Stationery>> list = new ArrayList<ArrayList<? extends Stationery>>();
list.add(pens);
list.add(pencils);
list.add(rubbers);
assertEquals("Pen 1", ((Pen) list.get(0)
.get(0)).getName());
assertEquals("Pencil 1", ((Pencil) list.get(1)
.get(0)).getName());
assertEquals("Rubber 1", ((Rubber) list.get(2)
.get(0)).getName());
}
}
@@ -0,0 +1,150 @@
package org.baeldung.guava;
import com.google.common.collect.Lists;
import com.google.common.reflect.Invokable;
import com.google.common.reflect.TypeToken;
import org.junit.Test;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class GuavaReflectionUtilsTest {
@Test
public void givenTwoGenericList_whenCheckIsAssignableFrom_thenReturnTrueDueToTypeErasure() {
//given
ArrayList<String> stringList = Lists.newArrayList();
ArrayList<Integer> intList = Lists.newArrayList();
//when
boolean result = stringList.getClass().isAssignableFrom(intList.getClass());
//then
assertTrue(result);
}
@Test
public void givenTypeToken_whenResolveType_thenShouldResolveProperType() {
//given
TypeToken<List<String>> stringListToken = new TypeToken<List<String>>() {
};
TypeToken<List<Integer>> integerListToken = new TypeToken<List<Integer>>() {
};
TypeToken<List<? extends Number>> numberTypeToken = new TypeToken<List<? extends Number>>() {
};
//then
assertFalse(stringListToken.isSubtypeOf(integerListToken));
assertFalse(numberTypeToken.isSubtypeOf(integerListToken));
assertTrue(integerListToken.isSubtypeOf(numberTypeToken));
}
@Test
public void givenCustomClass_whenCaptureGeneric_thenReturnTypeAtRuntime() {
//given
ParametrizedClass<String> parametrizedClass = new ParametrizedClass<String>() {
};
//then
assertEquals(parametrizedClass.type, TypeToken.of(String.class));
}
@Test
public void givenComplexType_whenGetTypeArgument_thenShouldReturnTypeAtRuntime() {
//given
TypeToken<Function<Integer, String>> funToken = new TypeToken<Function<Integer, String>>() {
};
//when
TypeToken<?> funResultToken = funToken.resolveType(Function.class.getTypeParameters()[1]);
//then
assertEquals(funResultToken, TypeToken.of(String.class));
}
@Test
public void givenMapType_whenGetTypeArgumentOfEntry_thenShouldReturnTypeAtRuntime() throws NoSuchMethodException {
//given
TypeToken<Map<String, Integer>> mapToken = new TypeToken<Map<String, Integer>>() {
};
//when
TypeToken<?> entrySetToken = mapToken.resolveType(Map.class.getMethod("entrySet").getGenericReturnType());
//then
assertEquals(entrySetToken, new TypeToken<Set<Map.Entry<String, Integer>>>() {
});
}
@Test
public void givenInvokable_whenCheckPublicMethod_shouldReturnTrue() throws NoSuchMethodException {
//given
Method method = CustomClass.class.getMethod("somePublicMethod");
Invokable<CustomClass, ?> invokable = new TypeToken<CustomClass>() {
}.method(method);
//when
boolean isPublicStandradJava = Modifier.isPublic(method.getModifiers());
boolean isPublicGuava = invokable.isPublic();
//then
assertTrue(isPublicStandradJava);
assertTrue(isPublicGuava);
}
@Test
public void givenInvokable_whenCheckFinalMethod_shouldReturnFalseForIsOverridable() throws NoSuchMethodException {
//given
Method method = CustomClass.class.getMethod("notOverridablePublicMethod");
Invokable<CustomClass, ?> invokable = new TypeToken<CustomClass>() {
}.method(method);
//when
boolean isOverridableStandardJava = (!(Modifier.isFinal(method.getModifiers()) || Modifier.isPrivate(method.getModifiers())
|| Modifier.isStatic(method.getModifiers())
|| Modifier.isFinal(method.getDeclaringClass().getModifiers())));
boolean isOverridableFinalGauava = invokable.isOverridable();
//then
assertFalse(isOverridableStandardJava);
assertFalse(isOverridableFinalGauava);
}
@Test
public void givenListOfType_whenGetReturnRype_shouldCaptureTypeAtRuntime() throws NoSuchMethodException {
//given
Method getMethod = List.class.getMethod("get", int.class);
//when
Invokable<List<Integer>, ?> invokable = new TypeToken<List<Integer>>() {
}.method(getMethod);
//then
assertEquals(TypeToken.of(Integer.class), invokable.getReturnType()); // Not Object.class!
}
abstract class ParametrizedClass<T> {
TypeToken<T> type = new TypeToken<T>(getClass()) {
};
}
class CustomClass {
public void somePublicMethod() {
}
public final void notOverridablePublicMethod() {
}
}
}
+34
View File
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.examples.guice</groupId>
<artifactId>guice-intro</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>${guice.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<guice.version>4.1.0</guice.version>
</properties>
<name>guice-intro</name>
</project>
@@ -0,0 +1,36 @@
package com.baeldung.examples;
import com.baeldung.examples.guice.Communication;
import com.baeldung.examples.guice.binding.AOPModule;
import com.baeldung.examples.guice.modules.BasicModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.Scanner;
/**
*
* @author Baeldung
*/
public class RunGuice {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new BasicModule(), new AOPModule());
Communication comms = injector.getInstance(Communication.class);
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your message to be sent; press Q to quit and P to print the message log");
while (true) {
String input = scanner.nextLine();
if (input.equalsIgnoreCase("q")) {
System.exit(0);
}
if (input.equalsIgnoreCase("p")) {
comms.print();
} else {
comms.sendMessage(input);
}
}
}
}
@@ -0,0 +1,57 @@
package com.baeldung.examples.guice;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;
import java.util.logging.Logger;
/**
*
* @author Baeldung
*/
public class Communication {
final Date start = new Date();
@Inject
private Logger logger;
private Queue<String> messageLog;
@Named("CommsUUID")
private String commsID;
@Inject
private DefaultCommunicator communicator;
public Communication(Boolean keepRecords) {
if (keepRecords) {
messageLog = new LinkedList();
}
}
public boolean sendMessage(String message) {
if (!message.isEmpty() && messageLog != null) {
messageLog.add(message);
}
return communicator.sendMessage(message);
}
public void print() {
if (messageLog != null) {
for (String message : messageLog) {
logger.info(message);
}
} else {
logger.info("Message logging wasn't enabled");
}
}
public DefaultCommunicator getCommunicator() {
return this.communicator;
}
}
@@ -0,0 +1,12 @@
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.constant.CommunicationModel;
public interface CommunicationMode {
public CommunicationModel getMode();
public boolean sendMessage(String message);
}
@@ -0,0 +1,48 @@
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.marker.Communicator;
import com.google.inject.Inject;
import com.google.inject.name.Named;
public class DefaultCommunicator implements Communicator {
private CommunicationMode defaultCommsMode;
@Inject
@Named("SMSComms")
CommunicationMode smsCommsMode;
@Inject
@Named("EmailComms")
CommunicationMode emailCommsMode;
@Inject
@Named("IMComms")
CommunicationMode imCommsMode;
protected DefaultCommunicator(CommunicationMode defaultComms) {
this.defaultCommsMode = defaultComms;
}
public DefaultCommunicator() {
}
public boolean sendMessage(String message) {
boolean sent = false;
if (defaultCommsMode != null) {
sent = sendMessageByDefault(message);
} else {
sent = smsCommsMode.sendMessage(message);
}
return sent;
}
private boolean sendMessageByDefault(String message) {
boolean sent = false;
if (message != null && !message.trim().equals("")) {
return defaultCommsMode.sendMessage(message);
}
return sent;
}
}
@@ -0,0 +1,23 @@
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.aop.MessageSentLoggable;
import com.baeldung.examples.guice.constant.CommunicationModel;
/**
*
* @author Baekdung
*/
public class EmailCommunicationMode implements CommunicationMode {
@Override
public CommunicationModel getMode() {
return CommunicationModel.EMAIL;
}
@Override
@MessageSentLoggable
public boolean sendMessage(String Message) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
@@ -0,0 +1,30 @@
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.aop.MessageSentLoggable;
import com.baeldung.examples.guice.constant.CommunicationModel;
import com.google.inject.Inject;
import java.util.logging.Logger;
/**
*
* @author Baeldung
*/
public class IMCommunicationMode implements CommunicationMode {
@Inject
private Logger logger;
@Override
public CommunicationModel getMode() {
return CommunicationModel.IM;
}
@Override
@MessageSentLoggable
public boolean sendMessage(String message) {
logger.info("IM Message Sent");
return true;
}
}
@@ -0,0 +1,29 @@
package com.baeldung.examples.guice;
import com.baeldung.examples.guice.aop.MessageSentLoggable;
import com.baeldung.examples.guice.constant.CommunicationModel;
import com.google.inject.Inject;
import java.util.logging.Logger;
/**
*
* @author Baeldung
*/
public class SMSCommunicationMode implements CommunicationMode {
@Inject
private Logger logger;
@Override
public CommunicationModel getMode() {
return CommunicationModel.SMS;
}
@Override
@MessageSentLoggable
public boolean sendMessage(String message) {
logger.info("SMS message sent");
return true;
}
}
@@ -0,0 +1,22 @@
package com.baeldung.examples.guice.aop;
import java.util.logging.Logger;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
*
* @author Baeldung
*/
public class MessageLogger implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object[] objectArray = invocation.getArguments();
int i = 0;
for (Object object : objectArray) {
Logger.getAnonymousLogger().info("Sending message: " + object.toString());
}
return invocation.proceed();
}
}
@@ -0,0 +1,16 @@
package com.baeldung.examples.guice.aop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author Baeldung
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MessageSentLoggable {
}
@@ -0,0 +1,22 @@
package com.baeldung.examples.guice.binding;
import com.baeldung.examples.guice.aop.MessageLogger;
import com.baeldung.examples.guice.aop.MessageSentLoggable;
import com.google.inject.AbstractModule;
import com.google.inject.matcher.Matchers;
/**
*
* @author Baeldung
*/
public class AOPModule extends AbstractModule {
@Override
protected void configure() {
bindInterceptor(Matchers.any(),
Matchers.annotatedWith(MessageSentLoggable.class),
new MessageLogger()
);
}
}
@@ -0,0 +1,36 @@
package com.baeldung.examples.guice.binding;
import com.baeldung.examples.guice.Communication;
import com.baeldung.examples.guice.CommunicationMode;
import com.baeldung.examples.guice.DefaultCommunicator;
import com.baeldung.examples.guice.EmailCommunicationMode;
import com.baeldung.examples.guice.IMCommunicationMode;
import com.baeldung.examples.guice.SMSCommunicationMode;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Baeldung
*/
public class BasicModule extends AbstractModule {
@Override
protected void configure() {
try {
bind(Communication.class).toConstructor(Communication.class.getConstructor(Boolean.TYPE));
} catch (NoSuchMethodException ex) {
Logger.getLogger(BasicModule.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(BasicModule.class.getName()).log(Level.SEVERE, null, ex);
}
bind(DefaultCommunicator.class).annotatedWith(Names.named("AnotherCommunicator")).to(DefaultCommunicator.class).asEagerSingleton();
bind(CommunicationMode.class).annotatedWith(Names.named("IMComms")).to(IMCommunicationMode.class);
bind(CommunicationMode.class).annotatedWith(Names.named("EmailComms")).to(EmailCommunicationMode.class);
bind(CommunicationMode.class).annotatedWith(Names.named("SMSComms")).to(SMSCommunicationMode.class);
}
}
@@ -0,0 +1,16 @@
package com.baeldung.examples.guice.constant;
/**
*
* @author Baeldung
*/
public enum CommunicationModel {
EMAIL("Email"), SMS("SMS"), IM("IM"), PHONE("Phone");
final String name;
CommunicationModel(String name) {
this.name = name;
}
}
@@ -0,0 +1,11 @@
package com.baeldung.examples.guice.marker;
/**
*
* @author Baeldung
*/
public interface Communicator {
public boolean sendMessage(String message);
}
@@ -0,0 +1,37 @@
package com.baeldung.examples.guice.modules;
import com.baeldung.examples.guice.Communication;
import com.baeldung.examples.guice.CommunicationMode;
import com.baeldung.examples.guice.DefaultCommunicator;
import com.baeldung.examples.guice.EmailCommunicationMode;
import com.baeldung.examples.guice.IMCommunicationMode;
import com.baeldung.examples.guice.SMSCommunicationMode;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Baeldung
*/
public class BasicModule extends AbstractModule {
@Override
protected void configure() {
try {
bind(Communication.class).toConstructor(Communication.class.getConstructor(Boolean.class));
bind(Boolean.class).toInstance(true);
} catch (NoSuchMethodException ex) {
Logger.getLogger(com.baeldung.examples.guice.binding.BasicModule.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(com.baeldung.examples.guice.binding.BasicModule.class.getName()).log(Level.SEVERE, null, ex);
}
bind(DefaultCommunicator.class).annotatedWith(Names.named("AnotherCommunicator")).to(DefaultCommunicator.class).asEagerSingleton();
bind(CommunicationMode.class).annotatedWith(Names.named("IMComms")).to(IMCommunicationMode.class);
bind(CommunicationMode.class).annotatedWith(Names.named("EmailComms")).to(EmailCommunicationMode.class);
bind(CommunicationMode.class).annotatedWith(Names.named("SMSComms")).to(SMSCommunicationMode.class);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>jasypt</artifactId>
<dependencies>
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>${jasypt.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<jasypt.version>1.9.2</jasypt.version>
<junit.version>4.12</junit.version>
</properties>
</project>

Some files were not shown because too many files have changed in this diff Show More