cleanup work

This commit is contained in:
Eugen Paraschiv 2018-03-04 17:39:09 +02:00
parent 14bf9a24d5
commit d2a2a65566
193 changed files with 1504 additions and 2388 deletions

Binary file not shown.

View File

@ -42,8 +42,7 @@ import org.bouncycastle.util.Store;
public class BouncyCastleCrypto { public class BouncyCastleCrypto {
public static byte[] signData(byte[] data, final X509Certificate signingCertificate, final PrivateKey signingKey) public static byte[] signData(byte[] data, final X509Certificate signingCertificate, final PrivateKey signingKey) throws CertificateEncodingException, OperatorCreationException, CMSException, IOException {
throws CertificateEncodingException, OperatorCreationException, CMSException, IOException {
byte[] signedMessage = null; byte[] signedMessage = null;
List<X509Certificate> certList = new ArrayList<X509Certificate>(); List<X509Certificate> certList = new ArrayList<X509Certificate>();
CMSTypedData cmsData = new CMSProcessableByteArray(data); CMSTypedData cmsData = new CMSProcessableByteArray(data);
@ -51,17 +50,14 @@ public class BouncyCastleCrypto {
Store certs = new JcaCertStore(certList); Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator cmsGenerator = new CMSSignedDataGenerator(); CMSSignedDataGenerator cmsGenerator = new CMSSignedDataGenerator();
ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(signingKey); ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(signingKey);
cmsGenerator.addSignerInfoGenerator( cmsGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(contentSigner, signingCertificate));
new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build())
.build(contentSigner, signingCertificate));
cmsGenerator.addCertificates(certs); cmsGenerator.addCertificates(certs);
CMSSignedData cms = cmsGenerator.generate(cmsData, true); CMSSignedData cms = cmsGenerator.generate(cmsData, true);
signedMessage = cms.getEncoded(); signedMessage = cms.getEncoded();
return signedMessage; return signedMessage;
} }
public static boolean verifSignData(final byte[] signedData) public static boolean verifSignData(final byte[] signedData) throws CMSException, IOException, OperatorCreationException, CertificateException {
throws CMSException, IOException, OperatorCreationException, CertificateException {
ByteArrayInputStream bIn = new ByteArrayInputStream(signedData); ByteArrayInputStream bIn = new ByteArrayInputStream(signedData);
ASN1InputStream aIn = new ASN1InputStream(bIn); ASN1InputStream aIn = new ASN1InputStream(bIn);
CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
@ -81,16 +77,14 @@ public class BouncyCastleCrypto {
return true; return true;
} }
public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate) public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate) throws CertificateEncodingException, CMSException, IOException {
throws CertificateEncodingException, CMSException, IOException {
byte[] encryptedData = null; byte[] encryptedData = null;
if (null != data && null != encryptionCertificate) { if (null != data && null != encryptionCertificate) {
CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator(); CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator();
JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate); JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate);
cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey); cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey);
CMSTypedData msg = new CMSProcessableByteArray(data); CMSTypedData msg = new CMSProcessableByteArray(data);
OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC") OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build();
.build();
CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor); CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor);
encryptedData = cmsEnvelopedData.getEncoded(); encryptedData = cmsEnvelopedData.getEncoded();
} }

View File

@ -5,12 +5,17 @@ import net.bytebuddy.implementation.bind.annotation.BindingPriority;
public class Bar { public class Bar {
@BindingPriority(3) @BindingPriority(3)
public static String sayHelloBar() { return "Holla in Bar!"; } public static String sayHelloBar() {
return "Holla in Bar!";
}
@BindingPriority(2) @BindingPriority(2)
public static String sayBar() { return "bar"; } public static String sayBar() {
return "bar";
public String bar() { return Bar.class.getSimpleName() + " - Bar"; } }
public String bar() {
return Bar.class.getSimpleName() + " - Bar";
}
} }

View File

@ -2,6 +2,8 @@ package com.baeldung.bytebuddy;
public class Foo { public class Foo {
public String sayHelloFoo() { return "Hello in Foo!"; } public String sayHelloFoo() {
return "Hello in Foo!";
}
} }

View File

@ -19,9 +19,7 @@ final class DataObject {
@Override @Override
public String toString() { public String toString() {
return "DataObject{" + return "DataObject{" + "data='" + data + '\'' + '}';
"data='" + data + '\'' +
'}';
} }
public static DataObject get(String data) { public static DataObject get(String data) {

View File

@ -7,9 +7,7 @@ import net.openhft.chronicle.ExcerptAppender;
public class ChronicleQueue { public class ChronicleQueue {
static void writeToQueue( static void writeToQueue(Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue) throws IOException {
Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue)
throws IOException {
ExcerptAppender appender = chronicle.createAppender(); ExcerptAppender appender = chronicle.createAppender();
appender.startExcerpt(); appender.startExcerpt();
appender.writeUTF(stringValue); appender.writeUTF(stringValue);

View File

@ -8,33 +8,27 @@ import org.apache.commons.beanutils.PropertyUtils;
public class CourseService { public class CourseService {
public static void setValues(Course course, String name, List<String> codes) public static void setValues(Course course, String name, List<String> codes) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// Setting the simple properties // Setting the simple properties
PropertyUtils.setSimpleProperty(course, "name", name); PropertyUtils.setSimpleProperty(course, "name", name);
PropertyUtils.setSimpleProperty(course, "codes", codes); PropertyUtils.setSimpleProperty(course, "codes", codes);
} }
public static void setIndexedValue(Course course, int codeIndex, String code) public static void setIndexedValue(Course course, int codeIndex, String code) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// Setting the indexed properties // Setting the indexed properties
PropertyUtils.setIndexedProperty(course, "codes[" + codeIndex + "]", code); PropertyUtils.setIndexedProperty(course, "codes[" + codeIndex + "]", code);
} }
public static void setMappedValue(Course course, String enrollId, Student student) public static void setMappedValue(Course course, String enrollId, Student student) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// Setting the mapped properties // Setting the mapped properties
PropertyUtils.setMappedProperty(course, "enrolledStudent(" + enrollId + ")", student); PropertyUtils.setMappedProperty(course, "enrolledStudent(" + enrollId + ")", student);
} }
public static String getNestedValue(Course course, String enrollId, String nestedPropertyName) public static String getNestedValue(Course course, String enrollId, String nestedPropertyName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (String) PropertyUtils.getNestedProperty(course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName);
return (String) PropertyUtils.getNestedProperty(
course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName);
} }
public static void copyProperties(Course course, CourseEntity courseEntity) public static void copyProperties(Course course, CourseEntity courseEntity) throws IllegalAccessException, InvocationTargetException {
throws IllegalAccessException, InvocationTargetException {
BeanUtils.copyProperties(course, courseEntity); BeanUtils.copyProperties(course, courseEntity);
} }
} }

View File

@ -7,7 +7,7 @@ public class AuditFilter implements Filter {
@Override @Override
public boolean postprocess(Context context, Exception exception) { public boolean postprocess(Context context, Exception exception) {
// Send notification to customer & bank. // Send notification to customer & bank.
return false; return false;
} }

View File

@ -21,7 +21,6 @@ public class Email {
this.employeeId = employeeId; this.employeeId = employeeId;
} }
public String getAddress() { public String getAddress() {
return address; return address;
} }

View File

@ -26,9 +26,7 @@ public class BuilderMethods {
@Override @Override
public int hashCode() { public int hashCode() {
return new HashCodeBuilder().append(this.intValue) return new HashCodeBuilder().append(this.intValue).append(this.strSample).toHashCode();
.append(this.strSample)
.toHashCode();
} }
@Override @Override
@ -41,16 +39,12 @@ public class BuilderMethods {
} }
final BuilderMethods otherObject = (BuilderMethods) obj; final BuilderMethods otherObject = (BuilderMethods) obj;
return new EqualsBuilder().append(this.intValue, otherObject.intValue) return new EqualsBuilder().append(this.intValue, otherObject.intValue).append(this.strSample, otherObject.strSample).isEquals();
.append(this.strSample, otherObject.strSample)
.isEquals();
} }
@Override @Override
public String toString() { public String toString() {
return new ToStringBuilder(this).append("INTVALUE", this.intValue) return new ToStringBuilder(this).append("INTVALUE", this.intValue).append("STRINGVALUE", this.strSample).toString();
.append("STRINGVALUE", this.strSample)
.toString();
} }
public static void main(final String[] arguments) { public static void main(final String[] arguments) {
@ -81,7 +75,7 @@ public class BuilderMethods {
} }
} }
class SampleBackgroundInitializer extends BackgroundInitializer<String>{ class SampleBackgroundInitializer extends BackgroundInitializer<String> {
@Override @Override
protected String initialize() throws Exception { protected String initialize() throws Exception {

View File

@ -2,6 +2,6 @@ package com.baeldung.commons.lang3;
public class SampleObject { public class SampleObject {
//Ignored // Ignored
} }

View File

@ -53,16 +53,12 @@ class Docx4jExample {
File image = new File(imagePath); File image = new File(imagePath);
byte[] fileContent = Files.readAllBytes(image.toPath()); byte[] fileContent = Files.readAllBytes(image.toPath());
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordPackage, fileContent);
.createImagePart(wordPackage, fileContent); Inline inline = imagePart.createImageInline("Baeldung Image", "Alt Text", 1, 2, false);
Inline inline = imagePart.createImageInline(
"Baeldung Image", "Alt Text", 1, 2, false);
P Imageparagraph = addImageToParagraph(inline); P Imageparagraph = addImageToParagraph(inline);
mainDocumentPart.getContent().add(Imageparagraph); mainDocumentPart.getContent().add(Imageparagraph);
int writableWidthTwips = wordPackage.getDocumentModel() int writableWidthTwips = wordPackage.getDocumentModel().getSections().get(0).getPageDimensions().getWritableWidthTwips();
.getSections().get(0).getPageDimensions()
.getWritableWidthTwips();
int columnNumber = 3; int columnNumber = 3;
Tbl tbl = TblFactory.createTable(3, 3, writableWidthTwips / columnNumber); Tbl tbl = TblFactory.createTable(3, 3, writableWidthTwips / columnNumber);
List<Object> rows = tbl.getContent(); List<Object> rows = tbl.getContent();

View File

@ -21,8 +21,7 @@ public class FunctionalJavaIOMain {
F<String, IO<Unit>> printLetters = i -> printLetters(i); F<String, IO<Unit>> printLetters = i -> printLetters(i);
IO<Unit> lowerCase = IOFunctions IO<Unit> lowerCase = IOFunctions.stdoutPrintln("What's your first Name ?");
.stdoutPrintln("What's your first Name ?");
IO<Unit> input = IOFunctions.stdoutPrint("First Name: "); IO<Unit> input = IOFunctions.stdoutPrint("First Name: ");
@ -32,14 +31,11 @@ public class FunctionalJavaIOMain {
F<String, String> toUpperCase = i -> i.toUpperCase(); F<String, String> toUpperCase = i -> i.toUpperCase();
F<String, IO<Unit>> transformInput = F1Functions F<String, IO<Unit>> transformInput = F1Functions.<String, IO<Unit>, String> o(printLetters).f(toUpperCase);
.<String, IO<Unit>, String> o(printLetters).f(toUpperCase);
IO<Unit> readAndPrintResult = IOFunctions.bind(readInput, IO<Unit> readAndPrintResult = IOFunctions.bind(readInput, transformInput);
transformInput);
IO<Unit> program = IOFunctions.bind(userInput, IO<Unit> program = IOFunctions.bind(userInput, nothing -> readAndPrintResult);
nothing -> readAndPrintResult);
IOFunctions.toSafe(program).run(); IOFunctions.toSafe(program).run();

View File

@ -13,8 +13,6 @@ public class LineSplitter implements FlatMapFunction<String, Tuple2<String, Inte
public void flatMap(String value, Collector<Tuple2<String, Integer>> out) { public void flatMap(String value, Collector<Tuple2<String, Integer>> out) {
String[] tokens = value.toLowerCase().split("\\W+"); String[] tokens = value.toLowerCase().split("\\W+");
Stream.of(tokens) Stream.of(tokens).filter(t -> t.length() > 0).forEach(token -> out.collect(new Tuple2<>(token, 1)));
.filter(t -> t.length() > 0)
.forEach(token -> out.collect(new Tuple2<>(token, 1)));
} }
} }

View File

@ -12,9 +12,7 @@ public class WordCount {
public static DataSet<Tuple2<String, Integer>> startWordCount(ExecutionEnvironment env, List<String> lines) throws Exception { public static DataSet<Tuple2<String, Integer>> startWordCount(ExecutionEnvironment env, List<String> lines) throws Exception {
DataSet<String> text = env.fromCollection(lines); DataSet<String> text = env.fromCollection(lines);
return text.flatMap(new LineSplitter()) return text.flatMap(new LineSplitter()).groupBy(0).aggregate(Aggregations.SUM, 1);
.groupBy(0)
.aggregate(Aggregations.SUM, 1);
} }
} }

View File

@ -20,21 +20,13 @@ import com.google.api.services.sheets.v4.SheetsScopes;
public class GoogleAuthorizeUtil { public class GoogleAuthorizeUtil {
public static Credential authorize() throws IOException, GeneralSecurityException { public static Credential authorize() throws IOException, GeneralSecurityException {
InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("/google-sheets-client-secret.json"); InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("/google-sheets-client-secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS); List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets, scopes).setDataStoreFactory(new MemoryDataStoreFactory())
.Builder(GoogleNetHttpTransport.newTrustedTransport(), .setAccessType("offline").build();
JacksonFactory.getDefaultInstance(), Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
clientSecrets,
scopes)
.setDataStoreFactory(new MemoryDataStoreFactory())
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
.authorize("user");
return credential; return credential;
} }

View File

@ -14,10 +14,7 @@ public class SheetsServiceUtil {
public static Sheets getSheetsService() throws IOException, GeneralSecurityException { public static Sheets getSheetsService() throws IOException, GeneralSecurityException {
Credential credential = GoogleAuthorizeUtil.authorize(); Credential credential = GoogleAuthorizeUtil.authorize();
return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential).setApplicationName(APPLICATION_NAME).build();
JacksonFactory.getDefaultInstance(), credential)
.setApplicationName(APPLICATION_NAME)
.build();
} }
} }

View File

@ -21,30 +21,23 @@ import java.util.concurrent.Future;
public class GitHubExample { public class GitHubExample {
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
//static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport(); // static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory(); static final JsonFactory JSON_FACTORY = new JacksonFactory();
//static final JsonFactory JSON_FACTORY = new GsonFactory(); // static final JsonFactory JSON_FACTORY = new GsonFactory();
private static void run() throws Exception { private static void run() throws Exception {
HttpRequestFactory requestFactory HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory((HttpRequest request) -> {
= HTTP_TRANSPORT.createRequestFactory( request.setParser(new JsonObjectParser(JSON_FACTORY));
(HttpRequest request) -> { });
request.setParser(new JsonObjectParser(JSON_FACTORY));
});
GitHubUrl url = new GitHubUrl("https://api.github.com/users"); GitHubUrl url = new GitHubUrl("https://api.github.com/users");
url.per_page = 10; url.per_page = 10;
url.page = 1; url.page = 1;
HttpRequest request = requestFactory.buildGetRequest(url); HttpRequest request = requestFactory.buildGetRequest(url);
ExponentialBackOff backoff = new ExponentialBackOff.Builder() ExponentialBackOff backoff = new ExponentialBackOff.Builder().setInitialIntervalMillis(500).setMaxElapsedTimeMillis(900000).setMaxIntervalMillis(6000).setMultiplier(1.5).setRandomizationFactor(0.5).build();
.setInitialIntervalMillis(500)
.setMaxElapsedTimeMillis(900000)
.setMaxIntervalMillis(6000)
.setMultiplier(1.5)
.setRandomizationFactor(0.5)
.build();
request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff)); request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
Type type = new TypeToken<List<User>>() {}.getType(); Type type = new TypeToken<List<User>>() {
List<User> users = (List<User>)request.execute().parseAs(type); }.getType();
List<User> users = (List<User>) request.execute().parseAs(type);
System.out.println(users); System.out.println(users);
url.appendRawPath("/eugenp"); url.appendRawPath("/eugenp");
request = requestFactory.buildGetRequest(url); request = requestFactory.buildGetRequest(url);

View File

@ -3,7 +3,7 @@ package com.baeldung.googlehttpclientguide;
import com.google.api.client.http.GenericUrl; import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Key; import com.google.api.client.util.Key;
public class GitHubUrl extends GenericUrl{ public class GitHubUrl extends GenericUrl {
public GitHubUrl(String encodedUrl) { public GitHubUrl(String encodedUrl) {
super(encodedUrl); super(encodedUrl);

View File

@ -73,5 +73,4 @@ public class User extends GenericJson {
return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}'; return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}';
} }
} }

View File

@ -14,14 +14,14 @@ public class DataSource {
private static HikariDataSource ds; private static HikariDataSource ds;
static { static {
// config = new HikariConfig("datasource.properties"); // config = new HikariConfig("datasource.properties");
// Properties props = new Properties(); // Properties props = new Properties();
// props.setProperty("dataSourceClassName", "org.h2.Driver"); // props.setProperty("dataSourceClassName", "org.h2.Driver");
// props.setProperty("dataSource.user", ""); // props.setProperty("dataSource.user", "");
// props.setProperty("dataSource.password", ""); // props.setProperty("dataSource.password", "");
// props.put("dataSource.logWriter", new PrintWriter(System.out)); // props.put("dataSource.logWriter", new PrintWriter(System.out));
// config = new HikariConfig(props); // config = new HikariConfig(props);
config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'"); config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'");
config.setUsername(""); config.setUsername("");
@ -31,12 +31,13 @@ public class DataSource {
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ds = new HikariDataSource(config); ds = new HikariDataSource(config);
// ds.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'"); // ds.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'");
// ds.setUsername(""); // ds.setUsername("");
// ds.setPassword(""); // ds.setPassword("");
} }
private DataSource() {} private DataSource() {
}
public static Connection getConnection() throws SQLException { public static Connection getConnection() throws SQLException {
return ds.getConnection(); return ds.getConnection();

View File

@ -12,9 +12,7 @@ public class HikariCPDemo {
public static List<Employee> fetchData() { public static List<Employee> fetchData() {
final String SQL_QUERY = "select * from emp"; final String SQL_QUERY = "select * from emp";
List<Employee> employees = null; List<Employee> employees = null;
try (Connection con = DataSource.getConnection(); try (Connection con = DataSource.getConnection(); PreparedStatement pst = con.prepareStatement(SQL_QUERY); ResultSet rs = pst.executeQuery();) {
PreparedStatement pst = con.prepareStatement(SQL_QUERY);
ResultSet rs = pst.executeQuery();) {
employees = new ArrayList<Employee>(); employees = new ArrayList<Employee>();
Employee employee; Employee employee;
while (rs.next()) { while (rs.next()) {

View File

@ -43,8 +43,7 @@ public class CacheConfiguration {
return this.buildCache(PASSIVATING_HELLO_WORLD_CACHE, cacheManager, listener, passivatingConfiguration()); return this.buildCache(PASSIVATING_HELLO_WORLD_CACHE, cacheManager, listener, passivatingConfiguration());
} }
private <K, V> Cache<K, V> buildCache(String cacheName, DefaultCacheManager cacheManager, private <K, V> Cache<K, V> buildCache(String cacheName, DefaultCacheManager cacheManager, CacheListener listener, Configuration configuration) {
CacheListener listener, Configuration configuration) {
cacheManager.defineConfiguration(cacheName, configuration); cacheManager.defineConfiguration(cacheName, configuration);
Cache<K, V> cache = cacheManager.getCache(cacheName); Cache<K, V> cache = cacheManager.getCache(cacheName);
@ -53,32 +52,19 @@ public class CacheConfiguration {
} }
private Configuration expiringConfiguration() { private Configuration expiringConfiguration() {
return new ConfigurationBuilder().expiration().lifespan(1, TimeUnit.SECONDS) return new ConfigurationBuilder().expiration().lifespan(1, TimeUnit.SECONDS).build();
.build();
} }
private Configuration evictingConfiguration() { private Configuration evictingConfiguration() {
return new ConfigurationBuilder() return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).build();
.memory().evictionType(EvictionType.COUNT).size(1)
.build();
} }
private Configuration passivatingConfiguration() { private Configuration passivatingConfiguration() {
return new ConfigurationBuilder() return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).persistence().passivation(true).addSingleFileStore().purgeOnStartup(true).location(System.getProperty("java.io.tmpdir")).build();
.memory().evictionType(EvictionType.COUNT).size(1)
.persistence()
.passivation(true)
.addSingleFileStore()
.purgeOnStartup(true)
.location(System.getProperty("java.io.tmpdir"))
.build();
} }
private Configuration transactionalConfiguration() { private Configuration transactionalConfiguration() {
return new ConfigurationBuilder() return new ConfigurationBuilder().transaction().transactionMode(TransactionMode.TRANSACTIONAL).lockingMode(LockingMode.PESSIMISTIC).build();
.transaction().transactionMode(TransactionMode.TRANSACTIONAL)
.lockingMode(LockingMode.PESSIMISTIC)
.build();
} }
} }

View File

@ -15,11 +15,8 @@ public class HelloWorldService {
private final Cache<String, String> evictingHelloWorldCache; private final Cache<String, String> evictingHelloWorldCache;
private final Cache<String, String> passivatingHelloWorldCache; private final Cache<String, String> passivatingHelloWorldCache;
public HelloWorldService(HelloWorldRepository repository, CacheListener listener, public HelloWorldService(HelloWorldRepository repository, CacheListener listener, Cache<String, String> simpleHelloWorldCache, Cache<String, String> expiringHelloWorldCache, Cache<String, String> evictingHelloWorldCache,
Cache<String, String> simpleHelloWorldCache, Cache<String, String> passivatingHelloWorldCache) {
Cache<String, String> expiringHelloWorldCache,
Cache<String, String> evictingHelloWorldCache,
Cache<String, String> passivatingHelloWorldCache) {
this.repository = repository; this.repository = repository;
@ -66,7 +63,7 @@ public class HelloWorldService {
public String findEvictingHelloWorld(String key) { public String findEvictingHelloWorld(String key) {
String value = evictingHelloWorldCache.get(key); String value = evictingHelloWorldCache.get(key);
if(value == null) { if (value == null) {
value = repository.getHelloWorld(); value = repository.getHelloWorld();
evictingHelloWorldCache.put(key, value); evictingHelloWorldCache.put(key, value);
} }

View File

@ -28,8 +28,7 @@ public class TransactionalService {
watch.start(); watch.start();
transactionalCache.put(KEY, howManyVisits); transactionalCache.put(KEY, howManyVisits);
watch.stop(); watch.stop();
System.out.println("I was able to set HowManyVisits to " + howManyVisits + System.out.println("I was able to set HowManyVisits to " + howManyVisits + " after waiting " + watch.getTotalTimeSeconds() + " seconds");
" after waiting " + watch.getTotalTimeSeconds() + " seconds");
tm.commit(); tm.commit();
return howManyVisits; return howManyVisits;
@ -44,8 +43,7 @@ public class TransactionalService {
TransactionManager tm = transactionalCache.getAdvancedCache().getTransactionManager(); TransactionManager tm = transactionalCache.getAdvancedCache().getTransactionManager();
tm.begin(); tm.begin();
transactionalCache.put(KEY, 1000); transactionalCache.put(KEY, 1000);
System.out.println("HowManyVisits should now be 1000, " + System.out.println("HowManyVisits should now be 1000, " + "but we are holding the transaction");
"but we are holding the transaction");
Thread.sleep(1000L); Thread.sleep(1000L);
tm.rollback(); tm.rollback();
System.out.println("The slow batch suffered a rollback"); System.out.println("The slow batch suffered a rollback");

View File

@ -1,6 +1,5 @@
package com.baeldung.javasisst; package com.baeldung.javasisst;
public class Point { public class Point {
public int x = 0; public int x = 0;
public int y = 0; public int y = 0;

View File

@ -1,6 +1,5 @@
package com.baeldung.javasisst; package com.baeldung.javasisst;
public class ThreeDimensionalPoint { public class ThreeDimensionalPoint {
public int x = 0; public int x = 0;
public int y = 0; public int y = 0;

View File

@ -1,6 +1,5 @@
package com.baeldung.javers; package com.baeldung.javers;
public class Address { public class Address {
private String country; private String country;

View File

@ -1,6 +1,5 @@
package com.baeldung.javers; package com.baeldung.javers;
import java.util.List; import java.util.List;
public class PersonWithAddress { public class PersonWithAddress {

View File

@ -19,14 +19,11 @@ class PipeDemo {
p.then((DonePipe<Integer, Integer, Exception, Void>) result -> { p.then((DonePipe<Integer, Integer, Exception, Void>) result -> {
if (result < 90) { if (result < 90) {
return new DeferredObject<Integer, Exception, Void>() return new DeferredObject<Integer, Exception, Void>().resolve(result);
.resolve(result);
} else { } else {
return new DeferredObject<Integer, Exception, Void>() return new DeferredObject<Integer, Exception, Void>().reject(new Exception("Unacceptable value"));
.reject(new Exception("Unacceptable value"));
} }
}).done(r -> status = Result.SUCCESS) }).done(r -> status = Result.SUCCESS).fail(r -> status = Result.FAILURE);
.fail(r -> status = Result.FAILURE);
d.resolve(num); d.resolve(num);

View File

@ -11,10 +11,7 @@ class PromiseDemo {
Deferred<String, String, String> deferred = new DeferredObject<>(); Deferred<String, String, String> deferred = new DeferredObject<>();
Promise<String, String, String> promise = deferred.promise(); Promise<String, String, String> promise = deferred.promise();
promise.done(result -> System.out.println("Job done")) promise.done(result -> System.out.println("Job done")).fail(rejection -> System.out.println("Job fail")).progress(progress -> System.out.println("Job is in progress")).always((state, result, rejection) -> System.out.println("Job execution started"));
.fail(rejection -> System.out.println("Job fail"))
.progress(progress -> System.out.println("Job is in progress"))
.always((state, result, rejection) -> System.out.println("Job execution started"));
deferred.resolve(jobName); deferred.resolve(jobName);
// deferred.notify(""); // deferred.notify("");

View File

@ -12,9 +12,7 @@ public class ThreadSafeDemo {
DeferredManager dm = new DefaultDeferredManager(); DeferredManager dm = new DefaultDeferredManager();
Deferred<String, String, String> deferred = new DeferredObject<>(); Deferred<String, String, String> deferred = new DeferredObject<>();
Promise<String, String, String> p1 = deferred.promise(); Promise<String, String, String> p1 = deferred.promise();
Promise<String, String, String> p = dm.when(p1) Promise<String, String, String> p = dm.when(p1).done(r -> System.out.println("done")).fail(r -> System.out.println("fail"));
.done(r -> System.out.println("done"))
.fail(r -> System.out.println("fail"));
synchronized (p) { synchronized (p) {
while (p.isPending()) { while (p.isPending()) {

View File

@ -16,9 +16,7 @@ class DeferredManagerWithExecutorDemo {
Deferred<String, String, String> deferred = new DeferredObject<>(); Deferred<String, String, String> deferred = new DeferredObject<>();
DeferredManager dm = new DefaultDeferredManager(executor); DeferredManager dm = new DefaultDeferredManager(executor);
Promise<String, String, String> p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise(); Promise<String, String, String> p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise();
dm.when(p1, p2, p3) dm.when(p1, p2, p3).done(r -> System.out.println("done")).fail(r -> System.out.println("fail"));
.done(r -> System.out.println("done"))
.fail(r -> System.out.println("fail"));
deferred.resolve("done"); deferred.resolve("done");
} }
} }

View File

@ -7,8 +7,6 @@ class SimpleDeferredManagerDemo {
public static void initiate() { public static void initiate() {
DeferredManager dm = new DefaultDeferredManager(); DeferredManager dm = new DefaultDeferredManager();
dm.when(() -> 1) dm.when(() -> 1).done(r -> System.out.println("done")).fail(Throwable::printStackTrace);
.done(r -> System.out.println("done"))
.fail(Throwable::printStackTrace);
} }
} }

View File

@ -42,7 +42,7 @@ public class GuideToJDO {
listXMLProducts(); listXMLProducts();
} }
public void CreateH2Properties(){ public void CreateH2Properties() {
pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addClassName("com.baeldung.jdo.Product"); pumd.addClassName("com.baeldung.jdo.Product");
@ -55,7 +55,7 @@ public class GuideToJDO {
} }
public void CreateXMLProperties(){ public void CreateXMLProperties() {
pumdXML = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); pumdXML = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumdXML.addClassName("com.baeldung.jdo.ProductXML"); pumdXML.addClassName("com.baeldung.jdo.ProductXML");
pumdXML.setExcludeUnlistedClasses(); pumdXML.setExcludeUnlistedClasses();
@ -91,7 +91,7 @@ public class GuideToJDO {
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public void UpdateProducts(){ public void UpdateProducts() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager(); PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction(); Transaction tx = pm.currentTransaction();
@ -111,7 +111,7 @@ public class GuideToJDO {
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public void DeleteProducts(){ public void DeleteProducts() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager(); PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction(); Transaction tx = pm.currentTransaction();
@ -157,7 +157,7 @@ public class GuideToJDO {
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
public void QueryJDOQL (){ public void QueryJDOQL() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager(); PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction(); Transaction tx = pm.currentTransaction();
@ -189,14 +189,14 @@ public class GuideToJDO {
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
public void QuerySQL (){ public void QuerySQL() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager(); PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction(); Transaction tx = pm.currentTransaction();
try { try {
tx.begin(); tx.begin();
//SQL : // SQL :
LOGGER.log(Level.INFO, "SQL --------------------------------------------------------------"); LOGGER.log(Level.INFO, "SQL --------------------------------------------------------------");
Query query = pm.newQuery("javax.jdo.query.SQL", "SELECT * FROM PRODUCT"); Query query = pm.newQuery("javax.jdo.query.SQL", "SELECT * FROM PRODUCT");
query.setClass(Product.class); query.setClass(Product.class);
@ -220,17 +220,17 @@ public class GuideToJDO {
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
public void QueryJPQL (){ public void QueryJPQL() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager(); PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction(); Transaction tx = pm.currentTransaction();
try { try {
tx.begin(); tx.begin();
//JPQL : // JPQL :
LOGGER.log(Level.INFO, "JPQL --------------------------------------------------------------"); LOGGER.log(Level.INFO, "JPQL --------------------------------------------------------------");
Query q = pm.newQuery("JPQL", "SELECT p FROM "+Product.class.getName()+" p WHERE p.name = 'Laptop'"); Query q = pm.newQuery("JPQL", "SELECT p FROM " + Product.class.getName() + " p WHERE p.name = 'Laptop'");
List results = (List)q.execute(); List results = (List) q.execute();
Iterator<Product> iter = results.iterator(); Iterator<Product> iter = results.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
@ -249,17 +249,17 @@ public class GuideToJDO {
} }
} }
public void persistXML(){ public void persistXML() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null); PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null);
PersistenceManager pm = pmf.getPersistenceManager(); PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction(); Transaction tx = pm.currentTransaction();
try { try {
tx.begin(); tx.begin();
ProductXML productXML = new ProductXML(0,"Tablet", 80.0); ProductXML productXML = new ProductXML(0, "Tablet", 80.0);
pm.makePersistent(productXML); pm.makePersistent(productXML);
ProductXML productXML2 = new ProductXML(1,"Phone", 20.0); ProductXML productXML2 = new ProductXML(1, "Phone", 20.0);
pm.makePersistent(productXML2); pm.makePersistent(productXML2);
ProductXML productXML3 = new ProductXML(2,"Laptop", 200.0); ProductXML productXML3 = new ProductXML(2, "Laptop", 200.0);
pm.makePersistent(productXML3); pm.makePersistent(productXML3);
tx.commit(); tx.commit();
} finally { } finally {
@ -271,7 +271,7 @@ public class GuideToJDO {
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
public void listXMLProducts(){ public void listXMLProducts() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null); PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null);
PersistenceManager pm = pmf.getPersistenceManager(); PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction(); Transaction tx = pm.currentTransaction();

View File

@ -26,19 +26,19 @@ public class MyApp {
} }
public static void createTestData(){ public static void createTestData() {
ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut",5); ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut", 5);
ProductItem item2 = new ProductItem("pro2", "price less than 10","InStock", 8); ProductItem item2 = new ProductItem("pro2", "price less than 10", "InStock", 8);
ProductItem item3 = new ProductItem("pro3", "price more than 10","SoldOut", 15); ProductItem item3 = new ProductItem("pro3", "price more than 10", "SoldOut", 15);
if( pm != null ){ if (pm != null) {
pm.makePersistent(item1); pm.makePersistent(item1);
pm.makePersistent(item2); pm.makePersistent(item2);
pm.makePersistent(item3); pm.makePersistent(item3);
} }
} }
public static void defineDynamicPersistentUnit(){ public static void defineDynamicPersistentUnit() {
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); 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.ConnectionURL", "jdbc:mysql://localhost:3306/jdo_db");
@ -51,53 +51,46 @@ public class MyApp {
pm = pmf.getPersistenceManager(); pm = pmf.getPersistenceManager();
} }
public static void queryUsingJDOQL(){ public static void queryUsingJDOQL() {
Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " + "WHERE price < threshold PARAMETERS double threshold");
+ "WHERE price < threshold PARAMETERS double threshold"); List<ProductItem> explicitParamResults = (List<ProductItem>) query.execute(10);
List<ProductItem> explicitParamResults = (List<ProductItem>)query.execute(10);
query = pm.newQuery("SELECT FROM " query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
+ "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
query.setParameters("double threshold"); query.setParameters("double threshold");
List<ProductItem> explicitParamResults2 = (List<ProductItem>)query.execute(10); List<ProductItem> explicitParamResults2 = (List<ProductItem>) query.execute(10);
query = pm.newQuery("SELECT FROM " query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
+ "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); List<ProductItem> implicitParamResults = (List<ProductItem>) query.execute(10);
List<ProductItem> implicitParamResults = (List<ProductItem>)query.execute(10);
} }
public static void queryUsingTypedJDOQL(){ public static void queryUsingTypedJDOQL() {
JDOQLTypedQuery<ProductItem> tq = pm.newJDOQLTypedQuery(ProductItem.class); JDOQLTypedQuery<ProductItem> tq = pm.newJDOQLTypedQuery(ProductItem.class);
QProductItem cand = QProductItem.candidate(); QProductItem cand = QProductItem.candidate();
tq=tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro"))); tq = tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro")));
List<ProductItem> results = tq.executeList(); List<ProductItem> results = tq.executeList();
} }
public static void queryUsingSQL(){ public static void queryUsingSQL() {
Query query = pm.newQuery("javax.jdo.query.SQL","select * from " Query query = pm.newQuery("javax.jdo.query.SQL", "select * from " + "product_item where price < ? and status = ?");
+ "product_item where price < ? and status = ?");
query.setClass(ProductItem.class); query.setClass(ProductItem.class);
query.setParameters(10,"InStock"); query.setParameters(10, "InStock");
List<ProductItem> results = query.executeList(); List<ProductItem> results = query.executeList();
} }
public static void queryUsingJPQL(){ public static void queryUsingJPQL() {
Query query = pm.newQuery("JPQL","select i from " Query query = pm.newQuery("JPQL", "select i from " + "com.baeldung.jdo.query.ProductItem i where i.price < 10" + " and i.status = 'InStock'");
+ "com.baeldung.jdo.query.ProductItem i where i.price < 10"
+ " and i.status = 'InStock'");
List<ProductItem> results = (List<ProductItem>) query.execute(); List<ProductItem> results = (List<ProductItem>) query.execute();
} }
public static void namedQuery(){ public static void namedQuery() {
Query<ProductItem> query = pm.newNamedQuery( Query<ProductItem> query = pm.newNamedQuery(ProductItem.class, "PriceBelow10");
ProductItem.class, "PriceBelow10");
List<ProductItem> results = query.executeList(); List<ProductItem> results = query.executeList();
} }

View File

@ -10,25 +10,24 @@ import javax.jdo.annotations.PrimaryKey;
public class ProductItem { public class ProductItem {
@PrimaryKey @PrimaryKey
@Persistent(valueStrategy=IdGeneratorStrategy.INCREMENT) @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT)
int id; int id;
String name; String name;
String description; String description;
String status; String status;
double price; double price;
public ProductItem(){ public ProductItem() {
} }
public ProductItem(String name,String description,String status,double price){ public ProductItem(String name, String description, String status, double price) {
this.name=name; this.name = name;
this.description = description; this.description = description;
this.status = status; this.status = status;
this.price = price; this.price = price;
} }
public int getId() { public int getId() {
return id; return id;
} }
@ -40,18 +39,23 @@ public class ProductItem {
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
public void setDescription(String description) { public void setDescription(String description) {
this.description = description; this.description = description;
} }
public double getPrice() { public double getPrice() {
return price; return price;
} }
public void setPrice(double price) { public void setPrice(double price) {
this.price = price; this.price = price;
} }
@ -64,5 +68,4 @@ public class ProductItem {
this.status = status; this.status = status;
} }
} }

View File

@ -12,10 +12,7 @@ import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlElementWrapper;
@PersistenceCapable( @PersistenceCapable(schema = "/myproduct/people", table = "person")
schema="/myproduct/people",
table="person"
)
public class AnnotadedPerson { public class AnnotadedPerson {
@XmlAttribute @XmlAttribute
private long personNum; private long personNum;
@ -24,12 +21,11 @@ public class AnnotadedPerson {
private String firstName; private String firstName;
private String lastName; private String lastName;
@XmlElementWrapper(name="phone-numbers") @XmlElementWrapper(name = "phone-numbers")
@XmlElement(name="phone-number") @XmlElement(name = "phone-number")
@Element(types=String.class) @Element(types = String.class)
private List phoneNumbers = new ArrayList(); private List phoneNumbers = new ArrayList();
public AnnotadedPerson(long personNum, String firstName, String lastName) { public AnnotadedPerson(long personNum, String firstName, String lastName) {
super(); super();
this.personNum = personNum; this.personNum = personNum;

View File

@ -17,26 +17,26 @@ public class MyApp {
private static PersistenceManagerFactory pmf; private static PersistenceManagerFactory pmf;
private static PersistenceManager pm; private static PersistenceManager pm;
public static void main( String[] args ) { public static void main(String[] args) {
//persist product object using dynamic persistence unit // persist product object using dynamic persistence unit
defineDynamicPersistentUnit(); defineDynamicPersistentUnit();
Product product = new Product("id1","Sony Discman", "A standard discman from Sony", 49.99); Product product = new Product("id1", "Sony Discman", "A standard discman from Sony", 49.99);
persistObject(product); persistObject(product);
closePersistenceManager(); closePersistenceManager();
//persist AnnotatedPerson object using named pmf // persist AnnotatedPerson object using named pmf
defineNamedPersistenceManagerFactory("XmlDatastore"); defineNamedPersistenceManagerFactory("XmlDatastore");
AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320,"annotated","person"); AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320, "annotated", "person");
annotatedPerson.getPhoneNumbers().add("999999999"); annotatedPerson.getPhoneNumbers().add("999999999");
annotatedPerson.getPhoneNumbers().add("000000000"); annotatedPerson.getPhoneNumbers().add("000000000");
persistObject(annotatedPerson); persistObject(annotatedPerson);
queryAnnotatedPersonsInXML(); queryAnnotatedPersonsInXML();
closePersistenceManager(); closePersistenceManager();
//persist Person object using PMF created by properties file // persist Person object using PMF created by properties file
definePersistenceManagerFactoryUsingPropertiesFile("META-INF\\datanucleus.properties"); definePersistenceManagerFactoryUsingPropertiesFile("META-INF\\datanucleus.properties");
Person person = new Person(654321,"bealdung","author"); Person person = new Person(654321, "bealdung", "author");
person.getPhoneNumbers().add("123456789"); person.getPhoneNumbers().add("123456789");
person.getPhoneNumbers().add("987654321"); person.getPhoneNumbers().add("987654321");
persistObject(person); persistObject(person);
@ -44,7 +44,7 @@ public class MyApp {
closePersistenceManager(); closePersistenceManager();
} }
public static void defineDynamicPersistentUnit(){ public static void defineDynamicPersistentUnit() {
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml"); pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml");
@ -55,26 +55,26 @@ public class MyApp {
pm = pmf.getPersistenceManager(); pm = pmf.getPersistenceManager();
} }
public static void defineNamedPersistenceManagerFactory(String pmfName){ public static void defineNamedPersistenceManagerFactory(String pmfName) {
pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore"); pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore");
pm = pmf.getPersistenceManager(); pm = pmf.getPersistenceManager();
} }
public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath){ public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath) {
pmf = JDOHelper.getPersistenceManagerFactory(filePath); pmf = JDOHelper.getPersistenceManagerFactory(filePath);
pm = pmf.getPersistenceManager(); pm = pmf.getPersistenceManager();
} }
public static void closePersistenceManager(){ public static void closePersistenceManager() {
if(pm!=null && !pm.isClosed()){ if (pm != null && !pm.isClosed()) {
pm.close(); pm.close();
} }
} }
public static void persistObject(Object obj){ public static void persistObject(Object obj) {
Transaction tx = pm.currentTransaction(); Transaction tx = pm.currentTransaction();
@ -89,17 +89,17 @@ public class MyApp {
} }
} }
public static void queryPersonsInXML(){ public static void queryPersonsInXML() {
Query<Person> query = pm.newQuery(Person.class); Query<Person> query = pm.newQuery(Person.class);
List<Person> result = query.executeList(); List<Person> result = query.executeList();
System.out.println("name: "+result.get(0).getFirstName()); System.out.println("name: " + result.get(0).getFirstName());
} }
public static void queryAnnotatedPersonsInXML(){ public static void queryAnnotatedPersonsInXML() {
Query<AnnotadedPerson> query = pm.newQuery(AnnotadedPerson.class); Query<AnnotadedPerson> query = pm.newQuery(AnnotadedPerson.class);
List<AnnotadedPerson> result = query.executeList(); List<AnnotadedPerson> result = query.executeList();
System.out.println("name: "+result.get(0).getFirstName()); System.out.println("name: " + result.get(0).getFirstName());
} }
} }

View File

@ -12,7 +12,6 @@ import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlElementWrapper;
@PersistenceCapable @PersistenceCapable
public class Person { public class Person {
private long personNum; private long personNum;

View File

@ -15,18 +15,17 @@ public class Product {
String description; String description;
double price; double price;
public Product(){ public Product() {
} }
public Product(String id,String name,String description,double price){ public Product(String id, String name, String description, double price) {
this.id = id; this.id = id;
this.name=name; this.name = name;
this.description = description; this.description = description;
this.price = price; this.price = price;
} }
public String getId() { public String getId() {
return id; return id;
} }
@ -38,21 +37,25 @@ public class Product {
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
public void setDescription(String description) { public void setDescription(String description) {
this.description = description; this.description = description;
} }
public double getPrice() { public double getPrice() {
return price; return price;
} }
public void setPrice(double price) { public void setPrice(double price) {
this.price = price; this.price = price;
} }
} }

View File

@ -14,4 +14,3 @@ public class BlockingServlet extends HttpServlet {
response.getWriter().println("{ \"status\": \"ok\"}"); response.getWriter().println("{ \"status\": \"ok\"}");
} }
} }

View File

@ -21,7 +21,7 @@ class JettyServer {
server = new Server(threadPool); server = new Server(threadPool);
ServerConnector connector = new ServerConnector(server); ServerConnector connector = new ServerConnector(server);
connector.setPort(8090); connector.setPort(8090);
server.setConnectors(new Connector[]{connector}); server.setConnectors(new Connector[] { connector });
ServletHandler servletHandler = new ServletHandler(); ServletHandler servletHandler = new ServletHandler();
server.setHandler(servletHandler); server.setHandler(servletHandler);

View File

@ -14,81 +14,79 @@ import org.eclipse.jetty.webapp.WebAppContext;
*/ */
public class JettyServerFactory { public class JettyServerFactory {
/** /**
* Exposed context of the app. * Exposed context of the app.
*/ */
public final static String APP_PATH = "/myApp"; public final static String APP_PATH = "/myApp";
/** /**
* The server port. * The server port.
*/ */
public final static int SERVER_PORT = 13133; public final static int SERVER_PORT = 13133;
/** /**
* Private constructor to avoid instantiation. * Private constructor to avoid instantiation.
*/ */
private JettyServerFactory() { private JettyServerFactory() {
} }
/** /**
* Returns a simple server listening on port 80 with a timeout of 30 seconds * Returns a simple server listening on port 80 with a timeout of 30 seconds
* for connections and no handlers. * for connections and no handlers.
* *
* @return a server * @return a server
*/ */
public static Server createBaseServer() { public static Server createBaseServer() {
Server server = new Server(); Server server = new Server();
// Adds a connector for port 80 with a timeout of 30 seconds. // Adds a connector for port 80 with a timeout of 30 seconds.
ServerConnector connector = new ServerConnector(server); ServerConnector connector = new ServerConnector(server);
connector.setPort(SERVER_PORT); connector.setPort(SERVER_PORT);
connector.setHost("127.0.0.1"); connector.setHost("127.0.0.1");
connector.setIdleTimeout(30000); connector.setIdleTimeout(30000);
server.addConnector(connector); server.addConnector(connector);
return server; return server;
} }
/** /**
* Creates a server which delegates the request handling to a web * Creates a server which delegates the request handling to a web
* application. * application.
* *
* @return a server * @return a server
*/ */
public static Server createWebAppServer() { public static Server createWebAppServer() {
// Adds an handler to a server and returns it. // Adds an handler to a server and returns it.
Server server = createBaseServer(); Server server = createBaseServer();
String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war") String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath();
.getPath(); Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH);
Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH); server.setHandler(webAppHandler);
server.setHandler(webAppHandler);
return server; return server;
} }
/** /**
* Creates a server which delegates the request handling to both a logging * Creates a server which delegates the request handling to both a logging
* handler and to a web application, in this order. * handler and to a web application, in this order.
* *
* @return a server * @return a server
*/ */
public static Server createMultiHandlerServer() { public static Server createMultiHandlerServer() {
Server server = createBaseServer(); Server server = createBaseServer();
// Creates the handlers and adds them to the server. // Creates the handlers and adds them to the server.
HandlerCollection handlers = new HandlerCollection(); HandlerCollection handlers = new HandlerCollection();
String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war") String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath();
.getPath(); Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH);
Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH); handlers.addHandler(customRequestHandler);
handlers.addHandler(customRequestHandler);
Handler loggingRequestHandler = new LoggingRequestHandler(); Handler loggingRequestHandler = new LoggingRequestHandler();
handlers.addHandler(loggingRequestHandler); handlers.addHandler(loggingRequestHandler);
server.setHandler(handlers); server.setHandler(handlers);
return server; return server;
} }
} }

View File

@ -19,150 +19,149 @@ import org.slf4j.LoggerFactory;
*/ */
public class LoggingRequestHandler implements Handler { public class LoggingRequestHandler implements Handler {
/** /**
* Logger. * Logger.
*/ */
private final static Logger LOG = LoggerFactory.getLogger(LoggingRequestHandler.class); private final static Logger LOG = LoggerFactory.getLogger(LoggingRequestHandler.class);
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.eclipse.jetty.util.component.LifeCycle#addLifeCycleListener(org. * @see org.eclipse.jetty.util.component.LifeCycle#addLifeCycleListener(org.
* eclipse.jetty.util.component.LifeCycle.Listener) * eclipse.jetty.util.component.LifeCycle.Listener)
*/ */
@Override @Override
public void addLifeCycleListener(Listener arg0) { public void addLifeCycleListener(Listener arg0) {
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.eclipse.jetty.util.component.LifeCycle#isFailed() * @see org.eclipse.jetty.util.component.LifeCycle#isFailed()
*/ */
@Override @Override
public boolean isFailed() { public boolean isFailed() {
return false; return false;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.eclipse.jetty.util.component.LifeCycle#isRunning() * @see org.eclipse.jetty.util.component.LifeCycle#isRunning()
*/ */
@Override @Override
public boolean isRunning() { public boolean isRunning() {
return true; return true;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.eclipse.jetty.util.component.LifeCycle#isStarted() * @see org.eclipse.jetty.util.component.LifeCycle#isStarted()
*/ */
@Override @Override
public boolean isStarted() { public boolean isStarted() {
return true; return true;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.eclipse.jetty.util.component.LifeCycle#isStarting() * @see org.eclipse.jetty.util.component.LifeCycle#isStarting()
*/ */
@Override @Override
public boolean isStarting() { public boolean isStarting() {
return false; return false;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.eclipse.jetty.util.component.LifeCycle#isStopped() * @see org.eclipse.jetty.util.component.LifeCycle#isStopped()
*/ */
@Override @Override
public boolean isStopped() { public boolean isStopped() {
return false; return false;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.eclipse.jetty.util.component.LifeCycle#isStopping() * @see org.eclipse.jetty.util.component.LifeCycle#isStopping()
*/ */
@Override @Override
public boolean isStopping() { public boolean isStopping() {
return false; return false;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see * @see
* org.eclipse.jetty.util.component.LifeCycle#removeLifeCycleListener(org. * org.eclipse.jetty.util.component.LifeCycle#removeLifeCycleListener(org.
* eclipse.jetty.util.component.LifeCycle.Listener) * eclipse.jetty.util.component.LifeCycle.Listener)
*/ */
@Override @Override
public void removeLifeCycleListener(Listener arg0) { public void removeLifeCycleListener(Listener arg0) {
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.eclipse.jetty.util.component.LifeCycle#start() * @see org.eclipse.jetty.util.component.LifeCycle#start()
*/ */
@Override @Override
public void start() throws Exception { public void start() throws Exception {
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.eclipse.jetty.util.component.LifeCycle#stop() * @see org.eclipse.jetty.util.component.LifeCycle#stop()
*/ */
@Override @Override
public void stop() throws Exception { public void stop() throws Exception {
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.eclipse.jetty.server.Handler#destroy() * @see org.eclipse.jetty.server.Handler#destroy()
*/ */
@Override @Override
public void destroy() { public void destroy() {
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.eclipse.jetty.server.Handler#getServer() * @see org.eclipse.jetty.server.Handler#getServer()
*/ */
@Override @Override
public Server getServer() { public Server getServer() {
return null; return null;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.eclipse.jetty.server.Handler#handle(java.lang.String, * @see org.eclipse.jetty.server.Handler#handle(java.lang.String,
* org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, * org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse) * javax.servlet.http.HttpServletResponse)
*/ */
@Override @Override
public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3) public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3) throws IOException, ServletException {
throws IOException, ServletException { LOG.info("Received a new request");
LOG.info("Received a new request"); }
}
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server. * @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server.
* Server) * Server)
*/ */
@Override @Override
public void setServer(Server server) { public void setServer(Server server) {
} }
} }

View File

@ -5,7 +5,6 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.logging.Logger; import java.util.logging.Logger;
public class ChannelHandlerB extends ChannelInboundHandlerAdapter { public class ChannelHandlerB extends ChannelInboundHandlerAdapter {
private Logger logger = Logger.getLogger(getClass().getName()); private Logger logger = Logger.getLogger(getClass().getName());
@ -14,7 +13,7 @@ public class ChannelHandlerB extends ChannelInboundHandlerAdapter {
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.info("Exception Handled in ChannelHandler B"); logger.info("Exception Handled in ChannelHandler B");
logger.info(cause.getLocalizedMessage()); logger.info(cause.getLocalizedMessage());
//do more exception handling // do more exception handling
ctx.close(); ctx.close();
} }
} }

View File

@ -9,7 +9,7 @@ import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel;
public class NettyServerB { public class NettyServerB {
private int port; private int port;
@ -24,15 +24,11 @@ public class NettyServerB {
try { try {
ServerBootstrap b = new ServerBootstrap(); ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup) b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
.channel(NioServerSocketChannel.class) public void initChannel(SocketChannel ch) throws Exception {
.childHandler(new ChannelInitializer<SocketChannel>() { ch.pipeline().addLast(new ChannelHandlerA(), new ChannelHandlerB());
public void initChannel(SocketChannel ch) throws Exception { }
ch.pipeline().addLast(new ChannelHandlerA(), new ChannelHandlerB()); }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync(); // (7) ChannelFuture f = b.bind(port).sync(); // (7)
f.channel().closeFuture().sync(); f.channel().closeFuture().sync();
} finally { } finally {

View File

@ -22,9 +22,6 @@ public class RequestData {
@Override @Override
public String toString() { public String toString() {
return "RequestData{" + return "RequestData{" + "intValue=" + intValue + ", stringValue='" + stringValue + '\'' + '}';
"intValue=" + intValue +
", stringValue='" + stringValue + '\'' +
'}';
} }
} }

View File

@ -13,8 +13,6 @@ public class ResponseData {
@Override @Override
public String toString() { public String toString() {
return "ResponseData{" + return "ResponseData{" + "intValue=" + intValue + '}';
"intValue=" + intValue +
'}';
} }
} }

View File

@ -41,7 +41,7 @@ public class NeurophXOR {
ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2)); ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2));
ann.addLayer(3, outputLayer); ann.addLayer(3, outputLayer);
ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3)); ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3));
ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount()-1), false); ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount() - 1), false);
ann.setInputNeurons(inputLayer.getNeurons()); ann.setInputNeurons(inputLayer.getNeurons());
ann.setOutputNeurons(outputLayer.getNeurons()); ann.setOutputNeurons(outputLayer.getNeurons());
@ -55,13 +55,13 @@ public class NeurophXOR {
int outputSize = 1; int outputSize = 1;
DataSet ds = new DataSet(inputSize, outputSize); DataSet ds = new DataSet(inputSize, outputSize);
DataSetRow rOne = new DataSetRow(new double[] {0, 1}, new double[] {1}); DataSetRow rOne = new DataSetRow(new double[] { 0, 1 }, new double[] { 1 });
ds.addRow(rOne); ds.addRow(rOne);
DataSetRow rTwo = new DataSetRow(new double[] {1, 1}, new double[] {0}); DataSetRow rTwo = new DataSetRow(new double[] { 1, 1 }, new double[] { 0 });
ds.addRow(rTwo); ds.addRow(rTwo);
DataSetRow rThree = new DataSetRow(new double[] {0, 0}, new double[] {0}); DataSetRow rThree = new DataSetRow(new double[] { 0, 0 }, new double[] { 0 });
ds.addRow(rThree); ds.addRow(rThree);
DataSetRow rFour = new DataSetRow(new double[] {1, 0}, new double[] {1}); DataSetRow rFour = new DataSetRow(new double[] { 1, 0 }, new double[] { 1 });
ds.addRow(rFour); ds.addRow(rFour);
BackPropagation backPropagation = new BackPropagation(); BackPropagation backPropagation = new BackPropagation();

View File

@ -11,10 +11,7 @@ public class CustomExceptionHandler extends ExceptionHandler {
@Override @Override
public boolean handle(Throwable throwable) { public boolean handle(Throwable throwable) {
if (throwable.getClass() if (throwable.getClass().isAssignableFrom(RuntimeException.class) || throwable.getClass().isAssignableFrom(Error.class)) {
.isAssignableFrom(RuntimeException.class)
|| throwable.getClass()
.isAssignableFrom(Error.class)) {
return false; return false;
} else { } else {
logger.error("Caught Exception ", throwable); logger.error("Caught Exception ", throwable);

View File

@ -20,18 +20,14 @@ public class StreamUtilsExample {
public void zipAStreamWithIndex() { public void zipAStreamWithIndex() {
Stream<String> source = Stream.of("Foo", "Bar", "Baz"); Stream<String> source = Stream.of("Foo", "Bar", "Baz");
List<Indexed<String>> zipped = StreamUtils List<Indexed<String>> zipped = StreamUtils.zipWithIndex(source).collect(Collectors.toList());
.zipWithIndex(source)
.collect(Collectors.toList());
} }
public void zipAPairOfStreams() { public void zipAPairOfStreams() {
Stream<String> streamA = Stream.of("A", "B", "C"); Stream<String> streamA = Stream.of("A", "B", "C");
Stream<String> streamB = Stream.of("Apple", "Banana", "Carrot"); Stream<String> streamB = Stream.of("Apple", "Banana", "Carrot");
List<String> zipped = StreamUtils List<String> zipped = StreamUtils.zip(streamA, streamB, (a, b) -> a + " is for " + b).collect(Collectors.toList());
.zip(streamA, streamB, (a, b) -> a + " is for " + b)
.collect(Collectors.toList());
} }
public void zipThreeStreams() { public void zipThreeStreams() {
@ -39,9 +35,7 @@ public class StreamUtilsExample {
Stream<String> streamB = Stream.of("aggravating", "banausic", "complaisant"); Stream<String> streamB = Stream.of("aggravating", "banausic", "complaisant");
Stream<String> streamC = Stream.of("Apple", "Banana", "Carrot"); Stream<String> streamC = Stream.of("Apple", "Banana", "Carrot");
List<String> zipped = StreamUtils List<String> zipped = StreamUtils.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c).collect(Collectors.toList());
.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c)
.collect(Collectors.toList());
} }
public void mergeThreeStreams() { public void mergeThreeStreams() {
@ -79,24 +73,16 @@ public class StreamUtilsExample {
public void windowedStream() { public void windowedStream() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5); Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
List<List<Integer>> windows = StreamUtils List<List<Integer>> windows = StreamUtils.windowed(integerStream, 2).collect(toList());
.windowed(integerStream, 2) List<List<Integer>> windowsWithSkipIndex = StreamUtils.windowed(integerStream, 3, 2).collect(toList());
.collect(toList()); List<List<Integer>> windowsWithSkipIndexAndAllowLowerSize = StreamUtils.windowed(integerStream, 2, 2, true).collect(toList());
List<List<Integer>> windowsWithSkipIndex = StreamUtils
.windowed(integerStream, 3, 2)
.collect(toList());
List<List<Integer>> windowsWithSkipIndexAndAllowLowerSize = StreamUtils
.windowed(integerStream, 2, 2, true)
.collect(toList());
} }
public void groupRunsStreams() { public void groupRunsStreams() {
Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5); Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5);
List<List<Integer>> runs = StreamUtils List<List<Integer>> runs = StreamUtils.groupRuns(integerStream).collect(toList());
.groupRuns(integerStream)
.collect(toList());
} }
public void aggreagateOnBiElementPredicate() { public void aggreagateOnBiElementPredicate() {

View File

@ -19,45 +19,17 @@ public class QuartzExample {
Scheduler sched = schedFact.getScheduler(); Scheduler sched = schedFact.getScheduler();
JobDetail job = JobBuilder.newJob(SimpleJob.class) JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("myJob", "group1").usingJobData("jobSays", "Hello World!").usingJobData("myFloatValue", 3.141f).build();
.withIdentity("myJob", "group1")
.usingJobData("jobSays", "Hello World!")
.usingJobData("myFloatValue", 3.141f)
.build();
Trigger trigger = TriggerBuilder.newTrigger() Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTrigger", "group1").startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();
.withIdentity("myTrigger", "group1")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(40)
.repeatForever())
.build();
JobDetail jobA = JobBuilder.newJob(JobA.class) JobDetail jobA = JobBuilder.newJob(JobA.class).withIdentity("jobA", "group2").build();
.withIdentity("jobA", "group2")
.build();
JobDetail jobB = JobBuilder.newJob(JobB.class) JobDetail jobB = JobBuilder.newJob(JobB.class).withIdentity("jobB", "group2").build();
.withIdentity("jobB", "group2")
.build();
Trigger triggerA = TriggerBuilder.newTrigger() Trigger triggerA = TriggerBuilder.newTrigger().withIdentity("triggerA", "group2").startNow().withPriority(15).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();
.withIdentity("triggerA", "group2")
.startNow()
.withPriority(15)
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(40)
.repeatForever())
.build();
Trigger triggerB = TriggerBuilder.newTrigger() Trigger triggerB = TriggerBuilder.newTrigger().withIdentity("triggerB", "group2").startNow().withPriority(10).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(20).repeatForever()).build();
.withIdentity("triggerB", "group2")
.startNow()
.withPriority(10)
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(20)
.repeatForever())
.build();
sched.scheduleJob(job, trigger); sched.scheduleJob(job, trigger);
sched.scheduleJob(jobA, triggerA); sched.scheduleJob(jobA, triggerA);

View File

@ -8,8 +8,7 @@ import org.quartz.JobExecutionException;
public class SimpleJob implements Job { public class SimpleJob implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException { public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap dataMap = context.getJobDetail() JobDataMap dataMap = context.getJobDetail().getJobDataMap();
.getJobDataMap();
String jobSays = dataMap.getString("jobSays"); String jobSays = dataMap.getString("jobSays");
float myFloatValue = dataMap.getFloat("myFloatValue"); float myFloatValue = dataMap.getFloat("myFloatValue");

View File

@ -26,8 +26,6 @@ public interface GitHubBasicApi {
* @return GitHub Repository Contributors * @return GitHub Repository Contributors
*/ */
@GET("repos/{user}/{repo}/contributors") @GET("repos/{user}/{repo}/contributors")
Call<List<Contributor>> listRepoContributors( Call<List<Contributor>> listRepoContributors(@Path("user") String user, @Path("repo") String repo);
@Path("user") String user,
@Path("repo") String repo);
} }

View File

@ -7,8 +7,7 @@ public class GitHubBasicApp {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
String userName = "eugenp"; String userName = "eugenp";
List<String> topContributors = new GitHubBasicService() List<String> topContributors = new GitHubBasicService().getTopContributors(userName);
.getTopContributors(userName);
topContributors.forEach(System.out::println); topContributors.forEach(System.out::println);
} }
} }

View File

@ -16,45 +16,29 @@ class GitHubBasicService {
private GitHubBasicApi gitHubApi; private GitHubBasicApi gitHubApi;
GitHubBasicService() { GitHubBasicService() {
Retrofit retrofit = new Retrofit.Builder() Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).build();
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
gitHubApi = retrofit.create(GitHubBasicApi.class); gitHubApi = retrofit.create(GitHubBasicApi.class);
} }
List<String> getTopContributors(String userName) throws IOException { List<String> getTopContributors(String userName) throws IOException {
List<Repository> repos = gitHubApi List<Repository> repos = gitHubApi.listRepos(userName).execute().body();
.listRepos(userName)
.execute()
.body();
repos = repos != null ? repos : Collections.emptyList(); repos = repos != null ? repos : Collections.emptyList();
return repos.stream() return repos.stream().flatMap(repo -> getContributors(userName, repo)).sorted((a, b) -> b.getContributions() - a.getContributions()).map(Contributor::getName).distinct().sorted().collect(Collectors.toList());
.flatMap(repo -> getContributors(userName, repo))
.sorted((a, b) -> b.getContributions() - a.getContributions())
.map(Contributor::getName)
.distinct()
.sorted()
.collect(Collectors.toList());
} }
private Stream<Contributor> getContributors(String userName, Repository repo) { private Stream<Contributor> getContributors(String userName, Repository repo) {
List<Contributor> contributors = null; List<Contributor> contributors = null;
try { try {
contributors = gitHubApi contributors = gitHubApi.listRepoContributors(userName, repo.getName()).execute().body();
.listRepoContributors(userName, repo.getName())
.execute()
.body();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
contributors = contributors != null ? contributors : Collections.emptyList(); contributors = contributors != null ? contributors : Collections.emptyList();
return contributors.stream() return contributors.stream().filter(c -> c.getContributions() > 100);
.filter(c -> c.getContributions() > 100);
} }
} }

View File

@ -12,12 +12,15 @@ public class Contributor {
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public Integer getContributions() { public Integer getContributions() {
return contributions; return contributions;
} }
public void setContributions(Integer contributions) { public void setContributions(Integer contributions) {
this.contributions = contributions; this.contributions = contributions;
} }

View File

@ -9,12 +9,15 @@ public class Repository {
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
public void setDescription(String description) { public void setDescription(String description) {
this.description = description; this.description = description;
} }

View File

@ -26,8 +26,6 @@ public interface GitHubRxApi {
* @return GitHub Repository Contributors * @return GitHub Repository Contributors
*/ */
@GET("repos/{user}/{repo}/contributors") @GET("repos/{user}/{repo}/contributors")
Observable<List<Contributor>> listRepoContributors( Observable<List<Contributor>> listRepoContributors(@Path("user") String user, @Path("repo") String repo);
@Path("user") String user,
@Path("repo") String repo);
} }

View File

@ -6,7 +6,6 @@ public class GitHubRxApp {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
String userName = "eugenp"; String userName = "eugenp";
new GitHubRxService().getTopContributors(userName) new GitHubRxService().getTopContributors(userName).subscribe(System.out::println);
.subscribe(System.out::println);
} }
} }

View File

@ -11,23 +11,13 @@ class GitHubRxService {
private GitHubRxApi gitHubApi; private GitHubRxApi gitHubApi;
GitHubRxService() { GitHubRxService() {
Retrofit retrofit = new Retrofit.Builder() Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
gitHubApi = retrofit.create(GitHubRxApi.class); gitHubApi = retrofit.create(GitHubRxApi.class);
} }
Observable<String> getTopContributors(String userName) { Observable<String> getTopContributors(String userName) {
return gitHubApi.listRepos(userName) return gitHubApi.listRepos(userName).flatMapIterable(x -> x).flatMap(repo -> gitHubApi.listRepoContributors(userName, repo.getName())).flatMapIterable(x -> x).filter(c -> c.getContributions() > 100)
.flatMapIterable(x -> x) .sorted((a, b) -> b.getContributions() - a.getContributions()).map(Contributor::getName).distinct();
.flatMap(repo -> gitHubApi.listRepoContributors(userName, repo.getName()))
.flatMapIterable(x -> x)
.filter(c -> c.getContributions() > 100)
.sorted((a, b) -> b.getContributions() - a.getContributions())
.map(Contributor::getName)
.distinct();
} }
} }

View File

@ -13,19 +13,13 @@ public class GitHubServiceGenerator {
private static final String BASE_URL = "https://api.github.com/"; private static final String BASE_URL = "https://api.github.com/";
private static Retrofit.Builder builder private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create());
= new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build(); private static Retrofit retrofit = builder.build();
private static OkHttpClient.Builder httpClient private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
= new OkHttpClient.Builder();
private static HttpLoggingInterceptor logging private static HttpLoggingInterceptor logging = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC);
= new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BASIC);
public static <S> S createService(Class<S> serviceClass) { public static <S> S createService(Class<S> serviceClass) {
if (!httpClient.interceptors().contains(logging)) { if (!httpClient.interceptors().contains(logging)) {
@ -43,8 +37,7 @@ public class GitHubServiceGenerator {
@Override @Override
public Response intercept(Interceptor.Chain chain) throws IOException { public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request(); Request original = chain.request();
Request.Builder builder = original.newBuilder() Request.Builder builder = original.newBuilder().header("Authorization", token);
.header("Authorization", token);
Request request = builder.build(); Request request = builder.build();
return chain.proceed(request); return chain.proceed(request);
} }

View File

@ -11,15 +11,11 @@ import retrofit2.converter.gson.GsonConverterFactory;
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
//Manual creation // Manual creation
OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder() Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).client(httpClient.build()).build();
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
UserService service = retrofit.create(UserService.class); UserService service = retrofit.create(UserService.class);
//Using GitHubServiceGenerator // Using GitHubServiceGenerator
service = GitHubServiceGenerator.createService(UserService.class); service = GitHubServiceGenerator.createService(UserService.class);
Call<User> callSync = service.getUser("eugenp"); Call<User> callSync = service.getUser("eugenp");
Call<User> callAsync = service.getUser("eugenp"); Call<User> callAsync = service.getUser("eugenp");

View File

@ -9,7 +9,7 @@ public enum Commodity {
public final int price; public final int price;
Commodity(int price){ Commodity(int price) {
this.price = price; this.price = price;
} }

View File

@ -12,7 +12,8 @@ public class Member {
private int points; private int points;
private Member(int points) { private Member(int points) {
if (points < 0) throw new IllegalArgumentException("points must not be negative!"); if (points < 0)
throw new IllegalArgumentException("points must not be negative!");
this.points = points; this.points = points;
} }
@ -22,9 +23,12 @@ public class Member {
} }
public MemberGrade getGrade() { public MemberGrade getGrade() {
if (points < 1000) return Bronze; if (points < 1000)
else if (points >= 1000 && points < 5000) return Silver; return Bronze;
else return Gold; else if (points >= 1000 && points < 5000)
return Silver;
else
return Gold;
} }
public void spend(int moneySpent) { public void spend(int moneySpent) {

View File

@ -3,7 +3,7 @@ package com.baeldung.serenity.membership;
/** /**
* @author aiet * @author aiet
*/ */
public enum MemberGrade { public enum MemberGrade {
Bronze, Silver, Gold; Bronze, Silver, Gold;

View File

@ -22,7 +22,6 @@ public class OrderConverter {
} }
} }
public String convertOrderXMLtoEDIFACT(String path) throws IOException, SAXException { public String convertOrderXMLtoEDIFACT(String path) throws IOException, SAXException {
return convertDocumentWithTempalte(path, "/smooks/smooks-transform-edi.xml"); return convertDocumentWithTempalte(path, "/smooks/smooks-transform-edi.xml");
} }

View File

@ -15,7 +15,6 @@ public class Item {
private Double price; private Double price;
private Integer quantity; private Integer quantity;
public String getCode() { public String getCode() {
return code; return code;
} }
@ -42,13 +41,17 @@ public class Item {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || getClass() != o.getClass()) return false; return true;
if (o == null || getClass() != o.getClass())
return false;
Item item = (Item) o; Item item = (Item) o;
if (code != null ? !code.equals(item.code) : item.code != null) return false; if (code != null ? !code.equals(item.code) : item.code != null)
if (price != null ? !price.equals(item.price) : item.price != null) return false; return false;
if (price != null ? !price.equals(item.price) : item.price != null)
return false;
return quantity != null ? quantity.equals(item.quantity) : item.quantity == null; return quantity != null ? quantity.equals(item.quantity) : item.quantity == null;
} }
@ -62,10 +65,6 @@ public class Item {
@Override @Override
public String toString() { public String toString() {
return "Item{" + return "Item{" + "code='" + code + '\'' + ", price=" + price + ", quantity=" + quantity + '}';
"code='" + code + '\'' +
", price=" + price +
", quantity=" + quantity +
'}';
} }
} }

View File

@ -31,12 +31,15 @@ public class Supplier {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || getClass() != o.getClass()) return false; return true;
if (o == null || getClass() != o.getClass())
return false;
Supplier supplier = (Supplier) o; Supplier supplier = (Supplier) o;
if (name != null ? !name.equals(supplier.name) : supplier.name != null) return false; if (name != null ? !name.equals(supplier.name) : supplier.name != null)
return false;
return phoneNumber != null ? phoneNumber.equals(supplier.phoneNumber) : supplier.phoneNumber == null; return phoneNumber != null ? phoneNumber.equals(supplier.phoneNumber) : supplier.phoneNumber == null;
} }

View File

@ -44,7 +44,6 @@ public class Account {
@Override @Override
public String toString() { public String toString() {
return StmUtils.atomic((TxnCallable<String>) return StmUtils.atomic((TxnCallable<String>) txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn));
txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn));
} }
} }

View File

@ -15,69 +15,43 @@ import one.util.streamex.StreamEx;
public class StreamEX { public class StreamEX {
public static void main(String[] args) { public static void main(String[] args) {
//Collector shortcut methods (toList, toSet, groupingBy, joining, etc.) // Collector shortcut methods (toList, toSet, groupingBy, joining, etc.)
List<User> users = Arrays.asList( List<User> users = Arrays.asList(new User("name"), new User(), new User());
new User("name"), new User(), new User()); users.stream().map(User::getName).collect(Collectors.toList());
users.stream() List<String> userNames = StreamEx.of(users).map(User::getName).toList();
.map(User::getName) Map<Role, List<User>> role2users = StreamEx.of(users).groupingBy(User::getRole);
.collect(Collectors.toList());
List<String> userNames = StreamEx.of(users)
.map(User::getName)
.toList();
Map<Role, List<User>> role2users = StreamEx.of(users)
.groupingBy(User::getRole);
StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3" StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3"
//Selecting stream elements of specific type // Selecting stream elements of specific type
List usersAndRoles = Arrays.asList(new User(), new Role()); List usersAndRoles = Arrays.asList(new User(), new Role());
List<Role> roles = IntStreamEx.range(usersAndRoles.size()) List<Role> roles = IntStreamEx.range(usersAndRoles.size()).mapToObj(usersAndRoles::get).select(Role.class).toList();
.mapToObj(usersAndRoles::get)
.select(Role.class)
.toList();
System.out.println(roles); System.out.println(roles);
//adding elements to Stream // adding elements to Stream
List<String> appendedUsers = StreamEx.of(users) List<String> appendedUsers = StreamEx.of(users).map(User::getName).prepend("(none)").append("LAST").toList();
.map(User::getName)
.prepend("(none)")
.append("LAST")
.toList();
System.out.println(appendedUsers); System.out.println(appendedUsers);
//Removing unwanted elements and using the stream as Iterable: // Removing unwanted elements and using the stream as Iterable:
for (String line : StreamEx.of(users).map(User::getName) for (String line : StreamEx.of(users).map(User::getName).nonNull()) {
.nonNull()) {
System.out.println(line); System.out.println(line);
} }
//Selecting map keys by value predicate: // Selecting map keys by value predicate:
Map<String, Role> nameToRole = new HashMap<>(); Map<String, Role> nameToRole = new HashMap<>();
nameToRole.put("first", new Role()); nameToRole.put("first", new Role());
nameToRole.put("second", null); nameToRole.put("second", null);
Set<String> nonNullRoles = StreamEx. Set<String> nonNullRoles = StreamEx.ofKeys(nameToRole, Objects::nonNull).toSet();
ofKeys(nameToRole, Objects::nonNull)
.toSet();
System.out.println(nonNullRoles); System.out.println(nonNullRoles);
//Operating on key-value pairs: // Operating on key-value pairs:
Map<User, List<Role>> users2roles = transformMap(role2users); Map<User, List<Role>> users2roles = transformMap(role2users);
Map<String, String> mapToString = EntryStream.of(users2roles) Map<String, String> mapToString = EntryStream.of(users2roles).mapKeys(String::valueOf).mapValues(String::valueOf).toMap();
.mapKeys(String::valueOf) // Support of byte/char/short/float types:
.mapValues(String::valueOf) short[] src = { 1, 2, 3 };
.toMap(); char[] output = IntStreamEx.of(src).map(x -> x * 5).toCharArray();
//Support of byte/char/short/float types:
short[] src = {1, 2, 3};
char[] output = IntStreamEx.of(src)
.map(x -> x * 5)
.toCharArray();
} }
public double[] getDiffBetweenPairs(double... numbers) { public double[] getDiffBetweenPairs(double... numbers) {
return DoubleStreamEx.of(numbers) return DoubleStreamEx.of(numbers).pairMap((a, b) -> b - a).toArray();
.pairMap((a, b) -> b - a).toArray();
} }
public static Map<User, List<Role>> transformMap( public static Map<User, List<Role>> transformMap(Map<Role, List<User>> role2users) {
Map<Role, List<User>> role2users) { Map<User, List<Role>> users2roles = EntryStream.of(role2users).flatMapValues(List::stream).invert().grouping();
Map<User, List<Role>> users2roles = EntryStream.of(role2users)
.flatMapValues(List::stream)
.invert()
.grouping();
return users2roles; return users2roles;
} }

View File

@ -9,14 +9,14 @@ import org.apache.commons.io.IOUtils;
import org.springframework.util.StreamUtils; import org.springframework.util.StreamUtils;
public class CopyStream { public class CopyStream {
public static String getStringFromInputStream(InputStream input) throws IOException { public static String getStringFromInputStream(InputStream input) throws IOException {
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "UTF-8"); IOUtils.copy(input, writer, "UTF-8");
return writer.toString(); return writer.toString();
} }
public InputStream getNonClosingInputStream() throws IOException { public InputStream getNonClosingInputStream() throws IOException {
InputStream in = new FileInputStream("src/test/resources/input.txt"); InputStream in = new FileInputStream("src/test/resources/input.txt");
return StreamUtils.nonClosing(in); return StreamUtils.nonClosing(in);
} }
} }

View File

@ -5,7 +5,7 @@ import java.io.InputStream;
import org.springframework.util.StreamUtils; import org.springframework.util.StreamUtils;
public class DrainStream { public class DrainStream {
public InputStream getInputStream() { public InputStream getInputStream() {
return StreamUtils.emptyInput(); return StreamUtils.emptyInput();
} }
} }

View File

@ -9,10 +9,7 @@ import java.io.IOException;
/** /**
* Created by adi on 1/10/18. * Created by adi on 1/10/18.
*/ */
@WebServlet( @WebServlet(name = "com.baeldung.tomcat.programmatic.MyServlet", urlPatterns = { "/my-servlet" })
name = "com.baeldung.tomcat.programmatic.MyServlet",
urlPatterns = {"/my-servlet"}
)
public class MyServlet extends HttpServlet { public class MyServlet extends HttpServlet {
@Override @Override

View File

@ -15,29 +15,27 @@ public class ProgrammaticTomcat {
private Tomcat tomcat = null; private Tomcat tomcat = null;
//uncomment for live test // uncomment for live test
// public static void main(String[] args) throws LifecycleException, ServletException, URISyntaxException, IOException { // public static void main(String[] args) throws LifecycleException, ServletException, URISyntaxException, IOException {
// startTomcat(); // startTomcat();
// } // }
public void startTomcat() throws LifecycleException { public void startTomcat() throws LifecycleException {
tomcat = new Tomcat(); tomcat = new Tomcat();
tomcat.setPort(8080); tomcat.setPort(8080);
tomcat.setHostname("localhost"); tomcat.setHostname("localhost");
String appBase = "."; String appBase = ".";
tomcat tomcat.getHost().setAppBase(appBase);
.getHost()
.setAppBase(appBase);
File docBase = new File(System.getProperty("java.io.tmpdir")); File docBase = new File(System.getProperty("java.io.tmpdir"));
Context context = tomcat.addContext("", docBase.getAbsolutePath()); Context context = tomcat.addContext("", docBase.getAbsolutePath());
//add a servlet // add a servlet
Class servletClass = MyServlet.class; Class servletClass = MyServlet.class;
Tomcat.addServlet(context, servletClass.getSimpleName(), servletClass.getName()); Tomcat.addServlet(context, servletClass.getSimpleName(), servletClass.getName());
context.addServletMappingDecoded("/my-servlet/*", servletClass.getSimpleName()); context.addServletMappingDecoded("/my-servlet/*", servletClass.getSimpleName());
//add a filter and filterMapping // add a filter and filterMapping
Class filterClass = MyFilter.class; Class filterClass = MyFilter.class;
FilterDef myFilterDef = new FilterDef(); FilterDef myFilterDef = new FilterDef();
myFilterDef.setFilterClass(filterClass.getName()); myFilterDef.setFilterClass(filterClass.getName());
@ -50,10 +48,10 @@ public class ProgrammaticTomcat {
context.addFilterMap(myFilterMap); context.addFilterMap(myFilterMap);
tomcat.start(); tomcat.start();
//uncomment for live test // uncomment for live test
// tomcat // tomcat
// .getServer() // .getServer()
// .await(); // .await();
} }
public void stopTomcat() throws LifecycleException { public void stopTomcat() throws LifecycleException {

View File

@ -30,25 +30,17 @@ public class DocumentController {
@RequestMapping(path = "/generate/doc", method = RequestMethod.GET) @RequestMapping(path = "/generate/doc", method = RequestMethod.GET)
public void generateDocument(HttpServletResponse response) throws IOException { public void generateDocument(HttpServletResponse response) throws IOException {
ReportBuilder reportBuilder = new ReportBuilder(); ReportBuilder reportBuilder = new ReportBuilder();
ReportTemplateBuilder reportTemplateBuilder = new ReportTemplateBuilder() ReportTemplateBuilder reportTemplateBuilder = new ReportTemplateBuilder().documentPath("./src/main/resources/Letter.docx").documentName("Letter.docx").outputType(ReportOutputType.docx).readFileFromPath();
.documentPath("./src/main/resources/Letter.docx")
.documentName("Letter.docx")
.outputType(ReportOutputType.docx)
.readFileFromPath();
reportBuilder.template(reportTemplateBuilder.build()); reportBuilder.template(reportTemplateBuilder.build());
BandBuilder bandBuilder = new BandBuilder(); BandBuilder bandBuilder = new BandBuilder();
String json = FileUtils.readFileToString(new File("./src/main/resources/Data.json")); String json = FileUtils.readFileToString(new File("./src/main/resources/Data.json"));
ReportBand main = bandBuilder.name("Main") ReportBand main = bandBuilder.name("Main").query("Main", "parameter=param1 $.main", "json").build();
.query("Main", "parameter=param1 $.main", "json")
.build();
reportBuilder.band(main); reportBuilder.band(main);
Report report = reportBuilder.build(); Report report = reportBuilder.build();
Reporting reporting = new Reporting(); Reporting reporting = new Reporting();
reporting.setFormatterFactory(new DefaultFormatterFactory()); reporting.setFormatterFactory(new DefaultFormatterFactory());
reporting.setLoaderFactory( reporting.setLoaderFactory(new DefaultLoaderFactory().setJsonDataLoader(new JsonDataLoader()));
new DefaultLoaderFactory()
.setJsonDataLoader(new JsonDataLoader()));
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
reporting.runReport(new RunParams(report).param("param1", json), response.getOutputStream()); reporting.runReport(new RunParams(report).param("param1", json), response.getOutputStream());
} }

View File

@ -186,17 +186,12 @@ public class AsyncHttpClientTestCase {
WebSocket WEBSOCKET_CLIENT = null; WebSocket WEBSOCKET_CLIENT = null;
try { try {
WEBSOCKET_CLIENT = Dsl.asyncHttpClient() WEBSOCKET_CLIENT = Dsl.asyncHttpClient().prepareGet("ws://localhost:5590/websocket").addHeader("header_name", "header_value").addQueryParam("key", "value").setRequestTimeout(5000).execute(wsHandler).get();
.prepareGet("ws://localhost:5590/websocket")
.addHeader("header_name", "header_value")
.addQueryParam("key", "value")
.setRequestTimeout(5000)
.execute(wsHandler).get();
if (WEBSOCKET_CLIENT.isOpen()) { if (WEBSOCKET_CLIENT.isOpen()) {
WEBSOCKET_CLIENT.sendPingFrame(); WEBSOCKET_CLIENT.sendPingFrame();
WEBSOCKET_CLIENT.sendTextFrame("test message"); WEBSOCKET_CLIENT.sendTextFrame("test message");
WEBSOCKET_CLIENT.sendBinaryFrame(new byte[]{'t', 'e', 's', 't'}); WEBSOCKET_CLIENT.sendBinaryFrame(new byte[] { 't', 'e', 's', 't' });
} }
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -35,10 +35,7 @@ public class AsyncServiceLongRunningUnitTest {
public void givenAsyncService_whenInitialize_thenInitOccurs2() { public void givenAsyncService_whenInitialize_thenInitOccurs2() {
asyncService.initialize(); asyncService.initialize();
Callable<Boolean> isInitialized = asyncService::isInitialized; Callable<Boolean> isInitialized = asyncService::isInitialized;
await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS) await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS).atMost(Duration.FIVE_SECONDS).with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS).until(isInitialized);
.atMost(Duration.FIVE_SECONDS)
.with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS)
.until(isInitialized);
} }
@Test @Test
@ -60,9 +57,7 @@ public class AsyncServiceLongRunningUnitTest {
@Test @Test
public void givenAsyncService_whenInitialize_thenInitOccurs3() { public void givenAsyncService_whenInitialize_thenInitOccurs3() {
asyncService.initialize(); asyncService.initialize();
await().until(fieldIn(asyncService) await().until(fieldIn(asyncService).ofType(boolean.class).andWithName("initialized"), equalTo(true));
.ofType(boolean.class)
.andWithName("initialized"), equalTo(true));
} }
@Test @Test
@ -77,10 +72,6 @@ public class AsyncServiceLongRunningUnitTest {
@Test @Test
public void givenAsyncService_whenGetValue_thenExceptionIgnored() { public void givenAsyncService_whenGetValue_thenExceptionIgnored() {
asyncService.initialize(); asyncService.initialize();
given().ignoreException(IllegalStateException.class) given().ignoreException(IllegalStateException.class).await().atMost(Duration.FIVE_SECONDS).atLeast(Duration.FIVE_HUNDRED_MILLISECONDS).until(asyncService::getValue, equalTo(0L));
.await()
.atMost(Duration.FIVE_SECONDS)
.atLeast(Duration.FIVE_HUNDRED_MILLISECONDS)
.until(asyncService::getValue, equalTo(0L));
} }
} }

View File

@ -28,14 +28,11 @@ public class BouncyCastleLiveTest {
char[] keyPassword = "password".toCharArray(); char[] keyPassword = "password".toCharArray();
@Test @Test
public void givenCryptographicResource_whenOperationSuccess_returnTrue() public void givenCryptographicResource_whenOperationSuccess_returnTrue() throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException, KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException {
throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException,
KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException {
Security.addProvider(new BouncyCastleProvider()); Security.addProvider(new BouncyCastleProvider());
CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC"); CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC");
X509Certificate certificate = (X509Certificate) certFactory X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(new FileInputStream(certificatePath));
.generateCertificate(new FileInputStream(certificatePath));
KeyStore keystore = KeyStore.getInstance("PKCS12"); KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(new FileInputStream(privateKeyPath), p12Password); keystore.load(new FileInputStream(privateKeyPath), p12Password);
PrivateKey privateKey = (PrivateKey) keystore.getKey("baeldung", keyPassword); PrivateKey privateKey = (PrivateKey) keystore.getKey("baeldung", keyPassword);

View File

@ -21,14 +21,9 @@ public class ByteBuddyUnitTest {
@Test @Test
public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException { public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException {
DynamicType.Unloaded unloadedType = new ByteBuddy() DynamicType.Unloaded unloadedType = new ByteBuddy().subclass(Object.class).method(ElementMatchers.isToString()).intercept(FixedValue.value("Hello World ByteBuddy!")).make();
.subclass(Object.class)
.method(ElementMatchers.isToString())
.intercept(FixedValue.value("Hello World ByteBuddy!"))
.make();
Class<?> dynamicType = unloadedType.load(getClass().getClassLoader()) Class<?> dynamicType = unloadedType.load(getClass().getClassLoader()).getLoaded();
.getLoaded();
assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!"); assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!");
} }
@ -36,12 +31,7 @@ public class ByteBuddyUnitTest {
@Test @Test
public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception { public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception {
ByteBuddyAgent.install(); ByteBuddyAgent.install();
new ByteBuddy() new ByteBuddy().redefine(Foo.class).method(named("sayHelloFoo")).intercept(FixedValue.value("Hello Foo Redefined")).make().load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
.redefine(Foo.class)
.method(named("sayHelloFoo"))
.intercept(FixedValue.value("Hello Foo Redefined"))
.make()
.load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
Foo f = new Foo(); Foo f = new Foo();
assertEquals(f.sayHelloFoo(), "Hello Foo Redefined"); assertEquals(f.sayHelloFoo(), "Hello Foo Redefined");
} }
@ -49,34 +39,16 @@ public class ByteBuddyUnitTest {
@Test @Test
public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException { public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException {
String r = new ByteBuddy() String r = new ByteBuddy().subclass(Foo.class).method(named("sayHelloFoo").and(isDeclaredBy(Foo.class).and(returns(String.class)))).intercept(MethodDelegation.to(Bar.class)).make().load(getClass().getClassLoader()).getLoaded().newInstance()
.subclass(Foo.class) .sayHelloFoo();
.method(
named("sayHelloFoo")
.and(isDeclaredBy(Foo.class)
.and(returns(String.class)))
)
.intercept(MethodDelegation.to(Bar.class))
.make()
.load(getClass().getClassLoader())
.getLoaded()
.newInstance()
.sayHelloFoo();
assertEquals(r, Bar.sayHelloBar()); assertEquals(r, Bar.sayHelloBar());
} }
@Test @Test
public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception { public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception {
Class<?> type = new ByteBuddy() Class<?> type = new ByteBuddy().subclass(Object.class).name("MyClassName").defineMethod("custom", String.class, Modifier.PUBLIC).intercept(MethodDelegation.to(Bar.class)).defineField("x", String.class, Modifier.PUBLIC).make()
.subclass(Object.class) .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
.name("MyClassName")
.defineMethod("custom", String.class, Modifier.PUBLIC)
.intercept(MethodDelegation.to(Bar.class))
.defineField("x", String.class, Modifier.PUBLIC)
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
Method m = type.getDeclaredMethod("custom", null); Method m = type.getDeclaredMethod("custom", null);
@ -85,5 +57,4 @@ public class ByteBuddyUnitTest {
} }
} }

View File

@ -16,10 +16,7 @@ public class CaffeineUnitTest {
@Test @Test
public void givenCache_whenPopulate_thenValueStored() { public void givenCache_whenPopulate_thenValueStored() {
Cache<String, DataObject> cache = Caffeine.newBuilder() Cache<String, DataObject> cache = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).maximumSize(100).build();
.expireAfterWrite(1, TimeUnit.MINUTES)
.maximumSize(100)
.build();
String key = "A"; String key = "A";
DataObject dataObject = cache.getIfPresent(key); DataObject dataObject = cache.getIfPresent(key);
@ -44,10 +41,7 @@ public class CaffeineUnitTest {
@Test @Test
public void givenLoadingCache_whenGet_thenValuePopulated() { public void givenLoadingCache_whenGet_thenValuePopulated() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder() LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
.maximumSize(100)
.expireAfterWrite(1, TimeUnit.MINUTES)
.build(k -> DataObject.get("Data for " + k));
String key = "A"; String key = "A";
DataObject dataObject = cache.get(key); DataObject dataObject = cache.get(key);
@ -63,10 +57,7 @@ public class CaffeineUnitTest {
@Test @Test
public void givenAsyncLoadingCache_whenGet_thenValuePopulated() { public void givenAsyncLoadingCache_whenGet_thenValuePopulated() {
AsyncLoadingCache<String, DataObject> cache = Caffeine.newBuilder() AsyncLoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).buildAsync(k -> DataObject.get("Data for " + k));
.maximumSize(100)
.expireAfterWrite(1, TimeUnit.MINUTES)
.buildAsync(k -> DataObject.get("Data for " + k));
String key = "A"; String key = "A";
cache.get(key).thenAccept(dataObject -> { cache.get(key).thenAccept(dataObject -> {
@ -74,16 +65,12 @@ public class CaffeineUnitTest {
assertEquals("Data for " + key, dataObject.getData()); assertEquals("Data for " + key, dataObject.getData());
}); });
cache.getAll(Arrays.asList("A", "B", "C")) cache.getAll(Arrays.asList("A", "B", "C")).thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size()));
.thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size()));
} }
@Test @Test
public void givenLoadingCacheWithSmallSize_whenPut_thenSizeIsConstant() { public void givenLoadingCacheWithSmallSize_whenPut_thenSizeIsConstant() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder() LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(1).refreshAfterWrite(10, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
.maximumSize(1)
.refreshAfterWrite(10, TimeUnit.MINUTES)
.build(k -> DataObject.get("Data for " + k));
assertEquals(0, cache.estimatedSize()); assertEquals(0, cache.estimatedSize());
@ -99,10 +86,7 @@ public class CaffeineUnitTest {
@Test @Test
public void givenLoadingCacheWithWeigher_whenPut_thenSizeIsConstant() { public void givenLoadingCacheWithWeigher_whenPut_thenSizeIsConstant() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder() LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumWeight(10).weigher((k, v) -> 5).build(k -> DataObject.get("Data for " + k));
.maximumWeight(10)
.weigher((k,v) -> 5)
.build(k -> DataObject.get("Data for " + k));
assertEquals(0, cache.estimatedSize()); assertEquals(0, cache.estimatedSize());
@ -122,20 +106,11 @@ public class CaffeineUnitTest {
@Test @Test
public void givenTimeEvictionCache_whenTimeLeft_thenValueEvicted() { public void givenTimeEvictionCache_whenTimeLeft_thenValueEvicted() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder() LoadingCache<String, DataObject> cache = Caffeine.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
.expireAfterAccess(5, TimeUnit.MINUTES)
.build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder() cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).weakKeys().weakValues().build(k -> DataObject.get("Data for " + k));
.expireAfterWrite(10, TimeUnit.SECONDS)
.weakKeys()
.weakValues()
.build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder() cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).softValues().build(k -> DataObject.get("Data for " + k));
.expireAfterWrite(10, TimeUnit.SECONDS)
.softValues()
.build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder().expireAfter(new Expiry<String, DataObject>() { cache = Caffeine.newBuilder().expireAfter(new Expiry<String, DataObject>() {
@Override @Override
@ -154,17 +129,12 @@ public class CaffeineUnitTest {
} }
}).build(k -> DataObject.get("Data for " + k)); }).build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder() cache = Caffeine.newBuilder().refreshAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
.refreshAfterWrite(1, TimeUnit.MINUTES)
.build(k -> DataObject.get("Data for " + k));
} }
@Test @Test
public void givenCache_whenStatsEnabled_thenStatsRecorded() { public void givenCache_whenStatsEnabled_thenStatsRecorded() {
LoadingCache<String, DataObject> cache = Caffeine.newBuilder() LoadingCache<String, DataObject> cache = Caffeine.newBuilder().maximumSize(100).recordStats().build(k -> DataObject.get("Data for " + k));
.maximumSize(100)
.recordStats()
.build(k -> DataObject.get("Data for " + k));
cache.get("A"); cache.get("A");
cache.get("A"); cache.get("A");

View File

@ -1,6 +1,5 @@
package com.baeldung.cglib.proxy; package com.baeldung.cglib.proxy;
import net.sf.cglib.beans.BeanGenerator; import net.sf.cglib.beans.BeanGenerator;
import org.junit.Test; import org.junit.Test;
@ -12,21 +11,17 @@ public class BeanGeneratorIntegrationTest {
@Test @Test
public void givenBeanCreator_whenAddProperty_thenClassShouldHaveFieldValue() throws Exception { public void givenBeanCreator_whenAddProperty_thenClassShouldHaveFieldValue() throws Exception {
//given // given
BeanGenerator beanGenerator = new BeanGenerator(); BeanGenerator beanGenerator = new BeanGenerator();
//when // when
beanGenerator.addProperty("name", String.class); beanGenerator.addProperty("name", String.class);
Object myBean = beanGenerator.create(); Object myBean = beanGenerator.create();
Method setter = myBean Method setter = myBean.getClass().getMethod("setName", String.class);
.getClass()
.getMethod("setName", String.class);
setter.invoke(myBean, "some string value set by a cglib"); setter.invoke(myBean, "some string value set by a cglib");
//then // then
Method getter = myBean Method getter = myBean.getClass().getMethod("getName");
.getClass()
.getMethod("getName");
assertEquals("some string value set by a cglib", getter.invoke(myBean)); assertEquals("some string value set by a cglib", getter.invoke(myBean));
} }
} }

View File

@ -14,14 +14,11 @@ public class MixinUnitTest {
@Test @Test
public void givenTwoClasses_whenMixedIntoOne_thenMixinShouldHaveMethodsFromBothClasses() throws Exception { public void givenTwoClasses_whenMixedIntoOne_thenMixinShouldHaveMethodsFromBothClasses() throws Exception {
//when // when
Mixin mixin = Mixin.create( Mixin mixin = Mixin.create(new Class[] { Interface1.class, Interface2.class, MixinInterface.class }, new Object[] { new Class1(), new Class2() });
new Class[]{Interface1.class, Interface2.class, MixinInterface.class},
new Object[]{new Class1(), new Class2()}
);
MixinInterface mixinDelegate = (MixinInterface) mixin; MixinInterface mixinDelegate = (MixinInterface) mixin;
//then // then
assertEquals("first behaviour", mixinDelegate.first()); assertEquals("first behaviour", mixinDelegate.first());
assertEquals("second behaviour", mixinDelegate.second()); assertEquals("second behaviour", mixinDelegate.second());
} }

View File

@ -10,34 +10,34 @@ import static org.junit.Assert.assertEquals;
public class ProxyIntegrationTest { public class ProxyIntegrationTest {
@Test @Test
public void givenPersonService_whenSayHello_thenReturnResult() { public void givenPersonService_whenSayHello_thenReturnResult() {
//given // given
PersonService personService = new PersonService(); PersonService personService = new PersonService();
//when // when
String res = personService.sayHello("Tom"); String res = personService.sayHello("Tom");
//then // then
assertEquals(res, "Hello Tom"); assertEquals(res, "Hello Tom");
} }
@Test @Test
public void givenEnhancerProxy_whenExtendPersonService_thenInterceptMethod() throws Exception { public void givenEnhancerProxy_whenExtendPersonService_thenInterceptMethod() throws Exception {
//given // given
Enhancer enhancer = new Enhancer(); Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersonService.class); enhancer.setSuperclass(PersonService.class);
enhancer.setCallback((FixedValue) () -> "Hello Tom!"); enhancer.setCallback((FixedValue) () -> "Hello Tom!");
PersonService proxy = (PersonService) enhancer.create(); PersonService proxy = (PersonService) enhancer.create();
//when // when
String res = proxy.sayHello(null); String res = proxy.sayHello(null);
//then // then
assertEquals("Hello Tom!", res); assertEquals("Hello Tom!", res);
} }
@Test @Test
public void givenEnhancer_whenExecuteMethodOnProxy_thenInterceptOnlyStringReturnTypeMethod() throws Exception { public void givenEnhancer_whenExecuteMethodOnProxy_thenInterceptOnlyStringReturnTypeMethod() throws Exception {
//given // given
Enhancer enhancer = new Enhancer(); Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersonService.class); enhancer.setSuperclass(PersonService.class);
enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> { enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
@ -48,10 +48,10 @@ public class ProxyIntegrationTest {
} }
}); });
//when // when
PersonService proxy = (PersonService) enhancer.create(); PersonService proxy = (PersonService) enhancer.create();
//then // then
assertEquals("Hello Tom!", proxy.sayHello(null)); assertEquals("Hello Tom!", proxy.sayHello(null));
int lengthOfName = proxy.lengthOfName("Mary"); int lengthOfName = proxy.lengthOfName("Mary");
assertEquals(4, lengthOfName); assertEquals(4, lengthOfName);

View File

@ -10,8 +10,7 @@ import org.junit.Test;
public class CourseServiceTest { public class CourseServiceTest {
@Test @Test
public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues() public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Course course = new Course(); Course course = new Course();
String name = "Computer Science"; String name = "Computer Science";
List<String> codes = Arrays.asList("CS", "CS01"); List<String> codes = Arrays.asList("CS", "CS01");
@ -36,8 +35,7 @@ public class CourseServiceTest {
} }
@Test @Test
public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWithSameName() public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWithSameName() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Course course = new Course(); Course course = new Course();
course.setName("Computer Science"); course.setName("Computer Science");
course.setCodes(Arrays.asList("CS")); course.setCodes(Arrays.asList("CS"));

View File

@ -1,6 +1,5 @@
package com.baeldung.commons.collections; package com.baeldung.commons.collections;
import com.baeldung.commons.collectionutil.Address; import com.baeldung.commons.collectionutil.Address;
import com.baeldung.commons.collectionutil.Customer; import com.baeldung.commons.collectionutil.Customer;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
@ -21,7 +20,6 @@ import static org.junit.Assert.assertTrue;
public class CollectionUtilsGuideTest { public class CollectionUtilsGuideTest {
Customer customer1 = new Customer(1, "Daniel", 123456l, "locality1", "city1", "1234"); Customer customer1 = new Customer(1, "Daniel", 123456l, "locality1", "city1", "1234");
Customer customer4 = new Customer(4, "Bob", 456789l, "locality4", "city4", "4567"); Customer customer4 = new Customer(4, "Bob", 456789l, "locality4", "city4", "4567");
List<Customer> list1, list2, list3, linkedList1; List<Customer> list1, list2, list3, linkedList1;
@ -77,8 +75,8 @@ public class CollectionUtilsGuideTest {
} }
}); });
//filterInverse does the opposite. It removes the element from the list if the Predicate returns true // filterInverse does the opposite. It removes the element from the list if the Predicate returns true
//select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection // select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection
assertTrue(isModified && linkedList1.size() == 2); assertTrue(isModified && linkedList1.size() == 2);
} }
@ -88,8 +86,8 @@ public class CollectionUtilsGuideTest {
List<Customer> emptyList = new ArrayList<>(); List<Customer> emptyList = new ArrayList<>();
List<Customer> nullList = null; List<Customer> nullList = null;
//Very handy at times where we want to check if a collection is not null and not empty too. // Very handy at times where we want to check if a collection is not null and not empty too.
//isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading // isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading
assertTrue(CollectionUtils.isNotEmpty(list1)); assertTrue(CollectionUtils.isNotEmpty(list1));
assertTrue(CollectionUtils.isEmpty(nullList)); assertTrue(CollectionUtils.isEmpty(nullList));
assertTrue(CollectionUtils.isEmpty(emptyList)); assertTrue(CollectionUtils.isEmpty(emptyList));

View File

@ -27,16 +27,8 @@ import static org.junit.Assert.assertTrue;
public class MapUtilsTest { public class MapUtilsTest {
private String[][] color2DArray = new String[][]{ private String[][] color2DArray = new String[][] { { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } };
{"RED", "#FF0000"}, private String[] color1DArray = new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF" };
{"GREEN", "#00FF00"},
{"BLUE", "#0000FF"}
};
private String[] color1DArray = new String[]{
"RED", "#FF0000",
"GREEN", "#00FF00",
"BLUE", "#0000FF"
};
private Map<String, String> colorMap; private Map<String, String> colorMap;
@Before @Before
@ -92,34 +84,26 @@ public class MapUtilsTest {
Map<String, String> invColorMap = MapUtils.invertMap(this.colorMap); Map<String, String> invColorMap = MapUtils.invertMap(this.colorMap);
int size = invColorMap.size(); int size = invColorMap.size();
Assertions.assertThat(invColorMap) Assertions.assertThat(invColorMap).hasSameSizeAs(colorMap).containsKeys(this.colorMap.values().toArray(new String[size])).containsValues(this.colorMap.keySet().toArray(new String[size]));
.hasSameSizeAs(colorMap)
.containsKeys(this.colorMap.values().toArray(new String[size]))
.containsValues(this.colorMap.keySet().toArray(new String[size]));
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() { public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() {
Map<String, String> rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll( Map<String, String> rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll(new HashMap<String, String>(), this.color1DArray));
new HashMap<String, String>(),
this.color1DArray));
rgbMap.put("ORANGE", "#FFA500"); rgbMap.put("ORANGE", "#FFA500");
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() { public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() {
Map<String, String> uniqValuesMap Map<String, String> uniqValuesMap = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate());
= MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate());
uniqValuesMap.put("NEW_RED", "#FF0000"); uniqValuesMap.put("NEW_RED", "#FF0000");
} }
@Test @Test
public void whenCreateLazyMap_theMapIsCreated() { public void whenCreateLazyMap_theMapIsCreated() {
Map<Integer, String> intStrMap = MapUtils.lazyMap( Map<Integer, String> intStrMap = MapUtils.lazyMap(new HashMap<Integer, String>(), TransformerUtils.stringValueTransformer());
new HashMap<Integer, String>(),
TransformerUtils.stringValueTransformer());
assertThat(intStrMap, is(anEmptyMap())); assertThat(intStrMap, is(anEmptyMap()));

View File

@ -17,8 +17,7 @@ public class SetUtilsUnitTest {
public void givenSetAndPredicate_whenPredicatedSet_thenValidateSet_and_throw_IllegalArgumentException() { public void givenSetAndPredicate_whenPredicatedSet_thenValidateSet_and_throw_IllegalArgumentException() {
Set<String> sourceSet = new HashSet<>(); Set<String> sourceSet = new HashSet<>();
sourceSet.addAll(Arrays.asList("London", "Lagos", "Err Source1")); sourceSet.addAll(Arrays.asList("London", "Lagos", "Err Source1"));
Set<String> validatingSet Set<String> validatingSet = SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L"));
= SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L"));
validatingSet.add("Err Source2"); validatingSet.add("Err Source2");
} }

View File

@ -14,8 +14,8 @@ import static org.junit.Assert.assertEquals;
public class OrderedMapUnitTest { public class OrderedMapUnitTest {
private String[] names = {"Emily", "Mathew", "Rose", "John", "Anna"}; private String[] names = { "Emily", "Mathew", "Rose", "John", "Anna" };
private Integer[] ages = {37, 28, 40, 36, 21}; private Integer[] ages = { 37, 28, 40, 36, 21 };
private int RUNNERS_COUNT = names.length; private int RUNNERS_COUNT = names.length;

View File

@ -18,8 +18,7 @@ public class BagTests {
@Test @Test
public void givenMultipleCopies_whenAdded_theCountIsKept() { public void givenMultipleCopies_whenAdded_theCountIsKept() {
Bag<Integer> bag = new HashBag<>( Bag<Integer> bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
assertThat(bag.getCount(1), equalTo(2)); assertThat(bag.getCount(1), equalTo(2));
} }
@ -65,8 +64,7 @@ public class BagTests {
@Test @Test
public void givenMultipleCopies_whenRemove_allAreRemoved() { public void givenMultipleCopies_whenRemove_allAreRemoved() {
Bag<Integer> bag = new HashBag<>( Bag<Integer> bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
// From 3 we delete 1, 2 remain // From 3 we delete 1, 2 remain
bag.remove(3, 1); bag.remove(3, 1);
@ -79,8 +77,7 @@ public class BagTests {
@Test @Test
public void givenTree_whenDuplicateElementsAdded_thenSort() { public void givenTree_whenDuplicateElementsAdded_thenSort() {
TreeBag<Integer> bag = new TreeBag<>( TreeBag<Integer> bag = new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }));
Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }));
assertThat(bag.first(), equalTo(1)); assertThat(bag.first(), equalTo(1));
assertThat(bag.getCount(bag.first()), equalTo(2)); assertThat(bag.getCount(bag.first()), equalTo(2));
@ -90,8 +87,7 @@ public class BagTests {
@Test @Test
public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() { public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() {
SortedBag<Integer> bag = CollectionSortedBag SortedBag<Integer> bag = CollectionSortedBag.collectionSortedBag(new TreeBag<>());
.collectionSortedBag(new TreeBag<>());
bag.add(1); bag.add(1);
assertThat(bag.add(1), is((true))); assertThat(bag.add(1), is((true)));
@ -99,9 +95,7 @@ public class BagTests {
@Test @Test
public void givenSortedBag_whenDuplicateElementsAdded_thenSort() { public void givenSortedBag_whenDuplicateElementsAdded_thenSort() {
SynchronizedSortedBag<Integer> bag = SynchronizedSortedBag SynchronizedSortedBag<Integer> bag = SynchronizedSortedBag.synchronizedSortedBag(new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })));
.synchronizedSortedBag(new TreeBag<>(
Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })));
assertThat(bag.first(), equalTo(1)); assertThat(bag.first(), equalTo(1));
assertThat(bag.getCount(bag.first()), equalTo(2)); assertThat(bag.getCount(bag.first()), equalTo(2));

View File

@ -29,10 +29,7 @@ public class CSVReaderWriterTest {
@Test @Test
public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException { public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException {
Reader in = new FileReader("src/test/resources/book.csv"); Reader in = new FileReader("src/test/resources/book.csv");
Iterable<CSVRecord> records = CSVFormat.DEFAULT Iterable<CSVRecord> records = CSVFormat.DEFAULT.withHeader(HEADERS).withFirstRecordAsHeader().parse(in);
.withHeader(HEADERS)
.withFirstRecordAsHeader()
.parse(in);
for (CSVRecord record : records) { for (CSVRecord record : records) {
String author = record.get("author"); String author = record.get("author");
String title = record.get("title"); String title = record.get("title");
@ -52,9 +49,7 @@ public class CSVReaderWriterTest {
} }
}); });
} }
assertEquals(EXPECTED_FILESTREAM, sw assertEquals(EXPECTED_FILESTREAM, sw.toString().trim());
.toString()
.trim());
} }
} }

View File

@ -47,10 +47,8 @@ public class DbUtilsUnitTest {
List<Map<String, Object>> list = runner.query(connection, "SELECT * FROM employee", beanListHandler); List<Map<String, Object>> list = runner.query(connection, "SELECT * FROM employee", beanListHandler);
assertEquals(list.size(), 5); assertEquals(list.size(), 5);
assertEquals(list.get(0) assertEquals(list.get(0).get("firstname"), "John");
.get("firstname"), "John"); assertEquals(list.get(4).get("firstname"), "Christian");
assertEquals(list.get(4)
.get("firstname"), "Christian");
} }
@Test @Test
@ -61,10 +59,8 @@ public class DbUtilsUnitTest {
List<Employee> employeeList = runner.query(connection, "SELECT * FROM employee", beanListHandler); List<Employee> employeeList = runner.query(connection, "SELECT * FROM employee", beanListHandler);
assertEquals(employeeList.size(), 5); assertEquals(employeeList.size(), 5);
assertEquals(employeeList.get(0) assertEquals(employeeList.get(0).getFirstName(), "John");
.getFirstName(), "John"); assertEquals(employeeList.get(4).getFirstName(), "Christian");
assertEquals(employeeList.get(4)
.getFirstName(), "Christian");
} }
@Test @Test
@ -85,12 +81,8 @@ public class DbUtilsUnitTest {
QueryRunner runner = new QueryRunner(); QueryRunner runner = new QueryRunner();
List<Employee> employees = runner.query(connection, "SELECT * FROM employee", employeeHandler); List<Employee> employees = runner.query(connection, "SELECT * FROM employee", employeeHandler);
assertEquals(employees.get(0) assertEquals(employees.get(0).getEmails().size(), 2);
.getEmails() assertEquals(employees.get(2).getEmails().size(), 3);
.size(), 2);
assertEquals(employees.get(2)
.getEmails()
.size(), 3);
assertNotNull(employees.get(0).getEmails().get(0).getEmployeeId()); assertNotNull(employees.get(0).getEmails().get(0).getEmployeeId());
} }

View File

@ -25,30 +25,23 @@ import java.nio.charset.Charset;
public class CommonsIOUnitTest { public class CommonsIOUnitTest {
@Test @Test
public void whenCopyANDReadFileTesttxt_thenMatchExpectedData() public void whenCopyANDReadFileTesttxt_thenMatchExpectedData() throws IOException {
throws IOException {
String expectedData = "Hello World from fileTest.txt!!!"; String expectedData = "Hello World from fileTest.txt!!!";
File file = FileUtils.getFile(getClass().getClassLoader() File file = FileUtils.getFile(getClass().getClassLoader().getResource("fileTest.txt").getPath());
.getResource("fileTest.txt")
.getPath());
File tempDir = FileUtils.getTempDirectory(); File tempDir = FileUtils.getTempDirectory();
FileUtils.copyFileToDirectory(file, tempDir); FileUtils.copyFileToDirectory(file, tempDir);
File newTempFile = FileUtils.getFile(tempDir, file.getName()); File newTempFile = FileUtils.getFile(tempDir, file.getName());
String data = FileUtils.readFileToString(newTempFile, String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset());
Charset.defaultCharset());
Assert.assertEquals(expectedData, data.trim()); Assert.assertEquals(expectedData, data.trim());
} }
@Test @Test
public void whenUsingFileNameUtils_thenshowdifferentFileOperations() public void whenUsingFileNameUtils_thenshowdifferentFileOperations() throws IOException {
throws IOException {
String path = getClass().getClassLoader() String path = getClass().getClassLoader().getResource("fileTest.txt").getPath();
.getResource("fileTest.txt")
.getPath();
String fullPath = FilenameUtils.getFullPath(path); String fullPath = FilenameUtils.getFullPath(path);
String extension = FilenameUtils.getExtension(path); String extension = FilenameUtils.getExtension(path);
@ -60,70 +53,54 @@ public class CommonsIOUnitTest {
} }
@Test @Test
public void whenUsingFileSystemUtils_thenDriveFreeSpace() public void whenUsingFileSystemUtils_thenDriveFreeSpace() throws IOException {
throws IOException {
long freeSpace = FileSystemUtils.freeSpaceKb("/"); long freeSpace = FileSystemUtils.freeSpaceKb("/");
} }
@SuppressWarnings("resource") @SuppressWarnings("resource")
@Test @Test
public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams() public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams() throws IOException {
throws IOException {
final String str = "Hello World."; final String str = "Hello World.";
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes()); ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1,outputStream2); FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);
new TeeInputStream(inputStream, teeOutputStream, true).read(new byte[str.length()]); new TeeInputStream(inputStream, teeOutputStream, true).read(new byte[str.length()]);
Assert.assertEquals(str, String.valueOf(outputStream1)); Assert.assertEquals(str, String.valueOf(outputStream1));
Assert.assertEquals(str, String.valueOf(outputStream2)); Assert.assertEquals(str, String.valueOf(outputStream2));
} }
@Test @Test
public void whenGetFilewithNameFileFilter_thenFindfileTesttxt() public void whenGetFilewithNameFileFilter_thenFindfileTesttxt() throws IOException {
throws IOException {
final String testFile = "fileTest.txt"; final String testFile = "fileTest.txt";
String path = getClass().getClassLoader() String path = getClass().getClassLoader().getResource(testFile).getPath();
.getResource(testFile)
.getPath();
File dir = FileUtils.getFile(FilenameUtils.getFullPath(path)); File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));
String[] possibleNames = { "NotThisOne", testFile }; String[] possibleNames = { "NotThisOne", testFile };
Assert.assertEquals(testFile, Assert.assertEquals(testFile, dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]);
dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]);
} }
@Test @Test
public void whenGetFilewith_ANDFileFilter_thenFindsampletxt() public void whenGetFilewith_ANDFileFilter_thenFindsampletxt() throws IOException {
throws IOException {
String path = getClass().getClassLoader() String path = getClass().getClassLoader().getResource("fileTest.txt").getPath();
.getResource("fileTest.txt")
.getPath();
File dir = FileUtils.getFile(FilenameUtils.getFullPath(path)); File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));
Assert.assertEquals("sample.txt", Assert.assertEquals("sample.txt", dir.list(new AndFileFilter(new WildcardFileFilter("*ple*", IOCase.INSENSITIVE), new SuffixFileFilter("txt")))[0]);
dir.list(new AndFileFilter(
new WildcardFileFilter("*ple*", IOCase.INSENSITIVE),
new SuffixFileFilter("txt")))[0]);
} }
@Test @Test
public void whenSortDirWithPathFileComparator_thenFirstFileaaatxt() public void whenSortDirWithPathFileComparator_thenFirstFileaaatxt() throws IOException {
throws IOException {
PathFileComparator pathFileComparator = new PathFileComparator( PathFileComparator pathFileComparator = new PathFileComparator(IOCase.INSENSITIVE);
IOCase.INSENSITIVE); String path = FilenameUtils.getFullPath(getClass().getClassLoader().getResource("fileTest.txt").getPath());
String path = FilenameUtils.getFullPath(getClass().getClassLoader()
.getResource("fileTest.txt")
.getPath());
File dir = new File(path); File dir = new File(path);
File[] files = dir.listFiles(); File[] files = dir.listFiles();
@ -133,16 +110,11 @@ public class CommonsIOUnitTest {
} }
@Test @Test
public void whenSizeFileComparator_thenLargerFile() public void whenSizeFileComparator_thenLargerFile() throws IOException {
throws IOException {
SizeFileComparator sizeFileComparator = new SizeFileComparator(); SizeFileComparator sizeFileComparator = new SizeFileComparator();
File largerFile = FileUtils.getFile(getClass().getClassLoader() File largerFile = FileUtils.getFile(getClass().getClassLoader().getResource("fileTest.txt").getPath());
.getResource("fileTest.txt") File smallerFile = FileUtils.getFile(getClass().getClassLoader().getResource("sample.txt").getPath());
.getPath());
File smallerFile = FileUtils.getFile(getClass().getClassLoader()
.getResource("sample.txt")
.getPath());
int i = sizeFileComparator.compare(largerFile, smallerFile); int i = sizeFileComparator.compare(largerFile, smallerFile);

View File

@ -9,71 +9,71 @@ import static org.junit.Assert.assertEquals;
public class ArrayUtilsUnitTest { public class ArrayUtilsUnitTest {
@Test @Test
public void givenArray_whenAddingElementAtSpecifiedPosition_thenCorrect() { public void givenArray_whenAddingElementAtSpecifiedPosition_thenCorrect() {
int[] oldArray = {2, 3, 4, 5}; int[] oldArray = { 2, 3, 4, 5 };
int[] newArray = ArrayUtils.add(oldArray, 0, 1); int[] newArray = ArrayUtils.add(oldArray, 0, 1);
int[] expectedArray = {1, 2, 3, 4, 5}; int[] expectedArray = { 1, 2, 3, 4, 5 };
assertArrayEquals(expectedArray, newArray); assertArrayEquals(expectedArray, newArray);
} }
@Test @Test
public void givenArray_whenAddingElementAtTheEnd_thenCorrect() { public void givenArray_whenAddingElementAtTheEnd_thenCorrect() {
int[] oldArray = {2, 3, 4, 5}; int[] oldArray = { 2, 3, 4, 5 };
int[] newArray = ArrayUtils.add(oldArray, 1); int[] newArray = ArrayUtils.add(oldArray, 1);
int[] expectedArray = {2, 3, 4, 5, 1}; int[] expectedArray = { 2, 3, 4, 5, 1 };
assertArrayEquals(expectedArray, newArray); assertArrayEquals(expectedArray, newArray);
} }
@Test @Test
public void givenArray_whenAddingAllElementsAtTheEnd_thenCorrect() { public void givenArray_whenAddingAllElementsAtTheEnd_thenCorrect() {
int[] oldArray = {0, 1, 2}; int[] oldArray = { 0, 1, 2 };
int[] newArray = ArrayUtils.addAll(oldArray, 3, 4, 5); int[] newArray = ArrayUtils.addAll(oldArray, 3, 4, 5);
int[] expectedArray = {0, 1, 2, 3, 4, 5}; int[] expectedArray = { 0, 1, 2, 3, 4, 5 };
assertArrayEquals(expectedArray, newArray); assertArrayEquals(expectedArray, newArray);
} }
@Test @Test
public void givenArray_whenRemovingElementAtSpecifiedPosition_thenCorrect() { public void givenArray_whenRemovingElementAtSpecifiedPosition_thenCorrect() {
int[] oldArray = {1, 2, 3, 4, 5}; int[] oldArray = { 1, 2, 3, 4, 5 };
int[] newArray = ArrayUtils.remove(oldArray, 1); int[] newArray = ArrayUtils.remove(oldArray, 1);
int[] expectedArray = {1, 3, 4, 5}; int[] expectedArray = { 1, 3, 4, 5 };
assertArrayEquals(expectedArray, newArray); assertArrayEquals(expectedArray, newArray);
} }
@Test @Test
public void givenArray_whenRemovingAllElementsAtSpecifiedPositions_thenCorrect() { public void givenArray_whenRemovingAllElementsAtSpecifiedPositions_thenCorrect() {
int[] oldArray = {1, 2, 3, 4, 5}; int[] oldArray = { 1, 2, 3, 4, 5 };
int[] newArray = ArrayUtils.removeAll(oldArray, 1, 3); int[] newArray = ArrayUtils.removeAll(oldArray, 1, 3);
int[] expectedArray = {1, 3, 5}; int[] expectedArray = { 1, 3, 5 };
assertArrayEquals(expectedArray, newArray); assertArrayEquals(expectedArray, newArray);
} }
@Test @Test
public void givenArray_whenRemovingAnElement_thenCorrect() { public void givenArray_whenRemovingAnElement_thenCorrect() {
int[] oldArray = {1, 2, 3, 3, 4}; int[] oldArray = { 1, 2, 3, 3, 4 };
int[] newArray = ArrayUtils.removeElement(oldArray, 3); int[] newArray = ArrayUtils.removeElement(oldArray, 3);
int[] expectedArray = {1, 2, 3, 4}; int[] expectedArray = { 1, 2, 3, 4 };
assertArrayEquals(expectedArray, newArray); assertArrayEquals(expectedArray, newArray);
} }
@Test @Test
public void givenArray_whenRemovingElements_thenCorrect() { public void givenArray_whenRemovingElements_thenCorrect() {
int[] oldArray = {1, 2, 3, 3, 4}; int[] oldArray = { 1, 2, 3, 3, 4 };
int[] newArray = ArrayUtils.removeElements(oldArray, 2, 3, 5); int[] newArray = ArrayUtils.removeElements(oldArray, 2, 3, 5);
int[] expectedArray = {1, 3, 4}; int[] expectedArray = { 1, 3, 4 };
assertArrayEquals(expectedArray, newArray); assertArrayEquals(expectedArray, newArray);
} }
@Test @Test
public void givenArray_whenRemovingAllElementOccurences_thenCorrect() { public void givenArray_whenRemovingAllElementOccurences_thenCorrect() {
int[] oldArray = {1, 2, 2, 2, 3}; int[] oldArray = { 1, 2, 2, 2, 3 };
int[] newArray = ArrayUtils.removeAllOccurences(oldArray, 2); int[] newArray = ArrayUtils.removeAllOccurences(oldArray, 2);
int[] expectedArray = {1, 3}; int[] expectedArray = { 1, 3 };
assertArrayEquals(expectedArray, newArray); assertArrayEquals(expectedArray, newArray);
} }
@Test @Test
public void givenArray_whenCheckingExistingElement_thenCorrect() { public void givenArray_whenCheckingExistingElement_thenCorrect() {
int[] array = {1, 3, 5, 7, 9}; int[] array = { 1, 3, 5, 7, 9 };
boolean evenContained = ArrayUtils.contains(array, 2); boolean evenContained = ArrayUtils.contains(array, 2);
boolean oddContained = ArrayUtils.contains(array, 7); boolean oddContained = ArrayUtils.contains(array, 7);
assertEquals(false, evenContained); assertEquals(false, evenContained);
@ -82,57 +82,57 @@ public class ArrayUtilsUnitTest {
@Test @Test
public void givenArray_whenReversingElementsWithinARange_thenCorrect() { public void givenArray_whenReversingElementsWithinARange_thenCorrect() {
int[] originalArray = {1, 2, 3, 4, 5}; int[] originalArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(originalArray, 1, 4); ArrayUtils.reverse(originalArray, 1, 4);
int[] expectedArray = {1, 4, 3, 2, 5}; int[] expectedArray = { 1, 4, 3, 2, 5 };
assertArrayEquals(expectedArray, originalArray); assertArrayEquals(expectedArray, originalArray);
} }
@Test @Test
public void givenArray_whenReversingAllElements_thenCorrect() { public void givenArray_whenReversingAllElements_thenCorrect() {
int[] originalArray = {1, 2, 3, 4, 5}; int[] originalArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(originalArray); ArrayUtils.reverse(originalArray);
int[] expectedArray = {5, 4, 3, 2, 1}; int[] expectedArray = { 5, 4, 3, 2, 1 };
assertArrayEquals(expectedArray, originalArray); assertArrayEquals(expectedArray, originalArray);
} }
@Test @Test
public void givenArray_whenShiftingElementsWithinARange_thenCorrect() { public void givenArray_whenShiftingElementsWithinARange_thenCorrect() {
int[] originalArray = {1, 2, 3, 4, 5}; int[] originalArray = { 1, 2, 3, 4, 5 };
ArrayUtils.shift(originalArray, 1, 4, 1); ArrayUtils.shift(originalArray, 1, 4, 1);
int[] expectedArray = {1, 4, 2, 3, 5}; int[] expectedArray = { 1, 4, 2, 3, 5 };
assertArrayEquals(expectedArray, originalArray); assertArrayEquals(expectedArray, originalArray);
} }
@Test @Test
public void givenArray_whenShiftingAllElements_thenCorrect() { public void givenArray_whenShiftingAllElements_thenCorrect() {
int[] originalArray = {1, 2, 3, 4, 5}; int[] originalArray = { 1, 2, 3, 4, 5 };
ArrayUtils.shift(originalArray, 1); ArrayUtils.shift(originalArray, 1);
int[] expectedArray = {5, 1, 2, 3, 4}; int[] expectedArray = { 5, 1, 2, 3, 4 };
assertArrayEquals(expectedArray, originalArray); assertArrayEquals(expectedArray, originalArray);
} }
@Test @Test
public void givenArray_whenExtractingElements_thenCorrect() { public void givenArray_whenExtractingElements_thenCorrect() {
int[] oldArray = {1, 2, 3, 4, 5}; int[] oldArray = { 1, 2, 3, 4, 5 };
int[] newArray = ArrayUtils.subarray(oldArray, 2, 7); int[] newArray = ArrayUtils.subarray(oldArray, 2, 7);
int[] expectedArray = {3, 4, 5}; int[] expectedArray = { 3, 4, 5 };
assertArrayEquals(expectedArray, newArray); assertArrayEquals(expectedArray, newArray);
} }
@Test @Test
public void givenArray_whenSwapingElementsWithinARange_thenCorrect() { public void givenArray_whenSwapingElementsWithinARange_thenCorrect() {
int[] originalArray = {1, 2, 3, 4, 5}; int[] originalArray = { 1, 2, 3, 4, 5 };
ArrayUtils.swap(originalArray, 0, 3, 2); ArrayUtils.swap(originalArray, 0, 3, 2);
int[] expectedArray = {4, 5, 3, 1, 2}; int[] expectedArray = { 4, 5, 3, 1, 2 };
assertArrayEquals(expectedArray, originalArray); assertArrayEquals(expectedArray, originalArray);
} }
@Test @Test
public void givenArray_whenSwapingElementsAtSpecifiedPositions_thenCorrect() { public void givenArray_whenSwapingElementsAtSpecifiedPositions_thenCorrect() {
int[] originalArray = {1, 2, 3, 4, 5}; int[] originalArray = { 1, 2, 3, 4, 5 };
ArrayUtils.swap(originalArray, 0, 3); ArrayUtils.swap(originalArray, 0, 3);
int[] expectedArray = {4, 2, 3, 1, 5}; int[] expectedArray = { 4, 2, 3, 1, 5 };
assertArrayEquals(expectedArray, originalArray); assertArrayEquals(expectedArray, originalArray);
} }
} }

View File

@ -15,7 +15,7 @@ public class IntegrationTest {
final double i = integrator.integrate(100, function, 0, 10); final double i = integrator.integrate(100, function, 0, 10);
Assert.assertEquals(16 + 2d/3d, i, 1e-7); Assert.assertEquals(16 + 2d / 3d, i, 1e-7);
} }
} }

View File

@ -8,9 +8,7 @@ public class LinearAlgebraUnitTest {
@Test @Test
public void whenDecompositionSolverSolve_thenCorrect() { public void whenDecompositionSolverSolve_thenCorrect() {
RealMatrix a = RealMatrix a = new Array2DRowRealMatrix(new double[][] { { 2, 3, -2 }, { -1, 7, 6 }, { 4, -3, -5 } }, false);
new Array2DRowRealMatrix(new double[][] { { 2, 3, -2 }, { -1, 7, 6 }, { 4, -3, -5 } },
false);
RealVector b = new ArrayRealVector(new double[] { 1, -2, 1 }, false); RealVector b = new ArrayRealVector(new double[] { 1, -2, 1 }, false);
DecompositionSolver solver = new LUDecomposition(a).getSolver(); DecompositionSolver solver = new LUDecomposition(a).getSolver();

View File

@ -12,10 +12,10 @@ public class StatisticsUnitTest {
@Before @Before
public void setUp() { public void setUp() {
values = new double[] {65, 51 , 16, 11 , 6519, 191 ,0 , 98, 19854, 1, 32}; values = new double[] { 65, 51, 16, 11, 6519, 191, 0, 98, 19854, 1, 32 };
descriptiveStatistics = new DescriptiveStatistics(); descriptiveStatistics = new DescriptiveStatistics();
for(double v : values) { for (double v : values) {
descriptiveStatistics.addValue(v); descriptiveStatistics.addValue(v);
} }
} }

View File

@ -13,42 +13,41 @@ public class CRDTTest {
@Test @Test
public void givenGrowOnlySet_whenTwoReplicasDiverge_thenShouldMergeItWithoutAConflict() { public void givenGrowOnlySet_whenTwoReplicasDiverge_thenShouldMergeItWithoutAConflict() {
//given // given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore(); final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
final LocalCrdtStore crdtStore2 = new LocalCrdtStore(); final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
crdtStore1.connect(crdtStore2); crdtStore1.connect(crdtStore2);
final GSet<String> replica1 = crdtStore1.createGSet("ID_1"); final GSet<String> replica1 = crdtStore1.createGSet("ID_1");
final GSet<String> replica2 = crdtStore2.<String>findGSet("ID_1").get(); final GSet<String> replica2 = crdtStore2.<String> findGSet("ID_1").get();
//when // when
replica1.add("apple"); replica1.add("apple");
replica2.add("banana"); replica2.add("banana");
//then // then
assertThat(replica1).contains("apple", "banana"); assertThat(replica1).contains("apple", "banana");
assertThat(replica2).contains("apple", "banana"); assertThat(replica2).contains("apple", "banana");
//when // when
crdtStore1.disconnect(crdtStore2); crdtStore1.disconnect(crdtStore2);
replica1.add("strawberry"); replica1.add("strawberry");
replica2.add("pear"); replica2.add("pear");
assertThat(replica1).contains("apple", "banana", "strawberry"); assertThat(replica1).contains("apple", "banana", "strawberry");
assertThat(replica2).contains("apple", "banana", "pear"); assertThat(replica2).contains("apple", "banana", "pear");
crdtStore1.connect(crdtStore2); crdtStore1.connect(crdtStore2);
//then // then
assertThat(replica1).contains("apple", "banana", "strawberry", "pear"); assertThat(replica1).contains("apple", "banana", "strawberry", "pear");
assertThat(replica2).contains("apple", "banana", "strawberry", "pear"); assertThat(replica2).contains("apple", "banana", "strawberry", "pear");
} }
@Test @Test
public void givenIncrementOnlyCounter_whenTwoReplicasDiverge_thenShouldMergeIt() { public void givenIncrementOnlyCounter_whenTwoReplicasDiverge_thenShouldMergeIt() {
//given // given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore(); final LocalCrdtStore crdtStore1 = new LocalCrdtStore();
final LocalCrdtStore crdtStore2 = new LocalCrdtStore(); final LocalCrdtStore crdtStore2 = new LocalCrdtStore();
crdtStore1.connect(crdtStore2); crdtStore1.connect(crdtStore2);
@ -56,21 +55,20 @@ public class CRDTTest {
final GCounter replica1 = crdtStore1.createGCounter("ID_1"); final GCounter replica1 = crdtStore1.createGCounter("ID_1");
final GCounter replica2 = crdtStore2.findGCounter("ID_1").get(); final GCounter replica2 = crdtStore2.findGCounter("ID_1").get();
//when // when
replica1.increment(); replica1.increment();
replica2.increment(2L); replica2.increment(2L);
//then // then
assertThat(replica1.get()).isEqualTo(3L); assertThat(replica1.get()).isEqualTo(3L);
assertThat(replica2.get()).isEqualTo(3L); assertThat(replica2.get()).isEqualTo(3L);
//when // when
crdtStore1.disconnect(crdtStore2); crdtStore1.disconnect(crdtStore2);
replica1.increment(3L); replica1.increment(3L);
replica2.increment(5L); replica2.increment(5L);
assertThat(replica1.get()).isEqualTo(6L); assertThat(replica1.get()).isEqualTo(6L);
assertThat(replica2.get()).isEqualTo(8L); assertThat(replica2.get()).isEqualTo(8L);
@ -91,15 +89,15 @@ public class CRDTTest {
final PNCounter replica1 = crdtStore1.createPNCounter("ID_1"); final PNCounter replica1 = crdtStore1.createPNCounter("ID_1");
final PNCounter replica2 = crdtStore2.findPNCounter("ID_1").get(); final PNCounter replica2 = crdtStore2.findPNCounter("ID_1").get();
//when // when
replica1.increment(); replica1.increment();
replica2.decrement(2L); replica2.decrement(2L);
//then // then
assertThat(replica1.get()).isEqualTo(-1L); assertThat(replica1.get()).isEqualTo(-1L);
assertThat(replica2.get()).isEqualTo(-1L); assertThat(replica2.get()).isEqualTo(-1L);
//when // when
crdtStore1.disconnect(crdtStore2); crdtStore1.disconnect(crdtStore2);
replica1.decrement(3L); replica1.decrement(3L);
@ -110,22 +108,22 @@ public class CRDTTest {
crdtStore1.connect(crdtStore2); crdtStore1.connect(crdtStore2);
//then // then
assertThat(replica1.get()).isEqualTo(1L); assertThat(replica1.get()).isEqualTo(1L);
assertThat(replica2.get()).isEqualTo(1L); assertThat(replica2.get()).isEqualTo(1L);
} }
@Test @Test
public void givenLastWriteWinsStrategy_whenReplicasDiverge_thenAfterMergeShouldKeepOnlyLastValue() { public void givenLastWriteWinsStrategy_whenReplicasDiverge_thenAfterMergeShouldKeepOnlyLastValue() {
//given // given
final LocalCrdtStore crdtStore1 = new LocalCrdtStore("N_1"); final LocalCrdtStore crdtStore1 = new LocalCrdtStore("N_1");
final LocalCrdtStore crdtStore2 = new LocalCrdtStore("N_2"); final LocalCrdtStore crdtStore2 = new LocalCrdtStore("N_2");
crdtStore1.connect(crdtStore2); crdtStore1.connect(crdtStore2);
final LWWRegister<String> replica1 = crdtStore1.createLWWRegister("ID_1"); final LWWRegister<String> replica1 = crdtStore1.createLWWRegister("ID_1");
final LWWRegister<String> replica2 = crdtStore2.<String>findLWWRegister("ID_1").get(); final LWWRegister<String> replica2 = crdtStore2.<String> findLWWRegister("ID_1").get();
//when // when
replica1.set("apple"); replica1.set("apple");
replica2.set("banana"); replica2.set("banana");
@ -133,20 +131,18 @@ public class CRDTTest {
assertThat(replica1.get()).isEqualTo("banana"); assertThat(replica1.get()).isEqualTo("banana");
assertThat(replica2.get()).isEqualTo("banana"); assertThat(replica2.get()).isEqualTo("banana");
// when // when
crdtStore1.disconnect(crdtStore2); crdtStore1.disconnect(crdtStore2);
replica1.set("strawberry"); replica1.set("strawberry");
replica2.set("pear"); replica2.set("pear");
assertThat(replica1.get()).isEqualTo("strawberry"); assertThat(replica1.get()).isEqualTo("strawberry");
assertThat(replica2.get()).isEqualTo("pear"); assertThat(replica2.get()).isEqualTo("pear");
crdtStore1.connect(crdtStore2); crdtStore1.connect(crdtStore2);
//then // then
assertThat(replica1.get()).isEqualTo("pear"); assertThat(replica1.get()).isEqualTo("pear");
assertThat(replica2.get()).isEqualTo("pear"); assertThat(replica2.get()).isEqualTo("pear");
} }

View File

@ -19,25 +19,19 @@ public class DistinctWithJavaFunctionUnitTest {
@Test @Test
public void whenFilterListByName_thenSizeShouldBe4() { public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = personList.stream() List<Person> personListFiltered = personList.stream().filter(distinctByKey(p -> p.getName())).collect(Collectors.toList());
.filter(distinctByKey(p -> p.getName()))
.collect(Collectors.toList());
assertTrue(personListFiltered.size() == 4); assertTrue(personListFiltered.size() == 4);
} }
@Test @Test
public void whenFilterListByAge_thenSizeShouldBe2() { public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = personList.stream() List<Person> personListFiltered = personList.stream().filter(distinctByKey(p -> p.getAge())).collect(Collectors.toList());
.filter(distinctByKey(p -> p.getAge()))
.collect(Collectors.toList());
assertTrue(personListFiltered.size() == 2); assertTrue(personListFiltered.size() == 2);
} }
@Test @Test
public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() { public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() {
List<Person> personListFiltered = personList.stream() List<Person> personListFiltered = personList.stream().distinct().collect(Collectors.toList());
.distinct()
.collect(Collectors.toList());
assertTrue(personListFiltered.size() == 5); assertTrue(personListFiltered.size() == 5);
} }

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