Skip to content

Commit

Permalink
Merge branch '__rultor'
Browse files Browse the repository at this point in the history
  • Loading branch information
rultor committed Sep 3, 2020
2 parents e77d8e1 + 8c58144 commit d477467
Show file tree
Hide file tree
Showing 3 changed files with 203 additions and 58 deletions.
110 changes: 82 additions & 28 deletions src/main/java/com/jcabi/http/request/BaseRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
*/
package com.jcabi.http.request;

import com.fasterxml.jackson.databind.util.ClassUtil;
import com.google.common.base.Joiner;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
Expand Down Expand Up @@ -279,34 +280,11 @@ public Response fetch(final InputStream stream) throws IOException {
}

@Override
public <T extends Wire> Request through(final Class<T> type,
final Object... args) {
Constructor<?> ctor = null;
for (final Constructor<?> opt : type.getDeclaredConstructors()) {
if (opt.getParameterTypes().length == args.length + 1) {
ctor = opt;
break;
}
}
if (ctor == null) {
throw new IllegalArgumentException(
String.format(
"class %s doesn't have a ctor with %d argument(s)",
type.getName(), args.length
)
);
}
final Object[] params = new Object[args.length + 1];
params[0] = this.wire;
System.arraycopy(args, 0, params, 1, args.length);
final Wire decorated;
try {
decorated = Wire.class.cast(ctor.newInstance(params));
} catch (final InstantiationException
| IllegalAccessException | InvocationTargetException ex) {
throw new IllegalStateException(ex);
}
return this.through(decorated);
public <T extends Wire> Request through(
final Class<T> type,
final Object... args
) {
return this.through(this.mkWire(type, args));
}

@Override
Expand Down Expand Up @@ -346,6 +324,32 @@ public String toString() {
.toString();
}

/**
* Create an instance of Wire.
*
* @param type Type of Wire.
* @param args Ctor arguments.
* @param <T> Type of Wire.
* @return An instance of Wire
*/
private <T extends Wire> Wire mkWire(
final Class<T> type,
final Object... args
) {
final Constructor<?> ctor = BaseRequest.findCtor(type, args);
final Object[] params = new Object[args.length + 1];
params[0] = this.wire;
System.arraycopy(args, 0, params, 1, args.length);
final Wire decorated;
try {
decorated = Wire.class.cast(ctor.newInstance(params));
} catch (final InstantiationException
| IllegalAccessException | InvocationTargetException ex) {
throw new IllegalStateException(ex);
}
return decorated;
}

/**
* Fetch response from server.
* @param stream The content to send.
Expand Down Expand Up @@ -391,6 +395,56 @@ private static URI createUri(final String uri) {
return addr;
}

/**
* Find a ctor which match arguments.
* @param type A type.
* @param args Ctor arguments.
* @param <T> Type of object
* @return A proper ctor for args.
*/
private static <T extends Wire> Constructor<?> findCtor(
final Class<T> type, final Object... args
) {
Constructor<?> ctor = null;
for (final Constructor<?> opt : type.getDeclaredConstructors()) {
final Class<?>[] types = opt.getParameterTypes();
if (types.length == args.length + 1) {
boolean match = true;
for (int inx = 1; inx < types.length && match; ++inx) {
match = BaseRequest
.wrappedIfNeeded(types[inx])
.isAssignableFrom(args[inx - 1].getClass());
}
if (match) {
ctor = opt;
break;
}
}
}
if (ctor == null) {
throw new IllegalArgumentException(
String.format(
"class %s doesn't have a ctor with %d argument(s)",
type.getName(), args.length
)
);
}
return ctor;
}

/**
* Wrap primitive types.
* @param type A type which could be primitive
* @return Wrapped type if it was a primitive
*/
private static Class<?> wrappedIfNeeded(final Class<?> type) {
Class<?> arg = type;
if (arg.isPrimitive()) {
arg = ClassUtil.wrapperType(arg);
}
return arg;
}

/**
* Base URI.
*
Expand Down
111 changes: 82 additions & 29 deletions src/main/java/com/jcabi/http/wire/CachingWire.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
import java.net.URI;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import lombok.EqualsAndHashCode;
import lombok.ToString;
Expand All @@ -66,47 +67,67 @@
* .uri().path("/save/123").back()
* .fetch();</pre>
*
* <p>Since 1.17.3, you can pass a {@see LoadingCache} alongside the wire.
*
* <pre>{@code
* final LoadingCache<Callable<Response>, Response> cache = ...;
* new JdkRequest(uri)
* .through(CachingWire.class, cache)
* .uri().path("/save/123").back()
* .fetch();
* }</pre>
*
* <p>The regular expression provided will be used against a string
* constructed as an HTTP method, space, path of the URI together with
* query part.
*
* <p>The class is immutable and thread-safe.
*
* @todo #179:30m This implementation depends on Guava. Investigate for a
* possible shared interface between this class and other implementations for
* caching. If this shared interface is possible replace this task with a task
* for implementing it.
* @since 1.0
*/
@Immutable
@ToString
@EqualsAndHashCode(of = {"origin", "regex"})
@SuppressWarnings("PMD.OnlyOneConstructorShouldDoInitialization")
public final class CachingWire implements Wire {

/**
* Loader.
*/
private static final CacheLoader<Wire,
LoadingCache<CachingWire.Query, Response>> LOADER =
new CacheLoader<Wire, LoadingCache<CachingWire.Query, Response>>() {
LoadingCache<Callable<Response>, Response>> LOADER =
new CacheLoader<Wire, LoadingCache<Callable<Response>, Response>>() {
@Override
public LoadingCache<CachingWire.Query, Response> load(
final Wire key) {
public LoadingCache<Callable<Response>, Response> load(
final Wire key
) {
return CacheBuilder.newBuilder().build(
new CacheLoader<CachingWire.Query, Response>() {
new CacheLoader<Callable<Response>, Response>() {
@Override
public Response load(final CachingWire.Query query)
throws IOException {
return query.fetch();
public Response load(final Callable<Response> query)
throws Exception {
return query.call();
}
}
);
}
};

/**
* Cache.
* Default cache.
*/
private static final LoadingCache<Wire,
LoadingCache<CachingWire.Query, Response>> CACHE =
LoadingCache<Callable<Response>, Response>> CACHE =
CacheBuilder.newBuilder().build(CachingWire.LOADER);

/**
* Default flushing regex.
*/
private static final String NEVER = "$never";

/**
* Original wire.
*/
Expand All @@ -117,12 +138,17 @@ public Response load(final CachingWire.Query query)
*/
private final transient String regex;

/**
* Cache.
*/
private final LoadingCache<Callable<Response>, Response> cache;

/**
* Public ctor.
* @param wire Original wire
*/
public CachingWire(final Wire wire) {
this(wire, "$never");
this(wire, CachingWire.NEVER);
}

/**
Expand All @@ -134,33 +160,62 @@ public CachingWire(final Wire wire) {
public CachingWire(final Wire wire, final String flsh) {
this.origin = wire;
this.regex = flsh;
this.cache = CACHE.getUnchecked(this);
}

/**
* Public ctor.
* @param wire Original wire
* @param storage Cache
* @since 1.17.4
*/
public CachingWire(
final Wire wire,
final LoadingCache<Callable<Response>, Response> storage
) {
this(wire, CachingWire.NEVER, storage);
}

/**
* Public ctor.
* @param wire Original wire
* @param flsh Flushing regular expression
* @param storage Cache
* @since 1.17.4
*/
public CachingWire(
final Wire wire,
final String flsh,
final LoadingCache<Callable<Response>, Response> storage
) {
this.origin = wire;
this.regex = flsh;
this.cache = storage;
}

// @checkstyle ParameterNumber (5 lines)
@Override
public Response send(final Request req, final String home,
public Response send(
final Request req, final String home,
final String method,
final Collection<Map.Entry<String, String>> headers,
final InputStream content,
final int connect,
final int read) throws IOException {
final int read
) throws IOException {
final URI uri = req.uri().get();
final StringBuilder label = new StringBuilder(Tv.HUNDRED)
.append(method).append(' ').append(uri.getPath());
if (uri.getQuery() != null) {
label.append('?').append(uri.getQuery());
}
if (label.toString().matches(this.regex)) {
try {
CachingWire.CACHE.get(this).invalidateAll();
} catch (final ExecutionException ex) {
throw new IllegalStateException(ex);
}
this.cache.invalidateAll();
}
final Response rsp;
if (method.equals(Request.GET)) {
try {
rsp = CachingWire.CACHE.get(this).get(
rsp = this.cache.get(
new CachingWire.Query(
this.origin, req, home, headers, content,
connect, read
Expand Down Expand Up @@ -194,7 +249,7 @@ public static void invalidate() {
*/
@ToString
@EqualsAndHashCode(of = {"origin", "request", "uri", "headers"})
private static final class Query {
private static final class Query implements Callable<Response> {
/**
* Origin wire.
*/
Expand Down Expand Up @@ -241,10 +296,12 @@ private static final class Query {
* @param rdd Read timeout
* @checkstyle ParameterNumberCheck (5 lines)
*/
Query(final Wire wire, final Request req, final String home,
Query(
final Wire wire, final Request req, final String home,
final Collection<Map.Entry<String, String>> hdrs,
final InputStream input, final int cnct,
final int rdd) {
final int rdd
) {
this.origin = wire;
this.request = req;
this.uri = home;
Expand All @@ -254,12 +311,8 @@ private static final class Query {
this.read = rdd;
}

/**
* Fetch.
* @return Response
* @throws IOException If fails
*/
public Response fetch() throws IOException {
@Override
public Response call() throws IOException {
return this.origin.send(
this.request, this.uri, Request.GET, this.headers, this.body,
this.connect, this.read
Expand Down
Loading

1 comment on commit d477467

@0pdd
Copy link

@0pdd 0pdd commented on d477467 Sep 3, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Puzzle 179-2a860650 discovered in src/main/java/com/jcabi/http/wire/CachingWire.java and submitted as #222. Please, remember that the puzzle was not necessarily added in this particular commit. Maybe it was added earlier, but we discovered it only now.

Please sign in to comment.