This commit is contained in:
Ahmed Tawila 2017-11-23 23:24:40 +02:00
commit f13048b63e
190 changed files with 3721 additions and 304 deletions

View File

@ -14,3 +14,4 @@
- [Bubble Sort in Java](http://www.baeldung.com/java-bubble-sort) - [Bubble Sort in Java](http://www.baeldung.com/java-bubble-sort)
- [Introduction to JGraphT](http://www.baeldung.com/jgrapht) - [Introduction to JGraphT](http://www.baeldung.com/jgrapht)
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm) - [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)

3
apache-spark/README.md Normal file
View File

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

View File

@ -65,6 +65,24 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<forkCount>3</forkCount>
<reuseForks>true</reuseForks>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
<exclude>**/JdbcTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
@ -107,4 +125,5 @@
</pluginRepositories> </pluginRepositories>
</project> </project>

View File

@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest @SpringBootTest
public class CasSecuredAppApplicationTests { public class CasSecuredAppApplicationIntegrationTest {
@Test @Test
public void contextLoads() { public void contextLoads() {

View File

@ -109,7 +109,7 @@ cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ?
cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect
cas.authn.jdbc.query[0].user=root cas.authn.jdbc.query[0].user=root
cas.authn.jdbc.query[0].password= cas.authn.jdbc.query[0].password=root
cas.authn.jdbc.query[0].ddlAuto=none cas.authn.jdbc.query[0].ddlAuto=none
#cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver #cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver
cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver

View File

@ -0,0 +1,16 @@
-- Dumping database structure for test
CREATE DATABASE IF NOT EXISTS `test` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `test`;
-- Dumping structure for table test.users
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(50) DEFAULT NULL,
`password` text DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` (`id`, `email`, `password`) VALUES
(1, 'test@test.com', 'Mellon');
/*!40000 ALTER TABLE `users` ENABLE KEYS */;

View File

@ -30,3 +30,5 @@
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) - [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) - [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception) - [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)

View File

@ -0,0 +1,5 @@
package com.baeldung.annotations;
@Deprecated
class ClassWithAnnotation {
}

View File

@ -0,0 +1,9 @@
package com.baeldung.annotations;
class ClassWithDeprecatedMethod {
@Deprecated
static void deprecatedMethod() {
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.annotations;
class ClassWithSafeVarargs<T> {
@SafeVarargs
final void iterateOverVarargs(T... args) {
for (T x : args) {
// do stuff with x
}
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.annotations;
class ClassWithSuppressWarnings {
@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
ClassWithDeprecatedMethod.deprecatedMethod(); // no warning is generated here
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.annotations;
@FunctionalInterface
interface IntConsumer {
void accept(Integer number);
}

View File

@ -0,0 +1,8 @@
package com.baeldung.annotations;
import java.lang.annotation.Repeatable;
@Repeatable(Intervals.class)
@interface Interval {
int hour() default 1;
}

View File

@ -0,0 +1,9 @@
package com.baeldung.annotations;
public class IntervalUsage {
@Interval(hour = 17)
@Interval(hour = 13)
void doPeriodicCleanup() {
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.annotations;
@interface Intervals {
Interval[] value();
}

View File

@ -0,0 +1,11 @@
package com.baeldung.annotations;
import java.lang.annotation.*;
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.LOCAL_VARIABLE, ElementType.FIELD})
@interface MyAnnotation {
}

View File

@ -0,0 +1,16 @@
package com.baeldung.annotations;
class MyAnnotationTarget {
// this is OK
@MyAnnotation
String someField;
// @MyAnnotation <- this is invalid usage!
void doSomething() {
// this also works
@MyAnnotation
String localVariable;
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.annotations;
interface MyOperation {
void perform();
}

View File

@ -0,0 +1,9 @@
package com.baeldung.annotations;
class MyOperationImpl implements MyOperation {
@Override
public void perform() {
}
}

View File

@ -0,0 +1,35 @@
/**
*
*/
package com.baeldung.datetime;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows different ways of converting java.util.Date into java.time.LocalDate.
*
* @author abialas
*
*/
public class DateToLocalDateConverter {
public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) {
return new java.sql.Date(dateToConvert.getTime()).toLocalDate();
}
public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) {
return Instant.ofEpochMilli(dateToConvert.getTime())
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
}

View File

@ -0,0 +1,35 @@
/**
*
*/
package com.baeldung.datetime;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows different ways of converting java.util.Date into java.time.LocalDateTime.
*
* @author abialas
*
*/
public class DateToLocalDateTimeConverter {
public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) {
return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime();
}
public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) {
return Instant.ofEpochMilli(dateToConvert.getTime())
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
}

View File

@ -0,0 +1,27 @@
/**
*
*/
package com.baeldung.datetime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows different ways of converting java.time.LocalDateTime into java.util.Date.
*
* @author abialas
*
*/
public class LocalDateTimeToDateConverter {
public static Date convertToDateViaSqlTimestamp(LocalDateTime dateToConvert) {
return java.sql.Timestamp.valueOf(dateToConvert);
}
public static Date convertToDateViaInstant(LocalDateTime dateToConvert) {
return java.util.Date.from(dateToConvert.atZone(ZoneId.systemDefault())
.toInstant());
}
}

View File

@ -0,0 +1,28 @@
/**
*
*/
package com.baeldung.datetime;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows different ways of converting java.time.LocalDate into java.util.Date.
*
* @author abialas
*
*/
public class LocalDateToDateConverter {
public static Date convertToDateViaSqlDate(LocalDate dateToConvert) {
return java.sql.Date.valueOf(dateToConvert);
}
public static Date convertToDateViaInstant(LocalDate dateToConvert) {
return java.util.Date.from(dateToConvert.atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant());
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.timezonedisplay;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class TimezoneDisplay {
public enum OffsetBase {
GMT, UTC
}
public List<String> getTimeZoneList(OffsetBase base) {
Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
LocalDateTime now = LocalDateTime.now();
return availableZoneIds
.stream()
.map(ZoneId::of)
.sorted(new ZoneComparator())
.map(id -> String.format("(%s%s) %s", base, getOffset(now, id), id.getId()))
.collect(Collectors.toList());
}
private String getOffset(LocalDateTime dateTime, ZoneId id) {
return dateTime
.atZone(id)
.getOffset()
.getId()
.replace("Z", "+00:00");
}
private class ZoneComparator implements Comparator<ZoneId> {
@Override
public int compare(ZoneId zoneId1, ZoneId zoneId2) {
LocalDateTime now = LocalDateTime.now();
ZoneOffset offset1 = now
.atZone(zoneId1)
.getOffset();
ZoneOffset offset2 = now
.atZone(zoneId2)
.getOffset();
return offset1.compareTo(offset2);
}
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.timezonedisplay;
import java.util.List;
public class TimezoneDisplayApp {
public static void main(String... args) {
TimezoneDisplay display = new TimezoneDisplay();
System.out.println("Time zones in UTC:");
List<String> utc = display.getTimeZoneList(TimezoneDisplay.OffsetBase.UTC);
utc.forEach(System.out::println);
System.out.println("Time zones in GMT:");
List<String> gmt = display.getTimeZoneList(TimezoneDisplay.OffsetBase.GMT);
gmt.forEach(System.out::println);
}
}

View File

@ -0,0 +1,72 @@
/**
*
*/
package com.baeldung.datetime;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
/**
*
* JUnits for {@link DateToLocalDateConverter} class.
*
* @author abialas
*
*/
public class DateToLocalDateConverterTest {
@Test
public void shouldReturn10thNovember2010WhenConvertViaInstant() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert);
// then
assertEquals(2010, localDate.get(ChronoField.YEAR));
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
}
@Test
public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert);
// then
assertEquals(2010, localDate.get(ChronoField.YEAR));
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
}
@Test
public void shouldReturn10thNovember2010WhenConvertViaSqlDate() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert);
// then
assertEquals(2010, localDate.get(ChronoField.YEAR));
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
}
}

View File

@ -0,0 +1,78 @@
/**
*
*/
package com.baeldung.datetime;
import static org.junit.Assert.assertEquals;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
/**
*
* JUnits for {@link DateToLocalDateTimeConverter} class.
*
* @author abialas
*
*/
public class DateToLocalDateTimeConverterTest {
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
}

View File

@ -0,0 +1,61 @@
/**
*
*/
package com.baeldung.datetime;
import static org.junit.Assert.assertEquals;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
/**
*
* JUnits for {@link LocalDateTimeToDateConverter} class.
*
* @author abialas
*
*/
public class LocalDateTimeToDateConverterTest {
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() {
// given
LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20);
// when
Date date = LocalDateTimeToDateConverter.convertToDateViaInstant(dateToConvert);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// then
assertEquals(2010, calendar.get(Calendar.YEAR));
assertEquals(10, calendar.get(Calendar.MONTH));
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
assertEquals(8, calendar.get(Calendar.HOUR));
assertEquals(20, calendar.get(Calendar.MINUTE));
assertEquals(0, calendar.get(Calendar.SECOND));
}
@Test
public void shouldReturn10thNovember2010WhenConvertViaSqlTimestamp() {
// given
LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20);
// when
Date date = LocalDateTimeToDateConverter.convertToDateViaSqlTimestamp(dateToConvert);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// then
assertEquals(2010, calendar.get(Calendar.YEAR));
assertEquals(10, calendar.get(Calendar.MONTH));
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
assertEquals(8, calendar.get(Calendar.HOUR));
assertEquals(20, calendar.get(Calendar.MINUTE));
assertEquals(0, calendar.get(Calendar.SECOND));
}
}

View File

@ -0,0 +1,55 @@
/**
*
*/
package com.baeldung.datetime;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
/**
*
* JUnits for {@link LocalDateToDateConverter} class.
*
* @author abialas
*
*/
public class LocalDateToDateConverterTest {
@Test
public void shouldReturn10thNovember2010WhenConvertViaInstant() {
// given
LocalDate dateToConvert = LocalDate.of(2010, 11, 10);
// when
Date date = LocalDateToDateConverter.convertToDateViaInstant(dateToConvert);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// then
assertEquals(2010, calendar.get(Calendar.YEAR));
assertEquals(10, calendar.get(Calendar.MONTH));
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
}
@Test
public void shouldReturn10thNovember2010WhenConvertViaSqlDate() {
// given
LocalDate dateToConvert = LocalDate.of(2010, 11, 10);
// when
Date date = LocalDateToDateConverter.convertToDateViaSqlDate(dateToConvert);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// then
assertEquals(2010, calendar.get(Calendar.YEAR));
assertEquals(10, calendar.get(Calendar.MONTH));
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
}
}

View File

@ -0,0 +1,22 @@
/**
*
*/
package com.baeldung.java9.datetime;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows a way to convert java.util.Date into java.time.LocalDate with new Java 1.9.
*
* @author abialas
*
*/
public class DateToLocalDateConverter {
public static LocalDate convertToLocalDate(Date dateToConvert) {
return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
}
}

View File

@ -0,0 +1,22 @@
/**
*
*/
package com.baeldung.java9.datetime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows a way to convert java.util.Date into java.time.LocalDateTime with new Java 1.9.
*
* @author abialas
*
*/
public class DateToLocalDateTimeConverter {
public static LocalDateTime convertToLocalDateTime(Date dateToConvert) {
return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
}
}

View File

@ -0,0 +1,41 @@
/**
*
*/
package com.baeldung.java9.datetime;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
import com.baeldung.java9.datetime.DateToLocalDateConverter;
/**
* JUnits for {@link DateToLocalDateConverter} class.
*
* @author abialas
*
*/
public class DateToLocalDateConverterTest {
@Test
public void shouldReturn10thNovember2010WhenConvertToLocalDate() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDateTime = DateToLocalDateConverter.convertToLocalDate(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
}
}

View File

@ -0,0 +1,43 @@
/**
*
*/
package com.baeldung.java9.datetime;
import static org.junit.Assert.assertEquals;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
import com.baeldung.java9.datetime.DateToLocalDateTimeConverter;
/**
* JUnits for {@link DateToLocalDateTimeConverter} class.
*
* @author abialas
*
*/
public class DateToLocalDateTimeConverterTest {
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
}

View File

@ -30,3 +30,4 @@
- [Guide to Volatile Keyword in Java](http://www.baeldung.com/java-volatile) - [Guide to Volatile Keyword in Java](http://www.baeldung.com/java-volatile)
- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent) - [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent)
- [Semaphores in Java](http://www.baeldung.com/java-semaphore) - [Semaphores in Java](http://www.baeldung.com/java-semaphore)
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)

View File

@ -0,0 +1,52 @@
package com.baeldung.concurrent.stopping;
import java.util.concurrent.atomic.AtomicBoolean;
public class ControlSubThread implements Runnable {
private Thread worker;
private int interval = 100;
private AtomicBoolean running = new AtomicBoolean(false);
private AtomicBoolean stopped = new AtomicBoolean(true);
public ControlSubThread(int sleepInterval) {
interval = sleepInterval;
}
public void start() {
worker = new Thread(this);
worker.start();
}
public void stop() {
running.set(false);
}
public void interrupt() {
running.set(false);
worker.interrupt();
}
boolean isRunning() {
return running.get();
}
boolean isStopped() {
return stopped.get();
}
public void run() {
running.set(true);
stopped.set(false);
while (running.get()) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
// no-op, just loop again
}
// do something
}
stopped.set(true);
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.concurrent.stopping;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class StopThreadTest {
@Test
public void whenStoppedThreadIsStopped() throws InterruptedException {
int interval = 100;
ControlSubThread controlSubThread = new ControlSubThread(interval);
controlSubThread.start();
// Give things a chance to get set up
Thread.sleep(interval);
assertTrue(controlSubThread.isRunning());
assertFalse(controlSubThread.isStopped());
// Stop it and make sure the flags have been reversed
controlSubThread.stop();
Thread.sleep(interval);
assertTrue(controlSubThread.isStopped());
}
@Test
public void whenInterruptedThreadIsStopped() throws InterruptedException {
int interval = 5000;
ControlSubThread controlSubThread = new ControlSubThread(interval);
controlSubThread.start();
// Give things a chance to get set up
Thread.sleep(100);
assertTrue(controlSubThread.isRunning());
assertFalse(controlSubThread.isStopped());
// Stop it and make sure the flags have been reversed
controlSubThread.interrupt();
// Wait less than the time we would normally sleep, and make sure we exited.
Thread.sleep(interval/10);
assertTrue(controlSubThread.isStopped());
}
}

View File

@ -115,4 +115,8 @@
- [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int) - [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int)
- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns) - [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) - [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)

View File

@ -460,7 +460,7 @@
<logback.version>1.1.7</logback.version> <logback.version>1.1.7</logback.version>
<!-- util --> <!-- util -->
<guava.version>22.0</guava.version> <guava.version>23.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version> <commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version> <bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version> <commons-codec.version>1.10</commons-codec.version>

View File

@ -0,0 +1,6 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public interface AbstractFactory {
Animal getAnimal(String toyType) ;
Color getColor(String colorType);
}

View File

@ -0,0 +1,18 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class AbstractPatternDriver {
public static void main(String[] args) {
AbstractFactory abstractFactory;
//creating a brown toy dog
abstractFactory = FactoryProvider.getFactory("Toy");
Animal toy = abstractFactory.getAnimal("Dog");
abstractFactory = FactoryProvider.getFactory("Color");
Color color = abstractFactory.getColor("Brown");
String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound();
System.out.println(result);
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public interface Animal {
String getType();
String makeSound();
}

View File

@ -0,0 +1,21 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class AnimalFactory implements AbstractFactory {
@Override
public Animal getAnimal(String animalType) {
if ("Dog".equalsIgnoreCase(animalType)) {
return new Dog();
} else if ("Duck".equalsIgnoreCase(animalType)) {
return new Duck();
}
return null;
}
@Override
public Color getColor(String color) {
throw new UnsupportedOperationException();
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class Brown implements Color {
@Override
public String getColor() {
return "brown";
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public interface Color {
String getColor();
}

View File

@ -0,0 +1,21 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class ColorFactory implements AbstractFactory {
@Override
public Color getColor(String colorType) {
if ("Brown".equalsIgnoreCase(colorType)) {
return new Brown();
} else if ("White".equalsIgnoreCase(colorType)) {
return new White();
}
return null;
}
@Override
public Animal getAnimal(String toyType) {
throw new UnsupportedOperationException();
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class Dog implements Animal {
@Override
public String getType() {
return "Dog";
}
@Override
public String makeSound() {
return "Barks";
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class Duck implements Animal {
@Override
public String getType() {
return "Duck";
}
@Override
public String makeSound() {
return "Squeks";
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class FactoryProvider {
public static AbstractFactory getFactory(String choice){
if("Toy".equalsIgnoreCase(choice)){
return new AnimalFactory();
}
else if("Color".equalsIgnoreCase(choice)){
return new ColorFactory();
}
return null;
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public class White implements Color {
@Override
public String getColor() {
return "White";
}
}

View File

@ -0,0 +1,64 @@
package com.baeldung.designpatterns.creational.builder;
public class BankAccount {
private String name;
private String accountNumber;
private String email;
private boolean newsletter;
//The constructor that takes a builder from which it will create object
//the access to this is only provided to builder
private BankAccount(BankAccountBuilder builder) {
this.name = builder.name;
this.accountNumber = builder.accountNumber;
this.email = builder.email;
this.newsletter = builder.newsletter;
}
public static class BankAccountBuilder {
private String name;
private String accountNumber;
private String email;
private boolean newsletter;
//All Mandatory parameters goes with this constructor
public BankAccountBuilder(String name, String accountNumber) {
this.name = name;
this.accountNumber = accountNumber;
}
//setters for optional parameters which returns this same builder
//to support fluent design
public BankAccountBuilder withEmail(String email) {
this.email = email;
return this;
}
public BankAccountBuilder wantNewsletter(boolean newsletter) {
this.newsletter = newsletter;
return this;
}
//the actual build method that prepares and returns a BankAccount object
public BankAccount build() {
return new BankAccount(this);
}
}
//getters
public String getName() {
return name;
}
public String getAccountNumber() {
return accountNumber;
}
public String getEmail() {
return email;
}
public boolean isNewsletter() {
return newsletter;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.designpatterns.creational.builder;
public class BuilderPatternDriver {
public static void main(String[] args) {
BankAccount newAccount = new BankAccount
.BankAccountBuilder("Jon", "22738022275")
.withEmail("jon@example.com")
.wantNewsletter(true)
.build();
System.out.println("Name: " + newAccount.getName());
System.out.println("AccountNumber:" + newAccount.getAccountNumber());
System.out.println("Email: " + newAccount.getEmail());
System.out.println("Want News letter?: " + newAccount.isNewsletter());
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.designpatterns.creational.factory;
public class FactoryDriver {
public static void main(String[] args) {
Polygon p;
PolygonFactory factory = new PolygonFactory();
//get the shape which has 4 sides
p = factory.getPolygon(4);
System.out.println("The shape with 4 sides is a " + p.getType());
//get the shape which has 4 sides
p = factory.getPolygon(8);
System.out.println("The shape with 8 sides is a " + p.getType());
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.factory;
public class Heptagon implements Polygon {
@Override
public String getType() {
return "Heptagon";
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.factory;
public class Octagon implements Polygon {
@Override
public String getType() {
return "Octagon";
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.factory;
public class Pentagon implements Polygon {
@Override
public String getType() {
return "Pentagon";
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.designpatterns.creational.factory;
public interface Polygon {
String getType();
}

View File

@ -0,0 +1,22 @@
package com.baeldung.designpatterns.creational.factory;
public class PolygonFactory {
public Polygon getPolygon(int numberOfSides) {
if(numberOfSides == 3) {
return new Triangle();
}
if(numberOfSides == 4) {
return new Square();
}
if(numberOfSides == 5) {
return new Pentagon();
}
if(numberOfSides == 4) {
return new Heptagon();
}
else if(numberOfSides == 8) {
return new Octagon();
}
return null;
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.factory;
public class Square implements Polygon {
@Override
public String getType() {
return "Square";
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.designpatterns.creational.factory;
public class Triangle implements Polygon {
@Override
public String getType() {
return "Triangle";
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.designpatterns.creational.singleton;
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.designpatterns.creational.singleton;
public class SingletonDriver {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
System.out.println(instance.toString());
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.timezonedisplay;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class TimezoneDisplayJava7 {
public enum OffsetBase {
GMT, UTC
}
public List<String> getTimeZoneList(TimezoneDisplayJava7.OffsetBase base) {
String[] availableZoneIds = TimeZone.getAvailableIDs();
List<String> result = new ArrayList<>(availableZoneIds.length);
for (String zoneId : availableZoneIds) {
TimeZone curTimeZone = TimeZone.getTimeZone(zoneId);
String offset = calculateOffset(curTimeZone.getRawOffset());
result.add(String.format("(%s%s) %s", base, offset, zoneId));
}
Collections.sort(result);
return result;
}
private String calculateOffset(int rawOffset) {
if (rawOffset == 0) {
return "+00:00";
}
long hours = TimeUnit.MILLISECONDS.toHours(rawOffset);
long minutes = TimeUnit.MILLISECONDS.toMinutes(rawOffset);
minutes = Math.abs(minutes - TimeUnit.HOURS.toMinutes(hours));
return String.format("%+03d:%02d", hours, Math.abs(minutes));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.timezonedisplay;
import java.util.List;
public class TimezoneDisplayJava7App {
public static void main(String... args) {
TimezoneDisplayJava7 display = new TimezoneDisplayJava7();
System.out.println("Time zones in UTC:");
List<String> utc = display.getTimeZoneList(TimezoneDisplayJava7.OffsetBase.UTC);
for (String timeZone : utc) {
System.out.println(timeZone);
}
System.out.println("Time zones in GMT:");
List<String> gmt = display.getTimeZoneList(TimezoneDisplayJava7.OffsetBase.GMT);
for (String timeZone : gmt) {
System.out.println(timeZone);
}
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.copyfiles;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class FileCopierTest {
File original = new File("src/test/resources/original.txt");
@Before
public void init() throws IOException {
if (!original.exists())
Files.createFile(original.toPath());
}
@Test
public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithIo.txt");
try (InputStream in = new BufferedInputStream(new FileInputStream(original));
OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) {
byte[] buffer = new byte[1024];
int lengthRead;
while ((lengthRead = in.read(buffer)) > 0) {
out.write(buffer, 0, lengthRead);
out.flush();
}
}
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
@Test
public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
FileUtils.copyFile(original, copied);
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
@Test
public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException {
Path copied = Paths.get("src/test/resources/copiedWithNio.txt");
Path originalPath = original.toPath();
Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
assertThat(copied).exists();
assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied)));
}
@Test
public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
com.google.common.io.Files.copy(original, copied);
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.designpatterns.creational.abstractfactory;
import static org.junit.Assert.*;
import org.junit.Test;
public class AbstractPatternIntegrationTest {
@Test
public void givenAbstractFactory_whenGettingObjects_thenSuccessful() {
AbstractFactory abstractFactory;
//creating a brown toy dog
abstractFactory = FactoryProvider.getFactory("Toy");
Animal toy = abstractFactory.getAnimal("Dog");
abstractFactory = FactoryProvider.getFactory("Color");
Color color = abstractFactory.getColor("Brown");
String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound();
assertEquals("A Dog with brown color Barks", result);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.designpatterns.creational.builder;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class BuilderPatternIntegrationTest {
@Test
public void whenCreatingObjectThroughBuilder_thenObjectValid() {
BankAccount newAccount = new BankAccount
.BankAccountBuilder("Jon", "22738022275")
.withEmail("jon@example.com")
.wantNewsletter(true)
.build();
assertEquals(newAccount.getName(), "Jon");
assertEquals(newAccount.getAccountNumber(), "22738022275");
assertEquals(newAccount.getEmail(), "jon@example.com");
assertEquals(newAccount.isNewsletter(), true);
}
@Test
public void whenSkippingOptionalParameters_thenObjectValid() {
BankAccount newAccount = new BankAccount
.BankAccountBuilder("Jon", "22738022275")
.build();
assertEquals(newAccount.getName(), "Jon");
assertEquals(newAccount.getAccountNumber(), "22738022275");
assertEquals(newAccount.getEmail(), null);
assertEquals(newAccount.isNewsletter(), false);
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.designpatterns.creational.factory;
import static org.junit.Assert.*;
import org.junit.Test;
public class FactoryIntegrationTest {
@Test
public void whenUsingFactoryForSquare_thenCorrectObjectReturned() {
Polygon p;
PolygonFactory factory = new PolygonFactory();
//get the shape which has 4 sides
p = factory.getPolygon(4);
String result = "The shape with 4 sides is a " + p.getType();
assertEquals("The shape with 4 sides is a Square", result);
}
@Test
public void whenUsingFactoryForOctagon_thenCorrectObjectReturned() {
Polygon p;
PolygonFactory factory = new PolygonFactory();
//get the shape which has 4 sides
p = factory.getPolygon(8);
String result = "The shape with 8 sides is a " + p.getType();
assertEquals("The shape with 8 sides is a Octagon", result);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.designpatterns.creational.singleton;
import org.junit.Test;
import static org.junit.Assert.*;
public class SingletonIntegrationTest {
@Test
/**
* Although there is absolutely no way to determine whether
* a class is Singleton, in this test case, we will just
* check for two objects if they point to same instance or
* not. We will also check for their hashcode.
*/
public void whenGettingMultipleObjects_thenAllPointToSame() {
//first object
Singleton obj1 = Singleton.getInstance();
//Second object
Singleton obj2 = Singleton.getInstance();
assertTrue(obj1 == obj2);
assertEquals(obj1.hashCode(), obj2.hashCode());
}
}

View File

@ -14,7 +14,8 @@ public class StringFormatterExampleTests {
public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() { public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() {
//Syntax of Format Specifiers for Date/Time Representation //Syntax of Format Specifiers for Date/Time Representation
Calendar c = new GregorianCalendar(2017, 11, 10); Calendar c = new GregorianCalendar(2017, 11, 10);
String s = String.format("The date is: %1$tm %1$te,%1$tY", c); String s = String.format("The date is: %tm %1$te,%1$tY", c);
assertEquals("The date is: 12 10,2017", s); assertEquals("The date is: 12 10,2017", s);
} }
@ -84,7 +85,7 @@ public class StringFormatterExampleTests {
public void givenString_whenLineSeparatorConversion_thenConvertedString() { public void givenString_whenLineSeparatorConversion_thenConvertedString() {
//Line Separator Conversion //Line Separator Conversion
String s = String.format("First Line %nSecond Line"); String s = String.format("First Line %nSecond Line");
assertEquals("First Line \n" assertEquals("First Line " + System.getProperty("line.separator")
+ "Second Line", s); + "Second Line", s);
} }
@ -114,10 +115,10 @@ public class StringFormatterExampleTests {
public void givenString_whenSpecifyArgumentIndex_thenGotExpected() { public void givenString_whenSpecifyArgumentIndex_thenGotExpected() {
Calendar c = new GregorianCalendar(2017, 11, 10); Calendar c = new GregorianCalendar(2017, 11, 10);
//Argument_Index //Argument_Index
String s = String.format("The date is: %1$tm %1$te,%1$tY", c); String s = String.format("The date is: %tm %1$te,%1$tY", c);
assertEquals("The date is: 12 10,2017", s); assertEquals("The date is: 12 10,2017", s);
s = String.format("The date is: %1$tm %<te,%<tY", c); s = String.format("The date is: %tm %<te,%<tY", c);
assertEquals("The date is: 12 10,2017", s); assertEquals("The date is: 12 10,2017", s);
} }
@ -126,8 +127,7 @@ public class StringFormatterExampleTests {
//Using String Formatter with Appendable //Using String Formatter with Appendable
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb); Formatter formatter = new Formatter(sb);
formatter.format("I am writting to a %1$s Instance.", sb.getClass()); formatter.format("I am writting to a %s Instance.", sb.getClass());
assertEquals("I am writting to a class java.lang.StringBuilder Instance.", sb.toString()); assertEquals("I am writting to a class java.lang.StringBuilder Instance.", sb.toString());
} }

View File

@ -0,0 +1,2 @@
#Copy a File with Java (www.Baeldung.com)
Copying Files with Java is Fun!

View File

@ -2,4 +2,4 @@
This is a sample project for the [deeplearning4j](https://deeplearning4j.org) library. This is a sample project for the [deeplearning4j](https://deeplearning4j.org) library.
### Relevant Articles: ### Relevant Articles:
- [A Guide to deeplearning4j](http://www.baeldung.com/a-guide-to-deeplearning4j/) - [A Guide to deeplearning4j](http://www.baeldung.com/deeplearning4j)

View File

@ -26,16 +26,13 @@ public class TestEJBServlet extends HttpServlet {
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
out.println("<html>"); out.println("<html>");
out.println("<head><title>Users</title></head>");
out.println("<body>"); out.println("<body>");
out.println("<center><h1>List of users:</h1>");
out.println("<table border=\"1\" align=\"center\" style=\"width:50%\">");
for (User user : users) { for (User user : users) {
out.println("<tr>"); out.print(user.getUsername());
out.print("<td>" + user.getUsername() + "</td>"); out.print(" " + user.getEmail() + " <br>");
out.print("<td>" + user.getEmail() + "</td>");
out.println("</tr>");
} }
out.println("</body>");
out.println("</html>");
} }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

1
gradle/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/.gradle/

27
gradle/.travis.yml Normal file
View File

@ -0,0 +1,27 @@
# More details on how to configure the Travis build
# https://docs.travis-ci.com/user/customizing-the-build/
# Speed up build with travis caches
cache:
directories:
- $HOME/.gradle/caches/
- $HOME/.gradle/wrapper/
language: java
jdk:
- oraclejdk8
#Skipping install step to avoid having Travis run arbitrary './gradlew assemble' task
# https://docs.travis-ci.com/user/customizing-the-build/#Skipping-the-Installation-Step
install:
- true
#Don't build tags
branches:
except:
- /^v\d/
#Build and perform release (if needed)
script:
- ./gradlew build -s && ./gradlew ciPerformRelease

View File

@ -1,25 +1,35 @@
apply plugin: 'java' allprojects {
apply plugin: 'maven' repositories {
jcenter()
repositories{ }
mavenCentral()
} }
dependencies{
compile 'org.springframework:spring-context:4.3.5.RELEASE'
}
task hello { subprojects {
println "this Baeldung's tutorial is ${awesomeness}"
version = '1.0'
} }
uploadArchives { apply plugin: 'eclipse'
repositories {
mavenDeployer { println 'This will be executed during the configuration phase.'
repository(url: 'http://yourmavenrepo/repository') {
authentication(userName: 'user', password: 'password'); task configured {
} println 'This will also be executed during the configuration phase.'
}
}
} task execFirstTest {
doLast {
println 'This will be executed during the execution phase.'
}
}
task execSecondTest {
doFirst {
println 'This will be executed first during the execution phase.'
}
doLast {
println 'This will be executed last during the execution phase.'
}
println 'This will be executed during the configuration phase as well.'
} }

View File

@ -1,3 +0,0 @@
awesomeness=awesome
group=com.baeldung.tutorial
version=1.0.1

View File

@ -0,0 +1,41 @@
//This default Shipkit configuration file was created automatically and is intended to be checked-in.
//Default configuration is sufficient for local testing and trying out Shipkit.
//To leverage Shipkit fully, please fix the TODO items, refer to our Getting Started Guide for help:
//
// https://github.com/mockito/shipkit/blob/master/docs/getting-started.md
//
shipkit {
//TODO is the repository correct?
gitHub.repository = "unspecified-user/unspecified-repo"
//TODO generate and use your own read-only GitHub personal access token
gitHub.readOnlyAuthToken = "76826c9ec886612f504d12fd4268b16721c4f85d"
//TODO generate GitHub write token, and ensure your Travis CI has this env variable exported
gitHub.writeAuthToken = System.getenv("GH_WRITE_TOKEN")
}
allprojects {
plugins.withId("com.jfrog.bintray") {
//Bintray configuration is handled by JFrog Bintray Gradle Plugin
//For reference see the official documentation: https://github.com/bintray/gradle-bintray-plugin
bintray {
//TODO sign up for free open source account with https://bintray.com, then look up your API key on your profile page in Bintray
key = '7ea297848ca948adb7d3ee92a83292112d7ae989'
//TODO don't check in the key, remove above line and use env variable exported on CI:
//key = System.getenv("BINTRAY_API_KEY")
pkg {
//TODO configure Bintray settings per your project (https://github.com/bintray/gradle-bintray-plugin)
repo = 'bootstrap'
user = 'shipkit-bootstrap-bot'
userOrg = 'shipkit-bootstrap'
name = 'maven'
licenses = ['MIT']
labels = ['continuous delivery', 'release automation', 'shipkit']
}
}
}
}

Binary file not shown.

View File

@ -1,6 +1,6 @@
#Sat Dec 31 15:46:08 BRT 2016 #Thu Oct 12 16:43:02 BDT 2017
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.2.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-4.2.1-bin.zip

View File

@ -0,0 +1,5 @@
task fromPlugin {
doLast {
println "I'm from plugin"
}
}

View File

@ -0,0 +1,110 @@
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "org.shipkit:shipkit:0.9.117"
}
}
plugins {
id 'java'
}
apply from: 'aplugin.gradle'
apply plugin: 'org.shipkit.bintray-release'
//hello task
task hello {
doLast {
println 'Baeldung'
}
}
//Groovy in gradle task
task toLower {
doLast {
String someString = 'HELLO FROM BAELDUNG'
println "Original: " + someString
println "Lower case: " + someString.toLowerCase()
}
}
// Task dependencies
task helloGradle {
doLast {
println 'Hello Gradle!'
}
}
task fromBaeldung(dependsOn: helloGradle) {
doLast {
println "I'm from Baeldung"
}
}
//Adding behavior to a task via api
task helloBaeldung {
doLast {
println 'I will be executed second'
}
}
helloBaeldung.doFirst {
println 'I will be executed first'
}
helloBaeldung.doLast {
println 'I will be executed third'
}
helloBaeldung {
doLast {
println 'I will be executed fourth'
}
}
//Adding extra task properties
task ourTask {
ext.theProperty = "theValue"
}
task printTaskProperty {
doLast {
println ourTask.theProperty
}
}
//Declaring dependencies
dependencies {
compile group:
'org.springframework', name: 'spring-core', version: '4.3.5.RELEASE'
compile 'org.springframework:spring-core:4.3.5.RELEASE',
'org.springframework:spring-aop:4.3.5.RELEASE'
compile(
[group: 'org.springframework', name: 'spring-core', version: '4.3.5.RELEASE'],
[group: 'org.springframework', name: 'spring-aop', version: '4.3.5.RELEASE']
)
testCompile('org.hibernate:hibernate-core:5.2.12.Final') {
transitive = true
}
runtime(group: 'org.hibernate', name: 'hibernate-core', version: '5.2.12.Final') {
transitive = false
}
runtime "org.codehaus.groovy:groovy-all:2.4.11@jar"
runtime group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.4.11', ext: 'jar'
compile fileTree(dir: 'libs', include: '*.jar')
}

View File

@ -0,0 +1,2 @@
Manifest-Version: 1.0

46
gradle/gradlew vendored
View File

@ -6,12 +6,30 @@
## ##
############################################################################## ##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Attempt to set APP_HOME
DEFAULT_JVM_OPTS="" # Resolve links: $0 may be a link
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
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"` APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD="maximum"
@ -30,6 +48,7 @@ die ( ) {
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false
case "`uname`" in case "`uname`" in
CYGWIN* ) CYGWIN* )
cygwin=true cygwin=true
@ -40,26 +59,11 @@ case "`uname`" in
MINGW* ) MINGW* )
msys=true msys=true
;; ;;
NONSTOP* )
nonstop=true
;;
esac esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
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
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM. # Determine the Java command to use to start the JVM.
@ -85,7 +89,7 @@ location of your Java installation."
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n` MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then

8
gradle/gradlew.bat vendored
View File

@ -8,14 +8,14 @@
@rem Set local scope for the variables with windows NT shell @rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=. if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe @rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome if defined JAVA_HOME goto findJavaFromJavaHome
@ -46,7 +46,7 @@ echo location of your Java installation.
goto fail goto fail
:init :init
@rem Get command-line arguments, handling Windowz variants @rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args if "%@eval[2+2]" == "4" goto 4NT_args

3
gradle/greeter/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/.gradle
/build
/bin

View File

@ -0,0 +1,18 @@
apply plugin : 'java'
apply plugin : 'application'
dependencies {
compile project(':greeting-library')
compile project(':greeting-library-java')
}
mainClassName = 'greeter.Greeter'
run {
if (project.hasProperty("appArgs")) {
args Eval.me(appArgs)
}
else
args = ["Baeldung"];
}

View File

@ -0,0 +1,13 @@
package greeter;
import baeldunggreeter.Formatter;
public class Greeter {
public static void main(String[] args) {
final String output = GreetingFormatter
.greeting(args[0]);
String date = Formatter.getFormattedDate();
System.out.println(output);
System.out.println("Today is :" + date);
}
}

View File

@ -0,0 +1,11 @@
public class TestGreeting{
}

View File

@ -0,0 +1,2 @@
/build
/bin

View File

@ -0,0 +1,9 @@
apply plugin :'java'
//apply plugin : 'application'
dependencies{
compile group: 'joda-time', name: 'joda-time', version: '2.9.9'
testCompile group: 'junit', name: 'junit', version: '4.12'
}

View File

@ -0,0 +1,14 @@
package baeldunggreeter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Formatter {
public static String getFormattedDate() {
DateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
}

View File

@ -0,0 +1,23 @@
package baeldunggreetertest;
import static org.junit.Assert.assertTrue;
import java.util.Date;
import java.util.regex.Pattern;
import org.junit.Test;
import baeldunggreeter.Formatter;
public class FormatterTest {
@Test
public void testFormatter() {
String dateRegex1 = "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) ([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])$";
String dateString = Formatter.getFormattedDate();
assertTrue(Pattern
.matches(dateRegex1, dateString));
}
}

1
gradle/greeting-library/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build/

View File

@ -0,0 +1,10 @@
package greeter
import groovy.transform.CompileStatic
@CompileStatic
class GreetingFormatter{
static String greeting(final String name) {
"Hello, ${name.capitalize()}"
}
}

View File

@ -0,0 +1,13 @@
package greeter
import spock.lang.Specification
class GreetingFormatterSpec extends Specification {
def 'Creating a greeting'() {
expect: 'The greeeting to be correctly capitalized'
GreetingFormatter.greeting('gradlephant') == 'Hello, Gradlephant'
}
}

View File

@ -0,0 +1,9 @@
apply plugin : 'groovy'
dependencies {
compile 'org.codehaus.groovy:groovy:2.4.12'
testCompile 'org.spockframework:spock-core:1.0-groovy-2.4', {
exclude module : 'groovy-all'
}
}

View File

@ -0,0 +1,10 @@
package greeter
import groovy.transform.CompileStatic
@CompileStatic
class GreetingFormatter{
static String greeting(final String name) {
"Hello, ${name.capitalize()}"
}
}

View File

@ -0,0 +1,13 @@
package greeter
import spock.lang.Specification
class GreetingFormatterSpec extends Specification {
def 'Creating a greeting'() {
expect: 'The greeeting to be correctly capitalized'
GreetingFormatter.greeting('gradlephant') == 'Hello, Gradlephant'
}
}

10
gradle/settings.gradle Normal file
View File

@ -0,0 +1,10 @@
rootProject.name = 'gradletutorial'
include 'greeting-library'
include 'greeting-library-java'
include 'greeter'
include 'gradletaskdemo'
println 'This will be executed during the initialization phase.'

View File

@ -1,5 +0,0 @@
public class Main{
public static void main(String[] args){
System.out.println("Baeldung Rocks");
}
}

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