Merge remote-tracking branch 'upstream/master'

This commit is contained in:
DianeDuan 2016-11-19 15:15:12 +08:00
commit 95425deb3c
131 changed files with 3097 additions and 386 deletions

131
aspectj/pom.xml Normal file
View File

@ -0,0 +1,131 @@
<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</groupId>
<artifactId>aspectj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>aspectj</name>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<!-- unit test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
</dependencies>
<build>
<finalName>aspectj</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${source.version}</source>
<target>${source.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<configuration>
<complianceLevel>${source.version}</complianceLevel>
<source>${source.version}</source>
<target>${source.version}</target>
<showWeaveInfo>true</showWeaveInfo>
<verbose>true</verbose>
<Xlint>ignore</Xlint>
<encoding>${project.build.sourceEncoding}</encoding>
<!-- Post-compile weaving -->
<!--
<weaveDependencies>
<weaveDependency>
<groupId>org.agroup</groupId>
<artifactId>to-weave</artifactId>
</weaveDependency>
<weaveDependency>
<groupId>org.anothergroup</groupId>
<artifactId>gen</artifactId>
</weaveDependency>
</weaveDependencies>
-->
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.10</version>
<configuration>
<argLine>-javaagent:"${settings.localRepository}"/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar</argLine>
<useSystemClassLoader>true</useSystemClassLoader>
<forkMode>always</forkMode>
</configuration>
</plugin> -->
</plugins>
</build>
<properties>
<source.version>1.8</source.version>
<aspectj.version>1.6.11</aspectj.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<aspectj.version>1.8.9</aspectj.version>
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<junit.version>4.12</junit.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
package com.baeldung.aspectj;
public class Account {
int balance = 20;
public boolean withdraw(int amount) {
if (balance - amount > 0) {
balance = balance - amount;
return true;
} else
return false;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.aspectj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public aspect AccountAspect {
private static final Logger logger = LoggerFactory.getLogger(AccountAspect.class);
final int MIN_BALANCE = 10;
pointcut callWithDraw(int amount, Account account):
call(boolean Account.withdraw(int)) && args(amount) && target(account);
before(int amount, Account account) : callWithDraw(amount, account) {
logger.info(" Balance before withdrawal: {}", account.balance);
logger.info(" Withdraw ammout: {}", amount);
}
boolean around(int amount, Account account) : callWithDraw(amount, account) {
if (account.balance - amount >= MIN_BALANCE)
return proceed(amount, account);
else {
logger.info("Withdrawal Rejected!");
return false;
}
}
after(int amount, Account balance) : callWithDraw(amount, balance) {
logger.info("Balance after withdrawal : {}", balance.balance);
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.aspectj;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Secured {
public boolean isLocked() default false;
}

View File

@ -0,0 +1,23 @@
package com.baeldung.aspectj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SecuredMethod {
private static final Logger logger = LoggerFactory.getLogger(SecuredMethod.class);
@Secured(isLocked = true)
public void lockedMethod() throws Exception {
logger.info("lockedMethod");
}
@Secured(isLocked = false)
public void unlockedMethod() {
logger.info("unlockedMethod");
}
public static void main(String[] args) throws Exception {
SecuredMethod sv = new SecuredMethod();
sv.lockedMethod();
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.aspectj;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Aspect
public class SecuredMethodAspect {
private static final Logger logger = LoggerFactory.getLogger(SecuredMethodAspect.class);
@Pointcut("@annotation(secured)")
public void callAt(Secured secured) {
}
@Around("callAt(secured)")
public Object around(ProceedingJoinPoint pjp, Secured secured) throws Throwable {
if (secured.isLocked()) {
logger.info(pjp.getSignature().toLongString() + " is locked");
return null;
} else {
return pjp.proceed();
}
}
}

View File

@ -0,0 +1,8 @@
<aspectj>
<aspects>
<aspect name="com.baeldung.aspectj.SecuredMethodAspect"/>
<weaver options="-verbose -showWeaveInfo">
<include within="com.baeldung.aspectj.*"/>
</weaver>
</aspects>
</aspectj>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg %n</pattern>
</layout>
</appender>
<logger name="com.baeldung.hazelcast" level="INFO" additivity="false">
<appender-ref ref="STDOUT" />
</logger>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,27 @@
package com.baeldung.aspectj.test;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.aspectj.Account;
public class AccountTest {
private Account account;
@Before
public void before() {
account = new Account();
}
@Test
public void givenBalance20AndMinBalance10_whenWithdraw5_thenSuccess() {
assertTrue(account.withdraw(5));
}
@Test
public void givenBalance20AndMinBalance10_whenWithdraw100_thenFail() {
assertFalse(account.withdraw(100));
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.aspectj.test;
import org.junit.Test;
import com.baeldung.aspectj.SecuredMethod;
public class SecuredMethodTest {
@Test
public void testMethod() throws Exception {
SecuredMethod service = new SecuredMethod();
service.unlockedMethod();
service.lockedMethod();
}
}

View File

@ -46,6 +46,11 @@
<version>3.3</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<!-- web -->
<!-- marshalling -->
@ -129,7 +134,7 @@
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
<version>${commons-codec.version}</version>
</dependency>
</dependencies>
@ -333,6 +338,8 @@
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>

View File

@ -0,0 +1,51 @@
package com.baeldung.hashing;
import com.google.common.hash.Hashing;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.util.encoders.Hex;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA256Hashing {
public static String HashWithJavaMessageDigest(final String originalString)
throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
final byte[] encodedhash = digest.digest(
originalString.getBytes(StandardCharsets.UTF_8));
return bytesToHex(encodedhash);
}
public static String HashWithGuava(final String originalString) {
final String sha256hex = Hashing.sha256().hashString(
originalString, StandardCharsets.UTF_8).toString();
return sha256hex;
}
public static String HashWithApacheCommons(final String originalString) {
final String sha256hex = DigestUtils.sha256Hex(originalString);
return sha256hex;
}
public static String HashWithBouncyCastle(final String originalString)
throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
final byte[] hash = digest.digest(
originalString.getBytes(StandardCharsets.UTF_8));
final String sha256hex = new String(Hex.encode(hash));
return sha256hex;
}
private static String bytesToHex(byte[] hash) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}

View File

@ -0,0 +1,63 @@
package org.baeldung.equalshashcode.entities;
import java.util.List;
import java.util.Set;
public class ComplexClass {
private List<?> genericList;
private Set<Integer> integerSet;
public ComplexClass(List<?> genericArrayList, Set<Integer> integerHashSet) {
super();
this.genericList = genericArrayList;
this.integerSet = integerHashSet;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((genericList == null) ? 0 : genericList.hashCode());
result = prime * result + ((integerSet == null) ? 0 : integerSet.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof ComplexClass))
return false;
ComplexClass other = (ComplexClass) obj;
if (genericList == null) {
if (other.genericList != null)
return false;
} else if (!genericList.equals(other.genericList))
return false;
if (integerSet == null) {
if (other.integerSet != null)
return false;
} else if (!integerSet.equals(other.integerSet))
return false;
return true;
}
protected List<?> getGenericList() {
return genericList;
}
protected void setGenericArrayList(List<?> genericList) {
this.genericList = genericList;
}
protected Set<Integer> getIntegerSet() {
return integerSet;
}
protected void setIntegerSet(Set<Integer> integerSet) {
this.integerSet = integerSet;
}
}

View File

@ -0,0 +1,54 @@
package org.baeldung.equalshashcode.entities;
public class PrimitiveClass {
private boolean primitiveBoolean;
private int primitiveInt;
public PrimitiveClass(boolean primitiveBoolean, int primitiveInt) {
super();
this.primitiveBoolean = primitiveBoolean;
this.primitiveInt = primitiveInt;
}
protected boolean isPrimitiveBoolean() {
return primitiveBoolean;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (primitiveBoolean ? 1231 : 1237);
result = prime * result + primitiveInt;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PrimitiveClass other = (PrimitiveClass) obj;
if (primitiveBoolean != other.primitiveBoolean)
return false;
if (primitiveInt != other.primitiveInt)
return false;
return true;
}
protected void setPrimitiveBoolean(boolean primitiveBoolean) {
this.primitiveBoolean = primitiveBoolean;
}
protected int getPrimitiveInt() {
return primitiveInt;
}
protected void setPrimitiveInt(int primitiveInt) {
this.primitiveInt = primitiveInt;
}
}

View File

@ -0,0 +1,58 @@
package org.baeldung.equalshashcode.entities;
public class Rectangle extends Shape {
private double width;
private double length;
public Rectangle(double width, double length) {
this.width = width;
this.length = length;
}
@Override
public double area() {
return width * length;
}
@Override
public double perimeter() {
return 2 * (width + length);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(length);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(width);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Rectangle other = (Rectangle) obj;
if (Double.doubleToLongBits(length) != Double.doubleToLongBits(other.length))
return false;
if (Double.doubleToLongBits(width) != Double.doubleToLongBits(other.width))
return false;
return true;
}
protected double getWidth() {
return width;
}
protected double getLength() {
return length;
}
}

View File

@ -0,0 +1,7 @@
package org.baeldung.equalshashcode.entities;
public abstract class Shape {
public abstract double area();
public abstract double perimeter();
}

View File

@ -0,0 +1,58 @@
package org.baeldung.equalshashcode.entities;
import java.awt.Color;
public class Square extends Rectangle {
Color color;
public Square(double width, Color color) {
super(width, width);
this.color = color;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((color == null) ? 0 : color.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof Square)) {
return false;
}
Square other = (Square) obj;
if (color == null) {
if (other.color != null) {
return false;
}
} else if (!color.equals(other.color)) {
return false;
}
return true;
}
protected Color getColor() {
return color;
}
protected void setColor(Color color) {
this.color = color;
}
}

View File

@ -0,0 +1,11 @@
package org.baeldung.executable;
import javax.swing.JOptionPane;
public class ExecutableMavenJar {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.hashing;
import org.junit.Test;
import static org.junit.Assert.*;
public class SHA256HashingTest {
private static String originalValue = "abc123";
private static String hashedValue =
"6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090";
@Test
public void testHashWithJavaMessageDigest() throws Exception {
final String currentHashedValue = SHA256Hashing.HashWithJavaMessageDigest(originalValue);
assertEquals(currentHashedValue, hashedValue);
}
@Test
public void testHashWithGuava() throws Exception {
final String currentHashedValue = SHA256Hashing.HashWithApacheCommons(originalValue);
assertEquals(currentHashedValue, hashedValue);
}
@Test
public void testHashWithApacheCommans() throws Exception {
final String currentHashedValue = SHA256Hashing.HashWithGuava(originalValue);
assertEquals(currentHashedValue, hashedValue);
}
@Test
public void testHashWithBouncyCastle() throws Exception {
final String currentHashedValue = SHA256Hashing.HashWithBouncyCastle(originalValue);
assertEquals(currentHashedValue, hashedValue);
}
}

View File

@ -2,7 +2,6 @@ package com.baeldung.java.conversion;
import static org.junit.Assert.assertEquals;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
@ -20,78 +19,111 @@ public class StringConversionTest {
@Test
public void whenConvertedToInt_thenCorrect() {
assertEquals(Integer.parseInt("1"), 1);
String beforeConvStr = "1";
int afterConvInt = 1;
assertEquals(Integer.parseInt(beforeConvStr), afterConvInt);
}
@Test
public void whenConvertedToInteger_thenCorrect() {
assertEquals(Integer.valueOf("12").equals(12), true);
String beforeConvStr = "12";
Integer afterConvInteger = 12;
assertEquals(Integer.valueOf(beforeConvStr).equals(afterConvInteger), true);
}
@Test
public void whenConvertedTolong_thenCorrect() {
assertEquals(Long.parseLong("12345"), 12345);
String beforeConvStr = "12345";
long afterConvLongPrimitive = 12345;
assertEquals(Long.parseLong(beforeConvStr), afterConvLongPrimitive);
}
@Test
public void whenConvertedToLong_thenCorrect() {
assertEquals(Long.valueOf("14567").equals(14567L), true);
String beforeConvStr = "14567";
Long afterConvLong = 14567l;
assertEquals(Long.valueOf(beforeConvStr).equals(afterConvLong), true);
}
@Test
public void whenConvertedTodouble_thenCorrect() {
assertEquals(Double.parseDouble("1.4"), 1.4, 0.0);
String beforeConvStr = "1.4";
double afterConvDoublePrimitive = 1.4;
assertEquals(Double.parseDouble(beforeConvStr), afterConvDoublePrimitive, 0.0);
}
@Test
public void whenConvertedToDouble_thenCorrect() {
assertEquals(Double.valueOf("145.67").equals(145.67d), true);
String beforeConvStr = "145.67";
double afterConvDouble = 145.67d;
assertEquals(Double.valueOf(beforeConvStr).equals(afterConvDouble), true);
}
@Test
public void whenConvertedToByteArray_thenCorrect() throws UnsupportedEncodingException {
byte[] byteArray1 = new byte[] { 'a', 'b', 'c' };
String string = new String(byteArray1, "UTF-8");
public void whenConvertedToByteArr_thenCorrect() {
String beforeConvStr = "abc";
byte[] afterConvByteArr = new byte[] { 'a', 'b', 'c' };
assertEquals(Arrays.equals(string.getBytes(), byteArray1), true);
assertEquals(Arrays.equals(beforeConvStr.getBytes(), afterConvByteArr), true);
}
@Test
public void whenConvertedToboolean_thenCorrect() {
assertEquals(Boolean.parseBoolean("true"), true);
String beforeConvStr = "true";
boolean afterConvBooleanPrimitive = true;
assertEquals(Boolean.parseBoolean(beforeConvStr), afterConvBooleanPrimitive);
}
@Test
public void whenConvertedToBoolean_thenCorrect() {
assertEquals(Boolean.valueOf("true"), true);
String beforeConvStr = "true";
Boolean afterConvBoolean = true;
assertEquals(Boolean.valueOf(beforeConvStr), afterConvBoolean);
}
@Test
public void whenConvertedToCharArray_thenCorrect() {
String str = "hello";
char[] charArray = { 'h', 'e', 'l', 'l', 'o' };
public void whenConvertedToCharArr_thenCorrect() {
String beforeConvStr = "hello";
char[] afterConvCharArr = { 'h', 'e', 'l', 'l', 'o' };
assertEquals(Arrays.equals(charArray, str.toCharArray()), true);
assertEquals(Arrays.equals(beforeConvStr.toCharArray(), afterConvCharArr), true);
}
@Test
public void whenConvertedToDate_thenCorrect() throws ParseException {
String str = "15/10/2013";
String beforeConvStr = "15/10/2013";
int afterConvCalendarDay = 15;
int afterConvCalendarMonth = 9;
int afterConvCalendarYear = 2013;
SimpleDateFormat formatter = new SimpleDateFormat("dd/M/yyyy");
Date date1 = formatter.parse(str);
Calendar calendar = new GregorianCalendar(2013, 9, 15);
Date date2 = calendar.getTime();
Date afterConvDate = formatter.parse(beforeConvStr);
Calendar calendar = new GregorianCalendar();
calendar.setTime(afterConvDate);
assertEquals(date1.compareTo(date2), 0);
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), afterConvCalendarDay);
assertEquals(calendar.get(Calendar.MONTH), afterConvCalendarMonth);
assertEquals(calendar.get(Calendar.YEAR), afterConvCalendarYear);
}
@Test
public void whenConvertedToLocalDateTime_thenCorrect() throws ParseException {
public void whenConvertedToLocalDateTime_thenCorrect() {
String str = "2007-12-03T10:15:30";
LocalDateTime localDateTime = new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
int afterConvCalendarDay = 03;
Month afterConvCalendarMonth = Month.DECEMBER;
int afterConvCalendarYear = 2007;
LocalDateTime afterConvDate
= new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
assertEquals(localDateTime.getDayOfMonth(), 3);
assertEquals(localDateTime.getMonth(), Month.DECEMBER);
assertEquals(localDateTime.getYear(), 2007);
assertEquals(afterConvDate.getDayOfMonth(), afterConvCalendarDay);
assertEquals(afterConvDate.getMonth(), afterConvCalendarMonth);
assertEquals(afterConvDate.getYear(), afterConvCalendarYear);
}
}

54
ejb/ejb-client/pom.xml Executable file
View File

@ -0,0 +1,54 @@
<?xml version="1.0"?>
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>ejb-client</artifactId>
<name>EJB3 Client Maven</name>
<description>EJB3 Client Maven</description>
<properties>
<junit.version>4.12</junit.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-ejb-client-bom</artifactId>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb-remote</artifactId>
<type>ejb</type>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*EJBSetupTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,71 @@
package com.baeldung.ejb.client;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.baeldung.ejb.tutorial.HelloWorld;
public class EJBClient {
public EJBClient() {
}
private Context context = null;
public String getEJBRemoteMessage() {
EJBClient main = new EJBClient();
try {
// 1. Obtaining Context
main.createInitialContext();
// 2. Generate JNDI Lookup name and caste
HelloWorld helloWorld = main.lookup();
return helloWorld.getHelloWorld();
} catch (NamingException e) {
e.printStackTrace();
return "";
} finally {
try {
main.closeContext();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
public HelloWorld lookup() throws NamingException {
// The app name is the EAR name of the deployed EJB without .ear suffix.
// Since we haven't deployed the application as a .ear, the app name for
// us will be an empty string
final String appName = "";
final String moduleName = "remote";
final String distinctName = "";
final String beanName = "HelloWorld";
final String viewClassName = HelloWorld.class.getName();
final String toLookup = "ejb:" + appName + "/" + moduleName
+ "/" + distinctName + "/" + beanName + "!" + viewClassName;
return (HelloWorld) context.lookup(toLookup);
}
public void createInitialContext() throws NamingException {
Properties prop = new Properties();
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
prop.put(Context.PROVIDER_URL, "http-remoting://127.0.0.1:8080");
prop.put(Context.SECURITY_PRINCIPAL, "testUser");
prop.put(Context.SECURITY_CREDENTIALS, "admin1234!");
prop.put("jboss.naming.client.ejb.context", false);
context = new InitialContext(prop);
}
public void closeContext() throws NamingException {
if (context != null) {
context.close();
}
}
}

View File

@ -0,0 +1,8 @@
remote.connections=default
remote.connection.default.host=127.0.0.1
remote.connection.default.port=8080
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER}
remote.connection.default.username=testUser
remote.connection.default.password=admin1234!

View File

@ -0,0 +1,16 @@
package com.baeldung.ejb.setup.test;
import static org.junit.Assert.*;
import org.junit.Test;
import com.baeldung.ejb.client.EJBClient;
import com.baeldung.ejb.tutorial.HelloWorldBean;
public class EJBSetupTest {
@Test
public void testEJBClient() {
EJBClient ejbClient = new EJBClient();
HelloWorldBean bean = new HelloWorldBean();
assertEquals(bean.getHelloWorld(), ejbClient.getEJBRemoteMessage());
}
}

39
ejb/ejb-remote/pom.xml Executable file
View File

@ -0,0 +1,39 @@
<?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>
<parent>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>ejb-remote</artifactId>
<packaging>ejb</packaging>
<!-- <name>ejb-remote</name> -->
<dependencies>
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.wildfly.plugins</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>1.1.0.Alpha5</version>
<configuration>
<hostname>127.0.0.1</hostname>
<port>9990</port>
<username>testUser</username>
<password>admin1234!</password>
<filename>${build.finalName}.jar</filename>
</configuration>
</plugin>
</plugins>
<!-- <finalName>ejb-remote</finalName> -->
</build>
</project>

View File

@ -0,0 +1,8 @@
package com.baeldung.ejb.tutorial;
import javax.ejb.Remote;
@Remote
public interface HelloWorld {
String getHelloWorld();
}

View File

@ -0,0 +1,13 @@
package com.baeldung.ejb.tutorial;
import javax.ejb.Stateless;
@Stateless(name = "HelloWorld")
public class HelloWorldBean implements HelloWorld {
@Override
public String getHelloWorld() {
return "Welcome to EJB Tutorial!";
}
}

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd"
version="3.2">
<module-name>remote</module-name>
</ejb-jar>

83
ejb/pom.xml Executable file
View File

@ -0,0 +1,83 @@
<?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.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>ejb</name>
<description>EJB Tutorial</description>
<repositories>
<repository>
<id>jboss-public-repository-group</id>
<name>JBoss Public Maven Repository Group</name>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb-remote</artifactId>
<version>1.0-SNAPSHOT</version>
<type>ejb</type>
</dependency>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-7.0</artifactId>
<version>1.0.1.Final</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-ejb-client-bom</artifactId>
<version>10.1.0.Final</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-ejb-plugin</artifactId>
<version>2.4</version>
<configuration>
<ejbVersion>3.2</ejbVersion>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<modules>
<module>ejb-remote</module>
<module>ejb-client</module>
</modules>
</project>

View File

@ -0,0 +1,25 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class AuditFilter extends BaseFilter {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpSession session = httpServletRequest.getSession(false);
if (session != null && session.getAttribute("username") != null) {
request.setAttribute("username", session.getAttribute("username"));
}
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(servletNames = "front-controller")
public class VisitorCounterFilter extends BaseFilter {
private int counter;
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
request.setAttribute("counter", ++counter);
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,35 @@
<?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.enterprise.patterns</groupId>
<artifactId>enterprise-patterns-parent</artifactId>
<packaging>pom</packaging>
<modules>
<module>spring-dispatcher-servlet</module>
</modules>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

9
javaxval/README.md Normal file
View File

@ -0,0 +1,9 @@
=========
## Java Bean Validation Examples
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Java Bean Validation Basics](http://www.baeldung.com/javax-validation)

170
jaxb/pom.xml Normal file
View File

@ -0,0 +1,170 @@
<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</groupId>
<artifactId>jaxb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jaxb</name>
<dependencies>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>${jaxb.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-core</artifactId>
<version>${jaxb.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>com.sun.istack</groupId>
<artifactId>istack-commons-runtime</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
</dependencies>
<build>
<finalName>jaxb</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<versionRange>[${jaxb2-maven-plugin.version},)</versionRange>
<goals>
<goal>schemagen</goal>
<goal>xjc</goal>
</goals>
</pluginExecutionFilter>
<action>
<execute />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- xjc -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>${jaxb2-maven-plugin.version}</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<xjbSources>
<xjbSource>src/main/resources/global.xjb</xjbSource>
</xjbSources>
<sources>
<source>src/main/resources/user.xsd</source>
</sources>
<outputDirectory>${basedir}/src/main/java</outputDirectory>
<clearOutputDir>false</clearOutputDir>
</configuration>
</plugin>
<!-- schemagen -->
<!--
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>${jaxb2-maven-plugin.version}</version>
<executions>
<execution>
<id>schemagen</id>
<goals>
<goal>schemagen</goal>
</goals>
</execution>
</executions>
<configuration>
<sources>
<source>src/main/java/com/baeldung/jaxb/gen</source>
</sources>
<outputDirectory>src/main/resources</outputDirectory>
<clearOutputDir>false</clearOutputDir>
<transformSchemas>
<transformSchema>
<uri>http://www.baeldung.com/jaxb/gen</uri>
<toPrefix>user</toPrefix>
<toFile>gen-schema.xsd</toFile>
</transformSchema>
</transformSchemas>
</configuration>
</plugin>
-->
</plugins>
</build>
<properties>
<!-- jaxb -->
<jaxb.version>2.2.11</jaxb.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<jaxb2-maven-plugin.version>2.3</jaxb2-maven-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,58 @@
package com.baeldung.jaxb;
import java.util.Date;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "book")
@XmlType(propOrder = { "id", "name", "date" })
public class Book {
private Long id;
private String name;
private String author;
private Date date;
@XmlAttribute
public void setId(Long id) {
this.id = id;
}
@XmlElement(name = "title")
public void setName(String name) {
this.name = name;
}
@XmlTransient
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Long getId() {
return id;
}
public String getAuthor() {
return author;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", author=" + author + ", date=" + date + "]";
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.jaxb;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class DateAdapter extends XmlAdapter<String, Date> {
private static final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
@Override
public Date unmarshal(String v) throws Exception {
return dateFormat.get().parse(v);
}
@Override
public String marshal(Date v) throws Exception {
return dateFormat.get().format(v);
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.jaxb;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Main {
public static void marshal() throws JAXBException, IOException {
Book book = new Book();
book.setId(1L);
book.setName("Book1");
book.setAuthor("Author1");
book.setDate(new Date());
JAXBContext context = JAXBContext.newInstance(Book.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(book, new File("./book.xml"));
}
public static Book unMashal() throws JAXBException, IOException {
JAXBContext context = JAXBContext.newInstance(Book.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Book book = (Book) unmarshaller.unmarshal(new FileReader("./book.xml"));
return book;
}
public static void main(String[] args) throws JAXBException, IOException {
marshal();
Book book = unMashal();
System.out.println(book.toString());
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxb:bindings version="2.0" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" xmlns:xs="http://www.w3.org/2001/XMLSchema"
jaxb:extensionBindingPrefixes="xjc">
<jaxb:globalBindings>
<xjc:simple />
<xjc:serializable uid="-1" />
<jaxb:javaType name="java.util.Calendar" xmlType="xs:dateTime"
parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime"
printMethod="javax.xml.bind.DatatypeConverter.printDateTime" />
</jaxb:globalBindings>
</jaxb:bindings>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg %n</pattern>
</layout>
</appender>
<logger name="com.baeldung.hazelcast" level="INFO" additivity="false">
<appender-ref ref="STDOUT" />
</logger>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.baeldung.com/jaxb/gen"
xmlns:userns="http://www.baeldung.com/jaxb/gen" elementFormDefault="qualified">
<element name="userRequest" type="userns:UserRequest"></element>
<element name="userResponse" type="userns:UserResponse"></element>
<complexType name="UserRequest">
<sequence>
<element name="id" type="int" />
<element name="name" type="string" />
</sequence>
</complexType>
<complexType name="UserResponse">
<sequence>
<element name="id" type="int" />
<element name="name" type="string" />
<element name="gender" type="string" />
<element name="created" type="dateTime" />
</sequence>
</complexType>
</schema>

View File

@ -1,6 +1,5 @@
<?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"
<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>
@ -14,40 +13,10 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<!-- Due to a bug in surefire-junit5-5.0.0-ALPHA we use the latest snapshot instead -->
<junit.gen5.version>5.0.0-SNAPSHOT</junit.gen5.version>
<junit.jupiter.version>5.0.0-M2</junit.jupiter.version>
<junit.platform.version>1.0.0-M2</junit.platform.version>
</properties>
<repositories>
<repository>
<id>snapshots-repo</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<!-- Do NOT cache JUnit 5 snapshot JARs. -->
<updatePolicy>always</updatePolicy>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>snapshots-repo</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<!-- Do NOT cache JUnit 5 snapshot JARs. -->
<updatePolicy>always</updatePolicy>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<build>
<plugins>
<plugin>
@ -63,9 +32,9 @@
<version>2.19</version>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>surefire-junit5</artifactId>
<version>${junit.gen5.version}</version>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
</dependencies>
</plugin>
@ -74,10 +43,11 @@
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit5-api</artifactId>
<version>${junit.gen5.version}</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,29 @@
package com.baeldung;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.expectThrows;
import org.junit.jupiter.api.Test;
public class AssertionTest {
@Test
public void testConvertToDoubleThrowException() {
String age = "eighteen";
expectThrows(NumberFormatException.class, () -> {
convertToInt(age);
});
assertThrows(NumberFormatException.class, () -> {
convertToInt(age);
});
}
private static Integer convertToInt(String str) {
if (str == null) {
return null;
}
return Integer.valueOf(str);
}
}

View File

@ -1,9 +1,11 @@
package com.baeldung;
import org.junit.gen5.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.junit.jupiter.api.Assumptions.assumingThat;
import static org.junit.gen5.api.Assertions.assertEquals;
import static org.junit.gen5.api.Assumptions.*;
import org.junit.jupiter.api.Test;
public class AssumptionTest {

View File

@ -1,18 +1,26 @@
package com.baeldung;
import org.junit.gen5.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.expectThrows;
import static org.junit.gen5.api.Assertions.assertEquals;
import static org.junit.gen5.api.Assertions.expectThrows;
import org.junit.jupiter.api.Test;
public class ExceptionTest {
@Test
void shouldThrowException() {
Throwable exception = expectThrows(UnsupportedOperationException.class,
() -> {
Throwable exception = expectThrows(UnsupportedOperationException.class, () -> {
throw new UnsupportedOperationException("Not supported");
});
assertEquals(exception.getMessage(), "Not supported");
}
@Test
void assertThrowsException() {
String str = null;
assertThrows(IllegalArgumentException.class, () -> {
Integer.valueOf(str);
});
}
}

View File

@ -1,12 +1,12 @@
package com.baeldung;
import org.junit.gen5.api.Disabled;
import org.junit.gen5.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Arrays;
import java.util.List;
import static org.junit.gen5.api.Assertions.*;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class FirstTest {

View File

@ -0,0 +1,50 @@
package com.baeldung;
import java.util.logging.Logger;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
//@RunWith(JUnitPlatform.class)
public class JUnit5NewFeaturesTest {
private static final Logger log = Logger.getLogger(JUnit5NewFeaturesTest.class.getName());
@BeforeAll
static void setup() {
log.info("@BeforeAll - executes once before all test methods in this class");
}
@BeforeEach
void init() {
log.info("@BeforeEach - executes before each test method in this class");
}
@DisplayName("Single test successful")
@Test
void testSingleSuccessTest() {
log.info("Success");
}
@Test
@Disabled("Not implemented yet.")
void testShowSomething() {
}
@AfterEach
void tearDown() {
log.info("@AfterEach - executed after each test method.");
}
@AfterAll
static void done() {
log.info("@AfterAll - executed after all test methods.");
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
public class LiveTest {
private List<String> in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No"));
private List<String> out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie"));
@TestFactory
public Stream<DynamicTest> translateDynamicTestsFromStream() {
return in.stream().map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> {
int id = in.indexOf(word);
assertEquals(out.get(id), translate(word));
}));
}
private String translate(String word) {
if ("Hello".equalsIgnoreCase(word)) {
return "Cześć";
} else if ("Yes".equalsIgnoreCase(word)) {
return "Tak";
} else if ("No".equalsIgnoreCase(word)) {
return "Nie";
}
return "Error";
}
}

View File

@ -1,10 +1,14 @@
package com.baeldung;
import org.junit.gen5.api.*;
import java.util.EmptyStackException;
import java.util.Stack;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
public class NestedTest {
Stack<Object> stack;
boolean isRun = false;

View File

@ -0,0 +1,11 @@
package com.baeldung;
public final class StringUtils {
public static Double convertToDouble(String str) {
if (str == null) {
return null;
}
return Double.valueOf(str);
}
}

View File

@ -1,9 +1,9 @@
package com.baeldung;
import org.junit.gen5.api.Tag;
import org.junit.gen5.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.gen5.api.Assertions.assertEquals;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@Tag("Test case")
public class TaggedTest {

View File

@ -0,0 +1,8 @@
package com.baeldung.suites;
//@RunWith(JUnitPlatform.class)
//@SelectPackages("com.baeldung")
//@SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class})
public class AllTests {
}

79
log4j2/pom.xml Normal file
View File

@ -0,0 +1,79 @@
<?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>
<artifactId>log4j2</artifactId>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<!-- This is the needed core component. -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
<!-- This is used by JSONLayout. -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.4</version>
</dependency>
<!-- This is used by XMLLayout. -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.8.4</version>
</dependency>
<!-- This is used by JDBC Appender. -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.192</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
<!-- This is used for testing only. -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,32 @@
package com.baeldung.logging.log4j2.tests;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.junit.LoggerContextRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.Assert.assertTrue;
@RunWith(JUnit4.class)
public class AsyncFileAppenderUsingJsonLayoutTest {
@Rule
public LoggerContextRule contextRule =
new LoggerContextRule("log4j2-async-file-appender_json-layout.xml");
@Test
public void givenLoggerWithAsyncConfig_shouldLogToJsonFile()
throws Exception {
Logger logger = contextRule.getLogger(getClass().getSimpleName());
final int count = 88;
for (int i = 0; i < count; i++) {
logger.info("This is async JSON message #{} at INFO level.", count);
}
long logEventsCount = Files.lines(Paths.get("target/logfile.json")).count();
assertTrue(logEventsCount > 0 && logEventsCount <= count);
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.logging.log4j2.tests;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class ConsoleAppenderUsingDefaultLayoutTest {
@Test
public void givenLoggerWithDefaultConfig_shouldLogToConsole()
throws Exception {
Logger logger = LogManager.getLogger(getClass());
Exception e = new RuntimeException("This is only a test!");
logger.info("This is a simple message at INFO level. " +
"It will be hidden.");
logger.error("This is a simple message at ERROR level. " +
"This is the minimum visible level.", e);
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.logging.log4j2.tests;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.junit.LoggerContextRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class ConsoleAppenderUsingPatternLayoutWithColorsTest {
@Rule
public LoggerContextRule contextRule =
new LoggerContextRule("log4j2-console-appender_pattern-layout.xml");
@Test
public void givenLoggerWithConsoleConfig_shouldLogToConsoleInColors()
throws Exception {
Logger logger = contextRule.getLogger(getClass().getSimpleName());
logger.trace("This is a colored message at TRACE level.");
logger.debug("This is a colored message at DEBUG level. " +
"This is the minimum visible level.");
logger.info("This is a colored message at INFO level.");
logger.warn("This is a colored message at WARN level.");
Exception e = new RuntimeException("This is only a test!");
logger.error("This is a colored message at ERROR level.", e);
logger.fatal("This is a colored message at FATAL level.");
}
@Test
public void givenLoggerWithConsoleConfig_shouldFilterByMarker() throws Exception {
Logger logger = contextRule.getLogger("ConnTrace");
Marker appError = MarkerManager.getMarker("APP_ERROR");
logger.error(appError, "This marker message at ERROR level should be hidden.");
Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE");
logger.trace(connectionTrace, "This is a marker message at TRACE level.");
}
@Test
public void givenLoggerWithConsoleConfig_shouldFilterByThreadContext() throws Exception {
Logger logger = contextRule.getLogger("UserAudit");
ThreadContext.put("userId", "1000");
logger.info("This is a log-visible user login. Maybe from an admin account?");
ThreadContext.put("userId", "1001");
logger.info("This is a log-invisible user login.");
boolean b = true;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.logging.log4j2.tests;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.junit.LoggerContextRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class FailoverSyslogConsoleAppenderTest {
@Rule
public LoggerContextRule contextRule =
new LoggerContextRule("log4j2-failover-syslog-console-appender_pattern-layout.xml");
@Test
public void givenLoggerWithFailoverConfig_shouldLog() throws Exception {
Logger logger = contextRule.getLogger(getClass().getSimpleName());
logger.trace("This is a syslog message at TRACE level.");
logger.debug("This is a syslog message at DEBUG level.");
logger.info("This is a syslog message at INFO level. This is the minimum visible level.");
logger.warn("This is a syslog message at WARN level.");
Exception e = new RuntimeException("This is only a test!");
logger.error("This is a syslog message at ERROR level.", e);
logger.fatal("This is a syslog message at FATAL level.");
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.logging.log4j2.tests;
import com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.junit.LoggerContextRule;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.sql.Connection;
import java.sql.ResultSet;
import static org.junit.Assert.assertTrue;
@RunWith(JUnit4.class)
public class JDBCAppenderTest {
@Rule
public LoggerContextRule contextRule = new LoggerContextRule("log4j2-jdbc-appender.xml");
@BeforeClass
public static void setup() throws Exception {
Connection connection = ConnectionFactory.getConnection();
connection.createStatement()
.execute("CREATE TABLE logs(" +
"when TIMESTAMP," +
"logger VARCHAR(255)," +
"level VARCHAR(255)," +
"message VARCHAR(4096)," +
"throwable TEXT)");
//connection.commit();
}
@Test
public void givenLoggerWithJdbcConfig_shouldLogToDataSource() throws Exception {
Logger logger = contextRule.getLogger(getClass().getSimpleName());
final int count = 88;
for (int i = 0; i < count; i++) {
logger.info("This is JDBC message #{} at INFO level.", count);
}
Connection connection = ConnectionFactory.getConnection();
ResultSet resultSet = connection.createStatement()
.executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs");
int logCount = 0;
if (resultSet.next()) {
logCount = resultSet.getInt("ROW_COUNT");
}
assertTrue(logCount == count);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.logging.log4j2.tests;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.junit.LoggerContextRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import static org.junit.Assert.assertTrue;
@RunWith(JUnit4.class)
public class RollingFileAppenderUsingXMLLayoutTest {
@Rule
public LoggerContextRule contextRule =
new LoggerContextRule("log4j2-rolling-file-appender_xml-layout.xml");
@Test
public void givenLoggerWithRollingFileConfig_shouldLogToXMLFile() throws Exception {
Logger logger = contextRule.getLogger(getClass().getSimpleName());
final int count = 88;
for (int i = 0; i < count; i++) {
logger.info("This is rolling file XML message #{} at INFO level.", i);
}
String[] logEvents = Files.readAllLines(Paths.get("target/logfile.xml")).stream()
.collect(Collectors.joining(System.lineSeparator()))
.split("\\n\\n+");
assertTrue(logEvents.length == 39);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.logging.log4j2.tests.jdbc;
import org.apache.commons.dbcp2.BasicDataSource;
import org.h2.Driver;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectionFactory {
private interface Singleton {
ConnectionFactory INSTANCE = new ConnectionFactory();
}
private BasicDataSource dataSource;
private ConnectionFactory() {
dataSource = new BasicDataSource();
dataSource.setDriver(new Driver());
dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
}
public static Connection getConnection() throws SQLException {
return Singleton.INSTANCE.dataSource.getConnection();
}
}

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<File name="JSONLogfileAppender" fileName="target/logfile.json">
<JSONLayout compact="true" eventEol="true"/>
<BurstFilter level="INFO" rate="2" maxBurst="10"/>
</File>
<Async name="AsyncAppender" bufferSize="80">
<AppenderRef ref="JSONLogfileAppender"/>
</Async>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="AsyncAppender"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" xmlns:xi="http://www.w3.org/2001/XInclude">
<Appenders>
<xi:include href="log4j2-includes/console-appender_pattern-layout_colored.xml"/>
<Console name="ConsoleRedAppender" target="SYSTEM_OUT">
<PatternLayout pattern="%style{%message}{red}%n"/>
<MarkerFilter marker="CONN_TRACE"/>
</Console>
<Console name="ConsoleGreenAppender" target="SYSTEM_OUT">
<PatternLayout pattern="%style{userId=%X{userId}:}{white} %style{%message}{green}%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="ConnTrace" level="TRACE" additivity="false">
<AppenderRef ref="ConsoleRedAppender"/>
</Logger>
<Logger name="UserAudit" level="INFO" additivity="false">
<AppenderRef ref="ConsoleGreenAppender"/>
<ThreadContextMapFilter>
<KeyValuePair key="userId" value="1000"/>
</ThreadContextMapFilter>
</Logger>
<Root level="DEBUG">
<AppenderRef ref="ConsoleAppender"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" xmlns:xi="http://www.w3.org/2001/XInclude">
<Appenders>
<xi:include href="log4j2-includes/console-appender_pattern-layout_colored.xml"/>
<Syslog name="Syslog" host="localhost" port="514" protocol="TCP" ignoreExceptions="false"/>
<Failover name="FailoverAppender" primary="Syslog">
<Failovers>
<AppenderRef ref="ConsoleAppender"/>
</Failovers>
</Failover>
</Appenders>
<Loggers>
<Root level="TRACE">
<AppenderRef ref="FailoverAppender"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<Console name="ConsoleAppender" target="SYSTEM_OUT">
<PatternLayout pattern="%style{%date{DEFAULT}}{yellow} [%style{%thread}{white}] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green, DEBUG=cyan, TRACE=blue} %style{%logger{36}}{cyan}:%n[+] %message%n%throwable"/>
</Console>

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<JDBC name="JDBCAppender" tableName="logs">
<ConnectionFactory class="com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory"
method="getConnection"/>
<Column name="when" isEventTimestamp="true"/>
<Column name="logger" pattern="%logger"/>
<Column name="level" pattern="%level"/>
<Column name="message" pattern="%message"/>
<Column name="throwable" pattern="%ex{full}"/>
</JDBC>
</Appenders>
<Loggers>
<Root level="trace">
<AppenderRef ref="JDBCAppender"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<RollingFile name="XMLLogfileAppender"
fileName="target/logfile.xml"
filePattern="target/logfile-%d{yyyy-MM-dd}-%i.log.gz">
<XMLLayout/>
<Policies>
<SizeBasedTriggeringPolicy size="17 kB"/>
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="TRACE">
<AppenderRef ref="XMLLogfileAppender"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT">
<PatternLayout pattern="%d [%t] %-5level %logger{36} - %msg%n%throwable"/>
</Console>
</Appenders>
<Loggers>
<Root level="ERROR">
<AppenderRef ref="ConsoleAppender"/>
</Root>
</Loggers>
</Configuration>

View File

@ -40,9 +40,9 @@
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>

View File

@ -1,6 +1,8 @@
package com.baeldung.pdf;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
@ -10,14 +12,21 @@ import javax.xml.parsers.ParserConfigurationException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.fit.pdfdom.PDFDomTree;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
public class PDF2HTMLExample {
private static final String FILENAME = "src/main/resources/pdf.pdf";
private static final String PDF = "src/main/resources/pdf.pdf";
private static final String HTML = "src/main/resources/html.html";
public static void main(String[] args) {
try {
generateHTMLFromPDF(FILENAME);
} catch (IOException | ParserConfigurationException e) {
generateHTMLFromPDF(PDF);
generatePDFFromHTML(HTML);
} catch (IOException | ParserConfigurationException | DocumentException e) {
e.printStackTrace();
}
}
@ -32,4 +41,12 @@ public class PDF2HTMLExample {
pdf.close();
}
}
private static void generatePDFFromHTML(String filename) throws ParserConfigurationException, IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("src/output/html.pdf"));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(filename));
document.close();
}
}

View File

@ -1,24 +1,36 @@
package com.baeldung.pdf;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.tools.imageio.ImageIOUtil;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
public class PDF2ImageExample {
private static final String FILENAME = "src/main/resources/pdf.pdf";
private static final String PDF = "src/main/resources/pdf.pdf";
private static final String JPG = "http://cdn2.baeldung.netdna-cdn.com/wp-content/uploads/2016/05/baeldung-rest-widget-main-1.2.0";
private static final String GIF = "https://media.giphy.com/media/l3V0x6kdXUW9M4ONq/giphy";
public static void main(String[] args) {
try {
generateImageFromPDF(FILENAME, "png");
generateImageFromPDF(FILENAME, "jpeg");
generateImageFromPDF(FILENAME, "gif");
} catch (IOException e) {
generateImageFromPDF(PDF, "png");
generateImageFromPDF(PDF, "jpeg");
generateImageFromPDF(PDF, "gif");
generatePDFFromImage(JPG, "jpg");
generatePDFFromImage(GIF, "gif");
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
}
@ -32,4 +44,19 @@ public class PDF2ImageExample {
}
document.close();
}
private static void generatePDFFromImage(String filename, String extension)
throws IOException, BadElementException, DocumentException {
Document document = new Document();
String input = filename + "." + extension;
String output = "src/output/" + extension + ".pdf";
FileOutputStream fos = new FileOutputStream(output);
PdfWriter writer = PdfWriter.getInstance(document, fos);
writer.open();
document.open();
document.add(Image.getInstance((new URL(input))));
document.close();
writer.close();
}
}

View File

@ -1,6 +1,9 @@
package com.baeldung.pdf;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
@ -10,14 +13,24 @@ import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
public class PDF2TextExample {
private static final String FILENAME = "src/main/resources/pdf.pdf";
private static final String PDF = "src/main/resources/pdf.pdf";
private static final String TXT = "src/main/resources/txt.txt";
public static void main(String[] args) {
try {
generateTxtFromPDF(FILENAME);
} catch (IOException e) {
generateTxtFromPDF(PDF);
generatePDFFromTxt(TXT);
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
}
@ -45,4 +58,27 @@ public class PDF2TextExample {
pw.close();
}
private static void generatePDFFromTxt(String filename) throws IOException, DocumentException {
Document pdfDoc = new Document(PageSize.A4);
PdfWriter.getInstance(pdfDoc, new FileOutputStream("src/output/txt.pdf"))
.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
pdfDoc.open();
Font myfont = new Font();
myfont.setStyle(Font.NORMAL);
myfont.setSize(11);
pdfDoc.add(new Paragraph("\n"));
BufferedReader br = new BufferedReader(new FileReader(filename));
String strLine;
while ((strLine = br.readLine()) != null) {
Paragraph para = new Paragraph(strLine + "\n", myfont);
para.setAlignment(Element.ALIGN_JUSTIFIED);
pdfDoc.add(para);
}
pdfDoc.close();
br.close();
}
}

View File

@ -0,0 +1,53 @@
<!DOCTYPE html>
<html>
<head>
<title>A very simple webpage</title>
</head>
<body>
<h1>A very simple webpage. This is an "h1" level header.</h1>
<h2>This is a level h2 header.</h2>
<h6>This is a level h6 header. Pretty small!</h6>
<p>This is a standard paragraph.</p>
<p align=center>Now I've aligned it in the center of the screen.</p>
<p align=right>Now aligned to the right</p>
<p><b>Bold text</b></p>
<p><strong>Strongly emphasized text</strong> Can you tell the difference vs. bold?</p>
<p><i>Italics</i></p>
<p><em>Emphasized text</em> Just like Italics!</p>
<h2>How about a nice ordered list!</h2>
<ol>
<li>This little piggy went to market</li>
<li>This little piggy went to SB228 class</li>
<li>This little piggy went to an expensive restaurant in Downtown Palo Alto</li>
<li>This little piggy ate too much at Indian Buffet.</li>
<li>This little piggy got lost</li>
</ol>
<h2>Unordered list</h2>
<ul>
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
</ul>
<p>And finally, how about some</p><a href="http://www.google.com/">Links?</a>
<p>Remember, you can view the HTMl code from this or any other page by using the "View Page Source" command of your browser.</p>
</body>
</html>

View File

@ -0,0 +1,3 @@
Test
Text
Test TEST

View File

@ -25,6 +25,7 @@
<include>**/*UnitTest.java</include>
</includes>
<systemPropertyVariables></systemPropertyVariables>
<testFailureIgnore>false</testFailureIgnore>
</configuration>
</plugin>
</plugins>
@ -42,6 +43,7 @@
<includes>
<include>**/*LiveTest.java</include>
</includes>
<testFailureIgnore>false</testFailureIgnore>
</configuration>
</plugin>
</plugins>

View File

@ -1,14 +1,13 @@
package main.java.com.baeldung.selenium;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class SeleniumExample {
private WebDriver webDriver;
@ -38,12 +37,12 @@ public class SeleniumExample {
private void closeOverlay() {
List<WebElement> webElementList = webDriver.findElements(By.tagName("a"));
try {
if (webElementList != null && !webElementList.isEmpty()) {
webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().orElseThrow(NoSuchElementException::new).click();
}
} catch (NoSuchElementException exception) {
exception.printStackTrace();
if (webElementList != null) {
webElementList.stream()
.filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title")))
.filter(WebElement::isDisplayed)
.findAny()
.ifPresent(WebElement::click);
}
}
@ -56,6 +55,6 @@ public class SeleniumExample {
}
public boolean isAuthorInformationAvailable() {
return webDriver.findElement(By.xpath("//*[contains(text(), 'Eugen an engineer')]")).isDisplayed();
return webDriver.findElement(By.xpath("//*[contains(text(), 'an engineer with a passion for teaching and building stuff on the web')]")).isDisplayed();
}
}

View File

@ -26,16 +26,11 @@ public class SeleniumWithJUnitLiveTest {
@Test
public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() {
try {
seleniumExample.getAboutBaeldungPage();
String actualTitle = seleniumExample.getTitle();
assertNotNull(actualTitle);
assertEquals(actualTitle, expecteTilteAboutBaeldungPage);
assertTrue(seleniumExample.isAuthorInformationAvailable());
} catch (Exception exception) {
exception.printStackTrace();
seleniumExample.closeWindow();
}
}
}

View File

@ -26,15 +26,10 @@ public class SeleniumWithTestNGLiveTest {
@Test
public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() {
try {
seleniumExample.getAboutBaeldungPage();
String actualTitle = seleniumExample.getTitle();
assertNotNull(actualTitle);
assertEquals(actualTitle, expecteTilteAboutBaeldungPage);
assertTrue(seleniumExample.isAuthorInformationAvailable());
} catch (Exception exception) {
exception.printStackTrace();
seleniumExample.closeWindow();
}
}
}

View File

@ -11,8 +11,9 @@
<properties>
<env.camel.version>2.16.1</env.camel.version>
<env.spring.version>4.2.4.RELEASE</env.spring.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<java.version>1.7</java.version>
<junit.version>4.1</junit.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
@ -62,6 +63,22 @@
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
<systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,68 @@
package org.apache.camel.file.processor;
import java.io.File;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baeldung.camel.file.FileProcessor;
public class FileProcessorIntegrationTest {
private static final long DURATION_MILIS = 10000;
private static final String SOURCE_FOLDER = "src/test/source-folder";
private static final String DESTINATION_FOLDER = "src/test/destination-folder";
@Before
public void setUp() throws Exception {
File sourceFolder = new File(SOURCE_FOLDER);
File destinationFolder = new File(DESTINATION_FOLDER);
cleanFolder(sourceFolder);
cleanFolder(destinationFolder);
sourceFolder.mkdirs();
File file1 = new File(SOURCE_FOLDER + "/File1.txt");
File file2 = new File(SOURCE_FOLDER + "/File2.txt");
file1.createNewFile();
file2.createNewFile();
}
private void cleanFolder(File folder) {
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
file.delete();
}
}
}
}
@Test
public void moveFolderContentJavaDSLTest() throws Exception {
final CamelContext camelContext = new DefaultCamelContext();
camelContext.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("file://" + SOURCE_FOLDER + "?delete=true").process(new FileProcessor()).to("file://" + DESTINATION_FOLDER);
}
});
camelContext.start();
Thread.sleep(DURATION_MILIS);
camelContext.stop();
}
@Test
public void moveFolderContentSpringDSLTest() throws InterruptedException {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context-test.xml");
Thread.sleep(DURATION_MILIS);
applicationContext.close();
}
}

View File

@ -15,7 +15,7 @@ import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
public class AppTest extends TestCase {
public class AppIntegrationTest extends TestCase {
private static final String FILE_NAME = "file.txt";
private static final String SAMPLE_INPUT_DIR = "src/test/data/sampleInputFile/";

View File

@ -6,3 +6,7 @@ spring.cloud.config.server.git.uri=file:///${user.home}/application-config
eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/
security.user.name=configUser
security.user.password=configPassword
security.user.role=SYSTEM

View File

@ -5,8 +5,8 @@ RemoteSystemsTempFiles/
bin/
.metadata/
docs/*.autosave
docs/*.autosave
.recommenders/
build/
.gradle/
.DS_Store
.idea/

View File

@ -14,12 +14,6 @@
</description>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
@ -50,6 +44,12 @@
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,28 @@
package com.baeldung.beanfactory;
public class Employee {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.beanfactory;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BeanFactoryWithClassPathResourceTest {
@Test
public void createBeanFactoryAndCheckEmployeeBean() {
Resource res = new ClassPathResource("beanfactory-example.xml");
BeanFactory factory = new XmlBeanFactory(res);
Employee emp = (Employee) factory.getBean("employee");
assertTrue(factory.isSingleton("employee"));
assertTrue(factory.getBean("employee") instanceof Employee);
assertTrue(factory.isTypeMatch("employee", Employee.class));
assertTrue(factory.getAliases("employee").length > 0);
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="employee" class="com.baeldung.beanfactory.Employee">
<constructor-arg name="name" value="Hello! My name is Java"/>
<constructor-arg name="age" value="18"/>
</bean>
<alias name="employee" alias="empalias" />
</beans>

View File

@ -53,17 +53,55 @@
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -14,12 +14,6 @@ public class Product {
@Indexed(name = "name", type = "string")
private String name;
@Indexed(name = "category", type = "string")
private String category;
@Indexed(name = "description", type = "string")
private String description;
public String getId() {
return id;
}
@ -36,20 +30,4 @@ public class Product {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -13,7 +13,7 @@ public interface ProductRepository extends SolrCrudRepository<Product, String> {
public List<Product> findByName(String name);
@Query("name:*?0* OR category:*?0* OR description:*?0*")
@Query("id:*?0* OR name:*?0*")
public Page<Product> findByCustomQuery(String searchTerm, Pageable pageable);
@Query(name = "Product.findByNamedQuery")

View File

@ -1 +1 @@
Product.findByNamedQuery=name:*?0* OR category:*?0* OR description:*?0*
Product.findByNamedQuery=id:*?0* OR name:*?0*

View File

@ -35,8 +35,6 @@ public class ProductRepositoryIntegrationTest {
final Product product = new Product();
product.setId("P000089998");
product.setName("Desk");
product.setCategory("Furniture");
product.setDescription("New Desk");
productRepository.save(product);
final Product retrievedProduct = productRepository.findOne(product.getId());
assertEquals(product.getId(), retrievedProduct.getId());
@ -47,15 +45,14 @@ public class ProductRepositoryIntegrationTest {
final Product product = new Product();
product.setId("P0001");
product.setName("T-Shirt");
product.setCategory("Kitchen");
product.setDescription("New T-Shirt");
productRepository.save(product);
product.setCategory("Clothes");
product.setName("Shirt");
productRepository.save(product);
final Product retrievedProduct = productRepository.findOne(product.getId());
assertEquals(product.getCategory(), retrievedProduct.getCategory());
assertEquals(product.getName(), retrievedProduct.getName());
}
@Test
@ -63,8 +60,6 @@ public class ProductRepositoryIntegrationTest {
final Product product = new Product();
product.setId("P0001");
product.setName("Desk");
product.setCategory("Furniture");
product.setDescription("New Desk");
productRepository.save(product);
productRepository.delete(product);
@ -79,8 +74,6 @@ public class ProductRepositoryIntegrationTest {
Product phone = new Product();
phone.setId("P0001");
phone.setName("Phone");
phone.setCategory("Electronics");
phone.setDescription("New Phone");
productRepository.save(phone);
List<Product> retrievedProducts = productRepository.findByName("Phone");
@ -92,22 +85,16 @@ public class ProductRepositoryIntegrationTest {
final Product phone = new Product();
phone.setId("P0001");
phone.setName("Smart Phone");
phone.setCategory("Electronics");
phone.setDescription("New Item");
productRepository.save(phone);
final Product phoneCover = new Product();
phoneCover.setId("P0002");
phoneCover.setName("Cover");
phoneCover.setCategory("Phone");
phoneCover.setDescription("New Product");
phoneCover.setName("Phone Cover");
productRepository.save(phoneCover);
final Product wirelessCharger = new Product();
wirelessCharger.setId("P0003");
wirelessCharger.setName("Charging Cable");
wirelessCharger.setCategory("Cable");
wirelessCharger.setDescription("Wireless Charger for Phone");
wirelessCharger.setName("Phone Charging Cable");
productRepository.save(wirelessCharger);
Page<Product> result = productRepository.findByCustomQuery("Phone", new PageRequest(0, 10));
@ -119,22 +106,16 @@ public class ProductRepositoryIntegrationTest {
final Product phone = new Product();
phone.setId("P0001");
phone.setName("Smart Phone");
phone.setCategory("Electronics");
phone.setDescription("New Item");
productRepository.save(phone);
final Product phoneCover = new Product();
phoneCover.setId("P0002");
phoneCover.setName("Cover");
phoneCover.setCategory("Phone");
phoneCover.setDescription("New Product");
phoneCover.setName("Phone Cover");
productRepository.save(phoneCover);
final Product wirelessCharger = new Product();
wirelessCharger.setId("P0003");
wirelessCharger.setName("Charging Cable");
wirelessCharger.setCategory("Cable");
wirelessCharger.setDescription("Wireless Charger for Phone");
wirelessCharger.setName("Phone Charging Cable");
productRepository.save(wirelessCharger);
Page<Product> result = productRepository.findByNamedQuery("one", new PageRequest(0, 10));

View File

@ -9,7 +9,7 @@ import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebApplicationInitializer implements org.springframework.web.WebApplicationInitializer {
public class DispatcherServletApplication implements org.springframework.web.WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext =

View File

@ -0,0 +1,73 @@
package com.baeldung.samples;
import java.io.File;
import java.util.Scanner;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.integration.annotation.Poller;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.file.FileReadingMessageSource;
import org.springframework.integration.file.FileWritingMessageHandler;
import org.springframework.integration.file.filters.SimplePatternFileListFilter;
import org.springframework.integration.file.support.FileExistsMode;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
@Configuration
@EnableIntegration
public class FileCopyConfig {
public final String INPUT_DIR = "source";
public final String OUTPUT_DIR = "target";
public final String FILE_PATTERN = "*.jpg";
@Bean
public MessageChannel fileChannel() {
return new DirectChannel();
}
@Bean
@InboundChannelAdapter(value = "fileChannel", poller = @Poller(fixedDelay = "10000"))
public MessageSource<File> fileReadingMessageSource() {
FileReadingMessageSource sourceReader = new FileReadingMessageSource();
sourceReader.setDirectory(new File(INPUT_DIR));
sourceReader.setFilter(new SimplePatternFileListFilter(FILE_PATTERN));
return sourceReader;
}
@Bean
@ServiceActivator(inputChannel = "fileChannel")
public MessageHandler fileWritingMessageHandler() {
FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(OUTPUT_DIR));
handler.setFileExistsMode(FileExistsMode.REPLACE);
handler.setExpectReply(false);
return handler;
}
public static void main(final String... args) {
final AbstractApplicationContext context = new AnnotationConfigApplicationContext(FileCopyConfig.class);
context.registerShutdownHook();
final Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a string and press <enter>: ");
while (true) {
final String input = scanner.nextLine();
if ("q".equals(input.trim())) {
context.close();
scanner.close();
break;
}
}
System.exit(0);
}
}

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- Appenders -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{HH:mm:ss.SSS} %-5p [%t][%c] %m%n"/>
</layout>
</appender>
<!-- Loggers -->
<logger name="org.springframework.integration">
<level value="warn"/>
</logger>
<logger name="com.baeldung.samples">
<level value="info"/>
</logger>
<!-- Root Logger -->
<root>
<priority value="warn"/>
<appender-ref ref="console"/>
</root>
</log4j:configuration>

View File

@ -17,11 +17,10 @@ package com.baeldung.samples;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Scanner;
/**
* Starts the Spring Context and will initialize the Spring Integration routes.
@ -35,15 +34,10 @@ public final class FileCopyTest {
private static final Logger LOGGER = Logger.getLogger(FileCopyTest.class);
@Test
public void test() throws InterruptedException {
final AbstractApplicationContext context =
new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/spring-integration-file-copy-context.xml");
public void whenFileCopyConfiguration_thanFileCopiedSuccessfully() throws InterruptedException {
final AbstractApplicationContext context = new AnnotationConfigApplicationContext(FileCopyConfig.class.getCanonicalName());
context.registerShutdownHook();
Thread.sleep(5000);
}
@Test

View File

@ -20,12 +20,10 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Created by Olga on 7/20/2016.
*/
@Controller
@RequestMapping("/mail")
public class MailController {
@Autowired
public EmailServiceImpl emailService;
@ -33,7 +31,6 @@ public class MailController {
private String attachmentPath;
@Autowired
@Qualifier("templateSimpleMessage")
public SimpleMailMessage template;
private static final Map<String, Map<String, String>> labels;

View File

@ -248,8 +248,8 @@
<properties>
<!-- Spring -->
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
<org.springframework.security.version>4.0.4.RELEASE</org.springframework.security.version>
<org.springframework.version>4.3.4.RELEASE</org.springframework.version>
<org.springframework.security.version>4.2.0.RELEASE</org.springframework.security.version>
<thymeleaf.version>2.1.4.RELEASE</thymeleaf.version>
<jackson.version>2.7.8</jackson.version>

View File

@ -112,6 +112,11 @@
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.8.0</version>
</dependency>
</dependencies>
<build>
@ -146,7 +151,7 @@
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<!-- <exclude>**/*ProductionTest.java</exclude> -->
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
<systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->

View File

@ -0,0 +1,28 @@
package com.baeldung.spring.controller;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baeldung.spring.form.GeoIP;
import com.baeldung.spring.service.RawDBDemoGeoIPLocationService;
@Controller
public class GeoIPTestController {
private RawDBDemoGeoIPLocationService locationService;
public GeoIPTestController() throws IOException {
locationService
= new RawDBDemoGeoIPLocationService();
}
@RequestMapping(value="/GeoIPTest", method = RequestMethod.POST)
@ResponseBody
public GeoIP getLocation(
@RequestParam(value="ipAddress", required=true) String ipAddress) throws Exception {
return locationService.getLocation(ipAddress);
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.spring.form;
public class GeoIP {
private String ipAddress;
private String city;
private String latitude;
private String longitude;
public GeoIP() {
}
public GeoIP(String ipAddress) {
this.ipAddress = ipAddress;
}
public GeoIP(String ipAddress, String city, String latitude, String longitude) {
this.ipAddress = ipAddress;
this.city = city;
this.latitude = latitude;
this.longitude = longitude;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}

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