Merge branch 'master' of https://github.com/ahmedtawila/tutorials
This commit is contained in:
@@ -3,7 +3,8 @@ package com.baeldung.concurrent.daemon;
|
||||
public class NewThread extends Thread {
|
||||
|
||||
public void run() {
|
||||
for (int i = 0; i < 10; i++)
|
||||
System.out.println("New Thread is running...");
|
||||
while (true)
|
||||
for (int i = 0; i < 10; i++)
|
||||
System.out.println("New Thread is running...");
|
||||
}
|
||||
}
|
||||
|
||||
-5
@@ -25,9 +25,4 @@ public class DaemonThreadTest {
|
||||
daemonThread.start();
|
||||
daemonThread.setDaemon(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserThread_whenStartThread_thenFalse() {
|
||||
NewThread daemonThread = new NewThread();
|
||||
}
|
||||
}
|
||||
|
||||
+8
@@ -4,6 +4,8 @@ import com.forketyfork.guest.springmvc.model.LoginData;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import java.util.Collections;
|
||||
@@ -28,4 +30,10 @@ public class InternalsController {
|
||||
}
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@PostMapping("/message")
|
||||
public MyOutputResource sendMessage(@RequestBody MyInputResource inputResource) {
|
||||
return new MyOutputResource("Received: " + inputResource.getRequestMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.forketyfork.guest.springmvc.web;
|
||||
|
||||
public class MyInputResource {
|
||||
|
||||
private String requestMessage;
|
||||
|
||||
public String getRequestMessage() {
|
||||
return requestMessage;
|
||||
}
|
||||
|
||||
public void setRequestMessage(String requestMessage) {
|
||||
this.requestMessage = requestMessage;
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.forketyfork.guest.springmvc.web;
|
||||
|
||||
public class MyOutputResource {
|
||||
|
||||
private String responseMessage;
|
||||
|
||||
public MyOutputResource(String responseMessage) {
|
||||
this.responseMessage = responseMessage;
|
||||
}
|
||||
|
||||
public String getResponseMessage() {
|
||||
return responseMessage;
|
||||
}
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.forketyfork.guest.springmvc.web;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class RestfulWebServiceController {
|
||||
|
||||
@GetMapping("/message")
|
||||
public MyOutputResource getMessage() {
|
||||
return new MyOutputResource("Hello!");
|
||||
}
|
||||
|
||||
}
|
||||
+4
-3
@@ -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>
|
||||
|
||||
@@ -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 + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.junit5.mockito.repository;
|
||||
|
||||
import com.baeldung.junit5.mockito.User;
|
||||
|
||||
public interface MailClient {
|
||||
|
||||
void sendUserRegistrationMail(User user);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.junit5.mockito.repository;
|
||||
|
||||
public interface SettingRepository {
|
||||
|
||||
int getUserMinAge();
|
||||
|
||||
int getUserNameMinLength();
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.junit5.mockito.service;
|
||||
|
||||
import com.baeldung.junit5.mockito.User;
|
||||
|
||||
public interface UserService {
|
||||
|
||||
User register(User user);
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
+43
-21
@@ -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,16 @@
|
||||
<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>bcpkix-jdk15on</artifactId>
|
||||
<version>1.58</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -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.
@@ -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>
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -171,6 +171,7 @@
|
||||
<module>spring-hibernate5</module>
|
||||
<module>spring-integration</module>
|
||||
<module>spring-jersey</module>
|
||||
<module>spring-jmeter-jenkins</module>
|
||||
<module>spring-jms</module>
|
||||
<module>spring-jooq</module>
|
||||
<module>spring-jpa</module>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user