├── deploy.sh ├── .gitignore ├── src ├── test │ └── java │ │ └── dev │ │ └── yasper │ │ └── rump │ │ ├── model │ │ └── Post.java │ │ ├── ProxyTest.java │ │ ├── RumpAsyncInstanceTest.java │ │ ├── RumpInstanceTest.java │ │ └── RumpTest.java └── main │ └── java │ └── dev │ └── yasper │ └── rump │ ├── client │ ├── RestClient.java │ ├── AsyncRestClient.java │ └── DefaultRestClient.java │ ├── exception │ ├── ExceptionHandler.java │ ├── DefaultExceptionHandler.java │ └── HttpStatusCodeException.java │ ├── Header.java │ ├── interceptor │ ├── ResponseInterceptor.java │ └── RequestInterceptor.java │ ├── request │ ├── RequestTransformer.java │ ├── RequestMethod.java │ ├── JacksonRequestTransformer.java │ └── RequestParams.java │ ├── response │ ├── JacksonResponseTransformer.java │ ├── ResponseTransformer.java │ ├── HttpResponse.java │ └── PrimitiveBody.java │ ├── HeaderNames.java │ ├── Rump.java │ ├── config │ └── RequestConfig.java │ └── Headers.java ├── .github └── workflows │ └── verify.yml ├── pom.xml ├── README.md └── LICENSE /deploy.sh: -------------------------------------------------------------------------------- 1 | mvn clean verify 2 | svn cleanup 3 | mvn release:prepare -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Intellij 2 | .idea/ 3 | *.iml 4 | *.iws 5 | 6 | # Mac 7 | .DS_Store 8 | 9 | # Maven 10 | log/ 11 | target/ -------------------------------------------------------------------------------- /src/test/java/dev/yasper/rump/model/Post.java: -------------------------------------------------------------------------------- 1 | package dev.yasper.rump.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import lombok.EqualsAndHashCode; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | import lombok.experimental.Accessors; 8 | 9 | @Setter 10 | @Accessors(chain = true) 11 | @EqualsAndHashCode 12 | @Getter 13 | public class Post { 14 | 15 | @JsonProperty 16 | int userId; 17 | 18 | @JsonProperty 19 | int id; 20 | 21 | @JsonProperty 22 | String title; 23 | 24 | @JsonProperty 25 | String body; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /.github/workflows/verify.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a package using Maven and then publish it to GitHub packages when a release is created 2 | # For more information see: https://github.com/actions/setup-java#apache-maven-with-a-settings-path 3 | 4 | name: Verify 5 | 6 | on: 7 | push: 8 | # Sequence of patterns matched against refs/heads 9 | branches-ignore: 10 | - erroneous 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up JDK 11 20 | uses: actions/setup-java@v1 21 | with: 22 | java-version: 11 23 | 24 | - name: Build with Maven 25 | run: mvn -B package --file pom.xml -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/client/RestClient.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.client; 20 | 21 | /** 22 | * Generic rest client description 23 | */ 24 | public interface RestClient { 25 | 26 | /** 27 | * Is this client async or not 28 | * @return true if the client is async, otherwise false 29 | */ 30 | boolean isAsync(); 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/exception/ExceptionHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.exception; 20 | 21 | public interface ExceptionHandler { 22 | 23 | /** 24 | * Called when an non ignored status code is encountered 25 | * @param e The exception to be handled 26 | */ 27 | void onHttpException(HttpStatusCodeException e); 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/Header.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump; 20 | 21 | public interface Header { 22 | 23 | /** 24 | * Get the header name/key 25 | * @return The header name/key 26 | */ 27 | String getName(); 28 | 29 | /** 30 | * Get the header value 31 | * @return the header value 32 | */ 33 | String getValue(); 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/dev/yasper/rump/ProxyTest.java: -------------------------------------------------------------------------------- 1 | package dev.yasper.rump; 2 | 3 | import dev.yasper.rump.client.DefaultRestClient; 4 | import dev.yasper.rump.config.RequestConfig; 5 | import org.junit.Assert; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | 9 | import java.io.IOException; 10 | import java.net.*; 11 | 12 | public class ProxyTest { 13 | 14 | private DefaultRestClient withProxy; 15 | 16 | @Before 17 | public void init() { 18 | SocketAddress address = new InetSocketAddress("104.168.211.27", 1080); 19 | RequestConfig withProxy = new RequestConfig() 20 | .setProxy(new Proxy(Proxy.Type.HTTP, address)) 21 | .setTimeout(25000); 22 | this.withProxy = Rump.createDefault(withProxy); 23 | } 24 | 25 | @Test 26 | public void fetchIp() throws IOException { 27 | try { 28 | String withProxy = this.withProxy.getForObject("https://api.ipify.org/?format=json", String.class); 29 | String res = Rump.getForObject("https://api.ipify.org/?format=json", String.class); 30 | Assert.assertNotEquals(withProxy, res); 31 | } catch (ConnectException | SocketTimeoutException ignore) { 32 | // This is fine, means the proxy is at least being applied. 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/dev/yasper/rump/RumpAsyncInstanceTest.java: -------------------------------------------------------------------------------- 1 | package dev.yasper.rump; 2 | 3 | import dev.yasper.rump.client.AsyncRestClient; 4 | import dev.yasper.rump.config.RequestConfig; 5 | import dev.yasper.rump.model.Post; 6 | import org.junit.Assert; 7 | import org.junit.Test; 8 | 9 | import java.util.concurrent.Executors; 10 | 11 | public class RumpAsyncInstanceTest { 12 | 13 | private final AsyncRestClient ars; 14 | 15 | public RumpAsyncInstanceTest() { 16 | RequestConfig config = new RequestConfig() 17 | .setBaseURL("https://jsonplaceholder.typicode.com/"); 18 | ars = Rump.createAsync(config, Executors.newFixedThreadPool(1)); 19 | } 20 | 21 | @Test 22 | public void testGetObject() { 23 | ars.get("posts/1", Post.class).thenAccept(post -> { 24 | Post match = new Post() 25 | .setId(1) 26 | .setUserId(1) 27 | .setTitle("sunt aut facere repellat provident occaecati excepturi optio reprehenderit") 28 | .setBody("quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"); 29 | Assert.assertEquals(match, post.getBody()); 30 | Assert.assertEquals(post.getResponseCode(), 200); 31 | }); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/exception/DefaultExceptionHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.exception; 20 | 21 | /** 22 | * Default exception handling implementation. This handler will throw any 23 | * status exception that it gets. See {@link dev.yasper.rump.config.RequestConfig#setExceptionHandler(ExceptionHandler)} 24 | * to change this behaviour. 25 | */ 26 | public class DefaultExceptionHandler implements ExceptionHandler { 27 | 28 | @Override 29 | public void onHttpException(HttpStatusCodeException e) { 30 | throw e; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/interceptor/ResponseInterceptor.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.interceptor; 20 | 21 | import dev.yasper.rump.response.HttpResponse; 22 | 23 | public interface ResponseInterceptor { 24 | 25 | /** 26 | * Method executed before the response is returned, can be used to change response data where necessary. 27 | * @param res The {@link HttpResponse} which will be returned 28 | * @return {@code true} iff this response should be forwarded, {@code false} if null should be returned. 29 | */ 30 | boolean beforeResponse(HttpResponse res); 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/request/RequestTransformer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.request; 20 | 21 | import dev.yasper.rump.Headers; 22 | 23 | /** 24 | * Transformer interface for request object. 25 | */ 26 | public interface RequestTransformer { 27 | 28 | /** 29 | * Transform a request body object to the object that should be passed in the request. 30 | * @param data The request body that is to be transformed 31 | * @param headers The headers that could be used to transform the object 32 | * @return The transformed object 33 | */ 34 | Object transform(Object data, Headers headers); 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/response/JacksonResponseTransformer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.response; 20 | 21 | import com.fasterxml.jackson.databind.ObjectMapper; 22 | 23 | import java.io.IOException; 24 | import java.io.InputStream; 25 | 26 | /** 27 | * Response transformer implementation that uses Jackson to transform the response object to the 28 | * requested type. 29 | */ 30 | public class JacksonResponseTransformer implements ResponseTransformer { 31 | 32 | private final ObjectMapper om = new ObjectMapper(); 33 | 34 | @Override 35 | public T transform(InputStream from, Class toType) throws IOException { 36 | return om.readValue(from, toType); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/request/RequestMethod.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.request; 20 | 21 | import dev.yasper.rump.config.RequestConfig; 22 | 23 | /** 24 | * Enum containing all different types of REST methods 25 | */ 26 | public enum RequestMethod { 27 | GET, POST, PUT, DELETE, PATCH, HEAD; 28 | 29 | /** 30 | *

31 | * Transforms the request method to a configurable value usable as a config overload. 32 | *

33 | * 34 | * @return A RequestConfig instance where {@link RequestConfig#getMethod()} will return this {@link RequestMethod} 35 | */ 36 | public RequestConfig toConfig() { 37 | return new RequestConfig() 38 | .setMethod(this); 39 | } 40 | } -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/response/ResponseTransformer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.response; 20 | 21 | import java.io.IOException; 22 | import java.io.InputStream; 23 | 24 | public interface ResponseTransformer { 25 | 26 | /** 27 | * Transforms the response from an input stream to the requested type 28 | * 29 | * @param from The input stream from which to extract the response 30 | * @param toType The type class to which to convert the input 31 | * @param The requested type to return 32 | * @return the transformed object in the requested type 33 | * @throws IOException for InputStream processing 34 | */ 35 | T transform(InputStream from, Class toType) throws IOException; 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/request/JacksonRequestTransformer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.request; 20 | 21 | import com.fasterxml.jackson.core.JsonProcessingException; 22 | import com.fasterxml.jackson.databind.ObjectMapper; 23 | import dev.yasper.rump.Headers; 24 | 25 | /** 26 | * Request transformer implementation to map objects to a json string to be sent in the request. 27 | */ 28 | public class JacksonRequestTransformer implements RequestTransformer { 29 | 30 | private final ObjectMapper om = new ObjectMapper(); 31 | 32 | @Override 33 | public Object transform(Object data, Headers headers) { 34 | try { 35 | return om.writeValueAsString(data); 36 | } catch (JsonProcessingException e) { 37 | return ""; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/exception/HttpStatusCodeException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.exception; 20 | 21 | import dev.yasper.rump.response.HttpResponse; 22 | 23 | /** 24 | * Class describing the exception thrown on an erroneous status code 25 | * (any value above 299 is considered erroneous by the HTTP specification) 26 | */ 27 | public class HttpStatusCodeException extends RuntimeException { 28 | 29 | private final HttpResponse errorResponse; 30 | 31 | /** 32 | * Constructor for this exception 33 | * @param errorResponse An HttpResponse containing the {@link java.net.HttpURLConnection} data and the error body 34 | */ 35 | public HttpStatusCodeException(HttpResponse errorResponse) { 36 | super(errorResponse.getResponseMessage()); 37 | this.errorResponse = errorResponse; 38 | } 39 | 40 | /** 41 | * Get the response for this exception 42 | * @return the {@link HttpResponse} containing the error 43 | */ 44 | public HttpResponse getErrorResponse() { 45 | return errorResponse; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/interceptor/RequestInterceptor.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.interceptor; 20 | 21 | import dev.yasper.rump.config.RequestConfig; 22 | 23 | import java.net.HttpURLConnection; 24 | 25 | /** 26 | * Interface for intercepting requests and modifying the connection where necessary. 27 | */ 28 | public interface RequestInterceptor { 29 | 30 | /** 31 | * Method executed before the request is made. 32 | * @param mergedURL The complete URL for this request (includes the base, the path and the params) 33 | * @param connection The connection which is being constructed for this request, you can modify properties on this 34 | * object 35 | * @param config The request configuration from which the request was constructed, these properties are modifiable 36 | * but won't have an impact on the outstanding connection as they won't be reapplied 37 | * @return {@code true} iff the request should be made, {@code false} if it should be canceled. 38 | */ 39 | boolean beforeRequest(String mergedURL, HttpURLConnection connection, RequestConfig config); 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/dev/yasper/rump/RumpInstanceTest.java: -------------------------------------------------------------------------------- 1 | package dev.yasper.rump; 2 | 3 | import dev.yasper.rump.client.DefaultRestClient; 4 | import dev.yasper.rump.config.RequestConfig; 5 | import dev.yasper.rump.model.Post; 6 | import dev.yasper.rump.response.HttpResponse; 7 | import org.junit.Assert; 8 | import org.junit.Test; 9 | 10 | import java.io.IOException; 11 | 12 | public class RumpInstanceTest { 13 | 14 | private final DefaultRestClient drs; 15 | 16 | public RumpInstanceTest() { 17 | RequestConfig config = new RequestConfig() 18 | .setIgnoreStatusCode((code) -> code >= 400) 19 | .setBaseURL("https://jsonplaceholder.typicode.com/") 20 | .addRequestInterceptor((mergedURL, connection, config1) -> { 21 | if (mergedURL.startsWith("https://www.google.nl")) { 22 | connection.setRequestProperty("Authorization", "Bearer myDomainToken"); 23 | } 24 | return true; 25 | }); 26 | drs = Rump.createDefault(config); 27 | } 28 | 29 | @Test 30 | public void testOtherBase() throws IOException { 31 | HttpResponse google = drs.get("https://www.google.nl/", String.class, 32 | new RequestConfig() 33 | .setBaseURL("") 34 | ); 35 | Assert.assertEquals(google.getResponseCode(), 200); 36 | } 37 | 38 | @Test 39 | public void testGetObject() { 40 | try { 41 | HttpResponse post = drs.get("posts/1", Post.class); 42 | Post match = new Post() 43 | .setId(1) 44 | .setUserId(1) 45 | .setTitle("sunt aut facere repellat provident occaecati excepturi optio reprehenderit") 46 | .setBody("quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"); 47 | Assert.assertEquals(match, post.getBody()); 48 | Assert.assertEquals(post.getResponseCode(), 200); 49 | } catch (IOException e) { 50 | e.printStackTrace(); 51 | } 52 | } 53 | 54 | @Test 55 | public void testHead() throws IOException { 56 | HttpResponse post = drs.head("posts/1"); 57 | Assert.assertEquals(post.getResponseHeaders().getServer(), "cloudflare"); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/response/HttpResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.response; 20 | 21 | import dev.yasper.rump.Headers; 22 | import dev.yasper.rump.config.RequestConfig; 23 | 24 | /** 25 | * Class encapsulating all relevant values to a http response 26 | * @param The response body type 27 | */ 28 | public class HttpResponse { 29 | 30 | private final Headers responseHeaders; 31 | private final int responseCode; 32 | private final String responseMessage; 33 | private final RequestConfig requestConfig; 34 | private final String url; 35 | private T body; 36 | 37 | /** 38 | * Constructor for HttpResponse 39 | * @param body body of type T 40 | * @param responseHeaders headers in the response 41 | * @param responseCode the response code 42 | * @param responseMessage the message of the response 43 | * @param requestConfig the request configuration with which this response was obtained 44 | * @param url the url that was requested (including base and params) 45 | */ 46 | public HttpResponse(T body, Headers responseHeaders, int responseCode, String responseMessage, RequestConfig requestConfig, 47 | String url) { 48 | this.body = body; 49 | this.responseHeaders = responseHeaders; 50 | this.responseCode = responseCode; 51 | this.requestConfig = requestConfig; 52 | this.url = url; 53 | this.responseMessage = responseMessage; 54 | } 55 | 56 | /** 57 | * Gets the response message 58 | * @return the response message 59 | */ 60 | public String getResponseMessage() { 61 | return responseMessage; 62 | } 63 | 64 | /** 65 | * Gets the requested url 66 | * @return the request url 67 | */ 68 | public String getUrl() { 69 | return url; 70 | } 71 | 72 | /** 73 | * Gets the request config used to get this response 74 | * @return the request config 75 | */ 76 | public RequestConfig getRequestConfig() { 77 | return requestConfig; 78 | } 79 | 80 | /** 81 | * Gets the response body as T 82 | * @return the response body 83 | */ 84 | public T getBody() { 85 | return this.body; 86 | } 87 | 88 | /** 89 | * Used to transform the body in response interceptors 90 | * @param to the new body to set it to 91 | */ 92 | public void setBody(T to) { 93 | this.body = to; 94 | } 95 | 96 | /** 97 | * Gets the response headers 98 | * @return the response headers 99 | */ 100 | public Headers getResponseHeaders() { 101 | return this.responseHeaders; 102 | } 103 | 104 | /** 105 | * Gets the response code 106 | * @return the response code 107 | */ 108 | public int getResponseCode() { 109 | return this.responseCode; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/test/java/dev/yasper/rump/RumpTest.java: -------------------------------------------------------------------------------- 1 | package dev.yasper.rump; 2 | 3 | import com.fasterxml.jackson.databind.JsonNode; 4 | import dev.yasper.rump.config.RequestConfig; 5 | import dev.yasper.rump.model.Post; 6 | import dev.yasper.rump.request.RequestMethod; 7 | import dev.yasper.rump.request.RequestParams; 8 | import dev.yasper.rump.response.HttpResponse; 9 | import org.junit.Assert; 10 | import org.junit.Test; 11 | 12 | import java.io.IOException; 13 | 14 | public class RumpTest { 15 | 16 | @Test 17 | public void testGetRequest() { 18 | try { 19 | HttpResponse result = Rump.get("https://www.google.nl/", String.class); 20 | Assert.assertNotNull(result); 21 | Assert.assertEquals(result.getResponseCode(), 200); 22 | } catch (IOException e) { 23 | e.printStackTrace(); 24 | } 25 | } 26 | 27 | @Test 28 | public void testGetObject() { 29 | try { 30 | 31 | HttpResponse post = Rump.get("https://jsonplaceholder.typicode.com/posts/1", Post.class); 32 | Post match = new Post() 33 | .setId(1) 34 | .setUserId(1) 35 | .setTitle("sunt aut facere repellat provident occaecati excepturi optio reprehenderit") 36 | .setBody("quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"); 37 | Assert.assertEquals(match, post.getBody()); 38 | Assert.assertEquals(post.getResponseCode(), 200); 39 | } catch (IOException e) { 40 | e.printStackTrace(); 41 | } 42 | } 43 | 44 | @Test 45 | public void overrideDefaultConfig() { 46 | RequestConfig params = new RequestParams() 47 | .add("test", 1) 48 | .toConfig(); 49 | 50 | RequestConfig headers = new Headers() 51 | .setAuthentication("Bearer token") 52 | .setContentType(Headers.ContentType.APPLICATION_JSON) 53 | .setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36") 54 | .toConfig(); 55 | 56 | try { 57 | // Params from default config are now overridden and headers from default config are now merged together 58 | HttpResponse res = Rump.get("https://jsonplaceholder.typicode.com/posts/1", Post.class, params, headers); 59 | Post match = new Post() 60 | .setId(1) 61 | .setUserId(1) 62 | .setTitle("sunt aut facere repellat provident occaecati excepturi optio reprehenderit") 63 | .setBody("quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"); 64 | Assert.assertEquals(match, res.getBody()); 65 | Assert.assertEquals(res.getResponseCode(), 200); 66 | } catch (IOException e) { 67 | e.printStackTrace(); 68 | } 69 | 70 | } 71 | 72 | @Test 73 | public void testPost() throws IOException { 74 | Post match = new Post() 75 | .setTitle("sunt aut facere repellat provident occaecati excepturi optio reprehenderit") 76 | .setBody("quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"); 77 | HttpResponse postRes = Rump.post("https://jsonplaceholder.typicode.com/posts/", match, JsonNode.class); 78 | Assert.assertEquals(postRes.getBody().get("id").asInt(), 101); 79 | } 80 | 81 | @Test 82 | public void testOverridePost() throws IOException { 83 | Post match = new Post() 84 | .setTitle("sunt aut facere repellat provident occaecati excepturi optio reprehenderit") 85 | .setBody("quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"); 86 | HttpResponse postRes = Rump.post("https://jsonplaceholder.typicode.com/posts/", match, JsonNode.class, RequestMethod.GET.toConfig()); 87 | Assert.assertFalse(postRes.getBody().has("id")); 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | 6 | org.sonatype.oss 7 | oss-parent 8 | 9 9 | 10 | 11 | dev.yasper 12 | rump 13 | 1.0.7 14 | 15 | 16 | 17 | ossrh 18 | https://oss.sonatype.org/content/repositories/snapshots 19 | 20 | 21 | ossrh 22 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 23 | 24 | 25 | 26 | 27 | 28 | gpl_v3 29 | https://www.gnu.org/licenses/gpl-3.0.en.html 30 | repo 31 | 32 | 33 | 34 | 35 | 14 36 | 14 37 | 14 38 | 39 | 40 | 41 | 42 | com.fasterxml.jackson.core 43 | jackson-core 44 | 2.11.1 45 | 46 | 47 | com.fasterxml.jackson.core 48 | jackson-databind 49 | 2.11.1 50 | 51 | 52 | junit 53 | junit 54 | 4.13 55 | test 56 | 57 | 58 | org.projectlombok 59 | lombok 60 | 1.18.12 61 | test 62 | 63 | 64 | 65 | 66 | 67 | 68 | org.apache.maven.plugins 69 | maven-source-plugin 70 | 3.2.1 71 | 72 | 73 | attach-sources 74 | 75 | jar-no-fork 76 | 77 | 78 | 79 | 80 | 81 | org.apache.maven.plugins 82 | maven-javadoc-plugin 83 | 3.2.0 84 | 85 | ${java.home}/bin/javadoc 86 | ${java.version} 87 | 88 | 89 | 90 | attach-javadocs 91 | 92 | jar 93 | 94 | 95 | 96 | 97 | 98 | org.apache.maven.plugins 99 | maven-gpg-plugin 100 | 1.6 101 | 102 | 103 | sign-artifacts 104 | verify 105 | 106 | sign 107 | 108 | 109 | 110 | 111 | 112 | --pinentry-mode 113 | loopback 114 | 115 | 116 | 117 | 118 | org.sonatype.plugins 119 | nexus-staging-maven-plugin 120 | 1.6.8 121 | true 122 | 123 | ossrh 124 | https://oss.sonatype.org/ 125 | true 126 | 127 | 128 | 129 | org.apache.maven.plugins 130 | maven-release-plugin 131 | 2.5 132 | 133 | v@{project.version} 134 | 135 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/response/PrimitiveBody.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.response; 20 | 21 | import java.io.BufferedReader; 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.io.InputStreamReader; 25 | 26 | /** 27 | * Used for parsing primitive body types that won't be properly accepted using a json parser. 28 | */ 29 | public class PrimitiveBody { 30 | 31 | private final InputStream responseStream; 32 | private final String parsed; 33 | 34 | /** 35 | * Construct a primitive body 36 | * @param responseStream the response stream to parse from 37 | */ 38 | public PrimitiveBody(InputStream responseStream) { 39 | this.responseStream = responseStream; 40 | this.parsed = parse(); 41 | } 42 | 43 | /** 44 | * Get the body as a buffered reader 45 | * @return a {@link BufferedReader} instsance 46 | */ 47 | public BufferedReader getAsReader() { 48 | return new BufferedReader(new InputStreamReader(responseStream)); 49 | } 50 | 51 | /** 52 | * Get the body as a string 53 | * @param includeLines include line breaks 54 | * @return the string as requested 55 | */ 56 | public String getAsString(boolean includeLines) { 57 | if (includeLines) { 58 | return getAsString(); 59 | } 60 | 61 | return getAsString().replaceAll("\n", ""); 62 | } 63 | 64 | /** 65 | * @return body as String 66 | */ 67 | public String getAsString() { 68 | return parsed; 69 | } 70 | 71 | /** 72 | * @return body as int 73 | */ 74 | public int getAsInt() { 75 | return Integer.parseInt(getAsString()); 76 | } 77 | 78 | /** 79 | * @return body as double 80 | */ 81 | public double getAsDouble() { 82 | return Double.parseDouble(getAsString()); 83 | } 84 | 85 | /** 86 | * @return body as short 87 | */ 88 | public short getAsShort() { 89 | return Short.parseShort(getAsString()); 90 | } 91 | 92 | /** 93 | * @return body as byte 94 | */ 95 | public byte getAsByte() { 96 | return Byte.parseByte(getAsString()); 97 | } 98 | 99 | /** 100 | * @return body as long 101 | */ 102 | public long getAsLong() { 103 | return Long.parseLong(getAsString()); 104 | } 105 | 106 | /** 107 | * @return body as float 108 | */ 109 | public float getAsFloat() { 110 | return Float.parseFloat(getAsString()); 111 | } 112 | 113 | /** 114 | * @return body as boolean 115 | */ 116 | public boolean getAsBoolean() { 117 | return Boolean.parseBoolean(getAsString()); 118 | } 119 | 120 | /** 121 | * @return body as char 122 | */ 123 | public char getAsCharacter() { 124 | String str = getAsString(); 125 | if (str.length() == 0) { 126 | return (char) 0; 127 | } 128 | 129 | return str.charAt(0); 130 | } 131 | 132 | /** 133 | * Generic primitive get as method 134 | * @param type the primitive box type's class 135 | * @param the returned value type 136 | * @return the value as type T 137 | */ 138 | public T getAs(Class type) { 139 | String asString = getAsString(); 140 | if (type == String.class) { 141 | return type.cast(asString); 142 | } else if (type == Integer.class) { 143 | return type.cast(getAsInt()); 144 | } else if (type == Double.class) { 145 | return type.cast(getAsDouble()); 146 | } else if (type == Short.class) { 147 | return type.cast(getAsShort()); 148 | } else if (type == Long.class) { 149 | return type.cast(getAsLong()); 150 | } else if (type == Float.class) { 151 | return type.cast(getAsFloat()); 152 | } else if (type == Byte.class) { 153 | return type.cast(getAsByte()); 154 | } else if (type == Boolean.class) { 155 | return type.cast(getAsBoolean()); 156 | } else { 157 | throw new IllegalStateException("This state should not be reachable"); 158 | } 159 | } 160 | 161 | private String parse() { 162 | try { 163 | try (BufferedReader reader = this.getAsReader()) { 164 | String line; 165 | StringBuilder resultB = new StringBuilder(); 166 | while ((line = reader.readLine()) != null) { 167 | resultB.append(line); 168 | resultB.append("\n"); 169 | } 170 | 171 | return resultB.toString(); 172 | } 173 | } catch (IOException e) { 174 | e.printStackTrace(); 175 | return ""; 176 | } 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/request/RequestParams.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.request; 20 | 21 | import dev.yasper.rump.config.RequestConfig; 22 | 23 | import java.net.URLEncoder; 24 | import java.nio.charset.Charset; 25 | import java.nio.charset.StandardCharsets; 26 | import java.util.HashMap; 27 | import java.util.Map; 28 | import java.util.Set; 29 | import java.util.function.Supplier; 30 | 31 | /** 32 | *

33 | * Class that contains request params. Can be constructed to a url part by calling {@link RequestParams#toURLPart()}. 34 | * Can otherwise also be provided via {@link RequestConfig#setParams(RequestParams)}. 35 | *

36 | */ 37 | public class RequestParams { 38 | 39 | private final Map> requestParams = new HashMap<>(); 40 | private boolean encoded = true; 41 | private Charset charset = StandardCharsets.UTF_8; 42 | 43 | /** 44 | * Converts this RequestParams instance to URL part to be added at the end of a URL. 45 | * Uses {@link RequestParams#charset} and {@link RequestParams#encoded} to determine 46 | * how the URL should be constructed. 47 | * 48 | * @return The part of the URL to be appended at the end 49 | */ 50 | public String toURLPart() { 51 | if (requestParams.size() == 0) { 52 | return ""; 53 | } 54 | 55 | StringBuilder result = new StringBuilder("?"); 56 | int index = 0; 57 | Set keySet = requestParams.keySet(); 58 | for (String key : keySet) { 59 | if (index > 0) { 60 | result.append("&"); 61 | } 62 | 63 | result.append(key); 64 | result.append("="); 65 | 66 | String value = requestParams.get(key).get(); 67 | result.append(isEncoded() ? URLEncoder.encode(value, getCharset()) : requestParams.get(key)); 68 | index++; 69 | } 70 | 71 | return result.toString(); 72 | } 73 | 74 | /** 75 | * Add a string request param 76 | * 77 | * @param key The param's key 78 | * @param value The param's value 79 | * @return this {@link RequestParams} instance to be used for setter chaining 80 | */ 81 | public RequestParams add(String key, String value) { 82 | return add(key, () -> value); 83 | } 84 | 85 | /** 86 | * Add an object request param, the object is converted to string by calling toString(); 87 | * 88 | * @param key The param's key 89 | * @param value The param's value 90 | * @return this {@link RequestParams} instance to be used for setter chaining 91 | */ 92 | public RequestParams add(String key, Object value) { 93 | return add(key, value::toString); 94 | } 95 | 96 | /** 97 | * Add an supplier request param which will be evaluated upon constructing the url. 98 | * 99 | * @param key The param's key 100 | * @param dynamicValue The param's value supplier 101 | * @return this {@link RequestParams} instance to be used for setter chaining 102 | */ 103 | public RequestParams add(String key, Supplier dynamicValue) { 104 | this.requestParams.put(key, dynamicValue); 105 | return this; 106 | } 107 | 108 | /** 109 | * True if the params should be encoded using {@link URLEncoder} 110 | * 111 | * @return {@link RequestParams#encoded} 112 | */ 113 | public boolean isEncoded() { 114 | return this.encoded; 115 | } 116 | 117 | /** 118 | * @param encoded New value for {@link RequestParams#encoded} 119 | * @return this {@link RequestParams} instance to be used for setter chaining 120 | */ 121 | public RequestParams setEncoded(boolean encoded) { 122 | this.encoded = encoded; 123 | return this; 124 | } 125 | 126 | /** 127 | * The charset that should be passed to {@link URLEncoder#encode(String, String)} if the params 128 | * are encoded. 129 | * 130 | * @return {@link RequestParams#charset} 131 | */ 132 | public Charset getCharset() { 133 | return this.charset; 134 | } 135 | 136 | /** 137 | * @param charset New value for {@link RequestParams#charset} 138 | * @return this {@link RequestParams} instance to be used for setter chaining 139 | */ 140 | public RequestParams setCharset(Charset charset) { 141 | this.charset = charset; 142 | return this; 143 | } 144 | 145 | /** 146 | * Converts this RequestParams instance to a RequestConfig instance for request overloading. 147 | * See {@link dev.yasper.rump.client.DefaultRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} 148 | * for more information. 149 | * 150 | * @return The RequestConfig instance 151 | */ 152 | public RequestConfig toConfig() { 153 | return new RequestConfig() 154 | .setParams(this); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/HeaderNames.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump; 20 | 21 | public class HeaderNames { 22 | private HeaderNames(){} 23 | 24 | /** RFC 2616 (HTTP/1.1) Section 14.1 */ 25 | public static final String ACCEPT = "Accept"; 26 | 27 | /** RFC 2616 (HTTP/1.1) Section 14.2 */ 28 | public static final String ACCEPT_CHARSET = "Accept-Charset"; 29 | 30 | /** RFC 2616 (HTTP/1.1) Section 14.3 */ 31 | public static final String ACCEPT_ENCODING = "Accept-Encoding"; 32 | 33 | /** RFC 2616 (HTTP/1.1) Section 14.4 */ 34 | public static final String ACCEPT_LANGUAGE = "Accept-Language"; 35 | 36 | /** RFC 2616 (HTTP/1.1) Section 14.5 */ 37 | public static final String ACCEPT_RANGES = "Accept-Ranges"; 38 | 39 | /** RFC 2616 (HTTP/1.1) Section 14.6 */ 40 | public static final String AGE = "Age"; 41 | 42 | /** RFC 1945 (HTTP/1.0) Section 10.1, RFC 2616 (HTTP/1.1) Section 14.7 */ 43 | public static final String ALLOW = "Allow"; 44 | 45 | /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */ 46 | public static final String AUTHORIZATION = "Authorization"; 47 | 48 | /** RFC 2616 (HTTP/1.1) Section 14.9 */ 49 | public static final String CACHE_CONTROL = "Cache-Control"; 50 | 51 | /** RFC 2616 (HTTP/1.1) Section 14.10 */ 52 | public static final String CONNECTION = "Connection"; 53 | 54 | /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */ 55 | public static final String CONTENT_ENCODING = "Content-Encoding"; 56 | 57 | /** RFC 2616 (HTTP/1.1) Section 14.12 */ 58 | public static final String CONTENT_LANGUAGE = "Content-Language"; 59 | 60 | /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */ 61 | public static final String CONTENT_LENGTH = "Content-Length"; 62 | 63 | /** RFC 2616 (HTTP/1.1) Section 14.14 */ 64 | public static final String CONTENT_LOCATION = "Content-Location"; 65 | 66 | /** RFC 2616 (HTTP/1.1) Section 14.15 */ 67 | public static final String CONTENT_MD5 = "Content-MD5"; 68 | 69 | /** RFC 2616 (HTTP/1.1) Section 14.16 */ 70 | public static final String CONTENT_RANGE = "Content-Range"; 71 | 72 | /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */ 73 | public static final String CONTENT_TYPE = "Content-Type"; 74 | 75 | /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */ 76 | public static final String DATE = "Date"; 77 | 78 | /** RFC 2518 (WevDAV) Section 9.1 */ 79 | public static final String DAV = "Dav"; 80 | 81 | /** RFC 2518 (WevDAV) Section 9.2 */ 82 | public static final String DEPTH = "Depth"; 83 | 84 | /** RFC 2518 (WevDAV) Section 9.3 */ 85 | public static final String DESTINATION = "Destination"; 86 | 87 | /** RFC 2616 (HTTP/1.1) Section 14.19 */ 88 | public static final String ETAG = "ETag"; 89 | 90 | /** RFC 2616 (HTTP/1.1) Section 14.20 */ 91 | public static final String EXPECT = "Expect"; 92 | 93 | /** RFC 1945 (HTTP/1.0) Section 10.7, RFC 2616 (HTTP/1.1) Section 14.21 */ 94 | public static final String EXPIRES = "Expires"; 95 | 96 | /** RFC 1945 (HTTP/1.0) Section 10.8, RFC 2616 (HTTP/1.1) Section 14.22 */ 97 | public static final String FROM = "From"; 98 | 99 | /** RFC 2616 (HTTP/1.1) Section 14.23 */ 100 | public static final String HOST = "Host"; 101 | 102 | /** RFC 2518 (WevDAV) Section 9.4 */ 103 | public static final String IF = "If"; 104 | 105 | /** RFC 2616 (HTTP/1.1) Section 14.24 */ 106 | public static final String IF_MATCH = "If-Match"; 107 | 108 | /** RFC 1945 (HTTP/1.0) Section 10.9, RFC 2616 (HTTP/1.1) Section 14.25 */ 109 | public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; 110 | 111 | /** RFC 2616 (HTTP/1.1) Section 14.26 */ 112 | public static final String IF_NONE_MATCH = "If-None-Match"; 113 | 114 | /** RFC 2616 (HTTP/1.1) Section 14.27 */ 115 | public static final String IF_RANGE = "If-Range"; 116 | 117 | /** RFC 2616 (HTTP/1.1) Section 14.28 */ 118 | public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; 119 | 120 | /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */ 121 | public static final String LAST_MODIFIED = "Last-Modified"; 122 | 123 | /** RFC 1945 (HTTP/1.0) Section 10.11, RFC 2616 (HTTP/1.1) Section 14.30 */ 124 | public static final String LOCATION = "Location"; 125 | 126 | /** RFC 2518 (WevDAV) Section 9.5 */ 127 | public static final String LOCK_TOKEN = "Lock-Token"; 128 | 129 | /** RFC 2616 (HTTP/1.1) Section 14.31 */ 130 | public static final String MAX_FORWARDS = "Max-Forwards"; 131 | 132 | /** RFC 2518 (WevDAV) Section 9.6 */ 133 | public static final String OVERWRITE = "Overwrite"; 134 | 135 | /** RFC 1945 (HTTP/1.0) Section 10.12, RFC 2616 (HTTP/1.1) Section 14.32 */ 136 | public static final String PRAGMA = "Pragma"; 137 | 138 | /** RFC 2616 (HTTP/1.1) Section 14.33 */ 139 | public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; 140 | 141 | /** RFC 2616 (HTTP/1.1) Section 14.34 */ 142 | public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; 143 | 144 | /** RFC 2616 (HTTP/1.1) Section 14.35 */ 145 | public static final String RANGE = "Range"; 146 | 147 | /** RFC 1945 (HTTP/1.0) Section 10.13, RFC 2616 (HTTP/1.1) Section 14.36 */ 148 | public static final String REFERER = "Referer"; 149 | 150 | /** RFC 2616 (HTTP/1.1) Section 14.37 */ 151 | public static final String RETRY_AFTER = "Retry-After"; 152 | 153 | /** RFC 1945 (HTTP/1.0) Section 10.14, RFC 2616 (HTTP/1.1) Section 14.38 */ 154 | public static final String SERVER = "Server"; 155 | 156 | /** RFC 2518 (WevDAV) Section 9.7 */ 157 | public static final String STATUS_URI = "Status-URI"; 158 | 159 | /** RFC 2616 (HTTP/1.1) Section 14.39 */ 160 | public static final String TE = "TE"; 161 | 162 | /** RFC 2518 (WevDAV) Section 9.8 */ 163 | public static final String TIMEOUT = "Timeout"; 164 | 165 | /** RFC 2616 (HTTP/1.1) Section 14.40 */ 166 | public static final String TRAILER = "Trailer"; 167 | 168 | /** RFC 2616 (HTTP/1.1) Section 14.41 */ 169 | public static final String TRANSFER_ENCODING = "Transfer-Encoding"; 170 | 171 | /** RFC 2616 (HTTP/1.1) Section 14.42 */ 172 | public static final String UPGRADE = "Upgrade"; 173 | 174 | /** RFC 1945 (HTTP/1.0) Section 10.15, RFC 2616 (HTTP/1.1) Section 14.43 */ 175 | public static final String USER_AGENT = "User-Agent"; 176 | 177 | /** RFC 2616 (HTTP/1.1) Section 14.44 */ 178 | public static final String VARY = "Vary"; 179 | 180 | /** RFC 2616 (HTTP/1.1) Section 14.45 */ 181 | public static final String VIA = "Via"; 182 | 183 | /** RFC 2616 (HTTP/1.1) Section 14.46 */ 184 | public static final String WARNING = "Warning"; 185 | 186 | /** RFC 1945 (HTTP/1.0) Section 10.16, RFC 2616 (HTTP/1.1) Section 14.47 */ 187 | public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; 188 | } 189 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/Rump.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump; 20 | 21 | import dev.yasper.rump.client.AsyncRestClient; 22 | import dev.yasper.rump.client.DefaultRestClient; 23 | import dev.yasper.rump.client.RestClient; 24 | import dev.yasper.rump.config.RequestConfig; 25 | import dev.yasper.rump.exception.DefaultExceptionHandler; 26 | import dev.yasper.rump.request.JacksonRequestTransformer; 27 | import dev.yasper.rump.request.RequestMethod; 28 | import dev.yasper.rump.request.RequestParams; 29 | import dev.yasper.rump.response.HttpResponse; 30 | import dev.yasper.rump.response.JacksonResponseTransformer; 31 | 32 | import java.io.IOException; 33 | import java.util.LinkedList; 34 | import java.util.concurrent.CompletableFuture; 35 | import java.util.concurrent.ExecutorService; 36 | import java.util.concurrent.Executors; 37 | 38 | /** 39 | * Main entry point for Rump. 40 | * See {@link DefaultRestClient} or {@link AsyncRestClient} for better documentation on the methods. 41 | * This class just encapsulates two instances of those clients for its methods. 42 | */ 43 | public class Rump { 44 | 45 | /** 46 | * Default config values for Rump 47 | */ 48 | public static final RequestConfig DEFAULT_CONFIG = new RequestConfig() 49 | .setBaseURL("") 50 | .setTimeout(7500) 51 | .setReadTimeout(7500) 52 | .setUseCaches(false) 53 | .setRequestHeaders(new Headers()) 54 | .setParams(new RequestParams()) 55 | .setRequestTransformer(new JacksonRequestTransformer()) 56 | .setResponseTransformer(new JacksonResponseTransformer()) 57 | .setRequestInterceptors(new LinkedList<>()) 58 | .setResponseInterceptors(new LinkedList<>()) 59 | .setMethod(RequestMethod.GET) 60 | .setIgnoreStatusCode((val) -> false) 61 | .setExceptionHandler(new DefaultExceptionHandler()) 62 | .setConnectionConsumer((connection -> { 63 | })); 64 | private static final ExecutorService DEFAULT_EXECUTOR = Executors.newFixedThreadPool(5); 65 | private static final DefaultRestClient DEFAULT_CLIENT = DefaultRestClient.create(DEFAULT_CONFIG); 66 | private static final AsyncRestClient ASYNC_CLIENT = new AsyncRestClient(DEFAULT_CLIENT, DEFAULT_EXECUTOR); 67 | 68 | public static T requestForObject(String path, RequestMethod method, Class responseType, RequestConfig... configs) throws IOException { 69 | return DEFAULT_CLIENT.requestForObject(path, method, null, responseType, configs); 70 | } 71 | 72 | public static T getForObject(String path, Class responseType, RequestConfig... configs) throws IOException { 73 | return DEFAULT_CLIENT.getForObject(path, responseType, configs); 74 | } 75 | 76 | public static T postForObject(String path, Object requestBody, Class responseType, RequestConfig... configs) throws IOException { 77 | return DEFAULT_CLIENT.postForObject(path, requestBody, responseType, configs); 78 | } 79 | 80 | public static T putForObject(String path, Object requestBody, Class responseType, RequestConfig... configs) throws IOException { 81 | return DEFAULT_CLIENT.putForObject(path, requestBody, responseType, configs); 82 | } 83 | 84 | public static T deleteForObject(String path, Class responseType, RequestConfig... configs) throws IOException { 85 | return DEFAULT_CLIENT.deleteForObject(path, responseType, configs); 86 | } 87 | 88 | public static HttpResponse get(String path, Class responseType, RequestConfig... configs) throws IOException { 89 | return DEFAULT_CLIENT.get(path, responseType, configs); 90 | } 91 | 92 | public static HttpResponse post(String path, Object requestBody, Class responseType, RequestConfig... configs) throws IOException { 93 | return DEFAULT_CLIENT.post(path, requestBody, responseType, configs); 94 | } 95 | 96 | public static HttpResponse put(String path, Object requestBody, Class responseType, RequestConfig... configs) throws IOException { 97 | return DEFAULT_CLIENT.put(path, requestBody, responseType, configs); 98 | } 99 | 100 | public static HttpResponse delete(String path, Class responseType, RequestConfig... configs) throws IOException { 101 | return DEFAULT_CLIENT.delete(path, responseType, configs); 102 | } 103 | 104 | public static HttpResponse head(String path, RequestConfig... configs) throws IOException { 105 | return DEFAULT_CLIENT.head(path, configs); 106 | } 107 | 108 | public static HttpResponse request(String path, Object requestBody, 109 | Class responseType, RequestConfig... configs) throws IOException { 110 | return DEFAULT_CLIENT.request(path, requestBody, responseType, configs); 111 | } 112 | 113 | public static CompletableFuture requestForObjectAsync(String path, RequestMethod method, Object requestBody, Class responseType, RequestConfig... configs) { 114 | return ASYNC_CLIENT.requestForObject(path, method, requestBody, responseType, configs); 115 | } 116 | 117 | public static CompletableFuture getForObjectAsync(String path, Class responseType, RequestConfig... configs) { 118 | return ASYNC_CLIENT.getForObject(path, responseType, configs); 119 | } 120 | 121 | public static CompletableFuture postForObjectAsync(String path, Object requestBody, Class responseType, RequestConfig... configs) { 122 | return ASYNC_CLIENT.postForObject(path, requestBody, responseType, configs); 123 | } 124 | 125 | public static CompletableFuture putForObjectAsync(String path, Object requestBody, Class responseType, RequestConfig... configs) { 126 | return ASYNC_CLIENT.putForObject(path, requestBody, responseType, configs); 127 | } 128 | 129 | public static CompletableFuture deleteForObjectAsync(String path, Class responseType, RequestConfig... configs) { 130 | return ASYNC_CLIENT.deleteForObject(path, responseType, configs); 131 | } 132 | 133 | public static CompletableFuture> getAsync(String path, Class responseType, RequestConfig... configs) { 134 | return ASYNC_CLIENT.get(path, responseType, configs); 135 | } 136 | 137 | public static CompletableFuture> postAsync(String path, Object requestBody, Class responseType, RequestConfig... configs) { 138 | return ASYNC_CLIENT.post(path, requestBody, responseType, configs); 139 | } 140 | 141 | public static CompletableFuture> putAsync(String path, Object requestBody, Class responseType, RequestConfig... configs) { 142 | return ASYNC_CLIENT.put(path, requestBody, responseType, configs); 143 | } 144 | 145 | public static CompletableFuture> deleteAsync(String path, Class responseType, RequestConfig... configs) { 146 | return ASYNC_CLIENT.delete(path, responseType, configs); 147 | } 148 | 149 | public static CompletableFuture> headAsync(String path, RequestConfig... configs) { 150 | return ASYNC_CLIENT.head(path, configs); 151 | } 152 | 153 | public static CompletableFuture> requestAsync(String path, RequestMethod method, Object requestBody, 154 | Class responseType, RequestConfig... configs) { 155 | return ASYNC_CLIENT.request(path, method, requestBody, responseType); 156 | } 157 | 158 | /** 159 | * Create a {@link RestClient} instance. 160 | * 161 | * @param config The config from which to construct the client 162 | * @param async Whether or not the returned client should be for async requests 163 | * @return The constructed {@link RestClient} 164 | */ 165 | public static RestClient create(RequestConfig config, boolean async) { 166 | DefaultRestClient backing = DefaultRestClient.create(config); 167 | if (async) { 168 | return new AsyncRestClient(backing, DEFAULT_EXECUTOR); 169 | } 170 | 171 | return backing; 172 | } 173 | 174 | /** 175 | * Creates a {@link DefaultRestClient} instance 176 | * 177 | * @param config The config from which to construct the client 178 | * @return The constructed {@link DefaultRestClient} 179 | */ 180 | public static DefaultRestClient createDefault(RequestConfig config) { 181 | return DefaultRestClient.create(config); 182 | } 183 | 184 | /** 185 | * Creates an {@link AsyncRestClient} instance 186 | * 187 | * @param config The config from which to construct the client 188 | * @param executor The executor to construct this instance from. See {@link Executors} to construct an executor. 189 | * @return The constructed {@link AsyncRestClient} 190 | */ 191 | public static AsyncRestClient createAsync(RequestConfig config, ExecutorService executor) { 192 | return new AsyncRestClient(DefaultRestClient.create(config), executor); 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rump 2 | Rump is a REST client for Java that attempts to resemble Axios from JavaScript. 3 | 4 | [![Actions Status](https://github.com/Jasper-ketelaar/Rump/workflows/Verify/badge.svg)](https://github.com/Jasper-ketelaar/Rump/actions) 5 | [![Maven Status](https://maven-badges.herokuapp.com/maven-central/dev.yasper/rump/badge.svg)](https://search.maven.org/artifact/dev.yasper/rump/1.0.6/jar) 6 | [![Javadocs](http://www.javadoc.io/badge/dev.yasper/rump.svg)](http://www.javadoc.io/doc/dev.yasper/rump) 7 | ## Install with Maven 8 | ```xml 9 | 10 | dev.yasper 11 | rump 12 | 1.0.6 13 | 14 | ``` 15 | 16 | ## Why 17 | I was working on a project and none of the currently available REST clients for Java seemed to match my needs. I am a pretty big fan of Axios for JavaScript 18 | so I decided to make a version of that for Java that would fit my needs. 19 | 20 | ## Features 21 | - Create rest requests synchronously 22 | - Create rest requests asynchronously 23 | - Custom response mapper support by modifying request config (By default Rump uses Jackson) 24 | - Customer request body mapper support (By default Rump uses Jackson) 25 | - Request transformation before sending it out 26 | - Intercept requests/responses to modify them 27 | - Canceling of requests by using a request interceptor 28 | - Canceling of responses by using a response interceptor 29 | - Creation of instances is fast and easy due to chaining of calls, and the ability to have multiple configs per request 30 | 31 | ## Basic Usage 32 | There's three different ways of making REST api calls with Rump: 33 | 34 | ### 1. Via the Rump class you can make requests directly. 35 | 36 | a) Synchronous 37 | ```java 38 | try { 39 | HttpResponse res = Rump.get("https://jsonplaceholder.typicode.com/posts/1", Post.class); 40 | Post post = res.getBody(); 41 | // Do something with post 42 | } catch (IOException e) { 43 | e.printStackTrace(); 44 | } 45 | ``` 46 | 47 | b) Asynchronous 48 | ```java 49 | Rump.getAsync("https://jsonplaceholder.typicode.com/posts/1", Post.class).thenAccept(res -> { 50 | Post post = res.getBody(); 51 | // Do something with post 52 | }); 53 | 54 | ``` 55 | 56 | ### 2. Synchronously using a DefaultRestClient instance 57 | ```java 58 | RequestConfig config = new RequestConfig() 59 | .setBaseURL("https://jsonplaceholder.typicode.com/"); 60 | DefaultRestClient drs = Rump.createDefault(config); 61 | 62 | try { 63 | HttpResponse res = drs.get("posts/1", Post.class); 64 | Post post = res.getBody(); 65 | // Do something with post 66 | } catch (IOException e) { 67 | e.printStackTrace(); 68 | } 69 | ``` 70 | 71 | ### 3. Asynchronously using an AsyncRestClient instance 72 | ```java 73 | RequestConfig config = new RequestConfig() 74 | .setBaseURL("https://jsonplaceholder.typicode.com/"); 75 | AsyncRestClient ars = Rump.createAsync(config, Executors.newFixedThreadPool(1)); 76 | ars.get("posts/1", Post.class).thenAccept(res -> { 77 | Post post = res.getBody(); 78 | // Do something with post 79 | }); 80 | ``` 81 | 82 | ## Request Configuration 83 | Requests are configured using the `RequestConfig` class. By default request config supports most 84 | configuratble options for a `HttpURLConnection` however any option not supported by this 85 | class can be modified using the `connectionConsumer` in `RequestConfig`. I can also add more options 86 | to the request configuration, just create an issue. 87 | 88 | ## HttpResponse 89 | The HttpResponse contains the following values: 90 | - The response code 91 | - The response message 92 | - The config used for the request that generated this response 93 | - The headers that the server responded with 94 | - The response body mapped as the type you requested 95 | 96 | The HttpResponse object will also be returned in case of an error, however 97 | the response body will not be mapped to your requested type but will be kept as 98 | a string. 99 | 100 | ## Overriding config values 101 | Sometimes your default config values, whether they come from a constructed instance or 102 | simply the default values supplied by Rump, are not enough for a specific request. 103 | 104 | This is where config overriding comes in. Rump supports config overriding 105 | by appending any number of configs to a request. A call could look like this: 106 | ` Rump.get("https://jsonplaceholder.typicode.com/posts/1", Post.class, config1, config2, config3);`. 107 | In this example the precedence taken is whatever config supplies the value last. 108 | For example, if the default config, config1, config2 and config3 all have a different value set for reqeust params 109 | then the values of config3 will be used in the request. 110 | 111 | To make it easier to construct config instances based of certain configurable request 112 | values, Rump gives you the option to convert a certain configurable instance such as 113 | RequestHeaders to a RequestConfig instance. An example could look like this: 114 | ```java 115 | RequestConfig params = new RequestParams() 116 | .add("test", 1) 117 | .toConfig(); 118 | 119 | RequestConfig headers = new RequestHeaders() 120 | .setAuthentication("Bearer token") 121 | .setContentType(RequestHeaders.ContentType.JSON) 122 | .setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36") 123 | .toConfig(); 124 | 125 | try { 126 | // Params from default config are now overridden and headers from default config are now merged together 127 | HttpResponse res = Rump.get("https://jsonplaceholder.typicode.com/posts/1", Post.class, params, headers); 128 | Post post = res.getBody(); 129 | // Do something with post 130 | } catch (IOException e) { 131 | e.printStackTrace(); 132 | } 133 | ``` 134 | 135 | ### Overriding config defaults 136 | With an instance created by Rump you can set the defaults yourself by the RequestConfig 137 | instance you passed. If you want to modify the defaults used by the backing instance for the static 138 | methods inside `Rump.java` then you can modify the constant `Rump.DEFAULT_CONFIG`. If you want 139 | to change the default base url for all static methods for example: 140 | ```java 141 | Rump.DEFAULT_CONFIG.setBaseURL("https://www.new-default.org"); 142 | ``` 143 | 144 | ## Mappers 145 | Rump supports configurable object mapping, but by default it uses Jackson. You can map request bodies 146 | using the `RequestTransformer` interface and overriding the config value. You can map response 147 | bodies by using the `ResponseTransformer` interface and overriding the config value. You can look at 148 | `JacksonRequestTransformer` and `JacksonResponseTransformer` for examples. 149 | 150 | ## Interceptors 151 | Interceptors can be used to intercept requests before they are fired and 152 | intercept responses before they are returned. For the request this can be used 153 | to modify the config or cancel the request completely. For the response these can be used 154 | to add a default error handler or a default response data transformation. 155 | 156 | ### Request interceptor 157 | A request interceptor could look like this: 158 | ```java 159 | RequestConfig config = new RequestConfig() 160 | .addRequestInterceptor((mergedURL, connection, config1) -> { 161 | if (mergedURL.startsWith("https://www.mydomain.com")) { 162 | connection.setRequestProperty("Authorization", "Bearer myDomainToken"); 163 | } 164 | return true; 165 | }); 166 | DefaultRestClient drs = Rump.createDefault(config); 167 | ``` 168 | 169 | Here we check if the domain we are sending a request to matches `https://www.mydomain.com` and if 170 | so we will append our authorization token for this domain to the header of that specific request. 171 | Please note that Rump applies the config values before calling the request interceptor 172 | so modifying the config values will have no effect on the request. Unless you added 173 | a response specific config value such as adding a response interceptor at this stage. 174 | 175 | ### Response interceptor 176 | A response interceptor could look like this: 177 | ```java 178 | RequestConfig config = new RequestConfig() 179 | .setBaseURL("https://jsonplaceholder.typicode.com/") 180 | .addResponseInterceptor(res -> { 181 | Object body = res.getBody(); 182 | if (body instanceof Post) { 183 | Post post = (Post) body; 184 | post.setTitle(String.format("[INTERCEPTED] %s", post.getTitle())); 185 | } 186 | return true; 187 | }); 188 | 189 | DefaultRestClient drs = Rump.createDefault(config); 190 | ``` 191 | 192 | Now whenever the response body is of type Post the interceptor will activate and 193 | modify the post's title appending [INTERCEPTED]. A sample request could be like this: 194 | ```java 195 | HttpResponse res = drs.get("posts/1", Post.class); 196 | System.out.println(res.getBody().getTitle()); 197 | ``` 198 | Output: 199 | ``` 200 | [INTERCEPTED] sunt aut facere repellat provident occaecati excepturi optio reprehenderit 201 | ``` 202 | 203 | ## Error handling 204 | Response status errors (any response status code above 299) are thrown as `HttpStatusCodeException`. 205 | These are thrown as completion errors within the async functionality of Rump. You are able to modify 206 | what status codes are considered as errors by adjusting `ignoreStatusCode` in `RequestConfig`. For example: 207 | ```java 208 | RequestConfig config = new RequestConfig() 209 | .setIgnoreStatusCode((code) -> code < 400); 210 | ``` 211 | Config now doesn't throw an error if the status code is between 300 and 399. 212 | 213 | The `HttpStatusCodeException` contains a `HttpResponse` where the error body is of string value. 214 | You can therefore easily inspect values of the error response the same way you would 215 | check values of a successful response. 216 | 217 | `RequestConfig` also has a value `exceptionHandler` that can be modified to change the default 218 | exception behaviour. `DefaultExceptionHandler` is the default exception handler that simply 219 | thros the `HttpStatusCodeException` that it is passed. 220 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/config/RequestConfig.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.config; 20 | 21 | import dev.yasper.rump.Headers; 22 | import dev.yasper.rump.exception.ExceptionHandler; 23 | import dev.yasper.rump.interceptor.RequestInterceptor; 24 | import dev.yasper.rump.interceptor.ResponseInterceptor; 25 | import dev.yasper.rump.request.RequestMethod; 26 | import dev.yasper.rump.request.RequestParams; 27 | import dev.yasper.rump.request.RequestTransformer; 28 | import dev.yasper.rump.response.ResponseTransformer; 29 | 30 | import java.lang.reflect.Field; 31 | import java.net.Authenticator; 32 | import java.net.HttpURLConnection; 33 | import java.net.Proxy; 34 | import java.util.LinkedList; 35 | import java.util.List; 36 | import java.util.function.Consumer; 37 | import java.util.function.Predicate; 38 | 39 | public class RequestConfig { 40 | 41 | private String baseURL = null; 42 | private Integer timeout = null; 43 | private Integer readTimeout = null; 44 | private Boolean useCaches = null; 45 | private Proxy proxy = null; 46 | private Authenticator authenticator = null; 47 | private Headers requestHeaders = null; 48 | private RequestParams params = null; 49 | private RequestTransformer requestTransformer = null; 50 | private ResponseTransformer responseTransformer = null; 51 | private List requestInterceptors = new LinkedList<>(); 52 | private List responseInterceptors = new LinkedList<>(); 53 | private RequestMethod method = null; 54 | private ExceptionHandler exceptionHandler = null; 55 | private Predicate ignoreStatusCode = null; 56 | private Consumer connectionConsumer = null; 57 | 58 | /** 59 | * Method to copy properties from a config instance into another config instance. Checks if the values in 60 | * from are not null to prevent the config from overwriting all the other values in to. We can ignore the type 61 | * safety because the fields will always hold the same types. 62 | * 63 | * @param to The RequestConfig to copy the properties into 64 | * @param from The RequestConfig to copy the properties from 65 | */ 66 | @SuppressWarnings({"unchecked", "rawtypes"}) 67 | public static void copyProperties(RequestConfig to, RequestConfig from) { 68 | for (Field field : from.getClass().getDeclaredFields()) { 69 | try { 70 | field.setAccessible(true); 71 | Object value = field.get(from); 72 | Object current = field.get(to); 73 | if (value instanceof List && current instanceof List) { 74 | List list = (List) value; 75 | ((List) current).addAll(list); 76 | } else if (value != null) { 77 | field.set(to, value); 78 | } 79 | } catch (IllegalAccessException e) { 80 | e.printStackTrace(); 81 | } 82 | } 83 | } 84 | 85 | @Override 86 | public String toString() { 87 | return "RequestConfig{" + "baseURL='" + baseURL + '\'' + 88 | ", timeout=" + timeout + 89 | ", readTimeout=" + readTimeout + 90 | ", useCaches=" + useCaches + 91 | ", proxy=" + proxy + 92 | ", authenticator=" + authenticator + 93 | ", requestHeaders=" + requestHeaders + 94 | ", params=" + params + 95 | ", requestTransformer=" + requestTransformer + 96 | ", responseTransformer=" + responseTransformer + 97 | ", requestInterceptors=" + requestInterceptors + 98 | ", responseInterceptors=" + responseInterceptors + 99 | ", method=" + method + 100 | ", ignoreStatusCode=" + ignoreStatusCode + 101 | ", connectionConsumer=" + connectionConsumer + 102 | '}'; 103 | } 104 | 105 | public boolean isOutputting() { 106 | return getMethod() == RequestMethod.POST || getMethod() == RequestMethod.PUT; 107 | } 108 | 109 | public Authenticator getAuthenticator() { 110 | return authenticator; 111 | } 112 | 113 | public RequestConfig setAuthenticator(Authenticator authenticator) { 114 | this.authenticator = authenticator; 115 | return this; 116 | } 117 | 118 | public ExceptionHandler getExceptionHandler() { 119 | return exceptionHandler; 120 | } 121 | 122 | public RequestConfig setExceptionHandler(ExceptionHandler exceptionHandler) { 123 | this.exceptionHandler = exceptionHandler; 124 | return this; 125 | } 126 | 127 | public Predicate getIgnoreStatusCode() { 128 | return ignoreStatusCode; 129 | } 130 | 131 | public RequestConfig setIgnoreStatusCode(Predicate ignoreStatusCode) { 132 | this.ignoreStatusCode = ignoreStatusCode; 133 | return this; 134 | } 135 | 136 | public Consumer getConnectionConsumer() { 137 | return connectionConsumer; 138 | } 139 | 140 | public RequestConfig setConnectionConsumer(Consumer connectionConsumer) { 141 | this.connectionConsumer = connectionConsumer; 142 | return this; 143 | } 144 | 145 | /** 146 | * Create a new request config that is a non-null merger of this instance and the passed merging instances 147 | * 148 | * @param merging varag request config array to merge this instance with 149 | * @return The create request config 150 | */ 151 | public RequestConfig merge(RequestConfig... merging) { 152 | RequestConfig result = new RequestConfig(); 153 | RequestConfig.copyProperties(result, this); 154 | for (RequestConfig merge : merging) { 155 | RequestConfig.copyProperties(result, merge); 156 | } 157 | 158 | return result; 159 | } 160 | 161 | public Proxy getProxy() { 162 | return proxy; 163 | } 164 | 165 | public RequestConfig setProxy(Proxy proxy) { 166 | this.proxy = proxy; 167 | return this; 168 | } 169 | 170 | public RequestConfig addRequestInterceptor(RequestInterceptor interceptor) { 171 | this.requestInterceptors.add(interceptor); 172 | return this; 173 | } 174 | 175 | public RequestConfig addResponseInterceptor(ResponseInterceptor interceptor) { 176 | this.responseInterceptors.add(interceptor); 177 | return this; 178 | } 179 | 180 | public String getBaseURL() { 181 | return this.baseURL; 182 | } 183 | 184 | public RequestConfig setBaseURL(String baseURL) { 185 | this.baseURL = baseURL; 186 | return this; 187 | } 188 | 189 | public int getTimeout() { 190 | return this.timeout; 191 | } 192 | 193 | public RequestConfig setTimeout(int timeout) { 194 | this.timeout = timeout; 195 | return this; 196 | } 197 | 198 | public int getReadTimeout() { 199 | return this.readTimeout; 200 | } 201 | 202 | public RequestConfig setReadTimeout(int readTimeout) { 203 | this.readTimeout = readTimeout; 204 | return this; 205 | } 206 | 207 | public Headers getRequestHeaders() { 208 | return this.requestHeaders; 209 | } 210 | 211 | public RequestConfig setRequestHeaders(Headers requestHeaders) { 212 | this.requestHeaders = requestHeaders; 213 | return this; 214 | } 215 | 216 | public Boolean isUsingCaches() { 217 | return this.useCaches; 218 | } 219 | 220 | public RequestParams getParams() { 221 | return this.params; 222 | } 223 | 224 | public RequestConfig setParams(RequestParams params) { 225 | this.params = params; 226 | return this; 227 | } 228 | 229 | public RequestTransformer getRequestTransformer() { 230 | return this.requestTransformer; 231 | } 232 | 233 | public RequestConfig setRequestTransformer(RequestTransformer requestTransformer) { 234 | this.requestTransformer = requestTransformer; 235 | return this; 236 | } 237 | 238 | public ResponseTransformer getResponseTransformer() { 239 | return this.responseTransformer; 240 | } 241 | 242 | public RequestConfig setResponseTransformer(ResponseTransformer responseTransformer) { 243 | this.responseTransformer = responseTransformer; 244 | return this; 245 | } 246 | 247 | public List getRequestInterceptors() { 248 | return this.requestInterceptors; 249 | } 250 | 251 | public RequestConfig setRequestInterceptors(List requestInterceptors) { 252 | this.requestInterceptors = requestInterceptors; 253 | return this; 254 | } 255 | 256 | public List getResponseInterceptors() { 257 | return this.responseInterceptors; 258 | } 259 | 260 | public RequestConfig setResponseInterceptors(List responseInterceptors) { 261 | this.responseInterceptors = responseInterceptors; 262 | return this; 263 | } 264 | 265 | public RequestMethod getMethod() { 266 | return this.method; 267 | } 268 | 269 | public RequestConfig setMethod(RequestMethod method) { 270 | this.method = method; 271 | return this; 272 | } 273 | 274 | public RequestConfig setUseCaches(boolean useCaches) { 275 | this.useCaches = useCaches; 276 | return this; 277 | } 278 | } 279 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/client/AsyncRestClient.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.client; 20 | 21 | import dev.yasper.rump.config.RequestConfig; 22 | import dev.yasper.rump.exception.HttpStatusCodeException; 23 | import dev.yasper.rump.request.RequestMethod; 24 | import dev.yasper.rump.response.HttpResponse; 25 | 26 | import java.io.IOException; 27 | import java.util.concurrent.CompletableFuture; 28 | import java.util.concurrent.CompletionException; 29 | import java.util.concurrent.ExecutorService; 30 | 31 | public class AsyncRestClient implements RestClient { 32 | 33 | private final DefaultRestClient backing; 34 | private final ExecutorService executor; 35 | 36 | /** 37 | * Constructor for AsyncRestClient 38 | * 39 | * @param backing The backing default (sync) rest client 40 | * @param executor The executor for this rest client 41 | */ 42 | public AsyncRestClient(DefaultRestClient backing, ExecutorService executor) { 43 | this.backing = backing; 44 | this.executor = executor; 45 | } 46 | 47 | /** 48 | * Get the backing executor 49 | * 50 | * @return the executor 51 | */ 52 | public ExecutorService getExecutor() { 53 | return executor; 54 | } 55 | 56 | /** 57 | * Calls {@link AsyncRestClient#requestForObject(String, RequestMethod, Object, Class, RequestConfig...)} using the 58 | * passed parameters and RequestMethod.GET 59 | * 60 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 61 | * @param responseType The type to parse the response as 62 | * @param merging The configs to overload the request with 63 | * @param The type of the response 64 | * @return A {@link CompletableFuture} containing just the response body of a {@link HttpResponse}. 65 | */ 66 | public CompletableFuture getForObject(String path, Class responseType, RequestConfig... merging) { 67 | return requestForObject(path, RequestMethod.GET, null, responseType, merging); 68 | } 69 | 70 | /** 71 | * Calls {@link AsyncRestClient#requestForObject(String, RequestMethod, Object, Class, RequestConfig...)} using the 72 | * passed parameters and RequestMethod.POST 73 | * 74 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 75 | * @param requestBody The body to send with this request, applicable to POST and PUT only 76 | * @param responseType The type to parse the response as 77 | * @param merging The configs to overload the request with 78 | * @param The type of the response 79 | * @return A {@link CompletableFuture} containing just the response body of a {@link HttpResponse}. 80 | */ 81 | public CompletableFuture postForObject(String path, Object requestBody, Class responseType, RequestConfig... merging) { 82 | return requestForObject(path, RequestMethod.POST, requestBody, responseType, merging); 83 | } 84 | 85 | /** 86 | * Calls {@link AsyncRestClient#requestForObject(String, RequestMethod, Object, Class, RequestConfig...)} using the 87 | * passed parameters and RequestMethod.PUT 88 | * 89 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 90 | * @param requestBody The body to send with this request, applicable to POST and PUT only 91 | * @param responseType The type to parse the response as 92 | * @param merging The configs to overload the request with 93 | * @param The type of the response 94 | * @return A {@link CompletableFuture} containing just the response body of a {@link HttpResponse}. 95 | */ 96 | public CompletableFuture putForObject(String path, Object requestBody, Class responseType, RequestConfig... merging) { 97 | return requestForObject(path, RequestMethod.PUT, requestBody, responseType, merging); 98 | } 99 | 100 | /** 101 | * Calls {@link AsyncRestClient#requestForObject(String, RequestMethod, Object, Class, RequestConfig...)} using the 102 | * passed parameters and RequestMethod.DELETE 103 | * 104 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 105 | * @param responseType The type to parse the response as 106 | * @param merging The configs to overload the request with 107 | * @param The type of the response 108 | * @return A {@link CompletableFuture} containing just the response body of a {@link HttpResponse}. 109 | */ 110 | public CompletableFuture deleteForObject(String path, Class responseType, RequestConfig... merging) { 111 | return requestForObject(path, RequestMethod.DELETE, null, responseType, merging); 112 | } 113 | 114 | /** 115 | * Calls {@link AsyncRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} and maps 116 | * the response to just return the body 117 | * 118 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 119 | * @param method The method to use for this request 120 | * @param requestBody The body to send with this request, applicable to POST and PUT only 121 | * @param responseType The type to parse the response as 122 | * @param merging The configs to overload the request with 123 | * @param The type of the response 124 | * @return A {@link CompletableFuture} containing just the response body of a {@link HttpResponse}. 125 | */ 126 | public CompletableFuture requestForObject(String path, RequestMethod method, Object requestBody, 127 | Class responseType, RequestConfig... merging) { 128 | return request(path, method, requestBody, responseType, merging) 129 | .thenApply(HttpResponse::getBody); 130 | } 131 | 132 | /** 133 | * Calls {@link AsyncRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} passing the parameters 134 | * and RequestMethod.POST 135 | * 136 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 137 | * @param requestBody The body to send with this request, applicable to POST and PUT only 138 | * @param responseType The type to parse the response as 139 | * @param merging The configs to overload the request with 140 | * @param The type of the response 141 | * @return A {@link CompletableFuture} containing a {@link HttpResponse} with the response body. 142 | */ 143 | public CompletableFuture> post(String path, Object requestBody, Class responseType, 144 | RequestConfig... merging) { 145 | return request(path, RequestMethod.POST, requestBody, responseType, merging); 146 | } 147 | 148 | /** 149 | * Calls {@link AsyncRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} passing the parameters 150 | * and RequestMethod.PUT 151 | * 152 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 153 | * @param requestBody The body to send with this request, applicable to POST and PUT only 154 | * @param responseType The type to parse the response as 155 | * @param merging The configs to overload the request with 156 | * @param The type of the response 157 | * @return A {@link CompletableFuture} containing a {@link HttpResponse} with the response body. 158 | */ 159 | public CompletableFuture> put(String path, Object requestBody, Class responseType, 160 | RequestConfig... merging) { 161 | return request(path, RequestMethod.PUT, requestBody, responseType, merging); 162 | } 163 | 164 | /** 165 | * Calls {@link AsyncRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} passing the parameters 166 | * and RequestMethod.GET 167 | * 168 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 169 | * @param responseType The type to parse the response as 170 | * @param merging The configs to overload the request with 171 | * @param The type of the response 172 | * @return A {@link CompletableFuture} containing a {@link HttpResponse} with the response body. 173 | */ 174 | public CompletableFuture> get(String path, Class responseType, RequestConfig... merging) { 175 | return request(path, RequestMethod.GET, null, responseType, merging); 176 | } 177 | 178 | /** 179 | * Calls {@link AsyncRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} passing the parameters 180 | * and RequestMethod.DELETE 181 | * 182 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 183 | * @param responseType The type to parse the response as 184 | * @param merging The configs to overload the request with 185 | * @param The type of the response 186 | * @return A {@link CompletableFuture} containing a {@link HttpResponse} with the response body. 187 | */ 188 | public CompletableFuture> delete(String path, Class responseType, RequestConfig... merging) { 189 | return request(path, RequestMethod.DELETE, null, responseType, merging); 190 | } 191 | 192 | 193 | /** 194 | * Calls {@link AsyncRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} passing the parameters 195 | * and RequestMethod.HEAD 196 | * 197 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 198 | * @param merging The configs to overload the request with 199 | * @return A {@link CompletableFuture} containing a {@link HttpResponse} with no response body and the headers. 200 | */ 201 | public CompletableFuture> head(String path, RequestConfig... merging) { 202 | return request(path, RequestMethod.HEAD, null, Void.class, merging); 203 | } 204 | 205 | /** 206 | * Returns a completable version of {@link DefaultRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} by 207 | * executing the request on the passed executor. 208 | * 209 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 210 | * @param method The method to use for this request 211 | * @param requestBody The body to send with this request, applicable to POST and PUT only 212 | * @param responseType The type to parse the response as 213 | * @param merging The configs to overload the request with 214 | * @param The type of the response 215 | * @return A {@link CompletableFuture} containing a {@link HttpResponse} with the response body. 216 | */ 217 | public CompletableFuture> request(String path, RequestMethod method, Object requestBody, 218 | Class responseType, RequestConfig... merging) { 219 | return CompletableFuture.supplyAsync(() -> { 220 | try { 221 | return backing.request(path, method, requestBody, responseType, merging); 222 | } catch (IOException | HttpStatusCodeException e) { 223 | throw new CompletionException(e); 224 | } 225 | }, executor); 226 | } 227 | 228 | @Override 229 | public boolean isAsync() { 230 | return true; 231 | } 232 | } 233 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/Headers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | * 4 | * Copyright (C) 2020 Jasper Ketelaar 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump; 20 | 21 | import dev.yasper.rump.config.RequestConfig; 22 | 23 | import java.nio.charset.Charset; 24 | import java.nio.charset.StandardCharsets; 25 | import java.util.*; 26 | import java.util.function.Supplier; 27 | 28 | /** 29 | * Class for storing headers 30 | */ 31 | public class Headers { 32 | 33 | private final Map headers = new HashMap<>(); 34 | 35 | /** 36 | * Headers instance constructed from a map of header fields 37 | * @param headerFields the header fields from which this instance should be constructed 38 | */ 39 | public Headers(Map> headerFields) { 40 | for (String key : headerFields.keySet()) { 41 | headers.put(key, new SimpleHeader(key, String.join(", ", headerFields.get(key)))); 42 | } 43 | } 44 | 45 | /** 46 | * Default constructor for empty instance 47 | */ 48 | public Headers() { 49 | } 50 | 51 | public String getAccept() { 52 | return getSafeValue(HeaderNames.ACCEPT); 53 | } 54 | 55 | public Headers setAccept(String accept) { 56 | return setHeader(HeaderNames.ACCEPT, accept); 57 | } 58 | 59 | public String getAcceptCharset() { 60 | return getSafeValue(HeaderNames.ACCEPT_CHARSET); 61 | } 62 | 63 | public Headers setAcceptCharset(String accept_charset) { 64 | return setHeader(HeaderNames.ACCEPT_CHARSET, accept_charset); 65 | } 66 | 67 | public String getAcceptEncoding() { 68 | return getSafeValue(HeaderNames.ACCEPT_ENCODING); 69 | } 70 | 71 | public Headers setAcceptEncoding(String accept_encoding) { 72 | return setHeader(HeaderNames.ACCEPT_ENCODING, accept_encoding); 73 | } 74 | 75 | public String getAcceptLanguage() { 76 | return getSafeValue(HeaderNames.ACCEPT_LANGUAGE); 77 | } 78 | 79 | public Headers setAcceptLanguage(String accept_language) { 80 | return setHeader(HeaderNames.ACCEPT_LANGUAGE, accept_language); 81 | } 82 | 83 | public String getAcceptRanges() { 84 | return getSafeValue(HeaderNames.ACCEPT_RANGES); 85 | } 86 | 87 | public Headers setAcceptRanges(String accept_ranges) { 88 | return setHeader(HeaderNames.ACCEPT_RANGES, accept_ranges); 89 | } 90 | 91 | public String getAge() { 92 | return getSafeValue(HeaderNames.AGE); 93 | } 94 | 95 | public Headers setAge(String age) { 96 | return setHeader(HeaderNames.AGE, age); 97 | } 98 | 99 | public String getAllow() { 100 | return getSafeValue(HeaderNames.ALLOW); 101 | } 102 | 103 | public Headers setAllow(String allow) { 104 | return setHeader(HeaderNames.ALLOW, allow); 105 | } 106 | 107 | public String getAuthorization() { 108 | return getSafeValue(HeaderNames.AUTHORIZATION); 109 | } 110 | 111 | public Headers setAuthorization(String authorization) { 112 | return setHeader(HeaderNames.AUTHORIZATION, authorization); 113 | } 114 | 115 | public String getCacheControl() { 116 | return getSafeValue(HeaderNames.CACHE_CONTROL); 117 | } 118 | 119 | public Headers setCacheControl(String cache_control) { 120 | return setHeader(HeaderNames.CACHE_CONTROL, cache_control); 121 | } 122 | 123 | public String getConnection() { 124 | return getSafeValue(HeaderNames.CONNECTION); 125 | } 126 | 127 | public Headers setConnection(String connection) { 128 | return setHeader(HeaderNames.CONNECTION, connection); 129 | } 130 | 131 | public String getContentEncoding() { 132 | return getSafeValue(HeaderNames.CONTENT_ENCODING); 133 | } 134 | 135 | public Headers setContentEncoding(String content_encoding) { 136 | return setHeader(HeaderNames.CONTENT_ENCODING, content_encoding); 137 | } 138 | 139 | public String getContentLanguage() { 140 | return getSafeValue(HeaderNames.CONTENT_LANGUAGE); 141 | } 142 | 143 | public Headers setContentLanguage(String content_language) { 144 | return setHeader(HeaderNames.CONTENT_LANGUAGE, content_language); 145 | } 146 | 147 | public String getContentLength() { 148 | return getSafeValue(HeaderNames.CONTENT_LENGTH); 149 | } 150 | 151 | public Headers setContentLength(String content_length) { 152 | return setHeader(HeaderNames.CONTENT_LENGTH, content_length); 153 | } 154 | 155 | public String getContentLocation() { 156 | return getSafeValue(HeaderNames.CONTENT_LOCATION); 157 | } 158 | 159 | public Headers setContentLocation(String content_location) { 160 | return setHeader(HeaderNames.CONTENT_LOCATION, content_location); 161 | } 162 | 163 | public String getContentMd5() { 164 | return getSafeValue(HeaderNames.CONTENT_MD5); 165 | } 166 | 167 | public Headers setContentMd5(String content_md5) { 168 | return setHeader(HeaderNames.CONTENT_MD5, content_md5); 169 | } 170 | 171 | public String getContentRange() { 172 | return getSafeValue(HeaderNames.CONTENT_RANGE); 173 | } 174 | 175 | public Headers setContentRange(String content_range) { 176 | return setHeader(HeaderNames.CONTENT_RANGE, content_range); 177 | } 178 | 179 | public String getContentType() { 180 | return getSafeValue(HeaderNames.CONTENT_TYPE); 181 | } 182 | 183 | public Headers setContentType(String type) { 184 | return setHeader(HeaderNames.CONTENT_TYPE, type); 185 | } 186 | 187 | public Headers setContentType(ContentType type) { 188 | return setContentType(type.getCode()); 189 | } 190 | 191 | public String getDate() { 192 | return getSafeValue(HeaderNames.DATE); 193 | } 194 | 195 | public Headers setDate(String date) { 196 | return setHeader(HeaderNames.DATE, date); 197 | } 198 | 199 | public String getDav() { 200 | return getSafeValue(HeaderNames.DAV); 201 | } 202 | 203 | public Headers setDav(String dav) { 204 | return setHeader(HeaderNames.DAV, dav); 205 | } 206 | 207 | public String getDepth() { 208 | return getSafeValue(HeaderNames.DEPTH); 209 | } 210 | 211 | public Headers setDepth(String depth) { 212 | return setHeader(HeaderNames.DEPTH, depth); 213 | } 214 | 215 | public String getDestination() { 216 | return getSafeValue(HeaderNames.DESTINATION); 217 | } 218 | 219 | public Headers setDestination(String destination) { 220 | return setHeader(HeaderNames.DESTINATION, destination); 221 | } 222 | 223 | public String getEtag() { 224 | return getSafeValue(HeaderNames.ETAG); 225 | } 226 | 227 | public Headers setEtag(String etag) { 228 | return setHeader(HeaderNames.ETAG, etag); 229 | } 230 | 231 | public String getExpect() { 232 | return getSafeValue(HeaderNames.EXPECT); 233 | } 234 | 235 | public Headers setExpect(String expect) { 236 | return setHeader(HeaderNames.EXPECT, expect); 237 | } 238 | 239 | public String getExpires() { 240 | return getSafeValue(HeaderNames.EXPIRES); 241 | } 242 | 243 | public Headers setExpires(String expires) { 244 | return setHeader(HeaderNames.EXPIRES, expires); 245 | } 246 | 247 | public String getFrom() { 248 | return getSafeValue(HeaderNames.FROM); 249 | } 250 | 251 | public Headers setFrom(String from) { 252 | return setHeader(HeaderNames.FROM, from); 253 | } 254 | 255 | public String getHost() { 256 | return getSafeValue(HeaderNames.HOST); 257 | } 258 | 259 | public Headers setHost(String host) { 260 | return setHeader(HeaderNames.HOST, host); 261 | } 262 | 263 | public String getIf() { 264 | return getSafeValue(HeaderNames.IF); 265 | } 266 | 267 | public Headers setIf(String iff) { 268 | return setHeader(HeaderNames.IF, iff); 269 | } 270 | 271 | public String getIfMatch() { 272 | return getSafeValue(HeaderNames.IF_MATCH); 273 | } 274 | 275 | public Headers setIfMatch(String if_match) { 276 | return setHeader(HeaderNames.IF_MATCH, if_match); 277 | } 278 | 279 | public String getIfModifiedSince() { 280 | return getSafeValue(HeaderNames.IF_MODIFIED_SINCE); 281 | } 282 | 283 | public Headers setIfModifiedSince(String if_modified_since) { 284 | return setHeader(HeaderNames.IF_MODIFIED_SINCE, if_modified_since); 285 | } 286 | 287 | public String getIfNoneMatch() { 288 | return getSafeValue(HeaderNames.IF_NONE_MATCH); 289 | } 290 | 291 | public Headers setIfNoneMatch(String if_none_match) { 292 | return setHeader(HeaderNames.IF_NONE_MATCH, if_none_match); 293 | } 294 | 295 | public String getIfRange() { 296 | return getSafeValue(HeaderNames.IF_RANGE); 297 | } 298 | 299 | public Headers setIfRange(String if_range) { 300 | return setHeader(HeaderNames.IF_RANGE, if_range); 301 | } 302 | 303 | public String getIfUnmodifiedSince() { 304 | return getSafeValue(HeaderNames.IF_UNMODIFIED_SINCE); 305 | } 306 | 307 | public Headers setIfUnmodifiedSince(String if_unmodified_since) { 308 | return setHeader(HeaderNames.IF_UNMODIFIED_SINCE, if_unmodified_since); 309 | } 310 | 311 | public String getLastModified() { 312 | return getSafeValue(HeaderNames.LAST_MODIFIED); 313 | } 314 | 315 | public Headers setLastModified(String last_modified) { 316 | return setHeader(HeaderNames.LAST_MODIFIED, last_modified); 317 | } 318 | 319 | public String getLocation() { 320 | return getSafeValue(HeaderNames.LOCATION); 321 | } 322 | 323 | public Headers setLocation(String location) { 324 | return setHeader(HeaderNames.LOCATION, location); 325 | } 326 | 327 | public String getLockToken() { 328 | return getSafeValue(HeaderNames.LOCK_TOKEN); 329 | } 330 | 331 | public Headers setLockToken(String lock_token) { 332 | return setHeader(HeaderNames.LOCK_TOKEN, lock_token); 333 | } 334 | 335 | public String getMaxForwards() { 336 | return getSafeValue(HeaderNames.MAX_FORWARDS); 337 | } 338 | 339 | public Headers setMaxForwards(String max_forwards) { 340 | return setHeader(HeaderNames.MAX_FORWARDS, max_forwards); 341 | } 342 | 343 | public String getOverwrite() { 344 | return getSafeValue(HeaderNames.OVERWRITE); 345 | } 346 | 347 | public Headers setOverwrite(String overwrite) { 348 | return setHeader(HeaderNames.OVERWRITE, overwrite); 349 | } 350 | 351 | public String getPragma() { 352 | return getSafeValue(HeaderNames.PRAGMA); 353 | } 354 | 355 | public Headers setPragma(String pragma) { 356 | return setHeader(HeaderNames.PRAGMA, pragma); 357 | } 358 | 359 | public String getProxyAuthenticate() { 360 | return getSafeValue(HeaderNames.PROXY_AUTHENTICATE); 361 | } 362 | 363 | public Headers setProxyAuthenticate(String proxy_authenticate) { 364 | return setHeader(HeaderNames.PROXY_AUTHENTICATE, proxy_authenticate); 365 | } 366 | 367 | public String getProxyAuthorization() { 368 | return getSafeValue(HeaderNames.PROXY_AUTHORIZATION); 369 | } 370 | 371 | public Headers setProxyAuthorization(String proxy_authorization) { 372 | return setHeader(HeaderNames.PROXY_AUTHORIZATION, proxy_authorization); 373 | } 374 | 375 | public String getRange() { 376 | return getSafeValue(HeaderNames.RANGE); 377 | } 378 | 379 | public Headers setRange(String range) { 380 | return setHeader(HeaderNames.RANGE, range); 381 | } 382 | 383 | public String getReferer() { 384 | return getSafeValue(HeaderNames.REFERER); 385 | } 386 | 387 | public Headers setReferer(String referer) { 388 | return setHeader(HeaderNames.REFERER, referer); 389 | } 390 | 391 | public String getRetryAfter() { 392 | return getSafeValue(HeaderNames.RETRY_AFTER); 393 | } 394 | 395 | public Headers setRetryAfter(String retry_after) { 396 | return setHeader(HeaderNames.RETRY_AFTER, retry_after); 397 | } 398 | 399 | public String getServer() { 400 | return getSafeValue(HeaderNames.SERVER); 401 | } 402 | 403 | public Headers setServer(String server) { 404 | return setHeader(HeaderNames.SERVER, server); 405 | } 406 | 407 | public String getStatusUri() { 408 | return getSafeValue(HeaderNames.STATUS_URI); 409 | } 410 | 411 | public Headers setStatusUri(String status_uri) { 412 | return setHeader(HeaderNames.STATUS_URI, status_uri); 413 | } 414 | 415 | public String getTe() { 416 | return getSafeValue(HeaderNames.TE); 417 | } 418 | 419 | public Headers setTe(String te) { 420 | return setHeader(HeaderNames.TE, te); 421 | } 422 | 423 | public String getTimeout() { 424 | return getSafeValue(HeaderNames.TIMEOUT); 425 | } 426 | 427 | public Headers setTimeout(String timeout) { 428 | return setHeader(HeaderNames.TIMEOUT, timeout); 429 | } 430 | 431 | public String getTrailer() { 432 | return getSafeValue(HeaderNames.TRAILER); 433 | } 434 | 435 | public Headers setTrailer(String trailer) { 436 | return setHeader(HeaderNames.TRAILER, trailer); 437 | } 438 | 439 | public String getTransferEncoding() { 440 | return getSafeValue(HeaderNames.TRANSFER_ENCODING); 441 | } 442 | 443 | public Headers setTransferEncoding(String transfer_encoding) { 444 | return setHeader(HeaderNames.TRANSFER_ENCODING, transfer_encoding); 445 | } 446 | 447 | public String getUpgrade() { 448 | return getSafeValue(HeaderNames.UPGRADE); 449 | } 450 | 451 | public Headers setUpgrade(String upgrade) { 452 | return setHeader(HeaderNames.UPGRADE, upgrade); 453 | } 454 | 455 | public String getUserAgent() { 456 | return getSafeValue(HeaderNames.USER_AGENT); 457 | } 458 | 459 | public Headers setUserAgent(String userAgent) { 460 | return setHeader(HeaderNames.USER_AGENT, userAgent); 461 | } 462 | 463 | public String getVary() { 464 | return getSafeValue(HeaderNames.VARY); 465 | } 466 | 467 | public Headers setVary(String vary) { 468 | return setHeader(HeaderNames.VARY, vary); 469 | } 470 | 471 | public String getVia() { 472 | return getSafeValue(HeaderNames.VIA); 473 | } 474 | 475 | public Headers setVia(String via) { 476 | return setHeader(HeaderNames.VIA, via); 477 | } 478 | 479 | public String getWarning() { 480 | return getSafeValue(HeaderNames.WARNING); 481 | } 482 | 483 | public Headers setWarning(String warning) { 484 | return setHeader(HeaderNames.WARNING, warning); 485 | } 486 | 487 | public String getWwwAuthenticate() { 488 | return getSafeValue(HeaderNames.WWW_AUTHENTICATE); 489 | } 490 | 491 | public Headers setWwwAuthenticate(String www_authenticate) { 492 | return setHeader(HeaderNames.WWW_AUTHENTICATE, www_authenticate); 493 | } 494 | 495 | public Set headerKeys() { 496 | return headers.keySet(); 497 | } 498 | 499 | public Header getHeader(String key) { 500 | return this.headers.get(key); 501 | } 502 | 503 | /** 504 | * Gets the header value safely (if the header does not exist returns empty string) 505 | * @param key the key to get the header value for 506 | * @return the header value 507 | */ 508 | public String getSafeValue(String key) { 509 | Header header = getHeader(key); 510 | if (header == null) { 511 | return ""; 512 | } 513 | 514 | return header.getValue(); 515 | } 516 | 517 | /** 518 | * Converts this Headers instance to a RequestConfig passable instance 519 | * @return the request instance 520 | */ 521 | public RequestConfig toConfig() { 522 | return new RequestConfig() 523 | .setRequestHeaders(this); 524 | } 525 | 526 | public Headers setAuthentication(String authentication) { 527 | return setHeader(HeaderNames.AUTHORIZATION, authentication); 528 | } 529 | 530 | /** 531 | * Sets the header value directly 532 | * @param key header key name 533 | * @param value header value string 534 | * @return Headers instance for setter chaining 535 | */ 536 | public Headers setHeader(String key, String value) { 537 | headers.put(key, new SimpleHeader(key, value)); 538 | return this; 539 | } 540 | 541 | /** 542 | * Sets the header to a supplier value evaluated when the request is made 543 | * @param key they header key to set 544 | * @param supplier the supplier value to set the header to 545 | * @return Headers instance for setter chaining 546 | */ 547 | public Headers setHeader(String key, Supplier supplier) { 548 | headers.put(key, new SupplierHeader(key, supplier)); 549 | return this; 550 | } 551 | 552 | @Override 553 | public String toString() { 554 | Collection
headers = this.headers.values(); 555 | return "RequestHeaders{" + "headers=" + headers + 556 | '}'; 557 | } 558 | 559 | public enum ContentType { 560 | APPLICATION_ATOM_XML("application/atom+xml", StandardCharsets.ISO_8859_1), 561 | APPLICATION_FORM_URL_ENCODED("application/x-www-form-urlencoded", StandardCharsets.ISO_8859_1), 562 | APPLICATION_JSON("application/json", StandardCharsets.UTF_8), 563 | IMAGE_BMP("image/bmp"), 564 | IMAGE_GIF("image/gif"), 565 | 566 | TEXT("text/plain"), 567 | WILDCARD("*/*"); 568 | 569 | private final String code; 570 | private Charset charset = StandardCharsets.UTF_8; 571 | 572 | ContentType(String code) { 573 | this.code = code; 574 | } 575 | 576 | ContentType(String code, Charset charset) { 577 | this.charset = charset; 578 | this.code = code; 579 | } 580 | 581 | public Charset getCharset() { 582 | return charset; 583 | } 584 | 585 | public String getCode() { 586 | return code; 587 | } 588 | } 589 | 590 | private static class SupplierHeader implements Header { 591 | private final String key; 592 | private final Supplier supplier; 593 | 594 | public SupplierHeader(String key, Supplier supplier) { 595 | this.key = key; 596 | this.supplier = supplier; 597 | } 598 | 599 | @Override 600 | public String getName() { 601 | return key; 602 | } 603 | 604 | @Override 605 | public String getValue() { 606 | return supplier.get(); 607 | } 608 | } 609 | 610 | private static class SimpleHeader implements Header { 611 | private final String key; 612 | private final String value; 613 | 614 | public SimpleHeader(String key, String value) { 615 | this.key = key; 616 | this.value = value; 617 | } 618 | 619 | @Override 620 | public String getName() { 621 | return key; 622 | } 623 | 624 | @Override 625 | public String getValue() { 626 | return value; 627 | } 628 | 629 | @Override 630 | public String toString() { 631 | return String.format("%s=%s", getName(), getValue()); 632 | } 633 | } 634 | } 635 | -------------------------------------------------------------------------------- /src/main/java/dev/yasper/rump/client/DefaultRestClient.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Rump is a REST client for Java that allows for easy configuration and default values. 3 | *

4 | * Copyright (C) 2020 Jasper Ketelaar 5 | *

6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | *

11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | *

16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | package dev.yasper.rump.client; 20 | 21 | import dev.yasper.rump.Headers; 22 | import dev.yasper.rump.Rump; 23 | import dev.yasper.rump.config.RequestConfig; 24 | import dev.yasper.rump.exception.HttpStatusCodeException; 25 | import dev.yasper.rump.interceptor.RequestInterceptor; 26 | import dev.yasper.rump.interceptor.ResponseInterceptor; 27 | import dev.yasper.rump.request.RequestMethod; 28 | import dev.yasper.rump.response.HttpResponse; 29 | import dev.yasper.rump.response.PrimitiveBody; 30 | import dev.yasper.rump.response.ResponseTransformer; 31 | 32 | import java.io.BufferedWriter; 33 | import java.io.IOException; 34 | import java.io.InputStream; 35 | import java.io.OutputStreamWriter; 36 | import java.net.HttpURLConnection; 37 | import java.net.ProtocolException; 38 | import java.net.Proxy; 39 | import java.net.URL; 40 | import java.util.Arrays; 41 | import java.util.List; 42 | 43 | public class DefaultRestClient implements RestClient { 44 | 45 | private static final List> PRIMITIVE_CLASSES = Arrays.asList( 46 | String.class, Double.class, Integer.class, Float.class, 47 | Short.class, Byte.class, Boolean.class, Character.class 48 | ); 49 | private static final int LAST_SUCCESSFUL_RESPONSE = 299; 50 | private final RequestConfig config; 51 | 52 | protected DefaultRestClient(RequestConfig config) { 53 | this.config = config; 54 | } 55 | 56 | /** 57 | * Create a DefaultRestClient, constructor is protected to prevent a user creating a RequestConfig with a null 58 | * value causing unexpected errors during execution. 59 | * 60 | * @param config The config instance for this rest client, this is merged with {@link Rump#DEFAULT_CONFIG} 61 | * @return The created {@link DefaultRestClient} 62 | */ 63 | public static DefaultRestClient create(RequestConfig config) { 64 | return new DefaultRestClient(Rump.DEFAULT_CONFIG.merge(config)); 65 | } 66 | 67 | public RequestConfig getConfig() { 68 | return config; 69 | } 70 | 71 | /** 72 | * Calls {@link DefaultRestClient#requestForObject(String, RequestMethod, Object, Class, RequestConfig...)} 73 | * with the passed parameters and RequestMethod.GET 74 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 75 | * @param responseType The type to parse the response as 76 | * @param merging The configs from which to construct this request 77 | * @return The {@link T} if everything is fine, else null 78 | * @param The required type of the response 79 | * @throws IOException Thrown by HttpURLConnection methods 80 | */ 81 | public T getForObject(String path, Class responseType, 82 | RequestConfig... merging) throws IOException { 83 | return requestForObject(path, RequestMethod.GET, null, responseType, merging); 84 | } 85 | 86 | /** 87 | * Calls {@link DefaultRestClient#requestForObject(String, RequestMethod, Object, Class, RequestConfig...)} 88 | * with the passed parameters and RequestMethod.POST 89 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 90 | * @param requestBody The body to send with this request, applicable to POST and PUT only 91 | * @param responseType The type to parse the response as 92 | * @param merging The configs from which to construct this request 93 | * @return The {@link T} if everything is fine, else null 94 | * @param The required type of the response 95 | * @throws IOException Thrown by HttpURLConnection methods 96 | */ 97 | public T postForObject(String path, Object requestBody, Class responseType, 98 | RequestConfig... merging) throws IOException { 99 | return requestForObject(path, RequestMethod.POST, requestBody, responseType, merging); 100 | } 101 | 102 | /** 103 | * Calls {@link DefaultRestClient#requestForObject(String, RequestMethod, Object, Class, RequestConfig...)} 104 | * with the passed parameters and RequestMethod.PUT 105 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 106 | * @param requestBody The body to send with this request, applicable to POST and PUT only 107 | * @param responseType The type to parse the response as 108 | * @param merging The configs from which to construct this request 109 | * @return The {@link T} if everything is fine, else null 110 | * @param The required type of the response 111 | * @throws IOException Thrown by HttpURLConnection methods 112 | */ 113 | public T putForObject(String path, Object requestBody, Class responseType, 114 | RequestConfig... merging) throws IOException { 115 | return requestForObject(path, RequestMethod.PUT, requestBody, responseType, merging); 116 | } 117 | 118 | /** 119 | * Calls {@link DefaultRestClient#requestForObject(String, RequestMethod, Object, Class, RequestConfig...)} 120 | * with the passed parameters and RequestMethod.DELETE 121 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 122 | * @param responseType The type to parse the response as 123 | * @param merging The configs from which to construct this request 124 | * @return The {@link T} if everything is fine, else null 125 | * @param The required type of the response 126 | * @throws IOException Thrown by HttpURLConnection methods 127 | */ 128 | public T deleteForObject(String path, Class responseType, RequestConfig... merging) throws IOException { 129 | return requestForObject(path, RequestMethod.DELETE, null, responseType, merging); 130 | } 131 | 132 | /** 133 | * Calls {@link DefaultRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} 134 | * with the passed parameters and returns just the body 135 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 136 | * @param method The request method for this request. 137 | * @param requestBody The body to send with this request, applicable to POST and PUT only 138 | * @param responseType The type to parse the response as 139 | * @param merging The configs from which to construct this request 140 | * @return The {@link HttpResponse} if everything is fine, else null 141 | * @param The required type of the response 142 | * @throws IOException Thrown by HttpURLConnection methods 143 | */ 144 | public T requestForObject(String path, RequestMethod method, Object requestBody, Class responseType, 145 | RequestConfig... merging) throws IOException { 146 | return request(path, method, requestBody, responseType, merging).getBody(); 147 | } 148 | 149 | /** 150 | * Calls {@link DefaultRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} 151 | * with the passed parameters and RequestMethod.POST 152 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 153 | * @param requestBody The body to send with this request, applicable to POST and PUT only 154 | * @param responseType The type to parse the response as 155 | * @param merging The configs from which to construct this request 156 | * @return The {@link HttpResponse} if everything is fine, else null 157 | * @param The required type of the response 158 | * @throws IOException Thrown by HttpURLConnection methods 159 | */ 160 | public HttpResponse post(String path, Object requestBody, Class responseType, 161 | RequestConfig... merging) throws IOException { 162 | return request(path, RequestMethod.POST, requestBody, responseType, merging); 163 | } 164 | 165 | /** 166 | * Calls {@link DefaultRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} 167 | * with the passed parameters and RequestMethod.PUT 168 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 169 | * @param requestBody The body to send with this request, applicable to POST and PUT only 170 | * @param responseType The type to parse the response as 171 | * @param merging The configs from which to construct this request 172 | * @return The {@link HttpResponse} if everything is fine, else null 173 | * @param The required type of the response 174 | * @throws IOException Thrown by HttpURLConnection methods 175 | */ 176 | public HttpResponse put(String path, Object requestBody, Class responseType, 177 | RequestConfig... merging) throws IOException { 178 | return request(path, RequestMethod.PUT, requestBody, responseType, merging); 179 | } 180 | 181 | /** 182 | * Calls {@link DefaultRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} 183 | * with the passed parameters and RequestMethod.GET 184 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 185 | * @param responseType The type to parse the response as 186 | * @param merging The configs from which to construct this request 187 | * @return The {@link HttpResponse} if everything is fine, else null 188 | * @param The required type of the response 189 | * @throws IOException Thrown by HttpURLConnection methods 190 | */ 191 | public HttpResponse get(String path, Class responseType, 192 | RequestConfig... merging) throws IOException { 193 | return request(path, RequestMethod.GET, null, responseType, merging); 194 | } 195 | 196 | /** 197 | * Calls {@link DefaultRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} 198 | * with the passed parameters and RequestMethod.DELETE 199 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 200 | * @param responseType The type to parse the response as 201 | * @param merging The configs from which to construct this request 202 | * @return The {@link HttpResponse} if everything is fine, else null 203 | * @param The required type of the response 204 | * @throws IOException Thrown by HttpURLConnection methods 205 | */ 206 | public HttpResponse delete(String path, Class responseType, RequestConfig... merging) throws IOException { 207 | return request(path, RequestMethod.DELETE, null, responseType, merging); 208 | } 209 | 210 | /** 211 | * Calls {@link DefaultRestClient#request(String, RequestMethod, Object, Class, RequestConfig...)} 212 | * with the passed parameters and RequestMethod.HEAD 213 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 214 | * @param merging The configs from which to construct this request 215 | * @return The {@link HttpResponse} if everything is fine, else null 216 | * @throws IOException Thrown by HttpURLConnection methods 217 | */ 218 | public HttpResponse head(String path, RequestConfig... merging) throws IOException { 219 | return request(path, RequestMethod.HEAD, null, Void.class, merging); 220 | } 221 | 222 | /** 223 | * Calls {@link DefaultRestClient#request(String, Object, Class, RequestConfig)} with the passed parameters 224 | * and the configs merged, method is converted into a config too. 225 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 226 | * @param method The request method for this request. 227 | * @param requestBody The body to send with this request, applicable to POST and PUT only 228 | * @param responseType The type to parse the response as 229 | * @param merging The configs from which to construct this request 230 | * @param The required type of the response 231 | * @return The {@link HttpResponse} if everything is fine, else null 232 | * @throws IOException Thrown by HttpURLConnection methods 233 | */ 234 | public HttpResponse request(String path, RequestMethod method, Object requestBody, 235 | Class responseType, RequestConfig... merging) throws IOException { 236 | return request(path, requestBody, responseType, this.config.merge(method.toConfig()).merge(merging)); 237 | } 238 | 239 | /** 240 | * Calls {@link DefaultRestClient#request(String, Object, Class, RequestConfig)} with the passed parameters 241 | * and the configs merged. 242 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 243 | * @param requestBody The body to send with this request, applicable to POST and PUT only 244 | * @param responseType The type to parse the response as 245 | * @param merging The configs from which to construct this request 246 | * @param The required type of the response 247 | * @return The {@link HttpResponse} if everything is fine, else null 248 | * @throws IOException Thrown by HttpURLConnection methods 249 | */ 250 | public HttpResponse request(String path, Object requestBody, Class responseType, 251 | RequestConfig... merging) throws IOException { 252 | RequestConfig config = this.config.merge(merging); 253 | return request(path, requestBody, responseType, config); 254 | } 255 | 256 | 257 | /** 258 | *

259 | * Main method for creating any request. Converts the config into a url using {@link RequestConfig#getBaseURL()} and 260 | * {@link RequestConfig#getParams()}. This url is then constructed into a HttpURLConnection using the Proxy defined in the 261 | * config if it is present. 262 | *

263 | * 264 | *

265 | * On this instance the rest of the config values are applied and the RequestInterceptors are called. If any of them 266 | * return false the request is canceled. 267 | *

268 | * 269 | *

270 | * The request body is written to the connections output stream. Now the request is completed and the repsonse parsing 271 | * starts. 272 | *

273 | * 274 | *

275 | * The response code is then checked for it to be erroneous using {@link RequestConfig#getIgnoreStatusCode()} 276 | * and if an error occurred a {@link HttpResponse} is constructed and sent to the error handler. 277 | *

278 | * 279 | *

280 | * If no error has occurred the connection input stream is read and parsed to the requested type using the 281 | * response transformer. This is when the ResponseInterceptors are called and if any of them return false the 282 | * response is canceled. If everything passes we then return the {@link HttpResponse} with the response body. 283 | *

284 | * 285 | * @param path The path of this request, full URL if no base URL is specified in the config or any of the overloads 286 | * @param requestBody The body to send with this request, applicable to POST and PUT only 287 | * @param responseType The type to parse the response as 288 | * @param config The config specifying the request 289 | * @param The required type of the response 290 | * @return The {@link HttpResponse} if everything is fine, else null 291 | * @throws IOException Thrown by HttpURLConnection methods 292 | */ 293 | private HttpResponse request(String path, Object requestBody, Class responseType, 294 | RequestConfig config) throws IOException { 295 | String urlMerged = config.getBaseURL() + path + config.getParams().toURLPart(); 296 | URL url = new URL(urlMerged); 297 | 298 | HttpURLConnection connection = openWithProxyIfPresent(url, config.getProxy()); 299 | applyConfig(connection, config); 300 | if (!beforeRequest(config, urlMerged, connection)) { 301 | connection.disconnect(); 302 | return null; 303 | } 304 | 305 | if (requestBody != null && config.isOutputting()) { 306 | writeToConnection(connection, requestBody, config); 307 | } 308 | 309 | Headers responseHeaders = new Headers(connection.getHeaderFields()); 310 | if (connection.getResponseCode() > LAST_SUCCESSFUL_RESPONSE 311 | && !config.getIgnoreStatusCode().test(connection.getResponseCode())) { 312 | PrimitiveBody body = new PrimitiveBody(connection.getErrorStream()); 313 | HttpResponse errorResponse = new HttpResponse<>( 314 | body.getAsString(), responseHeaders, 315 | connection.getResponseCode(), connection.getResponseMessage(), 316 | config, urlMerged 317 | ); 318 | 319 | config.getExceptionHandler().onHttpException(new HttpStatusCodeException(errorResponse)); 320 | return null; 321 | } 322 | 323 | T body = transform(connection.getInputStream(), responseType, config); 324 | HttpResponse res = new HttpResponse<>( 325 | body, responseHeaders, 326 | connection.getResponseCode(), connection.getResponseMessage(), 327 | config, urlMerged 328 | ); 329 | if (!beforeResponse(res)) { 330 | return null; 331 | } 332 | 333 | return res; 334 | } 335 | 336 | private void writeToConnection(HttpURLConnection connection, Object requestBody, RequestConfig config) throws IOException { 337 | String mapped = config.getRequestTransformer().transform(requestBody, config.getRequestHeaders()) 338 | .toString(); 339 | try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()))) { 340 | writer.write(mapped); 341 | } 342 | } 343 | 344 | private HttpURLConnection openWithProxyIfPresent(URL url, Proxy proxy) throws IOException { 345 | if (proxy == null) { 346 | return (HttpURLConnection) url.openConnection(); 347 | } else { 348 | return (HttpURLConnection) url.openConnection(proxy); 349 | } 350 | } 351 | 352 | private boolean beforeResponse(HttpResponse res) { 353 | for (ResponseInterceptor interceptor : config.getResponseInterceptors()) { 354 | if (!interceptor.beforeResponse(res)) { 355 | return false; 356 | } 357 | } 358 | 359 | return true; 360 | } 361 | 362 | private boolean beforeRequest(RequestConfig config, String mergedURL, HttpURLConnection connection) { 363 | for (RequestInterceptor interceptor : config.getRequestInterceptors()) { 364 | if (!interceptor.beforeRequest(mergedURL, connection, config)) { 365 | return false; 366 | } 367 | } 368 | 369 | return true; 370 | } 371 | 372 | private void applyConfig(HttpURLConnection connection, RequestConfig config) throws ProtocolException { 373 | connection.setConnectTimeout(config.getTimeout()); 374 | connection.setReadTimeout(config.getReadTimeout()); 375 | connection.setRequestMethod(config.getMethod().toString()); 376 | if (config.isOutputting()) { 377 | connection.setDoOutput(true); 378 | } 379 | 380 | if (config.getAuthenticator() != null) { 381 | connection.setAuthenticator(config.getAuthenticator()); 382 | } 383 | for (String key : config.getRequestHeaders().headerKeys()) { 384 | connection.setRequestProperty(key, config.getRequestHeaders().getSafeValue(key)); 385 | } 386 | 387 | connection.setUseCaches(config.isUsingCaches()); 388 | config.getConnectionConsumer().accept(connection); 389 | } 390 | 391 | private T transform(InputStream input, Class responseType, RequestConfig config) throws IOException { 392 | if (config.getMethod() == RequestMethod.HEAD) { 393 | return null; 394 | } 395 | 396 | if (responseType == PrimitiveBody.class || PRIMITIVE_CLASSES.contains(responseType)) { 397 | PrimitiveBody body = new PrimitiveBody(input); 398 | if (responseType == PrimitiveBody.class) { 399 | return responseType.cast(body); 400 | } else { 401 | return body.getAs(responseType); 402 | } 403 | } 404 | 405 | ResponseTransformer transformer = config.getResponseTransformer(); 406 | return transformer.transform(input, responseType); 407 | } 408 | 409 | @Override 410 | public boolean isAsync() { 411 | return false; 412 | } 413 | } 414 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------