library-mv-pt-2
This commit is contained in:
@@ -25,16 +25,13 @@
|
||||
- [Spring Yarg Integration](http://www.baeldung.com/spring-yarg)
|
||||
- [Delete a Directory Recursively in Java](http://www.baeldung.com/java-delete-directory)
|
||||
- [Guide to JDeferred](http://www.baeldung.com/jdeferred)
|
||||
- [Integrating Retrofit with RxJava](http://www.baeldung.com/retrofit-rxjava)
|
||||
- [Introduction to MBassador](http://www.baeldung.com/mbassador)
|
||||
- [Introduction to Retrofit](http://www.baeldung.com/retrofit)
|
||||
- [Using Pairs in Java](http://www.baeldung.com/java-pairs)
|
||||
- [Introduction to Caffeine](http://www.baeldung.com/java-caching-caffeine)
|
||||
- [Introduction to StreamEx](http://www.baeldung.com/streamex)
|
||||
- [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle)
|
||||
- [A Docker Guide for Java](http://www.baeldung.com/docker-java-api)
|
||||
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
|
||||
- [A Guide to Unirest](http://www.baeldung.com/unirest)
|
||||
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
|
||||
- [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy)
|
||||
- [Introduction to jOOL](http://www.baeldung.com/jool)
|
||||
@@ -42,17 +39,12 @@
|
||||
- [Introduction to Atlassian Fugue](http://www.baeldung.com/java-fugue)
|
||||
- [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client)
|
||||
- [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools)
|
||||
- [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices)
|
||||
- [Introduction to JavaPoet](http://www.baeldung.com/java-poet)
|
||||
- [Convert String to Date in Java](http://www.baeldung.com/java-string-to-date)
|
||||
- [Guide to Resilience4j](http://www.baeldung.com/resilience4j)
|
||||
- [Parsing YAML with SnakeYAML](http://www.baeldung.com/java-snake-yaml)
|
||||
- [Guide to JMapper](http://www.baeldung.com/jmapper)
|
||||
- [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once)
|
||||
- [An Introduction to SuanShu](https://www.baeldung.com/suanshu)
|
||||
- [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client)
|
||||
- [Introduction to Functional Java](https://www.baeldung.com/java-functional-library)
|
||||
- [Intro to Derive4J](https://www.baeldung.com/derive4j)
|
||||
- [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library)
|
||||
|
||||
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.
|
||||
|
||||
@@ -367,22 +367,7 @@
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Retrofit -->
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>retrofit</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>converter-gson</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>adapter-rxjava</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>logging-interceptor</artifactId>
|
||||
@@ -540,18 +525,9 @@
|
||||
<classifier>test</classifier>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mashape.unirest</groupId>
|
||||
<artifactId>unirest-java</artifactId>
|
||||
<version>${unirest.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- javalin -->
|
||||
<dependency>
|
||||
<groupId>io.javalin</groupId>
|
||||
<artifactId>javalin</artifactId>
|
||||
<version>${javalin.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- Atlassian Fugue -->
|
||||
<dependency>
|
||||
<groupId>io.atlassian.fugue</groupId>
|
||||
@@ -608,24 +584,6 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.yaml</groupId>
|
||||
<artifactId>snakeyaml</artifactId>
|
||||
<version>${snakeyaml.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.numericalmethod</groupId>
|
||||
<artifactId>suanshu</artifactId>
|
||||
<version>${suanshu.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.derive4j</groupId>
|
||||
<artifactId>derive4j</artifactId>
|
||||
<version>${derive4j.version}</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockftpserver</groupId>
|
||||
<artifactId>MockFtpServer</artifactId>
|
||||
@@ -765,8 +723,7 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<suanshu.version>4.0.0</suanshu.version>
|
||||
<snakeyaml.version>1.21</snakeyaml.version>
|
||||
|
||||
<googleclient.version>1.23.0</googleclient.version>
|
||||
<multiverse.version>0.7.0</multiverse.version>
|
||||
<cglib.version>3.2.7</cglib.version>
|
||||
@@ -799,7 +756,7 @@
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
<geotools.version>15.2</geotools.version>
|
||||
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
|
||||
<retrofit.version>2.3.0</retrofit.version>
|
||||
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
|
||||
<protonpack.version>1.15</protonpack.version>
|
||||
@@ -810,7 +767,7 @@
|
||||
<google-sheets.version>v4-rev493-1.21.0</google-sheets.version>
|
||||
<kafka.version>2.0.0</kafka.version>
|
||||
<docker.version>3.0.14</docker.version>
|
||||
<unirest.version>1.4.9</unirest.version>
|
||||
|
||||
<jctools.version>2.1.2</jctools.version>
|
||||
<commons-codec-version>1.10.L001</commons-codec-version>
|
||||
<jets3t-version>0.9.4.0006L</jets3t-version>
|
||||
@@ -842,11 +799,10 @@
|
||||
<jgrapht.version>1.0.1</jgrapht.version>
|
||||
<bouncycastle.version>1.58</bouncycastle.version>
|
||||
<jersey.version>1.19.4</jersey.version>
|
||||
<javalin.version>1.6.0</javalin.version>
|
||||
|
||||
<fugue.version>4.5.1</fugue.version>
|
||||
<maven-bundle-plugin.version>3.3.0</maven-bundle-plugin.version>
|
||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
<derive4j.version>1.1.0</derive4j.version>
|
||||
<mockftpserver.version>2.7.1</mockftpserver.version>
|
||||
<commons-net.version>3.6</commons-net.version>
|
||||
<reflections.version>0.9.11</reflections.version>
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.derive4j.adt;
|
||||
|
||||
import org.derive4j.Data;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
@Data
|
||||
interface Either<A,B>{
|
||||
<X> X match(Function<A, X> left, Function<B, X> right);
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.baeldung.derive4j.lazy;
|
||||
|
||||
import org.derive4j.Data;
|
||||
import org.derive4j.Derive;
|
||||
import org.derive4j.Make;
|
||||
|
||||
@Data(value = @Derive(
|
||||
inClass = "{ClassName}Impl",
|
||||
make = {Make.lazyConstructor, Make.constructors, Make.getters}
|
||||
))
|
||||
public interface LazyRequest {
|
||||
interface Cases<R>{
|
||||
R GET(String path);
|
||||
R POST(String path, String body);
|
||||
R PUT(String path, String body);
|
||||
R DELETE(String path);
|
||||
}
|
||||
|
||||
<R> R match(LazyRequest.Cases<R> method);
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.derive4j.pattern;
|
||||
|
||||
import org.derive4j.Data;
|
||||
|
||||
@Data
|
||||
interface HTTPRequest {
|
||||
interface Cases<R>{
|
||||
R GET(String path);
|
||||
R POST(String path, String body);
|
||||
R PUT(String path, String body);
|
||||
R DELETE(String path);
|
||||
}
|
||||
|
||||
<R> R match(Cases<R> method);
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.derive4j.pattern;
|
||||
|
||||
public class HTTPResponse {
|
||||
private int statusCode;
|
||||
private String responseBody;
|
||||
|
||||
public int getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
public String getResponseBody() {
|
||||
return responseBody;
|
||||
}
|
||||
|
||||
public HTTPResponse(int statusCode, String responseBody) {
|
||||
this.statusCode = statusCode;
|
||||
this.responseBody = responseBody;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.baeldung.derive4j.pattern;
|
||||
|
||||
|
||||
public class HTTPServer {
|
||||
public static String GET_RESPONSE_BODY = "Success!";
|
||||
public static String PUT_RESPONSE_BODY = "Resource Created!";
|
||||
public static String POST_RESPONSE_BODY = "Resource Updated!";
|
||||
public static String DELETE_RESPONSE_BODY = "Resource Deleted!";
|
||||
|
||||
public HTTPResponse acceptRequest(HTTPRequest request) {
|
||||
return HTTPRequests.caseOf(request)
|
||||
.GET((path) -> new HTTPResponse(200, GET_RESPONSE_BODY))
|
||||
.POST((path,body) -> new HTTPResponse(201, POST_RESPONSE_BODY))
|
||||
.PUT((path,body) -> new HTTPResponse(200, PUT_RESPONSE_BODY))
|
||||
.DELETE(path -> new HTTPResponse(200, DELETE_RESPONSE_BODY));
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.javalin;
|
||||
|
||||
import com.baeldung.javalin.User.UserController;
|
||||
import io.javalin.Javalin;
|
||||
|
||||
public class JavalinApp {
|
||||
public static void main(String[] args) {
|
||||
Javalin app = Javalin.create()
|
||||
.port(7000)
|
||||
.start();
|
||||
|
||||
app.get("/hello", ctx -> ctx.html("Hello, Javalin!"));
|
||||
app.get("/users", UserController.fetchAllUsernames);
|
||||
app.get("/users/:id", UserController.fetchById);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.javalin.User;
|
||||
|
||||
public class User {
|
||||
public final int id;
|
||||
public final String name;
|
||||
|
||||
public User(int id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.baeldung.javalin.User;
|
||||
|
||||
import io.javalin.Handler;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class UserController {
|
||||
public static Handler fetchAllUsernames = ctx -> {
|
||||
UserDao dao = UserDao.instance();
|
||||
Iterable<String> allUsers = dao.getAllUsernames();
|
||||
ctx.json(allUsers);
|
||||
};
|
||||
|
||||
public static Handler fetchById = ctx -> {
|
||||
int id = Integer.parseInt(Objects.requireNonNull(ctx.param("id")));
|
||||
UserDao dao = UserDao.instance();
|
||||
User user = dao.getUserById(id).get();
|
||||
if (user == null) {
|
||||
ctx.html("Not Found");
|
||||
} else {
|
||||
ctx.json(user);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package com.baeldung.javalin.User;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
class UserDao {
|
||||
|
||||
private final List<User> users = Arrays.asList(
|
||||
new User(0, "Steve Rogers"),
|
||||
new User(1, "Tony Stark"),
|
||||
new User(2, "Carol Danvers")
|
||||
);
|
||||
|
||||
private static UserDao userDao = null;
|
||||
|
||||
private UserDao() {
|
||||
}
|
||||
|
||||
static UserDao instance() {
|
||||
if (userDao == null) {
|
||||
userDao = new UserDao();
|
||||
}
|
||||
return userDao;
|
||||
}
|
||||
|
||||
Optional<User> getUserById(int id) { return users.stream().filter(u -> u.id == id).findFirst(); }
|
||||
|
||||
Iterable<String> getAllUsernames() {
|
||||
return users.stream().map(user -> user.name).collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.retrofit.basic;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.retrofit.models.Contributor;
|
||||
import com.baeldung.retrofit.models.Repository;
|
||||
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.Path;
|
||||
|
||||
public interface GitHubBasicApi {
|
||||
|
||||
/**
|
||||
* List GitHub repositories of user
|
||||
* @param user GitHub Account
|
||||
* @return GitHub repositories
|
||||
*/
|
||||
@GET("users/{user}/repos")
|
||||
Call<List<Repository>> listRepos(@Path("user") String user);
|
||||
|
||||
/**
|
||||
* List Contributors of a GitHub Repository
|
||||
* @param user GitHub Account
|
||||
* @param repo GitHub Repository
|
||||
* @return GitHub Repository Contributors
|
||||
*/
|
||||
@GET("repos/{user}/{repo}/contributors")
|
||||
Call<List<Contributor>> listRepoContributors(@Path("user") String user, @Path("repo") String repo);
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.retrofit.basic;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
public class GitHubBasicApp {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
String userName = "eugenp";
|
||||
List<String> topContributors = new GitHubBasicService().getTopContributors(userName);
|
||||
topContributors.forEach(System.out::println);
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.retrofit.basic;
|
||||
|
||||
import com.baeldung.retrofit.models.Contributor;
|
||||
import com.baeldung.retrofit.models.Repository;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
class GitHubBasicService {
|
||||
|
||||
private GitHubBasicApi gitHubApi;
|
||||
|
||||
GitHubBasicService() {
|
||||
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).build();
|
||||
|
||||
gitHubApi = retrofit.create(GitHubBasicApi.class);
|
||||
}
|
||||
|
||||
List<String> getTopContributors(String userName) throws IOException {
|
||||
List<Repository> repos = gitHubApi.listRepos(userName).execute().body();
|
||||
|
||||
repos = repos != null ? repos : Collections.emptyList();
|
||||
|
||||
return repos.stream().flatMap(repo -> getContributors(userName, repo)).sorted((a, b) -> b.getContributions() - a.getContributions()).map(Contributor::getName).distinct().sorted().collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private Stream<Contributor> getContributors(String userName, Repository repo) {
|
||||
List<Contributor> contributors = null;
|
||||
try {
|
||||
contributors = gitHubApi.listRepoContributors(userName, repo.getName()).execute().body();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
contributors = contributors != null ? contributors : Collections.emptyList();
|
||||
|
||||
return contributors.stream().filter(c -> c.getContributions() > 100);
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package com.baeldung.retrofit.models;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
|
||||
public class Contributor {
|
||||
|
||||
@SerializedName("login")
|
||||
private String name;
|
||||
|
||||
private Integer contributions;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getContributions() {
|
||||
return contributions;
|
||||
}
|
||||
|
||||
public void setContributions(Integer contributions) {
|
||||
this.contributions = contributions;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Contributer [name=" + name + ", contributions=" + contributions + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package com.baeldung.retrofit.models;
|
||||
|
||||
public class Repository {
|
||||
|
||||
private String name;
|
||||
|
||||
private String description;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Repository [name=" + name + ", description=" + description + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.retrofit.rx;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.retrofit.models.Contributor;
|
||||
import com.baeldung.retrofit.models.Repository;
|
||||
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.Path;
|
||||
import rx.Observable;
|
||||
|
||||
public interface GitHubRxApi {
|
||||
|
||||
/**
|
||||
* List GitHub repositories of user
|
||||
* @param user GitHub Account
|
||||
* @return GitHub repositories
|
||||
*/
|
||||
@GET("users/{user}/repos")
|
||||
Observable<List<Repository>> listRepos(@Path("user") String user);
|
||||
|
||||
/**
|
||||
* List Contributors of a GitHub Repository
|
||||
* @param user GitHub Account
|
||||
* @param repo GitHub Repository
|
||||
* @return GitHub Repository Contributors
|
||||
*/
|
||||
@GET("repos/{user}/{repo}/contributors")
|
||||
Observable<List<Contributor>> listRepoContributors(@Path("user") String user, @Path("repo") String repo);
|
||||
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.retrofit.rx;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class GitHubRxApp {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
String userName = "eugenp";
|
||||
new GitHubRxService().getTopContributors(userName).subscribe(System.out::println);
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.retrofit.rx;
|
||||
|
||||
import com.baeldung.retrofit.models.Contributor;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
import rx.Observable;
|
||||
|
||||
class GitHubRxService {
|
||||
|
||||
private GitHubRxApi gitHubApi;
|
||||
|
||||
GitHubRxService() {
|
||||
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
|
||||
|
||||
gitHubApi = retrofit.create(GitHubRxApi.class);
|
||||
}
|
||||
|
||||
Observable<String> getTopContributors(String userName) {
|
||||
return gitHubApi.listRepos(userName).flatMapIterable(x -> x).flatMap(repo -> gitHubApi.listRepoContributors(userName, repo.getName())).flatMapIterable(x -> x).filter(c -> c.getContributions() > 100)
|
||||
.sorted((a, b) -> b.getContributions() - a.getContributions()).map(Contributor::getName).distinct();
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package com.baeldung.retrofitguide;
|
||||
|
||||
import java.io.IOException;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import okhttp3.logging.HttpLoggingInterceptor;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
public class GitHubServiceGenerator {
|
||||
|
||||
private static final String BASE_URL = "https://api.github.com/";
|
||||
|
||||
private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create());
|
||||
|
||||
private static Retrofit retrofit = builder.build();
|
||||
|
||||
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
|
||||
|
||||
private static HttpLoggingInterceptor logging = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC);
|
||||
|
||||
public static <S> S createService(Class<S> serviceClass) {
|
||||
if (!httpClient.interceptors().contains(logging)) {
|
||||
httpClient.addInterceptor(logging);
|
||||
builder.client(httpClient.build());
|
||||
retrofit = builder.build();
|
||||
}
|
||||
return retrofit.create(serviceClass);
|
||||
}
|
||||
|
||||
public static <S> S createService(Class<S> serviceClass, final String token) {
|
||||
if (token != null) {
|
||||
httpClient.interceptors().clear();
|
||||
httpClient.addInterceptor(new Interceptor() {
|
||||
@Override
|
||||
public Response intercept(Interceptor.Chain chain) throws IOException {
|
||||
Request original = chain.request();
|
||||
Request.Builder builder = original.newBuilder().header("Authorization", token);
|
||||
Request request = builder.build();
|
||||
return chain.proceed(request);
|
||||
}
|
||||
});
|
||||
builder.client(httpClient.build());
|
||||
retrofit = builder.build();
|
||||
}
|
||||
return retrofit.create(serviceClass);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package com.baeldung.retrofitguide;
|
||||
|
||||
import java.io.IOException;
|
||||
import okhttp3.OkHttpClient;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.Callback;
|
||||
import retrofit2.Response;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Manual creation
|
||||
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
|
||||
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).client(httpClient.build()).build();
|
||||
UserService service = retrofit.create(UserService.class);
|
||||
// Using GitHubServiceGenerator
|
||||
service = GitHubServiceGenerator.createService(UserService.class);
|
||||
Call<User> callSync = service.getUser("eugenp");
|
||||
Call<User> callAsync = service.getUser("eugenp");
|
||||
|
||||
try {
|
||||
Response<User> response = callSync.execute();
|
||||
User user = response.body();
|
||||
System.out.println(user);
|
||||
} catch (IOException ex) {
|
||||
}
|
||||
|
||||
// Execute the call asynchronously. Get a positive or negative callback.
|
||||
callAsync.enqueue(new Callback<User>() {
|
||||
@Override
|
||||
public void onResponse(Call<User> call, Response<User> response) {
|
||||
User user = response.body();
|
||||
System.out.println(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call<User> call, Throwable throwable) {
|
||||
System.out.println(throwable);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package com.baeldung.retrofitguide;
|
||||
|
||||
public class User {
|
||||
|
||||
private String login;
|
||||
private long id;
|
||||
private String url;
|
||||
private String company;
|
||||
private String blog;
|
||||
private String email;
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public String getCompany() {
|
||||
return company;
|
||||
}
|
||||
|
||||
public void setCompany(String company) {
|
||||
this.company = company;
|
||||
}
|
||||
|
||||
public String getBlog() {
|
||||
return blog;
|
||||
}
|
||||
|
||||
public void setBlog(String blog) {
|
||||
this.blog = blog;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.baeldung.retrofitguide;
|
||||
|
||||
import java.util.List;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.Path;
|
||||
import retrofit2.http.Query;
|
||||
|
||||
public interface UserService {
|
||||
|
||||
@GET("/users")
|
||||
public Call<List<User>> getUsers(@Query("per_page") int per_page, @Query("page") int page);
|
||||
|
||||
@GET("/users/{username}")
|
||||
public Call<User> getUser(@Path("username") String username);
|
||||
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.snakeyaml;
|
||||
|
||||
public class Address {
|
||||
private String line;
|
||||
private String city;
|
||||
private String state;
|
||||
private Integer zip;
|
||||
|
||||
public String getLine() {
|
||||
return line;
|
||||
}
|
||||
|
||||
public void setLine(String line) {
|
||||
this.line = line;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public void setState(String state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public Integer getZip() {
|
||||
return zip;
|
||||
}
|
||||
|
||||
public void setZip(Integer zip) {
|
||||
this.zip = zip;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.snakeyaml;
|
||||
|
||||
public class Contact {
|
||||
|
||||
private String type;
|
||||
|
||||
private int number;
|
||||
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public int getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
public void setNumber(int number) {
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package com.baeldung.snakeyaml;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Customer {
|
||||
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private int age;
|
||||
private List<Contact> contactDetails;
|
||||
private Address homeAddress;
|
||||
|
||||
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 List<Contact> getContactDetails() {
|
||||
return contactDetails;
|
||||
}
|
||||
|
||||
public void setContactDetails(List<Contact> contactDetails) {
|
||||
this.contactDetails = contactDetails;
|
||||
}
|
||||
|
||||
public Address getHomeAddress() {
|
||||
return homeAddress;
|
||||
}
|
||||
|
||||
public void setHomeAddress(Address homeAddress) {
|
||||
this.homeAddress = homeAddress;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
package com.baeldung.suanshu;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.numericalmethod.suanshu.algebra.linear.matrix.doubles.Matrix;
|
||||
import com.numericalmethod.suanshu.algebra.linear.vector.doubles.Vector;
|
||||
import com.numericalmethod.suanshu.algebra.linear.vector.doubles.dense.DenseVector;
|
||||
import com.numericalmethod.suanshu.algebra.linear.matrix.doubles.matrixtype.dense.DenseMatrix;
|
||||
import com.numericalmethod.suanshu.algebra.linear.matrix.doubles.operation.Inverse;
|
||||
import com.numericalmethod.suanshu.analysis.function.polynomial.Polynomial;
|
||||
import com.numericalmethod.suanshu.analysis.function.polynomial.root.PolyRoot;
|
||||
import com.numericalmethod.suanshu.analysis.function.polynomial.root.PolyRootSolver;
|
||||
import com.numericalmethod.suanshu.number.complex.Complex;
|
||||
|
||||
class SuanShuMath {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SuanShuMath.class);
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SuanShuMath math = new SuanShuMath();
|
||||
|
||||
math.addingVectors();
|
||||
math.scaleVector();
|
||||
math.innerProductVectors();
|
||||
math.addingIncorrectVectors();
|
||||
|
||||
math.addingMatrices();
|
||||
math.multiplyMatrices();
|
||||
math.multiplyIncorrectMatrices();
|
||||
math.inverseMatrix();
|
||||
|
||||
Polynomial p = math.createPolynomial();
|
||||
math.evaluatePolynomial(p);
|
||||
math.solvePolynomial();
|
||||
}
|
||||
|
||||
public void addingVectors() throws Exception {
|
||||
Vector v1 = new DenseVector(new double[]{1, 2, 3, 4, 5});
|
||||
Vector v2 = new DenseVector(new double[]{5, 4, 3, 2, 1});
|
||||
Vector v3 = v1.add(v2);
|
||||
log.info("Adding vectors: {}", v3);
|
||||
}
|
||||
|
||||
public void scaleVector() throws Exception {
|
||||
Vector v1 = new DenseVector(new double[]{1, 2, 3, 4, 5});
|
||||
Vector v2 = v1.scaled(2.0);
|
||||
log.info("Scaling a vector: {}", v2);
|
||||
}
|
||||
|
||||
public void innerProductVectors() throws Exception {
|
||||
Vector v1 = new DenseVector(new double[]{1, 2, 3, 4, 5});
|
||||
Vector v2 = new DenseVector(new double[]{5, 4, 3, 2, 1});
|
||||
double inner = v1.innerProduct(v2);
|
||||
log.info("Vector inner product: {}", inner);
|
||||
}
|
||||
|
||||
public void addingIncorrectVectors() throws Exception {
|
||||
Vector v1 = new DenseVector(new double[]{1, 2, 3});
|
||||
Vector v2 = new DenseVector(new double[]{5, 4});
|
||||
Vector v3 = v1.add(v2);
|
||||
log.info("Adding vectors: {}", v3);
|
||||
}
|
||||
|
||||
public void addingMatrices() throws Exception {
|
||||
Matrix m1 = new DenseMatrix(new double[][]{
|
||||
{1, 2, 3},
|
||||
{4, 5, 6}
|
||||
});
|
||||
|
||||
Matrix m2 = new DenseMatrix(new double[][]{
|
||||
{3, 2, 1},
|
||||
{6, 5, 4}
|
||||
});
|
||||
|
||||
Matrix m3 = m1.add(m2);
|
||||
log.info("Adding matrices: {}", m3);
|
||||
}
|
||||
|
||||
public void multiplyMatrices() throws Exception {
|
||||
Matrix m1 = new DenseMatrix(new double[][]{
|
||||
{1, 2, 3},
|
||||
{4, 5, 6}
|
||||
});
|
||||
|
||||
Matrix m2 = new DenseMatrix(new double[][]{
|
||||
{1, 4},
|
||||
{2, 5},
|
||||
{3, 6}
|
||||
});
|
||||
|
||||
Matrix m3 = m1.multiply(m2);
|
||||
log.info("Multiplying matrices: {}", m3);
|
||||
}
|
||||
|
||||
public void multiplyIncorrectMatrices() throws Exception {
|
||||
Matrix m1 = new DenseMatrix(new double[][]{
|
||||
{1, 2, 3},
|
||||
{4, 5, 6}
|
||||
});
|
||||
|
||||
Matrix m2 = new DenseMatrix(new double[][]{
|
||||
{3, 2, 1},
|
||||
{6, 5, 4}
|
||||
});
|
||||
|
||||
Matrix m3 = m1.multiply(m2);
|
||||
log.info("Multiplying matrices: {}", m3);
|
||||
}
|
||||
|
||||
public void inverseMatrix() {
|
||||
Matrix m1 = new DenseMatrix(new double[][]{
|
||||
{1, 2},
|
||||
{3, 4}
|
||||
});
|
||||
|
||||
Inverse m2 = new Inverse(m1);
|
||||
log.info("Inverting a matrix: {}", m2);
|
||||
log.info("Verifying a matrix inverse: {}", m1.multiply(m2));
|
||||
}
|
||||
|
||||
public Polynomial createPolynomial() {
|
||||
return new Polynomial(new double[]{3, -5, 1});
|
||||
}
|
||||
|
||||
public void evaluatePolynomial(Polynomial p) {
|
||||
// Evaluate using a real number
|
||||
log.info("Evaluating a polynomial using a real number: {}", p.evaluate(5));
|
||||
// Evaluate using a complex number
|
||||
log.info("Evaluating a polynomial using a complex number: {}", p.evaluate(new Complex(1, 2)));
|
||||
}
|
||||
|
||||
public void solvePolynomial() {
|
||||
Polynomial p = new Polynomial(new double[]{2, 2, -4});
|
||||
PolyRootSolver solver = new PolyRoot();
|
||||
List<? extends Number> roots = solver.solve(p);
|
||||
log.info("Finding polynomial roots: {}", roots);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package com.baeldung.derive4j.adt;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class EitherUnitTest {
|
||||
@Test
|
||||
public void testEitherIsCreatedFromRight() {
|
||||
Either<Exception, String> either = Eithers.right("Okay");
|
||||
Optional<Exception> leftOptional = Eithers.getLeft(either);
|
||||
Optional<String> rightOptional = Eithers.getRight(either);
|
||||
Assertions.assertThat(leftOptional).isEmpty();
|
||||
Assertions.assertThat(rightOptional).hasValue("Okay");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEitherIsMatchedWithRight() {
|
||||
Either<Exception, String> either = Eithers.right("Okay");
|
||||
Function<Exception, String> leftFunction = Mockito.mock(Function.class);
|
||||
Function<String, String> rightFunction = Mockito.mock(Function.class);
|
||||
either.match(leftFunction, rightFunction);
|
||||
Mockito.verify(rightFunction, Mockito.times(1)).apply("Okay");
|
||||
Mockito.verify(leftFunction, Mockito.times(0)).apply(Mockito.any(Exception.class));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package com.baeldung.derive4j.lazy;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class LazyRequestUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLazyContstructedRequest_whenRequestIsReferenced_thenRequestIsLazilyContructed() {
|
||||
LazyRequestSupplier mockSupplier = Mockito.spy(new LazyRequestSupplier());
|
||||
|
||||
LazyRequest request = LazyRequestImpl.lazy(() -> mockSupplier.get());
|
||||
Mockito.verify(mockSupplier, Mockito.times(0)).get();
|
||||
Assert.assertEquals(LazyRequestImpl.getPath(request), "http://test.com/get");
|
||||
Mockito.verify(mockSupplier, Mockito.times(1)).get();
|
||||
|
||||
}
|
||||
|
||||
class LazyRequestSupplier implements Supplier<LazyRequest> {
|
||||
@Override
|
||||
public LazyRequest get() {
|
||||
return LazyRequestImpl.GET("http://test.com/get");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.derive4j.pattern;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class HTTPRequestUnitTest {
|
||||
public static HTTPServer server;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
server = new HTTPServer();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpGETRequest_whenRequestReachesServer_thenProperResponseIsReturned() {
|
||||
HTTPRequest postRequest = HTTPRequests.POST("http://test.com/post", "Resource");
|
||||
HTTPResponse response = server.acceptRequest(postRequest);
|
||||
Assert.assertEquals(201, response.getStatusCode());
|
||||
Assert.assertEquals(HTTPServer.POST_RESPONSE_BODY, response.getResponseBody());
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package com.baeldung.retrofit.basic;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.retrofit.basic.GitHubBasicApi;
|
||||
import com.baeldung.retrofit.models.Contributor;
|
||||
import com.baeldung.retrofit.models.Repository;
|
||||
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
public class GitHubBasicApiLiveTest {
|
||||
|
||||
GitHubBasicApi gitHub;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).build();
|
||||
|
||||
gitHub = retrofit.create(GitHubBasicApi.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListRepos_thenExpectReposThatContainTutorials() {
|
||||
try {
|
||||
List<Repository> repos = gitHub.listRepos("eugenp").execute().body();
|
||||
|
||||
assertThat(repos).isNotEmpty().extracting(Repository::getName).contains("tutorials");
|
||||
} catch (IOException e) {
|
||||
fail("Can not communicate with GitHub API");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListRepoContributers_thenExpectContributorsThatContainEugenp() {
|
||||
try {
|
||||
List<Contributor> contributors = gitHub.listRepoContributors("eugenp", "tutorials").execute().body();
|
||||
|
||||
assertThat(contributors).isNotEmpty().extracting(Contributor::getName).contains("eugenp");
|
||||
} catch (IOException e) {
|
||||
fail("Can not communicate with GitHub API");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.retrofit.rx;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.retrofit.models.Contributor;
|
||||
import com.baeldung.retrofit.models.Repository;
|
||||
import com.baeldung.retrofit.rx.GitHubRxApi;
|
||||
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
public class GitHubRxLiveTest {
|
||||
|
||||
GitHubRxApi gitHub;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
|
||||
|
||||
gitHub = retrofit.create(GitHubRxApi.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListRepos_thenExpectReposThatContainTutorials() {
|
||||
gitHub.listRepos("eugenp").subscribe(repos -> {
|
||||
assertThat(repos).isNotEmpty().extracting(Repository::getName).contains("tutorials");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListRepoContributers_thenExpectContributorsThatContainEugenp() {
|
||||
gitHub.listRepoContributors("eugenp", "tutorials").subscribe(contributors -> {
|
||||
assertThat(contributors).isNotEmpty().extracting(Contributor::getName).contains("eugenp");
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package com.baeldung.snakeyaml;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.nodes.Tag;
|
||||
|
||||
import com.baeldung.snakeyaml.Customer;
|
||||
|
||||
public class JavaToYAMLSerializationUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenDumpMap_thenGenerateCorrectYAML() {
|
||||
Map<String, Object> data = new LinkedHashMap<String, Object>();
|
||||
data.put("name", "Silenthand Olleander");
|
||||
data.put("race", "Human");
|
||||
data.put("traits", new String[] { "ONE_HAND", "ONE_EYE" });
|
||||
Yaml yaml = new Yaml();
|
||||
StringWriter writer = new StringWriter();
|
||||
yaml.dump(data, writer);
|
||||
String expectedYaml = "name: Silenthand Olleander\nrace: Human\ntraits: [ONE_HAND, ONE_EYE]\n";
|
||||
assertEquals(expectedYaml, writer.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDumpACustomType_thenGenerateCorrectYAML() {
|
||||
Customer customer = new Customer();
|
||||
customer.setAge(45);
|
||||
customer.setFirstName("Greg");
|
||||
customer.setLastName("McDowell");
|
||||
Yaml yaml = new Yaml();
|
||||
StringWriter writer = new StringWriter();
|
||||
yaml.dump(customer, writer);
|
||||
String expectedYaml = "!!com.baeldung.snakeyaml.Customer {age: 45, contactDetails: null, firstName: Greg,\n homeAddress: null, lastName: McDowell}\n";
|
||||
assertEquals(expectedYaml, writer.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDumpAsCustomType_thenGenerateCorrectYAML() {
|
||||
Customer customer = new Customer();
|
||||
customer.setAge(45);
|
||||
customer.setFirstName("Greg");
|
||||
customer.setLastName("McDowell");
|
||||
Yaml yaml = new Yaml();
|
||||
String expectedYaml = "{age: 45, contactDetails: null, firstName: Greg, homeAddress: null, lastName: McDowell}\n";
|
||||
assertEquals(expectedYaml, yaml.dumpAs(customer, Tag.MAP, null));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
package com.baeldung.snakeyaml;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.yaml.snakeyaml.TypeDescription;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.constructor.Constructor;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class YAMLToJavaDeserialisationUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenLoadYAMLDocument_thenLoadCorrectMap() {
|
||||
Yaml yaml = new Yaml();
|
||||
InputStream inputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customer.yaml");
|
||||
Map<String, Object> obj = yaml.load(inputStream);
|
||||
assertEquals("John", obj.get("firstName"));
|
||||
assertEquals("Doe", obj.get("lastName"));
|
||||
assertEquals(20, obj.get("age"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObject() {
|
||||
Yaml yaml = new Yaml(new Constructor(Customer.class));
|
||||
InputStream inputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customer.yaml");
|
||||
Customer customer = yaml.load(inputStream);
|
||||
assertEquals("John", customer.getFirstName());
|
||||
assertEquals("Doe", customer.getLastName());
|
||||
assertEquals(20, customer.getAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadYAMLDocumentWithAssumedClass_thenLoadCorrectJavaObject() {
|
||||
Yaml yaml = new Yaml();
|
||||
InputStream inputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customer_with_type.yaml");
|
||||
Customer customer = yaml.load(inputStream);
|
||||
assertEquals("John", customer.getFirstName());
|
||||
assertEquals("Doe", customer.getLastName());
|
||||
assertEquals(20, customer.getAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadYAML_thenLoadCorrectImplicitTypes() {
|
||||
Yaml yaml = new Yaml();
|
||||
Map<Object, Object> document = yaml.load("3.0: 2018-07-22");
|
||||
assertNotNull(document);
|
||||
assertEquals(1, document.size());
|
||||
assertTrue(document.containsKey(3.0d));
|
||||
assertTrue(document.get(3.0d) instanceof Date);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObjectWithNestedObjects() {
|
||||
Yaml yaml = new Yaml(new Constructor(Customer.class));
|
||||
InputStream inputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customer_with_contact_details_and_address.yaml");
|
||||
Customer customer = yaml.load(inputStream);
|
||||
assertNotNull(customer);
|
||||
assertEquals("John", customer.getFirstName());
|
||||
assertEquals("Doe", customer.getLastName());
|
||||
assertEquals(31, customer.getAge());
|
||||
assertNotNull(customer.getContactDetails());
|
||||
assertEquals(2, customer.getContactDetails().size());
|
||||
assertEquals("mobile", customer.getContactDetails()
|
||||
.get(0)
|
||||
.getType());
|
||||
assertEquals(123456789,customer.getContactDetails()
|
||||
.get(0)
|
||||
.getNumber());
|
||||
assertEquals("landline", customer.getContactDetails()
|
||||
.get(1)
|
||||
.getType());
|
||||
assertEquals(456786868, customer.getContactDetails()
|
||||
.get(1)
|
||||
.getNumber());
|
||||
assertNotNull(customer.getHomeAddress());
|
||||
assertEquals("Xyz, DEF Street", customer.getHomeAddress()
|
||||
.getLine());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadYAMLDocumentWithTypeDescription_thenLoadCorrectJavaObjectWithCorrectGenericType() {
|
||||
Constructor constructor = new Constructor(Customer.class);
|
||||
TypeDescription customTypeDescription = new TypeDescription(Customer.class);
|
||||
customTypeDescription.addPropertyParameters("contactDetails", Contact.class);
|
||||
constructor.addTypeDescription(customTypeDescription);
|
||||
Yaml yaml = new Yaml(constructor);
|
||||
InputStream inputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customer_with_contact_details.yaml");
|
||||
Customer customer = yaml.load(inputStream);
|
||||
assertNotNull(customer);
|
||||
assertEquals("John", customer.getFirstName());
|
||||
assertEquals("Doe", customer.getLastName());
|
||||
assertEquals(31, customer.getAge());
|
||||
assertNotNull(customer.getContactDetails());
|
||||
assertEquals(2, customer.getContactDetails().size());
|
||||
assertEquals("mobile", customer.getContactDetails()
|
||||
.get(0)
|
||||
.getType());
|
||||
assertEquals("landline", customer.getContactDetails()
|
||||
.get(1)
|
||||
.getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadMultipleYAMLDocuments_thenLoadCorrectJavaObjects() {
|
||||
Yaml yaml = new Yaml(new Constructor(Customer.class));
|
||||
InputStream inputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("yaml/customers.yaml");
|
||||
int count = 0;
|
||||
for (Object object : yaml.loadAll(inputStream)) {
|
||||
count++;
|
||||
assertTrue(object instanceof Customer);
|
||||
}
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.unirest;
|
||||
|
||||
public class Article {
|
||||
|
||||
private String id;
|
||||
private String title;
|
||||
private String author;
|
||||
|
||||
public Article(String id, String title, String author) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
}
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
package com.baeldung.unirest;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.unirest.Article;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.mashape.unirest.http.HttpResponse;
|
||||
import com.mashape.unirest.http.JsonNode;
|
||||
import com.mashape.unirest.http.ObjectMapper;
|
||||
import com.mashape.unirest.http.Unirest;
|
||||
import com.mashape.unirest.http.async.Callback;
|
||||
import com.mashape.unirest.http.exceptions.UnirestException;
|
||||
|
||||
public class HttpClientLiveTest {
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
// Unirest.setProxy(new HttpHost("localhost", 8080));
|
||||
Unirest.setTimeouts(20000, 15000);
|
||||
Unirest.setDefaultHeader("X-app-name", "baeldung-unirest");
|
||||
Unirest.setDefaultHeader("X-request-id", "100004f00ab5");
|
||||
Unirest.setConcurrency(20, 5);
|
||||
Unirest.setObjectMapper(new ObjectMapper() {
|
||||
com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
|
||||
public String writeValue(Object value) {
|
||||
try {
|
||||
return mapper.writeValueAsString(value);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public <T> T readValue(String value, Class<T> valueType) {
|
||||
|
||||
try {
|
||||
return mapper.readValue(value, valueType);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDown() throws IOException {
|
||||
Unirest.clearDefaultHeaders();
|
||||
Unirest.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOkay() throws UnirestException {
|
||||
HttpResponse<JsonNode> jsonResponse = Unirest.get("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154")
|
||||
.header("accept", "application/json")
|
||||
.queryString("apiKey", "123")
|
||||
.asJson();
|
||||
assertNotNull(jsonResponse.getBody());
|
||||
assertEquals(200, jsonResponse.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusAccepted() throws UnirestException {
|
||||
|
||||
Map<String, String> headers = new HashMap<String, String>();
|
||||
headers.put("accept", "application/json");
|
||||
headers.put("Authorization", "Bearer 5a9ce37b3100004f00ab5154");
|
||||
|
||||
Map<String, Object> fields = new HashMap<String, Object>();
|
||||
fields.put("name", "Sam Baeldung");
|
||||
fields.put("id", "PSP123");
|
||||
|
||||
HttpResponse<JsonNode> jsonResponse = Unirest.put("http://www.mocky.io/v2/5a9ce7853100002a00ab515e")
|
||||
.headers(headers)
|
||||
.fields(fields)
|
||||
.asJson();
|
||||
assertNotNull(jsonResponse.getBody());
|
||||
assertEquals(202, jsonResponse.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestBodyWhenCreatedThenCorrect() throws UnirestException {
|
||||
|
||||
HttpResponse<JsonNode> jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
|
||||
.body("{\"name\":\"Sam Baeldung\", \"city\":\"viena\"}")
|
||||
.asJson();
|
||||
assertEquals(201, jsonResponse.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void whenAysncRequestShouldReturnOk() throws InterruptedException, ExecutionException {
|
||||
Future<HttpResponse<JsonNode>> future = Unirest.post("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154?mocky-delay=10000ms")
|
||||
.header("accept", "application/json")
|
||||
.asJsonAsync(new Callback<JsonNode>() {
|
||||
|
||||
public void failed(UnirestException e) {
|
||||
// Do something if the request failed
|
||||
}
|
||||
|
||||
public void completed(HttpResponse<JsonNode> response) {
|
||||
// Do something if the request is successful
|
||||
}
|
||||
|
||||
public void cancelled() {
|
||||
// Do something if the request is cancelled
|
||||
}
|
||||
|
||||
});
|
||||
assertEquals(200, future.get()
|
||||
.getStatus());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArticleWhenCreatedThenCorrect() throws UnirestException {
|
||||
Article article = new Article("ID1213", "Guide to Rest", "baeldung");
|
||||
HttpResponse<JsonNode> jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
|
||||
.body(article)
|
||||
.asJson();
|
||||
assertEquals(201, jsonResponse.getStatus());
|
||||
}
|
||||
|
||||
// @Test
|
||||
public void givenFileWhenUploadedThenCorrect() throws UnirestException {
|
||||
|
||||
HttpResponse<JsonNode> jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
|
||||
.field("file", new File("/path/to/file"))
|
||||
.asJson();
|
||||
assertEquals(201, jsonResponse.getStatus());
|
||||
}
|
||||
|
||||
// @Test
|
||||
public void givenByteStreamWhenUploadedThenCorrect() throws IOException, UnirestException {
|
||||
try (InputStream inputStream = new FileInputStream(new File("/path/to/file/artcile.txt"))) {
|
||||
byte[] bytes = new byte[inputStream.available()];
|
||||
inputStream.read(bytes);
|
||||
HttpResponse<JsonNode> jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
|
||||
.field("file", bytes, "article.txt")
|
||||
.asJson();
|
||||
assertEquals(201, jsonResponse.getStatus());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// @Test
|
||||
public void givenInputStreamWhenUploadedThenCorrect() throws UnirestException, IOException {
|
||||
try (InputStream inputStream = new FileInputStream(new File("/path/to/file/artcile.txt"))) {
|
||||
|
||||
HttpResponse<JsonNode> jsonResponse = Unirest.post("http://www.mocky.io/v2/5a9ce7663100006800ab515d")
|
||||
.field("file", inputStream, ContentType.APPLICATION_OCTET_STREAM, "article.txt")
|
||||
.asJson();
|
||||
assertEquals(201, jsonResponse.getStatus());
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user