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

View File

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

View File

@ -2,6 +2,8 @@ package com.baeldung.bytebuddy;
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
public String toString() {
return "DataObject{" +
"data='" + data + '\'' +
'}';
return "DataObject{" + "data='" + data + '\'' + '}';
}
public static DataObject get(String data) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -21,8 +21,7 @@ public class FunctionalJavaIOMain {
F<String, IO<Unit>> printLetters = i -> printLetters(i);
IO<Unit> lowerCase = IOFunctions
.stdoutPrintln("What's your first Name ?");
IO<Unit> lowerCase = IOFunctions.stdoutPrintln("What's your 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, IO<Unit>> transformInput = F1Functions
.<String, IO<Unit>, String> o(printLetters).f(toUpperCase);
F<String, IO<Unit>> transformInput = F1Functions.<String, IO<Unit>, String> o(printLetters).f(toUpperCase);
IO<Unit> readAndPrintResult = IOFunctions.bind(readInput,
transformInput);
IO<Unit> readAndPrintResult = IOFunctions.bind(readInput, transformInput);
IO<Unit> program = IOFunctions.bind(userInput,
nothing -> readAndPrintResult);
IO<Unit> program = IOFunctions.bind(userInput, nothing -> readAndPrintResult);
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) {
String[] tokens = value.toLowerCase().split("\\W+");
Stream.of(tokens)
.filter(t -> t.length() > 0)
.forEach(token -> out.collect(new Tuple2<>(token, 1)));
Stream.of(tokens).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 {
DataSet<String> text = env.fromCollection(lines);
return text.flatMap(new LineSplitter())
.groupBy(0)
.aggregate(Aggregations.SUM, 1);
return text.flatMap(new LineSplitter()).groupBy(0).aggregate(Aggregations.SUM, 1);
}
}

View File

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

View File

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

View File

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

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 + '}';
}
}

View File

@ -36,7 +36,8 @@ public class DataSource {
// ds.setPassword("");
}
private DataSource() {}
private DataSource() {
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();

View File

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

View File

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

View File

@ -15,10 +15,7 @@ public class HelloWorldService {
private final Cache<String, String> evictingHelloWorldCache;
private final Cache<String, String> passivatingHelloWorldCache;
public HelloWorldService(HelloWorldRepository repository, CacheListener listener,
Cache<String, String> simpleHelloWorldCache,
Cache<String, String> expiringHelloWorldCache,
Cache<String, String> evictingHelloWorldCache,
public HelloWorldService(HelloWorldRepository repository, CacheListener listener, Cache<String, String> simpleHelloWorldCache, Cache<String, String> expiringHelloWorldCache, Cache<String, String> evictingHelloWorldCache,
Cache<String, String> passivatingHelloWorldCache) {
this.repository = repository;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -11,10 +11,7 @@ class PromiseDemo {
Deferred<String, String, String> deferred = new DeferredObject<>();
Promise<String, String, String> promise = deferred.promise();
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"));
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"));
deferred.resolve(jobName);
// deferred.notify("");

View File

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

View File

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

View File

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

View File

@ -53,17 +53,14 @@ public class MyApp {
public static void queryUsingJDOQL() {
Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem "
+ "WHERE price < threshold PARAMETERS double threshold");
Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " + "WHERE price < threshold PARAMETERS double threshold");
List<ProductItem> explicitParamResults = (List<ProductItem>) query.execute(10);
query = pm.newQuery("SELECT FROM "
+ "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
query.setParameters("double threshold");
List<ProductItem> explicitParamResults2 = (List<ProductItem>) query.execute(10);
query = pm.newQuery("SELECT FROM "
+ "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
List<ProductItem> implicitParamResults = (List<ProductItem>) query.execute(10);
}
@ -79,8 +76,7 @@ public class MyApp {
public static void queryUsingSQL() {
Query query = pm.newQuery("javax.jdo.query.SQL","select * from "
+ "product_item where price < ? and status = ?");
Query query = pm.newQuery("javax.jdo.query.SQL", "select * from " + "product_item where price < ? and status = ?");
query.setClass(ProductItem.class);
query.setParameters(10, "InStock");
List<ProductItem> results = query.executeList();
@ -88,16 +84,13 @@ public class MyApp {
}
public static void queryUsingJPQL() {
Query query = pm.newQuery("JPQL","select i from "
+ "com.baeldung.jdo.query.ProductItem i where i.price < 10"
+ " and i.status = 'InStock'");
Query query = pm.newQuery("JPQL", "select i from " + "com.baeldung.jdo.query.ProductItem i where i.price < 10" + " and i.status = 'InStock'");
List<ProductItem> results = (List<ProductItem>) query.execute();
}
public static void namedQuery() {
Query<ProductItem> query = pm.newNamedQuery(
ProductItem.class, "PriceBelow10");
Query<ProductItem> query = pm.newNamedQuery(ProductItem.class, "PriceBelow10");
List<ProductItem> results = query.executeList();
}

View File

@ -28,7 +28,6 @@ public class ProductItem {
this.price = price;
}
public int getId() {
return id;
}
@ -40,18 +39,23 @@ public class ProductItem {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@ -64,5 +68,4 @@ public class ProductItem {
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.XmlElementWrapper;
@PersistenceCapable(
schema="/myproduct/people",
table="person"
)
@PersistenceCapable(schema = "/myproduct/people", table = "person")
public class AnnotadedPerson {
@XmlAttribute
private long personNum;
@ -29,7 +26,6 @@ public class AnnotadedPerson {
@Element(types = String.class)
private List phoneNumbers = new ArrayList();
public AnnotadedPerson(long personNum, String firstName, String lastName) {
super();
this.personNum = personNum;

View File

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

View File

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

View File

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

View File

@ -58,8 +58,7 @@ public class JettyServerFactory {
public static Server createWebAppServer() {
// Adds an handler to a server and returns it.
Server server = createBaseServer();
String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war")
.getPath();
String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath();
Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH);
server.setHandler(webAppHandler);
@ -78,8 +77,7 @@ public class JettyServerFactory {
// Creates the handlers and adds them to the server.
HandlerCollection handlers = new HandlerCollection();
String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war")
.getPath();
String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath();
Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH);
handlers.addHandler(customRequestHandler);

View File

@ -150,8 +150,7 @@ public class LoggingRequestHandler implements Handler {
* javax.servlet.http.HttpServletResponse)
*/
@Override
public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3)
throws IOException, ServletException {
public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3) throws IOException, ServletException {
LOG.info("Received a new request");
}

View File

@ -5,7 +5,6 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.logging.Logger;
public class ChannelHandlerB extends ChannelInboundHandlerAdapter {
private Logger logger = Logger.getLogger(getClass().getName());

View File

@ -24,15 +24,11 @@ public class NettyServerB {
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
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)
f.channel().closeFuture().sync();
} finally {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -26,8 +26,6 @@ public interface GitHubBasicApi {
* @return GitHub Repository Contributors
*/
@GET("repos/{user}/{repo}/contributors")
Call<List<Contributor>> listRepoContributors(
@Path("user") String user,
@Path("repo") String repo);
Call<List<Contributor>> listRepoContributors(@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 {
String userName = "eugenp";
List<String> topContributors = new GitHubBasicService()
.getTopContributors(userName);
List<String> topContributors = new GitHubBasicService().getTopContributors(userName);
topContributors.forEach(System.out::println);
}
}

View File

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

View File

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

View File

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

View File

@ -26,8 +26,6 @@ public interface GitHubRxApi {
* @return GitHub Repository Contributors
*/
@GET("repos/{user}/{repo}/contributors")
Observable<List<Contributor>> listRepoContributors(
@Path("user") String user,
@Path("repo") String repo);
Observable<List<Contributor>> listRepoContributors(@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 {
String userName = "eugenp";
new GitHubRxService().getTopContributors(userName)
.subscribe(System.out::println);
new GitHubRxService().getTopContributors(userName).subscribe(System.out::println);
}
}

View File

@ -11,23 +11,13 @@ class GitHubRxService {
private GitHubRxApi gitHubApi;
GitHubRxService() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
gitHubApi = retrofit.create(GitHubRxApi.class);
}
Observable<String> getTopContributors(String userName) {
return gitHubApi.listRepos(userName)
.flatMapIterable(x -> x)
.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();
return gitHubApi.listRepos(userName).flatMapIterable(x -> x).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 Retrofit.Builder builder
= new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
private static OkHttpClient.Builder httpClient
= new OkHttpClient.Builder();
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static HttpLoggingInterceptor logging
= new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BASIC);
private static HttpLoggingInterceptor logging = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC);
public static <S> S createService(Class<S> serviceClass) {
if (!httpClient.interceptors().contains(logging)) {
@ -43,8 +37,7 @@ public class GitHubServiceGenerator {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder()
.header("Authorization", token);
Request.Builder builder = original.newBuilder().header("Authorization", token);
Request request = builder.build();
return chain.proceed(request);
}

View File

@ -13,11 +13,7 @@ public class Main {
public static void main(String[] args) {
// Manual creation
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).client(httpClient.build()).build();
UserService service = retrofit.create(UserService.class);
// Using GitHubServiceGenerator
service = GitHubServiceGenerator.createService(UserService.class);

View File

@ -12,7 +12,8 @@ public class Member {
private 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;
}
@ -22,9 +23,12 @@ public class Member {
}
public MemberGrade getGrade() {
if (points < 1000) return Bronze;
else if (points >= 1000 && points < 5000) return Silver;
else return Gold;
if (points < 1000)
return Bronze;
else if (points >= 1000 && points < 5000)
return Silver;
else
return Gold;
}
public void spend(int moneySpent) {

View File

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

View File

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

View File

@ -31,12 +31,15 @@ public class Supplier {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
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;
}

View File

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

View File

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

View File

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

View File

@ -25,9 +25,7 @@ public class ProgrammaticTomcat {
tomcat.setPort(8080);
tomcat.setHostname("localhost");
String appBase = ".";
tomcat
.getHost()
.setAppBase(appBase);
tomcat.getHost().setAppBase(appBase);
File docBase = new File(System.getProperty("java.io.tmpdir"));
Context context = tomcat.addContext("", docBase.getAbsolutePath());

View File

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

View File

@ -186,12 +186,7 @@ public class AsyncHttpClientTestCase {
WebSocket WEBSOCKET_CLIENT = null;
try {
WEBSOCKET_CLIENT = Dsl.asyncHttpClient()
.prepareGet("ws://localhost:5590/websocket")
.addHeader("header_name", "header_value")
.addQueryParam("key", "value")
.setRequestTimeout(5000)
.execute(wsHandler).get();
WEBSOCKET_CLIENT = Dsl.asyncHttpClient().prepareGet("ws://localhost:5590/websocket").addHeader("header_name", "header_value").addQueryParam("key", "value").setRequestTimeout(5000).execute(wsHandler).get();
if (WEBSOCKET_CLIENT.isOpen()) {
WEBSOCKET_CLIENT.sendPingFrame();

View File

@ -35,10 +35,7 @@ public class AsyncServiceLongRunningUnitTest {
public void givenAsyncService_whenInitialize_thenInitOccurs2() {
asyncService.initialize();
Callable<Boolean> isInitialized = asyncService::isInitialized;
await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS)
.atMost(Duration.FIVE_SECONDS)
.with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS)
.until(isInitialized);
await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS).atMost(Duration.FIVE_SECONDS).with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS).until(isInitialized);
}
@Test
@ -60,9 +57,7 @@ public class AsyncServiceLongRunningUnitTest {
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs3() {
asyncService.initialize();
await().until(fieldIn(asyncService)
.ofType(boolean.class)
.andWithName("initialized"), equalTo(true));
await().until(fieldIn(asyncService).ofType(boolean.class).andWithName("initialized"), equalTo(true));
}
@Test
@ -77,10 +72,6 @@ public class AsyncServiceLongRunningUnitTest {
@Test
public void givenAsyncService_whenGetValue_thenExceptionIgnored() {
asyncService.initialize();
given().ignoreException(IllegalStateException.class)
.await()
.atMost(Duration.FIVE_SECONDS)
.atLeast(Duration.FIVE_HUNDRED_MILLISECONDS)
.until(asyncService::getValue, equalTo(0L));
given().ignoreException(IllegalStateException.class).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();
@Test
public void givenCryptographicResource_whenOperationSuccess_returnTrue()
throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException,
KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException {
public void givenCryptographicResource_whenOperationSuccess_returnTrue() throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException, KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException {
Security.addProvider(new BouncyCastleProvider());
CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC");
X509Certificate certificate = (X509Certificate) certFactory
.generateCertificate(new FileInputStream(certificatePath));
X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(new FileInputStream(certificatePath));
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(new FileInputStream(privateKeyPath), p12Password);
PrivateKey privateKey = (PrivateKey) keystore.getKey("baeldung", keyPassword);

View File

@ -21,14 +21,9 @@ public class ByteBuddyUnitTest {
@Test
public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException {
DynamicType.Unloaded unloadedType = new ByteBuddy()
.subclass(Object.class)
.method(ElementMatchers.isToString())
.intercept(FixedValue.value("Hello World ByteBuddy!"))
.make();
DynamicType.Unloaded unloadedType = new ByteBuddy().subclass(Object.class).method(ElementMatchers.isToString()).intercept(FixedValue.value("Hello World ByteBuddy!")).make();
Class<?> dynamicType = unloadedType.load(getClass().getClassLoader())
.getLoaded();
Class<?> dynamicType = unloadedType.load(getClass().getClassLoader()).getLoaded();
assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!");
}
@ -36,12 +31,7 @@ public class ByteBuddyUnitTest {
@Test
public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception {
ByteBuddyAgent.install();
new ByteBuddy()
.redefine(Foo.class)
.method(named("sayHelloFoo"))
.intercept(FixedValue.value("Hello Foo Redefined"))
.make()
.load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
new ByteBuddy().redefine(Foo.class).method(named("sayHelloFoo")).intercept(FixedValue.value("Hello Foo Redefined")).make().load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
Foo f = new Foo();
assertEquals(f.sayHelloFoo(), "Hello Foo Redefined");
}
@ -49,18 +39,7 @@ public class ByteBuddyUnitTest {
@Test
public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException {
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()
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()
.sayHelloFoo();
assertEquals(r, Bar.sayHelloBar());
@ -68,15 +47,8 @@ public class ByteBuddyUnitTest {
@Test
public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception {
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()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
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()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
Method m = type.getDeclaredMethod("custom", null);
@ -85,5 +57,4 @@ public class ByteBuddyUnitTest {
}
}

View File

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

View File

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

View File

@ -15,10 +15,7 @@ public class MixinUnitTest {
@Test
public void givenTwoClasses_whenMixedIntoOne_thenMixinShouldHaveMethodsFromBothClasses() throws Exception {
// when
Mixin mixin = Mixin.create(
new Class[]{Interface1.class, Interface2.class, MixinInterface.class},
new Object[]{new Class1(), new Class2()}
);
Mixin mixin = Mixin.create(new Class[] { Interface1.class, Interface2.class, MixinInterface.class }, new Object[] { new Class1(), new Class2() });
MixinInterface mixinDelegate = (MixinInterface) mixin;
// then

View File

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

View File

@ -1,6 +1,5 @@
package com.baeldung.commons.collections;
import com.baeldung.commons.collectionutil.Address;
import com.baeldung.commons.collectionutil.Customer;
import org.apache.commons.collections4.CollectionUtils;
@ -21,7 +20,6 @@ import static org.junit.Assert.assertTrue;
public class CollectionUtilsGuideTest {
Customer customer1 = new Customer(1, "Daniel", 123456l, "locality1", "city1", "1234");
Customer customer4 = new Customer(4, "Bob", 456789l, "locality4", "city4", "4567");
List<Customer> list1, list2, list3, linkedList1;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -35,7 +35,6 @@ public class CRDTTest {
replica1.add("strawberry");
replica2.add("pear");
assertThat(replica1).contains("apple", "banana", "strawberry");
assertThat(replica2).contains("apple", "banana", "pear");
@ -70,7 +69,6 @@ public class CRDTTest {
replica1.increment(3L);
replica2.increment(5L);
assertThat(replica1.get()).isEqualTo(6L);
assertThat(replica2.get()).isEqualTo(8L);
@ -133,14 +131,12 @@ public class CRDTTest {
assertThat(replica1.get()).isEqualTo("banana");
assertThat(replica2.get()).isEqualTo("banana");
// when
crdtStore1.disconnect(crdtStore2);
replica1.set("strawberry");
replica2.set("pear");
assertThat(replica1.get()).isEqualTo("strawberry");
assertThat(replica2.get()).isEqualTo("pear");

View File

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

View File

@ -19,17 +19,13 @@ public class DistinctWithStreamexUnitTest {
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = StreamEx.of(personList)
.distinct(Person::getName)
.toList();
List<Person> personListFiltered = StreamEx.of(personList).distinct(Person::getName).toList();
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = StreamEx.of(personList)
.distinct(Person::getAge)
.toList();
List<Person> personListFiltered = StreamEx.of(personList).distinct(Person::getAge).toList();
assertTrue(personListFiltered.size() == 2);
}

View File

@ -17,17 +17,13 @@ public class DistinctWithVavrUnitTest {
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList)
.distinctBy(Person::getName)
.toJavaList();
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getName).toJavaList();
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList)
.distinctBy(Person::getAge)
.toJavaList();
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getAge).toJavaList();
assertTrue(personListFiltered.size() == 2);
}

View File

@ -38,11 +38,7 @@ public class ContainerLiveTest {
public void whenListingExitedContainers_thenReturnNonEmptyList() {
// when
List<Container> containers = dockerClient.listContainersCmd()
.withShowSize(true)
.withShowAll(true)
.withStatusFilter("exited")
.exec();
List<Container> containers = dockerClient.listContainersCmd().withShowSize(true).withShowAll(true).withStatusFilter("exited").exec();
// then
assertThat(containers.size(), is(not(0)));
@ -52,111 +48,73 @@ public class ContainerLiveTest {
public void whenCreatingContainer_thenMustReturnContainerId() {
// when
CreateContainerResponse container
= dockerClient.createContainerCmd("mongo:3.6")
.withCmd("--bind_ip_all")
.withName("mongo")
.withHostName("baeldung")
.withEnv("MONGO_LATEST_VERSION=3.6")
.withPortBindings(PortBinding.parse("9999:27017"))
.exec();
CreateContainerResponse container = dockerClient.createContainerCmd("mongo:3.6").withCmd("--bind_ip_all").withName("mongo").withHostName("baeldung").withEnv("MONGO_LATEST_VERSION=3.6").withPortBindings(PortBinding.parse("9999:27017")).exec();
// then
assertThat(container.getId(), is(not(null)));
}
@Test
public void whenHavingContainer_thenRunContainer() throws InterruptedException {
// when
CreateContainerResponse container
= dockerClient.createContainerCmd("alpine:3.6")
.withCmd("sleep", "10000")
.exec();
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
Thread.sleep(3000);
// then
dockerClient.startContainerCmd(container.getId())
.exec();
dockerClient.startContainerCmd(container.getId()).exec();
dockerClient.stopContainerCmd(container.getId())
.exec();
dockerClient.stopContainerCmd(container.getId()).exec();
}
@Test
public void whenRunningContainer_thenStopContainer() throws InterruptedException {
// when
CreateContainerResponse container
= dockerClient.createContainerCmd("alpine:3.6")
.withCmd("sleep", "10000")
.exec();
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
Thread.sleep(3000);
dockerClient.startContainerCmd(container.getId())
.exec();
dockerClient.startContainerCmd(container.getId()).exec();
// then
dockerClient.stopContainerCmd(container.getId())
.exec();
dockerClient.stopContainerCmd(container.getId()).exec();
}
@Test
public void whenRunningContainer_thenKillContainer() throws InterruptedException {
// when
CreateContainerResponse container
= dockerClient.createContainerCmd("alpine:3.6")
.withCmd("sleep", "10000")
.exec();
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
dockerClient.startContainerCmd(container.getId())
.exec();
dockerClient.startContainerCmd(container.getId()).exec();
Thread.sleep(3000);
dockerClient.stopContainerCmd(container.getId())
.exec();
dockerClient.stopContainerCmd(container.getId()).exec();
// then
dockerClient.killContainerCmd(container.getId())
.exec();
dockerClient.killContainerCmd(container.getId()).exec();
}
@Test
public void whenHavingContainer_thenInspectContainer() {
// when
CreateContainerResponse container
= dockerClient.createContainerCmd("alpine:3.6")
.withCmd("sleep", "10000")
.exec();
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
// then
InspectContainerResponse containerResponse
= dockerClient.inspectContainerCmd(container.getId())
.exec();
InspectContainerResponse containerResponse = dockerClient.inspectContainerCmd(container.getId()).exec();
assertThat(containerResponse.getId(), is(container.getId()));
}
@Test
public void givenContainer_whenCommittingContainer_thenMustReturnImageId() {
// given
CreateContainerResponse container
= dockerClient.createContainerCmd("alpine:3.6")
.withCmd("sleep", "10000")
.exec();
CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
// when
String imageId = dockerClient.commitCmd(container.getId())
.withEnv("SNAPSHOT_YEAR=2018")
.withMessage("add git support")
.withCmd("sleep", "10000")
.withRepository("alpine")
.withTag("3.6.v2").exec();
String imageId = dockerClient.commitCmd(container.getId()).withEnv("SNAPSHOT_YEAR=2018").withMessage("add git support").withCmd("sleep", "10000").withRepository("alpine").withTag("3.6.v2").exec();
// then
assertThat(imageId, is(not(null)));

View File

@ -15,8 +15,7 @@ public class DockerClientLiveTest {
public void whenCreatingDockerClient_thenReturnDefaultInstance() {
// when
DefaultDockerClientConfig.Builder config
= DefaultDockerClientConfig.createDefaultConfigBuilder();
DefaultDockerClientConfig.Builder config = DefaultDockerClientConfig.createDefaultConfigBuilder();
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
// then
@ -26,9 +25,7 @@ public class DockerClientLiveTest {
@Test
public void whenCreatingDockerClientWithDockerHost_thenReturnInstance() {
// when
DockerClient dockerClient
= DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375")
.build();
DockerClient dockerClient = DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375").build();
// then
assertNotNull(dockerClient);
@ -38,17 +35,8 @@ public class DockerClientLiveTest {
public void whenCreatingAdvanceDockerClient_thenReturnInstance() {
// when
DefaultDockerClientConfig config
= DefaultDockerClientConfig.createDefaultConfigBuilder()
.withRegistryEmail("info@bealdung.com")
.withRegistryUrl("register.bealdung.io/v2/")
.withRegistryPassword("strongpassword")
.withRegistryUsername("bealdung")
.withDockerCertPath("/home/bealdung/public/.docker/certs")
.withDockerConfig("/home/bealdung/public/.docker/")
.withDockerTlsVerify("1")
.withDockerHost("tcp://docker.beauldung.com:2376")
.build();
DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withRegistryEmail("info@bealdung.com").withRegistryUrl("register.bealdung.io/v2/").withRegistryPassword("strongpassword").withRegistryUsername("bealdung")
.withDockerCertPath("/home/bealdung/public/.docker/certs").withDockerConfig("/home/bealdung/public/.docker/").withDockerTlsVerify("1").withDockerHost("tcp://docker.beauldung.com:2376").build();
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
@ -70,10 +58,7 @@ public class DockerClientLiveTest {
properties.setProperty("DOCKER_TLS_VERIFY", "1");
properties.setProperty("DOCKER_HOST", "tcp://docker.bealdung.com:2376");
DefaultDockerClientConfig config
= DefaultDockerClientConfig.createDefaultConfigBuilder()
.withProperties(properties)
.build();
DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withProperties(properties).build();
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();

View File

@ -44,8 +44,7 @@ public class ImageLiveTest {
public void whenListingImagesWithIntermediateImages_thenReturnNonEmptyList() {
// when
List<Image> images = dockerClient.listImagesCmd()
.withShowAll(true).exec();
List<Image> images = dockerClient.listImagesCmd().withShowAll(true).exec();
// then
assertThat(images.size(), is(not(0)));
@ -55,8 +54,7 @@ public class ImageLiveTest {
public void whenListingDanglingImages_thenReturnNonNullList() {
// when
List<Image> images = dockerClient.listImagesCmd()
.withDanglingFilter(true).exec();
List<Image> images = dockerClient.listImagesCmd().withDanglingFilter(true).exec();
// then
assertThat(images, is(not(null)));
@ -66,13 +64,7 @@ public class ImageLiveTest {
public void whenBuildingImage_thenMustReturnImageId() {
// when
String imageId = dockerClient.buildImageCmd()
.withDockerfile(new File("src/test/resources/dockerapi/Dockerfile"))
.withPull(true)
.withNoCache(true)
.withTag("alpine:git")
.exec(new BuildImageResultCallback())
.awaitImageId();
String imageId = dockerClient.buildImageCmd().withDockerfile(new File("src/test/resources/dockerapi/Dockerfile")).withPull(true).withNoCache(true).withTag("alpine:git").exec(new BuildImageResultCallback()).awaitImageId();
// then
assertThat(imageId, is(not(null)));
@ -86,8 +78,7 @@ public class ImageLiveTest {
Image image = images.get(0);
// when
InspectImageResponse imageResponse
= dockerClient.inspectImageCmd(image.getId()).exec();
InspectImageResponse imageResponse = dockerClient.inspectImageCmd(image.getId()).exec();
// then
assertThat(imageResponse.getId(), is(image.getId()));
@ -110,20 +101,14 @@ public class ImageLiveTest {
public void pushingAnImage() throws InterruptedException {
dockerClient.pushImageCmd("baeldung/alpine")
.withTag("3.6.v2")
.exec(new PushImageResultCallback())
.awaitCompletion(90, TimeUnit.SECONDS);
dockerClient.pushImageCmd("baeldung/alpine").withTag("3.6.v2").exec(new PushImageResultCallback()).awaitCompletion(90, TimeUnit.SECONDS);
}
@Test
public void whenPullingImage_thenImageListNotEmpty() throws InterruptedException {
// when
dockerClient.pullImageCmd("alpine")
.withTag("latest")
.exec(new PullImageResultCallback())
.awaitCompletion(30, TimeUnit.SECONDS);
dockerClient.pullImageCmd("alpine").withTag("latest").exec(new PullImageResultCallback()).awaitCompletion(30, TimeUnit.SECONDS);
// then
List<Image> images = dockerClient.listImagesCmd().exec();

View File

@ -38,10 +38,7 @@ public class NetworkLiveTest {
public void whenCreatingNetwork_thenRetrieveResponse() {
// when
CreateNetworkResponse networkResponse
= dockerClient.createNetworkCmd()
.withName("baeldungDefault")
.withDriver("bridge").exec();
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungDefault").withDriver("bridge").exec();
// then
assertThat(networkResponse, is(not(null)));
@ -51,13 +48,7 @@ public class NetworkLiveTest {
public void whenCreatingAdvanceNetwork_thenRetrieveResponse() {
// when
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd()
.withName("baeldungAdvanced")
.withIpam(new Ipam()
.withConfig(new Ipam.Config()
.withSubnet("172.36.0.0/16")
.withIpRange("172.36.5.0/24")))
.withDriver("bridge").exec();
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungAdvanced").withIpam(new Ipam().withConfig(new Ipam.Config().withSubnet("172.36.0.0/16").withIpRange("172.36.5.0/24"))).withDriver("bridge").exec();
// then
assertThat(networkResponse, is(not(null)));
@ -68,8 +59,7 @@ public class NetworkLiveTest {
// when
String networkName = "bridge";
Network network
= dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec();
Network network = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec();
// then
assertThat(network.getName(), is(networkName));
@ -79,10 +69,7 @@ public class NetworkLiveTest {
public void whenCreatingNetwork_thenRemove() throws InterruptedException {
// when
CreateNetworkResponse networkResponse
= dockerClient.createNetworkCmd()
.withName("baeldungDefault")
.withDriver("bridge").exec();
CreateNetworkResponse networkResponse = dockerClient.createNetworkCmd().withName("baeldungDefault").withDriver("bridge").exec();
// then
Thread.sleep(4000);

View File

@ -44,8 +44,7 @@ public class VolumeLiveTest {
InspectVolumeResponse volume = volumes.get(0);
// when
InspectVolumeResponse volumeResponse
= dockerClient.inspectVolumeCmd(volume.getName()).exec();
InspectVolumeResponse volumeResponse = dockerClient.inspectVolumeCmd(volume.getName()).exec();
// then
assertThat(volumeResponse, is(not(null)));
@ -65,8 +64,7 @@ public class VolumeLiveTest {
public void whenCreatingNamedVolume_thenGetVolumeId() {
// when
CreateVolumeResponse namedVolume
= dockerClient.createVolumeCmd().withName("myNamedVolume").exec();
CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("myNamedVolume").exec();
// then
assertThat(namedVolume.getName(), is(not(null)));
@ -76,8 +74,7 @@ public class VolumeLiveTest {
public void whenGettingNamedVolume_thenRemove() throws InterruptedException {
// when
CreateVolumeResponse namedVolume
= dockerClient.createVolumeCmd().withName("anotherNamedVolume").exec();
CreateVolumeResponse namedVolume = dockerClient.createVolumeCmd().withName("anotherNamedVolume").exec();
// then
Thread.sleep(4000);

View File

@ -17,7 +17,6 @@ public class CollectPatternTest {
MutableList<String> lastNames = students.collect(Student::getLastName);
Assertions.assertThat(lastNames)
.containsExactly("Hopkins", "Adams");
Assertions.assertThat(lastNames).containsExactly("Hopkins", "Adams");
}
}

View File

@ -12,7 +12,6 @@ public class ConvertContainerToAnotherTest {
public void whenConvertContainerToAnother_thenCorrect() {
MutableList<String> cars = (MutableList) ConvertContainerToAnother.convertToList();
Assertions.assertThat(cars)
.containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes"));
Assertions.assertThat(cars).containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes"));
}
}

View File

@ -20,7 +20,6 @@ public class DetectPatternTest {
public void whenDetect_thenCorrect() {
Integer result = list.detect(Predicates.greaterThan(30));
Assertions.assertThat(result)
.isEqualTo(41);
Assertions.assertThat(result).isEqualTo(41);
}
}

View File

@ -44,7 +44,6 @@ public class FlatCollectTest {
public void whenFlatCollect_thenCorrect() {
MutableList<String> addresses = students.flatCollect(Student::getAddresses);
Assertions.assertThat(addresses)
.containsExactlyElementsOf(this.expectedAddresses);
Assertions.assertThat(addresses).containsExactlyElementsOf(this.expectedAddresses);
}
}

View File

@ -18,7 +18,6 @@ public class LazyIterationTest {
LazyIterable<Student> lazyStudents = students.asLazy();
LazyIterable<String> lastNames = lazyStudents.collect(Student::getLastName);
Assertions.assertThat(lastNames)
.containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez"));
Assertions.assertThat(lastNames).containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez"));
}
}

View File

@ -31,14 +31,10 @@ public class PartitionPatternTest {
return each > 30;
}
});
MutableList<Integer> greaterThanThirty = partitionedFolks.getSelected()
.sortThis();
MutableList<Integer> smallerThanThirty = partitionedFolks.getRejected()
.sortThis();
MutableList<Integer> greaterThanThirty = partitionedFolks.getSelected().sortThis();
MutableList<Integer> smallerThanThirty = partitionedFolks.getRejected().sortThis();
Assertions.assertThat(smallerThanThirty)
.containsExactly(1, 5, 8, 17, 23);
Assertions.assertThat(greaterThanThirty)
.containsExactly(31, 38, 41);
Assertions.assertThat(smallerThanThirty).containsExactly(1, 5, 8, 17, 23);
Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41);
}
}

View File

@ -20,10 +20,8 @@ public class RejectPatternTest {
@Test
public void whenReject_thenCorrect() {
MutableList<Integer> notGreaterThanThirty = list.reject(Predicates.greaterThan(30))
.sortThis();
MutableList<Integer> notGreaterThanThirty = list.reject(Predicates.greaterThan(30)).sortThis();
Assertions.assertThat(notGreaterThanThirty)
.containsExactlyElementsOf(this.expectedList);
Assertions.assertThat(notGreaterThanThirty).containsExactlyElementsOf(this.expectedList);
}
}

View File

@ -18,17 +18,14 @@ public class SelectPatternTest {
@Test
public void givenListwhenSelect_thenCorrect() {
MutableList<Integer> greaterThanThirty = list.select(Predicates.greaterThan(30))
.sortThis();
MutableList<Integer> greaterThanThirty = list.select(Predicates.greaterThan(30)).sortThis();
Assertions.assertThat(greaterThanThirty)
.containsExactly(31, 38, 41);
Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41);
}
@SuppressWarnings("rawtypes")
public MutableList selectUsingLambda() {
return list.select(each -> each > 30)
.sortThis();
return list.select(each -> each > 30).sortThis();
}
@SuppressWarnings("unchecked")
@ -36,7 +33,6 @@ public class SelectPatternTest {
public void givenListwhenSelectUsingLambda_thenCorrect() {
MutableList<Integer> greaterThanThirty = selectUsingLambda();
Assertions.assertThat(greaterThanThirty)
.containsExactly(31, 38, 41);
Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41);
}
}

View File

@ -28,7 +28,6 @@ public class ZipTest {
MutableList<String> cars = Lists.mutable.with("Porsche", "Volvo", "Toyota");
MutableList<Pair<String, String>> pairs = numbers.zip(cars);
Assertions.assertThat(pairs)
.containsExactlyElementsOf(this.expectedPairs);
Assertions.assertThat(pairs).containsExactlyElementsOf(this.expectedPairs);
}
}

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