Merge pull request #4 from eugenp/master

Update from master
This commit is contained in:
Donato Rimenti 2018-02-22 20:59:16 +01:00 committed by GitHub
commit 7c873655ed
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
148 changed files with 4368 additions and 252 deletions

114
checker-plugin/pom.xml Normal file
View File

@ -0,0 +1,114 @@
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>checker-plugin</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>checker-plugin</name>
<url>http://maven.apache.org</url>
<!-- https://checkerframework.org/manual/#maven -->
<properties>
<!-- These properties will be set by the Maven Dependency plugin -->
<annotatedJdk>${org.checkerframework:jdk8:jar}</annotatedJdk>
<!-- Uncomment to use the Type Annotations compiler. -->
<!--
<typeAnnotationsJavac>${org.checkerframework:compiler:jar}</typeAnnotationsJavac>
-->
</properties>
<dependencies>
<!-- Annotations from the Checker Framework: nullness, interning, locking, ... -->
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker-qual</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>jdk8</artifactId>
<version>2.3.1</version>
</dependency>
<!-- The Type Annotations compiler. Uncomment if using annotations in comments. -->
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>compiler</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<!-- This plugin will set properties values using dependency information -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<goals>
<!--
Goal that sets a property pointing to the artifact file for each project dependency.
For each dependency (direct and transitive) a project property will be set which
follows the:
groupId:artifactId:type:[classifier]
form and contains the path to the resolved artifact. -->
<goal>properties</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<!-- Uncomment the following line to use the type annotations compiler. -->
<!-- <fork>true</fork> -->
<compilerArguments>
<Xmaxerrs>10000</Xmaxerrs>
<Xmaxwarns>10000</Xmaxwarns>
</compilerArguments>
<annotationProcessors>
<!-- Add all the checkers you want to enable here -->
<annotationProcessor>org.checkerframework.checker.nullness.NullnessChecker</annotationProcessor>
<annotationProcessor>org.checkerframework.checker.interning.InterningChecker</annotationProcessor>
<annotationProcessor>org.checkerframework.checker.fenum.FenumChecker</annotationProcessor>
<annotationProcessor>org.checkerframework.checker.formatter.FormatterChecker</annotationProcessor>
<annotationProcessor>org.checkerframework.checker.regex.RegexChecker</annotationProcessor>
</annotationProcessors>
<compilerArgs>
<arg>-AprintErrorStack</arg>
<!-- location of the annotated JDK, which comes from a Maven dependency -->
<arg>-Xbootclasspath/p:${annotatedJdk}</arg>
<!--
-->
<!-- Uncomment the following line to use the type annotations compiler. -->
<!--
<arg>-J-Xbootclasspath/p:${typeAnnotationsJavac}</arg>
-->
<!-- Uncomment the following line to turn type-checking warnings into errors. -->
<arg>-Awarns</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,42 @@
package com.baeldung.typechecker;
import org.checkerframework.checker.fenum.qual.Fenum;
//@SuppressWarnings("fenum:assignment.type.incompatible")
public class FakeNumExample {
// Here we use some String constants to represents countries.
static final @Fenum("country") String ITALY = "IT";
static final @Fenum("country") String US = "US";
static final @Fenum("country") String UNITED_KINGDOM = "UK";
// Here we use other String constants to represent planets instead.
static final @Fenum("planet") String MARS = "Mars";
static final @Fenum("planet") String EARTH = "Earth";
static final @Fenum("planet") String VENUS = "Venus";
// Now we write this method and we want to be sure that
// the String parameter has a value of a country, not that is just a String.
void greetCountries(@Fenum("country") String country) {
System.out.println("Hello " + country);
}
// Similarly we're enforcing here that the provided
// parameter is a String that represent a planet.
void greetPlanets(@Fenum("planet") String planet) {
System.out.println("Hello " + planet);
}
public static void main(String[] args) {
FakeNumExample obj = new FakeNumExample();
// This will fail because we pass a planet-String to a method that
// accept a country-String.
obj.greetCountries(MARS);
// Here the opposite happens.
obj.greetPlanets(US);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.typechecker;
public class FormatExample {
public static void main(String[] args) {
// Just enabling org.checkerframework.checker.formatter.FormatterChecker
// we can be sure at compile time that the format strings we pass to format()
// are correct. Normally we would have those errors raised just at runtime.
// All those formats are in fact wrong.
String.format("%y", 7); // error: invalid format string
String.format("%d", "a string"); // error: invalid argument type for %d
String.format("%d %s", 7); // error: missing argument for %s
String.format("%d", 7, 3); // warning: unused argument 3
String.format("{0}", 7); // warning: unused argument 7, because {0} is wrong syntax
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.typechecker;
import org.checkerframework.checker.nullness.qual.KeyFor;
import java.util.HashMap;
import java.util.Map;
public class KeyForExample {
private final Map<String, String> config = new HashMap<>();
KeyForExample() {
// Here we initialize a map to store
// some config data.
config.put("url", "http://1.2.3.4");
config.put("name", "foobaz");
}
public void dumpPort() {
// Here, we want to dump the port value stored in the
// config, so we declare that this key has to be
// present in the config map.
// Obviously that will fail because such key is not present
// in the map.
@KeyFor("config") String key = "port";
System.out.println( config.get(key) );
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.typechecker;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import java.util.Date;
public class MonotonicNotNullExample {
// The idea is we need this field to be to lazily initialized,
// so it starts as null but once it becomes not null
// it cannot return null.
// In these cases, we can use @MonotonicNonNull
@MonotonicNonNull private Date firstCall;
public Date getFirstCall() {
if (firstCall == null) {
firstCall = new Date();
}
return firstCall;
}
public void reset() {
// This is reported as error because
// we wrongly set the field back to null.
firstCall = null;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.typechecker;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
public class NonNullExample {
// This method's parameter is annotated in order
// to tell the pluggable type system that it can never be null.
private static int countArgs(@NonNull String[] args) {
return args.length;
}
// This method's parameter is annotated in order
// to tell the pluggable type system that it may be null.
public static void main(@Nullable String[] args) {
// Here lies a potential error,
// because we pass a potential null reference to a method
// that does not accept nulls.
// The Checker Framework will spot this problem at compile time
// instead of runtime.
System.out.println(countArgs(args));
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.typechecker;
import org.checkerframework.checker.regex.qual.Regex;
public class RegexExample {
// For some reason we want to be sure that this regex
// contains at least one capturing group.
// However, we do an error and we forgot to define such
// capturing group in it.
@Regex(1) private static String findNumbers = "\\d*";
public static void main(String[] args) {
String message = "My phone number is +3911223344.";
message.matches(findNumbers);
}
}

4
core-groovy/README.md Normal file
View File

@ -0,0 +1,4 @@
# Groovy
## Relevant articles:

118
core-groovy/pom.xml Normal file
View File

@ -0,0 +1,118 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-groovy</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>central</id>
<url>http://jcenter.bintray.com</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>2.4.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-sql</artifactId>
<version>2.4.13</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.4.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<goals>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>compile</goal>
<goal>compileTests</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>junit5</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<includes>
<include>**/*Test5.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<kotlin-maven-plugin.version>1.1.2</kotlin-maven-plugin.version>
<kotlin-test-junit.version>1.1.2</kotlin-test-junit.version>
<kotlin-stdlib.version>1.1.2</kotlin-stdlib.version>
<kotlin-reflect.version>1.1.2</kotlin-reflect.version>
<kotlinx.version>0.15</kotlinx.version>
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
<junit.jupiter.version>5.0.0</junit.jupiter.version>
<junit.platform.version>1.0.0</junit.platform.version>
<junit.vintage.version>4.12.0</junit.vintage.version>
<junit4.version>4.12</junit4.version>
</properties>
</project>

View File

@ -0,0 +1,229 @@
package com.baeldung.groovy.sql
import groovy.sql.GroovyResultSet
import groovy.sql.GroovyRowResult
import groovy.sql.Sql
import groovy.transform.CompileStatic
import static org.junit.Assert.*
import org.junit.Test
class SqlTest {
final Map dbConnParams = [url: 'jdbc:hsqldb:mem:testDB', user: 'sa', password: '', driver: 'org.hsqldb.jdbc.JDBCDriver']
@Test
void whenNewSqlInstance_thenDbIsAccessed() {
def sql = Sql.newInstance(dbConnParams)
sql.close()
sql.close()
}
@Test
void whenTableDoesNotExist_thenSelectFails() {
try {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.eachRow('select * from PROJECT') {}
}
fail("An exception should have been thrown")
} catch (ignored) {
//Ok
}
}
@Test
void whenTableCreated_thenSelectIsPossible() {
Sql.withInstance(dbConnParams) { Sql sql ->
def result = sql.execute 'create table PROJECT_1 (id integer not null, name varchar(50), url varchar(100))'
assertEquals(0, sql.updateCount)
assertFalse(result)
result = sql.execute('select * from PROJECT_1')
assertTrue(result)
}
}
@Test
void whenIdentityColumn_thenInsertReturnsNewId() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
def ids = sql.executeInsert("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
assertEquals(0, ids[0][0])
ids = sql.executeInsert("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
assertEquals(1, ids[0][0])
}
}
@Test
void whenUpdate_thenNumberOfAffectedRows() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
def count = sql.executeUpdate("UPDATE PROJECT_3 SET URL = 'https://' + URL")
assertEquals(2, count)
}
}
@Test
void whenEachRow_thenResultSetHasProperties() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
sql.eachRow("SELECT * FROM PROJECT_4") { GroovyResultSet rs ->
assertNotNull(rs.name)
assertNotNull(rs.url)
assertNotNull(rs[0])
assertNotNull(rs[1])
assertNotNull(rs[2])
assertEquals(rs.name, rs['name'])
assertEquals(rs.url, rs['url'])
}
}
}
@Test
void whenPagination_thenSubsetIsReturned() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
def rows = sql.rows('SELECT * FROM PROJECT_5 ORDER BY NAME', 1, 1)
assertEquals(1, rows.size())
assertEquals('REST with Spring', rows[0].name)
}
}
@Test
void whenParameters_thenReplacement() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.execute('INSERT INTO PROJECT_6 (NAME, URL) VALUES (?, ?)', 'tutorials', 'github.com/eugenp/tutorials')
sql.execute("INSERT INTO PROJECT_6 (NAME, URL) VALUES (:name, :url)", [name: 'REST with Spring', url: 'github.com/eugenp/REST-With-Spring'])
def rows = sql.rows("SELECT * FROM PROJECT_6 WHERE NAME = 'tutorials'")
assertEquals(1, rows.size())
rows = sql.rows("SELECT * FROM PROJECT_6 WHERE NAME = 'REST with Spring'")
assertEquals(1, rows.size())
}
}
@Test
void whenParametersInGString_thenReplacement() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_7 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.execute "INSERT INTO PROJECT_7 (NAME, URL) VALUES (${'tutorials'}, ${'github.com/eugenp/tutorials'})"
def name = 'REST with Spring'
def url = 'github.com/eugenp/REST-With-Spring'
sql.execute "INSERT INTO PROJECT_7 (NAME, URL) VALUES (${name}, ${url})"
def rows = sql.rows("SELECT * FROM PROJECT_7 WHERE NAME = 'tutorials'")
assertEquals(1, rows.size())
rows = sql.rows("SELECT * FROM PROJECT_7 WHERE NAME = 'REST with Spring'")
assertEquals(1, rows.size())
}
}
@Test
void whenTransactionRollback_thenNoDataInserted() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.withTransaction {
sql.execute 'create table PROJECT_8 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
sql.rollback()
def rows = sql.rows("SELECT * FROM PROJECT_8")
assertEquals(0, rows.size())
}
}
}
@Test
void whenTransactionRollbackThenCommit_thenOnlyLastInserted() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.withTransaction {
sql.execute 'create table PROJECT_9 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
sql.rollback()
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
sql.rollback()
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
}
def rows = sql.rows("SELECT * FROM PROJECT_9")
assertEquals(2, rows.size())
}
}
@Test
void whenException_thenTransactionIsRolledBack() {
Sql.withInstance(dbConnParams) { Sql sql ->
try {
sql.withTransaction {
sql.execute 'create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_10 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
throw new Exception('rollback')
}
} catch (ignored) {}
def rows = sql.rows("SELECT * FROM PROJECT_10")
assertEquals(0, rows.size())
}
}
@Test
void givenCachedConnection_whenException_thenDataIsPersisted() {
Sql.withInstance(dbConnParams) { Sql sql ->
try {
sql.cacheConnection {
sql.execute 'create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_11 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
throw new Exception('This does not rollback')
}
} catch (ignored) {}
def rows = sql.rows("SELECT * FROM PROJECT_11")
assertEquals(1, rows.size())
}
}
/*@Test
void whenModifyResultSet_thenDataIsChanged() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
sql.eachRow("SELECT * FROM PROJECT_5 FOR UPDATE ") { GroovyResultSet rs ->
rs['name'] = "The great ${rs.name}!" as String
rs.updateRow()
}
sql.eachRow("SELECT * FROM PROJECT_5") { GroovyResultSet rs ->
assertTrue(rs.name.startsWith('The great '))
}
}
}*/
}

View File

@ -40,3 +40,4 @@
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency) - [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams) - [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) - [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)

View File

@ -22,7 +22,7 @@ public class ShufflingCollectionsUnitTest {
} }
@Test @Test
public void whenShufflingMapKeys_thenValuesAreShuffled() { public void whenShufflingMapEntries_thenValuesAreShuffled() {
Map<Integer, String> studentsById = new HashMap<>(); Map<Integer, String> studentsById = new HashMap<>();
studentsById.put(1, "Foo"); studentsById.put(1, "Foo");
studentsById.put(2, "Bar"); studentsById.put(2, "Bar");
@ -32,12 +32,12 @@ public class ShufflingCollectionsUnitTest {
System.out.println("Students before shuffling:"); System.out.println("Students before shuffling:");
System.out.println(studentsById.values()); System.out.println(studentsById.values());
List<Integer> shuffledStudentIds = new ArrayList<>(studentsById.keySet()); List<Map.Entry<Integer, String>> shuffledStudentEntries = new ArrayList<>(studentsById.entrySet());
Collections.shuffle(shuffledStudentIds); Collections.shuffle(shuffledStudentEntries);
List<String> shuffledStudents = shuffledStudentIds.stream() List<String> shuffledStudents = shuffledStudentEntries.stream()
.map(id -> studentsById.get(id)) .map(Map.Entry::getValue)
.collect(Collectors.toList()); .collect(Collectors.toList());
System.out.println("Students after shuffling"); System.out.println("Students after shuffling");
System.out.println(shuffledStudents); System.out.println(shuffledStudents);

View File

@ -0,0 +1,13 @@
package com.baeldung.casting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Animal {
private static final Logger LOGGER = LoggerFactory.getLogger(Animal.class);
public void eat() {
LOGGER.info("animal is eating");
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.casting;
import java.util.List;
public class AnimalFeeder {
public void feed(List<Animal> animals) {
animals.forEach(animal -> {
animal.eat();
if (animal instanceof Cat) {
((Cat) animal).meow();
}
});
}
public void uncheckedFeed(List<Animal> animals) {
animals.forEach(animal -> {
animal.eat();
((Cat) animal).meow();
});
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.casting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Cat extends Animal implements Mew {
private static final Logger LOGGER = LoggerFactory.getLogger(Cat.class);
public void eat() {
LOGGER.info("cat is eating");
}
public void meow() {
LOGGER.info("meow");
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.casting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Dog extends Animal {
private static final Logger LOGGER = LoggerFactory.getLogger(Dog.class);
public void eat() {
LOGGER.info("dog is eating");
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.casting;
public interface Mew {
public void meow();
}

View File

@ -0,0 +1,13 @@
package com.baeldung.designpatterns.chainofresponsibility;
public abstract class AuthenticationProcessor {
// next element in chain or responsibility
public AuthenticationProcessor nextProcessor;
public AuthenticationProcessor(AuthenticationProcessor nextProcessor) {
this.nextProcessor = nextProcessor;
}
public abstract boolean isAuthorized(AuthenticationProvider authProvider);
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.chainofresponsibility;
public interface AuthenticationProvider {
}

View File

@ -0,0 +1,21 @@
package com.baeldung.designpatterns.chainofresponsibility;
public class OAuthAuthenticationProcessor extends AuthenticationProcessor {
public OAuthAuthenticationProcessor(AuthenticationProcessor nextProcessor) {
super(nextProcessor);
}
@Override
public boolean isAuthorized(AuthenticationProvider authProvider) {
if (authProvider instanceof OAuthTokenProvider) {
return Boolean.TRUE;
} else if (nextProcessor != null) {
return nextProcessor.isAuthorized(authProvider);
} else {
return Boolean.FALSE;
}
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.chainofresponsibility;
public class OAuthTokenProvider implements AuthenticationProvider {
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.chainofresponsibility;
public class SamlAuthenticationProvider implements AuthenticationProvider {
}

View File

@ -0,0 +1,20 @@
package com.baeldung.designpatterns.chainofresponsibility;
public class UsernamePasswordAuthenticationProcessor extends AuthenticationProcessor {
public UsernamePasswordAuthenticationProcessor(AuthenticationProcessor nextProcessor) {
super(nextProcessor);
}
@Override
public boolean isAuthorized(AuthenticationProvider authProvider) {
if (authProvider instanceof UsernamePasswordProvider) {
return Boolean.TRUE;
} else if (nextProcessor != null) {
return nextProcessor.isAuthorized(authProvider);
} else {
return Boolean.FALSE;
}
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.chainofresponsibility;
public class UsernamePasswordProvider implements AuthenticationProvider {
}

View File

@ -0,0 +1,229 @@
package com.baeldung.java.list;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class CustomList<E> implements List<E> {
private Object[] internal = {};
@Override
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> collection) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(int index, Collection<? extends E> collection) {
throw new UnsupportedOperationException();
}
@Override
public E remove(int index) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object object) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> collection) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> collection) {
throw new UnsupportedOperationException();
}
@Override
public int size() {
return internal.length;
}
@Override
public boolean isEmpty() {
return internal.length == 0;
}
@Override
public boolean add(E element) {
// the first cycle
// internal = new Object[1];
// internal[0] = element;
// return true;
Object[] temp = new Object[internal.length + 1];
System.arraycopy(internal, 0, temp, 0, internal.length);
temp[internal.length] = element;
internal = temp;
return true;
}
@SuppressWarnings("unchecked")
@Override
public E get(int index) {
return (E) internal[index];
}
@Override
public boolean contains(Object object) {
// return false
for (Object element : internal) {
if (object.equals(element)) {
return true;
}
}
return false;
}
@Override
public boolean containsAll(Collection<?> collection) {
// the first cycle
// for (Object element : collection) {
// if (element.equals(internal[0])) {
// return true;
// }
// }
// return false;
for (Object element : collection)
if (!contains(element)) {
return false;
}
return true;
}
@SuppressWarnings("unchecked")
@Override
public E set(int index, E element) {
E oldElement = (E) internal[index];
internal[index] = element;
return oldElement;
}
@Override
public void clear() {
internal = new Object[0];
}
@Override
public int indexOf(Object object) {
// the first cycle
// if (object.equals(internal[0])) {
// return 0;
// }
// return -1;
for (int i = 0; i < internal.length; i++) {
if (object.equals(internal[i])) {
return i;
}
}
return -1;
}
@Override
public int lastIndexOf(Object object) {
// the first cycle
// if (object.equals(internal[0])) {
// return 0;
// }
// return -1;
for (int i = internal.length - 1; i >= 0; i--) {
if (object.equals(internal[i])) {
return i;
}
}
return -1;
}
@SuppressWarnings("unchecked")
@Override
public List<E> subList(int fromIndex, int toIndex) {
// the first cycle
// return (List<E>) Arrays.asList(internal);
Object[] temp = new Object[toIndex - fromIndex];
System.arraycopy(internal, fromIndex, temp, 0, temp.length);
return (List<E>) Arrays.asList(temp);
}
@Override
public Object[] toArray() {
return Arrays.copyOf(internal, internal.length);
}
@SuppressWarnings("unchecked")
@Override
public <T> T[] toArray(T[] array) {
// the first cycle
// array[0] = (T) internal[0];
// return array;
// the second cycle
// if (array.length < internal.length) {
// return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
// }
// return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
if (array.length < internal.length) {
return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
}
System.arraycopy(internal, 0, array, 0, internal.length);
if (array.length > internal.length) {
array[internal.length] = null;
}
return array;
}
@Override
public Iterator<E> iterator() {
return new CustomIterator();
}
@Override
public ListIterator<E> listIterator() {
return null;
}
@Override
public ListIterator<E> listIterator(int index) {
// ignored for brevity
return null;
}
private class CustomIterator implements Iterator<E> {
int index;
@Override
public boolean hasNext() {
// the first cycle
// return true;
return index != internal.length;
}
@SuppressWarnings("unchecked")
@Override
public E next() {
// the first cycle
// return (E) CustomList.this.internal[0];
E element = (E) CustomList.this.internal[index];
index++;
return element;
}
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.casting;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
public class CastingTest {
@Test
public void whenPrimitiveConverted_thenValueChanged() {
double myDouble = 1.1;
int myInt = (int) myDouble;
assertNotEquals(myDouble, myInt);
}
@Test
public void whenUpcast_thenInstanceUnchanged() {
Cat cat = new Cat();
Animal animal = cat;
animal = (Animal) cat;
assertTrue(animal instanceof Cat);
}
@Test
public void whenUpcastToObject_thenInstanceUnchanged() {
Object object = new Animal();
assertTrue(object instanceof Animal);
}
@Test
public void whenUpcastToInterface_thenInstanceUnchanged() {
Mew mew = new Cat();
assertTrue(mew instanceof Cat);
}
@Test
public void whenUpcastToAnimal_thenOverridenMethodsCalled() {
List<Animal> animals = new ArrayList<>();
animals.add(new Cat());
animals.add(new Dog());
new AnimalFeeder().feed(animals);
}
@Test
public void whenDowncastToCat_thenMeowIsCalled() {
Animal animal = new Cat();
((Cat) animal).meow();
}
@Test(expected = ClassCastException.class)
public void whenDownCastWithoutCheck_thenExceptionThrown() {
List<Animal> animals = new ArrayList<>();
animals.add(new Cat());
animals.add(new Dog());
new AnimalFeeder().uncheckedFeed(animals);
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.designpatterns.chainofresponsibility;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ChainOfResponsibilityTest {
private static AuthenticationProcessor getChainOfAuthProcessor() {
AuthenticationProcessor oAuthProcessor = new OAuthAuthenticationProcessor(null);
AuthenticationProcessor unamePasswordProcessor = new UsernamePasswordAuthenticationProcessor(oAuthProcessor);
return unamePasswordProcessor;
}
@Test
public void givenOAuthProvider_whenCheckingAuthorized_thenSuccess() {
AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();
boolean isAuthorized = authProcessorChain.isAuthorized(new OAuthTokenProvider());
assertTrue(isAuthorized);
}
@Test
public void givenUsernamePasswordProvider_whenCheckingAuthorized_thenSuccess() {
AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();
boolean isAuthorized = authProcessorChain.isAuthorized(new UsernamePasswordProvider());
assertTrue(isAuthorized);
}
@Test
public void givenSamlAuthProvider_whenCheckingAuthorized_thenFailure() {
AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();
boolean isAuthorized = authProcessorChain.isAuthorized(new SamlAuthenticationProvider());
assertTrue(!isAuthorized);
}
}

View File

@ -0,0 +1,282 @@
package com.baeldung.java.list;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
public class CustomListUnitTest {
@Test(expected = UnsupportedOperationException.class)
public void whenAddToSpecifiedIndex_thenExceptionIsThrown() {
new CustomList<>().add(0, null);
}
@Test(expected = UnsupportedOperationException.class)
public void whenAddAllToTheEnd_thenExceptionIsThrown() {
Collection<Object> collection = new ArrayList<>();
List<Object> list = new CustomList<>();
list.addAll(collection);
}
@Test(expected = UnsupportedOperationException.class)
public void whenAddAllToSpecifiedIndex_thenExceptionIsThrown() {
Collection<Object> collection = new ArrayList<>();
List<Object> list = new CustomList<>();
list.addAll(0, collection);
}
@Test(expected = UnsupportedOperationException.class)
public void whenRemoveAtSpecifiedIndex_thenExceptionIsThrown() {
List<Object> list = new CustomList<>();
list.add("baeldung");
list.remove(0);
}
@Test(expected = UnsupportedOperationException.class)
public void whenRemoveSpecifiedElement_thenExceptionIsThrown() {
List<Object> list = new CustomList<>();
list.add("baeldung");
list.remove("baeldung");
}
@Test(expected = UnsupportedOperationException.class)
public void whenRemoveAll_thenExceptionIsThrown() {
Collection<Object> collection = new ArrayList<>();
collection.add("baeldung");
List<Object> list = new CustomList<>();
list.removeAll(collection);
}
@Test(expected = UnsupportedOperationException.class)
public void whenRetainAll_thenExceptionIsThrown() {
Collection<Object> collection = new ArrayList<>();
collection.add("baeldung");
List<Object> list = new CustomList<>();
list.add("baeldung");
list.retainAll(collection);
}
@Test
public void givenEmptyList_whenSize_thenZeroIsReturned() {
List<Object> list = new CustomList<>();
assertEquals(0, list.size());
}
@Test
public void givenEmptyList_whenIsEmpty_thenTrueIsReturned() {
List<Object> list = new CustomList<>();
assertTrue(list.isEmpty());
}
@Test
public void givenEmptyList_whenElementIsAdded_thenGetReturnsThatElement() {
List<Object> list = new CustomList<>();
boolean succeeded = list.add("baeldung");
Object element = list.get(0);
assertTrue(succeeded);
assertEquals("baeldung", element);
}
@Test
public void givenListWithAnElement_whenAnotherIsAdded_thenGetReturnsBoth() {
List<Object> list = new CustomList<>();
boolean succeeded1 = list.add("baeldung");
boolean succeeded2 = list.add(".com");
Object element1 = list.get(0);
Object element2 = list.get(1);
assertTrue(succeeded1);
assertTrue(succeeded2);
assertEquals("baeldung", element1);
assertEquals(".com", element2);
}
@Test
public void givenEmptyList_whenContains_thenFalseIsReturned() {
List<Object> list = new CustomList<>();
assertFalse(list.contains(null));
}
@Test
public void givenListWithAnElement_whenContains_thenTrueIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
assertTrue(list.contains("baeldung"));
}
@Test
public void givenListWithAnElement_whenContainsAll_thenTrueIsReturned() {
Collection<Object> collection = new ArrayList<>();
collection.add("baeldung");
List<Object> list = new CustomList<>();
list.add("baeldung");
assertTrue(list.containsAll(collection));
}
@Test
public void givenList_whenContainsAll_thenEitherTrueOrFalseIsReturned() {
Collection<Object> collection1 = new ArrayList<>();
collection1.add("baeldung");
collection1.add(".com");
Collection<Object> collection2 = new ArrayList<>();
collection2.add("baeldung");
List<Object> list = new CustomList<>();
list.add("baeldung");
assertFalse(list.containsAll(collection1));
assertTrue(list.containsAll(collection2));
}
@Test
public void givenList_whenSet_thenOldElementIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
Object element = list.set(0, null);
assertEquals("baeldung", element);
assertNull(list.get(0));
}
@Test
public void givenList_whenClear_thenAllElementsAreRemoved() {
List<Object> list = new CustomList<>();
list.add("baeldung");
list.clear();
assertTrue(list.isEmpty());
}
@Test
public void givenList_whenIndexOf_thenIndexZeroIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
assertEquals(0, list.indexOf("baeldung"));
}
@Test
public void givenList_whenIndexOf_thenPositiveIndexOrMinusOneIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
list.add(".com");
list.add(".com");
assertEquals(1, list.indexOf(".com"));
assertEquals(-1, list.indexOf("com"));
}
@Test
public void whenLastIndexOf_thenIndexZeroIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
assertEquals(0, list.lastIndexOf("baeldung"));
}
@Test
public void whenLastIndexOf_thenPositiveIndexOrMinusOneIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
list.add("baeldung");
list.add(".com");
assertEquals(1, list.lastIndexOf("baeldung"));
assertEquals(-1, list.indexOf("com"));
}
@Test
public void whenSubListZeroToOne_thenListContainingFirstElementIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
List<Object> subList = list.subList(0, 1);
assertEquals("baeldung", subList.get(0));
}
@Test
public void whenSubListOneToTwo_thenListContainingSecondElementIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
list.add(".");
list.add("com");
List<Object> subList = list.subList(1, 2);
assertEquals(1, subList.size());
assertEquals(".", subList.get(0));
}
@Test
public void givenListWithElements_whenToArray_thenArrayContainsThose() {
List<Object> list = new CustomList<>();
list.add("baeldung");
list.add(".com");
Object[] array = list.toArray();
assertArrayEquals(new Object[] { "baeldung", ".com" }, array);
}
@Test
public void givenListWithAnElement_whenToArray_thenInputArrayIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
String[] input = new String[1];
String[] output = list.toArray(input);
assertArrayEquals(new String[] { "baeldung" }, input);
}
@Test
public void whenToArrayIsCalledWithEmptyInputArray_thenNewArrayIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
String[] input = {};
String[] output = list.toArray(input);
assertArrayEquals(new String[] { "baeldung" }, output);
}
@Test
public void whenToArrayIsCalledWithLargerInput_thenOutputHasTrailingNull() {
List<Object> list = new CustomList<>();
list.add("baeldung");
String[] input = new String[2];
String[] output = list.toArray(input);
assertArrayEquals(new String[] { "baeldung", null }, output);
}
@Test
public void givenListWithOneElement_whenIterator_thenThisElementIsNext() {
List<Object> list = new CustomList<>();
list.add("baeldung");
Iterator<Object> iterator = list.iterator();
assertTrue(iterator.hasNext());
assertEquals("baeldung", iterator.next());
}
@Test
public void whenIteratorNextIsCalledTwice_thenTheSecondReturnsFalse() {
List<Object> list = new CustomList<>();
list.add("baeldung");
Iterator<Object> iterator = list.iterator();
iterator.next();
assertFalse(iterator.hasNext());
}
}

View File

@ -0,0 +1,154 @@
package com.baeldung.string;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import java.util.Objects;
import static org.assertj.core.api.Assertions.assertThat;
public class StringComparisonTest {
@Test
public void whenUsingComparisonOperator_ThenComparingStrings(){
String string1 = "using comparison operator";
String string2 = "using comparison operator";
String string3 = new String("using comparison operator");
assertThat(string1 == string2).isTrue();
assertThat(string1 == string3).isFalse();
}
@Test
public void whenUsingEqualsMethod_ThenComparingStrings(){
String string1 = "using equals method";
String string2 = "using equals method";
String string3 = "using EQUALS method";
String string4 = new String("using equals method");
assertThat(string1.equals(string2)).isTrue();
assertThat(string1.equals(string4)).isTrue();
assertThat(string1.equals(null)).isFalse();
assertThat(string1.equals(string3)).isFalse();
}
@Test
public void whenUsingEqualsIgnoreCase_ThenComparingStrings(){
String string1 = "using equals ignore case";
String string2 = "USING EQUALS IGNORE CASE";
assertThat(string1.equalsIgnoreCase(string2)).isTrue();
}
@Test
public void whenUsingCompareTo_ThenComparingStrings(){
String author = "author";
String book = "book";
String duplicateBook = "book";
assertThat(author.compareTo(book)).isEqualTo(-1);
assertThat(book.compareTo(author)).isEqualTo(1);
assertThat(duplicateBook.compareTo(book)).isEqualTo(0);
}
@Test
public void whenUsingCompareToIgnoreCase_ThenComparingStrings(){
String author = "Author";
String book = "book";
String duplicateBook = "BOOK";
assertThat(author.compareToIgnoreCase(book)).isEqualTo(-1);
assertThat(book.compareToIgnoreCase(author)).isEqualTo(1);
assertThat(duplicateBook.compareToIgnoreCase(book)).isEqualTo(0);
}
@Test
public void whenUsingObjectsEqualsMethod_ThenComparingStrings(){
String string1 = "using objects equals";
String string2 = "using objects equals";
String string3 = new String("using objects equals");
assertThat(Objects.equals(string1, string2)).isTrue();
assertThat(Objects.equals(string1, string3)).isTrue();
assertThat(Objects.equals(null, null)).isTrue();
assertThat(Objects.equals(null, string1)).isFalse();
}
@Test
public void whenUsingEqualsOfApacheCommons_ThenComparingStrings(){
assertThat(StringUtils.equals(null, null)).isTrue();
assertThat(StringUtils.equals(null, "equals method")).isFalse();
assertThat(StringUtils.equals("equals method", "equals method")).isTrue();
assertThat(StringUtils.equals("equals method", "EQUALS METHOD")).isFalse();
}
@Test
public void whenUsingEqualsIgnoreCaseOfApacheCommons_ThenComparingStrings(){
assertThat(StringUtils.equalsIgnoreCase(null, null)).isTrue();
assertThat(StringUtils.equalsIgnoreCase(null, "equals method")).isFalse();
assertThat(StringUtils.equalsIgnoreCase("equals method", "equals method")).isTrue();
assertThat(StringUtils.equalsIgnoreCase("equals method", "EQUALS METHOD")).isTrue();
}
@Test
public void whenUsingEqualsAnyOf_ThenComparingStrings(){
assertThat(StringUtils.equalsAny(null, null, null)).isTrue();
assertThat(StringUtils.equalsAny("equals any", "equals any", "any")).isTrue();
assertThat(StringUtils.equalsAny("equals any", null, "equals any")).isTrue();
assertThat(StringUtils.equalsAny(null, "equals", "any")).isFalse();
assertThat(StringUtils.equalsAny("equals any", "EQUALS ANY", "ANY")).isFalse();
}
@Test
public void whenUsingEqualsAnyIgnoreCase_ThenComparingStrings(){
assertThat(StringUtils.equalsAnyIgnoreCase(null, null, null)).isTrue();
assertThat(StringUtils.equalsAnyIgnoreCase("equals any", "equals any", "any")).isTrue();
assertThat(StringUtils.equalsAnyIgnoreCase("equals any", null, "equals any")).isTrue();
assertThat(StringUtils.equalsAnyIgnoreCase(null, "equals", "any")).isFalse();
assertThat(StringUtils.equalsAnyIgnoreCase(
"equals any ignore case", "EQUALS ANY IGNORE CASE", "any")).isTrue();
}
@Test
public void whenUsingCompare_thenComparingStringsWithNulls(){
assertThat(StringUtils.compare(null, null)).isEqualTo(0);
assertThat(StringUtils.compare(null, "abc")).isEqualTo(-1);
assertThat(StringUtils.compare("abc", "bbc")).isEqualTo(-1);
assertThat(StringUtils.compare("bbc", "abc")).isEqualTo(1);
assertThat(StringUtils.compare("abc", "abc")).isEqualTo(0);
}
@Test
public void whenUsingCompareIgnoreCase_ThenComparingStringsWithNulls(){
assertThat(StringUtils.compareIgnoreCase(null, null)).isEqualTo(0);
assertThat(StringUtils.compareIgnoreCase(null, "abc")).isEqualTo(-1);
assertThat(StringUtils.compareIgnoreCase("Abc", "bbc")).isEqualTo(-1);
assertThat(StringUtils.compareIgnoreCase("bbc", "ABC")).isEqualTo(1);
assertThat(StringUtils.compareIgnoreCase("abc", "ABC")).isEqualTo(0);
}
@Test
public void whenUsingCompareWithNullIsLessOption_ThenComparingStrings(){
assertThat(StringUtils.compare(null, "abc", true)).isEqualTo(-1);
assertThat(StringUtils.compare(null, "abc", false)).isEqualTo(1);
}
}

View File

@ -17,4 +17,4 @@
- [Sealed Classes in Kotlin](http://www.baeldung.com/kotlin-sealed-classes) - [Sealed Classes in Kotlin](http://www.baeldung.com/kotlin-sealed-classes)
- [JUnit 5 for Kotlin Developers](http://www.baeldung.com/junit-5-kotlin) - [JUnit 5 for Kotlin Developers](http://www.baeldung.com/junit-5-kotlin)
- [Extension Methods in Kotlin](http://www.baeldung.com/kotlin-extension-methods) - [Extension Methods in Kotlin](http://www.baeldung.com/kotlin-extension-methods)
- [Infix Functions in Kotlin](http://www.baeldung.com/kotlin-infix-functions)

View File

@ -1,6 +1,6 @@
package com.baeldung.controller; package com.baeldung.controller;
import java.io.IOException; import com.baeldung.service.StudentService;
import javax.servlet.RequestDispatcher; import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException; import javax.servlet.ServletException;
@ -8,23 +8,19 @@ import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.baeldung.service.StudentService;
/**
*
* @author haseeb
*
*/
@WebServlet(name = "StudentServlet", urlPatterns = "/student-record") @WebServlet(name = "StudentServlet", urlPatterns = "/student-record")
public class StudentServlet extends HttpServlet { public class StudentServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { private final StudentService studentService = new StudentService();
StudentService studentService = new StudentService();
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String studentID = request.getParameter("id"); String studentID = request.getParameter("id");
if (studentID != null) { if (studentID != null) {
int id = Integer.parseInt(studentID); int id = Integer.parseInt(studentID);
request.setAttribute("studentRecord", studentService.getStudent(id)); studentService.getStudent(id)
.ifPresent(s -> request.setAttribute("studentRecord", s));
} }
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/student-record.jsp"); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/student-record.jsp");

View File

@ -1,10 +1,5 @@
package com.baeldung.model; package com.baeldung.model;
/**
*
* @author haseeb
*
*/
public class Student { public class Student {
private int id; private int id;
@ -18,44 +13,26 @@ public class Student {
this.lastName = lastName; this.lastName = lastName;
} }
/**
* @return the id
*/
public int getId() { public int getId() {
return id; return id;
} }
/**
* @param id the id to set
*/
public void setId(int id) { public void setId(int id) {
this.id = id; this.id = id;
} }
/**
* @return the firstName
*/
public String getFirstName() { public String getFirstName() {
return firstName; return firstName;
} }
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) { public void setFirstName(String firstName) {
this.firstName = firstName; this.firstName = firstName;
} }
/**
* @return the lastName
*/
public String getLastName() { public String getLastName() {
return lastName; return lastName;
} }
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) { public void setLastName(String lastName) {
this.lastName = lastName; this.lastName = lastName;
} }

View File

@ -2,33 +2,20 @@ package com.baeldung.service;
import com.baeldung.model.Student; import com.baeldung.model.Student;
/** import java.util.Optional;
*
* @author haseeb
*
*/
public class StudentService { public class StudentService {
/** public Optional<Student> getStudent(int id) {
*
* @param id
* @return
*/
public Student getStudent(int id) {
Student student = null;
switch (id) { switch (id) {
case 1: case 1:
student = new Student(1, "John", "Doe"); return Optional.of(new Student(1, "John", "Doe"));
break; case 2:
case 2: return Optional.of(new Student(2, "Jane", "Goodall"));
student = new Student(2, "Jane", "Goodall"); case 3:
break; return Optional.of(new Student(3, "Max", "Born"));
case 3: default:
student = new Student(3, "Max", "Born"); return Optional.empty();
break;
} }
return student;
} }
} }

View File

@ -1,7 +1,6 @@
package com.baeldung.servlets; package com.baeldung.servlets;
import javax.servlet.RequestDispatcher; import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet; import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -13,7 +12,7 @@ public class FormServlet extends HttpServlet {
@Override @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { throws IOException {
String height = request.getParameter("height"); String height = request.getParameter("height");
String weight = request.getParameter("weight"); String weight = request.getParameter("weight");
@ -28,20 +27,17 @@ public class FormServlet extends HttpServlet {
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/index.jsp"); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/index.jsp");
dispatcher.forward(request, response); dispatcher.forward(request, response);
} catch (Exception e) { } catch (Exception e) {
response.sendRedirect("index.jsp"); response.sendRedirect("index.jsp");
} }
} }
@Override @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) protected void doGet(HttpServletRequest request, HttpServletResponse response) {
throws ServletException, IOException {
// do something else here // do something else here
} }
private Double calculateBMI(Double weight, Double height) { private Double calculateBMI(Double weight, Double height) {
return weight / (height * height); return weight / (height * height);
} }
} }

24
jsonld/.gitignore vendored Normal file
View File

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

BIN
jsonld/.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

View File

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

22
jsonld/README.md Normal file
View File

@ -0,0 +1,22 @@
JSON-LD
=======
Hypermedia serialization with JSON-LD.
### Requirements
- Maven
- JDK 8
- JSON-LD
### Running
To build and start the server simply type
```bash
$ mvn clean install
$ mvn spring-boot:run
```
Now with default configurations it will be available at: [http://localhost:8080](http://localhost:8080)
Enjoy it :)

233
jsonld/mvnw vendored Executable file
View File

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

145
jsonld/mvnw.cmd vendored Normal file
View File

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

53
jsonld/pom.xml Normal file
View File

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jsonld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>jsonld</name>
<description>Hypermedia serialization with JSON-LD</description>
<parent>
<artifactId>parent-boot-5</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-5</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<jsonld.version>0.11.1</jsonld.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.jsonld-java</groupId>
<artifactId>jsonld-java</artifactId>
<version>${jsonld.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

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

View File

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

View File

@ -0,0 +1,33 @@
package com.baeldung;
import com.github.jsonldjava.core.JsonLdError;
import com.github.jsonldjava.core.JsonLdOptions;
import com.github.jsonldjava.core.JsonLdProcessor;
import com.github.jsonldjava.utils.JsonUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertNotEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class JsonLdSerializatorTest {
@Test
public void whenInserting_andCount_thenWeDontGetZero() throws JsonLdError {
String inputStream = "{name:}";
Object jsonObject = JsonUtils.fromInputStream(inputStream);
Map context = new HashMap();
JsonLdOptions options = new JsonLdOptions();
Object compact = JsonLdProcessor.compact(jsonObject, context, options);
assertNotEquals(0, 0);
}
}

View File

@ -20,8 +20,7 @@ public class CacheConfiguration {
public static final String TRANSACTIONAL_CACHE = "transactional-cache"; public static final String TRANSACTIONAL_CACHE = "transactional-cache";
public DefaultCacheManager cacheManager() { public DefaultCacheManager cacheManager() {
DefaultCacheManager cacheManager = new DefaultCacheManager(); return new DefaultCacheManager();
return cacheManager;
} }
public Cache<String, Integer> transactionalCache(DefaultCacheManager cacheManager, CacheListener listener) { public Cache<String, Integer> transactionalCache(DefaultCacheManager cacheManager, CacheListener listener) {

View File

@ -40,9 +40,7 @@ public class CacheListener {
@CacheEntriesEvicted @CacheEntriesEvicted
public void entriesEvicted(CacheEntriesEvictedEvent<String, String> event) { public void entriesEvicted(CacheEntriesEvictedEvent<String, String> event) {
final StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
event.getEntries().entrySet().forEach((e) -> event.getEntries().forEach((key, value) -> builder.append(key).append(", "));
builder.append(e.getKey() + ", ")
);
System.out.println("Evicting following entries from cache: " + builder.toString()); System.out.println("Evicting following entries from cache: " + builder.toString());
} }

View File

@ -31,12 +31,7 @@ public class HelloWorldService {
public String findSimpleHelloWorld() { public String findSimpleHelloWorld() {
String cacheKey = "simple-hello"; String cacheKey = "simple-hello";
String helloWorld = simpleHelloWorldCache.get(cacheKey); return simpleHelloWorldCache.computeIfAbsent(cacheKey, k -> repository.getHelloWorld());
if (helloWorld == null) {
helloWorld = repository.getHelloWorld();
simpleHelloWorldCache.put(cacheKey, helloWorld);
}
return helloWorld;
} }
public String findExpiringHelloWorld() { public String findExpiringHelloWorld() {
@ -79,12 +74,7 @@ public class HelloWorldService {
} }
public String findPassivatingHelloWorld(String key) { public String findPassivatingHelloWorld(String key) {
String value = passivatingHelloWorldCache.get(key); return passivatingHelloWorldCache.computeIfAbsent(key, k -> repository.getHelloWorld());
if(value == null) {
value = repository.getHelloWorld();
passivatingHelloWorldCache.put(key, value);
}
return value;
} }
} }

View File

@ -9,7 +9,7 @@ import org.infinispan.manager.DefaultCacheManager;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import java.util.concurrent.Callable; import java.util.function.Supplier;
public class ConfigurationTest { public class ConfigurationTest {
@ -47,7 +47,6 @@ public class ConfigurationTest {
passivatingHelloWorldCache); passivatingHelloWorldCache);
this.transactionalService = new TransactionalService(transactionalCache); this.transactionalService = new TransactionalService(transactionalCache);
} }
@After @After
@ -55,15 +54,9 @@ public class ConfigurationTest {
cacheManager.stop(); cacheManager.stop();
} }
protected long timeThis(Callable callable) { protected <T> long timeThis(Supplier<T> supplier) {
try { long millis = System.currentTimeMillis();
long milis = System.currentTimeMillis(); supplier.get();
callable.call(); return System.currentTimeMillis() - millis;
return System.currentTimeMillis() - milis;
} catch (Exception e) {
e.printStackTrace();
}
return 0l;
} }
} }

87
microprofile/pom.xml Normal file
View File

@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>microprofile</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<app.name>library</app.name>
<package.file>${project.build.directory}/${app.name}-service.jar</package.file>
<packaging.type>runnable</packaging.type>
</properties>
<dependencies>
<dependency>
<groupId>org.eclipse.microprofile</groupId>
<artifactId>microprofile</artifactId>
<version>1.2</version>
<scope>provided</scope>
<type>pom</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<packagingExcludes>pom.xml</packagingExcludes>
</configuration>
</plugin>
<plugin>
<groupId>net.wasdev.wlp.maven.plugins</groupId>
<artifactId>liberty-maven-plugin</artifactId>
<version>2.1.2</version>
<configuration>
<assemblyArtifact>
<groupId>io.openliberty</groupId>
<artifactId>openliberty-runtime</artifactId>
<version>17.0.0.4</version>
<type>zip</type>
</assemblyArtifact>
<configFile>${basedir}/src/main/liberty/config/server.xml</configFile>
<packageFile>${package.file}</packageFile>
<include>${packaging.type}</include>
<looseApplication>false</looseApplication>
<installAppPackages>project</installAppPackages>
<bootstrapProperties>
<app.context.root>/</app.context.root>
<app.location>${project.artifactId}-${project.version}.war</app.location>
<default.http.port>9080</default.http.port>
<default.https.port>9443</default.https.port>
</bootstrapProperties>
</configuration>
<executions>
<execution>
<id>install-server</id>
<phase>prepare-package</phase>
<goals>
<goal>install-server</goal>
<goal>create-server</goal>
<goal>install-feature</goal>
</goals>
</execution>
<execution>
<id>package-server-with-apps</id>
<phase>package</phase>
<goals>
<goal>install-apps</goal>
<goal>package-server</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,8 @@
package com.baeldung.microprofile;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("/library")
public class LibraryApplication extends Application {
}

View File

@ -0,0 +1,50 @@
package com.baeldung.microprofile.model;
public class Book {
private String id;
private String isbn;
private String name;
private String author;
private Integer pages;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getPages() {
return pages;
}
public void setPages(Integer pages) {
this.pages = pages;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.microprofile.providers;
import com.baeldung.microprofile.model.Book;
import com.baeldung.microprofile.util.BookMapper;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonWriter;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class BookListMessageBodyWriter implements MessageBodyWriter<List<Book>> {
@Override
public boolean isWriteable(Class<?> clazz, Type genericType, Annotation[] annotations, MediaType mediaType) {
return true;
}
@Override
public long getSize(List<Book> books, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return 0;
}
@Override
public void writeTo(List<Book> books, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
JsonWriter jsonWriter = Json.createWriter(entityStream);
JsonArray jsonArray = BookMapper.map(books);
jsonWriter.writeArray(jsonArray);
jsonWriter.close();
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.microprofile.providers;
import com.baeldung.microprofile.model.Book;
import com.baeldung.microprofile.util.BookMapper;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
@Provider
@Consumes(MediaType.APPLICATION_JSON)
public class BookMessageBodyReader implements MessageBodyReader<Book> {
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return type.equals(Book.class);
}
@Override
public Book readFrom(Class<Book> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
return BookMapper.map(entityStream);
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.microprofile.providers;
import com.baeldung.microprofile.model.Book;
import com.baeldung.microprofile.util.BookMapper;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class BookMessageBodyWriter implements MessageBodyWriter<Book> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return type.equals(Book.class);
}
/*
Deprecated in JAX RS 2.0
*/
@Override
public long getSize(Book book, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return 0;
}
/**
* Marsahl Book to OutputStream
*
* @param book
* @param type
* @param genericType
* @param annotations
* @param mediaType
* @param httpHeaders
* @param entityStream
* @throws IOException
* @throws WebApplicationException
*/
@Override
public void writeTo(Book book, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
JsonWriter jsonWriter = Json.createWriter(entityStream);
JsonObject jsonObject = BookMapper.map(book);
jsonWriter.writeObject(jsonObject);
jsonWriter.close();
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.microprofile.repo;
import com.baeldung.microprofile.model.Book;
import javax.enterprise.context.ApplicationScoped;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
@ApplicationScoped
public class BookManager {
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
private AtomicInteger bookIdGenerator = new AtomicInteger(0);
private ConcurrentMap<String, Book> inMemoryStore = new ConcurrentHashMap<>();
public BookManager() {
Book book = new Book();
book.setId(getNextId());
book.setName("Building Microservice With Eclipse MicroProfile");
book.setIsbn("1");
book.setAuthor("baeldung");
book.setPages(420);
inMemoryStore.put(book.getId(), book);
}
private String getNextId() {
String date = LocalDate.now().format(formatter);
return String.format("%04d-%s", bookIdGenerator.incrementAndGet(), date);
}
public String add(Book book) {
String id = getNextId();
book.setId(id);
inMemoryStore.put(id, book);
return id;
}
public Book get(String id) {
return inMemoryStore.get(id);
}
public List<Book> getAll() {
List<Book> books = new ArrayList<>();
books.addAll(inMemoryStore.values());
return books;
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.microprofile.util;
import com.baeldung.microprofile.model.Book;
import javax.json.*;
import java.io.InputStream;
import java.util.List;
public class BookMapper {
public static JsonObject map(Book book) {
JsonObjectBuilder builder = Json.createObjectBuilder();
addValue(builder, "id", book.getId());
addValue(builder, "isbn", book.getIsbn());
addValue(builder, "name", book.getName());
addValue(builder, "author", book.getAuthor());
addValue(builder, "pages", book.getPages());
return builder.build();
}
private static void addValue(JsonObjectBuilder builder, String key, Object value) {
if (value != null) {
builder.add(key, value.toString());
} else {
builder.addNull(key);
}
}
public static JsonArray map(List<Book> books) {
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
books.forEach(book -> {
JsonObject jsonObject = map(book);
arrayBuilder.add(jsonObject);
});
return arrayBuilder.build();
}
public static Book map(InputStream is) {
try(JsonReader jsonReader = Json.createReader(is)) {
JsonObject jsonObject = jsonReader.readObject();
Book book = new Book();
book.setId(getStringFromJson("id", jsonObject));
book.setIsbn(getStringFromJson("isbn", jsonObject));
book.setName(getStringFromJson("name", jsonObject));
book.setAuthor(getStringFromJson("author", jsonObject));
book.setPages(getIntFromJson("pages",jsonObject));
return book;
}
}
private static String getStringFromJson(String key, JsonObject json) {
String returnedString = null;
if (json.containsKey(key)) {
JsonString value = json.getJsonString(key);
if (value != null) {
returnedString = value.getString();
}
}
return returnedString;
}
private static Integer getIntFromJson(String key, JsonObject json) {
Integer returnedValue = null;
if (json.containsKey(key)) {
JsonNumber value = json.getJsonNumber(key);
if (value != null) {
returnedValue = value.intValue();
}
}
return returnedValue;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.microprofile.web;
import com.baeldung.microprofile.model.Book;
import com.baeldung.microprofile.repo.BookManager;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
@Path("books")
@RequestScoped
public class BookEndpoint {
@Inject
private BookManager bookManager;
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getBook(@PathParam("id") String id) {
Book book = bookManager.get(id);
return Response.ok(book).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllBooks() {
return Response.ok(bookManager.getAll()).build();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response add(Book book) {
String bookId = bookManager.add(book);
return Response.created(
UriBuilder.fromResource(this.getClass()).path(bookId).build())
.build();
}
}

View File

@ -0,0 +1,11 @@
<server description="OpenLiberty MicroProfile server">
<featureManager>
<feature>jaxrs-2.0</feature>
<feature>cdi-1.2</feature>
<feature>jsonp-1.0</feature>
</featureManager>
<httpEndpoint httpPort="${default.http.port}" httpsPort="${default.https.port}"
id="defaultHttpEndpoint" host="*"/>
<applicationManager autoExpand="true"/>
<webApplication context-root="${app.context.root}" location="${app.location}"/>
</server>

View File

@ -0,0 +1,2 @@
f5a6ba3b942a82fcbfb72e61502d5c30
9201deea

View File

@ -0,0 +1,20 @@
@*
* This template takes a single argument, a String containing a
* message to display.
*@
@(message: String)
@*
* Call the `main` template with two arguments. The first
* argument is a `String` with the title of the page, the second
* argument is an `Html` object containing the body of the page.
*@
@main("Welcome to Play") {
@*
* Get an `Html` object by calling the built-in Play welcome
* template and passing a `String` message.
*@
@play20.welcome(message, style = "Java")
}

View File

@ -0,0 +1,23 @@
@*
* This template is called from the `index` template. This template
* handles the rendering of the page header and body tags. It takes
* two arguments, a `String` for the title of the page and an `Html`
* object to insert into the body of the page.
*@
@(title: String)(content: Html)
<!DOCTYPE html>
<html lang="en">
<head>
@* Here's where we render the page title `String`. *@
<title>@title</title>
<link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("images/favicon.png")">
<script src="@routes.Assets.versioned("javascripts/hello.js")" type="text/javascript"></script>
</head>
<body>
@* And here's where we render the `Html` object containing
* the page content. *@
@content
</body>
</html>

13
out/production/main122/.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information)

View File

@ -0,0 +1,9 @@
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

View File

@ -0,0 +1,76 @@
About the application
---------------------
This application demonstrates the usage of JavaEE Web Annotations.
Contents of the application
---------------------------
1. AccountServlet.java - Demonstrates the @WebServlet and @ServletSecurity annotation.
NOTES: @WebServlet annotation designates the AccountServlet class as a Servlet component.
The usage of its parameters 'urlPatterns' & 'initParams' can be observed.
An initialization parameter 'type' is being set to denote the type of the bank account.
@ServletSecurity annotation imposes security constraints on the AccountServlet based on
the tomcat-users.xml.
 
This code assumes that your tomcat-users.xml looks as follows:
<role rolename="Admin"/>
<role rolename="Member"/>
<role rolename="Guest"/>
<user username="Annie" password="admin" roles="Admin, Member, Guest" />
<user username="Diane" password="coder" roles="Member, Guest" />
<user username="Ted" password="newbie" roles="Guest" />
 
N.B : To see @ServletSecurity annotation in action, please uncomment the annotation code
for @ServletSecurity.
2. BankAppServletContextListener.java - Demonstrates the @WebListener annotation for denoting a class as a ServletContextListener.
NOTES: Sets a Servlet context attribute ATTR_DEFAULT_LANGUAGE to 'english' on web application start up,
which can then be used throughout the application.
3. LogInFilter.java - Demonstrates the @WebFilter annotation.
NOTES: @WebFilter annotation designates the LogInFilter class as a Filter component.
It filters all requests to the bank account servlet and redirects them to
the login page.
N.B : To see @WebFilter annotation in action, please uncomment the annotation code for @WebFilter.
4. UploadCustomerDocumentsServlet.java - Demonstrates the @MultipartConfig annotation.
NOTES: @MultipartConfig anotation designates the UploadCustomerDocumentsServlet Servlet component,
to handle multipart/form-data requests.
To see it in action, deploy the web application an access the url: http://<your host>:<your port>/JavaEEAnnotationsSample/upload.jsp
Once you upload a file from here, it will get uploaded to D:/custDocs (assuming such a folder exists).
5. index.jsp - This is the welcome page.
NOTES: You can enter a deposit amount here and click on the 'Deposit' button to see the AccountServlet in action.
6. login.jsp - All requests to the AccountServlet are redirected to this page, if the LogInFilter is imposed.
7. upload.jsp - Demonstrates the usage of handling multipart/form-data requests by the UploadCustomerDocumentsServlet.
Building and Running the application
------------------------------------
To build the application:
1. Open the project in eclipse
2. Right click on it in eclispe and choose Run As > Maven build
3. Give 'clean install' under Goals
4. This should build the WAR file of the application
To run the application:
1. Right click on the project
2. Run as > Run on Server
3. This will start you Tomcat server and deploy the application (Provided that you have configured Tomcat in your eclipse)
4. You should now be able to access the url : http://<your host>:<your port>/JavaEEAnnotationsSample

View File

@ -0,0 +1,57 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.javaeeannotations</groupId>
<artifactId>JavaEEAnnotationsSample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>JavaEEAnnotationsSample</name>
<description>JavaEEAnnotationsSample</description>
<dependencies>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>SpringFieldConstructorInjection</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>JavaEEAnnotationsSample</finalName>
</build>
</project>

View File

@ -0,0 +1,10 @@
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>default</realm-name>
</login-config>
</web-app>

View File

@ -0,0 +1,16 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Account</title>
</head>
<body>
<form action="bankAccount" method="post">
Amount: <input type="text" size="5" name="dep"/>
&nbsp;&nbsp;
<input type="submit" value="Deposit" />
</form>
</body>
</html>

View File

@ -0,0 +1,12 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
Login Here...
</body>
</html>

View File

@ -0,0 +1,16 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="uploadCustDocs" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://topdown.server.jaxws.baeldung.com/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://topdown.server.jaxws.baeldung.com/"
name="EmployeeServiceTopDown">
<types>
<xsd:schema targetNamespace="http://topdown.server.jaxws.baeldung.com/">
<xsd:element name="countEmployeesResponse" type="xsd:int"/>
</xsd:schema>
</types>
<message name="countEmployees">
</message>
<message name="countEmployeesResponse">
<part name="parameters" element="tns:countEmployeesResponse"/>
</message>
<portType name="EmployeeServiceTopDown">
<operation name="countEmployees">
<input message="tns:countEmployees"/>
<output message="tns:countEmployeesResponse"/>
</operation>
</portType>
<binding name="EmployeeServiceTopDownSOAP" type="tns:EmployeeServiceTopDown">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="countEmployees">
<soap:operation soapAction="http://topdown.server.jaxws.baeldung.com/EmployeeServiceTopDown/countEmployees"/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="EmployeeServiceTopDown">
<port name="EmployeeServiceTopDownSOAP" binding="tns:EmployeeServiceTopDownSOAP">
<soap:address location="http://localhost:8080/employeeservicetopdown"/>
</port>
</service>
</definitions>

View File

@ -0,0 +1,2 @@
###Relevant Articles:
- [Introduction to the Java NIO Selector](http://www.baeldung.com/java-nio-selector)

View File

@ -0,0 +1,10 @@
# Properties file which configures the operation of the JDK logging facility.
# The system will look for this config file to be specified as a system property:
# -Djava.util.logging.config.file=${project_loc:dailymotion-simple-cmdline-sample}/logging.properties
# Set up the console handler (uncomment "level" to show more fine-grained messages)
handlers = java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level = ALL
# Set up logging of HTTP requests and responses (uncomment "level" to show)
com.google.api.client.http.level = ALL

View File

@ -0,0 +1,52 @@
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="utf-8" />
<title>Wicket Intro Examples</title>
<style type="text/css" media="screen">
<!--
body {
margin: 0px
}
#horizon {
text-align: center;
position: absolute;
top: 50%;
left: 0px;
width: 100%;
height: 1px;
overflow: visible;
visibility: visible;
display: block
}
#content {
font-family: Verdana, Geneva, Arial, sans-serif;
margin-left: -250px;
position: absolute;
top: -35px;
left: 50%;
width: 500px;
height: 70px;
visibility: visible
}
-->
</style>
</head>
<body>
<div id="horizon">
<div id="content">
<div>
<h3>Wicket Introduction Examples:</h3>
<wicket:link>
<a href="helloworld/HelloWorld.html">Hello World!</a>
<br />
<br />
<a href="cafeaddress/CafeAddress.html">Cafes</a>
</wicket:link>
</div>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="utf-8" />
<title>Cafes</title>
</head>
<body>
<div style="width: 800px; margin: 0 auto;">
<select wicket:id="cafes"></select>
<p>
Address: <span wicket:id="address">address</span>
</p>
</div>
</body>
</html>

View File

@ -0,0 +1,5 @@
<html>
<body>
<span wicket:id="hello"></span>
</body>
</html>

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="JavaPersonBean" class="com.baeldug.groovyconfig.JavaPersonBean">
<property name="firstName" value="John" />
<property name="LastName" value="Doe" />
<property name="age" value="30" />
<property name="eyesColor" value="brown" />
<property name="hairColor" value="brown" />
</bean>
</beans>

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean)

View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)

View File

@ -0,0 +1,5 @@
### Relevant Articles:
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
- [A Guide To HTTP Cookies In Java](http://www.baeldung.com/cookies-java)
- [A Guide to the Java URL](http://www.baeldung.com/java-url)
- [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)

View File

@ -0,0 +1,9 @@
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

View File

@ -0,0 +1,3 @@
### Relevant articles
- [Returning an Image or a File with Spring](http://www.baeldung.com/spring-controller-return-image-file)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information)

View File

@ -0,0 +1,20 @@
@*
* This template takes a single argument, a String containing a
* message to display.
*@
@(message: String)
@*
* Call the `main` template with two arguments. The first
* argument is a `String` with the title of the page, the second
* argument is an `Html` object containing the body of the page.
*@
@main("Welcome to Play") {
@*
* Get an `Html` object by calling the built-in Play welcome
* template and passing a `String` message.
*@
@play20.welcome(message, style = "Java")
}

View File

@ -0,0 +1,23 @@
@*
* This template is called from the `index` template. This template
* handles the rendering of the page header and body tags. It takes
* two arguments, a `String` for the title of the page and an `Html`
* object to insert into the body of the page.
*@
@(title: String)(content: Html)
<!DOCTYPE html>
<html lang="en">
<head>
@* Here's where we render the page title `String`. *@
<title>@title</title>
<link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("images/favicon.png")">
<script src="@routes.Assets.versioned("javascripts/hello.js")" type="text/javascript"></script>
</head>
<body>
@* And here's where we render the `Html` object containing
* the page content. *@
@content
</body>
</html>

View File

@ -0,0 +1,3 @@
### Relevant articles
- [Introduction to cglib](http://www.baeldung.com/cglib)

View File

@ -0,0 +1,2 @@
### Relevant Artiles:
- [Filtering a Stream of Optionals in Java](http://www.baeldung.com/java-filter-stream-of-optional)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Testing with Hamcrest](http://www.baeldung.com/java-junit-hamcrest-guide)

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [WebAppConfiguration in Spring Tests](http://www.baeldung.com/spring-webappconfiguration)

View File

@ -0,0 +1,11 @@
### Relevant Articles:
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)
- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel)
- [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng)
- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)
- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor)
- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute)
- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean)
- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice)
- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="punit">
<class>org.baeldung.persistence.model.Foo</class>
<class>org.baeldung.persistence.model.Bar</class>
<properties>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/HIBERTEST"/>
<property name="javax.persistence.ddl-generation" value="drop-and-create-tables"/>
<property name="javax.persistence.logging.level" value="INFO"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<property name="hibernate.cache.use_query_cache" value="false"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Convert Hex to ASCII in Java](http://www.baeldung.com/java-convert-hex-to-ascii)

View File

@ -0,0 +1,2 @@
Relevant Articles:
- [Java String Conversions](http://www.baeldung.com/java-string-conversions)

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