commit
c3680c228a
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.algorithms.enumstatemachine;
|
||||
|
||||
public enum LeaveRequestState {
|
||||
|
||||
Submitted {
|
||||
@Override
|
||||
public LeaveRequestState nextState() {
|
||||
System.out.println("Starting the Leave Request and sending to Team Leader for approval.");
|
||||
return Escalated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String responsiblePerson() {
|
||||
return "Employee";
|
||||
}
|
||||
},
|
||||
Escalated {
|
||||
@Override
|
||||
public LeaveRequestState nextState() {
|
||||
System.out.println("Reviewing the Leave Request and escalating to Department Manager.");
|
||||
return Approved;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String responsiblePerson() {
|
||||
return "Team Leader";
|
||||
}
|
||||
},
|
||||
Approved {
|
||||
@Override
|
||||
public LeaveRequestState nextState() {
|
||||
System.out.println("Approving the Leave Request.");
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String responsiblePerson() {
|
||||
return "Department Manager";
|
||||
}
|
||||
};
|
||||
|
||||
public abstract String responsiblePerson();
|
||||
|
||||
public abstract LeaveRequestState nextState();
|
||||
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.algorithms.enumstatemachine;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LeaveRequestStateUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() {
|
||||
LeaveRequestState state = LeaveRequestState.Escalated;
|
||||
|
||||
assertEquals(state.responsiblePerson(), "Team Leader");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() {
|
||||
LeaveRequestState state = LeaveRequestState.Approved;
|
||||
|
||||
assertEquals(state.responsiblePerson(), "Department Manager");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() {
|
||||
LeaveRequestState state = LeaveRequestState.Submitted;
|
||||
|
||||
state = state.nextState();
|
||||
assertEquals(state, LeaveRequestState.Escalated);
|
||||
|
||||
state = state.nextState();
|
||||
assertEquals(state, LeaveRequestState.Approved);
|
||||
|
||||
state = state.nextState();
|
||||
assertEquals(state, LeaveRequestState.Approved);
|
||||
}
|
||||
}
|
|
@ -14,13 +14,7 @@ import org.apache.kafka.common.serialization.StringDeserializer;
|
|||
import org.apache.log4j.Level;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.apache.spark.SparkConf;
|
||||
import org.apache.spark.api.java.JavaPairRDD;
|
||||
import org.apache.spark.api.java.JavaRDD;
|
||||
import org.apache.spark.api.java.function.FlatMapFunction;
|
||||
import org.apache.spark.api.java.function.Function;
|
||||
import org.apache.spark.api.java.function.Function2;
|
||||
import org.apache.spark.api.java.function.PairFunction;
|
||||
import org.apache.spark.api.java.function.VoidFunction;
|
||||
import org.apache.spark.streaming.Durations;
|
||||
import org.apache.spark.streaming.api.java.JavaDStream;
|
||||
import org.apache.spark.streaming.api.java.JavaInputDStream;
|
||||
|
@ -59,17 +53,17 @@ public class WordCountingApp {
|
|||
|
||||
JavaInputDStream<ConsumerRecord<String, String>> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies.<String, String> Subscribe(topics, kafkaParams));
|
||||
|
||||
JavaPairDStream<String, String> results = messages.mapToPair((PairFunction<ConsumerRecord<String, String>, String, String>) record -> new Tuple2<>(record.key(), record.value()));
|
||||
JavaPairDStream<String, String> results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value()));
|
||||
|
||||
JavaDStream<String> lines = results.map((Function<Tuple2<String, String>, String>) tuple2 -> tuple2._2());
|
||||
JavaDStream<String> lines = results.map(tuple2 -> tuple2._2());
|
||||
|
||||
JavaDStream<String> words = lines.flatMap((FlatMapFunction<String, String>) x -> Arrays.asList(x.split("\\s+"))
|
||||
JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(x.split("\\s+"))
|
||||
.iterator());
|
||||
|
||||
JavaPairDStream<String, Integer> wordCounts = words.mapToPair((PairFunction<String, String, Integer>) s -> new Tuple2<>(s, 1))
|
||||
.reduceByKey((Function2<Integer, Integer, Integer>) (i1, i2) -> i1 + i2);
|
||||
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
|
||||
.reduceByKey((i1, i2) -> i1 + i2);
|
||||
|
||||
wordCounts.foreachRDD((VoidFunction<JavaPairRDD<String, Integer>>) javaRdd -> {
|
||||
wordCounts.foreachRDD(javaRdd -> {
|
||||
Map<String, Integer> wordCountMap = javaRdd.collectAsMap();
|
||||
for (String key : wordCountMap.keySet()) {
|
||||
List<Word> wordList = Arrays.asList(new Word(key, wordCountMap.get(key)));
|
||||
|
|
|
@ -16,15 +16,8 @@ import org.apache.log4j.Logger;
|
|||
import org.apache.spark.SparkConf;
|
||||
import org.apache.spark.api.java.JavaRDD;
|
||||
import org.apache.spark.api.java.JavaSparkContext;
|
||||
import org.apache.spark.api.java.Optional;
|
||||
import org.apache.spark.api.java.function.FlatMapFunction;
|
||||
import org.apache.spark.api.java.function.Function;
|
||||
import org.apache.spark.api.java.function.Function2;
|
||||
import org.apache.spark.api.java.function.Function3;
|
||||
import org.apache.spark.api.java.function.PairFunction;
|
||||
import org.apache.spark.api.java.function.VoidFunction;
|
||||
import org.apache.spark.streaming.Durations;
|
||||
import org.apache.spark.streaming.State;
|
||||
import org.apache.spark.streaming.StateSpec;
|
||||
import org.apache.spark.streaming.api.java.JavaDStream;
|
||||
import org.apache.spark.streaming.api.java.JavaInputDStream;
|
||||
|
@ -71,24 +64,24 @@ public class WordCountingAppWithCheckpoint {
|
|||
|
||||
JavaInputDStream<ConsumerRecord<String, String>> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies.<String, String> Subscribe(topics, kafkaParams));
|
||||
|
||||
JavaPairDStream<String, String> results = messages.mapToPair((PairFunction<ConsumerRecord<String, String>, String, String>) record -> new Tuple2<>(record.key(), record.value()));
|
||||
JavaPairDStream<String, String> results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value()));
|
||||
|
||||
JavaDStream<String> lines = results.map((Function<Tuple2<String, String>, String>) tuple2 -> tuple2._2());
|
||||
JavaDStream<String> lines = results.map(tuple2 -> tuple2._2());
|
||||
|
||||
JavaDStream<String> words = lines.flatMap((FlatMapFunction<String, String>) x -> Arrays.asList(x.split("\\s+"))
|
||||
JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(x.split("\\s+"))
|
||||
.iterator());
|
||||
|
||||
JavaPairDStream<String, Integer> wordCounts = words.mapToPair((PairFunction<String, String, Integer>) s -> new Tuple2<>(s, 1))
|
||||
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
|
||||
.reduceByKey((Function2<Integer, Integer, Integer>) (i1, i2) -> i1 + i2);
|
||||
|
||||
JavaMapWithStateDStream<String, Integer, Integer, Tuple2<String, Integer>> cumulativeWordCounts = wordCounts.mapWithState(StateSpec.function((Function3<String, Optional<Integer>, State<Integer>, Tuple2<String, Integer>>) (word, one, state) -> {
|
||||
JavaMapWithStateDStream<String, Integer, Integer, Tuple2<String, Integer>> cumulativeWordCounts = wordCounts.mapWithState(StateSpec.function((word, one, state) -> {
|
||||
int sum = one.orElse(0) + (state.exists() ? state.get() : 0);
|
||||
Tuple2<String, Integer> output = new Tuple2<>(word, sum);
|
||||
state.update(sum);
|
||||
return output;
|
||||
}));
|
||||
|
||||
cumulativeWordCounts.foreachRDD((VoidFunction<JavaRDD<Tuple2<String, Integer>>>) javaRdd -> {
|
||||
cumulativeWordCounts.foreachRDD(javaRdd -> {
|
||||
List<Tuple2<String, Integer>> wordCountList = javaRdd.collect();
|
||||
for (Tuple2<String, Integer> tuple : wordCountList) {
|
||||
List<Word> wordList = Arrays.asList(new Word(tuple._1, tuple._2));
|
||||
|
|
|
@ -0,0 +1,5 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Blade - A Complete GuideBook](http://www.baeldung.com/blade)
|
||||
|
||||
Run Integration Tests with `mvn integration-test`
|
|
@ -0,0 +1,189 @@
|
|||
<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>
|
||||
<artifactId>blade</artifactId>
|
||||
<name>blade</name>
|
||||
|
||||
<!-- WITH THIS mvn integration-test DOES WORK -->
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
||||
<!-- WITH THIS mvn integration-test DOESN'T WORK -->
|
||||
<!-- <parent> -->
|
||||
<!-- <groupId>com.baeldung</groupId> -->
|
||||
<!-- <artifactId>parent-modules</artifactId> -->
|
||||
<!-- <version>1.0.0-SNAPSHOT</version> -->
|
||||
<!-- </parent> -->
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.bladejava</groupId>
|
||||
<artifactId>blade-mvc</artifactId>
|
||||
<version>2.0.14.RELEASE</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.webjars</groupId>
|
||||
<artifactId>bootstrap</artifactId>
|
||||
<version>4.2.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.8.1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- PROVIDED -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.4</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- TEST -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.11.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>4.5.6</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpmime</artifactId>
|
||||
<version>4.5.6</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpcore</artifactId>
|
||||
<version>4.4.10</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>sample-blade-app</finalName>
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<forkCount>3</forkCount>
|
||||
<reuseForks>true</reuseForks>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.0.0-M3</version>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*LiveTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>integration-test</goal>
|
||||
<goal>verify</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>com.bazaarvoice.maven.plugins</groupId>
|
||||
<artifactId>process-exec-maven-plugin</artifactId>
|
||||
<version>0.7</version>
|
||||
<executions>
|
||||
<!--Start Blade -->
|
||||
<execution>
|
||||
<id>blade-process</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>start</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<name>Blade</name>
|
||||
<waitForInterrupt>false</waitForInterrupt>
|
||||
<arguments>
|
||||
<argument>java</argument>
|
||||
<argument>-jar</argument>
|
||||
<argument>sample-blade-app.jar</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
|
||||
<!--Stop all processes in reverse order -->
|
||||
<execution>
|
||||
<id>stop-all</id>
|
||||
<phase>post-integration-test</phase>
|
||||
<goals>
|
||||
<goal>stop-all</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<configuration>
|
||||
<finalName>${project.build.finalName}</finalName>
|
||||
<appendAssemblyId>false</appendAssemblyId>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>com.baeldung.blade.sample.App</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>make-assembly</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<encoding>UTF-8</encoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.blade.sample;
|
||||
|
||||
import com.baeldung.blade.sample.interceptors.BaeldungMiddleware;
|
||||
import com.blade.Blade;
|
||||
import com.blade.event.EventType;
|
||||
import com.blade.mvc.WebContext;
|
||||
import com.blade.mvc.http.Session;
|
||||
|
||||
public class App {
|
||||
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(App.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Blade.of()
|
||||
.get("/", ctx -> ctx.render("index.html"))
|
||||
.get("/basic-route-example", ctx -> ctx.text("GET called"))
|
||||
.post("/basic-route-example", ctx -> ctx.text("POST called"))
|
||||
.put("/basic-route-example", ctx -> ctx.text("PUT called"))
|
||||
.delete("/basic-route-example", ctx -> ctx.text("DELETE called"))
|
||||
.addStatics("/custom-static")
|
||||
// .showFileList(true)
|
||||
.enableCors(true)
|
||||
.before("/user/*", ctx -> log.info("[NarrowedHook] Before '/user/*', URL called: " + ctx.uri()))
|
||||
.on(EventType.SERVER_STARTED, e -> {
|
||||
String version = WebContext.blade()
|
||||
.env("app.version")
|
||||
.orElse("N/D");
|
||||
log.info("[Event::serverStarted] Loading 'app.version' from configuration, value: " + version);
|
||||
})
|
||||
.on(EventType.SESSION_CREATED, e -> {
|
||||
Session session = (Session) e.attribute("session");
|
||||
session.attribute("mySessionValue", "Baeldung");
|
||||
})
|
||||
.use(new BaeldungMiddleware())
|
||||
.start(App.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.blade.sample;
|
||||
|
||||
import com.blade.mvc.annotation.GetRoute;
|
||||
import com.blade.mvc.annotation.Path;
|
||||
import com.blade.mvc.http.Request;
|
||||
import com.blade.mvc.http.Response;
|
||||
import com.blade.mvc.http.Session;
|
||||
|
||||
@Path
|
||||
public class AttributesExampleController {
|
||||
|
||||
public final static String REQUEST_VALUE = "Some Request value";
|
||||
public final static String SESSION_VALUE = "1337";
|
||||
public final static String HEADER = "Some Header";
|
||||
|
||||
@GetRoute("/request-attribute-example")
|
||||
public void getRequestAttribute(Request request, Response response) {
|
||||
request.attribute("request-val", REQUEST_VALUE);
|
||||
String requestVal = request.attribute("request-val");
|
||||
response.text(requestVal);
|
||||
}
|
||||
|
||||
@GetRoute("/session-attribute-example")
|
||||
public void getSessionAttribute(Request request, Response response) {
|
||||
Session session = request.session();
|
||||
session.attribute("session-val", SESSION_VALUE);
|
||||
String sessionVal = session.attribute("session-val");
|
||||
response.text(sessionVal);
|
||||
}
|
||||
|
||||
@GetRoute("/header-example")
|
||||
public void getHeader(Request request, Response response) {
|
||||
String headerVal = request.header("a-header", HEADER);
|
||||
response.header("a-header", headerVal);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.blade.sample;
|
||||
|
||||
import com.blade.mvc.annotation.Path;
|
||||
import com.blade.mvc.annotation.Route;
|
||||
import com.blade.mvc.http.Response;
|
||||
|
||||
@Path
|
||||
public class LogExampleController {
|
||||
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleController.class);
|
||||
|
||||
@Route(value = "/test-logs")
|
||||
public void testLogs(Response response) {
|
||||
log.trace("This is a TRACE Message");
|
||||
log.debug("This is a DEBUG Message");
|
||||
log.info("This is an INFO Message");
|
||||
log.warn("This is a WARN Message");
|
||||
log.error("This is an ERROR Message");
|
||||
response.text("Check in ./logs");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
package com.baeldung.blade.sample;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
|
||||
import com.baeldung.blade.sample.vo.User;
|
||||
import com.blade.mvc.annotation.CookieParam;
|
||||
import com.blade.mvc.annotation.GetRoute;
|
||||
import com.blade.mvc.annotation.HeaderParam;
|
||||
import com.blade.mvc.annotation.JSON;
|
||||
import com.blade.mvc.annotation.MultipartParam;
|
||||
import com.blade.mvc.annotation.Param;
|
||||
import com.blade.mvc.annotation.Path;
|
||||
import com.blade.mvc.annotation.PathParam;
|
||||
import com.blade.mvc.annotation.PostRoute;
|
||||
import com.blade.mvc.http.Response;
|
||||
import com.blade.mvc.multipart.FileItem;
|
||||
import com.blade.mvc.ui.RestResponse;
|
||||
|
||||
@Path
|
||||
public class ParameterInjectionExampleController {
|
||||
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ParameterInjectionExampleController.class);
|
||||
|
||||
@GetRoute("/params/form")
|
||||
public void formParam(@Param String name, Response response) {
|
||||
log.info("name: " + name);
|
||||
response.text(name);
|
||||
}
|
||||
|
||||
@GetRoute("/params/path/:uid")
|
||||
public void restfulParam(@PathParam Integer uid, Response response) {
|
||||
log.info("uid: " + uid);
|
||||
response.text(String.valueOf(uid));
|
||||
}
|
||||
|
||||
@PostRoute("/params-file") // DO NOT USE A SLASH WITHIN THE ROUTE OR IT WILL BREAK (?)
|
||||
@JSON
|
||||
public RestResponse<?> fileParam(@MultipartParam FileItem fileItem) throws Exception {
|
||||
try {
|
||||
byte[] fileContent = fileItem.getData();
|
||||
|
||||
log.debug("Saving the uploaded file");
|
||||
java.nio.file.Path tempFile = Files.createTempFile("baeldung_tempfiles", ".tmp");
|
||||
Files.write(tempFile, fileContent, StandardOpenOption.WRITE);
|
||||
|
||||
return RestResponse.ok();
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return RestResponse.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@GetRoute("/params/header")
|
||||
public void headerParam(@HeaderParam String customheader, Response response) {
|
||||
log.info("Custom header: " + customheader);
|
||||
response.text(customheader);
|
||||
}
|
||||
|
||||
@GetRoute("/params/cookie")
|
||||
public void cookieParam(@CookieParam(defaultValue = "default value") String myCookie, Response response) {
|
||||
log.info("myCookie: " + myCookie);
|
||||
response.text(myCookie);
|
||||
}
|
||||
|
||||
@PostRoute("/params/vo")
|
||||
public void voParam(@Param User user, Response response) {
|
||||
log.info("user as voParam: " + user.toString());
|
||||
response.html(user.toString() + "<br/><br/><a href='/'>Back</a>");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
package com.baeldung.blade.sample;
|
||||
|
||||
import com.baeldung.blade.sample.configuration.BaeldungException;
|
||||
import com.blade.mvc.WebContext;
|
||||
import com.blade.mvc.annotation.DeleteRoute;
|
||||
import com.blade.mvc.annotation.GetRoute;
|
||||
import com.blade.mvc.annotation.Path;
|
||||
import com.blade.mvc.annotation.PostRoute;
|
||||
import com.blade.mvc.annotation.PutRoute;
|
||||
import com.blade.mvc.annotation.Route;
|
||||
import com.blade.mvc.http.HttpMethod;
|
||||
import com.blade.mvc.http.Request;
|
||||
import com.blade.mvc.http.Response;
|
||||
|
||||
@Path
|
||||
public class RouteExampleController {
|
||||
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RouteExampleController.class);
|
||||
|
||||
@GetRoute("/route-example")
|
||||
public String get() {
|
||||
return "get.html";
|
||||
}
|
||||
|
||||
@PostRoute("/route-example")
|
||||
public String post() {
|
||||
return "post.html";
|
||||
}
|
||||
|
||||
@PutRoute("/route-example")
|
||||
public String put() {
|
||||
return "put.html";
|
||||
}
|
||||
|
||||
@DeleteRoute("/route-example")
|
||||
public String delete() {
|
||||
return "delete.html";
|
||||
}
|
||||
|
||||
@Route(value = "/another-route-example", method = HttpMethod.GET)
|
||||
public String anotherGet() {
|
||||
return "get.html";
|
||||
}
|
||||
|
||||
@Route(value = "/allmatch-route-example")
|
||||
public String allmatch() {
|
||||
return "allmatch.html";
|
||||
}
|
||||
|
||||
@Route(value = "/triggerInternalServerError")
|
||||
public void triggerInternalServerError() {
|
||||
int x = 1 / 0;
|
||||
}
|
||||
|
||||
@Route(value = "/triggerBaeldungException")
|
||||
public void triggerBaeldungException() throws BaeldungException {
|
||||
throw new BaeldungException("Foobar Exception to threat differently");
|
||||
}
|
||||
|
||||
@Route(value = "/user/foo")
|
||||
public void urlCoveredByNarrowedWebhook(Response response) {
|
||||
response.text("Check out for the WebHook covering '/user/*' in the logs");
|
||||
}
|
||||
|
||||
@GetRoute("/load-configuration-in-a-route")
|
||||
public void loadConfigurationInARoute(Response response) {
|
||||
String authors = WebContext.blade()
|
||||
.env("app.authors", "Unknown authors");
|
||||
log.info("[/load-configuration-in-a-route] Loading 'app.authors' from configuration, value: " + authors);
|
||||
response.render("index.html");
|
||||
}
|
||||
|
||||
@GetRoute("/template-output-test")
|
||||
public void templateOutputTest(Request request, Response response) {
|
||||
request.attribute("name", "Blade");
|
||||
response.render("template-output-test.html");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.blade.sample.configuration;
|
||||
|
||||
public class BaeldungException extends RuntimeException {
|
||||
|
||||
public BaeldungException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.blade.sample.configuration;
|
||||
|
||||
import com.blade.ioc.annotation.Bean;
|
||||
import com.blade.mvc.WebContext;
|
||||
import com.blade.mvc.handler.DefaultExceptionHandler;
|
||||
|
||||
@Bean
|
||||
public class GlobalExceptionHandler extends DefaultExceptionHandler {
|
||||
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
@Override
|
||||
public void handle(Exception e) {
|
||||
if (e instanceof BaeldungException) {
|
||||
Exception baeldungException = (BaeldungException) e;
|
||||
String msg = baeldungException.getMessage();
|
||||
log.error("[GlobalExceptionHandler] Intercepted an exception to threat with additional logic. Error message: " + msg);
|
||||
WebContext.response()
|
||||
.render("index.html");
|
||||
|
||||
} else {
|
||||
super.handle(e);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.blade.sample.configuration;
|
||||
|
||||
import com.blade.Blade;
|
||||
import com.blade.ioc.annotation.Bean;
|
||||
import com.blade.loader.BladeLoader;
|
||||
import com.blade.mvc.WebContext;
|
||||
|
||||
@Bean
|
||||
public class LoadConfig implements BladeLoader {
|
||||
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoadConfig.class);
|
||||
|
||||
@Override
|
||||
public void load(Blade blade) {
|
||||
String version = WebContext.blade()
|
||||
.env("app.version")
|
||||
.orElse("N/D");
|
||||
String authors = WebContext.blade()
|
||||
.env("app.authors", "Unknown authors");
|
||||
|
||||
log.info("[LoadConfig] loaded 'app.version' (" + version + ") and 'app.authors' (" + authors + ") in a configuration bean");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.blade.sample.configuration;
|
||||
|
||||
import com.blade.ioc.annotation.Bean;
|
||||
import com.blade.task.annotation.Schedule;
|
||||
|
||||
@Bean
|
||||
public class ScheduleExample {
|
||||
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ScheduleExample.class);
|
||||
|
||||
@Schedule(name = "baeldungTask", cron = "0 */1 * * * ?")
|
||||
public void runScheduledTask() {
|
||||
log.info("[ScheduleExample] This is a scheduled Task running once per minute.");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.blade.sample.interceptors;
|
||||
|
||||
import com.blade.ioc.annotation.Bean;
|
||||
import com.blade.mvc.RouteContext;
|
||||
import com.blade.mvc.hook.WebHook;
|
||||
|
||||
@Bean
|
||||
public class BaeldungHook implements WebHook {
|
||||
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BaeldungHook.class);
|
||||
|
||||
@Override
|
||||
public boolean before(RouteContext ctx) {
|
||||
log.info("[BaeldungHook] called before Route method");
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.blade.sample.interceptors;
|
||||
|
||||
import com.blade.mvc.RouteContext;
|
||||
import com.blade.mvc.hook.WebHook;
|
||||
|
||||
public class BaeldungMiddleware implements WebHook {
|
||||
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BaeldungMiddleware.class);
|
||||
|
||||
@Override
|
||||
public boolean before(RouteContext context) {
|
||||
log.info("[BaeldungMiddleware] called before Route method and other WebHooks");
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.blade.sample.vo;
|
||||
|
||||
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
public class User {
|
||||
@Getter @Setter private String name;
|
||||
@Getter @Setter private String site;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return ReflectionToStringBuilder.toString(this);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
mvc.statics.show-list=true
|
||||
mvc.view.404=my-404.html
|
||||
mvc.view.500=my-500.html
|
||||
app.version=0.0.1
|
||||
app.authors=Andrea Ligios
|
Binary file not shown.
After Width: | Height: | Size: 28 KiB |
Binary file not shown.
After Width: | Height: | Size: 650 B |
|
@ -0,0 +1 @@
|
|||
/* App CSS */
|
|
@ -0,0 +1,43 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Title</title>
|
||||
<script src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
|
||||
<h1>File Upload and download test</h1>
|
||||
<form id="uploadForm" enctype="multipart/form-data">
|
||||
<input id="file" type="file" name="file" />
|
||||
<button id="upload" type="button">Upload</button>
|
||||
</form>
|
||||
|
||||
<br />
|
||||
<a href="/">Back</a>
|
||||
<script>
|
||||
var data = new FormData();
|
||||
|
||||
$('#upload').click(function() {
|
||||
$.ajax({
|
||||
url : '/params-file',
|
||||
type : 'POST',
|
||||
cache : false,
|
||||
data : new FormData($('#uploadForm')[0]),
|
||||
processData : false,
|
||||
contentType : false
|
||||
}).done(function(res) {
|
||||
console.log(res);
|
||||
if (res.success) {
|
||||
alert('Ok');
|
||||
} else {
|
||||
alert(res.msg || 'Error');
|
||||
}
|
||||
}).fail(function(res) {
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,25 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Title</title>
|
||||
<script src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
|
||||
<h1>User POJO post test</h1>
|
||||
|
||||
|
||||
<form id="uploadForm" action="/params/vo" method="post">
|
||||
<span>Person POJO:</span>
|
||||
<input type="text" name="name" placeholder="name"/>
|
||||
<input type="text" name="site" placeholder="site"/>
|
||||
<button id="upload" type="submit">Send user object</button>
|
||||
</form>
|
||||
|
||||
<br />
|
||||
<a href="/">Back</a>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1 @@
|
|||
ALLMATCH called
|
|
@ -0,0 +1 @@
|
|||
DELETE called
|
|
@ -0,0 +1 @@
|
|||
GET called
|
|
@ -0,0 +1,30 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Baeldung Blade App • Written by Andrea Ligios</title>
|
||||
<link href="/static/app.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<h1>Baeldung Blade App - Showcase</h1>
|
||||
|
||||
<h3>Manual tests</h3>
|
||||
<p>The following are tests which are not covered by integration tests, but that can be run manually in order to check the functionality, either in the browser or in the logs, depending on the case.</p>
|
||||
|
||||
<ul>
|
||||
<li><a href="/static/file-upload.html">File Upload</a></li>
|
||||
<li><a href="/static/user-post.html">User POJO Post</a></li>
|
||||
<li><a href="/user/foo">Webhook narrowed to the '/user/*' URL</a></li>
|
||||
<li><a href="/load-configuration-in-a-route">Load Configuration in a Route</a></li>
|
||||
<li><a href="/triggerInternalServerError">Trigger internal server error (and test the custom error 500 page)</a></li>
|
||||
<li><a href="/triggerBaeldungException">Trigger BaeldungException (and test the Global Exception Handler)</a></li>
|
||||
</ul>
|
||||
|
||||
|
||||
<h3>Session value created in App.java</h3>
|
||||
<p>mySessionValue = ${mySessionValue}</p>
|
||||
|
||||
|
||||
<script src="/static/app.js"></script>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,10 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>404 Not found</title>
|
||||
</head>
|
||||
<body>
|
||||
Custom Error 404 Page
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,12 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>500 Internal Server Error</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1> Custom Error 500 Page </h1>
|
||||
<p> The following error occurred: "<strong>${message}</strong>"</p>
|
||||
<pre> ${stackTrace} </pre>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1 @@
|
|||
POST called
|
|
@ -0,0 +1 @@
|
|||
PUT called
|
|
@ -0,0 +1 @@
|
|||
<h1>Hello, ${name}!</h1>
|
|
@ -0,0 +1,56 @@
|
|||
package com.baeldung.blade.sample;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpDelete;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.methods.HttpPut;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class AppLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenBasicRoute_whenGet_thenCorrectOutput() throws Exception {
|
||||
final HttpUriRequest request = new HttpGet("http://localhost:9000/basic-route-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("GET called");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBasicRoute_whenPost_thenCorrectOutput() throws Exception {
|
||||
final HttpUriRequest request = new HttpPost("http://localhost:9000/basic-route-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("POST called");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBasicRoute_whenPut_thenCorrectOutput() throws Exception {
|
||||
final HttpUriRequest request = new HttpPut("http://localhost:9000/basic-route-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("PUT called");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBasicRoute_whenDelete_thenCorrectOutput() throws Exception {
|
||||
final HttpUriRequest request = new HttpDelete("http://localhost:9000/basic-route-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("DELETE called");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package com.baeldung.blade.sample;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class AttributesExampleControllerLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenRequestAttribute_whenSet_thenRetrieveWithGet() throws Exception {
|
||||
final HttpUriRequest request = new HttpGet("http://localhost:9000/request-attribute-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo(AttributesExampleController.REQUEST_VALUE);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSessionAttribute_whenSet_thenRetrieveWithGet() throws Exception {
|
||||
final HttpUriRequest request = new HttpGet("http://localhost:9000/session-attribute-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo(AttributesExampleController.SESSION_VALUE);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHeader_whenSet_thenRetrieveWithGet() throws Exception {
|
||||
final HttpUriRequest request = new HttpGet("http://localhost:9000/header-example");
|
||||
request.addHeader("a-header","foobar");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(httpResponse.getHeaders("a-header")[0].getValue()).isEqualTo("foobar");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNoHeader_whenSet_thenRetrieveDefaultValueWithGet() throws Exception {
|
||||
final HttpUriRequest request = new HttpGet("http://localhost:9000/header-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(httpResponse.getHeaders("a-header")[0].getValue()).isEqualTo(AttributesExampleController.HEADER);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,82 @@
|
|||
package com.baeldung.blade.sample;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.apache.http.client.utils.URIBuilder;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ParameterInjectionExampleControllerLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenFormParam_whenSet_thenRetrieveWithGet() throws Exception {
|
||||
URIBuilder builder = new URIBuilder("http://localhost:9000/params/form");
|
||||
builder.setParameter("name", "Andrea Ligios");
|
||||
|
||||
final HttpUriRequest request = new HttpGet(builder.build());
|
||||
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("Andrea Ligios");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathParam_whenSet_thenRetrieveWithGet() throws Exception {
|
||||
final HttpUriRequest request = new HttpGet("http://localhost:9000/params/path/1337");
|
||||
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("1337");
|
||||
}
|
||||
}
|
||||
|
||||
// @Test
|
||||
// public void givenFileParam_whenSet_thenRetrieveWithGet() throws Exception {
|
||||
//
|
||||
// byte[] data = "this is some temp file content".getBytes("UTF-8");
|
||||
// java.nio.file.Path tempFile = Files.createTempFile("baeldung_test_tempfiles", ".tmp");
|
||||
// Files.write(tempFile, data, StandardOpenOption.WRITE);
|
||||
//
|
||||
// //HttpEntity entity = MultipartEntityBuilder.create().addPart("file", new FileBody(tempFile.toFile())).build();
|
||||
// HttpEntity entity = MultipartEntityBuilder.create().addTextBody("field1", "value1")
|
||||
// .addBinaryBody("fileItem", tempFile.toFile(), ContentType.create("application/octet-stream"), "file1.txt").build();
|
||||
//
|
||||
// final HttpPost post = new HttpPost("http://localhost:9000/params-file");
|
||||
// post.setEntity(entity);
|
||||
//
|
||||
// try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create().build().execute(post);) {
|
||||
// assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("file1.txt");
|
||||
// }
|
||||
// }
|
||||
|
||||
@Test
|
||||
public void givenHeader_whenSet_thenRetrieveWithGet() throws Exception {
|
||||
final HttpUriRequest request = new HttpGet("http://localhost:9000/params/header");
|
||||
request.addHeader("customheader", "foobar");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("foobar");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNoCookie_whenCalled_thenReadDefaultValue() throws Exception {
|
||||
|
||||
final HttpUriRequest request = new HttpGet("http://localhost:9000/params/cookie");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("default value");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,117 @@
|
|||
package com.baeldung.blade.sample;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpDelete;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.methods.HttpPut;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class RouteExampleControllerLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenRoute_whenGet_thenCorrectOutput() throws Exception {
|
||||
final HttpUriRequest request = new HttpGet("http://localhost:9000/route-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("GET called");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRoute_whenPost_thenCorrectOutput() throws Exception {
|
||||
final HttpUriRequest request = new HttpPost("http://localhost:9000/route-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("POST called");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRoute_whenPut_thenCorrectOutput() throws Exception {
|
||||
final HttpUriRequest request = new HttpPut("http://localhost:9000/route-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("PUT called");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRoute_whenDelete_thenCorrectOutput() throws Exception {
|
||||
final HttpUriRequest request = new HttpDelete("http://localhost:9000/route-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("DELETE called");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnotherRoute_whenGet_thenCorrectOutput() throws Exception {
|
||||
final HttpUriRequest request = new HttpGet("http://localhost:9000/another-route-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("GET called");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllMatchRoute_whenGet_thenCorrectOutput() throws Exception {
|
||||
final HttpUriRequest request = new HttpGet("http://localhost:9000/allmatch-route-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("ALLMATCH called");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllMatchRoute_whenPost_thenCorrectOutput() throws Exception {
|
||||
final HttpUriRequest request = new HttpPost("http://localhost:9000/allmatch-route-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("ALLMATCH called");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllMatchRoute_whenPut_thenCorrectOutput() throws Exception {
|
||||
final HttpUriRequest request = new HttpPut("http://localhost:9000/allmatch-route-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("ALLMATCH called");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllMatchRoute_whenDelete_thenCorrectOutput() throws Exception {
|
||||
final HttpUriRequest request = new HttpDelete("http://localhost:9000/allmatch-route-example");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("ALLMATCH called");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestAttribute_whenRenderedWithTemplate_thenCorrectlyEvaluateIt() throws Exception {
|
||||
final HttpUriRequest request = new HttpGet("http://localhost:9000/template-output-test");
|
||||
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
|
||||
.build()
|
||||
.execute(request);) {
|
||||
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("<h1>Hello, Blade!</h1>");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.strings;
|
||||
|
||||
class Concatenate {
|
||||
String first = 'Hello'
|
||||
String last = 'Groovy'
|
||||
|
||||
String doSimpleConcat() {
|
||||
return 'My name is ' + first + ' ' + last
|
||||
}
|
||||
|
||||
String doConcatUsingGString() {
|
||||
return "My name is $first $last"
|
||||
}
|
||||
|
||||
String doConcatUsingGStringClosures() {
|
||||
return "My name is ${-> first} ${-> last}"
|
||||
}
|
||||
|
||||
String doConcatUsingStringConcatMethod() {
|
||||
return 'My name is '.concat(first).concat(' ').concat(last)
|
||||
}
|
||||
|
||||
String doConcatUsingLeftShiftOperator() {
|
||||
return 'My name is ' << first << ' ' << last
|
||||
}
|
||||
|
||||
String doConcatUsingArrayJoinMethod() {
|
||||
return ['My name is', first, last].join(' ')
|
||||
}
|
||||
|
||||
String doConcatUsingArrayInjectMethod() {
|
||||
return [first,' ', last]
|
||||
.inject(new StringBuffer('My name is '), { initial, name -> initial.append(name); return initial }).toString()
|
||||
}
|
||||
|
||||
String doConcatUsingStringBuilder() {
|
||||
return new StringBuilder().append('My name is ').append(first).append(' ').append(last)
|
||||
}
|
||||
|
||||
String doConcatUsingStringBuffer() {
|
||||
return new StringBuffer().append('My name is ').append(first).append(' ').append(last)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,101 @@
|
|||
import com.baeldung.strings.Concatenate;
|
||||
|
||||
class ConcatenateTest extends GroovyTestCase {
|
||||
|
||||
void testSimpleConcat() {
|
||||
def name = new Concatenate()
|
||||
name.first = 'Joe';
|
||||
name.last = 'Smith';
|
||||
def expected = 'My name is Joe Smith'
|
||||
assertToString(name.doSimpleConcat(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingGString() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingGString(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingGStringClosures() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingGStringClosures(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingStringConcatMethod() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingStringConcatMethod(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingLeftShiftOperator() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingLeftShiftOperator(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingArrayJoinMethod() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingArrayJoinMethod(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingArrayInjectMethod() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingArrayInjectMethod(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingStringBuilder() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingStringBuilder(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingStringBuffer() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingStringBuffer(), expected)
|
||||
}
|
||||
|
||||
void testConcatMultilineUsingStringConcatMethod() {
|
||||
def name = new Concatenate()
|
||||
name.first = '''Joe
|
||||
Smith
|
||||
''';
|
||||
name.last = 'Junior';
|
||||
def expected = '''My name is Joe
|
||||
Smith
|
||||
Junior''';
|
||||
assertToString(name.doConcatUsingStringConcatMethod(), expected)
|
||||
}
|
||||
|
||||
void testGStringvsClosure(){
|
||||
def first = "Joe";
|
||||
def last = "Smith";
|
||||
def eagerGString = "My name is $first $last"
|
||||
def lazyGString = "My name is ${-> first} ${-> last}"
|
||||
|
||||
assert eagerGString == "My name is Joe Smith"
|
||||
assert lazyGString == "My name is Joe Smith"
|
||||
first = "David";
|
||||
assert eagerGString == "My name is Joe Smith"
|
||||
assert lazyGString == "My name is David Smith"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.java8.lambda.methodreference;
|
||||
|
||||
public class Bicycle {
|
||||
|
||||
private String brand;
|
||||
private Integer frameSize;
|
||||
|
||||
public Bicycle(String brand) {
|
||||
this.brand = brand;
|
||||
this.frameSize = 0;
|
||||
}
|
||||
|
||||
public Bicycle(String brand, Integer frameSize) {
|
||||
this.brand = brand;
|
||||
this.frameSize = frameSize;
|
||||
}
|
||||
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
public void setBrand(String brand) {
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
public Integer getFrameSize() {
|
||||
return frameSize;
|
||||
}
|
||||
|
||||
public void setFrameSize(Integer frameSize) {
|
||||
this.frameSize = frameSize;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.java8.lambda.methodreference;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
public class BicycleComparator implements Comparator<Bicycle> {
|
||||
|
||||
@Override
|
||||
public int compare(Bicycle a, Bicycle b) {
|
||||
return a.getFrameSize()
|
||||
.compareTo(b.getFrameSize());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
package com.baeldung.java8.lambda.methodreference;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class MethodReferenceExamples {
|
||||
|
||||
private static <T> void doNothingAtAll(Object... o) {
|
||||
}
|
||||
|
||||
;
|
||||
|
||||
@Test
|
||||
public void referenceToStaticMethod() {
|
||||
List<String> messages = Arrays.asList("Hello", "Baeldung", "readers!");
|
||||
messages.forEach((word) -> {
|
||||
System.out.println(word);
|
||||
});
|
||||
messages.forEach(System.out::println);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void referenceToInstanceMethodOfParticularObject() {
|
||||
BicycleComparator bikeFrameSizeComparator = new BicycleComparator();
|
||||
createBicyclesList().stream()
|
||||
.sorted((a, b) -> bikeFrameSizeComparator.compare(a, b));
|
||||
createBicyclesList().stream()
|
||||
.sorted(bikeFrameSizeComparator::compare);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void referenceToInstanceMethodOfArbitratyObjectOfParticularType() {
|
||||
List<Integer> numbers = Arrays.asList(5, 3, 50, 24, 40, 2, 9, 18);
|
||||
numbers.stream()
|
||||
.sorted((a, b) -> Integer.compare(a, b));
|
||||
numbers.stream()
|
||||
.sorted(Integer::compare);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void referenceToConstructor() {
|
||||
BiFunction<String, Integer, Bicycle> bikeCreator = (brand, frameSize) -> new Bicycle(brand, frameSize);
|
||||
BiFunction<String, Integer, Bicycle> bikeCreatorMethodReference = Bicycle::new;
|
||||
List<Bicycle> bikes = new ArrayList<>();
|
||||
bikes.add(bikeCreator.apply("Giant", 50));
|
||||
bikes.add(bikeCreator.apply("Scott", 20));
|
||||
bikes.add(bikeCreatorMethodReference.apply("Trek", 35));
|
||||
bikes.add(bikeCreatorMethodReference.apply("GT", 40));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void referenceToConstructorSimpleExample() {
|
||||
List<String> bikeBrands = Arrays.asList("Giant", "Scott", "Trek", "GT");
|
||||
bikeBrands.stream()
|
||||
.map(Bicycle::new)
|
||||
.toArray(Bicycle[]::new);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void limitationsAndAdditionalExamples() {
|
||||
createBicyclesList().forEach(b -> System.out.printf("Bike brand is '%s' and frame size is '%d'%n", b.getBrand(), b.getFrameSize()));
|
||||
createBicyclesList().forEach((o) -> MethodReferenceExamples.doNothingAtAll(o));
|
||||
}
|
||||
|
||||
private List<Bicycle> createBicyclesList() {
|
||||
List<Bicycle> bikes = new ArrayList<>();
|
||||
bikes.add(new Bicycle("Giant", 50));
|
||||
bikes.add(new Bicycle("Scott", 20));
|
||||
bikes.add(new Bicycle("Trek", 35));
|
||||
bikes.add(new Bicycle("GT", 40));
|
||||
return bikes;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.time;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.powermock.api.mockito.PowerMockito.mockStatic;
|
||||
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest({ Instant.class })
|
||||
public class InstantUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenInstantMock_whenNow_thenGetFixedInstant() {
|
||||
String instantExpected = "2014-12-22T10:15:30Z";
|
||||
Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC"));
|
||||
Instant instant = Instant.now(clock);
|
||||
mockStatic(Instant.class);
|
||||
when(Instant.now()).thenReturn(instant);
|
||||
|
||||
Instant now = Instant.now();
|
||||
|
||||
assertThat(now.toString()).isEqualTo(instantExpected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFixedClock_whenNow_thenGetFixedInstant() {
|
||||
String instantExpected = "2014-12-22T10:15:30Z";
|
||||
Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC"));
|
||||
|
||||
Instant instant = Instant.now(clock);
|
||||
|
||||
assertThat(instant.toString()).isEqualTo(instantExpected);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.time;
|
||||
|
||||
import mockit.Expectations;
|
||||
import mockit.Mock;
|
||||
import mockit.MockUp;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class InstantWithJMockUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenInstantWithJMock_whenNow_thenGetFixedInstant() {
|
||||
String instantExpected = "2014-12-21T10:15:30Z";
|
||||
Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC"));
|
||||
new MockUp<Instant>() {
|
||||
@Mock
|
||||
public Instant now() {
|
||||
return Instant.now(clock);
|
||||
}
|
||||
};
|
||||
|
||||
Instant now = Instant.now();
|
||||
|
||||
assertThat(now.toString()).isEqualTo(instantExpected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInstantWithExpectations_whenNow_thenGetFixedInstant() {
|
||||
Clock clock = Clock.fixed(Instant.parse("2014-12-23T10:15:30.00Z"), ZoneId.of("UTC"));
|
||||
Instant instantExpected = Instant.now(clock);
|
||||
new Expectations(Instant.class) {
|
||||
{
|
||||
Instant.now();
|
||||
result = instantExpected;
|
||||
}
|
||||
};
|
||||
|
||||
Instant now = Instant.now();
|
||||
|
||||
assertThat(now).isEqualTo(instantExpected);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.array.conversions;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
public class FloatToByteArray {
|
||||
|
||||
/**
|
||||
* convert float into byte array using Float API floatToIntBits
|
||||
* @param value
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] floatToByteArray(float value) {
|
||||
int intBits = Float.floatToIntBits(value);
|
||||
return new byte[] {(byte) (intBits >> 24), (byte) (intBits >> 16), (byte) (intBits >> 8), (byte) (intBits) };
|
||||
}
|
||||
|
||||
/**
|
||||
* convert byte array into float using Float API intBitsToFloat
|
||||
* @param bytes
|
||||
* @return float
|
||||
*/
|
||||
public static float byteArrayToFloat(byte[] bytes) {
|
||||
int intBits = bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
|
||||
return Float.intBitsToFloat(intBits);
|
||||
}
|
||||
|
||||
/**
|
||||
* convert float into byte array using ByteBuffer
|
||||
* @param value
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] floatToByteArrayWithByteBuffer(float value) {
|
||||
return ByteBuffer.allocate(4).putFloat(value).array();
|
||||
}
|
||||
|
||||
/**
|
||||
* convert byte array into float using ByteBuffer
|
||||
* @param bytes
|
||||
* @return float
|
||||
*/
|
||||
public static float byteArrayToFloatWithByteBuffer(byte[] bytes) {
|
||||
return ByteBuffer.wrap(bytes).getFloat();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.arrays;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class ParallelPrefixBenchmark {
|
||||
private static final int ARRAY_SIZE = 200_000_000;
|
||||
|
||||
@State(Scope.Benchmark)
|
||||
public static class BigArray {
|
||||
|
||||
int[] data;
|
||||
|
||||
@Setup(Level.Iteration)
|
||||
public void prepare() {
|
||||
data = new int[ARRAY_SIZE];
|
||||
for(int j = 0; j< ARRAY_SIZE; j++) {
|
||||
data[j] = 1;
|
||||
}
|
||||
}
|
||||
|
||||
@TearDown(Level.Iteration)
|
||||
public void destroy() {
|
||||
data = null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void largeArrayLoopSum(BigArray bigArray, Blackhole blackhole) {
|
||||
for (int i = 0; i < ARRAY_SIZE - 1; i++) {
|
||||
bigArray.data[i + 1] += bigArray.data[i];
|
||||
}
|
||||
blackhole.consume(bigArray.data);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void largeArrayParallelPrefixSum(BigArray bigArray, Blackhole blackhole) {
|
||||
Arrays.parallelPrefix(bigArray.data, (left, right) -> left + right);
|
||||
blackhole.consume(bigArray.data);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.array.conversions;
|
||||
|
||||
import static com.baeldung.array.conversions.FloatToByteArray.byteArrayToFloat;
|
||||
import static com.baeldung.array.conversions.FloatToByteArray.byteArrayToFloatWithByteBuffer;
|
||||
import static com.baeldung.array.conversions.FloatToByteArray.floatToByteArray;
|
||||
import static com.baeldung.array.conversions.FloatToByteArray.floatToByteArrayWithByteBuffer;
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FloatToByteArrayUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAFloat_thenConvertToByteArray() {
|
||||
assertArrayEquals(new byte[] { 63, -116, -52, -51}, floatToByteArray(1.1f));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAByteArray_thenConvertToFloat() {
|
||||
assertEquals(1.1f, byteArrayToFloat(new byte[] { 63, -116, -52, -51}), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAFloat_thenConvertToByteArrayUsingByteBuffer() {
|
||||
assertArrayEquals(new byte[] { 63, -116, -52, -51}, floatToByteArrayWithByteBuffer(1.1f));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAByteArray_thenConvertToFloatUsingByteBuffer() {
|
||||
assertEquals(1.1f, byteArrayToFloatWithByteBuffer(new byte[] { 63, -116, -52, -51}), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAFloat_thenConvertToByteArray_thenConvertToFloat() {
|
||||
float floatToConvert = 200.12f;
|
||||
byte[] byteArray = floatToByteArray(floatToConvert);
|
||||
assertEquals(200.12f, byteArrayToFloat(byteArray), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAFloat_thenConvertToByteArrayWithByteBuffer_thenConvertToFloatWithByteBuffer() {
|
||||
float floatToConvert = 30100.42f;
|
||||
byte[] byteArray = floatToByteArrayWithByteBuffer(floatToConvert);
|
||||
assertEquals(30100.42f, byteArrayToFloatWithByteBuffer(byteArray), 0);
|
||||
}
|
||||
}
|
|
@ -1,5 +1,7 @@
|
|||
package com.baeldung.arrays;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Before;
|
||||
|
@ -9,6 +11,7 @@ import org.junit.rules.ExpectedException;
|
|||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class ArraysUnitTest {
|
||||
|
@ -150,4 +153,52 @@ public class ArraysUnitTest {
|
|||
exception.expect(UnsupportedOperationException.class);
|
||||
rets.add("the");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenPrefixAdd_thenAllAccumulated() {
|
||||
int[] arri = new int[] { 1, 2, 3, 4};
|
||||
Arrays.parallelPrefix(arri, (left, right) -> left + right);
|
||||
assertThat(arri, is(new int[] { 1, 3, 6, 10}));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringArray_whenPrefixConcat_thenAllMerged() {
|
||||
String[] arrs = new String[] { "1", "2", "3" };
|
||||
Arrays.parallelPrefix(arrs, (left, right) -> left + right);
|
||||
assertThat(arrs, is(new String[] { "1", "12", "123" }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPrefixAddWithRange_thenRangeAdded() {
|
||||
int[] arri = new int[] { 1, 2, 3, 4, 5 };
|
||||
Arrays.parallelPrefix(arri, 1, 4, (left, right) -> left + right);
|
||||
assertThat(arri, is(new int[] { 1, 2, 5, 9, 5 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPrefixNonAssociative_thenError() {
|
||||
boolean consistent = true;
|
||||
Random r = new Random();
|
||||
for (int k = 0; k < 100_000; k++) {
|
||||
int[] arrA = r.ints(100, 1, 5).toArray();
|
||||
int[] arrB = Arrays.copyOf(arrA, arrA.length);
|
||||
|
||||
Arrays.parallelPrefix(arrA, this::nonassociativeFunc);
|
||||
|
||||
for (int i = 1; i < arrB.length; i++) {
|
||||
arrB[i] = nonassociativeFunc(arrB[i - 1], arrB[i]);
|
||||
}
|
||||
consistent = Arrays.equals(arrA, arrB);
|
||||
if(!consistent) break;
|
||||
}
|
||||
assertFalse(consistent);
|
||||
}
|
||||
|
||||
/**
|
||||
* non-associative int binary operator
|
||||
*/
|
||||
private int nonassociativeFunc(int left, int right) {
|
||||
return left + right*left;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -26,3 +26,4 @@
|
|||
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
|
||||
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
|
||||
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
|
||||
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
|
||||
|
|
|
@ -36,6 +36,22 @@
|
|||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.sf.trove4j</groupId>
|
||||
<artifactId>trove4j</artifactId>
|
||||
<version>3.0.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>fastutil</artifactId>
|
||||
<version>8.1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>colt</groupId>
|
||||
<artifactId>colt</artifactId>
|
||||
<version>1.2.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.list.primitive;
|
||||
|
||||
import com.google.common.primitives.ImmutableIntArray;
|
||||
import com.google.common.primitives.Ints;
|
||||
import gnu.trove.list.array.TIntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.function.IntPredicate;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class PrimitiveCollections {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
int[] primitives = new int[] {5, 10, 0, 2, -8};
|
||||
|
||||
guavaPrimitives(primitives);
|
||||
|
||||
intStream(primitives);
|
||||
|
||||
TIntArrayList tList = new TIntArrayList(primitives);
|
||||
|
||||
cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(primitives);
|
||||
|
||||
IntArrayList fastUtilList = new IntArrayList(primitives);
|
||||
|
||||
System.out.println(tList);
|
||||
|
||||
System.out.println(coltList);
|
||||
|
||||
System.out.println(fastUtilList);
|
||||
}
|
||||
|
||||
private static void intStream(int[] primitives) {
|
||||
|
||||
IntStream stream = IntStream.of(5, 10, 0, 2, -8);
|
||||
|
||||
IntStream newStream = IntStream.of(primitives);
|
||||
|
||||
OptionalDouble average = stream.filter(i -> i > 0).average();
|
||||
}
|
||||
|
||||
|
||||
private static void guavaPrimitives(int[] primitives) {
|
||||
|
||||
ImmutableIntArray immutableIntArray = ImmutableIntArray.builder().addAll(primitives).build();
|
||||
System.out.println(immutableIntArray);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.queueinterface;
|
||||
|
||||
import java.util.AbstractQueue;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class CustomBaeldungQueue<T> extends AbstractQueue<T> {
|
||||
|
||||
private LinkedList<T> elements;
|
||||
|
||||
public CustomBaeldungQueue() {
|
||||
this.elements = new LinkedList<T>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<T> iterator() {
|
||||
return elements.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return elements.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean offer(T t) {
|
||||
if(t == null) return false;
|
||||
elements.add(t);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T poll() {
|
||||
|
||||
Iterator<T> iter = elements.iterator();
|
||||
T t = iter.next();
|
||||
if(t != null){
|
||||
iter.remove();
|
||||
return t;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T peek() {
|
||||
return elements.getFirst();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package com.baeldung.queueinterface;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.PriorityQueue;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class PriorityQueueUnitTest {
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void givenIntegerQueue_whenIntegersOutOfOrder_checkRetrievalOrderIsNatural() {
|
||||
|
||||
PriorityQueue<Integer> integerQueue = new PriorityQueue<>();
|
||||
|
||||
integerQueue.add(9);
|
||||
integerQueue.add(2);
|
||||
integerQueue.add(4);
|
||||
|
||||
int first = integerQueue.poll();
|
||||
int second = integerQueue.poll();
|
||||
int third = integerQueue.poll();
|
||||
|
||||
assertEquals(2, first);
|
||||
assertEquals(4, second);
|
||||
assertEquals(9, third);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringQueue_whenStringsAddedOutOfNaturalOrder_checkRetrievalOrderNatural() {
|
||||
|
||||
PriorityQueue<String> stringQueue = new PriorityQueue<>();
|
||||
|
||||
stringQueue.add("banana");
|
||||
stringQueue.add("apple");
|
||||
stringQueue.add("cherry");
|
||||
|
||||
String first = stringQueue.poll();
|
||||
String second = stringQueue.poll();
|
||||
String third = stringQueue.poll();
|
||||
|
||||
assertEquals("apple", first);
|
||||
assertEquals("banana", second);
|
||||
assertEquals("cherry", third);
|
||||
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.queueinterface;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class CustomBaeldungQueueUnitTest {
|
||||
|
||||
private CustomBaeldungQueue<Integer> customQueue;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
customQueue = new CustomBaeldungQueue<>();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenQueueWithTwoElements_whenElementsRetrieved_checkRetrievalCorrect() {
|
||||
|
||||
customQueue.add(7);
|
||||
customQueue.add(5);
|
||||
|
||||
int first = customQueue.poll();
|
||||
int second = customQueue.poll();
|
||||
|
||||
assertEquals(7, first);
|
||||
assertEquals(5, second);
|
||||
|
||||
}
|
||||
}
|
|
@ -14,4 +14,5 @@
|
|||
- [ExecutorService - Waiting for Threads to Finish](http://www.baeldung.com/java-executor-wait-for-threads)
|
||||
- [wait and notify() Methods in Java](http://www.baeldung.com/java-wait-notify)
|
||||
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
|
||||
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
|
||||
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
|
||||
- [What is Thread-Safety and How to Achieve it](https://www.baeldung.com/java-thread-safety)
|
||||
|
|
|
@ -36,4 +36,5 @@
|
|||
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
|
||||
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
||||
- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension)
|
||||
- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
|
||||
- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
|
||||
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
|
||||
|
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.csv;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class WriteCsvFileExample {
|
||||
|
||||
public String convertToCSV(String[] data) {
|
||||
return Stream.of(data)
|
||||
.map(this::escapeSpecialCharacters)
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
public String escapeSpecialCharacters(String data) {
|
||||
String escapedData = data.replaceAll("\\R", " ");
|
||||
if (data.contains(",") || data.contains("\"") || data.contains("'")) {
|
||||
data = data.replace("\"", "\"\"");
|
||||
escapedData = "\"" + data + "\"";
|
||||
}
|
||||
return escapedData;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
package com.baeldung.files;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.FileVisitResult;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.SimpleFileVisitor;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class ListFiles {
|
||||
public static final int DEPTH = 1;
|
||||
|
||||
public Set<String> listFilesUsingJavaIO(String dir) {
|
||||
return Stream.of(new File(dir).listFiles())
|
||||
.filter(file -> !file.isDirectory())
|
||||
.map(File::getName)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public Set<String> listFilesUsingFileWalk(String dir, int depth) throws IOException {
|
||||
try (Stream<Path> stream = Files.walk(Paths.get(dir), depth)) {
|
||||
return stream.filter(file -> !Files.isDirectory(file))
|
||||
.map(Path::getFileName)
|
||||
.map(Path::toString)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
|
||||
public Set<String> listFilesUsingFileWalkAndVisitor(String dir) throws IOException {
|
||||
Set<String> fileList = new HashSet<>();
|
||||
Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
|
||||
if (!Files.isDirectory(file)) {
|
||||
fileList.add(file.getFileName()
|
||||
.toString());
|
||||
}
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
return fileList;
|
||||
}
|
||||
|
||||
public Set<String> listFilesUsingDirectoryStream(String dir) throws IOException {
|
||||
Set<String> fileList = new HashSet<>();
|
||||
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(dir))) {
|
||||
for (Path path : stream) {
|
||||
if (!Files.isDirectory(path)) {
|
||||
fileList.add(path.getFileName()
|
||||
.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
return fileList;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
package com.baeldung.csv;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class WriteCsvFileExampleUnitTest {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(WriteCsvFileExampleUnitTest.class);
|
||||
|
||||
private static final String CSV_FILE_NAME = "src/test/resources/exampleOutput.csv";
|
||||
private WriteCsvFileExample csvExample;
|
||||
|
||||
@Before
|
||||
public void setupClass() {
|
||||
csvExample = new WriteCsvFileExample();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommaContainingData_whenEscapeSpecialCharacters_stringReturnedInQuotes() {
|
||||
String data = "three,two,one";
|
||||
String escapedData = csvExample.escapeSpecialCharacters(data);
|
||||
|
||||
String expectedData = "\"three,two,one\"";
|
||||
assertEquals(expectedData, escapedData);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenQuoteContainingData_whenEscapeSpecialCharacters_stringReturnedFormatted() {
|
||||
String data = "She said \"Hello\"";
|
||||
String escapedData = csvExample.escapeSpecialCharacters(data);
|
||||
|
||||
String expectedData = "\"She said \"\"Hello\"\"\"";
|
||||
assertEquals(expectedData, escapedData);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewlineContainingData_whenEscapeSpecialCharacters_stringReturnedInQuotes() {
|
||||
String dataNewline = "This contains\na newline";
|
||||
String dataCarriageReturn = "This contains\r\na newline and carriage return";
|
||||
String escapedDataNl = csvExample.escapeSpecialCharacters(dataNewline);
|
||||
String escapedDataCr = csvExample.escapeSpecialCharacters(dataCarriageReturn);
|
||||
|
||||
String expectedData = "This contains a newline";
|
||||
assertEquals(expectedData, escapedDataNl);
|
||||
String expectedDataCr = "This contains a newline and carriage return";
|
||||
assertEquals(expectedDataCr, escapedDataCr);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonSpecialData_whenEscapeSpecialCharacters_stringReturnedUnchanged() {
|
||||
String data = "This is nothing special";
|
||||
String returnedData = csvExample.escapeSpecialCharacters(data);
|
||||
|
||||
assertEquals(data, returnedData);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDataArray_whenConvertToCSV_thenOutputCreated() {
|
||||
List<String[]> dataLines = new ArrayList<String[]>();
|
||||
dataLines.add(new String[] { "John", "Doe", "38", "Comment Data\nAnother line of comment data" });
|
||||
dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" });
|
||||
|
||||
File csvOutputFile = new File(CSV_FILE_NAME);
|
||||
try (PrintWriter pw = new PrintWriter(csvOutputFile)) {
|
||||
dataLines.stream()
|
||||
.map(csvExample::convertToCSV)
|
||||
.forEach(pw::println);
|
||||
} catch (FileNotFoundException e) {
|
||||
LOG.error("IOException " + e.getMessage());
|
||||
}
|
||||
|
||||
assertTrue(csvOutputFile.exists());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,100 @@
|
|||
package com.baeldung.directories;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class NewDirectoryUnitTest {
|
||||
|
||||
private static final File TEMP_DIRECTORY = new File(System.getProperty("java.io.tmpdir"));
|
||||
|
||||
@Before
|
||||
public void beforeEach() {
|
||||
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
|
||||
File nestedInNewDirectory = new File(newDirectory, "nested_directory");
|
||||
File existingDirectory = new File(TEMP_DIRECTORY, "existing_directory");
|
||||
File existingNestedDirectory = new File(existingDirectory, "existing_nested_directory");
|
||||
File nestedInExistingDirectory = new File(existingDirectory, "nested_directory");
|
||||
|
||||
nestedInNewDirectory.delete();
|
||||
newDirectory.delete();
|
||||
nestedInExistingDirectory.delete();
|
||||
existingDirectory.mkdir();
|
||||
existingNestedDirectory.mkdir();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnexistingDirectory_whenMkdir_thenTrue() {
|
||||
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
|
||||
assertFalse(newDirectory.exists());
|
||||
|
||||
boolean directoryCreated = newDirectory.mkdir();
|
||||
|
||||
assertTrue(directoryCreated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingDirectory_whenMkdir_thenFalse() {
|
||||
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
|
||||
newDirectory.mkdir();
|
||||
assertTrue(newDirectory.exists());
|
||||
|
||||
boolean directoryCreated = newDirectory.mkdir();
|
||||
|
||||
assertFalse(directoryCreated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnexistingNestedDirectories_whenMkdir_thenFalse() {
|
||||
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
|
||||
File nestedDirectory = new File(newDirectory, "nested_directory");
|
||||
assertFalse(newDirectory.exists());
|
||||
assertFalse(nestedDirectory.exists());
|
||||
|
||||
boolean directoriesCreated = nestedDirectory.mkdir();
|
||||
|
||||
assertFalse(directoriesCreated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnexistingNestedDirectories_whenMkdirs_thenTrue() {
|
||||
File newDirectory = new File(System.getProperty("java.io.tmpdir") + File.separator + "new_directory");
|
||||
File nestedDirectory = new File(newDirectory, "nested_directory");
|
||||
assertFalse(newDirectory.exists());
|
||||
assertFalse(nestedDirectory.exists());
|
||||
|
||||
boolean directoriesCreated = nestedDirectory.mkdirs();
|
||||
|
||||
assertTrue(directoriesCreated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingParentDirectories_whenMkdirs_thenTrue() {
|
||||
File newDirectory = new File(TEMP_DIRECTORY, "existing_directory");
|
||||
newDirectory.mkdir();
|
||||
File nestedDirectory = new File(newDirectory, "nested_directory");
|
||||
assertTrue(newDirectory.exists());
|
||||
assertFalse(nestedDirectory.exists());
|
||||
|
||||
boolean directoriesCreated = nestedDirectory.mkdirs();
|
||||
|
||||
assertTrue(directoriesCreated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingNestedDirectories_whenMkdirs_thenFalse() {
|
||||
File existingDirectory = new File(TEMP_DIRECTORY, "existing_directory");
|
||||
File existingNestedDirectory = new File(existingDirectory, "existing_nested_directory");
|
||||
assertTrue(existingDirectory.exists());
|
||||
assertTrue(existingNestedDirectory.exists());
|
||||
|
||||
boolean directoriesCreated = existingNestedDirectory.mkdirs();
|
||||
|
||||
assertFalse(directoriesCreated);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,96 @@
|
|||
package com.baeldung.file;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.util.StreamUtils;
|
||||
|
||||
public class FilesClearDataUnitTest {
|
||||
|
||||
public static final String FILE_PATH = "src/test/resources/fileexample.txt";
|
||||
|
||||
@Before
|
||||
@After
|
||||
public void setup() throws IOException {
|
||||
PrintWriter writer = new PrintWriter(FILE_PATH);
|
||||
writer.print("This example shows how we can delete the file contents without deleting the file");
|
||||
writer.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingFile_whenDeleteContentUsingPrintWritter_thenEmptyFile() throws IOException {
|
||||
PrintWriter writer = new PrintWriter(FILE_PATH);
|
||||
writer.print("");
|
||||
writer.close();
|
||||
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingFile_whenDeleteContentUsingPrintWritterWithougObject_thenEmptyFile() throws IOException {
|
||||
new PrintWriter(FILE_PATH).close();
|
||||
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingFile_whenDeleteContentUsingFileWriter_thenEmptyFile() throws IOException {
|
||||
new FileWriter(FILE_PATH, false).close();
|
||||
|
||||
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingFile_whenDeleteContentUsingFileOutputStream_thenEmptyFile() throws IOException {
|
||||
new FileOutputStream(FILE_PATH).close();
|
||||
|
||||
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingFile_whenDeleteContentUsingFileUtils_thenEmptyFile() throws IOException {
|
||||
FileUtils.write(new File(FILE_PATH), "", Charset.defaultCharset());
|
||||
|
||||
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingFile_whenDeleteContentUsingNIOFiles_thenEmptyFile() throws IOException {
|
||||
BufferedWriter writer = Files.newBufferedWriter(Paths.get(FILE_PATH));
|
||||
writer.write("");
|
||||
writer.flush();
|
||||
|
||||
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingFile_whenDeleteContentUsingNIOFileChannel_thenEmptyFile() throws IOException {
|
||||
FileChannel.open(Paths.get(FILE_PATH), StandardOpenOption.WRITE).truncate(0).close();
|
||||
|
||||
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingFile_whenDeleteContentUsingGuava_thenEmptyFile() throws IOException {
|
||||
File file = new File(FILE_PATH);
|
||||
byte[] empty = new byte[0];
|
||||
com.google.common.io.Files.write(empty, file);
|
||||
|
||||
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.file;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.files.ListFiles;
|
||||
|
||||
public class ListFilesUnitTest {
|
||||
|
||||
private ListFiles listFiles = new ListFiles();
|
||||
private String DIRECTORY = "src/test/resources/listFilesUnitTestFolder";
|
||||
private static final int DEPTH = 1;
|
||||
private Set<String> EXPECTED_FILE_LIST = new HashSet<String>() {
|
||||
{
|
||||
add("test.xml");
|
||||
add("employee.json");
|
||||
add("students.json");
|
||||
add("country.txt");
|
||||
}
|
||||
};
|
||||
|
||||
@Test
|
||||
public void givenDir_whenUsingJAVAIO_thenListAllFiles() throws IOException {
|
||||
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingJavaIO(DIRECTORY));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDir_whenWalkingTree_thenListAllFiles() throws IOException {
|
||||
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFileWalk(DIRECTORY,DEPTH));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDir_whenWalkingTreeWithVisitor_thenListAllFiles() throws IOException {
|
||||
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFileWalkAndVisitor(DIRECTORY));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDir_whenUsingDirectoryStream_thenListAllFiles() throws IOException {
|
||||
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingDirectoryStream(DIRECTORY));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
package org.baeldung.java.io;
|
||||
|
||||
import com.google.common.io.ByteSource;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
|
||||
import static java.nio.channels.Channels.newChannel;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class InputStreamToByteBufferUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUsingCoreClasses_whenByteArrayInputStreamToAByteBuffer_thenLengthMustMatch() throws IOException {
|
||||
byte[] input = new byte[] { 0, 1, 2 };
|
||||
InputStream initialStream = new ByteArrayInputStream(input);
|
||||
ByteBuffer byteBuffer = ByteBuffer.allocate(3);
|
||||
while (initialStream.available() > 0) {
|
||||
byteBuffer.put((byte) initialStream.read());
|
||||
}
|
||||
|
||||
assertEquals(byteBuffer.position(), input.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava__whenByteArrayInputStreamToAByteBuffer_thenLengthMustMatch() throws IOException {
|
||||
InputStream initialStream = ByteSource
|
||||
.wrap(new byte[] { 0, 1, 2 })
|
||||
.openStream();
|
||||
byte[] targetArray = ByteStreams.toByteArray(initialStream);
|
||||
ByteBuffer bufferByte = ByteBuffer.wrap(targetArray);
|
||||
while (bufferByte.hasRemaining()) {
|
||||
bufferByte.get();
|
||||
}
|
||||
|
||||
assertEquals(bufferByte.position(), targetArray.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIo_whenByteArrayInputStreamToAByteBuffer_thenLengthMustMatch() throws IOException {
|
||||
byte[] input = new byte[] { 0, 1, 2 };
|
||||
InputStream initialStream = new ByteArrayInputStream(input);
|
||||
ByteBuffer byteBuffer = ByteBuffer.allocate(3);
|
||||
ReadableByteChannel channel = newChannel(initialStream);
|
||||
IOUtils.readFully(channel, byteBuffer);
|
||||
|
||||
assertEquals(byteBuffer.position(), input.length);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
John,Doe,38,Comment Data Another line of comment data
|
||||
Jane,"Doe, Jr.",19,"She said ""I'm being quoted"""
|
|
|
@ -0,0 +1 @@
|
|||
This example shows how we can delete the file contents without deleting the file
|
Binary file not shown.
After Width: | Height: | Size: 190 KiB |
|
@ -0,0 +1 @@
|
|||
This is a sample txt file for unit test ListFilesUnitTest
|
|
@ -0,0 +1 @@
|
|||
{}
|
|
@ -0,0 +1 @@
|
|||
{}
|
|
@ -0,0 +1 @@
|
|||
<xml></xml>
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.keyword;
|
||||
|
||||
public class Circle extends Round implements Shape {
|
||||
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.keyword;
|
||||
|
||||
public class Ring extends Round {
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.keyword;
|
||||
|
||||
public class Round {
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.keyword;
|
||||
|
||||
public interface Shape {
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.keyword;
|
||||
|
||||
public class Triangle implements Shape {
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package com.baeldung.keyword.test;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.keyword.Circle;
|
||||
import com.baeldung.keyword.Ring;
|
||||
import com.baeldung.keyword.Round;
|
||||
import com.baeldung.keyword.Shape;
|
||||
import com.baeldung.keyword.Triangle;
|
||||
|
||||
public class InstanceOfUnitTest {
|
||||
|
||||
@Test
|
||||
public void giveWhenInstanceIsCorrect_thenReturnTrue() {
|
||||
Ring ring = new Ring();
|
||||
Assert.assertTrue("ring is instance of Round ", ring instanceof Round);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveWhenObjectIsInstanceOfType_thenReturnTrue() {
|
||||
Circle circle = new Circle();
|
||||
Assert.assertTrue("circle is instance of Circle ", circle instanceof Circle);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void giveWhenInstanceIsOfSubtype_thenReturnTrue() {
|
||||
Circle circle = new Circle();
|
||||
Assert.assertTrue("circle is instance of Round", circle instanceof Round);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveWhenTypeIsInterface_thenReturnTrue() {
|
||||
Circle circle = new Circle();
|
||||
Assert.assertTrue("circle is instance of Shape", circle instanceof Shape);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveWhenTypeIsOfObjectType_thenReturnTrue() {
|
||||
Thread thread = new Thread();
|
||||
Assert.assertTrue("thread is instance of Object", thread instanceof Object);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveWhenInstanceValueIsNull_thenReturnFalse() {
|
||||
Circle circle = null;
|
||||
Assert.assertFalse("circle is instance of Round", circle instanceof Round);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveWhenComparingClassInDiffHierarchy_thenCompilationError() {
|
||||
// Assert.assertFalse("circle is instance of Triangle", circle instanceof Triangle);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.objects;
|
||||
|
||||
public class Car {
|
||||
|
||||
private String type;
|
||||
private String model;
|
||||
private String color;
|
||||
private int speed;
|
||||
|
||||
public Car(String type, String model, String color) {
|
||||
this.type = type;
|
||||
this.model = model;
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public void setColor(String color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public int getSpeed() {
|
||||
return speed;
|
||||
}
|
||||
|
||||
public int increaseSpeed(int increment) {
|
||||
if (increment > 0) {
|
||||
this.speed += increment;
|
||||
} else {
|
||||
System.out.println("Increment can't be negative.");
|
||||
}
|
||||
return this.speed;
|
||||
}
|
||||
|
||||
public int decreaseSpeed(int decrement) {
|
||||
if (decrement > 0 && decrement <= this.speed) {
|
||||
this.speed -= decrement;
|
||||
} else {
|
||||
System.out.println("Decrement can't be negative or greater than current speed.");
|
||||
}
|
||||
return this.speed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Car [type=" + type + ", model=" + model + ", color=" + color + ", speed=" + speed + "]";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package org.baeldung.variable.scope.examples;
|
||||
|
||||
public class BracketScopeExample {
|
||||
|
||||
public void mathOperationExample() {
|
||||
Integer sum = 0;
|
||||
{
|
||||
Integer number = 2;
|
||||
sum = sum + number;
|
||||
}
|
||||
// compiler error, number cannot be solved as a variable
|
||||
// number++;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package org.baeldung.variable.scope.examples;
|
||||
|
||||
public class ClassScopeExample {
|
||||
|
||||
Integer amount = 0;
|
||||
|
||||
public void exampleMethod() {
|
||||
amount++;
|
||||
}
|
||||
|
||||
public void anotherExampleMethod() {
|
||||
Integer anotherAmount = amount + 4;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package org.baeldung.variable.scope.examples;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class LoopScopeExample {
|
||||
|
||||
List<String> listOfNames = Arrays.asList("Joe", "Susan", "Pattrick");
|
||||
|
||||
public void iterationOfNames() {
|
||||
String allNames = "";
|
||||
for (String name : listOfNames) {
|
||||
allNames = allNames + " " + name;
|
||||
}
|
||||
// compiler error, name cannot be resolved to a variable
|
||||
// String lastNameUsed = name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package org.baeldung.variable.scope.examples;
|
||||
|
||||
public class MethodScopeExample {
|
||||
|
||||
public void methodA() {
|
||||
Integer area = 2;
|
||||
}
|
||||
|
||||
public void methodB() {
|
||||
// compiler error, area cannot be resolved to a variable
|
||||
// area = area + 2;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package org.baeldung.variable.scope.examples;
|
||||
|
||||
public class NestedScopesExample {
|
||||
|
||||
String title = "Baeldung";
|
||||
|
||||
public void printTitle() {
|
||||
System.out.println(title);
|
||||
String title = "John Doe";
|
||||
System.out.println(title);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.objects;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CarUnitTest {
|
||||
|
||||
private Car car;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
car = new Car("Ford", "Focus", "red");
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void when_speedIncreased_then_verifySpeed() {
|
||||
car.increaseSpeed(30);
|
||||
assertEquals(30, car.getSpeed());
|
||||
|
||||
car.increaseSpeed(20);
|
||||
assertEquals(50, car.getSpeed());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void when_speedDecreased_then_verifySpeed() {
|
||||
car.increaseSpeed(50);
|
||||
assertEquals(50, car.getSpeed());
|
||||
|
||||
car.decreaseSpeed(30);
|
||||
assertEquals(20, car.getSpeed());
|
||||
|
||||
car.decreaseSpeed(20);
|
||||
assertEquals(0, car.getSpeed());
|
||||
}
|
||||
|
||||
}
|
|
@ -44,8 +44,8 @@
|
|||
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<bouncycastle.version>1.55</bouncycastle.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<bouncycastle.version>1.60</bouncycastle.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
|
||||
<!-- testing -->
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.hashing;
|
||||
|
||||
public class DigestAlgorithms {
|
||||
|
||||
public static final String SHA3_256 = "SHA3-256";
|
||||
public static final String SHA_256 = "SHA-256";
|
||||
public static final String KECCAK_256 = "Keccak-256";
|
||||
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.hashing;
|
||||
|
||||
import org.bouncycastle.jcajce.provider.digest.Keccak;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.Security;
|
||||
|
||||
import static com.baeldung.hashing.DigestAlgorithms.KECCAK_256;
|
||||
import static com.baeldung.hashing.SHACommonUtils.bytesToHex;
|
||||
|
||||
public class Keccak256Hashing {
|
||||
|
||||
public static String hashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
final MessageDigest digest = MessageDigest.getInstance(KECCAK_256);
|
||||
final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return bytesToHex(encodedhash);
|
||||
}
|
||||
|
||||
public static String hashWithBouncyCastle(final String originalString) {
|
||||
Keccak.Digest256 digest256 = new Keccak.Digest256();
|
||||
byte[] hashbytes = digest256.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return new String(Hex.encode(hashbytes));
|
||||
}
|
||||
|
||||
}
|
|
@ -8,15 +8,18 @@ import java.nio.charset.StandardCharsets;
|
|||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import static com.baeldung.hashing.DigestAlgorithms.SHA_256;
|
||||
import static com.baeldung.hashing.SHACommonUtils.bytesToHex;
|
||||
|
||||
public class SHA256Hashing {
|
||||
|
||||
public static String HashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException {
|
||||
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
final MessageDigest digest = MessageDigest.getInstance(SHA_256);
|
||||
final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return bytesToHex(encodedhash);
|
||||
}
|
||||
|
||||
public static String HashWithGuava(final String originalString) {
|
||||
public static String hashWithGuava(final String originalString) {
|
||||
final String sha256hex = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
|
||||
return sha256hex;
|
||||
}
|
||||
|
@ -27,20 +30,10 @@ public class SHA256Hashing {
|
|||
}
|
||||
|
||||
public static String HashWithBouncyCastle(final String originalString) throws NoSuchAlgorithmException {
|
||||
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
final MessageDigest digest = MessageDigest.getInstance(SHA_256);
|
||||
final byte[] hash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
final String sha256hex = new String(Hex.encode(hash));
|
||||
return sha256hex;
|
||||
}
|
||||
|
||||
private static String bytesToHex(byte[] hash) {
|
||||
StringBuffer hexString = new StringBuffer();
|
||||
for (int i = 0; i < hash.length; i++) {
|
||||
String hex = Integer.toHexString(0xff & hash[i]);
|
||||
if (hex.length() == 1)
|
||||
hexString.append('0');
|
||||
hexString.append(hex);
|
||||
}
|
||||
return hexString.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.hashing;
|
||||
|
||||
import com.google.common.hash.Hashing;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.bouncycastle.crypto.digests.SHA3Digest;
|
||||
import org.bouncycastle.jcajce.provider.digest.SHA3;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.Security;
|
||||
|
||||
import static com.baeldung.hashing.DigestAlgorithms.SHA3_256;
|
||||
import static com.baeldung.hashing.SHACommonUtils.bytesToHex;
|
||||
|
||||
public class SHA3Hashing {
|
||||
|
||||
/* works with JDK9+ only */
|
||||
public static String hashWithJavaMessageDigestJDK9(final String originalString) throws NoSuchAlgorithmException {
|
||||
final MessageDigest digest = MessageDigest.getInstance(SHA3_256);
|
||||
final byte[] hashbytes = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return bytesToHex(hashbytes);
|
||||
}
|
||||
|
||||
public static String hashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
final MessageDigest digest = MessageDigest.getInstance(SHA3_256);
|
||||
final byte[] hashbytes = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return bytesToHex(hashbytes);
|
||||
}
|
||||
|
||||
/* works with JDK9+ only */
|
||||
public static String hashWithApacheCommonsJDK9(final String originalString) {
|
||||
return new DigestUtils(SHA3_256).digestAsHex(originalString);
|
||||
}
|
||||
|
||||
public static String hashWithBouncyCastle(final String originalString) {
|
||||
SHA3.Digest256 digest256 = new SHA3.Digest256();
|
||||
byte[] hashbytes = digest256.digest(originalString.getBytes(StandardCharsets.UTF_8));
|
||||
return new String(Hex.encode(hashbytes));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.hashing;
|
||||
|
||||
class SHACommonUtils {
|
||||
|
||||
public static String bytesToHex(byte[] hash) {
|
||||
StringBuffer hexString = new StringBuffer();
|
||||
for (byte h : hash) {
|
||||
String hex = Integer.toHexString(0xff & h);
|
||||
if (hex.length() == 1)
|
||||
hexString.append('0');
|
||||
hexString.append(hex);
|
||||
}
|
||||
return hexString.toString();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.hashing;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Keccak256HashingUnitTest {
|
||||
|
||||
private static String originalValue = "abc123";
|
||||
private static String hashedValue = "719accc61a9cc126830e5906f9d672d06eab6f8597287095a2c55a8b775e7016";
|
||||
|
||||
@Test public void testHashWithJavaMessageDigest() throws Exception {
|
||||
final String currentHashedValue = Keccak256Hashing.hashWithJavaMessageDigest(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
@Test public void testHashWithBouncyCastle() {
|
||||
final String currentHashedValue = Keccak256Hashing.hashWithBouncyCastle(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
}
|
|
@ -12,24 +12,24 @@ public class SHA256HashingUnitTest {
|
|||
@Test
|
||||
public void testHashWithJavaMessageDigest() throws Exception {
|
||||
final String currentHashedValue = SHA256Hashing.HashWithJavaMessageDigest(originalValue);
|
||||
assertEquals(currentHashedValue, hashedValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashWithGuava() throws Exception {
|
||||
final String currentHashedValue = SHA256Hashing.HashWithApacheCommons(originalValue);
|
||||
assertEquals(currentHashedValue, hashedValue);
|
||||
final String currentHashedValue = SHA256Hashing.hashWithGuava(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashWithApacheCommans() throws Exception {
|
||||
final String currentHashedValue = SHA256Hashing.HashWithGuava(originalValue);
|
||||
assertEquals(currentHashedValue, hashedValue);
|
||||
final String currentHashedValue = SHA256Hashing.HashWithApacheCommons(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashWithBouncyCastle() throws Exception {
|
||||
final String currentHashedValue = SHA256Hashing.HashWithBouncyCastle(originalValue);
|
||||
assertEquals(currentHashedValue, hashedValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.hashing;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class SHA3HashingUnitTest {
|
||||
|
||||
private static String originalValue = "abc123";
|
||||
private static String hashedValue = "f58fa3df820114f56e1544354379820cff464c9c41cb3ca0ad0b0843c9bb67ee";
|
||||
|
||||
/* works with JDK9+ only */
|
||||
//@Test
|
||||
public void testHashWithJavaMessageDigestJDK9() throws Exception {
|
||||
final String currentHashedValue = SHA3Hashing.hashWithJavaMessageDigestJDK9(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashWithJavaMessageDigest() throws Exception {
|
||||
final String currentHashedValue = SHA3Hashing.hashWithJavaMessageDigest(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
/* works with JDK9+ only */
|
||||
//@Test
|
||||
public void testHashWithApacheCommonsJDK9() {
|
||||
final String currentHashedValue = SHA3Hashing.hashWithApacheCommonsJDK9(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashWithBouncyCastle() {
|
||||
final String currentHashedValue = SHA3Hashing.hashWithBouncyCastle(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
}
|
|
@ -46,3 +46,4 @@
|
|||
- [Graphs in Java](https://www.baeldung.com/java-graphs)
|
||||
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
|
||||
- [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf)
|
||||
- [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields)
|
||||
|
|
|
@ -13,6 +13,7 @@
|
|||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
|
|
|
@ -0,0 +1,81 @@
|
|||
package com.baeldung.bitwiseoperator.test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class BitwiseOperatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoIntegers_whenAndOperator_thenNewDecimalNumber() {
|
||||
int value1 = 6;
|
||||
int value2 = 5;
|
||||
int result = value1 & value2;
|
||||
assertEquals(4, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoIntegers_whenOrOperator_thenNewDecimalNumber() {
|
||||
int value1 = 6;
|
||||
int value2 = 5;
|
||||
int result = value1 | value2;
|
||||
assertEquals(7, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoIntegers_whenXorOperator_thenNewDecimalNumber() {
|
||||
int value1 = 6;
|
||||
int value2 = 5;
|
||||
int result = value1 ^ value2;
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneInteger_whenNotOperator_thenNewDecimalNumber() {
|
||||
int value1 = 6;
|
||||
int result = ~value1;
|
||||
assertEquals(result, -7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOnePositiveInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() {
|
||||
int value = 12;
|
||||
int rightShift = value >> 2;
|
||||
assertEquals(3, rightShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneNegativeInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() {
|
||||
int value = -12;
|
||||
int rightShift = value >> 2;
|
||||
assertEquals(-3, rightShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOnePositiveInteger_whenLeftShiftOperator_thenNewDecimalNumber() {
|
||||
int value = 12;
|
||||
int leftShift = value << 2;
|
||||
assertEquals(48, leftShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneNegativeInteger_whenLeftShiftOperator_thenNewDecimalNumber() {
|
||||
int value = -12;
|
||||
int leftShift = value << 2;
|
||||
assertEquals(-48, leftShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOnePositiveInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() {
|
||||
int value = 12;
|
||||
int unsignedRightShift = value >>> 2;
|
||||
assertEquals(3, unsignedRightShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneNegativeInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() {
|
||||
int value = -12;
|
||||
int unsignedRightShift = value >>> 2;
|
||||
assertEquals(1073741821, unsignedRightShift);
|
||||
}
|
||||
|
||||
}
|
|
@ -3,19 +3,16 @@ package com.baeldung.curltojava;
|
|||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaCurlExamplesUnitTest {
|
||||
|
||||
public class JavaCurlExamplesLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenCommand_whenCalled_thenProduceZeroExitCode() throws IOException {
|
||||
String command = "curl --location --request GET \"https://postman-echo.com/get?foo1=bar1&foo2=bar2\"";
|
||||
ProcessBuilder processBuilder = new ProcessBuilder(command.replaceAll("\"", "").split(" "));
|
||||
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
|
||||
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
|
||||
processBuilder.directory(new File("/home/"));
|
||||
Process process = processBuilder.start();
|
||||
InputStream inputStream = process.getInputStream();
|
||||
|
@ -28,8 +25,8 @@ public class JavaCurlExamplesUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenNewCommands_whenCalled_thenCheckIfIsAlive() throws IOException {
|
||||
String command = "curl --location --request GET \"https://postman-echo.com/get?foo1=bar1&foo2=bar2\"";
|
||||
ProcessBuilder processBuilder = new ProcessBuilder(command.replaceAll("\"", "").split(" "));
|
||||
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
|
||||
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
|
||||
processBuilder.directory(new File("/home/"));
|
||||
Process process = processBuilder.start();
|
||||
|
||||
|
@ -40,16 +37,14 @@ public class JavaCurlExamplesUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestGet_thenReturnSuccessResponseCode() throws IOException {
|
||||
String url = "https://postman-echo.com/get?foo1=bar1&foo2=bar2";
|
||||
URL urlObj = new URL(url);
|
||||
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
|
||||
connection.setDoOutput(true);
|
||||
connection.setInstanceFollowRedirects(false);
|
||||
connection.setRequestMethod("GET");
|
||||
connection.connect();
|
||||
public void whenRequestPost_thenCheckIfReturnContent() throws IOException {
|
||||
String command = "curl -X POST https://postman-echo.com/post --data foo1=bar1&foo2=bar2";
|
||||
Process process = Runtime.getRuntime().exec(command);
|
||||
|
||||
Assert.assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
|
||||
// Get the POST result
|
||||
String content = JavaCurlExamples.inputStreamToString(process.getInputStream());
|
||||
|
||||
Assert.assertTrue(null != content && !content.isEmpty());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.leapyear;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Year;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LeapYearUnitTest {
|
||||
|
||||
//Before Java8
|
||||
@Test
|
||||
public void testLeapYearUsingGregorianCalendar () {
|
||||
Assert.assertFalse(new GregorianCalendar().isLeapYear(2018));
|
||||
}
|
||||
|
||||
//Java 8 and above
|
||||
@Test
|
||||
public void testLeapYearUsingJavaTimeYear () {
|
||||
Assert.assertTrue(Year.isLeap(2012));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBCYearUsingJavaTimeYear () {
|
||||
Assert.assertTrue(Year.isLeap(-4));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrongLeapYearUsingJavaTimeYear () {
|
||||
Assert.assertFalse(Year.isLeap(2018));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLeapYearInDateUsingJavaTimeYear () {
|
||||
LocalDate date = LocalDate.parse("2020-01-05", DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
Assert.assertTrue(Year.from(date).isLeap());
|
||||
}
|
||||
|
||||
}
|
|
@ -72,17 +72,6 @@
|
|||
<artifactId>injekt-core</artifactId>
|
||||
<version>1.16.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>uy.kohesive.kovert</groupId>
|
||||
<artifactId>kovert-vertx</artifactId>
|
||||
<version>[1.5.0,1.6.0)</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>nl.komponents.kovenant</groupId>
|
||||
<artifactId>kovenant</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue