Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA
2018-01-16 22:20:28 +02:00
82 changed files with 2370 additions and 428 deletions
@@ -0,0 +1,44 @@
package com.baeldung.spliteratorAPI;
import java.util.List;
public class Article {
private List<Author> listOfAuthors;
private int id;
private String name;
public Article(String name) {
this.name = name;
}
public Article(List<Author> listOfAuthors, int id) {
super();
this.listOfAuthors = listOfAuthors;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<Author> getListOfAuthors() {
return listOfAuthors;
}
public void setListOfAuthors(List<Author> listOfAuthors) {
this.listOfAuthors = listOfAuthors;
}
}
@@ -0,0 +1,33 @@
package com.baeldung.spliteratorAPI;
public class Author {
private String name;
private int relatedArticleId;
public Author(String name, int relatedArticleId) {
this.name = name;
this.relatedArticleId = relatedArticleId;
}
public int getRelatedArticleId() {
return relatedArticleId;
}
public void setRelatedArticleId(int relatedArticleId) {
this.relatedArticleId = relatedArticleId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "[name: " + name + ", relatedId: " + relatedArticleId + "]";
}
}
@@ -0,0 +1,45 @@
package com.baeldung.spliteratorAPI;
import java.util.Arrays;
import java.util.List;
import java.util.Spliterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class Executor {
public void executeCustomSpliterator() {
Article article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1),
new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0),
new Author("Alice", 1), new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0);
Stream<Author> stream = IntStream.range(0, article.getListOfAuthors()
.size())
.mapToObj(article.getListOfAuthors()::get);
System.out.println("count= " + countAutors(stream.parallel()));
Spliterator<Author> spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors());
Stream<Author> stream2 = StreamSupport.stream(spliterator, true);
System.out.println("count= " + countAutors(stream2.parallel()));
}
public void executeSpliterator() {
Spliterator<Article> split1 = generateElements().spliterator();
Spliterator<Article> split2 = split1.trySplit();
ExecutorService service = Executors.newCachedThreadPool();
service.execute(new Task(split1));
service.execute(new Task(split2));
}
private static int countAutors(Stream<Author> stream) {
RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true), RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine);
return wordCounter.getCounter();
}
private List<Article> generateElements() {
return Stream.generate(() -> new Article("Java"))
.limit(35000)
.collect(Collectors.toList());
}
}
@@ -0,0 +1,27 @@
package com.baeldung.spliteratorAPI;
public class RelatedAuthorCounter {
private final int counter;
private final boolean isRelated;
public RelatedAuthorCounter(int counter, boolean isRelated) {
this.counter = counter;
this.isRelated = isRelated;
}
public RelatedAuthorCounter accumulate(Author author) {
if (author.getRelatedArticleId() == 0) {
return isRelated ? this : new RelatedAuthorCounter(counter, true);
} else {
return isRelated ? new RelatedAuthorCounter(counter + 1, false) : this;
}
}
public RelatedAuthorCounter combine(RelatedAuthorCounter RelatedAuthorCounter) {
return new RelatedAuthorCounter(counter + RelatedAuthorCounter.counter, RelatedAuthorCounter.isRelated);
}
public int getCounter() {
return counter;
}
}
@@ -0,0 +1,47 @@
package com.baeldung.spliteratorAPI;
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;
public class RelatedAuthorSpliterator implements Spliterator<Author> {
private final List<Author> list;
private int current = 0;
public RelatedAuthorSpliterator(List<Author> list) {
this.list = list;
}
@Override
public boolean tryAdvance(Consumer<? super Author> action) {
action.accept(list.get(current++));
return current < list.size();
}
@Override
public Spliterator<Author> trySplit() {
int currentSize = list.size() - current;
if (currentSize < 10) {
return null;
}
for (int splitPos = currentSize / 2 + current; splitPos < list.size(); splitPos++) {
if (list.get(splitPos)
.getRelatedArticleId() == 0) {
Spliterator<Author> spliterator = new RelatedAuthorSpliterator(list.subList(current, splitPos));
current = splitPos;
return spliterator;
}
}
return null;
}
@Override
public long estimateSize() {
return list.size() - current;
}
@Override
public int characteristics() {
return SIZED + CONCURRENT;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.spliteratorAPI;
import java.util.Spliterator;
public class Task implements Runnable {
private Spliterator<Article> spliterator;
private final static String SUFFIX = "- published by Baeldung";
public Task(Spliterator<Article> spliterator) {
this.spliterator = spliterator;
}
@Override
public void run() {
int current = 0;
while (spliterator.tryAdvance(article -> {
article.setName(article.getName()
.concat(SUFFIX));
})) {
current++;
}
;
System.out.println(Thread.currentThread()
.getName() + ":" + current);
}
}
@@ -43,8 +43,9 @@ public class ControlSubThread implements Runnable {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
// no-op, just loop again
}
Thread.currentThread().interrupt();
System.out.println("Thread was interrupted, Failed to complete operation");
}
// do something
}
stopped.set(true);
+5
View File
@@ -44,6 +44,11 @@
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin-stdlib.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jre8</artifactId>
<version>${kotlin-stdlib.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test-junit</artifactId>
@@ -0,0 +1,67 @@
package com.baeldung.kotlin
import org.junit.Test
import java.beans.ExceptionListener
import java.beans.XMLEncoder
import java.io.*
import java.lang.Exception
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.fail
class UseTest {
@Test
fun givenCloseable_whenUseIsCalled_thenItIsClosed() {
val stringWriter = StringWriter()
val writer = BufferedWriter(stringWriter) //Using a BufferedWriter because after close() it throws.
writer.use {
assertEquals(writer, it)
it.write("something")
}
try {
writer.write("something else")
fail("write() should have thrown an exception because the writer is closed.")
} catch (e: IOException) {
//Ok
}
assertEquals("something", stringWriter.toString())
}
@Test
fun givenAutoCloseable_whenUseIsCalled_thenItIsClosed() {
val baos = ByteArrayOutputStream()
val encoder = XMLEncoder(PrintStream(baos)) //XMLEncoder is AutoCloseable but not Closeable.
//Here, we use a PrintStream because after close() it throws.
encoder.exceptionListener = ThrowingExceptionListener()
encoder.use {
assertEquals(encoder, it)
it.writeObject("something")
}
try {
encoder.writeObject("something else")
encoder.flush()
fail("write() should have thrown an exception because the encoder is closed.")
} catch (e: IOException) {
//Ok
}
}
@Test
fun whenSimpleFormIsUsed_thenItWorks() {
StringWriter().use { it.write("something") }
}
}
class ThrowingExceptionListener : ExceptionListener {
override fun exceptionThrown(e: Exception?) {
if(e != null) {
throw e
}
}
}
@@ -55,7 +55,7 @@ public class InfluxDBConnectionLiveTest {
InfluxDB connection = connectDatabase();
// Create "baeldung and check for it
// Create "baeldung" and check for it
connection.createDatabase("baeldung");
assertTrue(connection.databaseExists("baeldung"));
+89
View File
@@ -0,0 +1,89 @@
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>plugin</artifactId>
<version>2.33</version>
<relativePath />
</parent>
<artifactId>jenkins-hello-world</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>hpi</packaging>
<properties>
<!-- Baseline Jenkins version you use to build the plugin. Users must have this version or newer to run. -->
<jenkins.version>2.7.3</jenkins.version>
</properties>
<name>Hello World Plugin</name>
<description>A sample Jenkins Hello World plugin</description>
<url>https://wiki.jenkins-ci.org/display/JENKINS/TODO+Plugin</url>
<licenses>
<license>
<name>MIT License</name>
<url>http://opensource.org/licenses/MIT</url>
</license>
</licenses>
<dependencies>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>structs</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-step-api</artifactId>
<version>2.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-cps</artifactId>
<version>2.39</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-job</artifactId>
<version>2.11.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-basic-steps</artifactId>
<version>2.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-durable-task-step</artifactId>
<version>2.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-api</artifactId>
<version>2.20</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-support</artifactId>
<version>2.14</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>repo.jenkins-ci.org</id>
<url>https://repo.jenkins-ci.org/public/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>repo.jenkins-ci.org</id>
<url>https://repo.jenkins-ci.org/public/</url>
</pluginRepository>
</pluginRepositories>
</project>
@@ -0,0 +1,20 @@
package com.baeldung.jenkins.helloworld;
public class ProjectStats {
private final int classesNumber;
private final int linesNumber;
public ProjectStats(int classesNumber, int linesNumber) {
this.classesNumber = classesNumber;
this.linesNumber = linesNumber;
}
public int getClassesNumber() {
return classesNumber;
}
public int getLinesNumber() {
return linesNumber;
}
}
@@ -0,0 +1,123 @@
package com.baeldung.jenkins.helloworld;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrapperDescriptor;
import org.kohsuke.stapler.DataBoundConstructor;
import javax.annotation.Nonnull;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Stack;
public class ProjectStatsBuildWrapper extends BuildWrapper {
private static final String REPORT_TEMPLATE_PATH = "/stats.html";
private static final String PROJECT_NAME_VAR = "$PROJECT_NAME$";
private static final String CLASSES_NUMBER_VAR = "$CLASSES_NUMBER$";
private static final String LINES_NUMBER_VAR = "$LINES_NUMBER$";
@DataBoundConstructor
public ProjectStatsBuildWrapper() {
}
@Override
public Environment setUp(AbstractBuild build, final Launcher launcher, BuildListener listener) {
return new Environment() {
@Override
public boolean tearDown(AbstractBuild build, BuildListener listener)
throws IOException, InterruptedException
{
ProjectStats stats = buildStats(build.getWorkspace());
String report = generateReport(build.getProject().getDisplayName(), stats);
File artifactsDir = build.getArtifactsDir();
if (!artifactsDir.isDirectory()) {
boolean success = artifactsDir.mkdirs();
if (!success) {
listener.getLogger().println("Can't create artifacts directory at "
+ artifactsDir.getAbsolutePath());
}
}
String path = artifactsDir.getCanonicalPath() + REPORT_TEMPLATE_PATH;
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),
StandardCharsets.UTF_8))) {
writer.write(report);
}
return super.tearDown(build, listener);
}
};
}
private static ProjectStats buildStats(FilePath root) throws IOException, InterruptedException {
int classesNumber = 0;
int linesNumber = 0;
Stack<FilePath> toProcess = new Stack<>();
toProcess.push(root);
while (!toProcess.isEmpty()) {
FilePath path = toProcess.pop();
if (path.isDirectory()) {
toProcess.addAll(path.list());
} else if (path.getName().endsWith(".java")) {
classesNumber++;
linesNumber += countLines(path);
}
}
return new ProjectStats(classesNumber, linesNumber);
}
private static int countLines(FilePath path) throws IOException, InterruptedException {
byte[] buffer = new byte[1024];
int result = 1;
try (InputStream in = path.read()) {
while (true) {
int read = in.read(buffer);
if (read < 0) {
return result;
}
for (int i = 0; i < read; i++) {
if (buffer[i] == '\n') {
result++;
}
}
}
}
}
private static String generateReport(String projectName, ProjectStats stats) throws IOException {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try (InputStream in = ProjectStatsBuildWrapper.class.getResourceAsStream(REPORT_TEMPLATE_PATH)) {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) >= 0) {
bOut.write(buffer, 0, read);
}
}
String content = new String(bOut.toByteArray(), StandardCharsets.UTF_8);
content = content.replace(PROJECT_NAME_VAR, projectName);
content = content.replace(CLASSES_NUMBER_VAR, String.valueOf(stats.getClassesNumber()));
content = content.replace(LINES_NUMBER_VAR, String.valueOf(stats.getLinesNumber()));
return content;
}
@Extension
public static final class DescriptorImpl extends BuildWrapperDescriptor {
@Override
public boolean isApplicable(AbstractProject<?, ?> item) {
return true;
}
@Nonnull
@Override
public String getDisplayName() {
return "Construct project stats during build";
}
}
}
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>$PROJECT_NAME$</title>
</head>
<body>
Project $PROJECT_NAME$:
<table border="1">
<tr>
<th>Classes number</th>
<th>Lines number</th>
</tr>
<tr>
<td>$CLASSES_NUMBER$</td>
<td>$LINES_NUMBER$</td>
</tr>
</table>
</body>
</html>
+2
View File
@@ -1,3 +1,5 @@
### Relevant Articles:
- [Intro to Jedis – the Java Redis Client Library](http://www.baeldung.com/jedis-java-redis-client-library)
- [A Guide to Redis with Redisson](http://www.baeldung.com/redis-redisson)
- [Intro to Lettuce – the Java Redis Client Library](http://www.baeldung.com/lettuce-java-redis-client-library)
+7
View File
@@ -36,6 +36,13 @@
<artifactId>redisson</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
</dependencies>
<properties>
+5
View File
@@ -43,6 +43,10 @@
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Dependencies for Yasson -->
<!-- <dependency> -->
@@ -198,4 +202,5 @@
<geronimo-json_1.1_spec.version>1.0</geronimo-json_1.1_spec.version>
</properties>
</project>
@@ -1,4 +1,4 @@
package com.baeldung.actuator;
package com.baeldung.reactive.actuator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.ReactiveHealthIndicator;
@@ -1,4 +1,4 @@
package com.baeldung.actuator;
package com.baeldung.reactive.actuator;
import org.springframework.boot.actuate.endpoint.annotation.*;
import org.springframework.stereotype.Component;
@@ -1,4 +1,4 @@
package com.baeldung.actuator;
package com.baeldung.reactive.actuator;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.web.WebEndpointResponse;
@@ -1 +1,4 @@
logging.level.root=INFO
logging.level.root=INFO
management.endpoints.web.expose=*
info.app.name=Spring Boot 2 actuator Application
@@ -1,6 +1,5 @@
package com.baeldung.actuator;
package com.baeldung.reactive.actuator;
import com.baeldung.jsonb.Spring5Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@@ -10,12 +9,14 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.reactive.Spring5ReactiveApplication;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5Application.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5ReactiveApplication.class)
public class ActuatorInfoIntegrationTest {
@Autowired
+3
View File
@@ -0,0 +1,3 @@
## Relevant articles:
- [Spring Security 5 -OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login)
-4
View File
@@ -43,10 +43,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.projectreactor</groupId>
<artifactId>reactor-spring</artifactId>
@@ -17,7 +17,6 @@ public class SecurityConfig {
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
return http.authorizeExchange()
.pathMatchers("/admin").hasAuthority("ROLE_ADMIN")
.pathMatchers("/actuator/**").permitAll()
.anyExchange().authenticated()
.and().formLogin()
.and().build();
@@ -1,5 +1,3 @@
server.port=8081
management.endpoints.web.expose=*
info.app.name=Spring Boot 2 actuator Application
logging.level.root=INFO
+5 -3
View File
@@ -1,6 +1,8 @@
### Spring Boot Security Auto-Configuration
- mvn clean install
- uncomment in application.properties spring.profiles.active=basic # for basic auth config
- uncomment in application.properties spring.profiles.active=form # for form based auth config
- uncomment actuator dependency simultaneously with the line from main class
- uncomment actuator dependency simultaneously with the line from basic auth main class
- uncomment security properties for easy testing. If not random will be generated.
### CURL commands
- curl -X POST -u baeldung-admin:baeldung -d grant_type=client_credentials -d username=baeldung-admin -d password=baeldung http://localhost:8080/oauth/token
+4
View File
@@ -43,6 +43,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
@@ -1,4 +1,4 @@
package com.baeldung.springbootsecurity;
package com.baeldung.springbootsecurity.basic_auth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
@SpringBootApplication(exclude = {
SecurityAutoConfiguration.class
// ,ManagementWebSecurityAutoConfiguration.class
})
}, scanBasePackages = "com.baeldung.springbootsecurity.basic_auth")
public class SpringBootSecurityApplication {
public static void main(String[] args) {

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