library-mv-pt-2

This commit is contained in:
Sjmillington
2019-08-12 17:35:47 +01:00
parent 1f104924c7
commit 16489a1de1
56 changed files with 145 additions and 59 deletions

View File

@@ -0,0 +1,16 @@
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);
}
}

View File

@@ -0,0 +1,11 @@
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;
}
}

View File

@@ -0,0 +1,24 @@
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);
}
};
}

View File

@@ -0,0 +1,33 @@
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());
}
}

View File

@@ -0,0 +1,31 @@
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);
}

View File

@@ -0,0 +1,13 @@
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);
}
}

View File

@@ -0,0 +1,44 @@
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);
}
}

View File

@@ -0,0 +1,33 @@
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 + "]";
}
}

View File

@@ -0,0 +1,30 @@
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 + "]";
}
}

View File

@@ -0,0 +1,31 @@
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);
}

View File

@@ -0,0 +1,11 @@
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);
}
}

View File

@@ -0,0 +1,23 @@
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();
}
}

View File

@@ -0,0 +1,51 @@
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);
}
}

View File

@@ -0,0 +1,45 @@
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);
}
});
}
}

View File

@@ -0,0 +1,65 @@
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 + '}';
}
}

View File

@@ -0,0 +1,17 @@
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);
}

View File

@@ -0,0 +1,52 @@
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");
}
}
}

View File

@@ -0,0 +1,41 @@
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");
});
}
}

View File

@@ -0,0 +1,39 @@
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;
}
}

View File

@@ -0,0 +1,174 @@
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());
}
}
}