Merge pull request #2 from eugenp/master

Reverse Merge
This commit is contained in:
Shubham Aggarwal 2017-10-28 11:17:10 +05:30 committed by GitHub
commit 4f23603852
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
45 changed files with 1565 additions and 57 deletions

View File

@ -17,37 +17,24 @@ import scala.Tuple2;
public class WordCount {
private static final Pattern SPACE = Pattern.compile(" ");
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Usage: JavaWordCount <file>");
System.exit(1);
if (args.length < 1) {
System.err.println("Usage: JavaWordCount <file>");
System.exit(1);
}
SparkConf sparkConf = new SparkConf().setAppName("JavaWordCount")
.setMaster("local");
JavaSparkContext ctx = new JavaSparkContext(sparkConf);
JavaRDD<String> lines = ctx.textFile(args[0], 1);
JavaRDD<String> words = lines.flatMap(s -> Arrays.asList(SPACE.split(s)).iterator());
JavaPairRDD<String, Integer> wordAsTuple = words.mapToPair(word -> new Tuple2<>(word, 1));
JavaPairRDD<String, Integer> wordWithCount = wordAsTuple.reduceByKey((Integer i1, Integer i2)->i1 + i2);
List<Tuple2<String, Integer>> output = wordWithCount.collect();
for (Tuple2<?, ?> tuple : output) {
System.out.println(tuple._1() + ": " + tuple._2());
}
ctx.stop();
}
SparkConf sparkConf = new SparkConf().setAppName("JavaWordCount").setMaster("local");
JavaSparkContext ctx = new JavaSparkContext(sparkConf);
JavaRDD<String> lines = ctx.textFile(args[0], 1);
JavaRDD<String> words = lines.flatMap(s -> Arrays.asList(SPACE.split(s)).iterator());
JavaPairRDD<String, Integer> ones = words.mapToPair(
new PairFunction<String, String, Integer>() {
@Override
public Tuple2<String, Integer> call(String s) {
return new Tuple2<>(s, 1);
}
});
JavaPairRDD<String, Integer> counts = ones.reduceByKey(
new Function2<Integer, Integer, Integer>() {
@Override
public Integer call(Integer i1, Integer i2) {
return i1 + i2;
}
});
List<Tuple2<String, Integer>> output = counts.collect();
for (Tuple2<?, ?> tuple : output) {
System.out.println(tuple._1() + ": " + tuple._2());
}
ctx.stop();
}
}

View File

@ -19,11 +19,12 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<junit.jupiter.version>5.0.0-RC2</junit.jupiter.version>
<junit.platform.version>1.0.0-RC2</junit.platform.version>
<junit.vintage.version>4.12.0-RC2</junit.vintage.version>
<junit.jupiter.version>5.0.1</junit.jupiter.version>
<junit.platform.version>1.0.1</junit.platform.version>
<junit.vintage.version>4.12.1</junit.vintage.version>
<log4j2.version>2.8.2</log4j2.version>
<h2.version>1.4.196</h2.version>
<mockito.version>2.11.0</mockito.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>

View File

@ -0,0 +1,41 @@
package com.baeldung.junit5.mockito;
public class User {
private Integer id;
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.junit5.mockito.repository;
import com.baeldung.junit5.mockito.User;
public interface MailClient {
void sendUserRegistrationMail(User user);
}

View File

@ -0,0 +1,9 @@
package com.baeldung.junit5.mockito.repository;
public interface SettingRepository {
int getUserMinAge();
int getUserNameMinLength();
}

View File

@ -0,0 +1,10 @@
package com.baeldung.junit5.mockito.repository;
import com.baeldung.junit5.mockito.User;
public interface UserRepository {
User insert(User user);
boolean isUsernameAlreadyExists(String userName);
}

View File

@ -0,0 +1,46 @@
package com.baeldung.junit5.mockito.service;
import com.baeldung.junit5.mockito.User;
import com.baeldung.junit5.mockito.repository.MailClient;
import com.baeldung.junit5.mockito.repository.SettingRepository;
import com.baeldung.junit5.mockito.repository.UserRepository;
public class DefaultUserService implements UserService {
private UserRepository userRepository;
private SettingRepository settingRepository;
private MailClient mailClient;
public DefaultUserService(UserRepository userRepository, SettingRepository settingRepository, MailClient mailClient) {
this.userRepository = userRepository;
this.settingRepository = settingRepository;
this.mailClient = mailClient;
}
@Override
public User register(User user) {
validate(user);
User insertedUser = userRepository.insert(user);
mailClient.sendUserRegistrationMail(insertedUser);
return insertedUser;
}
private void validate(User user) {
if(user.getName() == null) {
throw new RuntimeException(Errors.USER_NAME_REQUIRED);
}
if(user.getName().length() < settingRepository.getUserNameMinLength()) {
throw new RuntimeException(Errors.USER_NAME_SHORT);
}
if(user.getAge() < settingRepository.getUserMinAge()) {
throw new RuntimeException(Errors.USER_AGE_YOUNG);
}
if(userRepository.isUsernameAlreadyExists(user.getName())) {
throw new RuntimeException(Errors.USER_NAME_DUPLICATE);
}
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.junit5.mockito.service;
public class Errors {
public static final String USER_NAME_REQUIRED = "user.name.required";
public static final String USER_NAME_SHORT = "user.name.short";
public static final String USER_AGE_YOUNG = "user.age.young";
public static final String USER_NAME_DUPLICATE = "user.name.duplicate";
}

View File

@ -0,0 +1,9 @@
package com.baeldung.junit5.mockito.service;
import com.baeldung.junit5.mockito.User;
public interface UserService {
User register(User user);
}

View File

@ -0,0 +1,75 @@
/*
* Copyright 2015-2016 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.baeldung.junit5.mockito;
import static org.mockito.Mockito.mock;
import java.lang.reflect.Parameter;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
import org.junit.jupiter.api.extension.ExtensionContext.Store;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.TestInstancePostProcessor;
import org.mockito.MockitoAnnotations;
import org.mockito.Mock;
/**
* {@code MockitoExtension} showcases the {@link TestInstancePostProcessor}
* and {@link ParameterResolver} extension APIs of JUnit 5 by providing
* dependency injection support at the field level and at the method parameter
* level via Mockito 2.x's {@link Mock @Mock} annotation.
*
* @since 5.0
*/
public class MockitoExtension implements TestInstancePostProcessor, ParameterResolver {
@Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) {
MockitoAnnotations.initMocks(testInstance);
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
return parameterContext.getParameter().isAnnotationPresent(Mock.class);
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
return getMock(parameterContext.getParameter(), extensionContext);
}
private Object getMock(Parameter parameter, ExtensionContext extensionContext) {
Class<?> mockType = parameter.getType();
Store mocks = extensionContext.getStore(Namespace.create(MockitoExtension.class, mockType));
String mockName = getMockName(parameter);
if (mockName != null) {
return mocks.getOrComputeIfAbsent(mockName, key -> mock(mockType, mockName));
}
else {
return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(), key -> mock(mockType));
}
}
private String getMockName(Parameter parameter) {
String explicitMockName = parameter.getAnnotation(Mock.class).name().trim();
if (!explicitMockName.isEmpty()) {
return explicitMockName;
}
else if (parameter.isNamePresent()) {
return parameter.getName();
}
return null;
}
}

View File

@ -0,0 +1,122 @@
package com.baeldung.junit5.mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.baeldung.junit5.mockito.repository.MailClient;
import com.baeldung.junit5.mockito.repository.SettingRepository;
import com.baeldung.junit5.mockito.repository.UserRepository;
import com.baeldung.junit5.mockito.service.DefaultUserService;
import com.baeldung.junit5.mockito.service.Errors;
import com.baeldung.junit5.mockito.service.UserService;
@RunWith(JUnitPlatform.class)
@ExtendWith(MockitoExtension.class)
public class UserServiceUnitTest {
UserService userService;
@Mock UserRepository userRepository;
User user;
@BeforeEach
void init(@Mock SettingRepository settingRepository, @Mock MailClient mailClient) {
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
when(settingRepository.getUserMinAge()).thenReturn(10);
when(settingRepository.getUserNameMinLength()).thenReturn(4);
when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(false);
}
@Test
void givenValidUser_whenSaveUser_thenSucceed(@Mock MailClient mailClient) {
// Given
user = new User("Jerry", 12);
when(userRepository.insert(any(User.class))).then(new Answer<User>() {
int sequence = 1;
@Override
public User answer(InvocationOnMock invocation) throws Throwable {
User user = (User) invocation.getArgument(0);
user.setId(sequence++);
return user;
}
});
// When
User insertedUser = userService.register(user);
// Then
verify(userRepository).insert(user);
Assertions.assertNotNull(user.getId());
verify(mailClient).sendUserRegistrationMail(insertedUser);
}
@Test
void givenShortName_whenSaveUser_thenGiveShortUsernameError() {
// Given
user = new User("tom", 12);
// When
try {
userService.register(user);
fail("Should give an error");
} catch(Exception ex) {
assertEquals(ex.getMessage(), Errors.USER_NAME_SHORT);
}
// Then
verify(userRepository, never()).insert(user);
}
@Test
void givenSmallAge_whenSaveUser_thenGiveYoungUserError() {
// Given
user = new User("jerry", 3);
// When
try {
userService.register(user);
fail("Should give an error");
} catch(Exception ex) {
assertEquals(ex.getMessage(), Errors.USER_AGE_YOUNG);
}
// Then
verify(userRepository, never()).insert(user);
}
@Test
void givenUserWithExistingName_whenSaveUser_thenGiveUsernameAlreadyExistsError() {
// Given
user = new User("jerry", 12);
Mockito.reset(userRepository);
when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(true);
// When
try {
userService.register(user);
fail("Should give an error");
} catch(Exception ex) {
assertEquals(ex.getMessage(), Errors.USER_NAME_DUPLICATE);
}
// Then
verify(userRepository, never()).insert(user);
}
}

View File

@ -1,6 +1,6 @@
<?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">
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>
@ -105,6 +105,13 @@
</executions>
</plugin>
<!-- /Neuroph -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
@ -326,6 +333,11 @@
<artifactId>datanucleus-xml</artifactId>
<version>5.0.0-release</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-jdo-query</artifactId>
<version>5.0.2</version>
</dependency>
<dependency>
<groupId>net.openhft</groupId>
<artifactId>chronicle</artifactId>
@ -546,29 +558,29 @@
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava-java8</artifactId>
<version>4.7</version>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava-quickcheck</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava-java-core</artifactId>
<version>4.7</version>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava-java8</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>${cache.version}</version>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava-quickcheck</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava-java-core</artifactId>
<version>4.7</version>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>${cache.version}</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
@ -581,7 +593,7 @@
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>com.netopyr.wurmloch</groupId>
<groupId>com.netopyr.wurmloch</groupId>
<artifactId>wurmloch-crdt</artifactId>
<version>${crdt.version}</version>
</dependency>
@ -600,6 +612,21 @@
<artifactId>caffeine</artifactId>
<version>${caffeine.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.58</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.58</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.58</version>
</dependency>
</dependencies>
<repositories>
<repository>

View File

@ -0,0 +1,111 @@
package com.baeldung.bouncycastle;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSAlgorithm;
import org.bouncycastle.cms.CMSEnvelopedData;
import org.bouncycastle.cms.CMSEnvelopedDataGenerator;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSTypedData;
import org.bouncycastle.cms.KeyTransRecipientInformation;
import org.bouncycastle.cms.RecipientInformation;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder;
import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient;
import org.bouncycastle.cms.jcajce.JceKeyTransRecipient;
import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.OutputEncryptor;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.Store;
public class BouncyCastleCrypto {
public static byte[] signData(byte[] data, final X509Certificate signingCertificate, final PrivateKey signingKey)
throws CertificateEncodingException, OperatorCreationException, CMSException, IOException {
byte[] signedMessage = null;
List<X509Certificate> certList = new ArrayList<X509Certificate>();
CMSTypedData cmsData = new CMSProcessableByteArray(data);
certList.add(signingCertificate);
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator cmsGenerator = new CMSSignedDataGenerator();
ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(signingKey);
cmsGenerator.addSignerInfoGenerator(
new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build())
.build(contentSigner, signingCertificate));
cmsGenerator.addCertificates(certs);
CMSSignedData cms = cmsGenerator.generate(cmsData, true);
signedMessage = cms.getEncoded();
return signedMessage;
}
public static boolean verifSignData(final byte[] signedData)
throws CMSException, IOException, OperatorCreationException, CertificateException {
ByteArrayInputStream bIn = new ByteArrayInputStream(signedData);
ASN1InputStream aIn = new ASN1InputStream(bIn);
CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
aIn.close();
bIn.close();
Store certs = s.getCertificates();
SignerInformationStore signers = s.getSignerInfos();
Collection<SignerInformation> c = signers.getSigners();
SignerInformation signer = c.iterator().next();
Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID());
Iterator<X509CertificateHolder> certIt = certCollection.iterator();
X509CertificateHolder certHolder = certIt.next();
boolean verifResult = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder));
if (!verifResult) {
return false;
}
return true;
}
public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate)
throws CertificateEncodingException, CMSException, IOException {
byte[] encryptedData = null;
if (null != data && null != encryptionCertificate) {
CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator();
JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate);
cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey);
CMSTypedData msg = new CMSProcessableByteArray(data);
OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC")
.build();
CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor);
encryptedData = cmsEnvelopedData.getEncoded();
}
return encryptedData;
}
public static byte[] decryptData(final byte[] encryptedData, final PrivateKey decryptionKey) throws CMSException {
byte[] decryptedData = null;
if (null != encryptedData && null != decryptionKey) {
CMSEnvelopedData envelopedData = new CMSEnvelopedData(encryptedData);
Collection<RecipientInformation> recip = envelopedData.getRecipientInfos().getRecipients();
KeyTransRecipientInformation recipientInfo = (KeyTransRecipientInformation) recip.iterator().next();
JceKeyTransRecipient recipient = new JceKeyTransEnvelopedRecipient(decryptionKey);
decryptedData = recipientInfo.getContent(recipient);
}
return decryptedData;
}
}

View File

@ -0,0 +1,104 @@
package com.baeldung.jdo.query;
import java.util.List;
import javax.jdo.JDOQLTypedQuery;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
import org.datanucleus.metadata.PersistenceUnitMetaData;
public class MyApp {
private static PersistenceManagerFactory pmf;
private static PersistenceManager pm;
public static void main(String[] args) {
defineDynamicPersistentUnit();
createTestData();
queryUsingJDOQL();
queryUsingTypedJDOQL();
queryUsingSQL();
queryUsingJPQL();
}
public static void createTestData(){
ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut",5);
ProductItem item2 = new ProductItem("pro2", "price less than 10","InStock", 8);
ProductItem item3 = new ProductItem("pro3", "price more than 10","SoldOut", 15);
if( pm != null ){
pm.makePersistent(item1);
pm.makePersistent(item2);
pm.makePersistent(item3);
}
}
public static void defineDynamicPersistentUnit(){
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:mysql://localhost:3306/jdo_db");
pumd.addProperty("javax.jdo.option.ConnectionUserName", "root");
pumd.addProperty("javax.jdo.option.ConnectionPassword", "admin");
pumd.addProperty("javax.jdo.option.ConnectionDriverName", "com.mysql.jdbc.Driver");
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
pmf = new JDOPersistenceManagerFactory(pumd, null);
pm = pmf.getPersistenceManager();
}
public static void queryUsingJDOQL(){
Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem "
+ "WHERE price < threshold PARAMETERS double threshold");
List<ProductItem> explicitParamResults = (List<ProductItem>)query.execute(10);
query = pm.newQuery("SELECT FROM "
+ "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
query.setParameters("double threshold");
List<ProductItem> explicitParamResults2 = (List<ProductItem>)query.execute(10);
query = pm.newQuery("SELECT FROM "
+ "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
List<ProductItem> implicitParamResults = (List<ProductItem>)query.execute(10);
}
public static void queryUsingTypedJDOQL(){
JDOQLTypedQuery<ProductItem> tq = pm.newJDOQLTypedQuery(ProductItem.class);
QProductItem cand = QProductItem.candidate();
tq=tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro")));
List<ProductItem> results = tq.executeList();
}
public static void queryUsingSQL(){
Query query = pm.newQuery("javax.jdo.query.SQL","select * from "
+ "product_item where price < ? and status = ?");
query.setClass(ProductItem.class);
query.setParameters(10,"InStock");
List<ProductItem> results = query.executeList();
}
public static void queryUsingJPQL(){
Query query = pm.newQuery("JPQL","select i from "
+ "com.baeldung.jdo.query.ProductItem i where i.price < 10"
+ " and i.status = 'InStock'");
List<ProductItem> results = (List<ProductItem>) query.execute();
}
public static void namedQuery(){
Query<ProductItem> query = pm.newNamedQuery(
ProductItem.class, "PriceBelow10");
List<ProductItem> results = query.executeList();
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.jdo.query;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceAware;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
@PersistenceCapable(table = "product_item")
public class ProductItem {
@PrimaryKey
@Persistent(valueStrategy=IdGeneratorStrategy.INCREMENT)
int id;
String name;
String description;
String status;
double price;
public ProductItem(){
}
public ProductItem(String name,String description,String status,double price){
this.name=name;
this.description = description;
this.status = status;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}

View File

@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDPjCCAiagAwIBAgIJAPvd1gx14C3CMA0GCSqGSIb3DQEBBQUAMEcxCzAJBgNV
BAYTAk1BMRAwDgYDVQQIEwdNb3JvY2NvMRMwEQYDVQQHEwpDYXNhYmxhbmNhMREw
DwYDVQQDEwhCYWVsZHVuZzAeFw0xNzEwMTIxMDQzMTRaFw0yNzEwMTMxMDQzMTRa
MEcxCzAJBgNVBAYTAk1BMRAwDgYDVQQIEwdNb3JvY2NvMRMwEQYDVQQHEwpDYXNh
YmxhbmNhMREwDwYDVQQDEwhCYWVsZHVuZzCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBAMyi5GmOeN4QaH/CP5gSOyHX8znb5TDHWV8wc+ZT7kNU8zt5tGMh
jozK6hax155/6tOsBDR0rSYBhL+Dm/+uCVS7qOlRHhf6cNGtzGF1gnNJB2WjI8oM
AYm24xpLj1WphKUwKrn3nTMPnQup5OoNAMYl99flANrRYVjjxrLQvDZDUio6Iujr
CZ2TtXGM0g/gP++28KT7g1KlUui3xtB0u33wx7UN8Fix3JmjOaPHGwxGpwP3VGSj
fs8cuhqVwRQaZpCOoHU/P8wpXKw80sSdhz+SRueMPtVYqK0CiLL5/O0h0Y3le4IV
whgg3KG1iTGOWn60UMFn1EYmQ18k5Nsma6UCAwEAAaMtMCswCQYDVR0TBAIwADAR
BglghkgBhvhCAQEEBAMCBPAwCwYDVR0PBAQDAgUgMA0GCSqGSIb3DQEBBQUAA4IB
AQC8DDBmJ3p4xytxBiE0s4p1715WT6Dm/QJHp0XC0hkSoyZKDh+XVmrzm+J3SiW1
vpswb5hLgPo040YX9jnDmgOD+TpleTuKHxZRYj92UYWmdjkWLVtFMcvOh+gxBiAP
pHIqZsqo8lfcyAuh8Jx834IXbknfCUtERDLG/rU9P/3XJhrM2GC5qPQznrW4EYhU
CGPyIJXmvATMVvXMWCtfogAL+n42vjYXQXZoAWomHhLHoNbSJUErnNdWDOh4WoJt
XJCxA6U5LSBplqb3wB2hUTqw+0admKltvmy+KA1PD7OxoGiY7V544zeGqJam1qxU
ia7y5BL6uOa/4ShSV8pcJDYz
-----END CERTIFICATE-----

Binary file not shown.

View File

@ -16,6 +16,14 @@
</field>
</class>
</package>
<package name="com.baeldung.jdo.query">
<class name="ProductItem" detachable="true" table="product_item">
<query name="PriceBelow10" language="javax.jdo.query.SQL">
<![CDATA[SELECT * FROM PRODUCT_ITEM WHERE PRICE < 10
]]></query>
</class>
</package>
</jdo>

View File

@ -0,0 +1,53 @@
package com.baeldung.bouncycastle;
import static org.junit.Assert.assertTrue;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.OperatorCreationException;
import org.junit.Test;
public class BouncyCastleLiveTest {
String certificatePath = "src/main/resources/Baeldung.cer";
String privateKeyPath = "src/main/resources/Baeldung.p12";
char[] p12Password = "password".toCharArray();
char[] keyPassword = "password".toCharArray();
@Test
public void givenCryptographicResource_whenOperationSuccess_returnTrue()
throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException,
KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException {
Security.addProvider(new BouncyCastleProvider());
CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC");
X509Certificate certificate = (X509Certificate) certFactory
.generateCertificate(new FileInputStream(certificatePath));
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(new FileInputStream(privateKeyPath), p12Password);
PrivateKey privateKey = (PrivateKey) keystore.getKey("baeldung", keyPassword);
String secretMessage = "My password is 123456Seven";
System.out.println("Original Message : " + secretMessage);
byte[] stringToEncrypt = secretMessage.getBytes();
byte[] encryptedData = BouncyCastleCrypto.encryptData(stringToEncrypt, certificate);
byte[] rawData = BouncyCastleCrypto.decryptData(encryptedData, privateKey);
String decryptedMessage = new String(rawData);
assertTrue(decryptedMessage.equals(secretMessage));
byte[] signedData = BouncyCastleCrypto.signData(rawData, certificate, privateKey);
Boolean check = BouncyCastleCrypto.verifSignData(signedData);
assertTrue(check);
}
}

View File

@ -0,0 +1,62 @@
package org.baeldung.mockito;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import org.mockito.ArgumentCaptor;
import static org.mockito.Matchers.any;
import org.mockito.stubbing.Answer;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class MockitoVoidMethodsTest {
@Test
public void whenAddCalledVerified() {
MyList mockVoid = mock(MyList.class);
mockVoid.add(0, "");
verify(mockVoid, times(1)).add(0, "");
}
@Test(expected = Exception.class)
public void givenNull_addThrows() {
MyList mockVoid = mock(MyList.class);
doThrow().when(mockVoid).add(isA(Integer.class), isNull());
mockVoid.add(0, null);
}
@Test
public void whenAddCalledValueCaptured() {
MyList mockVoid = mock(MyList.class);
ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class);
doNothing().when(mockVoid).add(any(Integer.class), valueCapture.capture());
mockVoid.add(0, "captured");
assertEquals("captured", valueCapture.getValue());
}
@Test
public void whenAddCalledAnswered() {
MyList mockVoid = mock(MyList.class);
doAnswer((Answer<Void>) invocation -> {
Object arg0 = invocation.getArgument(0);
Object arg1 = invocation.getArgument(1);
//do something with the arguments here
assertEquals(3, arg0);
assertEquals("answer me", arg1);
return null;
}).when(mockVoid).add(any(Integer.class), any(String.class));
mockVoid.add(3, "answer me");
}
@Test
public void whenAddCalledRealMethodCalled() {
MyList mockVoid = mock(MyList.class);
doCallRealMethod().when(mockVoid).add(any(Integer.class), any(String.class));
mockVoid.add(1, "real");
verify(mockVoid, times(1)).add(1, "real");
}
}

View File

@ -14,4 +14,9 @@ class MyList extends AbstractList<String> {
return 1;
}
@Override
public void add(int index, String element) {
// no-op
}
}

149
spring-boot/.factorypath Normal file
View File

@ -0,0 +1,149 @@
<factorypath>
<factorypathentry kind="VARJAR" id="M2_REPO/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/javax/transaction/javax.transaction-api/1.2/javax.transaction-api-1.2.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/javax/servlet/javax.servlet-api/3.1.0/javax.servlet-api-3.1.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/javax/activation/activation/1.1.1/activation-1.1.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/javax/mail/mail/1.4.4/mail-1.4.4.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-starter-thymeleaf/1.5.3.RELEASE/spring-boot-starter-thymeleaf-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-starter/1.5.3.RELEASE/spring-boot-starter-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot/1.5.3.RELEASE/spring-boot-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-core/4.3.4.RELEASE/spring-core-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-context/4.3.4.RELEASE/spring-context-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-aop/4.3.4.RELEASE/spring-aop-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-beans/4.3.4.RELEASE/spring-beans-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-expression/4.3.4.RELEASE/spring-expression-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-autoconfigure/1.5.3.RELEASE/spring-boot-autoconfigure-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-starter-logging/1.5.3.RELEASE/spring-boot-starter-logging-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/ch/qos/logback/logback-classic/1.1.11/logback-classic-1.1.11.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/ch/qos/logback/logback-core/1.1.11/logback-core-1.1.11.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/slf4j/jcl-over-slf4j/1.7.25/jcl-over-slf4j-1.7.25.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/slf4j/jul-to-slf4j/1.7.25/jul-to-slf4j-1.7.25.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/slf4j/log4j-over-slf4j/1.7.25/log4j-over-slf4j-1.7.25.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/yaml/snakeyaml/1.17/snakeyaml-1.17.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-starter-web/1.5.3.RELEASE/spring-boot-starter-web-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-starter-tomcat/1.5.3.RELEASE/spring-boot-starter-tomcat-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/tomcat/embed/tomcat-embed-core/8.5.14/tomcat-embed-core-8.5.14.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/tomcat/embed/tomcat-embed-el/8.5.14/tomcat-embed-el-8.5.14.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/tomcat/embed/tomcat-embed-websocket/8.5.14/tomcat-embed-websocket-8.5.14.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/hibernate/hibernate-validator/5.3.5.Final/hibernate-validator-5.3.5.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/jboss/logging/jboss-logging/3.3.1.Final/jboss-logging-3.3.1.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/fasterxml/classmate/1.3.3/classmate-1.3.3.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/fasterxml/jackson/core/jackson-databind/2.8.8/jackson-databind-2.8.8.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/fasterxml/jackson/core/jackson-annotations/2.8.0/jackson-annotations-2.8.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/fasterxml/jackson/core/jackson-core/2.8.8/jackson-core-2.8.8.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-web/4.3.4.RELEASE/spring-web-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-webmvc/4.3.4.RELEASE/spring-webmvc-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/thymeleaf/thymeleaf-spring4/2.1.5.RELEASE/thymeleaf-spring4-2.1.5.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/thymeleaf/thymeleaf/2.1.5.RELEASE/thymeleaf-2.1.5.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/ognl/ognl/3.0.8/ognl-3.0.8.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/javassist/javassist/3.21.0-GA/javassist-3.21.0-GA.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/unbescape/unbescape/1.1.0.RELEASE/unbescape-1.1.0.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/nz/net/ultraq/thymeleaf/thymeleaf-layout-dialect/1.4.0/thymeleaf-layout-dialect-1.4.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/codehaus/groovy/groovy/2.4.10/groovy-2.4.10.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-starter-data-jpa/1.5.3.RELEASE/spring-boot-starter-data-jpa-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-starter-aop/1.5.3.RELEASE/spring-boot-starter-aop-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/aspectj/aspectjweaver/1.8.10/aspectjweaver-1.8.10.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-starter-jdbc/1.5.3.RELEASE/spring-boot-starter-jdbc-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/tomcat/tomcat-jdbc/8.5.14/tomcat-jdbc-8.5.14.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/tomcat/tomcat-juli/8.5.14/tomcat-juli-8.5.14.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-jdbc/4.3.4.RELEASE/spring-jdbc-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-tx/4.3.4.RELEASE/spring-tx-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/hibernate/hibernate-core/5.0.12.Final/hibernate-core-5.0.12.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/antlr/antlr/2.7.7/antlr-2.7.7.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/jboss/jandex/2.0.0.Final/jandex-2.0.0.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/hibernate/common/hibernate-commons-annotations/5.0.1.Final/hibernate-commons-annotations-5.0.1.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/hibernate/hibernate-entitymanager/5.0.12.Final/hibernate-entitymanager-5.0.12.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/data/spring-data-jpa/1.11.3.RELEASE/spring-data-jpa-1.11.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/data/spring-data-commons/1.13.3.RELEASE/spring-data-commons-1.13.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-orm/4.3.4.RELEASE/spring-orm-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-aspects/4.3.4.RELEASE/spring-aspects-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-starter-actuator/1.5.3.RELEASE/spring-boot-starter-actuator-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-actuator/1.5.3.RELEASE/spring-boot-actuator-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-starter-security/1.5.3.RELEASE/spring-boot-starter-security-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/security/spring-security-config/4.2.2.RELEASE/spring-security-config-4.2.2.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/security/spring-security-core/4.2.2.RELEASE/spring-security-core-4.2.2.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/security/spring-security-web/4.2.2.RELEASE/spring-security-web-4.2.2.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/graphql-java/graphql-spring-boot-starter/3.6.0/graphql-spring-boot-starter-3.6.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/graphql-java/graphql-spring-boot-autoconfigure/3.6.0/graphql-spring-boot-autoconfigure-3.6.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-configuration-processor/1.5.3.RELEASE/spring-boot-configuration-processor-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/vaadin/external/google/android-json/0.0.20131108.vaadin1/android-json-0.0.20131108.vaadin1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/graphql-java/graphql-java-servlet/4.2.0/graphql-java-servlet-4.2.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/google/guava/guava/18.0/guava-18.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/commons-fileupload/commons-fileupload/1.3.1/commons-fileupload-1.3.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/commons-io/commons-io/2.2/commons-io-2.2.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/graphql-java/graphql-java/3.0.0/graphql-java-3.0.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/antlr/antlr4-runtime/4.5.1/antlr4-runtime-4.5.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/fasterxml/jackson/datatype/jackson-datatype-jdk8/2.8.8/jackson-datatype-jdk8-2.8.8.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/graphql-java/graphiql-spring-boot-starter/3.6.0/graphiql-spring-boot-starter-3.6.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/graphql-java/graphiql-spring-boot-autoconfigure/3.6.0/graphiql-spring-boot-autoconfigure-3.6.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/graphql-java/graphql-java-tools/3.2.0/graphql-java-tools-3.2.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/jetbrains/kotlin/kotlin-stdlib/1.1.3-2/kotlin-stdlib-1.1.3-2.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/jetbrains/annotations/13.0/annotations-13.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/fasterxml/jackson/module/jackson-module-kotlin/2.8.8/jackson-module-kotlin-2.8.8.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/jetbrains/kotlin/kotlin-reflect/1.1.1/kotlin-reflect-1.1.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/esotericsoftware/reflectasm/1.11.3/reflectasm-1.11.3.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/ow2/asm/asm/5.0.4/asm-5.0.4.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/ru/vyarus/generics-resolver/2.0.1/generics-resolver-2.0.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-starter-test/1.5.3.RELEASE/spring-boot-starter-test-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-test/1.5.3.RELEASE/spring-boot-test-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-test-autoconfigure/1.5.3.RELEASE/spring-boot-test-autoconfigure-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/jayway/jsonpath/json-path/2.2.0/json-path-2.2.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/net/minidev/json-smart/2.2.1/json-smart-2.2.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/net/minidev/accessors-smart/1.1/accessors-smart-1.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/junit/junit/4.12/junit-4.12.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/assertj/assertj-core/2.6.0/assertj-core-2.6.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/mockito/mockito-core/1.10.19/mockito-core-1.10.19.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/objenesis/objenesis/2.1/objenesis-2.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/hamcrest/hamcrest-library/1.3/hamcrest-library-1.3.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/skyscreamer/jsonassert/1.4.0/jsonassert-1.4.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-test/4.3.4.RELEASE/spring-test-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/io/dropwizard/metrics/metrics-core/3.1.4/metrics-core-3.1.4.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/h2database/h2/1.4.194/h2-1.4.194.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/boot/spring-boot-starter-mail/1.5.3.RELEASE/spring-boot-starter-mail-1.5.3.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-context-support/4.3.4.RELEASE/spring-context-support-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/sun/mail/javax.mail/1.5.6/javax.mail-1.5.6.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/subethamail/subethasmtp/3.1.7/subethasmtp-3.1.7.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/com/google/code/findbugs/jsr305/1.3.9/jsr305-1.3.9.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/webjars/bootstrap/3.3.7-1/bootstrap-3.3.7-1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/webjars/jquery/3.1.1/jquery-3.1.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/tomcat/tomcat-servlet-api/8.5.11/tomcat-servlet-api-8.5.11.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/mysql/mysql-connector-java/6.0.6/mysql-connector-java-6.0.6.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-websocket/4.3.4.RELEASE/spring-websocket-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/springframework/spring-messaging/4.3.4.RELEASE/spring-messaging-4.3.4.RELEASE.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/togglz/togglz-spring-boot-starter/2.4.1.Final/togglz-spring-boot-starter-2.4.1.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/togglz/togglz-core/2.4.1.Final/togglz-core-2.4.1.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/togglz/togglz-spring-core/2.4.1.Final/togglz-spring-core-2.4.1.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/togglz/togglz-spring-web/2.4.1.Final/togglz-spring-web-2.4.1.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/togglz/togglz-servlet/2.4.1.Final/togglz-servlet-2.4.1.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/togglz/togglz-spring-security/2.4.1.Final/togglz-spring-security-2.4.1.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/activemq/artemis-server/1.5.4/artemis-server-1.5.4.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/activemq/artemis-commons/1.5.4/artemis-commons-1.5.4.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/io/netty/netty-all/4.1.5.Final/netty-all-4.1.5.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/commons-beanutils/commons-beanutils/1.9.3/commons-beanutils-1.9.3.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/activemq/artemis-selector/1.5.4/artemis-selector-1.5.4.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/activemq/artemis-journal/1.5.4/artemis-journal-1.5.4.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/activemq/artemis-native/1.5.4/artemis-native-1.5.4.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/activemq/artemis-jdbc-store/1.5.4/artemis-jdbc-store-1.5.4.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/activemq/artemis-core-client/1.5.4/artemis-core-client-1.5.4.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/jgroups/jgroups/3.6.9.Final/jgroups-3.6.9.Final.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/geronimo/specs/geronimo-json_1.0_spec/1.0-alpha-1/geronimo-json_1.0_spec-1.0-alpha-1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/johnzon/johnzon-core/0.9.5/johnzon-core-0.9.5.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/io/rest-assured/rest-assured/3.0.1/rest-assured-3.0.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/codehaus/groovy/groovy-xml/2.4.10/groovy-xml-2.4.10.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/httpcomponents/httpclient/4.5.3/httpclient-4.5.3.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/httpcomponents/httpcore/4.4.6/httpcore-4.4.6.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/commons-codec/commons-codec/1.10/commons-codec-1.10.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/httpcomponents/httpmime/4.5.3/httpmime-4.5.3.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/ccil/cowan/tagsoup/tagsoup/1.2.1/tagsoup-1.2.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/io/rest-assured/json-path/3.0.1/json-path-3.0.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/codehaus/groovy/groovy-json/2.4.10/groovy-json-2.4.10.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/io/rest-assured/rest-assured-common/3.0.1/rest-assured-common-3.0.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/org/apache/commons/commons-lang3/3.4/commons-lang3-3.4.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="VARJAR" id="M2_REPO/io/rest-assured/xml-path/3.0.1/xml-path-3.0.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="PLUGIN" id="org.eclipse.jst.ws.annotations.core" enabled="true" runInBatchMode="false"/>
</factorypath>

View File

@ -2,3 +2,4 @@
.settings/
.classpath
.project
/.apt_generated/

View File

@ -24,7 +24,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
@ -170,6 +173,17 @@
<artifactId>artemis-server</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.keycloak.bom</groupId>
<artifactId>keycloak-adapter-bom</artifactId>
<version>3.3.0.CR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<finalName>spring-boot</finalName>

View File

@ -0,0 +1,42 @@
package com.baeldung.keycloak;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String serviceRendered;
private String address;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getServiceRendered() {
return serviceRendered;
}
public void setServiceRendered(String serviceRendered) {
this.serviceRendered = serviceRendered;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.keycloak;
import org.springframework.data.repository.CrudRepository;
public interface CustomerDAO extends CrudRepository<Customer, Long> {
}

View File

@ -0,0 +1,52 @@
package com.baeldung.keycloak;
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.keycloak.adapters.springsecurity.KeycloakSecurityComponents;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
// Submits the KeycloakAuthenticationProvider to the AuthenticationManager
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Bean
public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
// Specifies the session authentication strategy
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/customers*")
.hasRole("user")
.anyRequest()
.permitAll();
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.keycloak;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBoot {
public static void main(String[] args) {
SpringApplication.run(SpringBoot.class, args);
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.keycloak;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
@Controller
public class WebController {
@Autowired
private CustomerDAO customerDAO;
@GetMapping(path = "/")
public String index() {
return "external";
}
@GetMapping(path = "/customers")
public String customers(Principal principal, Model model) {
addCustomers();
Iterable<Customer> customers = customerDAO.findAll();
model.addAttribute("customers", customers);
model.addAttribute("username", principal.getName());
return "customers";
}
// add customers for demonstration
public void addCustomers() {
Customer customer1 = new Customer();
customer1.setAddress("1111 foo blvd");
customer1.setName("Foo Industries");
customer1.setServiceRendered("Important services");
customerDAO.save(customer1);
Customer customer2 = new Customer();
customer2.setAddress("2222 bar street");
customer2.setName("Bar LLP");
customer2.setServiceRendered("Important services");
customerDAO.save(customer2);
Customer customer3 = new Customer();
customer3.setAddress("33 main street");
customer3.setName("Big LLC");
customer3.setServiceRendered("Important services");
customerDAO.save(customer3);
}
}

View File

@ -49,3 +49,10 @@ contactInfoType=email
endpoints.beans.id=springbeans
endpoints.beans.sensitive=false
#Keycloak Configuration
keycloak.auth-server-url=http://localhost:8180/auth
keycloak.realm=SpringBootKeycloak
keycloak.resource=login-app
keycloak.public-client=true
keycloak.principal-attribute=preferred_username

View File

@ -0,0 +1,33 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:include="layout :: headerFragment">
</head>
<body>
<div id="container">
<h1>
Hello, <span th:text="${username}">--name--</span>.
</h1>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Service Rendered</th>
</tr>
</thead>
<tbody>
<tr th:each="customer : ${customers}">
<td th:text="${customer.id}">Text ...</td>
<td th:text="${customer.name}">Text ...</td>
<td th:text="${customer.address}">Text ...</td>
<td th:text="${customer.serviceRendered}">Text...</td>
</tr>
</tbody>
</table>
<div id="pagefoot" th:include="layout :: footerFragment">Footer
</div>
</div>
<!-- container -->
</body>
</html>

View File

@ -0,0 +1,31 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:include="layout :: headerFragment">
</head>
<body>
<div class="container">
<div class="jumbotron text-center">
<h1>Customer Portal</h1>
</div>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam
erat lectus, vehicula feugiat ultricies at, tempus sed ante. Cras
arcu erat, lobortis vitae quam et, mollis pharetra odio. Nullam sit
amet congue ipsum. Nunc dapibus odio ut ligula venenatis porta non
id dui. Duis nec tempor tellus. Suspendisse id blandit ligula, sit
amet varius mauris. Nulla eu eros pharetra, tristique dui quis,
vehicula libero. Aenean a neque sit amet tellus porttitor rutrum nec
at leo.</p>
<h2>Existing Customers</h2>
<div class="well">
<b>Enter the intranet: </b><a th:href="@{/customers}">customers</a>
</div>
</div>
<div id="pagefoot" th:include="layout :: footerFragment">Footer
</div>
</div>
<!-- container -->
</body>
</html>

View File

@ -0,0 +1,18 @@
<head th:fragment="headerFragment">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Customer Portal</title>
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous"></link>
<link
href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"
rel="stylesheet"></link>
</head>
<div id="pagefoot" th:fragment="footerFragment">
<p>Document last modified 2017/10/23.</p>
<p>Copyright: Lorem Ipsum</p>
</div>

View File

@ -0,0 +1,53 @@
package com.baeldung.keycloak;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.adapters.springboot.client.KeycloakSecurityContextClientRequestInterceptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringBoot.class)
public class KeycloakConfigurationTest {
@Spy
private KeycloakSecurityContextClientRequestInterceptor factory;
private MockHttpServletRequest servletRequest;
@Mock
public KeycloakSecurityContext keycloakSecurityContext;
@Mock
private KeycloakPrincipal keycloakPrincipal;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
servletRequest = new MockHttpServletRequest();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(servletRequest));
servletRequest.setUserPrincipal(keycloakPrincipal);
when(keycloakPrincipal.getKeycloakSecurityContext()).thenReturn(keycloakSecurityContext);
}
@Test
public void testGetKeycloakSecurityContext() throws Exception {
assertNotNull(keycloakPrincipal.getKeycloakSecurityContext());
}
}

View File

@ -37,5 +37,38 @@
<artifactId>spring-integration-groovy</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<compilerId>groovy-eclipse-compiler</compilerId>
<verbose>true</verbose>
<source>1.8</source>
<target>1.8</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-compiler</artifactId>
<version>2.9.2-01</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-batch</artifactId>
<version>2.4.3-01</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,17 @@
package com.baeldug.groovyconfig;
import java.util.ArrayList;
import java.util.List;
public class BandsBean {
private List<String> bandsList = new ArrayList<>();
public List<String> getBandsList() {
return bandsList;
}
public void setBandsList(List<String> bandsList) {
this.bandsList = bandsList;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldug.groovyconfig;
beans {
javaPesronBean(JavaPersonBean) {
firstName = 'John'
lastName = 'Doe'
age ='32'
eyesColor = 'blue'
hairColor='black'
}
bandsBean(BandsBean) { bean->
bean.scope = "singleton"
bandsList=['Nirvana', 'Pearl Jam', 'Foo Fighters']
}
registerAlias("bandsBean","bands")
}

View File

@ -0,0 +1,21 @@
package com.baeldug.groovyconfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JavaBeanConfig {
@Bean
public JavaPersonBean javaPerson() {
JavaPersonBean jPerson = new JavaPersonBean();
jPerson.setFirstName("John");
jPerson.setLastName("Doe");
jPerson.setAge("31");
jPerson.setEyesColor("green");
jPerson.setHairColor("blond");
return jPerson;
}
}

View File

@ -0,0 +1,57 @@
package com.baeldug.groovyconfig;
public class JavaPersonBean {
public String jj;
private String firstName;
private String lastName;
private String age;
private String eyesColor;
private String hairColor;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getEyesColor() {
return eyesColor;
}
public void setEyesColor(String eyesColor) {
this.eyesColor = eyesColor;
}
public String getHairColor() {
return hairColor;
}
public void setHairColor(String hairColor) {
this.hairColor = hairColor;
}
}

View File

@ -0,0 +1,12 @@
<?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.xsd">
<bean id="JavaPersonBean" class="com.baeldug.groovyconfig.JavaPersonBean">
<property name="firstName" value="John" />
<property name="LastName" value="Doe" />
<property name="age" value="30" />
<property name="eyesColor" value="brown" />
<property name="hairColor" value="brown" />
</bean>
</beans>

View File

@ -0,0 +1,50 @@
package com.baeldug.groovyconfig;
import static org.junit.Assert.assertEquals;
import java.io.File;
import org.junit.Test;
import org.springframework.context.support.GenericGroovyApplicationContext;
public class GroovyConfigurationTest {
private static final String FILE_NAME = "GroovyBeanConfig.groovy";
private static final String FILE_PATH = "src/main/java/com/baeldug/groovyconfig/";
@Test
public void whenGroovyConfig_thenCorrectPerson() throws Exception {
GenericGroovyApplicationContext ctx = new GenericGroovyApplicationContext();
ctx.load("file:" + getPathPart() + FILE_NAME);
ctx.refresh();
JavaPersonBean j = ctx.getBean(JavaPersonBean.class);
assertEquals("32", j.getAge());
assertEquals("blue", j.getEyesColor());
assertEquals("black", j.getHairColor());
}
@Test
public void whenGroovyConfig_thenCorrectListLength() throws Exception {
GenericGroovyApplicationContext ctx = new GenericGroovyApplicationContext();
ctx.load("file:" + getPathPart() + FILE_NAME);
ctx.refresh();
BandsBean bb = ctx.getBean(BandsBean.class);
assertEquals(3, bb.getBandsList()
.size());
}
private String getPathPart() {
String pathPart = new File(".").getAbsolutePath();
pathPart = pathPart.replace(".", "");
pathPart = pathPart.replace("\\", "/");
pathPart = pathPart + FILE_PATH;
return pathPart;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldug.groovyconfig;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class JavaConfigurationTest {
@Test
public void whenJavaConfig_thenCorrectPerson() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(JavaBeanConfig.class);
ctx.refresh();
JavaPersonBean j = ctx.getBean(JavaPersonBean.class);
assertEquals("31", j.getAge());
assertEquals("green", j.getEyesColor());
assertEquals("blond", j.getHairColor());
}
}

View File

@ -0,0 +1,23 @@
package com.baeldug.groovyconfig;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlConfigurationTest {
@Test
public void whenXmlConfig_thenCorrectPerson() {
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("xml-bean-config.xml");
JavaPersonBean j = (JavaPersonBean) applicationContext.getBean("JavaPersonBean");
assertEquals("30", j.getAge());
assertEquals("brown", j.getEyesColor());
assertEquals("brown", j.getHairColor());
}
}

View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
Class-Path:

View File

@ -14,6 +14,7 @@
- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource)
- [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate)
- [Self-Contained Testing Using an In-Memory Database](http://www.baeldung.com/spring-jpa-test-in-memory-database)
- [Spring Data JPA Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories)
### Eclipse Config
After importing the project into Eclipse, you may see the following error: