Skip to content

Commit

Permalink
Issue 1929 - define function as lambda (#1945)
Browse files Browse the repository at this point in the history
* define function as lambda

* Replace anonymous inner class with lambda

* method reference

* spacing

* method reference
  • Loading branch information
wcekan committed Mar 26, 2021
1 parent ed94182 commit 5aa899e
Show file tree
Hide file tree
Showing 15 changed files with 67 additions and 123 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import javax.ws.rs.PathParam;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.container.TimeoutHandler;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
Expand Down Expand Up @@ -68,12 +67,9 @@ public ExportApiEndpoint(
public void get(@PathParam("asyncQueryId") String asyncQueryId, @Context HttpServletResponse httpServletResponse,
@Suspended final AsyncResponse asyncResponse) {
asyncResponse.setTimeout(exportApiProperties.getMaxDownloadTimeSeconds(), TimeUnit.SECONDS);
asyncResponse.setTimeoutHandler(new TimeoutHandler() {
@Override
public void handleTimeout(AsyncResponse asyncResponse) {
ResponseBuilder resp = Response.status(Response.Status.REQUEST_TIMEOUT).entity("Timed out.");
asyncResponse.resume(resp.build());
}
asyncResponse.setTimeoutHandler(async -> {
ResponseBuilder resp = Response.status(Response.Status.REQUEST_TIMEOUT).entity("Timed out.");
async.resume(resp.build());
});

exportApiProperties.getExecutor().submit(() -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ public TableExport storeResults(TableExport tableExport, Observable<String> resu
throwable -> {
throw new IllegalStateException(STORE_ERROR, throwable);
},
() ->
writer.flush()
writer::flush
);
} catch (IOException e) {
throw new IllegalStateException(STORE_ERROR, e);
Expand Down
4 changes: 1 addition & 3 deletions elide-core/src/main/java/com/yahoo/elide/Elide.java
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,7 @@ public Elide(ElideSettings elideSettings) {
this.mapper = elideSettings.getMapper();
this.transactionRegistry = new TransactionRegistry();

elideSettings.getSerdes().forEach((targetType, serde) -> {
CoerceUtil.register(targetType, serde);
});
elideSettings.getSerdes().forEach(CoerceUtil::register);

registerCustomSerde();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,22 +81,14 @@ public Object getRelation(DataStoreTransaction relationTx,
Object entity,
Relationship relationship,
RequestScope scope) {
DataFetcher fetcher = new DataFetcher() {
@Override
public Object fetch(Optional<FilterExpression> filterExpression,
Optional<Sorting> sorting,
Optional<Pagination> pagination,
RequestScope scope) {

return tx.getRelation(relationTx, entity, relationship.copyOf()
DataFetcher fetcher = (filterExpression, sorting, pagination, requestScope) ->
tx.getRelation(relationTx, entity, relationship.copyOf()
.projection(relationship.getProjection().copyOf()
.filterExpression(filterExpression.orElse(null))
.sorting(sorting.orElse(null))
.pagination(pagination.orElse(null))
.build()
).build(), scope);
}
};
).build(), requestScope);


/*
Expand All @@ -123,20 +115,12 @@ public Object loadObject(EntityProjection projection,
public Iterable<Object> loadObjects(EntityProjection projection,
RequestScope scope) {

DataFetcher fetcher = new DataFetcher() {
@Override
public Iterable<Object> fetch(Optional<FilterExpression> filterExpression,
Optional<Sorting> sorting,
Optional<Pagination> pagination,
RequestScope scope) {

return tx.loadObjects(projection.copyOf()
DataFetcher fetcher = (filterExpression, sorting, pagination, requestScope) ->
tx.loadObjects(projection.copyOf()
.filterExpression(filterExpression.orElse(null))
.pagination(pagination.orElse(null))
.sorting(sorting.orElse(null))
.build(), scope);
}
};
.build(), requestScope);

return (Iterable<Object>) fetchData(fetcher, Optional.empty(), projection, false, scope);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -592,12 +592,7 @@ public <A extends Annotation> Collection<LifeCycleHook> getTriggers(Operation op
/**
* Cache placeholder for no annotation.
*/
private static final Annotation NO_ANNOTATION = new Annotation() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
};
private static final Annotation NO_ANNOTATION = () -> null;

/**
* Return annotation from class, parents or package.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,18 +157,15 @@ public EntityDictionary(Map<String, Class<? extends Check>> checks, Set<Type<?>>
initializeChecks();

//Default injector only injects Elide internals.
this.injector = new Injector() {
@Override
public void inject(Object entity) {
if (entity instanceof FilterExpressionCheck) {
try {
java.lang.reflect.Field field =
FilterExpressionCheck.class.getDeclaredField("dictionary");
field.setAccessible(true);
field.set(entity, EntityDictionary.this);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
this.injector = entity -> {
if (entity instanceof FilterExpressionCheck) {
try {
java.lang.reflect.Field field =
FilterExpressionCheck.class.getDeclaredField("dictionary");
field.setAccessible(true);
field.set(entity, EntityDictionary.this);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
};
Expand Down Expand Up @@ -1997,32 +1994,25 @@ private void bindHookMethod(
}

private static LifeCycleHook generateHook(Method method) {
return new LifeCycleHook() {
@Override
public void execute(Operation operation,
TransactionPhase phase,
Object model,
com.yahoo.elide.core.security.RequestScope scope,
Optional changes) {
try {
int paramCount = method.getParameterCount();
Class<?>[] paramTypes = method.getParameterTypes();

if (changes.isPresent() && paramCount == 2
&& paramTypes[0].isInstance(scope)
&& paramTypes[1].isInstance(changes.get())) {
method.invoke(model, scope, changes.get());
} else if (paramCount == 1 && paramTypes[0].isInstance(scope)) {
method.invoke(model, scope);
} else if (paramCount == 0) {
method.invoke(model);
} else {
throw new IllegalArgumentException();
}
} catch (ReflectiveOperationException e) {
Throwables.propagateIfPossible(e.getCause());
throw new IllegalArgumentException(e);
return (operation, phase, model, scope, changes) -> {
try {
int paramCount = method.getParameterCount();
Class<?>[] paramTypes = method.getParameterTypes();

if (changes.isPresent() && paramCount == 2
&& paramTypes[0].isInstance(scope)
&& paramTypes[1].isInstance(changes.get())) {
method.invoke(model, scope, changes.get());
} else if (paramCount == 1 && paramTypes[0].isInstance(scope)) {
method.invoke(model, scope);
} else if (paramCount == 0) {
method.invoke(model);
} else {
throw new IllegalArgumentException();
}
} catch (ReflectiveOperationException e) {
Throwables.propagateIfPossible(e.getCause());
throw new IllegalArgumentException(e);
}
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ private void parseArguments(String argsString, Set<Argument> arguments) throws U
private void addDefaultArguments(Set<Argument> clientArguments, Set<ArgumentType> availableArgTypes) {

Set<String> clientArgNames = clientArguments.stream()
.map(arg -> arg.getName())
.map(Argument::getName)
.collect(Collectors.toSet());

// Check if there is any argument which has default value but not provided by client, then add it.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.persistence.Entity;

Expand All @@ -53,12 +54,8 @@ public class MetaDataStore implements DataStore {
Arrays.asList(FromTable.class, FromSubquery.class, Subselect.class, javax.persistence.Table.class,
javax.persistence.Entity.class);

private static final java.util.function.Function<String, HashMapDataStore> SERVER_ERROR =
new java.util.function.Function<String, HashMapDataStore>() {
@Override
public HashMapDataStore apply(String key) {
throw new InternalServerErrorException("API version " + key + " not found");
}
private static final Function<String, HashMapDataStore> SERVER_ERROR = key -> {
throw new InternalServerErrorException("API version " + key + " not found");
};

@Getter
Expand Down Expand Up @@ -171,16 +168,13 @@ public void populateEntityDictionary(EntityDictionary dictionary) {
}
}

private final java.util.function.Function<String, HashMapDataStore> getHashMapDataStoreInitializer() {
return new java.util.function.Function<String, HashMapDataStore>() {
@Override
public HashMapDataStore apply(String key) {
HashMapDataStore hashMapDataStore = new HashMapDataStore(META_DATA_PACKAGE);
EntityDictionary dictionary = new EntityDictionary(new HashMap<>());
metadataModelClasses.forEach(dictionary::bindEntity);
hashMapDataStore.populateEntityDictionary(dictionary);
return hashMapDataStore;
}
private final Function<String, HashMapDataStore> getHashMapDataStoreInitializer() {
return key -> {
HashMapDataStore hashMapDataStore = new HashMapDataStore(META_DATA_PACKAGE);
EntityDictionary dictionary = new EntityDictionary(new HashMap<>());
metadataModelClasses.forEach(dictionary::bindEntity);
hashMapDataStore.populateEntityDictionary(dictionary);
return hashMapDataStore;
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,8 @@
*/
public class MetaDataStoreTransaction implements DataStoreTransaction {

private static final Function<String, HashMapDataStore> REQUEST_ERROR = new Function<String, HashMapDataStore>() {
@Override
public HashMapDataStore apply(String key) {
throw new BadRequestException("API version " + key + " not found");
}
private static final Function<String, HashMapDataStore> REQUEST_ERROR = key -> {
throw new BadRequestException("API version " + key + " not found");
};

private final Map<String, HashMapDataStore> hashMapDataStores;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,18 +101,14 @@ public SQLQueryEngine(MetaDataStore metaDataStore, ConnectionDetails defaultConn
this.optimizers = optimizers;
}

private static final Function<ResultSet, Object> SINGLE_RESULT_MAPPER = new Function<ResultSet, Object>() {
@Override
public Object apply(ResultSet rs) {
try {
if (rs.next()) {
return rs.getObject(1);
} else {
return null;
}
} catch (SQLException e) {
throw new IllegalStateException(e);
private static final Function<ResultSet, Object> SINGLE_RESULT_MAPPER = rs -> {
try {
if (rs.next()) {
return rs.getObject(1);
}
return null;
} catch (SQLException e) {
throw new IllegalStateException(e);
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,7 @@ public PersistentResourceFetcherTest() {
.withISO8601Dates("yyyy-MM-dd'T'HH:mm'Z'", TimeZone.getTimeZone("UTC"))
.build();

settings.getSerdes().forEach((targetType, serde) -> {
CoerceUtil.register(targetType, serde);
});
settings.getSerdes().forEach(CoerceUtil::register);

hashMapDataStore = new HashMapDataStore(Author.class.getPackage());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public class ElideTableConfig {
public boolean hasTable(String name) {
return tables
.stream()
.map(t -> t.getName())
.map(Named::getName)
.anyMatch(name::equals);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public interface Named {
default boolean hasName(Collection<? extends Named> collection, String name) {
return collection
.stream()
.map(obj -> obj.getName())
.map(Named::getName)
.anyMatch(name::equals);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -636,13 +636,13 @@ private static void validateJoinedTablesDBConnectionName(ElideTableConfig elideT

Set<String> joinedTables = table.getJoins()
.stream()
.map(join -> join.getTo())
.map(Join::getTo)
.collect(Collectors.toSet());

Set<String> connections = elideTableConfig.getTables()
.stream()
.filter(t -> joinedTables.contains(t.getName()))
.map(t -> t.getDbConnectionName())
.map(Table::getDbConnectionName)
.collect(Collectors.toSet());

if (connections.size() > 1 || (connections.size() == 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,11 @@ public DocEndpoint(@Named("swagger") List<SwaggerRegistration> docs) {
public Response list(@HeaderParam("ApiVersion") String apiVersion) {
String safeApiVersion = apiVersion == null ? NO_VERSION : apiVersion;

List<String> documentPaths = documents.keySet().stream()
String body = documents.keySet().stream()
.filter(key -> key.getLeft().equals(safeApiVersion))
.map(key -> key.getRight())
.collect(Collectors.toList());

String body = "[" + documentPaths.stream()
.map(Pair::getRight)
.map(key -> '"' + key + '"')
.collect(Collectors.joining(",")) + "]";
.collect(Collectors.joining(",", "[", "]"));

return Response.ok(body).build();
}
Expand Down

0 comments on commit 5aa899e

Please sign in to comment.