This commit is contained in:
Ahmed Tawila 2017-11-15 22:21:13 +02:00
commit 56c4397f9d
48 changed files with 1776 additions and 32 deletions

View File

@ -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...");
}
}

View File

@ -25,9 +25,4 @@ public class DaemonThreadTest {
daemonThread.start();
daemonThread.setDaemon(true);
}
@Test
public void givenUserThread_whenStartThread_thenFalse() {
NewThread daemonThread = new NewThread();
}
}

View File

@ -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());
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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!");
}
}

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,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>

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

@ -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>

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());
}
}

24
spring-jmeter-jenkins/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

Binary file not shown.

View File

@ -0,0 +1 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip

View File

@ -0,0 +1,55 @@
BASIC CRUD API with Spring Boot
================================
This is the code of a simple API for some CRUD operations realised for a seminar at [FGI](www.fgi-ud.org) using Spring Boot.
### Demo
* API: The online version **is**/**will be** hosted here: https://fgi-tcheck.herokuapp.com
* Mobile version is also opensource and located here: https://github.com/valdesekamdem/tcheck-mobile
### Features
#### Currently Implemented
* CRUD
* Student
#### To DO
* Validations of input with: [Spring Data Rest Validators](http://docs.spring.io/spring-data/rest/docs/2.1.0.RELEASE/reference/html/validation-chapter.html)
### Requirements
- Maven
- JDK 8
- MongoDB
### Running
To build and start the server simply type
```bash
$ mvn clean install
$ mvn spring-boot:run -Dserver.port=8989
```
### Available CRUD
You can see what crud operation are available using curl:
```bash
$ curl localhost:8080
```
You can view existing student objects with this command:
```bash
$ curl localhost:8080/students
```
Or create a new one via a POST:
```bash
$ curl -X POST -H "Content-Type:application/json" -d '{ "firstName" : "Dassi", "lastName" : "Orleando", "phoneNumber": "+237 545454545", "email": "mymail@yahoo.fr" }' localhost:8080/students
```
Now with default configurations it will be available at: [http://localhost:8080](http://localhost:8080)
Enjoy it :)

233
spring-jmeter-jenkins/mvnw vendored Executable file
View File

@ -0,0 +1,233 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
#
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
# for the new JDKs provided by Oracle.
#
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
#
# Oracle JDKs
#
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
#
# Apple JDKs
#
export JAVA_HOME=`/usr/libexec/java_home`
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
local basedir=$(pwd)
local wdir=$(pwd)
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
wdir=$(cd "$wdir/.."; pwd)
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} "$@"

145
spring-jmeter-jenkins/mvnw.cmd vendored Normal file
View File

@ -0,0 +1,145 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
set MAVEN_CMD_LINE_ARGS=%*
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-jmeter-jenkins</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-jmeter-jenkins</name>
<description>Run and Show JMeter test with Jenkins</description>
<parent>
<artifactId>parent-boot-5</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-5</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

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

View File

@ -0,0 +1,66 @@
package com.baeldung.domain;
import javax.validation.constraints.NotNull;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
@Document(collection = "STUDENT")
public class Student implements Serializable {
@Id
private String id;
@NotNull
private String firstName;
private String lastName;
@NotNull
private String phoneNumber;
private String email;
public String getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Student{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", email='" + email + '\'' +
'}';
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.baeldung.domain.Student;
public interface StudentRepository extends MongoRepository<Student, String> {
}

View File

@ -0,0 +1,96 @@
<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="3.2" jmeter="3.3 r1808647">
<hashTree>
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="JMeter Jenkins" enabled="true">
<stringProp name="TestPlan.comments"></stringProp>
<boolProp name="TestPlan.functional_mode">false</boolProp>
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
<collectionProp name="Arguments.arguments"/>
</elementProp>
<stringProp name="TestPlan.user_define_classpath"></stringProp>
</TestPlan>
<hashTree>
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group" enabled="true">
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
<boolProp name="LoopController.continue_forever">false</boolProp>
<stringProp name="LoopController.loops">1</stringProp>
</elementProp>
<stringProp name="ThreadGroup.num_threads">5</stringProp>
<stringProp name="ThreadGroup.ramp_time">1</stringProp>
<longProp name="ThreadGroup.start_time">1507776008000</longProp>
<longProp name="ThreadGroup.end_time">1507776008000</longProp>
<boolProp name="ThreadGroup.scheduler">false</boolProp>
<stringProp name="ThreadGroup.duration"></stringProp>
<stringProp name="ThreadGroup.delay"></stringProp>
</ThreadGroup>
<hashTree>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Request" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
<collectionProp name="Arguments.arguments"/>
</elementProp>
<stringProp name="HTTPSampler.domain">localhost</stringProp>
<stringProp name="HTTPSampler.port">8989</stringProp>
<stringProp name="HTTPSampler.protocol"></stringProp>
<stringProp name="HTTPSampler.contentEncoding"></stringProp>
<stringProp name="HTTPSampler.path">/students</stringProp>
<stringProp name="HTTPSampler.method">GET</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp>
<stringProp name="HTTPSampler.connect_timeout"></stringProp>
<stringProp name="HTTPSampler.response_timeout"></stringProp>
</HTTPSamplerProxy>
<hashTree>
<ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="true">
<boolProp name="ResultCollector.error_logging">false</boolProp>
<objProp>
<name>saveConfig</name>
<value class="SampleSaveConfiguration">
<time>true</time>
<latency>true</latency>
<timestamp>true</timestamp>
<success>true</success>
<label>true</label>
<code>true</code>
<message>true</message>
<threadName>true</threadName>
<dataType>true</dataType>
<encoding>false</encoding>
<assertions>true</assertions>
<subresults>true</subresults>
<responseData>false</responseData>
<samplerData>false</samplerData>
<xml>false</xml>
<fieldNames>true</fieldNames>
<responseHeaders>false</responseHeaders>
<requestHeaders>false</requestHeaders>
<responseDataOnError>false</responseDataOnError>
<saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
<assertionsResultsToSave>0</assertionsResultsToSave>
<bytes>true</bytes>
<sentBytes>true</sentBytes>
<threadCounts>true</threadCounts>
<idleTime>true</idleTime>
<connectTime>true</connectTime>
</value>
</objProp>
<stringProp name="filename"></stringProp>
</ResultCollector>
<hashTree/>
<DurationAssertion guiclass="DurationAssertionGui" testclass="DurationAssertion" testname="Duration Assertion" enabled="true">
<stringProp name="DurationAssertion.duration">10</stringProp>
</DurationAssertion>
<hashTree/>
</hashTree>
</hashTree>
</hashTree>
<WorkBench guiclass="WorkBenchGui" testclass="WorkBench" testname="WorkBench" enabled="true">
<boolProp name="WorkBench.save">true</boolProp>
</WorkBench>
<hashTree/>
</hashTree>
</jmeterTestPlan>

View File

@ -0,0 +1,14 @@
# the db host
spring.data.mongodb.host=localhost
# the connection port (defaults to 27107)
spring.data.mongodb.port=27017
# The database's name
spring.data.mongodb.database=JMeter-Jenkins
# Or this
# spring.data.mongodb.uri=mongodb://localhost/JMeter-Jenkins
# spring.data.mongodb.username=
# spring.data.mongodb.password=
spring.data.mongodb.repositories.enabled=true

View File

@ -0,0 +1,16 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringJMeterJenkinsApplicationTests {
@Test
public void contextLoads() {
}
}

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: