Merge branch 'master' of https://github.com/sanketmeghani/tutorials into sanketmeghani-master
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
public class GetCurrentDate {
|
||||
|
||||
public static void main(String args[]) {
|
||||
|
||||
LocalDate localDate = LocalDate.now();
|
||||
System.out.println("Today's date is: " + localDate);
|
||||
|
||||
localDate = LocalDate.now(ZoneId.of("GMT+02:30"));
|
||||
System.out.println("Current date in GMT +02:30 timezone: " + localDate);
|
||||
|
||||
LocalDateTime localDateTime = LocalDateTime.now();
|
||||
System.out.println("Today's date is: " + localDateTime.toLocalDate());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
public class GetCurrentTime {
|
||||
|
||||
public static void main(String args[]) {
|
||||
|
||||
LocalTime localTime = LocalTime.now();
|
||||
System.out.println("Current time is: " + localTime);
|
||||
|
||||
localTime = LocalTime.now(ZoneId.of("GMT+02:30"));
|
||||
System.out.println("Current time in GMT +02:30 timezone: " + localTime);
|
||||
|
||||
LocalDateTime localDateTime = LocalDateTime.now();
|
||||
System.out.println("Current time is: " + localDateTime.toLocalTime());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class GetCurrentTimestamp {
|
||||
|
||||
public static void main(String args[]) {
|
||||
|
||||
Instant instant = Instant.now();
|
||||
System.out.println("Current timestamp is: " + instant.toEpochMilli());
|
||||
|
||||
System.out.println("Number of seconds: " + instant.getEpochSecond());
|
||||
}
|
||||
}
|
||||
@@ -19,9 +19,9 @@ public class ArrayListTest {
|
||||
@Before
|
||||
public void setUp() {
|
||||
List<String> xs = LongStream.range(0, 16)
|
||||
.boxed()
|
||||
.map(Long::toHexString)
|
||||
.collect(toCollection(ArrayList::new));
|
||||
.boxed()
|
||||
.map(Long::toHexString)
|
||||
.collect(toCollection(ArrayList::new));
|
||||
stringsToSearch = new ArrayList<>(xs);
|
||||
stringsToSearch.addAll(xs);
|
||||
}
|
||||
@@ -35,7 +35,7 @@ public class ArrayListTest {
|
||||
@Test
|
||||
public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() {
|
||||
Collection<Integer> numbers =
|
||||
IntStream.range(0, 10).boxed().collect(toSet());
|
||||
IntStream.range(0, 10).boxed().collect(toSet());
|
||||
|
||||
List<Integer> xs = new ArrayList<>(numbers);
|
||||
assertEquals(10, xs.size());
|
||||
@@ -57,7 +57,7 @@ public class ArrayListTest {
|
||||
public void givenCollection_whenAddToArrayList_thenIsAdded() {
|
||||
List<Long> xs = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
|
||||
LongStream.range(4, 10).boxed()
|
||||
.collect(collectingAndThen(toList(), ys -> xs.addAll(0, ys)));
|
||||
.collect(collectingAndThen(toCollection(ArrayList::new), ys -> xs.addAll(0, ys)));
|
||||
|
||||
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(xs));
|
||||
}
|
||||
@@ -89,9 +89,9 @@ public class ArrayListTest {
|
||||
Set<String> matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9"));
|
||||
|
||||
List<String> result = stringsToSearch
|
||||
.stream()
|
||||
.filter(matchingStrings::contains)
|
||||
.collect(toCollection(ArrayList::new));
|
||||
.stream()
|
||||
.filter(matchingStrings::contains)
|
||||
.collect(toCollection(ArrayList::new));
|
||||
|
||||
assertEquals(6, result.size());
|
||||
}
|
||||
@@ -132,7 +132,7 @@ public class ArrayListTest {
|
||||
@Test
|
||||
public void givenCondition_whenIterateArrayList_thenRemoveAllElementsSatisfyingCondition() {
|
||||
Set<String> matchingStrings
|
||||
= Sets.newHashSet("a", "b", "c", "d", "e", "f");
|
||||
= Sets.newHashSet("a", "b", "c", "d", "e", "f");
|
||||
|
||||
Iterator<String> it = stringsToSearch.iterator();
|
||||
while (it.hasNext()) {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
=========
|
||||
|
||||
## ElasticSearch
|
||||
|
||||
### Relevant Articles:
|
||||
- [A Guide to ElasticSearch](http://www.baeldung.com/????????)
|
||||
@@ -0,0 +1,35 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>elasticsearch</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>elasticsearch</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.elasticsearch</groupId>
|
||||
<artifactId>elasticsearch</artifactId>
|
||||
<version>2.3.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>1.2.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.elasticsearch;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class Person {
|
||||
|
||||
private int age;
|
||||
|
||||
private String fullName;
|
||||
|
||||
private Date dateOfBirth;
|
||||
|
||||
public Person() {
|
||||
|
||||
}
|
||||
|
||||
public Person(int age, String fullName, Date dateOfBirth) {
|
||||
super();
|
||||
this.age = age;
|
||||
this.fullName = fullName;
|
||||
this.dateOfBirth = dateOfBirth;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getFullName() {
|
||||
return fullName;
|
||||
}
|
||||
|
||||
public void setFullName(String fullName) {
|
||||
this.fullName = fullName;
|
||||
}
|
||||
|
||||
public Date getDateOfBirth() {
|
||||
return dateOfBirth;
|
||||
}
|
||||
|
||||
public void setDateOfBirth(Date dateOfBirth) {
|
||||
this.dateOfBirth = dateOfBirth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Person [age=" + age + ", fullName=" + fullName + ", dateOfBirth=" + dateOfBirth + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.baeldung.elasticsearch;
|
||||
|
||||
import static org.elasticsearch.node.NodeBuilder.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.elasticsearch.action.delete.DeleteResponse;
|
||||
import org.elasticsearch.action.index.IndexResponse;
|
||||
import org.elasticsearch.action.search.SearchResponse;
|
||||
import org.elasticsearch.action.search.SearchType;
|
||||
import org.elasticsearch.client.Client;
|
||||
import org.elasticsearch.common.xcontent.XContentBuilder;
|
||||
import org.elasticsearch.common.xcontent.XContentFactory;
|
||||
import org.elasticsearch.index.query.QueryBuilders;
|
||||
import org.elasticsearch.node.Node;
|
||||
import org.elasticsearch.search.SearchHit;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
|
||||
public class ElasticSearchUnitTests {
|
||||
private List<Person> listOfPersons = new ArrayList<Person>();
|
||||
String jsonString = null;
|
||||
Client client = null;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
Person person1 = new Person(10, "John Doe", new Date());
|
||||
Person person2 = new Person(25, "Janette Doe", new Date());
|
||||
listOfPersons.add(person1);
|
||||
listOfPersons.add(person2);
|
||||
jsonString = JSON.toJSONString(listOfPersons);
|
||||
Node node = nodeBuilder().clusterName("elasticsearch").client(true).node();
|
||||
client = node.client();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJsonString_whenJavaObject_thenIndexDocument() {
|
||||
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
|
||||
IndexResponse response = client.prepareIndex("people", "Doe")
|
||||
.setSource(jsonObject).get();
|
||||
String index = response.getIndex();
|
||||
String type = response.getType();
|
||||
assertTrue(response.isCreated());
|
||||
assertEquals(index, "people");
|
||||
assertEquals(type, "Doe");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDocumentId_whenJavaObject_thenDeleteDocument() {
|
||||
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
|
||||
IndexResponse response = client.prepareIndex("people", "Doe")
|
||||
.setSource(jsonObject).get();
|
||||
String id = response.getId();
|
||||
DeleteResponse deleteResponse = client.prepareDelete("people", "Doe", id).get();
|
||||
assertTrue(deleteResponse.isFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSearchRequest_whenMatchAll_thenReturnAllResults() {
|
||||
SearchResponse response = client.prepareSearch().execute().actionGet();
|
||||
SearchHit[] searchHits = response.getHits().getHits();
|
||||
List<Person> results = new ArrayList<Person>();
|
||||
for (SearchHit hit : searchHits) {
|
||||
String sourceAsString = hit.getSourceAsString();
|
||||
Person person = JSON.parseObject(sourceAsString, Person.class);
|
||||
results.add(person);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSearchParamters_thenReturnResults() {
|
||||
boolean isExecutedSuccessfully = true;
|
||||
SearchResponse response = client.prepareSearch()
|
||||
.setTypes()
|
||||
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
|
||||
.setPostFilter(QueryBuilders.rangeQuery("age").from(5).to(15))
|
||||
.setFrom(0).setSize(60).setExplain(true)
|
||||
.execute()
|
||||
.actionGet();
|
||||
|
||||
SearchResponse response2 = client.prepareSearch()
|
||||
.setTypes()
|
||||
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
|
||||
.setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette"))
|
||||
.setFrom(0).setSize(60).setExplain(true)
|
||||
.execute()
|
||||
.actionGet();
|
||||
|
||||
SearchResponse response3 = client.prepareSearch()
|
||||
.setTypes()
|
||||
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
|
||||
.setPostFilter(QueryBuilders.matchQuery("John", "Name*"))
|
||||
.setFrom(0).setSize(60).setExplain(true)
|
||||
.execute()
|
||||
.actionGet();
|
||||
try {
|
||||
response2.getHits();
|
||||
response3.getHits();
|
||||
SearchHit[] searchHits = response.getHits().getHits();
|
||||
List<Person> results = new ArrayList<Person>();
|
||||
for (SearchHit hit : searchHits) {
|
||||
String sourceAsString = hit.getSourceAsString();
|
||||
Person person = JSON.parseObject(sourceAsString, Person.class);
|
||||
results.add(person);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
isExecutedSuccessfully = false;
|
||||
}
|
||||
assertTrue(isExecutedSuccessfully);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
|
||||
XContentBuilder builder = XContentFactory.jsonBuilder()
|
||||
.startObject()
|
||||
.field("fullName", "Test")
|
||||
.field("salary", "11500")
|
||||
.field("age", "10")
|
||||
.endObject();
|
||||
IndexResponse response = client.prepareIndex("people", "Doe")
|
||||
.setSource(builder).get();
|
||||
assertTrue(response.isCreated());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
## Feign Hypermedia Client ##
|
||||
|
||||
This is the implementation of a [spring-hypermedia-api][1] client using Feign.
|
||||
|
||||
[1]: https://github.com/eugenp/spring-hypermedia-api
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung.feign</groupId>
|
||||
<artifactId>feign-client</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-core</artifactId>
|
||||
<version>9.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-okhttp</artifactId>
|
||||
<version>9.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-gson</artifactId>
|
||||
<version>9.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-slf4j</artifactId>
|
||||
<version>9.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>1.7.21</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.6.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-slf4j-impl</artifactId>
|
||||
<version>2.6.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.16.10</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.19.1</version>
|
||||
<configuration>
|
||||
<skipTests>true</skipTests>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>1.4.0.RELEASE</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.feign;
|
||||
|
||||
import com.baeldung.feign.clients.BookClient;
|
||||
import feign.Feign;
|
||||
import feign.Logger;
|
||||
import feign.gson.GsonDecoder;
|
||||
import feign.gson.GsonEncoder;
|
||||
import feign.okhttp.OkHttpClient;
|
||||
import feign.slf4j.Slf4jLogger;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class BookControllerFeignClientBuilder {
|
||||
private BookClient bookClient = createClient(BookClient.class,
|
||||
"http://localhost:8081/api/books");
|
||||
|
||||
private static <T> T createClient(Class<T> type, String uri) {
|
||||
return Feign.builder()
|
||||
.client(new OkHttpClient())
|
||||
.encoder(new GsonEncoder())
|
||||
.decoder(new GsonDecoder())
|
||||
.logger(new Slf4jLogger(type))
|
||||
.logLevel(Logger.Level.FULL)
|
||||
.target(type, uri);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.feign.clients;
|
||||
|
||||
import com.baeldung.feign.models.Book;
|
||||
import com.baeldung.feign.models.BookResource;
|
||||
import feign.Headers;
|
||||
import feign.Param;
|
||||
import feign.RequestLine;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface BookClient {
|
||||
@RequestLine("GET /{isbn}")
|
||||
BookResource findByIsbn(@Param("isbn") String isbn);
|
||||
|
||||
@RequestLine("GET")
|
||||
List<BookResource> findAll();
|
||||
|
||||
@RequestLine("POST")
|
||||
@Headers("Content-Type: application/json")
|
||||
void create(Book book);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.feign.models;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.ToString;
|
||||
|
||||
@Data
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Book {
|
||||
private String isbn;
|
||||
private String author;
|
||||
private String title;
|
||||
private String synopsis;
|
||||
private String language;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.feign.models;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.ToString;
|
||||
|
||||
@Data
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BookResource {
|
||||
private Book book;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
<Appenders>
|
||||
<Console name="Console" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}:%n[+] %msg%n"/>
|
||||
</Console>
|
||||
</Appenders>
|
||||
|
||||
<Loggers>
|
||||
<Root level="debug">
|
||||
<AppenderRef ref="Console"/>
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.feign.clients;
|
||||
|
||||
import com.baeldung.feign.BookControllerFeignClientBuilder;
|
||||
import com.baeldung.feign.models.Book;
|
||||
import com.baeldung.feign.models.BookResource;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@Slf4j
|
||||
@RunWith(JUnit4.class)
|
||||
public class BookClientTest {
|
||||
private BookClient bookClient;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
BookControllerFeignClientBuilder feignClientBuilder = new BookControllerFeignClientBuilder();
|
||||
bookClient = feignClientBuilder.getBookClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBookClient_shouldRunSuccessfully() throws Exception {
|
||||
List<Book> books = bookClient.findAll().stream()
|
||||
.map(BookResource::getBook)
|
||||
.collect(Collectors.toList());
|
||||
assertTrue(books.size() > 2);
|
||||
log.info("{}", books);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBookClient_shouldFindOneBook() throws Exception {
|
||||
Book book = bookClient.findByIsbn("0151072558").getBook();
|
||||
assertThat(book.getAuthor(), containsString("Orwell"));
|
||||
log.info("{}", book);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBookClient_shouldPostBook() throws Exception {
|
||||
String isbn = UUID.randomUUID().toString();
|
||||
Book book = new Book(isbn, "Me", "It's me!", null, null);
|
||||
bookClient.create(book);
|
||||
|
||||
book = bookClient.findByIsbn(isbn).getBook();
|
||||
assertThat(book.getAuthor(), is("Me"));
|
||||
log.info("{}", book);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
logs
|
||||
target
|
||||
/.idea
|
||||
/.idea_modules
|
||||
/.classpath
|
||||
/.project
|
||||
/.settings
|
||||
/RUNNING_PID
|
||||
@@ -0,0 +1,8 @@
|
||||
This software is licensed under the Apache 2 license, quoted below.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project except in compliance with
|
||||
the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
|
||||
language governing permissions and limitations under the License.
|
||||
@@ -0,0 +1,49 @@
|
||||
This is your new Play application
|
||||
=================================
|
||||
|
||||
This file will be packaged with your application when using `activator dist`.
|
||||
|
||||
There are several demonstration files available in this template.
|
||||
|
||||
Controllers
|
||||
===========
|
||||
|
||||
- HomeController.java:
|
||||
|
||||
Shows how to handle simple HTTP requests.
|
||||
|
||||
- AsyncController.java:
|
||||
|
||||
Shows how to do asynchronous programming when handling a request.
|
||||
|
||||
- CountController.java:
|
||||
|
||||
Shows how to inject a component into a controller and use the component when
|
||||
handling requests.
|
||||
|
||||
Components
|
||||
==========
|
||||
|
||||
- Module.java:
|
||||
|
||||
Shows how to use Guice to bind all the components needed by your application.
|
||||
|
||||
- Counter.java:
|
||||
|
||||
An example of a component that contains state, in this case a simple counter.
|
||||
|
||||
- ApplicationTimer.java:
|
||||
|
||||
An example of a component that starts when the application starts and stops
|
||||
when the application stops.
|
||||
|
||||
Filters
|
||||
=======
|
||||
|
||||
- Filters.java:
|
||||
|
||||
Creates the list of HTTP filters used by your application.
|
||||
|
||||
- ExampleFilter.java
|
||||
|
||||
A simple filter that adds a header to every response.
|
||||
@@ -0,0 +1,46 @@
|
||||
import javax.inject.*;
|
||||
import play.*;
|
||||
import play.mvc.EssentialFilter;
|
||||
import play.http.HttpFilters;
|
||||
import play.mvc.*;
|
||||
|
||||
import filters.ExampleFilter;
|
||||
|
||||
/**
|
||||
* This class configures filters that run on every request. This
|
||||
* class is queried by Play to get a list of filters.
|
||||
*
|
||||
* Play will automatically use filters from any class called
|
||||
* <code>Filters</code> that is placed the root package. You can load filters
|
||||
* from a different class by adding a `play.http.filters` setting to
|
||||
* the <code>application.conf</code> configuration file.
|
||||
*/
|
||||
@Singleton
|
||||
public class Filters implements HttpFilters {
|
||||
|
||||
private final Environment env;
|
||||
private final EssentialFilter exampleFilter;
|
||||
|
||||
/**
|
||||
* @param env Basic environment settings for the current application.
|
||||
* @param exampleFilter A demonstration filter that adds a header to
|
||||
*/
|
||||
@Inject
|
||||
public Filters(Environment env, ExampleFilter exampleFilter) {
|
||||
this.env = env;
|
||||
this.exampleFilter = exampleFilter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EssentialFilter[] filters() {
|
||||
// Use the example filter if we're running development mode. If
|
||||
// we're running in production or test mode then don't use any
|
||||
// filters at all.
|
||||
if (env.mode().equals(Mode.DEV)) {
|
||||
return new EssentialFilter[] { exampleFilter };
|
||||
} else {
|
||||
return new EssentialFilter[] {};
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import com.google.inject.AbstractModule;
|
||||
import java.time.Clock;
|
||||
|
||||
import services.ApplicationTimer;
|
||||
import services.AtomicCounter;
|
||||
import services.Counter;
|
||||
|
||||
/**
|
||||
* This class is a Guice module that tells Guice how to bind several
|
||||
* different types. This Guice module is created when the Play
|
||||
* application starts.
|
||||
*
|
||||
* Play will automatically use any class called `Module` that is in
|
||||
* the root package. You can create modules in other locations by
|
||||
* adding `play.modules.enabled` settings to the `application.conf`
|
||||
* configuration file.
|
||||
*/
|
||||
public class Module extends AbstractModule {
|
||||
|
||||
@Override
|
||||
public void configure() {
|
||||
// Use the system clock as the default implementation of Clock
|
||||
bind(Clock.class).toInstance(Clock.systemDefaultZone());
|
||||
// Ask Guice to create an instance of ApplicationTimer when the
|
||||
// application starts.
|
||||
bind(ApplicationTimer.class).asEagerSingleton();
|
||||
// Set AtomicCounter as the implementation for Counter.
|
||||
bind(Counter.class).to(AtomicCounter.class);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package controllers;
|
||||
|
||||
import akka.actor.ActorSystem;
|
||||
import javax.inject.*;
|
||||
import play.*;
|
||||
import play.mvc.*;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import scala.concurrent.duration.Duration;
|
||||
import scala.concurrent.ExecutionContextExecutor;
|
||||
|
||||
/**
|
||||
* This controller contains an action that demonstrates how to write
|
||||
* simple asynchronous code in a controller. It uses a timer to
|
||||
* asynchronously delay sending a response for 1 second.
|
||||
*
|
||||
* @param actorSystem We need the {@link ActorSystem}'s
|
||||
* {@link Scheduler} to run code after a delay.
|
||||
* @param exec We need a Java {@link Executor} to apply the result
|
||||
* of the {@link CompletableFuture} and a Scala
|
||||
* {@link ExecutionContext} so we can use the Akka {@link Scheduler}.
|
||||
* An {@link ExecutionContextExecutor} implements both interfaces.
|
||||
*/
|
||||
@Singleton
|
||||
public class AsyncController extends Controller {
|
||||
|
||||
private final ActorSystem actorSystem;
|
||||
private final ExecutionContextExecutor exec;
|
||||
|
||||
@Inject
|
||||
public AsyncController(ActorSystem actorSystem, ExecutionContextExecutor exec) {
|
||||
this.actorSystem = actorSystem;
|
||||
this.exec = exec;
|
||||
}
|
||||
|
||||
/**
|
||||
* An action that returns a plain text message after a delay
|
||||
* of 1 second.
|
||||
*
|
||||
* The configuration in the <code>routes</code> file means that this method
|
||||
* will be called when the application receives a <code>GET</code> request with
|
||||
* a path of <code>/message</code>.
|
||||
*/
|
||||
public CompletionStage<Result> message() {
|
||||
return getFutureMessage(1, TimeUnit.SECONDS).thenApplyAsync(Results::ok, exec);
|
||||
}
|
||||
|
||||
private CompletionStage<String> getFutureMessage(long time, TimeUnit timeUnit) {
|
||||
CompletableFuture<String> future = new CompletableFuture<>();
|
||||
actorSystem.scheduler().scheduleOnce(
|
||||
Duration.create(time, timeUnit),
|
||||
() -> future.complete("Hi!"),
|
||||
exec
|
||||
);
|
||||
return future;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package controllers;
|
||||
|
||||
import javax.inject.*;
|
||||
import play.*;
|
||||
import play.mvc.*;
|
||||
|
||||
import services.Counter;
|
||||
|
||||
/**
|
||||
* This controller demonstrates how to use dependency injection to
|
||||
* bind a component into a controller class. The class contains an
|
||||
* action that shows an incrementing count to users. The {@link Counter}
|
||||
* object is injected by the Guice dependency injection system.
|
||||
*/
|
||||
@Singleton
|
||||
public class CountController extends Controller {
|
||||
|
||||
private final Counter counter;
|
||||
|
||||
@Inject
|
||||
public CountController(Counter counter) {
|
||||
this.counter = counter;
|
||||
}
|
||||
|
||||
/**
|
||||
* An action that responds with the {@link Counter}'s current
|
||||
* count. The result is plain text. This action is mapped to
|
||||
* <code>GET</code> requests with a path of <code>/count</code>
|
||||
* requests by an entry in the <code>routes</code> config file.
|
||||
*/
|
||||
public Result count() {
|
||||
return ok(Integer.toString(counter.nextCount()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package controllers;
|
||||
|
||||
import play.mvc.*;
|
||||
|
||||
import views.html.*;
|
||||
|
||||
/**
|
||||
* This controller contains an action to handle HTTP requests
|
||||
* to the application's home page.
|
||||
*/
|
||||
public class HomeController extends Controller {
|
||||
|
||||
/**
|
||||
* An action that renders an HTML page with a welcome message.
|
||||
* The configuration in the <code>routes</code> file means that
|
||||
* this method will be called when the application receives a
|
||||
* <code>GET</code> request with a path of <code>/</code>.
|
||||
*/
|
||||
public Result index() {
|
||||
return ok(index.render("Your new application is ready."));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package controllers;
|
||||
import models.*;
|
||||
import util.*;
|
||||
import play.mvc.*;
|
||||
import play.libs.Json;
|
||||
import play.libs.Json.*;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.util.List;
|
||||
|
||||
public class StudentController extends Controller {
|
||||
public Result create() {
|
||||
JsonNode json = request().body().asJson();
|
||||
if(json == null)
|
||||
return badRequest(Util.createResponse("Expecting Json data",false));
|
||||
Student student=StudentStore.getInstance().addStudent((Student)Json.fromJson(json,Student.class));
|
||||
JsonNode jsonObject=Json.toJson(student);
|
||||
return created(Util.createResponse(jsonObject,true));
|
||||
}
|
||||
public Result update() {
|
||||
JsonNode json = request().body().asJson();
|
||||
if(json == null)
|
||||
return badRequest(Util.createResponse("Expecting Json data",false));
|
||||
Student student=StudentStore.getInstance().updateStudent((Student)Json.fromJson(json,Student.class));
|
||||
if(student==null){
|
||||
return notFound(Util.createResponse("Student not found",false));
|
||||
}
|
||||
|
||||
JsonNode jsonObject=Json.toJson(student);
|
||||
return ok(Util.createResponse(jsonObject,true));
|
||||
}
|
||||
public Result retrieve(int id) {
|
||||
Student student=StudentStore.getInstance().getStudent(id);
|
||||
if(student==null){
|
||||
return notFound(Util.createResponse("Student with id:"+id+" not found",false));
|
||||
}
|
||||
JsonNode jsonObjects=Json.toJson(student);
|
||||
return ok(Util.createResponse(jsonObjects,true));
|
||||
}
|
||||
public Result listStudents() {
|
||||
List<Student> result=StudentStore.getInstance().getAllStudents();
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
JsonNode jsonData=mapper.convertValue(result, JsonNode.class);
|
||||
return ok(Util.createResponse(jsonData,true));
|
||||
|
||||
}
|
||||
public Result delete(int id) {
|
||||
boolean status=StudentStore.getInstance().deleteStudent(id);
|
||||
if(!status){
|
||||
return notFound(Util.createResponse("Student with id:"+id+" not found",false));
|
||||
}
|
||||
return ok(Util.createResponse("Student with id:"+id+" deleted",true));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package filters;
|
||||
|
||||
import akka.stream.Materializer;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Function;
|
||||
import javax.inject.*;
|
||||
import play.mvc.*;
|
||||
import play.mvc.Http.RequestHeader;
|
||||
|
||||
|
||||
/**
|
||||
* This is a simple filter that adds a header to all requests. It's
|
||||
* added to the application's list of filters by the
|
||||
* {@link Filters} class.
|
||||
*/
|
||||
@Singleton
|
||||
public class ExampleFilter extends Filter {
|
||||
|
||||
private final Executor exec;
|
||||
|
||||
/**
|
||||
* @param mat This object is needed to handle streaming of requests
|
||||
* and responses.
|
||||
* @param exec This class is needed to execute code asynchronously.
|
||||
* It is used below by the <code>thenAsyncApply</code> method.
|
||||
*/
|
||||
@Inject
|
||||
public ExampleFilter(Materializer mat, Executor exec) {
|
||||
super(mat);
|
||||
this.exec = exec;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletionStage<Result> apply(
|
||||
Function<RequestHeader, CompletionStage<Result>> next,
|
||||
RequestHeader requestHeader) {
|
||||
|
||||
return next.apply(requestHeader).thenApplyAsync(
|
||||
result -> result.withHeader("X-ExampleFilter", "foo"),
|
||||
exec
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package models;
|
||||
public class Student {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private int age;
|
||||
private int id;
|
||||
public Student(){}
|
||||
public Student(String firstName, String lastName, int age) {
|
||||
super();
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package models;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class StudentStore {
|
||||
private static StudentStore instance;
|
||||
private Map<Integer, Student> students = new HashMap<>();
|
||||
|
||||
public static StudentStore getInstance() {
|
||||
if (instance == null)
|
||||
instance = new StudentStore();
|
||||
return instance;
|
||||
}
|
||||
|
||||
public Student addStudent(Student student) {
|
||||
int id = students.size() + 1;
|
||||
student.setId(id);
|
||||
students.put(id, student);
|
||||
return student;
|
||||
}
|
||||
|
||||
public Student getStudent(int id) {
|
||||
if (students.containsKey(id))
|
||||
return students.get(id);
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<Student> getAllStudents() {
|
||||
return new ArrayList<Student>(students.values());
|
||||
}
|
||||
|
||||
public Student updateStudent(Student student) {
|
||||
int id=student.getId();
|
||||
if (students.containsKey(id)) {
|
||||
student.setId(id);
|
||||
students.put(id, student);
|
||||
return student;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean deleteStudent(int id) {
|
||||
|
||||
if (!students.containsKey(id))
|
||||
return false;
|
||||
students.remove(id);
|
||||
return true;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package services;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.inject.*;
|
||||
import play.Logger;
|
||||
import play.inject.ApplicationLifecycle;
|
||||
|
||||
/**
|
||||
* This class demonstrates how to run code when the
|
||||
* application starts and stops. It starts a timer when the
|
||||
* application starts. When the application stops it prints out how
|
||||
* long the application was running for.
|
||||
*
|
||||
* This class is registered for Guice dependency injection in the
|
||||
* {@link Module} class. We want the class to start when the application
|
||||
* starts, so it is registered as an "eager singleton". See the code
|
||||
* in the {@link Module} class to see how this happens.
|
||||
*
|
||||
* This class needs to run code when the server stops. It uses the
|
||||
* application's {@link ApplicationLifecycle} to register a stop hook.
|
||||
*/
|
||||
@Singleton
|
||||
public class ApplicationTimer {
|
||||
|
||||
private final Clock clock;
|
||||
private final ApplicationLifecycle appLifecycle;
|
||||
private final Instant start;
|
||||
|
||||
@Inject
|
||||
public ApplicationTimer(Clock clock, ApplicationLifecycle appLifecycle) {
|
||||
this.clock = clock;
|
||||
this.appLifecycle = appLifecycle;
|
||||
// This code is called when the application starts.
|
||||
start = clock.instant();
|
||||
Logger.info("ApplicationTimer demo: Starting application at " + start);
|
||||
|
||||
// When the application starts, register a stop hook with the
|
||||
// ApplicationLifecycle object. The code inside the stop hook will
|
||||
// be run when the application stops.
|
||||
appLifecycle.addStopHook(() -> {
|
||||
Instant stop = clock.instant();
|
||||
Long runningTime = stop.getEpochSecond() - start.getEpochSecond();
|
||||
Logger.info("ApplicationTimer demo: Stopping application at " + clock.instant() + " after " + runningTime + "s.");
|
||||
return CompletableFuture.completedFuture(null);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package services;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import javax.inject.*;
|
||||
|
||||
/**
|
||||
* This class is a concrete implementation of the {@link Counter} trait.
|
||||
* It is configured for Guice dependency injection in the {@link Module}
|
||||
* class.
|
||||
*
|
||||
* This class has a {@link Singleton} annotation because we need to make
|
||||
* sure we only use one counter per application. Without this
|
||||
* annotation we would get a new instance every time a {@link Counter} is
|
||||
* injected.
|
||||
*/
|
||||
@Singleton
|
||||
public class AtomicCounter implements Counter {
|
||||
|
||||
private final AtomicInteger atomicCounter = new AtomicInteger();
|
||||
|
||||
@Override
|
||||
public int nextCount() {
|
||||
return atomicCounter.getAndIncrement();
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user