repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
gibffe/fuse
src/main/java/com/sulaco/fuse/akka/actor/RouteFinderActor.java
// Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessageImpl.java // public class FuseRequestMessageImpl implements FuseRequestMessage { // // long id; // // HttpRequest incomingRequest; // // ChannelHandlerContext channelContext; // // Route route; // // volatile boolean flushed = false; // // public FuseRequestMessageImpl(long id, ChannelHandlerContext context, HttpRequest request) { // this.id = id; // this.channelContext = context; // this.incomingRequest = request; // } // // @Override // public long getId() { // return id; // } // // @Override // public HttpRequest getRequest() { // return incomingRequest; // } // // @Override // public ChannelHandlerContext getChannelContext() { // return channelContext; // } // // @Override // public RouteHandler getHandler() { // return route.getHandler(); // } // // @Override // public Map<String, String> getParams() { // return route.getParams(); // } // // @Override // public Optional<String> getParam(String name) { // return route.getParam(name); // } // // @Override // public <T> Optional<T> getParam(String name, Class<T> clazz) { // Optional<String> param = route.getParam(name); // return param.map(v -> PrimitiveConverters.convert(v, clazz)); // } // // @Override // public String getRequestBody() { // return ((DefaultFullHttpRequest) incomingRequest).content().toString(charset_utf8); // } // // public void setRoute(Route route) { // this.route = route; // } // // @Override // public void flush() { // channelContext.flush(); // flushed = true; // } // // @Override // public boolean flushed() { // return flushed; // } // // private static final Charset charset_utf8 = Charset.forName("UTF-8"); // // } // // Path: src/main/java/com/sulaco/fuse/config/route/Route.java // public interface Route { // // public RouteHandler getHandler(); // // public Map<String, String> getParams(); // // public Optional<String> getParam(String name); // // } // // Path: src/main/java/com/sulaco/fuse/config/route/RoutesConfig.java // public interface RoutesConfig { // // public void parse(); // // public Optional<Route> getFuseRoute(String uri); // // public void addEndpoint(ActorRef ref, String httpMethod, String path); // }
import io.netty.handler.codec.http.HttpMethod; import java.util.Optional; import io.netty.handler.codec.http.HttpResponseStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.akka.message.FuseRequestMessageImpl; import com.sulaco.fuse.config.route.Route; import com.sulaco.fuse.config.route.RoutesConfig;
package com.sulaco.fuse.akka.actor; public class RouteFinderActor extends FuseEndpointActor { @Autowired protected RoutesConfig routes; @Override protected void onRequest(final FuseRequestMessage message) { String uri = message.getRequest().getUri(); Optional<Route> route = routes.getFuseRoute(uri); if (route.isPresent()) { Route rte = route.get(); // add route to the message
// Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessageImpl.java // public class FuseRequestMessageImpl implements FuseRequestMessage { // // long id; // // HttpRequest incomingRequest; // // ChannelHandlerContext channelContext; // // Route route; // // volatile boolean flushed = false; // // public FuseRequestMessageImpl(long id, ChannelHandlerContext context, HttpRequest request) { // this.id = id; // this.channelContext = context; // this.incomingRequest = request; // } // // @Override // public long getId() { // return id; // } // // @Override // public HttpRequest getRequest() { // return incomingRequest; // } // // @Override // public ChannelHandlerContext getChannelContext() { // return channelContext; // } // // @Override // public RouteHandler getHandler() { // return route.getHandler(); // } // // @Override // public Map<String, String> getParams() { // return route.getParams(); // } // // @Override // public Optional<String> getParam(String name) { // return route.getParam(name); // } // // @Override // public <T> Optional<T> getParam(String name, Class<T> clazz) { // Optional<String> param = route.getParam(name); // return param.map(v -> PrimitiveConverters.convert(v, clazz)); // } // // @Override // public String getRequestBody() { // return ((DefaultFullHttpRequest) incomingRequest).content().toString(charset_utf8); // } // // public void setRoute(Route route) { // this.route = route; // } // // @Override // public void flush() { // channelContext.flush(); // flushed = true; // } // // @Override // public boolean flushed() { // return flushed; // } // // private static final Charset charset_utf8 = Charset.forName("UTF-8"); // // } // // Path: src/main/java/com/sulaco/fuse/config/route/Route.java // public interface Route { // // public RouteHandler getHandler(); // // public Map<String, String> getParams(); // // public Optional<String> getParam(String name); // // } // // Path: src/main/java/com/sulaco/fuse/config/route/RoutesConfig.java // public interface RoutesConfig { // // public void parse(); // // public Optional<Route> getFuseRoute(String uri); // // public void addEndpoint(ActorRef ref, String httpMethod, String path); // } // Path: src/main/java/com/sulaco/fuse/akka/actor/RouteFinderActor.java import io.netty.handler.codec.http.HttpMethod; import java.util.Optional; import io.netty.handler.codec.http.HttpResponseStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.akka.message.FuseRequestMessageImpl; import com.sulaco.fuse.config.route.Route; import com.sulaco.fuse.config.route.RoutesConfig; package com.sulaco.fuse.akka.actor; public class RouteFinderActor extends FuseEndpointActor { @Autowired protected RoutesConfig routes; @Override protected void onRequest(final FuseRequestMessage message) { String uri = message.getRequest().getUri(); Optional<Route> route = routes.getFuseRoute(uri); if (route.isPresent()) { Route rte = route.get(); // add route to the message
((FuseRequestMessageImpl) message).setRoute(rte);
gibffe/fuse
src/main/java/com/sulaco/fuse/akka/actor/NoopActor.java
// Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import com.sulaco.fuse.akka.message.FuseRequestMessage;
package com.sulaco.fuse.akka.actor; public class NoopActor extends FuseEndpointActor { @Override
// Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: src/main/java/com/sulaco/fuse/akka/actor/NoopActor.java import com.sulaco.fuse.akka.message.FuseRequestMessage; package com.sulaco.fuse.akka.actor; public class NoopActor extends FuseEndpointActor { @Override
protected void onRequest(FuseRequestMessage message) {
gibffe/fuse
src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessageImpl.java
// Path: src/main/java/com/sulaco/fuse/util/PrimitiveConverters.java // @SuppressWarnings({"unchecked"}) // public class PrimitiveConverters { // // static Map<Class<?>, Function<String, ?>> converters = new HashMap<>(); // static { // converters.put(Integer.class , Integer::valueOf); // converters.put(Long.class , Long::valueOf); // converters.put(Double.class , Double::valueOf); // converters.put(Float.class , Float::valueOf); // converters.put(Boolean.class , Boolean::valueOf); // } // // public static <T> T convert(String value, Class<T> target) { // // T converted = // (T) converters.getOrDefault(target, v -> null) // .apply(value); // // return converted; // } // // } // // Path: src/main/java/com/sulaco/fuse/config/route/Route.java // public interface Route { // // public RouteHandler getHandler(); // // public Map<String, String> getParams(); // // public Optional<String> getParam(String name); // // } // // Path: src/main/java/com/sulaco/fuse/config/route/RouteHandler.java // public class RouteHandler { // // Optional<ActorRef> actor; // // Optional<String> methodName; // // HttpMethod httpMethod; // // // private RouteHandler() { // actor = Optional.ofNullable(null); // methodName = Optional.ofNullable(null); // httpMethod = HttpMethod.GET; // } // // public static RouteHandlerBuilder builder() { // return new RouteHandlerBuilder(); // } // // public RouteHandler(Optional<ActorRef> actor, String methodName) { // this.actor = actor; // this.methodName = Optional.ofNullable(methodName); // } // // public Optional<ActorRef> getActor() { // return actor; // } // // public Optional<String> getMethodName() { // return methodName; // } // // public HttpMethod getHttpMethod() { // return httpMethod; // } // // // public static class RouteHandlerBuilder { // // private RouteHandler instance; // // public RouteHandlerBuilder() { // this.instance = new RouteHandler(); // } // // public RouteHandlerBuilder withActorRef(Optional<ActorRef> actor) { // instance.actor = actor; // return this; // } // // public RouteHandlerBuilder withMethodName(String methodName) { // instance.methodName = Optional.ofNullable(methodName); // return this; // } // // public RouteHandlerBuilder withHttpMethod(String httpMethod) { // if (!StringUtils.isEmpty(httpMethod)) { // try { // instance.httpMethod = HttpMethod.valueOf(httpMethod); // } // catch (Exception ex) { // log.warn("Invalid method specified:{}, defaulting to GET", httpMethod, ex); // instance.httpMethod = HttpMethod.GET; // } // } // return this; // } // // public RouteHandler build() { // return instance; // } // } // // private static final Logger log = LoggerFactory.getLogger(RouteHandler.class); // // }
import com.sulaco.fuse.util.PrimitiveConverters; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.HttpRequest; import java.nio.charset.Charset; import java.util.Map; import java.util.Optional; import java.util.UUID; import com.sulaco.fuse.config.route.Route; import com.sulaco.fuse.config.route.RouteHandler;
package com.sulaco.fuse.akka.message; public class FuseRequestMessageImpl implements FuseRequestMessage { long id; HttpRequest incomingRequest; ChannelHandlerContext channelContext;
// Path: src/main/java/com/sulaco/fuse/util/PrimitiveConverters.java // @SuppressWarnings({"unchecked"}) // public class PrimitiveConverters { // // static Map<Class<?>, Function<String, ?>> converters = new HashMap<>(); // static { // converters.put(Integer.class , Integer::valueOf); // converters.put(Long.class , Long::valueOf); // converters.put(Double.class , Double::valueOf); // converters.put(Float.class , Float::valueOf); // converters.put(Boolean.class , Boolean::valueOf); // } // // public static <T> T convert(String value, Class<T> target) { // // T converted = // (T) converters.getOrDefault(target, v -> null) // .apply(value); // // return converted; // } // // } // // Path: src/main/java/com/sulaco/fuse/config/route/Route.java // public interface Route { // // public RouteHandler getHandler(); // // public Map<String, String> getParams(); // // public Optional<String> getParam(String name); // // } // // Path: src/main/java/com/sulaco/fuse/config/route/RouteHandler.java // public class RouteHandler { // // Optional<ActorRef> actor; // // Optional<String> methodName; // // HttpMethod httpMethod; // // // private RouteHandler() { // actor = Optional.ofNullable(null); // methodName = Optional.ofNullable(null); // httpMethod = HttpMethod.GET; // } // // public static RouteHandlerBuilder builder() { // return new RouteHandlerBuilder(); // } // // public RouteHandler(Optional<ActorRef> actor, String methodName) { // this.actor = actor; // this.methodName = Optional.ofNullable(methodName); // } // // public Optional<ActorRef> getActor() { // return actor; // } // // public Optional<String> getMethodName() { // return methodName; // } // // public HttpMethod getHttpMethod() { // return httpMethod; // } // // // public static class RouteHandlerBuilder { // // private RouteHandler instance; // // public RouteHandlerBuilder() { // this.instance = new RouteHandler(); // } // // public RouteHandlerBuilder withActorRef(Optional<ActorRef> actor) { // instance.actor = actor; // return this; // } // // public RouteHandlerBuilder withMethodName(String methodName) { // instance.methodName = Optional.ofNullable(methodName); // return this; // } // // public RouteHandlerBuilder withHttpMethod(String httpMethod) { // if (!StringUtils.isEmpty(httpMethod)) { // try { // instance.httpMethod = HttpMethod.valueOf(httpMethod); // } // catch (Exception ex) { // log.warn("Invalid method specified:{}, defaulting to GET", httpMethod, ex); // instance.httpMethod = HttpMethod.GET; // } // } // return this; // } // // public RouteHandler build() { // return instance; // } // } // // private static final Logger log = LoggerFactory.getLogger(RouteHandler.class); // // } // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessageImpl.java import com.sulaco.fuse.util.PrimitiveConverters; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.HttpRequest; import java.nio.charset.Charset; import java.util.Map; import java.util.Optional; import java.util.UUID; import com.sulaco.fuse.config.route.Route; import com.sulaco.fuse.config.route.RouteHandler; package com.sulaco.fuse.akka.message; public class FuseRequestMessageImpl implements FuseRequestMessage { long id; HttpRequest incomingRequest; ChannelHandlerContext channelContext;
Route route;
gibffe/fuse
src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessageImpl.java
// Path: src/main/java/com/sulaco/fuse/util/PrimitiveConverters.java // @SuppressWarnings({"unchecked"}) // public class PrimitiveConverters { // // static Map<Class<?>, Function<String, ?>> converters = new HashMap<>(); // static { // converters.put(Integer.class , Integer::valueOf); // converters.put(Long.class , Long::valueOf); // converters.put(Double.class , Double::valueOf); // converters.put(Float.class , Float::valueOf); // converters.put(Boolean.class , Boolean::valueOf); // } // // public static <T> T convert(String value, Class<T> target) { // // T converted = // (T) converters.getOrDefault(target, v -> null) // .apply(value); // // return converted; // } // // } // // Path: src/main/java/com/sulaco/fuse/config/route/Route.java // public interface Route { // // public RouteHandler getHandler(); // // public Map<String, String> getParams(); // // public Optional<String> getParam(String name); // // } // // Path: src/main/java/com/sulaco/fuse/config/route/RouteHandler.java // public class RouteHandler { // // Optional<ActorRef> actor; // // Optional<String> methodName; // // HttpMethod httpMethod; // // // private RouteHandler() { // actor = Optional.ofNullable(null); // methodName = Optional.ofNullable(null); // httpMethod = HttpMethod.GET; // } // // public static RouteHandlerBuilder builder() { // return new RouteHandlerBuilder(); // } // // public RouteHandler(Optional<ActorRef> actor, String methodName) { // this.actor = actor; // this.methodName = Optional.ofNullable(methodName); // } // // public Optional<ActorRef> getActor() { // return actor; // } // // public Optional<String> getMethodName() { // return methodName; // } // // public HttpMethod getHttpMethod() { // return httpMethod; // } // // // public static class RouteHandlerBuilder { // // private RouteHandler instance; // // public RouteHandlerBuilder() { // this.instance = new RouteHandler(); // } // // public RouteHandlerBuilder withActorRef(Optional<ActorRef> actor) { // instance.actor = actor; // return this; // } // // public RouteHandlerBuilder withMethodName(String methodName) { // instance.methodName = Optional.ofNullable(methodName); // return this; // } // // public RouteHandlerBuilder withHttpMethod(String httpMethod) { // if (!StringUtils.isEmpty(httpMethod)) { // try { // instance.httpMethod = HttpMethod.valueOf(httpMethod); // } // catch (Exception ex) { // log.warn("Invalid method specified:{}, defaulting to GET", httpMethod, ex); // instance.httpMethod = HttpMethod.GET; // } // } // return this; // } // // public RouteHandler build() { // return instance; // } // } // // private static final Logger log = LoggerFactory.getLogger(RouteHandler.class); // // }
import com.sulaco.fuse.util.PrimitiveConverters; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.HttpRequest; import java.nio.charset.Charset; import java.util.Map; import java.util.Optional; import java.util.UUID; import com.sulaco.fuse.config.route.Route; import com.sulaco.fuse.config.route.RouteHandler;
package com.sulaco.fuse.akka.message; public class FuseRequestMessageImpl implements FuseRequestMessage { long id; HttpRequest incomingRequest; ChannelHandlerContext channelContext; Route route; volatile boolean flushed = false; public FuseRequestMessageImpl(long id, ChannelHandlerContext context, HttpRequest request) { this.id = id; this.channelContext = context; this.incomingRequest = request; } @Override public long getId() { return id; } @Override public HttpRequest getRequest() { return incomingRequest; } @Override public ChannelHandlerContext getChannelContext() { return channelContext; } @Override
// Path: src/main/java/com/sulaco/fuse/util/PrimitiveConverters.java // @SuppressWarnings({"unchecked"}) // public class PrimitiveConverters { // // static Map<Class<?>, Function<String, ?>> converters = new HashMap<>(); // static { // converters.put(Integer.class , Integer::valueOf); // converters.put(Long.class , Long::valueOf); // converters.put(Double.class , Double::valueOf); // converters.put(Float.class , Float::valueOf); // converters.put(Boolean.class , Boolean::valueOf); // } // // public static <T> T convert(String value, Class<T> target) { // // T converted = // (T) converters.getOrDefault(target, v -> null) // .apply(value); // // return converted; // } // // } // // Path: src/main/java/com/sulaco/fuse/config/route/Route.java // public interface Route { // // public RouteHandler getHandler(); // // public Map<String, String> getParams(); // // public Optional<String> getParam(String name); // // } // // Path: src/main/java/com/sulaco/fuse/config/route/RouteHandler.java // public class RouteHandler { // // Optional<ActorRef> actor; // // Optional<String> methodName; // // HttpMethod httpMethod; // // // private RouteHandler() { // actor = Optional.ofNullable(null); // methodName = Optional.ofNullable(null); // httpMethod = HttpMethod.GET; // } // // public static RouteHandlerBuilder builder() { // return new RouteHandlerBuilder(); // } // // public RouteHandler(Optional<ActorRef> actor, String methodName) { // this.actor = actor; // this.methodName = Optional.ofNullable(methodName); // } // // public Optional<ActorRef> getActor() { // return actor; // } // // public Optional<String> getMethodName() { // return methodName; // } // // public HttpMethod getHttpMethod() { // return httpMethod; // } // // // public static class RouteHandlerBuilder { // // private RouteHandler instance; // // public RouteHandlerBuilder() { // this.instance = new RouteHandler(); // } // // public RouteHandlerBuilder withActorRef(Optional<ActorRef> actor) { // instance.actor = actor; // return this; // } // // public RouteHandlerBuilder withMethodName(String methodName) { // instance.methodName = Optional.ofNullable(methodName); // return this; // } // // public RouteHandlerBuilder withHttpMethod(String httpMethod) { // if (!StringUtils.isEmpty(httpMethod)) { // try { // instance.httpMethod = HttpMethod.valueOf(httpMethod); // } // catch (Exception ex) { // log.warn("Invalid method specified:{}, defaulting to GET", httpMethod, ex); // instance.httpMethod = HttpMethod.GET; // } // } // return this; // } // // public RouteHandler build() { // return instance; // } // } // // private static final Logger log = LoggerFactory.getLogger(RouteHandler.class); // // } // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessageImpl.java import com.sulaco.fuse.util.PrimitiveConverters; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.HttpRequest; import java.nio.charset.Charset; import java.util.Map; import java.util.Optional; import java.util.UUID; import com.sulaco.fuse.config.route.Route; import com.sulaco.fuse.config.route.RouteHandler; package com.sulaco.fuse.akka.message; public class FuseRequestMessageImpl implements FuseRequestMessage { long id; HttpRequest incomingRequest; ChannelHandlerContext channelContext; Route route; volatile boolean flushed = false; public FuseRequestMessageImpl(long id, ChannelHandlerContext context, HttpRequest request) { this.id = id; this.channelContext = context; this.incomingRequest = request; } @Override public long getId() { return id; } @Override public HttpRequest getRequest() { return incomingRequest; } @Override public ChannelHandlerContext getChannelContext() { return channelContext; } @Override
public RouteHandler getHandler() {
gibffe/fuse
src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessageImpl.java
// Path: src/main/java/com/sulaco/fuse/util/PrimitiveConverters.java // @SuppressWarnings({"unchecked"}) // public class PrimitiveConverters { // // static Map<Class<?>, Function<String, ?>> converters = new HashMap<>(); // static { // converters.put(Integer.class , Integer::valueOf); // converters.put(Long.class , Long::valueOf); // converters.put(Double.class , Double::valueOf); // converters.put(Float.class , Float::valueOf); // converters.put(Boolean.class , Boolean::valueOf); // } // // public static <T> T convert(String value, Class<T> target) { // // T converted = // (T) converters.getOrDefault(target, v -> null) // .apply(value); // // return converted; // } // // } // // Path: src/main/java/com/sulaco/fuse/config/route/Route.java // public interface Route { // // public RouteHandler getHandler(); // // public Map<String, String> getParams(); // // public Optional<String> getParam(String name); // // } // // Path: src/main/java/com/sulaco/fuse/config/route/RouteHandler.java // public class RouteHandler { // // Optional<ActorRef> actor; // // Optional<String> methodName; // // HttpMethod httpMethod; // // // private RouteHandler() { // actor = Optional.ofNullable(null); // methodName = Optional.ofNullable(null); // httpMethod = HttpMethod.GET; // } // // public static RouteHandlerBuilder builder() { // return new RouteHandlerBuilder(); // } // // public RouteHandler(Optional<ActorRef> actor, String methodName) { // this.actor = actor; // this.methodName = Optional.ofNullable(methodName); // } // // public Optional<ActorRef> getActor() { // return actor; // } // // public Optional<String> getMethodName() { // return methodName; // } // // public HttpMethod getHttpMethod() { // return httpMethod; // } // // // public static class RouteHandlerBuilder { // // private RouteHandler instance; // // public RouteHandlerBuilder() { // this.instance = new RouteHandler(); // } // // public RouteHandlerBuilder withActorRef(Optional<ActorRef> actor) { // instance.actor = actor; // return this; // } // // public RouteHandlerBuilder withMethodName(String methodName) { // instance.methodName = Optional.ofNullable(methodName); // return this; // } // // public RouteHandlerBuilder withHttpMethod(String httpMethod) { // if (!StringUtils.isEmpty(httpMethod)) { // try { // instance.httpMethod = HttpMethod.valueOf(httpMethod); // } // catch (Exception ex) { // log.warn("Invalid method specified:{}, defaulting to GET", httpMethod, ex); // instance.httpMethod = HttpMethod.GET; // } // } // return this; // } // // public RouteHandler build() { // return instance; // } // } // // private static final Logger log = LoggerFactory.getLogger(RouteHandler.class); // // }
import com.sulaco.fuse.util.PrimitiveConverters; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.HttpRequest; import java.nio.charset.Charset; import java.util.Map; import java.util.Optional; import java.util.UUID; import com.sulaco.fuse.config.route.Route; import com.sulaco.fuse.config.route.RouteHandler;
} @Override public HttpRequest getRequest() { return incomingRequest; } @Override public ChannelHandlerContext getChannelContext() { return channelContext; } @Override public RouteHandler getHandler() { return route.getHandler(); } @Override public Map<String, String> getParams() { return route.getParams(); } @Override public Optional<String> getParam(String name) { return route.getParam(name); } @Override public <T> Optional<T> getParam(String name, Class<T> clazz) { Optional<String> param = route.getParam(name);
// Path: src/main/java/com/sulaco/fuse/util/PrimitiveConverters.java // @SuppressWarnings({"unchecked"}) // public class PrimitiveConverters { // // static Map<Class<?>, Function<String, ?>> converters = new HashMap<>(); // static { // converters.put(Integer.class , Integer::valueOf); // converters.put(Long.class , Long::valueOf); // converters.put(Double.class , Double::valueOf); // converters.put(Float.class , Float::valueOf); // converters.put(Boolean.class , Boolean::valueOf); // } // // public static <T> T convert(String value, Class<T> target) { // // T converted = // (T) converters.getOrDefault(target, v -> null) // .apply(value); // // return converted; // } // // } // // Path: src/main/java/com/sulaco/fuse/config/route/Route.java // public interface Route { // // public RouteHandler getHandler(); // // public Map<String, String> getParams(); // // public Optional<String> getParam(String name); // // } // // Path: src/main/java/com/sulaco/fuse/config/route/RouteHandler.java // public class RouteHandler { // // Optional<ActorRef> actor; // // Optional<String> methodName; // // HttpMethod httpMethod; // // // private RouteHandler() { // actor = Optional.ofNullable(null); // methodName = Optional.ofNullable(null); // httpMethod = HttpMethod.GET; // } // // public static RouteHandlerBuilder builder() { // return new RouteHandlerBuilder(); // } // // public RouteHandler(Optional<ActorRef> actor, String methodName) { // this.actor = actor; // this.methodName = Optional.ofNullable(methodName); // } // // public Optional<ActorRef> getActor() { // return actor; // } // // public Optional<String> getMethodName() { // return methodName; // } // // public HttpMethod getHttpMethod() { // return httpMethod; // } // // // public static class RouteHandlerBuilder { // // private RouteHandler instance; // // public RouteHandlerBuilder() { // this.instance = new RouteHandler(); // } // // public RouteHandlerBuilder withActorRef(Optional<ActorRef> actor) { // instance.actor = actor; // return this; // } // // public RouteHandlerBuilder withMethodName(String methodName) { // instance.methodName = Optional.ofNullable(methodName); // return this; // } // // public RouteHandlerBuilder withHttpMethod(String httpMethod) { // if (!StringUtils.isEmpty(httpMethod)) { // try { // instance.httpMethod = HttpMethod.valueOf(httpMethod); // } // catch (Exception ex) { // log.warn("Invalid method specified:{}, defaulting to GET", httpMethod, ex); // instance.httpMethod = HttpMethod.GET; // } // } // return this; // } // // public RouteHandler build() { // return instance; // } // } // // private static final Logger log = LoggerFactory.getLogger(RouteHandler.class); // // } // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessageImpl.java import com.sulaco.fuse.util.PrimitiveConverters; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.HttpRequest; import java.nio.charset.Charset; import java.util.Map; import java.util.Optional; import java.util.UUID; import com.sulaco.fuse.config.route.Route; import com.sulaco.fuse.config.route.RouteHandler; } @Override public HttpRequest getRequest() { return incomingRequest; } @Override public ChannelHandlerContext getChannelContext() { return channelContext; } @Override public RouteHandler getHandler() { return route.getHandler(); } @Override public Map<String, String> getParams() { return route.getParams(); } @Override public Optional<String> getParam(String name) { return route.getParam(name); } @Override public <T> Optional<T> getParam(String name, Class<T> clazz) { Optional<String> param = route.getParam(name);
return param.map(v -> PrimitiveConverters.convert(v, clazz));
gibffe/fuse
src/main/java/com/sulaco/fuse/config/ConfigSourceImpl.java
// Path: src/main/java/com/sulaco/fuse/config/route/RoutesConfig.java // public interface RoutesConfig { // // public void parse(); // // public Optional<Route> getFuseRoute(String uri); // // public void addEndpoint(ActorRef ref, String httpMethod, String path); // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.sulaco.fuse.config.route.RoutesConfig; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory;
package com.sulaco.fuse.config; @Component public class ConfigSourceImpl implements ConfigSource { protected Config config;
// Path: src/main/java/com/sulaco/fuse/config/route/RoutesConfig.java // public interface RoutesConfig { // // public void parse(); // // public Optional<Route> getFuseRoute(String uri); // // public void addEndpoint(ActorRef ref, String httpMethod, String path); // } // Path: src/main/java/com/sulaco/fuse/config/ConfigSourceImpl.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.sulaco.fuse.config.route.RoutesConfig; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; package com.sulaco.fuse.config; @Component public class ConfigSourceImpl implements ConfigSource { protected Config config;
@Autowired protected RoutesConfig routesConfig;
gibffe/fuse
src/main/java/com/sulaco/fuse/akka/actor/ServerVersionActor.java
// Path: src/main/java/com/sulaco/fuse/FuseVersion.java // @Component // public class FuseVersion { // // String version = "Fuse v0.0.3-SNAPSHOT"; // // public FuseVersion() { // super(); // } // // public String toString() { // return version; // } // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import com.sulaco.fuse.FuseVersion; import com.sulaco.fuse.akka.message.FuseRequestMessage;
package com.sulaco.fuse.akka.actor; public class ServerVersionActor extends FuseEndpointActor { @Autowired FuseVersion version; @Override
// Path: src/main/java/com/sulaco/fuse/FuseVersion.java // @Component // public class FuseVersion { // // String version = "Fuse v0.0.3-SNAPSHOT"; // // public FuseVersion() { // super(); // } // // public String toString() { // return version; // } // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: src/main/java/com/sulaco/fuse/akka/actor/ServerVersionActor.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import com.sulaco.fuse.FuseVersion; import com.sulaco.fuse.akka.message.FuseRequestMessage; package com.sulaco.fuse.akka.actor; public class ServerVersionActor extends FuseEndpointActor { @Autowired FuseVersion version; @Override
protected void onRequest(FuseRequestMessage message) {
gibffe/fuse
src/main/java/com/sulaco/fuse/akka/actor/StaticContentActor.java
// Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: src/main/java/com/sulaco/fuse/config/ConfigSource.java // public interface ConfigSource { // // public void parseLocalConfig(); // // public Config getConfig(); // // public RoutesConfig getRoutesConfig(); // }
import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.config.ConfigSource; import io.netty.handler.codec.http.HttpResponseStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths;
package com.sulaco.fuse.akka.actor; public class StaticContentActor extends FuseEndpointActor { String contentDir = null;
// Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: src/main/java/com/sulaco/fuse/config/ConfigSource.java // public interface ConfigSource { // // public void parseLocalConfig(); // // public Config getConfig(); // // public RoutesConfig getRoutesConfig(); // } // Path: src/main/java/com/sulaco/fuse/akka/actor/StaticContentActor.java import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.config.ConfigSource; import io.netty.handler.codec.http.HttpResponseStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; package com.sulaco.fuse.akka.actor; public class StaticContentActor extends FuseEndpointActor { String contentDir = null;
@Autowired ConfigSource configSource;
gibffe/fuse
src/main/java/com/sulaco/fuse/akka/actor/StaticContentActor.java
// Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: src/main/java/com/sulaco/fuse/config/ConfigSource.java // public interface ConfigSource { // // public void parseLocalConfig(); // // public Config getConfig(); // // public RoutesConfig getRoutesConfig(); // }
import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.config.ConfigSource; import io.netty.handler.codec.http.HttpResponseStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths;
package com.sulaco.fuse.akka.actor; public class StaticContentActor extends FuseEndpointActor { String contentDir = null; @Autowired ConfigSource configSource; @Override
// Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: src/main/java/com/sulaco/fuse/config/ConfigSource.java // public interface ConfigSource { // // public void parseLocalConfig(); // // public Config getConfig(); // // public RoutesConfig getRoutesConfig(); // } // Path: src/main/java/com/sulaco/fuse/akka/actor/StaticContentActor.java import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.config.ConfigSource; import io.netty.handler.codec.http.HttpResponseStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; package com.sulaco.fuse.akka.actor; public class StaticContentActor extends FuseEndpointActor { String contentDir = null; @Autowired ConfigSource configSource; @Override
protected void onRequest(FuseRequestMessage request) {
gibffe/fuse
src/main/java/com/sulaco/fuse/util/Tools.java
// Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import java.lang.reflect.Method; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sulaco.fuse.akka.message.FuseRequestMessage;
package com.sulaco.fuse.util; public class Tools { private static ConcurrentMap<String, ConcurrentMap<String, String>> keyCache = new ConcurrentHashMap<>(); private static ConcurrentMap<String, Optional<Method>> methodCache = new ConcurrentHashMap<>(); public static <T> Optional<T> empty() { return Optional.empty(); } public static final <T> Optional<T> optional(T value) { return Optional.ofNullable(value); } public static final Optional<Method> lookupMethod(final Object target, final String methodName) { Class<?> clazz = target.getClass(); String key = getMethodKey(clazz.getName(), methodName); methodCache .computeIfAbsent( key, k -> { Method method = null; try {
// Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: src/main/java/com/sulaco/fuse/util/Tools.java import java.lang.reflect.Method; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sulaco.fuse.akka.message.FuseRequestMessage; package com.sulaco.fuse.util; public class Tools { private static ConcurrentMap<String, ConcurrentMap<String, String>> keyCache = new ConcurrentHashMap<>(); private static ConcurrentMap<String, Optional<Method>> methodCache = new ConcurrentHashMap<>(); public static <T> Optional<T> empty() { return Optional.empty(); } public static final <T> Optional<T> optional(T value) { return Optional.ofNullable(value); } public static final Optional<Method> lookupMethod(final Object target, final String methodName) { Class<?> clazz = target.getClass(); String key = getMethodKey(clazz.getName(), methodName); methodCache .computeIfAbsent( key, k -> { Method method = null; try {
method = clazz.getMethod(methodName, FuseRequestMessage.class);
gibffe/fuse
src/main/java/com/sulaco/fuse/akka/actor/SuspendedAnimationActor.java
// Path: src/main/java/com/sulaco/fuse/akka/async/RequestSuspender.java // public interface RequestSuspender { // // void suspend(FuseInternalMessage message); // // Optional<FuseInternalMessage> revive(long id); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseReviveMessage.java // public interface FuseReviveMessage { // // long getId(); // // Optional<?> getPayload(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseSuspendMessage.java // public interface FuseSuspendMessage extends FuseInternalMessage { // // }
import com.sulaco.fuse.akka.async.RequestSuspender; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseReviveMessage; import com.sulaco.fuse.akka.message.FuseSuspendMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional; import java.util.UUID;
package com.sulaco.fuse.akka.actor; public class SuspendedAnimationActor extends FuseBaseActor { @Autowired RequestSuspender suspender; @Override
// Path: src/main/java/com/sulaco/fuse/akka/async/RequestSuspender.java // public interface RequestSuspender { // // void suspend(FuseInternalMessage message); // // Optional<FuseInternalMessage> revive(long id); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseReviveMessage.java // public interface FuseReviveMessage { // // long getId(); // // Optional<?> getPayload(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseSuspendMessage.java // public interface FuseSuspendMessage extends FuseInternalMessage { // // } // Path: src/main/java/com/sulaco/fuse/akka/actor/SuspendedAnimationActor.java import com.sulaco.fuse.akka.async.RequestSuspender; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseReviveMessage; import com.sulaco.fuse.akka.message.FuseSuspendMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional; import java.util.UUID; package com.sulaco.fuse.akka.actor; public class SuspendedAnimationActor extends FuseBaseActor { @Autowired RequestSuspender suspender; @Override
public void onMessage(FuseInternalMessage message) {
gibffe/fuse
src/main/java/com/sulaco/fuse/akka/actor/SuspendedAnimationActor.java
// Path: src/main/java/com/sulaco/fuse/akka/async/RequestSuspender.java // public interface RequestSuspender { // // void suspend(FuseInternalMessage message); // // Optional<FuseInternalMessage> revive(long id); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseReviveMessage.java // public interface FuseReviveMessage { // // long getId(); // // Optional<?> getPayload(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseSuspendMessage.java // public interface FuseSuspendMessage extends FuseInternalMessage { // // }
import com.sulaco.fuse.akka.async.RequestSuspender; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseReviveMessage; import com.sulaco.fuse.akka.message.FuseSuspendMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional; import java.util.UUID;
package com.sulaco.fuse.akka.actor; public class SuspendedAnimationActor extends FuseBaseActor { @Autowired RequestSuspender suspender; @Override public void onMessage(FuseInternalMessage message) {
// Path: src/main/java/com/sulaco/fuse/akka/async/RequestSuspender.java // public interface RequestSuspender { // // void suspend(FuseInternalMessage message); // // Optional<FuseInternalMessage> revive(long id); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseReviveMessage.java // public interface FuseReviveMessage { // // long getId(); // // Optional<?> getPayload(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseSuspendMessage.java // public interface FuseSuspendMessage extends FuseInternalMessage { // // } // Path: src/main/java/com/sulaco/fuse/akka/actor/SuspendedAnimationActor.java import com.sulaco.fuse.akka.async.RequestSuspender; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseReviveMessage; import com.sulaco.fuse.akka.message.FuseSuspendMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional; import java.util.UUID; package com.sulaco.fuse.akka.actor; public class SuspendedAnimationActor extends FuseBaseActor { @Autowired RequestSuspender suspender; @Override public void onMessage(FuseInternalMessage message) {
if (message instanceof FuseSuspendMessage) {
gibffe/fuse
src/main/java/com/sulaco/fuse/akka/actor/SuspendedAnimationActor.java
// Path: src/main/java/com/sulaco/fuse/akka/async/RequestSuspender.java // public interface RequestSuspender { // // void suspend(FuseInternalMessage message); // // Optional<FuseInternalMessage> revive(long id); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseReviveMessage.java // public interface FuseReviveMessage { // // long getId(); // // Optional<?> getPayload(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseSuspendMessage.java // public interface FuseSuspendMessage extends FuseInternalMessage { // // }
import com.sulaco.fuse.akka.async.RequestSuspender; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseReviveMessage; import com.sulaco.fuse.akka.message.FuseSuspendMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional; import java.util.UUID;
package com.sulaco.fuse.akka.actor; public class SuspendedAnimationActor extends FuseBaseActor { @Autowired RequestSuspender suspender; @Override public void onMessage(FuseInternalMessage message) { if (message instanceof FuseSuspendMessage) { suspender.suspend(message); } else
// Path: src/main/java/com/sulaco/fuse/akka/async/RequestSuspender.java // public interface RequestSuspender { // // void suspend(FuseInternalMessage message); // // Optional<FuseInternalMessage> revive(long id); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseReviveMessage.java // public interface FuseReviveMessage { // // long getId(); // // Optional<?> getPayload(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseSuspendMessage.java // public interface FuseSuspendMessage extends FuseInternalMessage { // // } // Path: src/main/java/com/sulaco/fuse/akka/actor/SuspendedAnimationActor.java import com.sulaco.fuse.akka.async.RequestSuspender; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseReviveMessage; import com.sulaco.fuse.akka.message.FuseSuspendMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional; import java.util.UUID; package com.sulaco.fuse.akka.actor; public class SuspendedAnimationActor extends FuseBaseActor { @Autowired RequestSuspender suspender; @Override public void onMessage(FuseInternalMessage message) { if (message instanceof FuseSuspendMessage) { suspender.suspend(message); } else
if (message instanceof FuseReviveMessage) {
gibffe/fuse
src/main/java/com/sulaco/fuse/netty/FuseChannelInitializer.java
// Path: src/main/java/com/sulaco/fuse/config/ConfigSource.java // public interface ConfigSource { // // public void parseLocalConfig(); // // public Config getConfig(); // // public RoutesConfig getRoutesConfig(); // }
import com.sulaco.fuse.config.ConfigSource; import com.typesafe.config.Config; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; import io.netty.handler.stream.ChunkedWriteHandler; import java.util.List; import java.util.concurrent.TimeUnit; import io.netty.handler.timeout.IdleStateHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import akka.actor.ActorRef;
package com.sulaco.fuse.netty; @Component public class FuseChannelInitializer extends ChannelInitializer<SocketChannel> {
// Path: src/main/java/com/sulaco/fuse/config/ConfigSource.java // public interface ConfigSource { // // public void parseLocalConfig(); // // public Config getConfig(); // // public RoutesConfig getRoutesConfig(); // } // Path: src/main/java/com/sulaco/fuse/netty/FuseChannelInitializer.java import com.sulaco.fuse.config.ConfigSource; import com.typesafe.config.Config; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; import io.netty.handler.stream.ChunkedWriteHandler; import java.util.List; import java.util.concurrent.TimeUnit; import io.netty.handler.timeout.IdleStateHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import akka.actor.ActorRef; package com.sulaco.fuse.netty; @Component public class FuseChannelInitializer extends ChannelInitializer<SocketChannel> {
@Autowired ConfigSource configSource;
gibffe/fuse
examples/simple/src/main/java/com/sulaco/fuse/example/actor/PostActor.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.springframework.context.ApplicationContext;
package com.sulaco.fuse.example.actor; public class PostActor extends FuseEndpointActor { @Override
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: examples/simple/src/main/java/com/sulaco/fuse/example/actor/PostActor.java import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.springframework.context.ApplicationContext; package com.sulaco.fuse.example.actor; public class PostActor extends FuseEndpointActor { @Override
protected void onRequest(FuseRequestMessage request) {
gibffe/fuse
examples/simple/src/main/java/com/sulaco/fuse/example/actor/EchoActor.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: examples/simple/src/main/java/com/sulaco/fuse/example/tools/StringReverser.java // public interface StringReverser { // // Optional<String> reverse(Optional<String> input); // }
import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.example.tools.StringReverser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional;
package com.sulaco.fuse.example.actor; public class EchoActor extends FuseEndpointActor { @Autowired
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: examples/simple/src/main/java/com/sulaco/fuse/example/tools/StringReverser.java // public interface StringReverser { // // Optional<String> reverse(Optional<String> input); // } // Path: examples/simple/src/main/java/com/sulaco/fuse/example/actor/EchoActor.java import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.example.tools.StringReverser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional; package com.sulaco.fuse.example.actor; public class EchoActor extends FuseEndpointActor { @Autowired
StringReverser reverser;
gibffe/fuse
examples/simple/src/main/java/com/sulaco/fuse/example/actor/EchoActor.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: examples/simple/src/main/java/com/sulaco/fuse/example/tools/StringReverser.java // public interface StringReverser { // // Optional<String> reverse(Optional<String> input); // }
import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.example.tools.StringReverser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional;
package com.sulaco.fuse.example.actor; public class EchoActor extends FuseEndpointActor { @Autowired StringReverser reverser;
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: examples/simple/src/main/java/com/sulaco/fuse/example/tools/StringReverser.java // public interface StringReverser { // // Optional<String> reverse(Optional<String> input); // } // Path: examples/simple/src/main/java/com/sulaco/fuse/example/actor/EchoActor.java import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.example.tools.StringReverser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional; package com.sulaco.fuse.example.actor; public class EchoActor extends FuseEndpointActor { @Autowired StringReverser reverser;
public void echo(FuseRequestMessage request) {
gibffe/fuse
examples/simple/src/main/java/com/sulaco/fuse/example/actor/VoidActor.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessageImpl.java // public class FuseInternalMessageImpl implements FuseInternalMessage { // // protected FuseMessageContext ctx; // // protected Deque<ActorRef> chain; // // protected long timestamp; // // public FuseInternalMessageImpl(FuseRequestMessage request) { // this(); // ctx.setRequest(request); // } // // public FuseInternalMessageImpl(FuseInternalMessage message) { // timestamp(); // this.ctx = message.getContext(); // this.chain = message.getChain(); // } // // public FuseInternalMessageImpl() { // timestamp(); // this.ctx = new FuseMessageContextImpl(); // this.chain = new LinkedList<>(); // } // // @Override // public Optional<ActorRef> popOrigin() { // return Optional.ofNullable(chain.pop()); // } // // @Override // public void pushOrigin(ActorRef actorRef) { // chain.push(actorRef); // } // // @Override // public FuseMessageContext getContext() { // return ctx; // } // // @Override // public Deque<ActorRef> getChain() { // return chain; // } // // @Override // public long getTimestamp() { // return timestamp; // } // // @Override // public FuseInternalMessage timestamp() { // timestamp = System.currentTimeMillis(); // return this; // } // // @Override // public long getRequestId() { // return ctx.getRequest().get().getId(); // } // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessageImpl; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.springframework.context.ApplicationContext;
package com.sulaco.fuse.example.actor; public class VoidActor extends FuseEndpointActor { @Override
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessageImpl.java // public class FuseInternalMessageImpl implements FuseInternalMessage { // // protected FuseMessageContext ctx; // // protected Deque<ActorRef> chain; // // protected long timestamp; // // public FuseInternalMessageImpl(FuseRequestMessage request) { // this(); // ctx.setRequest(request); // } // // public FuseInternalMessageImpl(FuseInternalMessage message) { // timestamp(); // this.ctx = message.getContext(); // this.chain = message.getChain(); // } // // public FuseInternalMessageImpl() { // timestamp(); // this.ctx = new FuseMessageContextImpl(); // this.chain = new LinkedList<>(); // } // // @Override // public Optional<ActorRef> popOrigin() { // return Optional.ofNullable(chain.pop()); // } // // @Override // public void pushOrigin(ActorRef actorRef) { // chain.push(actorRef); // } // // @Override // public FuseMessageContext getContext() { // return ctx; // } // // @Override // public Deque<ActorRef> getChain() { // return chain; // } // // @Override // public long getTimestamp() { // return timestamp; // } // // @Override // public FuseInternalMessage timestamp() { // timestamp = System.currentTimeMillis(); // return this; // } // // @Override // public long getRequestId() { // return ctx.getRequest().get().getId(); // } // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: examples/simple/src/main/java/com/sulaco/fuse/example/actor/VoidActor.java import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessageImpl; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.springframework.context.ApplicationContext; package com.sulaco.fuse.example.actor; public class VoidActor extends FuseEndpointActor { @Override
protected void onRequest(FuseRequestMessage request) {
gibffe/fuse
examples/async/src/main/java/com/sulaco/fuse/example/async/endpoint/PlaylistReadActor.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/dao/CassandraDao.java // public interface CassandraDao { // // public void getSongById(String id, Function<Optional<?>, ?> fuseConsumer); // // public void getPlaylistById(String id, Function<Optional<?>, ?> fuseConsumer); // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Playlist.java // public class Playlist { // // UUID id; // Set<Song> songs; // // public Playlist() { // this.songs = new HashSet<>(); // } // // public Playlist(UUID id) { // this(); // this.id = id; // } // // public UUID getId() { // return id; // } // // public Set<Song> getSongs() { // return songs; // } // // public void addSong(Song song) { // this.songs.add(song); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Playlist)) return false; // // Playlist playlist = (Playlist) o; // // if (!id.equals(playlist.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public static final Playlist EMPTY = new Playlist(); // }
import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.example.async.domain.dao.CassandraDao; import com.sulaco.fuse.example.async.domain.entity.Playlist; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional;
package com.sulaco.fuse.example.async.endpoint; public class PlaylistReadActor extends FuseEndpointActor { @Autowired CassandraDao dao; @Override
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/dao/CassandraDao.java // public interface CassandraDao { // // public void getSongById(String id, Function<Optional<?>, ?> fuseConsumer); // // public void getPlaylistById(String id, Function<Optional<?>, ?> fuseConsumer); // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Playlist.java // public class Playlist { // // UUID id; // Set<Song> songs; // // public Playlist() { // this.songs = new HashSet<>(); // } // // public Playlist(UUID id) { // this(); // this.id = id; // } // // public UUID getId() { // return id; // } // // public Set<Song> getSongs() { // return songs; // } // // public void addSong(Song song) { // this.songs.add(song); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Playlist)) return false; // // Playlist playlist = (Playlist) o; // // if (!id.equals(playlist.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public static final Playlist EMPTY = new Playlist(); // } // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/endpoint/PlaylistReadActor.java import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.example.async.domain.dao.CassandraDao; import com.sulaco.fuse.example.async.domain.entity.Playlist; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional; package com.sulaco.fuse.example.async.endpoint; public class PlaylistReadActor extends FuseEndpointActor { @Autowired CassandraDao dao; @Override
protected void onRequest(final FuseRequestMessage request) {
gibffe/fuse
examples/async/src/main/java/com/sulaco/fuse/example/async/endpoint/PlaylistReadActor.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/dao/CassandraDao.java // public interface CassandraDao { // // public void getSongById(String id, Function<Optional<?>, ?> fuseConsumer); // // public void getPlaylistById(String id, Function<Optional<?>, ?> fuseConsumer); // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Playlist.java // public class Playlist { // // UUID id; // Set<Song> songs; // // public Playlist() { // this.songs = new HashSet<>(); // } // // public Playlist(UUID id) { // this(); // this.id = id; // } // // public UUID getId() { // return id; // } // // public Set<Song> getSongs() { // return songs; // } // // public void addSong(Song song) { // this.songs.add(song); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Playlist)) return false; // // Playlist playlist = (Playlist) o; // // if (!id.equals(playlist.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public static final Playlist EMPTY = new Playlist(); // }
import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.example.async.domain.dao.CassandraDao; import com.sulaco.fuse.example.async.domain.entity.Playlist; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional;
package com.sulaco.fuse.example.async.endpoint; public class PlaylistReadActor extends FuseEndpointActor { @Autowired CassandraDao dao; @Override protected void onRequest(final FuseRequestMessage request) { Optional<String> id = request.getParam("playlistId"); if (id.isPresent()) { // Once suspended request is revived, it will be passed towards an actor // represented by custom path. If suspended without a path, this actor is treated // as origin, and revival message will be sent back to it. Take a look at FuseBaseActor.onMessage // suspend(request); // we will cross thread boundaries inside the dao, take a look dao.getPlaylistById( id.get(), result -> revive(request, result) ); } else {
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/dao/CassandraDao.java // public interface CassandraDao { // // public void getSongById(String id, Function<Optional<?>, ?> fuseConsumer); // // public void getPlaylistById(String id, Function<Optional<?>, ?> fuseConsumer); // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Playlist.java // public class Playlist { // // UUID id; // Set<Song> songs; // // public Playlist() { // this.songs = new HashSet<>(); // } // // public Playlist(UUID id) { // this(); // this.id = id; // } // // public UUID getId() { // return id; // } // // public Set<Song> getSongs() { // return songs; // } // // public void addSong(Song song) { // this.songs.add(song); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Playlist)) return false; // // Playlist playlist = (Playlist) o; // // if (!id.equals(playlist.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public static final Playlist EMPTY = new Playlist(); // } // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/endpoint/PlaylistReadActor.java import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.example.async.domain.dao.CassandraDao; import com.sulaco.fuse.example.async.domain.entity.Playlist; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional; package com.sulaco.fuse.example.async.endpoint; public class PlaylistReadActor extends FuseEndpointActor { @Autowired CassandraDao dao; @Override protected void onRequest(final FuseRequestMessage request) { Optional<String> id = request.getParam("playlistId"); if (id.isPresent()) { // Once suspended request is revived, it will be passed towards an actor // represented by custom path. If suspended without a path, this actor is treated // as origin, and revival message will be sent back to it. Take a look at FuseBaseActor.onMessage // suspend(request); // we will cross thread boundaries inside the dao, take a look dao.getPlaylistById( id.get(), result -> revive(request, result) ); } else {
proto.respond(request, Playlist.EMPTY);
gibffe/fuse
examples/async/src/main/java/com/sulaco/fuse/example/async/endpoint/PlaylistReadActor.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/dao/CassandraDao.java // public interface CassandraDao { // // public void getSongById(String id, Function<Optional<?>, ?> fuseConsumer); // // public void getPlaylistById(String id, Function<Optional<?>, ?> fuseConsumer); // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Playlist.java // public class Playlist { // // UUID id; // Set<Song> songs; // // public Playlist() { // this.songs = new HashSet<>(); // } // // public Playlist(UUID id) { // this(); // this.id = id; // } // // public UUID getId() { // return id; // } // // public Set<Song> getSongs() { // return songs; // } // // public void addSong(Song song) { // this.songs.add(song); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Playlist)) return false; // // Playlist playlist = (Playlist) o; // // if (!id.equals(playlist.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public static final Playlist EMPTY = new Playlist(); // }
import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.example.async.domain.dao.CassandraDao; import com.sulaco.fuse.example.async.domain.entity.Playlist; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional;
package com.sulaco.fuse.example.async.endpoint; public class PlaylistReadActor extends FuseEndpointActor { @Autowired CassandraDao dao; @Override protected void onRequest(final FuseRequestMessage request) { Optional<String> id = request.getParam("playlistId"); if (id.isPresent()) { // Once suspended request is revived, it will be passed towards an actor // represented by custom path. If suspended without a path, this actor is treated // as origin, and revival message will be sent back to it. Take a look at FuseBaseActor.onMessage // suspend(request); // we will cross thread boundaries inside the dao, take a look dao.getPlaylistById( id.get(), result -> revive(request, result) ); } else { proto.respond(request, Playlist.EMPTY); } } // The revival message is delivered by suspended animation actor. // @Override
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/dao/CassandraDao.java // public interface CassandraDao { // // public void getSongById(String id, Function<Optional<?>, ?> fuseConsumer); // // public void getPlaylistById(String id, Function<Optional<?>, ?> fuseConsumer); // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Playlist.java // public class Playlist { // // UUID id; // Set<Song> songs; // // public Playlist() { // this.songs = new HashSet<>(); // } // // public Playlist(UUID id) { // this(); // this.id = id; // } // // public UUID getId() { // return id; // } // // public Set<Song> getSongs() { // return songs; // } // // public void addSong(Song song) { // this.songs.add(song); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Playlist)) return false; // // Playlist playlist = (Playlist) o; // // if (!id.equals(playlist.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public static final Playlist EMPTY = new Playlist(); // } // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/endpoint/PlaylistReadActor.java import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.example.async.domain.dao.CassandraDao; import com.sulaco.fuse.example.async.domain.entity.Playlist; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.util.Optional; package com.sulaco.fuse.example.async.endpoint; public class PlaylistReadActor extends FuseEndpointActor { @Autowired CassandraDao dao; @Override protected void onRequest(final FuseRequestMessage request) { Optional<String> id = request.getParam("playlistId"); if (id.isPresent()) { // Once suspended request is revived, it will be passed towards an actor // represented by custom path. If suspended without a path, this actor is treated // as origin, and revival message will be sent back to it. Take a look at FuseBaseActor.onMessage // suspend(request); // we will cross thread boundaries inside the dao, take a look dao.getPlaylistById( id.get(), result -> revive(request, result) ); } else { proto.respond(request, Playlist.EMPTY); } } // The revival message is delivered by suspended animation actor. // @Override
protected void onRevive(FuseInternalMessage message, Optional<?> payload) {
gibffe/fuse
src/main/java/com/sulaco/fuse/akka/actor/ChannelClosingActor.java
// Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // }
import com.sulaco.fuse.akka.message.FuseInternalMessage;
package com.sulaco.fuse.akka.actor; public class ChannelClosingActor extends FuseBaseActor { @Override
// Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // Path: src/main/java/com/sulaco/fuse/akka/actor/ChannelClosingActor.java import com.sulaco.fuse.akka.message.FuseInternalMessage; package com.sulaco.fuse.akka.actor; public class ChannelClosingActor extends FuseBaseActor { @Override
public void onMessage(FuseInternalMessage message) {
gibffe/fuse
src/test/java/com/sulaco/fuse/ActorAwareTest.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/codec/WireProtocol.java // public interface WireProtocol { // // void ok(FuseRequestMessage message); // // // void respond(FuseRequestMessage message, Object object); // // void respond(FuseRequestMessage message, String content); // // void respondRaw(FuseRequestMessage message, HttpResponseStatus status, ByteBuffer data, Map<String, String> headers); // // // void error(FuseRequestMessage message); // // void error(FuseRequestMessage message, Object object); // // void error(FuseRequestMessage message, String content); // // void error(FuseRequestMessage message, HttpResponseStatus status, Object object); // // void error(FuseRequestMessage message, HttpResponseStatus status, String content); // // // <T> Optional<T> read(FuseRequestMessage message, Class<T> clazz); // // default void stream(FuseRequestMessage message, Path path) { // // if (!message.flushed()) { // ChannelHandlerContext ctx = message.getChannelContext(); // HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); // // long size = WireProtocol.getFileSize(path); // // response.headers().set(CONTENT_LENGTH, size); // // ctx.write(response); // // try { // ctx.write( // new DefaultFileRegion(FileChannel.open(path), 0, size) // ); // // ChannelFuture cfuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // // if (!isKeepAlive(message.getRequest())) { // cfuture.addListener(ChannelFutureListener.CLOSE); // } // } // catch (Exception ex) { // log.error("Error streaming file !", ex); // ctx.close(); // } // } // } // // static long getFileSize(Path path) { // try { // return Files.size(path); // } // catch (Exception ex) { // log.warn("Error getting file size ! {}", path, ex); // return -1; // } // } // // static final Logger log = LoggerFactory.getLogger(WireProtocol.class); // }
import akka.actor.Actor; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.TestActorRef; import com.codahale.metrics.Timer; import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.codec.WireProtocol; import org.junit.Ignore; import org.mockito.Mock; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; import static org.mockito.Mockito.when;
package com.sulaco.fuse; @Ignore public class ActorAwareTest { ActorSystem system = ActorSystem.create("test"); @Mock protected ApplicationContext mockAppCtx; @Mock protected AutowireCapableBeanFactory mockAutowireFactory;
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/codec/WireProtocol.java // public interface WireProtocol { // // void ok(FuseRequestMessage message); // // // void respond(FuseRequestMessage message, Object object); // // void respond(FuseRequestMessage message, String content); // // void respondRaw(FuseRequestMessage message, HttpResponseStatus status, ByteBuffer data, Map<String, String> headers); // // // void error(FuseRequestMessage message); // // void error(FuseRequestMessage message, Object object); // // void error(FuseRequestMessage message, String content); // // void error(FuseRequestMessage message, HttpResponseStatus status, Object object); // // void error(FuseRequestMessage message, HttpResponseStatus status, String content); // // // <T> Optional<T> read(FuseRequestMessage message, Class<T> clazz); // // default void stream(FuseRequestMessage message, Path path) { // // if (!message.flushed()) { // ChannelHandlerContext ctx = message.getChannelContext(); // HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); // // long size = WireProtocol.getFileSize(path); // // response.headers().set(CONTENT_LENGTH, size); // // ctx.write(response); // // try { // ctx.write( // new DefaultFileRegion(FileChannel.open(path), 0, size) // ); // // ChannelFuture cfuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // // if (!isKeepAlive(message.getRequest())) { // cfuture.addListener(ChannelFutureListener.CLOSE); // } // } // catch (Exception ex) { // log.error("Error streaming file !", ex); // ctx.close(); // } // } // } // // static long getFileSize(Path path) { // try { // return Files.size(path); // } // catch (Exception ex) { // log.warn("Error getting file size ! {}", path, ex); // return -1; // } // } // // static final Logger log = LoggerFactory.getLogger(WireProtocol.class); // } // Path: src/test/java/com/sulaco/fuse/ActorAwareTest.java import akka.actor.Actor; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.TestActorRef; import com.codahale.metrics.Timer; import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.codec.WireProtocol; import org.junit.Ignore; import org.mockito.Mock; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; import static org.mockito.Mockito.when; package com.sulaco.fuse; @Ignore public class ActorAwareTest { ActorSystem system = ActorSystem.create("test"); @Mock protected ApplicationContext mockAppCtx; @Mock protected AutowireCapableBeanFactory mockAutowireFactory;
@Mock protected WireProtocol mockProto;
gibffe/fuse
src/test/java/com/sulaco/fuse/ActorAwareTest.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/codec/WireProtocol.java // public interface WireProtocol { // // void ok(FuseRequestMessage message); // // // void respond(FuseRequestMessage message, Object object); // // void respond(FuseRequestMessage message, String content); // // void respondRaw(FuseRequestMessage message, HttpResponseStatus status, ByteBuffer data, Map<String, String> headers); // // // void error(FuseRequestMessage message); // // void error(FuseRequestMessage message, Object object); // // void error(FuseRequestMessage message, String content); // // void error(FuseRequestMessage message, HttpResponseStatus status, Object object); // // void error(FuseRequestMessage message, HttpResponseStatus status, String content); // // // <T> Optional<T> read(FuseRequestMessage message, Class<T> clazz); // // default void stream(FuseRequestMessage message, Path path) { // // if (!message.flushed()) { // ChannelHandlerContext ctx = message.getChannelContext(); // HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); // // long size = WireProtocol.getFileSize(path); // // response.headers().set(CONTENT_LENGTH, size); // // ctx.write(response); // // try { // ctx.write( // new DefaultFileRegion(FileChannel.open(path), 0, size) // ); // // ChannelFuture cfuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // // if (!isKeepAlive(message.getRequest())) { // cfuture.addListener(ChannelFutureListener.CLOSE); // } // } // catch (Exception ex) { // log.error("Error streaming file !", ex); // ctx.close(); // } // } // } // // static long getFileSize(Path path) { // try { // return Files.size(path); // } // catch (Exception ex) { // log.warn("Error getting file size ! {}", path, ex); // return -1; // } // } // // static final Logger log = LoggerFactory.getLogger(WireProtocol.class); // }
import akka.actor.Actor; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.TestActorRef; import com.codahale.metrics.Timer; import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.codec.WireProtocol; import org.junit.Ignore; import org.mockito.Mock; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; import static org.mockito.Mockito.when;
package com.sulaco.fuse; @Ignore public class ActorAwareTest { ActorSystem system = ActorSystem.create("test"); @Mock protected ApplicationContext mockAppCtx; @Mock protected AutowireCapableBeanFactory mockAutowireFactory; @Mock protected WireProtocol mockProto; @Mock protected Timer mockMeter; protected void setup() { when(mockAppCtx.getAutowireCapableBeanFactory()).thenReturn(mockAutowireFactory); }
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/codec/WireProtocol.java // public interface WireProtocol { // // void ok(FuseRequestMessage message); // // // void respond(FuseRequestMessage message, Object object); // // void respond(FuseRequestMessage message, String content); // // void respondRaw(FuseRequestMessage message, HttpResponseStatus status, ByteBuffer data, Map<String, String> headers); // // // void error(FuseRequestMessage message); // // void error(FuseRequestMessage message, Object object); // // void error(FuseRequestMessage message, String content); // // void error(FuseRequestMessage message, HttpResponseStatus status, Object object); // // void error(FuseRequestMessage message, HttpResponseStatus status, String content); // // // <T> Optional<T> read(FuseRequestMessage message, Class<T> clazz); // // default void stream(FuseRequestMessage message, Path path) { // // if (!message.flushed()) { // ChannelHandlerContext ctx = message.getChannelContext(); // HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); // // long size = WireProtocol.getFileSize(path); // // response.headers().set(CONTENT_LENGTH, size); // // ctx.write(response); // // try { // ctx.write( // new DefaultFileRegion(FileChannel.open(path), 0, size) // ); // // ChannelFuture cfuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // // if (!isKeepAlive(message.getRequest())) { // cfuture.addListener(ChannelFutureListener.CLOSE); // } // } // catch (Exception ex) { // log.error("Error streaming file !", ex); // ctx.close(); // } // } // } // // static long getFileSize(Path path) { // try { // return Files.size(path); // } // catch (Exception ex) { // log.warn("Error getting file size ! {}", path, ex); // return -1; // } // } // // static final Logger log = LoggerFactory.getLogger(WireProtocol.class); // } // Path: src/test/java/com/sulaco/fuse/ActorAwareTest.java import akka.actor.Actor; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.TestActorRef; import com.codahale.metrics.Timer; import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.codec.WireProtocol; import org.junit.Ignore; import org.mockito.Mock; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; import static org.mockito.Mockito.when; package com.sulaco.fuse; @Ignore public class ActorAwareTest { ActorSystem system = ActorSystem.create("test"); @Mock protected ApplicationContext mockAppCtx; @Mock protected AutowireCapableBeanFactory mockAutowireFactory; @Mock protected WireProtocol mockProto; @Mock protected Timer mockMeter; protected void setup() { when(mockAppCtx.getAutowireCapableBeanFactory()).thenReturn(mockAutowireFactory); }
protected <T extends FuseEndpointActor> TestActorRef<T> mockEndpoint(Class<T> clazz) {
gibffe/fuse
examples/annotations/src/main/java/com/sulaco/fuse/example/endpoint/EchoActor.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseMessageContext.java // public interface FuseMessageContext { // // public int inc(String key); // // public int dec(String key); // // public <T> Optional<T> get(String key); // // public <T> Optional<T> payload(); // // public FuseMessageContext put(String key, Object value); // // public FuseMessageContext put(String key, Optional<?> value); // // public FuseMessageContext remove(String key); // // public Set<String> keys(); // // // public void setRequest(FuseRequestMessage request); // // public Optional<FuseRequestMessage> getRequest(); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseMessageContext; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.config.annotation.FuseEndpoint;
package com.sulaco.fuse.example.endpoint; @FuseEndpoint( path = "/echo" ) public class EchoActor extends FuseEndpointActor { @Override
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseMessageContext.java // public interface FuseMessageContext { // // public int inc(String key); // // public int dec(String key); // // public <T> Optional<T> get(String key); // // public <T> Optional<T> payload(); // // public FuseMessageContext put(String key, Object value); // // public FuseMessageContext put(String key, Optional<?> value); // // public FuseMessageContext remove(String key); // // public Set<String> keys(); // // // public void setRequest(FuseRequestMessage request); // // public Optional<FuseRequestMessage> getRequest(); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: examples/annotations/src/main/java/com/sulaco/fuse/example/endpoint/EchoActor.java import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseMessageContext; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.config.annotation.FuseEndpoint; package com.sulaco.fuse.example.endpoint; @FuseEndpoint( path = "/echo" ) public class EchoActor extends FuseEndpointActor { @Override
protected void onRequest(FuseRequestMessage request) {
gibffe/fuse
examples/annotations/src/main/java/com/sulaco/fuse/example/endpoint/EchoActor.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseMessageContext.java // public interface FuseMessageContext { // // public int inc(String key); // // public int dec(String key); // // public <T> Optional<T> get(String key); // // public <T> Optional<T> payload(); // // public FuseMessageContext put(String key, Object value); // // public FuseMessageContext put(String key, Optional<?> value); // // public FuseMessageContext remove(String key); // // public Set<String> keys(); // // // public void setRequest(FuseRequestMessage request); // // public Optional<FuseRequestMessage> getRequest(); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseMessageContext; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.config.annotation.FuseEndpoint;
package com.sulaco.fuse.example.endpoint; @FuseEndpoint( path = "/echo" ) public class EchoActor extends FuseEndpointActor { @Override protected void onRequest(FuseRequestMessage request) { // we'll let the Echo actor figure out how to echo the request uri string //
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseMessageContext.java // public interface FuseMessageContext { // // public int inc(String key); // // public int dec(String key); // // public <T> Optional<T> get(String key); // // public <T> Optional<T> payload(); // // public FuseMessageContext put(String key, Object value); // // public FuseMessageContext put(String key, Optional<?> value); // // public FuseMessageContext remove(String key); // // public Set<String> keys(); // // // public void setRequest(FuseRequestMessage request); // // public Optional<FuseRequestMessage> getRequest(); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: examples/annotations/src/main/java/com/sulaco/fuse/example/endpoint/EchoActor.java import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseMessageContext; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.config.annotation.FuseEndpoint; package com.sulaco.fuse.example.endpoint; @FuseEndpoint( path = "/echo" ) public class EchoActor extends FuseEndpointActor { @Override protected void onRequest(FuseRequestMessage request) { // we'll let the Echo actor figure out how to echo the request uri string //
FuseInternalMessage message = newMessage(request);
gibffe/fuse
examples/annotations/src/main/java/com/sulaco/fuse/example/endpoint/EchoActor.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseMessageContext.java // public interface FuseMessageContext { // // public int inc(String key); // // public int dec(String key); // // public <T> Optional<T> get(String key); // // public <T> Optional<T> payload(); // // public FuseMessageContext put(String key, Object value); // // public FuseMessageContext put(String key, Optional<?> value); // // public FuseMessageContext remove(String key); // // public Set<String> keys(); // // // public void setRequest(FuseRequestMessage request); // // public Optional<FuseRequestMessage> getRequest(); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseMessageContext; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.config.annotation.FuseEndpoint;
package com.sulaco.fuse.example.endpoint; @FuseEndpoint( path = "/echo" ) public class EchoActor extends FuseEndpointActor { @Override protected void onRequest(FuseRequestMessage request) { // we'll let the Echo actor figure out how to echo the request uri string // FuseInternalMessage message = newMessage(request); message.getContext() .put( "echo", request.getRequest().getUri() ); send(message, "/user/echo"); // once the message is processed by example.actor.Echo, at some point in the future this actor will receive an // internal message back } @Override protected void onInternal(FuseInternalMessage message) {
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseInternalMessage.java // public interface FuseInternalMessage extends FuseOriginChain { // // FuseMessageContext getContext(); // // long getRequestId(); // // long getTimestamp(); // // FuseInternalMessage timestamp(); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseMessageContext.java // public interface FuseMessageContext { // // public int inc(String key); // // public int dec(String key); // // public <T> Optional<T> get(String key); // // public <T> Optional<T> payload(); // // public FuseMessageContext put(String key, Object value); // // public FuseMessageContext put(String key, Optional<?> value); // // public FuseMessageContext remove(String key); // // public Set<String> keys(); // // // public void setRequest(FuseRequestMessage request); // // public Optional<FuseRequestMessage> getRequest(); // // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: examples/annotations/src/main/java/com/sulaco/fuse/example/endpoint/EchoActor.java import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseInternalMessage; import com.sulaco.fuse.akka.message.FuseMessageContext; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.config.annotation.FuseEndpoint; package com.sulaco.fuse.example.endpoint; @FuseEndpoint( path = "/echo" ) public class EchoActor extends FuseEndpointActor { @Override protected void onRequest(FuseRequestMessage request) { // we'll let the Echo actor figure out how to echo the request uri string // FuseInternalMessage message = newMessage(request); message.getContext() .put( "echo", request.getRequest().getUri() ); send(message, "/user/echo"); // once the message is processed by example.actor.Echo, at some point in the future this actor will receive an // internal message back } @Override protected void onInternal(FuseInternalMessage message) {
FuseMessageContext ctx = message.getContext();
gibffe/fuse
src/main/java/com/sulaco/fuse/codec/FuseWireProtocol.java
// Path: src/main/java/com/sulaco/fuse/FuseVersion.java // @Component // public class FuseVersion { // // String version = "Fuse v0.0.3-SNAPSHOT"; // // public FuseVersion() { // super(); // } // // public String toString() { // return version; // } // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive; import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION; import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; import static io.netty.handler.codec.http.HttpHeaders.Names.SERVER; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.HttpHeaders.Values; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.*; import io.netty.handler.stream.ChunkedFile; import io.netty.handler.stream.ChunkedNioFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.sulaco.fuse.FuseVersion; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.springframework.util.FileSystemUtils; import javax.annotation.PostConstruct;
package com.sulaco.fuse.codec; @Component public class FuseWireProtocol implements WireProtocol { @Autowired WireCodec codec;
// Path: src/main/java/com/sulaco/fuse/FuseVersion.java // @Component // public class FuseVersion { // // String version = "Fuse v0.0.3-SNAPSHOT"; // // public FuseVersion() { // super(); // } // // public String toString() { // return version; // } // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: src/main/java/com/sulaco/fuse/codec/FuseWireProtocol.java import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive; import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION; import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; import static io.netty.handler.codec.http.HttpHeaders.Names.SERVER; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.HttpHeaders.Values; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.*; import io.netty.handler.stream.ChunkedFile; import io.netty.handler.stream.ChunkedNioFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.sulaco.fuse.FuseVersion; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.springframework.util.FileSystemUtils; import javax.annotation.PostConstruct; package com.sulaco.fuse.codec; @Component public class FuseWireProtocol implements WireProtocol { @Autowired WireCodec codec;
@Autowired FuseVersion version;
gibffe/fuse
src/main/java/com/sulaco/fuse/codec/FuseWireProtocol.java
// Path: src/main/java/com/sulaco/fuse/FuseVersion.java // @Component // public class FuseVersion { // // String version = "Fuse v0.0.3-SNAPSHOT"; // // public FuseVersion() { // super(); // } // // public String toString() { // return version; // } // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive; import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION; import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; import static io.netty.handler.codec.http.HttpHeaders.Names.SERVER; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.HttpHeaders.Values; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.*; import io.netty.handler.stream.ChunkedFile; import io.netty.handler.stream.ChunkedNioFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.sulaco.fuse.FuseVersion; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.springframework.util.FileSystemUtils; import javax.annotation.PostConstruct;
package com.sulaco.fuse.codec; @Component public class FuseWireProtocol implements WireProtocol { @Autowired WireCodec codec; @Autowired FuseVersion version; Map<String, String> defaultHeaders; @PostConstruct public void init() { defaultHeaders = new HashMap<>(); defaultHeaders.put(SERVER , version.toString()); defaultHeaders.put(CONTENT_TYPE , APP_JSON); } @Override
// Path: src/main/java/com/sulaco/fuse/FuseVersion.java // @Component // public class FuseVersion { // // String version = "Fuse v0.0.3-SNAPSHOT"; // // public FuseVersion() { // super(); // } // // public String toString() { // return version; // } // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: src/main/java/com/sulaco/fuse/codec/FuseWireProtocol.java import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive; import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION; import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; import static io.netty.handler.codec.http.HttpHeaders.Names.SERVER; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.HttpHeaders.Values; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.*; import io.netty.handler.stream.ChunkedFile; import io.netty.handler.stream.ChunkedNioFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.sulaco.fuse.FuseVersion; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.springframework.util.FileSystemUtils; import javax.annotation.PostConstruct; package com.sulaco.fuse.codec; @Component public class FuseWireProtocol implements WireProtocol { @Autowired WireCodec codec; @Autowired FuseVersion version; Map<String, String> defaultHeaders; @PostConstruct public void init() { defaultHeaders = new HashMap<>(); defaultHeaders.put(SERVER , version.toString()); defaultHeaders.put(CONTENT_TYPE , APP_JSON); } @Override
public void ok(FuseRequestMessage message) {
gibffe/fuse
examples/async/src/main/java/com/sulaco/fuse/example/async/domain/dao/CassandraDaoImpl.java
// Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Playlist.java // public class Playlist { // // UUID id; // Set<Song> songs; // // public Playlist() { // this.songs = new HashSet<>(); // } // // public Playlist(UUID id) { // this(); // this.id = id; // } // // public UUID getId() { // return id; // } // // public Set<Song> getSongs() { // return songs; // } // // public void addSong(Song song) { // this.songs.add(song); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Playlist)) return false; // // Playlist playlist = (Playlist) o; // // if (!id.equals(playlist.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public static final Playlist EMPTY = new Playlist(); // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Song.java // public class Song { // // UUID id; // // String artist; // // String album; // // String title; // // int length; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public int getLength() { // return length; // } // // public void setLength(int length) { // this.length = length; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAlbum() { // return album; // } // // public void setAlbum(String album) { // this.album = album; // } // // public String getArtist() { // return artist; // } // // public void setArtist(String artist) { // this.artist = artist; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Song)) return false; // // Song song = (Song) o; // // if (!id.equals(song.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id.hashCode(); // } // // public static Song EMPTY = new Song(); // }
import com.datastax.driver.core.*; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.sulaco.fuse.example.async.domain.entity.Playlist; import com.sulaco.fuse.example.async.domain.entity.Song; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.function.Function;
.build(); session = cluster.connect("test"); stmt_get_playlist = session.prepare("select * from playlist where pid = ?"); stmt_get_song = session.prepare("select * from song where sid = ?"); } @Override public void getSongById(String id, Function<Optional<?>, ?> consumer) { ResultSetFuture future = session.executeAsync( stmt_get_song.bind(UUID.fromString(id)) ); consumeRowAsync(future, this::songFromRow, consumer); } @Override public void getPlaylistById(String id, Function<Optional<?>, ?> consumer) { ResultSetFuture future = session.executeAsync( stmt_get_playlist.bind(UUID.fromString(id)) ); consumeRowsAsync(future, rs -> playlistFromRows(id, rs), consumer); }
// Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Playlist.java // public class Playlist { // // UUID id; // Set<Song> songs; // // public Playlist() { // this.songs = new HashSet<>(); // } // // public Playlist(UUID id) { // this(); // this.id = id; // } // // public UUID getId() { // return id; // } // // public Set<Song> getSongs() { // return songs; // } // // public void addSong(Song song) { // this.songs.add(song); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Playlist)) return false; // // Playlist playlist = (Playlist) o; // // if (!id.equals(playlist.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public static final Playlist EMPTY = new Playlist(); // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Song.java // public class Song { // // UUID id; // // String artist; // // String album; // // String title; // // int length; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public int getLength() { // return length; // } // // public void setLength(int length) { // this.length = length; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAlbum() { // return album; // } // // public void setAlbum(String album) { // this.album = album; // } // // public String getArtist() { // return artist; // } // // public void setArtist(String artist) { // this.artist = artist; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Song)) return false; // // Song song = (Song) o; // // if (!id.equals(song.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id.hashCode(); // } // // public static Song EMPTY = new Song(); // } // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/dao/CassandraDaoImpl.java import com.datastax.driver.core.*; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.sulaco.fuse.example.async.domain.entity.Playlist; import com.sulaco.fuse.example.async.domain.entity.Song; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.function.Function; .build(); session = cluster.connect("test"); stmt_get_playlist = session.prepare("select * from playlist where pid = ?"); stmt_get_song = session.prepare("select * from song where sid = ?"); } @Override public void getSongById(String id, Function<Optional<?>, ?> consumer) { ResultSetFuture future = session.executeAsync( stmt_get_song.bind(UUID.fromString(id)) ); consumeRowAsync(future, this::songFromRow, consumer); } @Override public void getPlaylistById(String id, Function<Optional<?>, ?> consumer) { ResultSetFuture future = session.executeAsync( stmt_get_playlist.bind(UUID.fromString(id)) ); consumeRowsAsync(future, rs -> playlistFromRows(id, rs), consumer); }
Optional<Playlist> playlistFromRows(String id, Optional<List<Row>> rows) {
gibffe/fuse
examples/async/src/main/java/com/sulaco/fuse/example/async/domain/dao/CassandraDaoImpl.java
// Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Playlist.java // public class Playlist { // // UUID id; // Set<Song> songs; // // public Playlist() { // this.songs = new HashSet<>(); // } // // public Playlist(UUID id) { // this(); // this.id = id; // } // // public UUID getId() { // return id; // } // // public Set<Song> getSongs() { // return songs; // } // // public void addSong(Song song) { // this.songs.add(song); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Playlist)) return false; // // Playlist playlist = (Playlist) o; // // if (!id.equals(playlist.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public static final Playlist EMPTY = new Playlist(); // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Song.java // public class Song { // // UUID id; // // String artist; // // String album; // // String title; // // int length; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public int getLength() { // return length; // } // // public void setLength(int length) { // this.length = length; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAlbum() { // return album; // } // // public void setAlbum(String album) { // this.album = album; // } // // public String getArtist() { // return artist; // } // // public void setArtist(String artist) { // this.artist = artist; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Song)) return false; // // Song song = (Song) o; // // if (!id.equals(song.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id.hashCode(); // } // // public static Song EMPTY = new Song(); // }
import com.datastax.driver.core.*; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.sulaco.fuse.example.async.domain.entity.Playlist; import com.sulaco.fuse.example.async.domain.entity.Song; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.function.Function;
= session.executeAsync( stmt_get_song.bind(UUID.fromString(id)) ); consumeRowAsync(future, this::songFromRow, consumer); } @Override public void getPlaylistById(String id, Function<Optional<?>, ?> consumer) { ResultSetFuture future = session.executeAsync( stmt_get_playlist.bind(UUID.fromString(id)) ); consumeRowsAsync(future, rs -> playlistFromRows(id, rs), consumer); } Optional<Playlist> playlistFromRows(String id, Optional<List<Row>> rows) { Playlist playlist = new Playlist(UUID.fromString(id)); rows.ifPresent( list -> list.forEach( row -> playlist.addSong(songFromRow(row)) ) ); return Optional.of(playlist); }
// Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Playlist.java // public class Playlist { // // UUID id; // Set<Song> songs; // // public Playlist() { // this.songs = new HashSet<>(); // } // // public Playlist(UUID id) { // this(); // this.id = id; // } // // public UUID getId() { // return id; // } // // public Set<Song> getSongs() { // return songs; // } // // public void addSong(Song song) { // this.songs.add(song); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Playlist)) return false; // // Playlist playlist = (Playlist) o; // // if (!id.equals(playlist.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // public static final Playlist EMPTY = new Playlist(); // } // // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/entity/Song.java // public class Song { // // UUID id; // // String artist; // // String album; // // String title; // // int length; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public int getLength() { // return length; // } // // public void setLength(int length) { // this.length = length; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAlbum() { // return album; // } // // public void setAlbum(String album) { // this.album = album; // } // // public String getArtist() { // return artist; // } // // public void setArtist(String artist) { // this.artist = artist; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Song)) return false; // // Song song = (Song) o; // // if (!id.equals(song.id)) return false; // // return true; // } // // @Override // public int hashCode() { // return id.hashCode(); // } // // public static Song EMPTY = new Song(); // } // Path: examples/async/src/main/java/com/sulaco/fuse/example/async/domain/dao/CassandraDaoImpl.java import com.datastax.driver.core.*; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.sulaco.fuse.example.async.domain.entity.Playlist; import com.sulaco.fuse.example.async.domain.entity.Song; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.function.Function; = session.executeAsync( stmt_get_song.bind(UUID.fromString(id)) ); consumeRowAsync(future, this::songFromRow, consumer); } @Override public void getPlaylistById(String id, Function<Optional<?>, ?> consumer) { ResultSetFuture future = session.executeAsync( stmt_get_playlist.bind(UUID.fromString(id)) ); consumeRowsAsync(future, rs -> playlistFromRows(id, rs), consumer); } Optional<Playlist> playlistFromRows(String id, Optional<List<Row>> rows) { Playlist playlist = new Playlist(UUID.fromString(id)); rows.ifPresent( list -> list.forEach( row -> playlist.addSong(songFromRow(row)) ) ); return Optional.of(playlist); }
Optional<Song> songFromRow(Optional<Row> row) {
gibffe/fuse
src/test/java/com/sulaco/fuse/config/AnnotationScannerImplTest.java
// Path: src/main/java/com/sulaco/fuse/config/actor/ActorFactory.java // public interface ActorFactory extends ActorSystemAware, ApplicationContextAware { // // public Optional<ActorRef> getLocalActor(String actorClass); // // public Optional<ActorRef> getLocalActor(String actorClass, String actorName); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, int spinCount); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, String actorName, int spinCount); // // public Optional<ActorRef> getLocalActorByRef(String ref); // // public Optional<ActorSelection> select(String path); // // public Iterable<ActorRef> getRoutees(String ref, Class<?> clazz, int spinCount); // // // } // // Path: src/main/java/com/sulaco/fuse/config/route/RoutesConfig.java // public interface RoutesConfig { // // public void parse(); // // public Optional<Route> getFuseRoute(String uri); // // public void addEndpoint(ActorRef ref, String httpMethod, String path); // }
import akka.actor.ActorRef; import com.sulaco.fuse.config.actor.ActorFactory; import com.sulaco.fuse.config.route.RoutesConfig; import com.typesafe.config.Config; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*;
package com.sulaco.fuse.config; @RunWith(MockitoJUnitRunner.class) public class AnnotationScannerImplTest { @Mock Config mockConfig; @Mock ConfigSource mockConfigSource;
// Path: src/main/java/com/sulaco/fuse/config/actor/ActorFactory.java // public interface ActorFactory extends ActorSystemAware, ApplicationContextAware { // // public Optional<ActorRef> getLocalActor(String actorClass); // // public Optional<ActorRef> getLocalActor(String actorClass, String actorName); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, int spinCount); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, String actorName, int spinCount); // // public Optional<ActorRef> getLocalActorByRef(String ref); // // public Optional<ActorSelection> select(String path); // // public Iterable<ActorRef> getRoutees(String ref, Class<?> clazz, int spinCount); // // // } // // Path: src/main/java/com/sulaco/fuse/config/route/RoutesConfig.java // public interface RoutesConfig { // // public void parse(); // // public Optional<Route> getFuseRoute(String uri); // // public void addEndpoint(ActorRef ref, String httpMethod, String path); // } // Path: src/test/java/com/sulaco/fuse/config/AnnotationScannerImplTest.java import akka.actor.ActorRef; import com.sulaco.fuse.config.actor.ActorFactory; import com.sulaco.fuse.config.route.RoutesConfig; import com.typesafe.config.Config; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; package com.sulaco.fuse.config; @RunWith(MockitoJUnitRunner.class) public class AnnotationScannerImplTest { @Mock Config mockConfig; @Mock ConfigSource mockConfigSource;
@Mock RoutesConfig mockRoutesConfig;
gibffe/fuse
src/test/java/com/sulaco/fuse/config/AnnotationScannerImplTest.java
// Path: src/main/java/com/sulaco/fuse/config/actor/ActorFactory.java // public interface ActorFactory extends ActorSystemAware, ApplicationContextAware { // // public Optional<ActorRef> getLocalActor(String actorClass); // // public Optional<ActorRef> getLocalActor(String actorClass, String actorName); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, int spinCount); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, String actorName, int spinCount); // // public Optional<ActorRef> getLocalActorByRef(String ref); // // public Optional<ActorSelection> select(String path); // // public Iterable<ActorRef> getRoutees(String ref, Class<?> clazz, int spinCount); // // // } // // Path: src/main/java/com/sulaco/fuse/config/route/RoutesConfig.java // public interface RoutesConfig { // // public void parse(); // // public Optional<Route> getFuseRoute(String uri); // // public void addEndpoint(ActorRef ref, String httpMethod, String path); // }
import akka.actor.ActorRef; import com.sulaco.fuse.config.actor.ActorFactory; import com.sulaco.fuse.config.route.RoutesConfig; import com.typesafe.config.Config; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*;
package com.sulaco.fuse.config; @RunWith(MockitoJUnitRunner.class) public class AnnotationScannerImplTest { @Mock Config mockConfig; @Mock ConfigSource mockConfigSource; @Mock RoutesConfig mockRoutesConfig;
// Path: src/main/java/com/sulaco/fuse/config/actor/ActorFactory.java // public interface ActorFactory extends ActorSystemAware, ApplicationContextAware { // // public Optional<ActorRef> getLocalActor(String actorClass); // // public Optional<ActorRef> getLocalActor(String actorClass, String actorName); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, int spinCount); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, String actorName, int spinCount); // // public Optional<ActorRef> getLocalActorByRef(String ref); // // public Optional<ActorSelection> select(String path); // // public Iterable<ActorRef> getRoutees(String ref, Class<?> clazz, int spinCount); // // // } // // Path: src/main/java/com/sulaco/fuse/config/route/RoutesConfig.java // public interface RoutesConfig { // // public void parse(); // // public Optional<Route> getFuseRoute(String uri); // // public void addEndpoint(ActorRef ref, String httpMethod, String path); // } // Path: src/test/java/com/sulaco/fuse/config/AnnotationScannerImplTest.java import akka.actor.ActorRef; import com.sulaco.fuse.config.actor.ActorFactory; import com.sulaco.fuse.config.route.RoutesConfig; import com.typesafe.config.Config; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; package com.sulaco.fuse.config; @RunWith(MockitoJUnitRunner.class) public class AnnotationScannerImplTest { @Mock Config mockConfig; @Mock ConfigSource mockConfigSource; @Mock RoutesConfig mockRoutesConfig;
@Mock ActorFactory mockFactory;
gibffe/fuse
examples/simple/src/main/java/com/sulaco/fuse/example/actor/GetActor.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.springframework.context.ApplicationContext;
package com.sulaco.fuse.example.actor; public class GetActor extends FuseEndpointActor { @Override
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: examples/simple/src/main/java/com/sulaco/fuse/example/actor/GetActor.java import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.springframework.context.ApplicationContext; package com.sulaco.fuse.example.actor; public class GetActor extends FuseEndpointActor { @Override
protected void onRequest(FuseRequestMessage request) {
gibffe/fuse
src/test/java/com/sulaco/fuse/config/route/RoutesConfigImplTest.java
// Path: src/main/java/com/sulaco/fuse/config/ConfigSource.java // public interface ConfigSource { // // public void parseLocalConfig(); // // public Config getConfig(); // // public RoutesConfig getRoutesConfig(); // } // // Path: src/main/java/com/sulaco/fuse/config/actor/ActorFactory.java // public interface ActorFactory extends ActorSystemAware, ApplicationContextAware { // // public Optional<ActorRef> getLocalActor(String actorClass); // // public Optional<ActorRef> getLocalActor(String actorClass, String actorName); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, int spinCount); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, String actorName, int spinCount); // // public Optional<ActorRef> getLocalActorByRef(String ref); // // public Optional<ActorSelection> select(String path); // // public Iterable<ActorRef> getRoutees(String ref, Class<?> clazz, int spinCount); // // // }
import static org.assertj.core.api.Assertions.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import io.netty.handler.codec.http.HttpMethod; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import akka.actor.ActorRef; import akka.actor.ActorSystem; import com.sulaco.fuse.config.ConfigSource; import com.sulaco.fuse.config.actor.ActorFactory; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory;
package com.sulaco.fuse.config.route; @RunWith(MockitoJUnitRunner.class) public class RoutesConfigImplTest { Config config; @Mock
// Path: src/main/java/com/sulaco/fuse/config/ConfigSource.java // public interface ConfigSource { // // public void parseLocalConfig(); // // public Config getConfig(); // // public RoutesConfig getRoutesConfig(); // } // // Path: src/main/java/com/sulaco/fuse/config/actor/ActorFactory.java // public interface ActorFactory extends ActorSystemAware, ApplicationContextAware { // // public Optional<ActorRef> getLocalActor(String actorClass); // // public Optional<ActorRef> getLocalActor(String actorClass, String actorName); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, int spinCount); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, String actorName, int spinCount); // // public Optional<ActorRef> getLocalActorByRef(String ref); // // public Optional<ActorSelection> select(String path); // // public Iterable<ActorRef> getRoutees(String ref, Class<?> clazz, int spinCount); // // // } // Path: src/test/java/com/sulaco/fuse/config/route/RoutesConfigImplTest.java import static org.assertj.core.api.Assertions.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import io.netty.handler.codec.http.HttpMethod; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import akka.actor.ActorRef; import akka.actor.ActorSystem; import com.sulaco.fuse.config.ConfigSource; import com.sulaco.fuse.config.actor.ActorFactory; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; package com.sulaco.fuse.config.route; @RunWith(MockitoJUnitRunner.class) public class RoutesConfigImplTest { Config config; @Mock
ConfigSource mockConfigSource;
gibffe/fuse
src/test/java/com/sulaco/fuse/config/route/RoutesConfigImplTest.java
// Path: src/main/java/com/sulaco/fuse/config/ConfigSource.java // public interface ConfigSource { // // public void parseLocalConfig(); // // public Config getConfig(); // // public RoutesConfig getRoutesConfig(); // } // // Path: src/main/java/com/sulaco/fuse/config/actor/ActorFactory.java // public interface ActorFactory extends ActorSystemAware, ApplicationContextAware { // // public Optional<ActorRef> getLocalActor(String actorClass); // // public Optional<ActorRef> getLocalActor(String actorClass, String actorName); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, int spinCount); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, String actorName, int spinCount); // // public Optional<ActorRef> getLocalActorByRef(String ref); // // public Optional<ActorSelection> select(String path); // // public Iterable<ActorRef> getRoutees(String ref, Class<?> clazz, int spinCount); // // // }
import static org.assertj.core.api.Assertions.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import io.netty.handler.codec.http.HttpMethod; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import akka.actor.ActorRef; import akka.actor.ActorSystem; import com.sulaco.fuse.config.ConfigSource; import com.sulaco.fuse.config.actor.ActorFactory; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory;
package com.sulaco.fuse.config.route; @RunWith(MockitoJUnitRunner.class) public class RoutesConfigImplTest { Config config; @Mock ConfigSource mockConfigSource; @Mock
// Path: src/main/java/com/sulaco/fuse/config/ConfigSource.java // public interface ConfigSource { // // public void parseLocalConfig(); // // public Config getConfig(); // // public RoutesConfig getRoutesConfig(); // } // // Path: src/main/java/com/sulaco/fuse/config/actor/ActorFactory.java // public interface ActorFactory extends ActorSystemAware, ApplicationContextAware { // // public Optional<ActorRef> getLocalActor(String actorClass); // // public Optional<ActorRef> getLocalActor(String actorClass, String actorName); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, int spinCount); // // public Optional<ActorRef> getLocalActor(String ref, String actorClass, String actorName, int spinCount); // // public Optional<ActorRef> getLocalActorByRef(String ref); // // public Optional<ActorSelection> select(String path); // // public Iterable<ActorRef> getRoutees(String ref, Class<?> clazz, int spinCount); // // // } // Path: src/test/java/com/sulaco/fuse/config/route/RoutesConfigImplTest.java import static org.assertj.core.api.Assertions.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import io.netty.handler.codec.http.HttpMethod; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import akka.actor.ActorRef; import akka.actor.ActorSystem; import com.sulaco.fuse.config.ConfigSource; import com.sulaco.fuse.config.actor.ActorFactory; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; package com.sulaco.fuse.config.route; @RunWith(MockitoJUnitRunner.class) public class RoutesConfigImplTest { Config config; @Mock ConfigSource mockConfigSource; @Mock
ActorFactory mockActorFactory;
gibffe/fuse
examples/annotations/src/main/java/com/sulaco/fuse/example/endpoint/EchoParam.java
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.config.annotation.FuseEndpoint;
package com.sulaco.fuse.example.endpoint; @FuseEndpoint(path = "/echo/<param1>") public class EchoParam extends FuseEndpointActor { @Override
// Path: src/main/java/com/sulaco/fuse/akka/actor/FuseEndpointActor.java // public abstract class FuseEndpointActor extends FuseBaseActor { // // @Autowired protected MetricsRegistry metrics; // // public FuseEndpointActor() { // super(); // } // // // TODO: refactor metrics // // meter = metrics.getRegistry().timer(getClass().getName()); // // @Override // public void onReceive(Object message) throws Exception { // try { // if (message instanceof FuseRequestMessage) { // onRequest((FuseRequestMessage) message); // //proto.error((FuseRequestMessage) message); // } // else { // super.onReceive(message); // } // } // catch (Exception ex) { // log.error("Error handling request !", ex); // unhandled(message); // } // finally { // // TODO: context flush // } // } // // protected void onRequest(final FuseRequestMessage request) { // // RouteHandler rhandler = request.getHandler(); // // Optional<String> method = rhandler.getMethodName(); // // if (method.isPresent()) { // // Invoke configured method instead of default 'onReceive'. Method needs to have correct // // signature, otherwise, fallback to 'onReceive' will occur. // // // Optional<Method> target = lookupMethod(this, method.get()); // if (target.isPresent()) { // try { // target.get() // .invoke(this, request); // } // catch (Exception ex) { // log.warn("[fuse] Invocation failure. x_x", ex); // } // } // } // else { // log.warn("[fuse] No handling method specified. Override onReceive. x_x"); // } // } // // // // @Override // public void unhandled(Object message) { // super.unhandled(message); // if (message instanceof FuseRequestMessage) { // proto.error((FuseRequestMessage) message); // } // } // // public void setProto(WireProtocol proto) { // this.proto = proto; // } // // protected static final Logger log = LoggerFactory.getLogger(FuseEndpointActor.class); // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: examples/annotations/src/main/java/com/sulaco/fuse/example/endpoint/EchoParam.java import com.sulaco.fuse.akka.actor.FuseEndpointActor; import com.sulaco.fuse.akka.message.FuseRequestMessage; import com.sulaco.fuse.config.annotation.FuseEndpoint; package com.sulaco.fuse.example.endpoint; @FuseEndpoint(path = "/echo/<param1>") public class EchoParam extends FuseEndpointActor { @Override
protected void onRequest(FuseRequestMessage request) {
gibffe/fuse
src/test/java/com/sulaco/fuse/akka/actor/ServerVersionActorTest.java
// Path: src/test/java/com/sulaco/fuse/ActorAwareTest.java // @Ignore // public class ActorAwareTest { // // ActorSystem system = ActorSystem.create("test"); // // @Mock protected ApplicationContext mockAppCtx; // // @Mock protected AutowireCapableBeanFactory mockAutowireFactory; // // @Mock protected WireProtocol mockProto; // // @Mock protected Timer mockMeter; // // protected void setup() { // when(mockAppCtx.getAutowireCapableBeanFactory()).thenReturn(mockAutowireFactory); // } // // protected <T extends FuseEndpointActor> TestActorRef<T> mockEndpoint(Class<T> clazz) { // Props props = Props.create(clazz); // TestActorRef<T> testActorRef = TestActorRef.create(system, props); // testActorRef.underlyingActor().setProto(mockProto); // testActorRef.underlyingActor().autowire(mockAppCtx); // // return testActorRef; // } // // } // // Path: src/main/java/com/sulaco/fuse/FuseVersion.java // @Component // public class FuseVersion { // // String version = "Fuse v0.0.3-SNAPSHOT"; // // public FuseVersion() { // super(); // } // // public String toString() { // return version; // } // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import akka.testkit.TestActorRef; import com.sulaco.fuse.ActorAwareTest; import com.sulaco.fuse.FuseVersion; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnit44Runner; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.sulaco.fuse.akka.actor; @RunWith(MockitoJUnit44Runner.class) public class ServerVersionActorTest extends ActorAwareTest { TestActorRef<ServerVersionActor> instance;
// Path: src/test/java/com/sulaco/fuse/ActorAwareTest.java // @Ignore // public class ActorAwareTest { // // ActorSystem system = ActorSystem.create("test"); // // @Mock protected ApplicationContext mockAppCtx; // // @Mock protected AutowireCapableBeanFactory mockAutowireFactory; // // @Mock protected WireProtocol mockProto; // // @Mock protected Timer mockMeter; // // protected void setup() { // when(mockAppCtx.getAutowireCapableBeanFactory()).thenReturn(mockAutowireFactory); // } // // protected <T extends FuseEndpointActor> TestActorRef<T> mockEndpoint(Class<T> clazz) { // Props props = Props.create(clazz); // TestActorRef<T> testActorRef = TestActorRef.create(system, props); // testActorRef.underlyingActor().setProto(mockProto); // testActorRef.underlyingActor().autowire(mockAppCtx); // // return testActorRef; // } // // } // // Path: src/main/java/com/sulaco/fuse/FuseVersion.java // @Component // public class FuseVersion { // // String version = "Fuse v0.0.3-SNAPSHOT"; // // public FuseVersion() { // super(); // } // // public String toString() { // return version; // } // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: src/test/java/com/sulaco/fuse/akka/actor/ServerVersionActorTest.java import akka.testkit.TestActorRef; import com.sulaco.fuse.ActorAwareTest; import com.sulaco.fuse.FuseVersion; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnit44Runner; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package com.sulaco.fuse.akka.actor; @RunWith(MockitoJUnit44Runner.class) public class ServerVersionActorTest extends ActorAwareTest { TestActorRef<ServerVersionActor> instance;
@Mock FuseVersion mockVersion;
gibffe/fuse
src/test/java/com/sulaco/fuse/akka/actor/ServerVersionActorTest.java
// Path: src/test/java/com/sulaco/fuse/ActorAwareTest.java // @Ignore // public class ActorAwareTest { // // ActorSystem system = ActorSystem.create("test"); // // @Mock protected ApplicationContext mockAppCtx; // // @Mock protected AutowireCapableBeanFactory mockAutowireFactory; // // @Mock protected WireProtocol mockProto; // // @Mock protected Timer mockMeter; // // protected void setup() { // when(mockAppCtx.getAutowireCapableBeanFactory()).thenReturn(mockAutowireFactory); // } // // protected <T extends FuseEndpointActor> TestActorRef<T> mockEndpoint(Class<T> clazz) { // Props props = Props.create(clazz); // TestActorRef<T> testActorRef = TestActorRef.create(system, props); // testActorRef.underlyingActor().setProto(mockProto); // testActorRef.underlyingActor().autowire(mockAppCtx); // // return testActorRef; // } // // } // // Path: src/main/java/com/sulaco/fuse/FuseVersion.java // @Component // public class FuseVersion { // // String version = "Fuse v0.0.3-SNAPSHOT"; // // public FuseVersion() { // super(); // } // // public String toString() { // return version; // } // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // }
import akka.testkit.TestActorRef; import com.sulaco.fuse.ActorAwareTest; import com.sulaco.fuse.FuseVersion; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnit44Runner; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.sulaco.fuse.akka.actor; @RunWith(MockitoJUnit44Runner.class) public class ServerVersionActorTest extends ActorAwareTest { TestActorRef<ServerVersionActor> instance; @Mock FuseVersion mockVersion; @Before public void setup() { super.setup(); instance = mockEndpoint(ServerVersionActor.class); instance.underlyingActor().version = mockVersion; } @Test public void testGetVersion() { // given
// Path: src/test/java/com/sulaco/fuse/ActorAwareTest.java // @Ignore // public class ActorAwareTest { // // ActorSystem system = ActorSystem.create("test"); // // @Mock protected ApplicationContext mockAppCtx; // // @Mock protected AutowireCapableBeanFactory mockAutowireFactory; // // @Mock protected WireProtocol mockProto; // // @Mock protected Timer mockMeter; // // protected void setup() { // when(mockAppCtx.getAutowireCapableBeanFactory()).thenReturn(mockAutowireFactory); // } // // protected <T extends FuseEndpointActor> TestActorRef<T> mockEndpoint(Class<T> clazz) { // Props props = Props.create(clazz); // TestActorRef<T> testActorRef = TestActorRef.create(system, props); // testActorRef.underlyingActor().setProto(mockProto); // testActorRef.underlyingActor().autowire(mockAppCtx); // // return testActorRef; // } // // } // // Path: src/main/java/com/sulaco/fuse/FuseVersion.java // @Component // public class FuseVersion { // // String version = "Fuse v0.0.3-SNAPSHOT"; // // public FuseVersion() { // super(); // } // // public String toString() { // return version; // } // } // // Path: src/main/java/com/sulaco/fuse/akka/message/FuseRequestMessage.java // public interface FuseRequestMessage extends Route { // // long getId(); // // HttpRequest getRequest(); // // String getRequestBody(); // // ChannelHandlerContext getChannelContext(); // // void flush(); // // boolean flushed(); // // public <T> Optional<T> getParam(String name, Class<T> clazz); // // } // Path: src/test/java/com/sulaco/fuse/akka/actor/ServerVersionActorTest.java import akka.testkit.TestActorRef; import com.sulaco.fuse.ActorAwareTest; import com.sulaco.fuse.FuseVersion; import com.sulaco.fuse.akka.message.FuseRequestMessage; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnit44Runner; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package com.sulaco.fuse.akka.actor; @RunWith(MockitoJUnit44Runner.class) public class ServerVersionActorTest extends ActorAwareTest { TestActorRef<ServerVersionActor> instance; @Mock FuseVersion mockVersion; @Before public void setup() { super.setup(); instance = mockEndpoint(ServerVersionActor.class); instance.underlyingActor().version = mockVersion; } @Test public void testGetVersion() { // given
FuseRequestMessage mockMessage = mock(FuseRequestMessage.class);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/instantiation/DefaultTypeConversions.java
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/DatabaseSQLException.java // public class DatabaseSQLException extends DatabaseException { // // public DatabaseSQLException(@NotNull String message, @NotNull SQLException cause) { // super(message, cause); // } // // public DatabaseSQLException(@NotNull SQLException cause) { // super(cause); // } // // @Override // public synchronized @NotNull SQLException getCause() { // return (SQLException) super.getCause(); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // }
import org.dalesbred.DatabaseException; import org.dalesbred.DatabaseSQLException; import org.dalesbred.conversion.TypeConversionRegistry; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Document; import javax.xml.transform.dom.DOMSource; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.sql.*; import java.time.*; import java.util.TimeZone;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.instantiation; final class DefaultTypeConversions { private static final int BUFFER_SIZE = 1024; private static final int EPOCH_YEAR = 1900; private DefaultTypeConversions() { }
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/DatabaseSQLException.java // public class DatabaseSQLException extends DatabaseException { // // public DatabaseSQLException(@NotNull String message, @NotNull SQLException cause) { // super(message, cause); // } // // public DatabaseSQLException(@NotNull SQLException cause) { // super(cause); // } // // @Override // public synchronized @NotNull SQLException getCause() { // return (SQLException) super.getCause(); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // } // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/DefaultTypeConversions.java import org.dalesbred.DatabaseException; import org.dalesbred.DatabaseSQLException; import org.dalesbred.conversion.TypeConversionRegistry; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Document; import javax.xml.transform.dom.DOMSource; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.sql.*; import java.time.*; import java.util.TimeZone; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.instantiation; final class DefaultTypeConversions { private static final int BUFFER_SIZE = 1024; private static final int EPOCH_YEAR = 1900; private DefaultTypeConversions() { }
public static void register(@NotNull TypeConversionRegistry registry) {
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/instantiation/DefaultTypeConversions.java
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/DatabaseSQLException.java // public class DatabaseSQLException extends DatabaseException { // // public DatabaseSQLException(@NotNull String message, @NotNull SQLException cause) { // super(message, cause); // } // // public DatabaseSQLException(@NotNull SQLException cause) { // super(cause); // } // // @Override // public synchronized @NotNull SQLException getCause() { // return (SQLException) super.getCause(); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // }
import org.dalesbred.DatabaseException; import org.dalesbred.DatabaseSQLException; import org.dalesbred.conversion.TypeConversionRegistry; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Document; import javax.xml.transform.dom.DOMSource; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.sql.*; import java.time.*; import java.util.TimeZone;
private static @NotNull URL convertStringToUrl(@NotNull String value) { try { return new URL(value); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } } private static @NotNull URI convertStringToUri(@NotNull String value) { try { return new URI(value); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } private static @NotNull String convertClobToString(@NotNull Clob value) { try (Reader reader = value.getCharacterStream()) { StringBuilder sb = new StringBuilder((int) value.length()); char[] buf = new char[BUFFER_SIZE]; int n; while ((n = reader.read(buf)) != -1) sb.append(buf, 0, n); return sb.toString(); } catch (SQLException e) {
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/DatabaseSQLException.java // public class DatabaseSQLException extends DatabaseException { // // public DatabaseSQLException(@NotNull String message, @NotNull SQLException cause) { // super(message, cause); // } // // public DatabaseSQLException(@NotNull SQLException cause) { // super(cause); // } // // @Override // public synchronized @NotNull SQLException getCause() { // return (SQLException) super.getCause(); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // } // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/DefaultTypeConversions.java import org.dalesbred.DatabaseException; import org.dalesbred.DatabaseSQLException; import org.dalesbred.conversion.TypeConversionRegistry; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Document; import javax.xml.transform.dom.DOMSource; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.sql.*; import java.time.*; import java.util.TimeZone; private static @NotNull URL convertStringToUrl(@NotNull String value) { try { return new URL(value); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } } private static @NotNull URI convertStringToUri(@NotNull String value) { try { return new URI(value); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } private static @NotNull String convertClobToString(@NotNull Clob value) { try (Reader reader = value.getCharacterStream()) { StringBuilder sb = new StringBuilder((int) value.length()); char[] buf = new char[BUFFER_SIZE]; int n; while ((n = reader.read(buf)) != -1) sb.append(buf, 0, n); return sb.toString(); } catch (SQLException e) {
throw new DatabaseSQLException(e);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/instantiation/DefaultTypeConversions.java
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/DatabaseSQLException.java // public class DatabaseSQLException extends DatabaseException { // // public DatabaseSQLException(@NotNull String message, @NotNull SQLException cause) { // super(message, cause); // } // // public DatabaseSQLException(@NotNull SQLException cause) { // super(cause); // } // // @Override // public synchronized @NotNull SQLException getCause() { // return (SQLException) super.getCause(); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // }
import org.dalesbred.DatabaseException; import org.dalesbred.DatabaseSQLException; import org.dalesbred.conversion.TypeConversionRegistry; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Document; import javax.xml.transform.dom.DOMSource; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.sql.*; import java.time.*; import java.util.TimeZone;
try { return new URL(value); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } } private static @NotNull URI convertStringToUri(@NotNull String value) { try { return new URI(value); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } private static @NotNull String convertClobToString(@NotNull Clob value) { try (Reader reader = value.getCharacterStream()) { StringBuilder sb = new StringBuilder((int) value.length()); char[] buf = new char[BUFFER_SIZE]; int n; while ((n = reader.read(buf)) != -1) sb.append(buf, 0, n); return sb.toString(); } catch (SQLException e) { throw new DatabaseSQLException(e); } catch (IOException e) {
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/DatabaseSQLException.java // public class DatabaseSQLException extends DatabaseException { // // public DatabaseSQLException(@NotNull String message, @NotNull SQLException cause) { // super(message, cause); // } // // public DatabaseSQLException(@NotNull SQLException cause) { // super(cause); // } // // @Override // public synchronized @NotNull SQLException getCause() { // return (SQLException) super.getCause(); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // } // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/DefaultTypeConversions.java import org.dalesbred.DatabaseException; import org.dalesbred.DatabaseSQLException; import org.dalesbred.conversion.TypeConversionRegistry; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Document; import javax.xml.transform.dom.DOMSource; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.sql.*; import java.time.*; import java.util.TimeZone; try { return new URL(value); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } } private static @NotNull URI convertStringToUri(@NotNull String value) { try { return new URI(value); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } private static @NotNull String convertClobToString(@NotNull Clob value) { try (Reader reader = value.getCharacterStream()) { StringBuilder sb = new StringBuilder((int) value.length()); char[] buf = new char[BUFFER_SIZE]; int n; while ((n = reader.read(buf)) != -1) sb.append(buf, 0, n); return sb.toString(); } catch (SQLException e) { throw new DatabaseSQLException(e); } catch (IOException e) {
throw new DatabaseException("failed to convert Clob to String", e);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/result/ResultTable.java
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/TypeUtils.java // public final class TypeUtils { // // private TypeUtils() { } // // public static @NotNull Class<?> rawType(@NotNull Type type) { // if (type instanceof Class<?>) { // return (Class<?>) type; // // } else if (type instanceof ParameterizedType) { // return rawType(((ParameterizedType) type).getRawType()); // // } else if (type instanceof TypeVariable<?>) { // // We could return one of the bounds, but it won't work if there are multiple bounds. // // Therefore just return object. // return Object.class; // // } else if (type instanceof WildcardType) { // return rawType(((WildcardType) type).getUpperBounds()[0]); // // } else if (type instanceof GenericArrayType) { // return arrayType(rawType(((GenericArrayType) type).getGenericComponentType())); // // } else { // throw new IllegalArgumentException("unexpected type: " + type); // } // } // // public static @NotNull Type typeParameter(@NotNull Type type) { // if (type instanceof ParameterizedType) // return ((ParameterizedType) type).getActualTypeArguments()[0]; // // return Object.class; // } // // public static boolean isEnum(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isEnum(); // } // // public static boolean isPrimitive(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isPrimitive(); // } // // public static @NotNull Class<?> arrayType(@NotNull Class<?> type) { // return Array.newInstance(type, 0).getClass(); // } // // public static @Nullable Type genericSuperClass(@NotNull Type type) { // return rawType(type).getGenericSuperclass(); // } // // public static @NotNull Type[] genericInterfaces(@NotNull Type type) { // return rawType(type).getGenericInterfaces(); // } // // public static boolean isAssignable(@NotNull Type target, @NotNull Type source) { // // TODO: implement proper rules for generic types // return isAssignableByBoxing(rawType(target), rawType(source)); // } // // private static boolean isAssignableByBoxing(@NotNull Class<?> target, @NotNull Class<?> source) { // return Primitives.wrap(target).isAssignableFrom(Primitives.wrap(source)); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/CollectionUtils.java // public static @NotNull <A,B> List<B> mapToList(@NotNull Collection<? extends A> xs, @NotNull Function<? super A, ? extends B> mapper) { // return xs.stream().map(mapper).collect(toListWithCapacity(xs.size())); // }
import static java.util.Collections.unmodifiableList; import static java.util.Objects.requireNonNull; import static org.dalesbred.internal.utils.CollectionUtils.mapToList; import org.dalesbred.internal.utils.TypeUtils; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
/* * Copyright (c) 2018 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.result; /** * Represents the results of the query along with its metadata. Basically a detached * version of {@link java.sql.ResultSet}. */ public final class ResultTable implements Iterable<ResultTable.ResultRow> { private final @NotNull List<ColumnMetadata> columns; private final @NotNull List<ResultRow> rows; private ResultTable(@NotNull List<ColumnMetadata> columns, @NotNull List<ResultRow> rows) { this.columns = unmodifiableList(columns); this.rows = unmodifiableList(rows); } public int getRowCount() { return rows.size(); } public int getColumnCount() { return columns.size(); } /** * Returns the value of given column of given row. Both indices are zero-based. */ public Object get(int row, int column) { return rows.get(row).get(column); } /** * Returns the value of given named column of given row. */ public Object get(int row, @NotNull String column) { return rows.get(row).get(column); } public @NotNull List<ResultRow> getRows() { return rows; } public @NotNull List<ColumnMetadata> getColumns() { return columns; } public @NotNull List<String> getColumnNames() {
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/TypeUtils.java // public final class TypeUtils { // // private TypeUtils() { } // // public static @NotNull Class<?> rawType(@NotNull Type type) { // if (type instanceof Class<?>) { // return (Class<?>) type; // // } else if (type instanceof ParameterizedType) { // return rawType(((ParameterizedType) type).getRawType()); // // } else if (type instanceof TypeVariable<?>) { // // We could return one of the bounds, but it won't work if there are multiple bounds. // // Therefore just return object. // return Object.class; // // } else if (type instanceof WildcardType) { // return rawType(((WildcardType) type).getUpperBounds()[0]); // // } else if (type instanceof GenericArrayType) { // return arrayType(rawType(((GenericArrayType) type).getGenericComponentType())); // // } else { // throw new IllegalArgumentException("unexpected type: " + type); // } // } // // public static @NotNull Type typeParameter(@NotNull Type type) { // if (type instanceof ParameterizedType) // return ((ParameterizedType) type).getActualTypeArguments()[0]; // // return Object.class; // } // // public static boolean isEnum(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isEnum(); // } // // public static boolean isPrimitive(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isPrimitive(); // } // // public static @NotNull Class<?> arrayType(@NotNull Class<?> type) { // return Array.newInstance(type, 0).getClass(); // } // // public static @Nullable Type genericSuperClass(@NotNull Type type) { // return rawType(type).getGenericSuperclass(); // } // // public static @NotNull Type[] genericInterfaces(@NotNull Type type) { // return rawType(type).getGenericInterfaces(); // } // // public static boolean isAssignable(@NotNull Type target, @NotNull Type source) { // // TODO: implement proper rules for generic types // return isAssignableByBoxing(rawType(target), rawType(source)); // } // // private static boolean isAssignableByBoxing(@NotNull Class<?> target, @NotNull Class<?> source) { // return Primitives.wrap(target).isAssignableFrom(Primitives.wrap(source)); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/CollectionUtils.java // public static @NotNull <A,B> List<B> mapToList(@NotNull Collection<? extends A> xs, @NotNull Function<? super A, ? extends B> mapper) { // return xs.stream().map(mapper).collect(toListWithCapacity(xs.size())); // } // Path: dalesbred/src/main/java/org/dalesbred/result/ResultTable.java import static java.util.Collections.unmodifiableList; import static java.util.Objects.requireNonNull; import static org.dalesbred.internal.utils.CollectionUtils.mapToList; import org.dalesbred.internal.utils.TypeUtils; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /* * Copyright (c) 2018 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.result; /** * Represents the results of the query along with its metadata. Basically a detached * version of {@link java.sql.ResultSet}. */ public final class ResultTable implements Iterable<ResultTable.ResultRow> { private final @NotNull List<ColumnMetadata> columns; private final @NotNull List<ResultRow> rows; private ResultTable(@NotNull List<ColumnMetadata> columns, @NotNull List<ResultRow> rows) { this.columns = unmodifiableList(columns); this.rows = unmodifiableList(rows); } public int getRowCount() { return rows.size(); } public int getColumnCount() { return columns.size(); } /** * Returns the value of given column of given row. Both indices are zero-based. */ public Object get(int row, int column) { return rows.get(row).get(column); } /** * Returns the value of given named column of given row. */ public Object get(int row, @NotNull String column) { return rows.get(row).get(column); } public @NotNull List<ResultRow> getRows() { return rows; } public @NotNull List<ColumnMetadata> getColumns() { return columns; } public @NotNull List<String> getColumnNames() {
return mapToList(columns, ColumnMetadata::getName);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/result/ResultTable.java
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/TypeUtils.java // public final class TypeUtils { // // private TypeUtils() { } // // public static @NotNull Class<?> rawType(@NotNull Type type) { // if (type instanceof Class<?>) { // return (Class<?>) type; // // } else if (type instanceof ParameterizedType) { // return rawType(((ParameterizedType) type).getRawType()); // // } else if (type instanceof TypeVariable<?>) { // // We could return one of the bounds, but it won't work if there are multiple bounds. // // Therefore just return object. // return Object.class; // // } else if (type instanceof WildcardType) { // return rawType(((WildcardType) type).getUpperBounds()[0]); // // } else if (type instanceof GenericArrayType) { // return arrayType(rawType(((GenericArrayType) type).getGenericComponentType())); // // } else { // throw new IllegalArgumentException("unexpected type: " + type); // } // } // // public static @NotNull Type typeParameter(@NotNull Type type) { // if (type instanceof ParameterizedType) // return ((ParameterizedType) type).getActualTypeArguments()[0]; // // return Object.class; // } // // public static boolean isEnum(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isEnum(); // } // // public static boolean isPrimitive(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isPrimitive(); // } // // public static @NotNull Class<?> arrayType(@NotNull Class<?> type) { // return Array.newInstance(type, 0).getClass(); // } // // public static @Nullable Type genericSuperClass(@NotNull Type type) { // return rawType(type).getGenericSuperclass(); // } // // public static @NotNull Type[] genericInterfaces(@NotNull Type type) { // return rawType(type).getGenericInterfaces(); // } // // public static boolean isAssignable(@NotNull Type target, @NotNull Type source) { // // TODO: implement proper rules for generic types // return isAssignableByBoxing(rawType(target), rawType(source)); // } // // private static boolean isAssignableByBoxing(@NotNull Class<?> target, @NotNull Class<?> source) { // return Primitives.wrap(target).isAssignableFrom(Primitives.wrap(source)); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/CollectionUtils.java // public static @NotNull <A,B> List<B> mapToList(@NotNull Collection<? extends A> xs, @NotNull Function<? super A, ? extends B> mapper) { // return xs.stream().map(mapper).collect(toListWithCapacity(xs.size())); // }
import static java.util.Collections.unmodifiableList; import static java.util.Objects.requireNonNull; import static org.dalesbred.internal.utils.CollectionUtils.mapToList; import org.dalesbred.internal.utils.TypeUtils; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
this.type = requireNonNull(type); this.jdbcType = jdbcType; this.databaseType = requireNonNull(databaseType); } /** * Returns the zero-based index of this column. */ public int getIndex() { return index; } /** * Returns the name of this column. */ public @NotNull String getName() { return name; } /** * Returns the Java-type of this column. */ public @NotNull Type getType() { return type; } /** * Returns the raw Java-type of this column. */ public @NotNull Class<?> getRawType() {
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/TypeUtils.java // public final class TypeUtils { // // private TypeUtils() { } // // public static @NotNull Class<?> rawType(@NotNull Type type) { // if (type instanceof Class<?>) { // return (Class<?>) type; // // } else if (type instanceof ParameterizedType) { // return rawType(((ParameterizedType) type).getRawType()); // // } else if (type instanceof TypeVariable<?>) { // // We could return one of the bounds, but it won't work if there are multiple bounds. // // Therefore just return object. // return Object.class; // // } else if (type instanceof WildcardType) { // return rawType(((WildcardType) type).getUpperBounds()[0]); // // } else if (type instanceof GenericArrayType) { // return arrayType(rawType(((GenericArrayType) type).getGenericComponentType())); // // } else { // throw new IllegalArgumentException("unexpected type: " + type); // } // } // // public static @NotNull Type typeParameter(@NotNull Type type) { // if (type instanceof ParameterizedType) // return ((ParameterizedType) type).getActualTypeArguments()[0]; // // return Object.class; // } // // public static boolean isEnum(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isEnum(); // } // // public static boolean isPrimitive(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isPrimitive(); // } // // public static @NotNull Class<?> arrayType(@NotNull Class<?> type) { // return Array.newInstance(type, 0).getClass(); // } // // public static @Nullable Type genericSuperClass(@NotNull Type type) { // return rawType(type).getGenericSuperclass(); // } // // public static @NotNull Type[] genericInterfaces(@NotNull Type type) { // return rawType(type).getGenericInterfaces(); // } // // public static boolean isAssignable(@NotNull Type target, @NotNull Type source) { // // TODO: implement proper rules for generic types // return isAssignableByBoxing(rawType(target), rawType(source)); // } // // private static boolean isAssignableByBoxing(@NotNull Class<?> target, @NotNull Class<?> source) { // return Primitives.wrap(target).isAssignableFrom(Primitives.wrap(source)); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/CollectionUtils.java // public static @NotNull <A,B> List<B> mapToList(@NotNull Collection<? extends A> xs, @NotNull Function<? super A, ? extends B> mapper) { // return xs.stream().map(mapper).collect(toListWithCapacity(xs.size())); // } // Path: dalesbred/src/main/java/org/dalesbred/result/ResultTable.java import static java.util.Collections.unmodifiableList; import static java.util.Objects.requireNonNull; import static org.dalesbred.internal.utils.CollectionUtils.mapToList; import org.dalesbred.internal.utils.TypeUtils; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Iterator; import java.util.List; this.type = requireNonNull(type); this.jdbcType = jdbcType; this.databaseType = requireNonNull(databaseType); } /** * Returns the zero-based index of this column. */ public int getIndex() { return index; } /** * Returns the name of this column. */ public @NotNull String getName() { return name; } /** * Returns the Java-type of this column. */ public @NotNull Type getType() { return type; } /** * Returns the raw Java-type of this column. */ public @NotNull Class<?> getRawType() {
return TypeUtils.rawType(type);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/dialect/OracleDialect.java
// Path: dalesbred/src/main/java/org/dalesbred/datatype/SqlArray.java // public final class SqlArray { // // /** Database specific type name of the array */ // private final @NotNull String type; // // /** Values for the array */ // private final @NotNull List<?> values; // // private SqlArray(@NotNull String type, @NotNull Collection<?> values) { // this.type = requireNonNull(type); // this.values = unmodifiableList(new ArrayList<>(values)); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Collection<?> values) { // return new SqlArray(type, values); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Object[] values) { // return of(type, asList(values)); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull Collection<String> values) { // return of("varchar", values); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull String... values) { // return varchars(asList(values)); // } // // /** // * Returns the database type for the array. // */ // public @NotNull String getType() { // return type; // } // // /** // * Returns the values of the array. // */ // public @NotNull List<?> getValues() { // return values; // } // // @Override // public String toString() { // return "SQLArray[type=" + type + ", values=" + values + ']'; // } // }
import oracle.jdbc.OracleConnection; import org.dalesbred.datatype.SqlArray; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.sql.PreparedStatement; import java.sql.SQLException;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.dialect; /** * Support for Oracle. */ public class OracleDialect extends Dialect { @Override public void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException {
// Path: dalesbred/src/main/java/org/dalesbred/datatype/SqlArray.java // public final class SqlArray { // // /** Database specific type name of the array */ // private final @NotNull String type; // // /** Values for the array */ // private final @NotNull List<?> values; // // private SqlArray(@NotNull String type, @NotNull Collection<?> values) { // this.type = requireNonNull(type); // this.values = unmodifiableList(new ArrayList<>(values)); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Collection<?> values) { // return new SqlArray(type, values); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Object[] values) { // return of(type, asList(values)); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull Collection<String> values) { // return of("varchar", values); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull String... values) { // return varchars(asList(values)); // } // // /** // * Returns the database type for the array. // */ // public @NotNull String getType() { // return type; // } // // /** // * Returns the values of the array. // */ // public @NotNull List<?> getValues() { // return values; // } // // @Override // public String toString() { // return "SQLArray[type=" + type + ", values=" + values + ']'; // } // } // Path: dalesbred/src/main/java/org/dalesbred/dialect/OracleDialect.java import oracle.jdbc.OracleConnection; import org.dalesbred.datatype.SqlArray; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.sql.PreparedStatement; import java.sql.SQLException; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.dialect; /** * Support for Oracle. */ public class OracleDialect extends Dialect { @Override public void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException {
if (value instanceof SqlArray) {
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/utils/EnumUtils.java
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/InstantiationFailureException.java // public class InstantiationFailureException extends DatabaseException { // // public InstantiationFailureException(@NotNull String message) { // super(message); // } // // public InstantiationFailureException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // }
import org.dalesbred.DatabaseException; import org.dalesbred.internal.instantiation.InstantiationFailureException; import org.jetbrains.annotations.NotNull; import java.util.Objects; import java.util.function.Function;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.utils; public final class EnumUtils { private EnumUtils() { } public static @NotNull <T extends Enum<T>> T enumByOrdinal(@NotNull Class<T> enumType, int ordinal) { Enum<?>[] constants = enumType.getEnumConstants(); if (ordinal >= 0 && ordinal < constants.length) return enumType.cast(constants[ordinal]); else
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/InstantiationFailureException.java // public class InstantiationFailureException extends DatabaseException { // // public InstantiationFailureException(@NotNull String message) { // super(message); // } // // public InstantiationFailureException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // } // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/EnumUtils.java import org.dalesbred.DatabaseException; import org.dalesbred.internal.instantiation.InstantiationFailureException; import org.jetbrains.annotations.NotNull; import java.util.Objects; import java.util.function.Function; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.utils; public final class EnumUtils { private EnumUtils() { } public static @NotNull <T extends Enum<T>> T enumByOrdinal(@NotNull Class<T> enumType, int ordinal) { Enum<?>[] constants = enumType.getEnumConstants(); if (ordinal >= 0 && ordinal < constants.length) return enumType.cast(constants[ordinal]); else
throw new DatabaseException("invalid ordinal " + ordinal + " for enum type " + enumType.getName());
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/utils/EnumUtils.java
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/InstantiationFailureException.java // public class InstantiationFailureException extends DatabaseException { // // public InstantiationFailureException(@NotNull String message) { // super(message); // } // // public InstantiationFailureException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // }
import org.dalesbred.DatabaseException; import org.dalesbred.internal.instantiation.InstantiationFailureException; import org.jetbrains.annotations.NotNull; import java.util.Objects; import java.util.function.Function;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.utils; public final class EnumUtils { private EnumUtils() { } public static @NotNull <T extends Enum<T>> T enumByOrdinal(@NotNull Class<T> enumType, int ordinal) { Enum<?>[] constants = enumType.getEnumConstants(); if (ordinal >= 0 && ordinal < constants.length) return enumType.cast(constants[ordinal]); else throw new DatabaseException("invalid ordinal " + ordinal + " for enum type " + enumType.getName()); } public static @NotNull <T extends Enum<T>,K> T enumByKey(@NotNull Class<T> enumType, @NotNull Function<T, K> keyFunction, @NotNull K key) { for (T enumConstant : enumType.getEnumConstants()) if (Objects.equals(key, keyFunction.apply(enumConstant))) return enumConstant;
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/InstantiationFailureException.java // public class InstantiationFailureException extends DatabaseException { // // public InstantiationFailureException(@NotNull String message) { // super(message); // } // // public InstantiationFailureException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // } // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/EnumUtils.java import org.dalesbred.DatabaseException; import org.dalesbred.internal.instantiation.InstantiationFailureException; import org.jetbrains.annotations.NotNull; import java.util.Objects; import java.util.function.Function; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.utils; public final class EnumUtils { private EnumUtils() { } public static @NotNull <T extends Enum<T>> T enumByOrdinal(@NotNull Class<T> enumType, int ordinal) { Enum<?>[] constants = enumType.getEnumConstants(); if (ordinal >= 0 && ordinal < constants.length) return enumType.cast(constants[ordinal]); else throw new DatabaseException("invalid ordinal " + ordinal + " for enum type " + enumType.getName()); } public static @NotNull <T extends Enum<T>,K> T enumByKey(@NotNull Class<T> enumType, @NotNull Function<T, K> keyFunction, @NotNull K key) { for (T enumConstant : enumType.getEnumConstants()) if (Objects.equals(key, keyFunction.apply(enumConstant))) return enumConstant;
throw new InstantiationFailureException("could not find enum constant of type " + enumType.getName() + " for " + key);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/jdbc/ArgumentBinder.java
// Path: dalesbred/src/main/java/org/dalesbred/datatype/InputStreamWithSize.java // public final class InputStreamWithSize extends FilterInputStream { // // private final long size; // // public InputStreamWithSize(@NotNull InputStream in, long size) { // super(in); // // if (size < 0) throw new IllegalArgumentException("negative size: " + size); // // this.size = size; // } // // public long getSize() { // return size; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/datatype/ReaderWithSize.java // public final class ReaderWithSize extends FilterReader { // // private final long size; // // public ReaderWithSize(@NotNull Reader reader, long size) { // super(reader); // // if (size < 0) throw new IllegalArgumentException("negative size: " + size); // // this.size = size; // } // // public long getSize() { // return size; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/datatype/SqlArray.java // public final class SqlArray { // // /** Database specific type name of the array */ // private final @NotNull String type; // // /** Values for the array */ // private final @NotNull List<?> values; // // private SqlArray(@NotNull String type, @NotNull Collection<?> values) { // this.type = requireNonNull(type); // this.values = unmodifiableList(new ArrayList<>(values)); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Collection<?> values) { // return new SqlArray(type, values); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Object[] values) { // return of(type, asList(values)); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull Collection<String> values) { // return of("varchar", values); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull String... values) { // return varchars(asList(values)); // } // // /** // * Returns the database type for the array. // */ // public @NotNull String getType() { // return type; // } // // /** // * Returns the values of the array. // */ // public @NotNull List<?> getValues() { // return values; // } // // @Override // public String toString() { // return "SQLArray[type=" + type + ", values=" + values + ']'; // } // }
import java.io.InputStream; import java.io.Reader; import java.sql.Array; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLXML; import org.dalesbred.datatype.InputStreamWithSize; import org.dalesbred.datatype.ReaderWithSize; import org.dalesbred.datatype.SqlArray; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.w3c.dom.Document; import javax.xml.transform.dom.DOMResult;
/* * Copyright (c) 2015 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.jdbc; public final class ArgumentBinder { private ArgumentBinder() { } public static void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { if (value instanceof InputStream) { bindInputStream(ps, index, (InputStream) value); } else if (value instanceof Reader) { bindReader(ps, index, (Reader) value); } else if (value instanceof Document) { bindXmlDocument(ps, index, (Document) value);
// Path: dalesbred/src/main/java/org/dalesbred/datatype/InputStreamWithSize.java // public final class InputStreamWithSize extends FilterInputStream { // // private final long size; // // public InputStreamWithSize(@NotNull InputStream in, long size) { // super(in); // // if (size < 0) throw new IllegalArgumentException("negative size: " + size); // // this.size = size; // } // // public long getSize() { // return size; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/datatype/ReaderWithSize.java // public final class ReaderWithSize extends FilterReader { // // private final long size; // // public ReaderWithSize(@NotNull Reader reader, long size) { // super(reader); // // if (size < 0) throw new IllegalArgumentException("negative size: " + size); // // this.size = size; // } // // public long getSize() { // return size; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/datatype/SqlArray.java // public final class SqlArray { // // /** Database specific type name of the array */ // private final @NotNull String type; // // /** Values for the array */ // private final @NotNull List<?> values; // // private SqlArray(@NotNull String type, @NotNull Collection<?> values) { // this.type = requireNonNull(type); // this.values = unmodifiableList(new ArrayList<>(values)); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Collection<?> values) { // return new SqlArray(type, values); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Object[] values) { // return of(type, asList(values)); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull Collection<String> values) { // return of("varchar", values); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull String... values) { // return varchars(asList(values)); // } // // /** // * Returns the database type for the array. // */ // public @NotNull String getType() { // return type; // } // // /** // * Returns the values of the array. // */ // public @NotNull List<?> getValues() { // return values; // } // // @Override // public String toString() { // return "SQLArray[type=" + type + ", values=" + values + ']'; // } // } // Path: dalesbred/src/main/java/org/dalesbred/internal/jdbc/ArgumentBinder.java import java.io.InputStream; import java.io.Reader; import java.sql.Array; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLXML; import org.dalesbred.datatype.InputStreamWithSize; import org.dalesbred.datatype.ReaderWithSize; import org.dalesbred.datatype.SqlArray; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.w3c.dom.Document; import javax.xml.transform.dom.DOMResult; /* * Copyright (c) 2015 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.jdbc; public final class ArgumentBinder { private ArgumentBinder() { } public static void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { if (value instanceof InputStream) { bindInputStream(ps, index, (InputStream) value); } else if (value instanceof Reader) { bindReader(ps, index, (Reader) value); } else if (value instanceof Document) { bindXmlDocument(ps, index, (Document) value);
} else if (value instanceof SqlArray) {
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/jdbc/ArgumentBinder.java
// Path: dalesbred/src/main/java/org/dalesbred/datatype/InputStreamWithSize.java // public final class InputStreamWithSize extends FilterInputStream { // // private final long size; // // public InputStreamWithSize(@NotNull InputStream in, long size) { // super(in); // // if (size < 0) throw new IllegalArgumentException("negative size: " + size); // // this.size = size; // } // // public long getSize() { // return size; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/datatype/ReaderWithSize.java // public final class ReaderWithSize extends FilterReader { // // private final long size; // // public ReaderWithSize(@NotNull Reader reader, long size) { // super(reader); // // if (size < 0) throw new IllegalArgumentException("negative size: " + size); // // this.size = size; // } // // public long getSize() { // return size; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/datatype/SqlArray.java // public final class SqlArray { // // /** Database specific type name of the array */ // private final @NotNull String type; // // /** Values for the array */ // private final @NotNull List<?> values; // // private SqlArray(@NotNull String type, @NotNull Collection<?> values) { // this.type = requireNonNull(type); // this.values = unmodifiableList(new ArrayList<>(values)); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Collection<?> values) { // return new SqlArray(type, values); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Object[] values) { // return of(type, asList(values)); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull Collection<String> values) { // return of("varchar", values); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull String... values) { // return varchars(asList(values)); // } // // /** // * Returns the database type for the array. // */ // public @NotNull String getType() { // return type; // } // // /** // * Returns the values of the array. // */ // public @NotNull List<?> getValues() { // return values; // } // // @Override // public String toString() { // return "SQLArray[type=" + type + ", values=" + values + ']'; // } // }
import java.io.InputStream; import java.io.Reader; import java.sql.Array; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLXML; import org.dalesbred.datatype.InputStreamWithSize; import org.dalesbred.datatype.ReaderWithSize; import org.dalesbred.datatype.SqlArray; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.w3c.dom.Document; import javax.xml.transform.dom.DOMResult;
/* * Copyright (c) 2015 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.jdbc; public final class ArgumentBinder { private ArgumentBinder() { } public static void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { if (value instanceof InputStream) { bindInputStream(ps, index, (InputStream) value); } else if (value instanceof Reader) { bindReader(ps, index, (Reader) value); } else if (value instanceof Document) { bindXmlDocument(ps, index, (Document) value); } else if (value instanceof SqlArray) { bindArray(ps, index, (SqlArray) value); } else { ps.setObject(index, value); } } private static void bindInputStream(@NotNull PreparedStatement ps, int index, @NotNull InputStream stream) throws SQLException { // We check whether the InputStream is actually InputStreamWithSize, for two reasons: // 1) the database/driver can optimize the call better if it knows the size in advance // 2) calls without size were introduced in JDBC4 and not all drivers support them
// Path: dalesbred/src/main/java/org/dalesbred/datatype/InputStreamWithSize.java // public final class InputStreamWithSize extends FilterInputStream { // // private final long size; // // public InputStreamWithSize(@NotNull InputStream in, long size) { // super(in); // // if (size < 0) throw new IllegalArgumentException("negative size: " + size); // // this.size = size; // } // // public long getSize() { // return size; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/datatype/ReaderWithSize.java // public final class ReaderWithSize extends FilterReader { // // private final long size; // // public ReaderWithSize(@NotNull Reader reader, long size) { // super(reader); // // if (size < 0) throw new IllegalArgumentException("negative size: " + size); // // this.size = size; // } // // public long getSize() { // return size; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/datatype/SqlArray.java // public final class SqlArray { // // /** Database specific type name of the array */ // private final @NotNull String type; // // /** Values for the array */ // private final @NotNull List<?> values; // // private SqlArray(@NotNull String type, @NotNull Collection<?> values) { // this.type = requireNonNull(type); // this.values = unmodifiableList(new ArrayList<>(values)); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Collection<?> values) { // return new SqlArray(type, values); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Object[] values) { // return of(type, asList(values)); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull Collection<String> values) { // return of("varchar", values); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull String... values) { // return varchars(asList(values)); // } // // /** // * Returns the database type for the array. // */ // public @NotNull String getType() { // return type; // } // // /** // * Returns the values of the array. // */ // public @NotNull List<?> getValues() { // return values; // } // // @Override // public String toString() { // return "SQLArray[type=" + type + ", values=" + values + ']'; // } // } // Path: dalesbred/src/main/java/org/dalesbred/internal/jdbc/ArgumentBinder.java import java.io.InputStream; import java.io.Reader; import java.sql.Array; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLXML; import org.dalesbred.datatype.InputStreamWithSize; import org.dalesbred.datatype.ReaderWithSize; import org.dalesbred.datatype.SqlArray; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.w3c.dom.Document; import javax.xml.transform.dom.DOMResult; /* * Copyright (c) 2015 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.jdbc; public final class ArgumentBinder { private ArgumentBinder() { } public static void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { if (value instanceof InputStream) { bindInputStream(ps, index, (InputStream) value); } else if (value instanceof Reader) { bindReader(ps, index, (Reader) value); } else if (value instanceof Document) { bindXmlDocument(ps, index, (Document) value); } else if (value instanceof SqlArray) { bindArray(ps, index, (SqlArray) value); } else { ps.setObject(index, value); } } private static void bindInputStream(@NotNull PreparedStatement ps, int index, @NotNull InputStream stream) throws SQLException { // We check whether the InputStream is actually InputStreamWithSize, for two reasons: // 1) the database/driver can optimize the call better if it knows the size in advance // 2) calls without size were introduced in JDBC4 and not all drivers support them
if (stream instanceof InputStreamWithSize) {
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/jdbc/ArgumentBinder.java
// Path: dalesbred/src/main/java/org/dalesbred/datatype/InputStreamWithSize.java // public final class InputStreamWithSize extends FilterInputStream { // // private final long size; // // public InputStreamWithSize(@NotNull InputStream in, long size) { // super(in); // // if (size < 0) throw new IllegalArgumentException("negative size: " + size); // // this.size = size; // } // // public long getSize() { // return size; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/datatype/ReaderWithSize.java // public final class ReaderWithSize extends FilterReader { // // private final long size; // // public ReaderWithSize(@NotNull Reader reader, long size) { // super(reader); // // if (size < 0) throw new IllegalArgumentException("negative size: " + size); // // this.size = size; // } // // public long getSize() { // return size; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/datatype/SqlArray.java // public final class SqlArray { // // /** Database specific type name of the array */ // private final @NotNull String type; // // /** Values for the array */ // private final @NotNull List<?> values; // // private SqlArray(@NotNull String type, @NotNull Collection<?> values) { // this.type = requireNonNull(type); // this.values = unmodifiableList(new ArrayList<>(values)); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Collection<?> values) { // return new SqlArray(type, values); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Object[] values) { // return of(type, asList(values)); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull Collection<String> values) { // return of("varchar", values); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull String... values) { // return varchars(asList(values)); // } // // /** // * Returns the database type for the array. // */ // public @NotNull String getType() { // return type; // } // // /** // * Returns the values of the array. // */ // public @NotNull List<?> getValues() { // return values; // } // // @Override // public String toString() { // return "SQLArray[type=" + type + ", values=" + values + ']'; // } // }
import java.io.InputStream; import java.io.Reader; import java.sql.Array; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLXML; import org.dalesbred.datatype.InputStreamWithSize; import org.dalesbred.datatype.ReaderWithSize; import org.dalesbred.datatype.SqlArray; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.w3c.dom.Document; import javax.xml.transform.dom.DOMResult;
/* * Copyright (c) 2015 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.jdbc; public final class ArgumentBinder { private ArgumentBinder() { } public static void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { if (value instanceof InputStream) { bindInputStream(ps, index, (InputStream) value); } else if (value instanceof Reader) { bindReader(ps, index, (Reader) value); } else if (value instanceof Document) { bindXmlDocument(ps, index, (Document) value); } else if (value instanceof SqlArray) { bindArray(ps, index, (SqlArray) value); } else { ps.setObject(index, value); } } private static void bindInputStream(@NotNull PreparedStatement ps, int index, @NotNull InputStream stream) throws SQLException { // We check whether the InputStream is actually InputStreamWithSize, for two reasons: // 1) the database/driver can optimize the call better if it knows the size in advance // 2) calls without size were introduced in JDBC4 and not all drivers support them if (stream instanceof InputStreamWithSize) { InputStreamWithSize streamWithSize = (InputStreamWithSize) stream; long size = streamWithSize.getSize(); // The overload which takes 'long' as parameter was introduced in JDBC4 and is not // universally supported so we'll call the 'int' overload if possible. if (size <= Integer.MAX_VALUE) ps.setBinaryStream(index, streamWithSize, (int) size); else ps.setBinaryStream(index, streamWithSize, size); } else { ps.setBinaryStream(index, stream); } } private static void bindReader(@NotNull PreparedStatement ps, int index, @NotNull Reader reader) throws SQLException { // The structure followed bindInputStream, see the comments there.
// Path: dalesbred/src/main/java/org/dalesbred/datatype/InputStreamWithSize.java // public final class InputStreamWithSize extends FilterInputStream { // // private final long size; // // public InputStreamWithSize(@NotNull InputStream in, long size) { // super(in); // // if (size < 0) throw new IllegalArgumentException("negative size: " + size); // // this.size = size; // } // // public long getSize() { // return size; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/datatype/ReaderWithSize.java // public final class ReaderWithSize extends FilterReader { // // private final long size; // // public ReaderWithSize(@NotNull Reader reader, long size) { // super(reader); // // if (size < 0) throw new IllegalArgumentException("negative size: " + size); // // this.size = size; // } // // public long getSize() { // return size; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/datatype/SqlArray.java // public final class SqlArray { // // /** Database specific type name of the array */ // private final @NotNull String type; // // /** Values for the array */ // private final @NotNull List<?> values; // // private SqlArray(@NotNull String type, @NotNull Collection<?> values) { // this.type = requireNonNull(type); // this.values = unmodifiableList(new ArrayList<>(values)); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Collection<?> values) { // return new SqlArray(type, values); // } // // /** // * Constructs array of specified type. // * // * @param type database type for the array // * @param values for the array // */ // public static @NotNull SqlArray of(@NotNull String type, @NotNull Object[] values) { // return of(type, asList(values)); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull Collection<String> values) { // return of("varchar", values); // } // // /** // * Constructs varchar array of given values. // */ // public static @NotNull SqlArray varchars(@NotNull String... values) { // return varchars(asList(values)); // } // // /** // * Returns the database type for the array. // */ // public @NotNull String getType() { // return type; // } // // /** // * Returns the values of the array. // */ // public @NotNull List<?> getValues() { // return values; // } // // @Override // public String toString() { // return "SQLArray[type=" + type + ", values=" + values + ']'; // } // } // Path: dalesbred/src/main/java/org/dalesbred/internal/jdbc/ArgumentBinder.java import java.io.InputStream; import java.io.Reader; import java.sql.Array; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLXML; import org.dalesbred.datatype.InputStreamWithSize; import org.dalesbred.datatype.ReaderWithSize; import org.dalesbred.datatype.SqlArray; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.w3c.dom.Document; import javax.xml.transform.dom.DOMResult; /* * Copyright (c) 2015 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.jdbc; public final class ArgumentBinder { private ArgumentBinder() { } public static void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { if (value instanceof InputStream) { bindInputStream(ps, index, (InputStream) value); } else if (value instanceof Reader) { bindReader(ps, index, (Reader) value); } else if (value instanceof Document) { bindXmlDocument(ps, index, (Document) value); } else if (value instanceof SqlArray) { bindArray(ps, index, (SqlArray) value); } else { ps.setObject(index, value); } } private static void bindInputStream(@NotNull PreparedStatement ps, int index, @NotNull InputStream stream) throws SQLException { // We check whether the InputStream is actually InputStreamWithSize, for two reasons: // 1) the database/driver can optimize the call better if it knows the size in advance // 2) calls without size were introduced in JDBC4 and not all drivers support them if (stream instanceof InputStreamWithSize) { InputStreamWithSize streamWithSize = (InputStreamWithSize) stream; long size = streamWithSize.getSize(); // The overload which takes 'long' as parameter was introduced in JDBC4 and is not // universally supported so we'll call the 'int' overload if possible. if (size <= Integer.MAX_VALUE) ps.setBinaryStream(index, streamWithSize, (int) size); else ps.setBinaryStream(index, streamWithSize, size); } else { ps.setBinaryStream(index, stream); } } private static void bindReader(@NotNull PreparedStatement ps, int index, @NotNull Reader reader) throws SQLException { // The structure followed bindInputStream, see the comments there.
if (reader instanceof ReaderWithSize) {
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/integration/joda/JodaTypeConversions.java
// Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // }
import java.sql.Time; import java.sql.Timestamp; import org.dalesbred.conversion.TypeConversionRegistry; import org.jetbrains.annotations.NotNull; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import org.joda.time.LocalTime; import java.sql.Date;
/* * Copyright (c) 2015 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.integration.joda; /** * Conversions for Joda Time. These are automatically detected if Joda is found on * classpath, so the user doesn't need to do anything to get Joda-support. */ public final class JodaTypeConversions { private JodaTypeConversions() { } /** * Returns true if Joda is found on classpath. */ public static boolean hasJoda() { try { Class.forName("org.joda.time.LocalDate"); return true; } catch (ClassNotFoundException e) { return false; } }
// Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // } // Path: dalesbred/src/main/java/org/dalesbred/integration/joda/JodaTypeConversions.java import java.sql.Time; import java.sql.Timestamp; import org.dalesbred.conversion.TypeConversionRegistry; import org.jetbrains.annotations.NotNull; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import org.joda.time.LocalTime; import java.sql.Date; /* * Copyright (c) 2015 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.integration.joda; /** * Conversions for Joda Time. These are automatically detected if Joda is found on * classpath, so the user doesn't need to do anything to get Joda-support. */ public final class JodaTypeConversions { private JodaTypeConversions() { } /** * Returns true if Joda is found on classpath. */ public static boolean hasJoda() { try { Class.forName("org.joda.time.LocalDate"); return true; } catch (ClassNotFoundException e) { return false; } }
public static void register(@NotNull TypeConversionRegistry typeConversionRegistry) {
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/transaction/DefaultTransaction.java
// Path: dalesbred/src/main/java/org/dalesbred/dialect/Dialect.java // public abstract class Dialect { // // private static final String SERIALIZATION_FAILURE = "40001"; // // private static final Logger log = LoggerFactory.getLogger(Dialect.class); // // public @NotNull Object valueToDatabase(@NotNull Object value) { // return value; // } // // public @NotNull <T extends Enum<T>, K> TypeConversionPair<Object,T> createNativeEnumConversions(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction) { // throw new UnsupportedOperationException("native enums are not supported by " + getClass().getName()); // } // // @Override // public @NotNull String toString() { // return getClass().getName(); // } // // public static @NotNull Dialect detect(@NotNull DataSource dataSource) { // return detect(new DataSourceConnectionProvider(dataSource)); // } // // public static @NotNull Dialect detect(@NotNull TransactionManager transactionManager) { // return transactionManager.withTransaction(new TransactionSettings(), // tx -> detect(tx.getConnection()), new DefaultDialect()); // } // // public static @NotNull Dialect detect(@NotNull ConnectionProvider connectionProvider) { // try { // Connection connection = connectionProvider.getConnection(); // try { // return detect(connection); // } finally { // connectionProvider.releaseConnection(connection); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public static @NotNull Dialect detect(@NotNull Connection connection) { // try { // String productName = connection.getMetaData().getDatabaseProductName(); // // switch (productName) { // case "PostgreSQL": // log.debug("Automatically detected dialect PostgreSQL."); // return new PostgreSQLDialect(); // // case "HSQL Database Engine": // log.debug("Automatically detected dialect HSQLDB."); // return new HsqldbDialect(); // // case "H2": // log.debug("Automatically detected dialect H2."); // return new H2Dialect(); // // case "MySQL": // log.debug("Automatically detected dialect MySQL."); // return new MySQLDialect(); // // case "Oracle": // log.debug("Automatically detected dialect Oracle."); // return new OracleDialect(); // // case "Microsoft SQL Server": // log.debug("Automatically detected dialect SQLServer."); // return new SQLServerDialect(); // // default: // log.info("Could not detect dialect for product name '{}', falling back to default.", productName); // return new DefaultDialect(); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public @NotNull DatabaseException convertException(@NotNull SQLException e) { // String sqlState = e.getSQLState(); // if (sqlState == null) // return new DatabaseSQLException(e); // // if (sqlState.equals(SERIALIZATION_FAILURE)) // return new TransactionSerializationException(e); // else if (sqlState.startsWith("40")) // return new TransactionRollbackException(e); // else // return new DatabaseSQLException(e); // } // // public void registerTypeConversions(@NotNull TypeConversionRegistry typeConversionRegistry) { // // } // // /** // * Bind object to {@link PreparedStatement}. Can be overridden by subclasses to // * implement custom argument binding. // * // * @param ps statement to bind object to // * @param index index of the parameter // * @param value to bind // * @throws SQLException if something fails // */ // public void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { // ArgumentBinder.bindArgument(ps, index, value); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/Throwables.java // public final class Throwables { // // private Throwables() { } // // public static @NotNull RuntimeException propagate(@NotNull Throwable e) { // if (e instanceof Error) // throw (Error) e; // else if (e instanceof RuntimeException) // return (RuntimeException) e; // else // return new WrappedCheckedException(e); // } // // public static @NotNull <T extends Exception> T propagate(@NotNull Throwable e, @NotNull Class<T> allowed) { // if (allowed.isInstance(e)) // return allowed.cast(e); // else // throw propagate(e); // } // }
import java.sql.Savepoint; import static java.util.Objects.requireNonNull; import org.dalesbred.dialect.Dialect; import org.dalesbred.internal.utils.Throwables; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.SQLException;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.transaction; final class DefaultTransaction { private final @NotNull Connection connection; private static final @NotNull Logger log = LoggerFactory.getLogger(DefaultTransaction.class); DefaultTransaction(@NotNull Connection connection) { this.connection = requireNonNull(connection); }
// Path: dalesbred/src/main/java/org/dalesbred/dialect/Dialect.java // public abstract class Dialect { // // private static final String SERIALIZATION_FAILURE = "40001"; // // private static final Logger log = LoggerFactory.getLogger(Dialect.class); // // public @NotNull Object valueToDatabase(@NotNull Object value) { // return value; // } // // public @NotNull <T extends Enum<T>, K> TypeConversionPair<Object,T> createNativeEnumConversions(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction) { // throw new UnsupportedOperationException("native enums are not supported by " + getClass().getName()); // } // // @Override // public @NotNull String toString() { // return getClass().getName(); // } // // public static @NotNull Dialect detect(@NotNull DataSource dataSource) { // return detect(new DataSourceConnectionProvider(dataSource)); // } // // public static @NotNull Dialect detect(@NotNull TransactionManager transactionManager) { // return transactionManager.withTransaction(new TransactionSettings(), // tx -> detect(tx.getConnection()), new DefaultDialect()); // } // // public static @NotNull Dialect detect(@NotNull ConnectionProvider connectionProvider) { // try { // Connection connection = connectionProvider.getConnection(); // try { // return detect(connection); // } finally { // connectionProvider.releaseConnection(connection); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public static @NotNull Dialect detect(@NotNull Connection connection) { // try { // String productName = connection.getMetaData().getDatabaseProductName(); // // switch (productName) { // case "PostgreSQL": // log.debug("Automatically detected dialect PostgreSQL."); // return new PostgreSQLDialect(); // // case "HSQL Database Engine": // log.debug("Automatically detected dialect HSQLDB."); // return new HsqldbDialect(); // // case "H2": // log.debug("Automatically detected dialect H2."); // return new H2Dialect(); // // case "MySQL": // log.debug("Automatically detected dialect MySQL."); // return new MySQLDialect(); // // case "Oracle": // log.debug("Automatically detected dialect Oracle."); // return new OracleDialect(); // // case "Microsoft SQL Server": // log.debug("Automatically detected dialect SQLServer."); // return new SQLServerDialect(); // // default: // log.info("Could not detect dialect for product name '{}', falling back to default.", productName); // return new DefaultDialect(); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public @NotNull DatabaseException convertException(@NotNull SQLException e) { // String sqlState = e.getSQLState(); // if (sqlState == null) // return new DatabaseSQLException(e); // // if (sqlState.equals(SERIALIZATION_FAILURE)) // return new TransactionSerializationException(e); // else if (sqlState.startsWith("40")) // return new TransactionRollbackException(e); // else // return new DatabaseSQLException(e); // } // // public void registerTypeConversions(@NotNull TypeConversionRegistry typeConversionRegistry) { // // } // // /** // * Bind object to {@link PreparedStatement}. Can be overridden by subclasses to // * implement custom argument binding. // * // * @param ps statement to bind object to // * @param index index of the parameter // * @param value to bind // * @throws SQLException if something fails // */ // public void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { // ArgumentBinder.bindArgument(ps, index, value); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/Throwables.java // public final class Throwables { // // private Throwables() { } // // public static @NotNull RuntimeException propagate(@NotNull Throwable e) { // if (e instanceof Error) // throw (Error) e; // else if (e instanceof RuntimeException) // return (RuntimeException) e; // else // return new WrappedCheckedException(e); // } // // public static @NotNull <T extends Exception> T propagate(@NotNull Throwable e, @NotNull Class<T> allowed) { // if (allowed.isInstance(e)) // return allowed.cast(e); // else // throw propagate(e); // } // } // Path: dalesbred/src/main/java/org/dalesbred/transaction/DefaultTransaction.java import java.sql.Savepoint; import static java.util.Objects.requireNonNull; import org.dalesbred.dialect.Dialect; import org.dalesbred.internal.utils.Throwables; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.SQLException; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.transaction; final class DefaultTransaction { private final @NotNull Connection connection; private static final @NotNull Logger log = LoggerFactory.getLogger(DefaultTransaction.class); DefaultTransaction(@NotNull Connection connection) { this.connection = requireNonNull(connection); }
<T> T execute(@NotNull TransactionCallback<T> callback, @NotNull Dialect dialect) {
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/result/TableFormatter.java
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/StringUtils.java // public static @NotNull String rightPad(@NotNull String s, int length, char padding) { // if (s.length() >= length) return s; // // StringBuilder sb = new StringBuilder(length); // sb.append(s); // // for (int i = length - s.length(); i > 0; i--) // sb.append(padding); // // return sb.toString(); // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/StringUtils.java // public static @NotNull String truncate(@NotNull String s, int length) { // return truncate(s, length, "..."); // }
import static java.util.Collections.nCopies; import static java.util.stream.Collectors.toList; import static org.dalesbred.internal.utils.StringUtils.rightPad; import static org.dalesbred.internal.utils.StringUtils.truncate; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.UncheckedIOException; import java.util.List; import static java.lang.Math.max; import static java.lang.Math.min;
} static void write(@NotNull ResultTable table, @NotNull Appendable out) throws IOException { List<List<String>> formattedValues = format(table); int[] columnLengths = columnLengths(table.getColumnNames(), formattedValues); writeRow(out, table.getColumnNames(), columnLengths, ' '); writeRow(out, nCopies(table.getColumnCount(), ""), columnLengths, '-'); for (List<String> row : formattedValues) writeRow(out, row, columnLengths, ' '); } private static void writeRow(@NotNull Appendable out, @NotNull List<String> values, int[] columnLengths, char padding) throws IOException { assert values.size() == columnLengths.length; out.append('|'); for (int i = 0; i < columnLengths.length; i++) out.append(' ').append(formatCell(values.get(i), columnLengths[i], padding)).append(" |"); out.append('\n'); } private static @NotNull List<List<String>> format(@NotNull ResultTable table) { return table.getRows().stream() .map(it -> it.asList().stream().map(String::valueOf).collect(toList())) .collect(toList()); } private static @NotNull String formatCell(@NotNull String v, int length, char padding) {
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/StringUtils.java // public static @NotNull String rightPad(@NotNull String s, int length, char padding) { // if (s.length() >= length) return s; // // StringBuilder sb = new StringBuilder(length); // sb.append(s); // // for (int i = length - s.length(); i > 0; i--) // sb.append(padding); // // return sb.toString(); // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/StringUtils.java // public static @NotNull String truncate(@NotNull String s, int length) { // return truncate(s, length, "..."); // } // Path: dalesbred/src/main/java/org/dalesbred/result/TableFormatter.java import static java.util.Collections.nCopies; import static java.util.stream.Collectors.toList; import static org.dalesbred.internal.utils.StringUtils.rightPad; import static org.dalesbred.internal.utils.StringUtils.truncate; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.UncheckedIOException; import java.util.List; import static java.lang.Math.max; import static java.lang.Math.min; } static void write(@NotNull ResultTable table, @NotNull Appendable out) throws IOException { List<List<String>> formattedValues = format(table); int[] columnLengths = columnLengths(table.getColumnNames(), formattedValues); writeRow(out, table.getColumnNames(), columnLengths, ' '); writeRow(out, nCopies(table.getColumnCount(), ""), columnLengths, '-'); for (List<String> row : formattedValues) writeRow(out, row, columnLengths, ' '); } private static void writeRow(@NotNull Appendable out, @NotNull List<String> values, int[] columnLengths, char padding) throws IOException { assert values.size() == columnLengths.length; out.append('|'); for (int i = 0; i < columnLengths.length; i++) out.append(' ').append(formatCell(values.get(i), columnLengths[i], padding)).append(" |"); out.append('\n'); } private static @NotNull List<List<String>> format(@NotNull ResultTable table) { return table.getRows().stream() .map(it -> it.asList().stream().map(String::valueOf).collect(toList())) .collect(toList()); } private static @NotNull String formatCell(@NotNull String v, int length, char padding) {
return rightPad(truncate(v, length), length, padding);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/result/TableFormatter.java
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/StringUtils.java // public static @NotNull String rightPad(@NotNull String s, int length, char padding) { // if (s.length() >= length) return s; // // StringBuilder sb = new StringBuilder(length); // sb.append(s); // // for (int i = length - s.length(); i > 0; i--) // sb.append(padding); // // return sb.toString(); // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/StringUtils.java // public static @NotNull String truncate(@NotNull String s, int length) { // return truncate(s, length, "..."); // }
import static java.util.Collections.nCopies; import static java.util.stream.Collectors.toList; import static org.dalesbred.internal.utils.StringUtils.rightPad; import static org.dalesbred.internal.utils.StringUtils.truncate; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.UncheckedIOException; import java.util.List; import static java.lang.Math.max; import static java.lang.Math.min;
} static void write(@NotNull ResultTable table, @NotNull Appendable out) throws IOException { List<List<String>> formattedValues = format(table); int[] columnLengths = columnLengths(table.getColumnNames(), formattedValues); writeRow(out, table.getColumnNames(), columnLengths, ' '); writeRow(out, nCopies(table.getColumnCount(), ""), columnLengths, '-'); for (List<String> row : formattedValues) writeRow(out, row, columnLengths, ' '); } private static void writeRow(@NotNull Appendable out, @NotNull List<String> values, int[] columnLengths, char padding) throws IOException { assert values.size() == columnLengths.length; out.append('|'); for (int i = 0; i < columnLengths.length; i++) out.append(' ').append(formatCell(values.get(i), columnLengths[i], padding)).append(" |"); out.append('\n'); } private static @NotNull List<List<String>> format(@NotNull ResultTable table) { return table.getRows().stream() .map(it -> it.asList().stream().map(String::valueOf).collect(toList())) .collect(toList()); } private static @NotNull String formatCell(@NotNull String v, int length, char padding) {
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/StringUtils.java // public static @NotNull String rightPad(@NotNull String s, int length, char padding) { // if (s.length() >= length) return s; // // StringBuilder sb = new StringBuilder(length); // sb.append(s); // // for (int i = length - s.length(); i > 0; i--) // sb.append(padding); // // return sb.toString(); // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/StringUtils.java // public static @NotNull String truncate(@NotNull String s, int length) { // return truncate(s, length, "..."); // } // Path: dalesbred/src/main/java/org/dalesbred/result/TableFormatter.java import static java.util.Collections.nCopies; import static java.util.stream.Collectors.toList; import static org.dalesbred.internal.utils.StringUtils.rightPad; import static org.dalesbred.internal.utils.StringUtils.truncate; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.UncheckedIOException; import java.util.List; import static java.lang.Math.max; import static java.lang.Math.min; } static void write(@NotNull ResultTable table, @NotNull Appendable out) throws IOException { List<List<String>> formattedValues = format(table); int[] columnLengths = columnLengths(table.getColumnNames(), formattedValues); writeRow(out, table.getColumnNames(), columnLengths, ' '); writeRow(out, nCopies(table.getColumnCount(), ""), columnLengths, '-'); for (List<String> row : formattedValues) writeRow(out, row, columnLengths, ' '); } private static void writeRow(@NotNull Appendable out, @NotNull List<String> values, int[] columnLengths, char padding) throws IOException { assert values.size() == columnLengths.length; out.append('|'); for (int i = 0; i < columnLengths.length; i++) out.append(' ').append(formatCell(values.get(i), columnLengths[i], padding)).append(" |"); out.append('\n'); } private static @NotNull List<List<String>> format(@NotNull ResultTable table) { return table.getRows().stream() .map(it -> it.asList().stream().map(String::valueOf).collect(toList())) .collect(toList()); } private static @NotNull String formatCell(@NotNull String v, int length, char padding) {
return rightPad(truncate(v, length), length, padding);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/instantiation/SqlArrayConversion.java
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseSQLException.java // public class DatabaseSQLException extends DatabaseException { // // public DatabaseSQLException(@NotNull String message, @NotNull SQLException cause) { // super(message, cause); // } // // public DatabaseSQLException(@NotNull SQLException cause) { // super(cause); // } // // @Override // public synchronized @NotNull SQLException getCause() { // return (SQLException) super.getCause(); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/jdbc/ResultSetUtils.java // public final class ResultSetUtils { // // private ResultSetUtils() { } // // public static @NotNull NamedTypeList getTypes(@NotNull ResultSetMetaData metaData) throws SQLException { // int columns = metaData.getColumnCount(); // // NamedTypeList.Builder result = NamedTypeList.builder(columns); // // for (int i = 0; i < columns; i++) // result.add(metaData.getColumnLabel(i+1), getColumnType(metaData, i + 1)); // // return result.build(); // } // // public static @NotNull Type getColumnType(@NotNull ResultSetMetaData metaData, int column) throws SQLException { // String className = metaData.getColumnClassName(column); // try { // return Class.forName(className); // } catch (ClassNotFoundException e) { // throw new DatabaseException("Could not find class '" + className + "' specified by ResultSet.", e); // } // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/jdbc/SqlUtils.java // public final class SqlUtils { // // private SqlUtils() { } // // public static void freeArray(@NotNull Array array) throws SQLException { // try { // array.free(); // } catch (SQLFeatureNotSupportedException ignored) { // } // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/TypeUtils.java // public final class TypeUtils { // // private TypeUtils() { } // // public static @NotNull Class<?> rawType(@NotNull Type type) { // if (type instanceof Class<?>) { // return (Class<?>) type; // // } else if (type instanceof ParameterizedType) { // return rawType(((ParameterizedType) type).getRawType()); // // } else if (type instanceof TypeVariable<?>) { // // We could return one of the bounds, but it won't work if there are multiple bounds. // // Therefore just return object. // return Object.class; // // } else if (type instanceof WildcardType) { // return rawType(((WildcardType) type).getUpperBounds()[0]); // // } else if (type instanceof GenericArrayType) { // return arrayType(rawType(((GenericArrayType) type).getGenericComponentType())); // // } else { // throw new IllegalArgumentException("unexpected type: " + type); // } // } // // public static @NotNull Type typeParameter(@NotNull Type type) { // if (type instanceof ParameterizedType) // return ((ParameterizedType) type).getActualTypeArguments()[0]; // // return Object.class; // } // // public static boolean isEnum(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isEnum(); // } // // public static boolean isPrimitive(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isPrimitive(); // } // // public static @NotNull Class<?> arrayType(@NotNull Class<?> type) { // return Array.newInstance(type, 0).getClass(); // } // // public static @Nullable Type genericSuperClass(@NotNull Type type) { // return rawType(type).getGenericSuperclass(); // } // // public static @NotNull Type[] genericInterfaces(@NotNull Type type) { // return rawType(type).getGenericInterfaces(); // } // // public static boolean isAssignable(@NotNull Type target, @NotNull Type source) { // // TODO: implement proper rules for generic types // return isAssignableByBoxing(rawType(target), rawType(source)); // } // // private static boolean isAssignableByBoxing(@NotNull Class<?> target, @NotNull Class<?> source) { // return Primitives.wrap(target).isAssignableFrom(Primitives.wrap(source)); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/result/UnexpectedResultException.java // public class UnexpectedResultException extends DatabaseException { // public UnexpectedResultException(@NotNull String message) { // super(message); // } // }
import java.sql.Array; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import org.dalesbred.DatabaseSQLException; import org.dalesbred.internal.jdbc.ResultSetUtils; import org.dalesbred.internal.jdbc.SqlUtils; import org.dalesbred.internal.utils.TypeUtils; import org.dalesbred.result.UnexpectedResultException; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Type;
NamedTypeList types = NamedTypeList.builder(1).add("value", ResultSetUtils.getColumnType(resultSet.getMetaData(), 2)).build(); Instantiator<?> ctor = instantiatorRegistry.findInstantiator(elementType, types); ArrayList<Object> result = new ArrayList<>(); // For performance reasons we reuse the same arguments-array and InstantiatorArguments-object for all rows. // This should be fine as long as the instantiators don't hang on to their arguments for too long. Object[] arguments = new Object[1]; InstantiatorArguments instantiatorArguments = new InstantiatorArguments(types, arguments); while (resultSet.next()) { arguments[0] = resultSet.getObject(2); Object value = ctor.instantiate(instantiatorArguments); if (value != null || allowNulls) result.add(value); else throw new UnexpectedResultException("Expected " + elementType + ", but got null"); } return result; } finally { try { resultSet.close(); } finally { SqlUtils.freeArray(array); } } } catch (SQLException e) {
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseSQLException.java // public class DatabaseSQLException extends DatabaseException { // // public DatabaseSQLException(@NotNull String message, @NotNull SQLException cause) { // super(message, cause); // } // // public DatabaseSQLException(@NotNull SQLException cause) { // super(cause); // } // // @Override // public synchronized @NotNull SQLException getCause() { // return (SQLException) super.getCause(); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/jdbc/ResultSetUtils.java // public final class ResultSetUtils { // // private ResultSetUtils() { } // // public static @NotNull NamedTypeList getTypes(@NotNull ResultSetMetaData metaData) throws SQLException { // int columns = metaData.getColumnCount(); // // NamedTypeList.Builder result = NamedTypeList.builder(columns); // // for (int i = 0; i < columns; i++) // result.add(metaData.getColumnLabel(i+1), getColumnType(metaData, i + 1)); // // return result.build(); // } // // public static @NotNull Type getColumnType(@NotNull ResultSetMetaData metaData, int column) throws SQLException { // String className = metaData.getColumnClassName(column); // try { // return Class.forName(className); // } catch (ClassNotFoundException e) { // throw new DatabaseException("Could not find class '" + className + "' specified by ResultSet.", e); // } // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/jdbc/SqlUtils.java // public final class SqlUtils { // // private SqlUtils() { } // // public static void freeArray(@NotNull Array array) throws SQLException { // try { // array.free(); // } catch (SQLFeatureNotSupportedException ignored) { // } // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/TypeUtils.java // public final class TypeUtils { // // private TypeUtils() { } // // public static @NotNull Class<?> rawType(@NotNull Type type) { // if (type instanceof Class<?>) { // return (Class<?>) type; // // } else if (type instanceof ParameterizedType) { // return rawType(((ParameterizedType) type).getRawType()); // // } else if (type instanceof TypeVariable<?>) { // // We could return one of the bounds, but it won't work if there are multiple bounds. // // Therefore just return object. // return Object.class; // // } else if (type instanceof WildcardType) { // return rawType(((WildcardType) type).getUpperBounds()[0]); // // } else if (type instanceof GenericArrayType) { // return arrayType(rawType(((GenericArrayType) type).getGenericComponentType())); // // } else { // throw new IllegalArgumentException("unexpected type: " + type); // } // } // // public static @NotNull Type typeParameter(@NotNull Type type) { // if (type instanceof ParameterizedType) // return ((ParameterizedType) type).getActualTypeArguments()[0]; // // return Object.class; // } // // public static boolean isEnum(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isEnum(); // } // // public static boolean isPrimitive(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isPrimitive(); // } // // public static @NotNull Class<?> arrayType(@NotNull Class<?> type) { // return Array.newInstance(type, 0).getClass(); // } // // public static @Nullable Type genericSuperClass(@NotNull Type type) { // return rawType(type).getGenericSuperclass(); // } // // public static @NotNull Type[] genericInterfaces(@NotNull Type type) { // return rawType(type).getGenericInterfaces(); // } // // public static boolean isAssignable(@NotNull Type target, @NotNull Type source) { // // TODO: implement proper rules for generic types // return isAssignableByBoxing(rawType(target), rawType(source)); // } // // private static boolean isAssignableByBoxing(@NotNull Class<?> target, @NotNull Class<?> source) { // return Primitives.wrap(target).isAssignableFrom(Primitives.wrap(source)); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/result/UnexpectedResultException.java // public class UnexpectedResultException extends DatabaseException { // public UnexpectedResultException(@NotNull String message) { // super(message); // } // } // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/SqlArrayConversion.java import java.sql.Array; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import org.dalesbred.DatabaseSQLException; import org.dalesbred.internal.jdbc.ResultSetUtils; import org.dalesbred.internal.jdbc.SqlUtils; import org.dalesbred.internal.utils.TypeUtils; import org.dalesbred.result.UnexpectedResultException; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Type; NamedTypeList types = NamedTypeList.builder(1).add("value", ResultSetUtils.getColumnType(resultSet.getMetaData(), 2)).build(); Instantiator<?> ctor = instantiatorRegistry.findInstantiator(elementType, types); ArrayList<Object> result = new ArrayList<>(); // For performance reasons we reuse the same arguments-array and InstantiatorArguments-object for all rows. // This should be fine as long as the instantiators don't hang on to their arguments for too long. Object[] arguments = new Object[1]; InstantiatorArguments instantiatorArguments = new InstantiatorArguments(types, arguments); while (resultSet.next()) { arguments[0] = resultSet.getObject(2); Object value = ctor.instantiate(instantiatorArguments); if (value != null || allowNulls) result.add(value); else throw new UnexpectedResultException("Expected " + elementType + ", but got null"); } return result; } finally { try { resultSet.close(); } finally { SqlUtils.freeArray(array); } } } catch (SQLException e) {
throw new DatabaseSQLException(e);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/instantiation/ReflectionInstantiator.java
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/Throwables.java // public final class Throwables { // // private Throwables() { } // // public static @NotNull RuntimeException propagate(@NotNull Throwable e) { // if (e instanceof Error) // throw (Error) e; // else if (e instanceof RuntimeException) // return (RuntimeException) e; // else // return new WrappedCheckedException(e); // } // // public static @NotNull <T extends Exception> T propagate(@NotNull Throwable e, @NotNull Class<T> allowed) { // if (allowed.isInstance(e)) // return allowed.cast(e); // else // throw propagate(e); // } // }
import static java.util.Objects.requireNonNull; import org.dalesbred.internal.utils.Throwables; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Constructor; import java.lang.reflect.Executable; import java.lang.reflect.Method; import java.util.List;
ReflectionInstantiator(@NotNull Executable instantiator, @NotNull List<TypeConversion> conversions, @NotNull List<PropertyAccessor> accessors) { this.instantiator = requireNonNull(instantiator); this.conversions = requireNonNull(conversions); this.accessors = requireNonNull(accessors); this.parameterCount = instantiator.getParameterTypes().length; } @Override public @NotNull T instantiate(@NotNull InstantiatorArguments arguments) { try { Object[] argumentArray = toArgumentArray(arguments.getValues()); Object v; if (instantiator instanceof Constructor<?>) { v = ((Constructor<?>) instantiator).newInstance(argumentArray); } else if (instantiator instanceof Method) { v = ((Method) instantiator).invoke(null, argumentArray); } else { throw new IllegalStateException("Unexpected instantiator: " + instantiator); } @SuppressWarnings("unchecked") T value = (T) v; bindRemainingProperties(value, arguments); return value; } catch (Exception e) {
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/Throwables.java // public final class Throwables { // // private Throwables() { } // // public static @NotNull RuntimeException propagate(@NotNull Throwable e) { // if (e instanceof Error) // throw (Error) e; // else if (e instanceof RuntimeException) // return (RuntimeException) e; // else // return new WrappedCheckedException(e); // } // // public static @NotNull <T extends Exception> T propagate(@NotNull Throwable e, @NotNull Class<T> allowed) { // if (allowed.isInstance(e)) // return allowed.cast(e); // else // throw propagate(e); // } // } // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/ReflectionInstantiator.java import static java.util.Objects.requireNonNull; import org.dalesbred.internal.utils.Throwables; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Constructor; import java.lang.reflect.Executable; import java.lang.reflect.Method; import java.util.List; ReflectionInstantiator(@NotNull Executable instantiator, @NotNull List<TypeConversion> conversions, @NotNull List<PropertyAccessor> accessors) { this.instantiator = requireNonNull(instantiator); this.conversions = requireNonNull(conversions); this.accessors = requireNonNull(accessors); this.parameterCount = instantiator.getParameterTypes().length; } @Override public @NotNull T instantiate(@NotNull InstantiatorArguments arguments) { try { Object[] argumentArray = toArgumentArray(arguments.getValues()); Object v; if (instantiator instanceof Constructor<?>) { v = ((Constructor<?>) instantiator).newInstance(argumentArray); } else if (instantiator instanceof Method) { v = ((Method) instantiator).invoke(null, argumentArray); } else { throw new IllegalStateException("Unexpected instantiator: " + instantiator); } @SuppressWarnings("unchecked") T value = (T) v; bindRemainingProperties(value, arguments); return value; } catch (Exception e) {
throw Throwables.propagate(e);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/instantiation/PropertyAccessor.java
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/Throwables.java // public final class Throwables { // // private Throwables() { } // // public static @NotNull RuntimeException propagate(@NotNull Throwable e) { // if (e instanceof Error) // throw (Error) e; // else if (e instanceof RuntimeException) // return (RuntimeException) e; // else // return new WrappedCheckedException(e); // } // // public static @NotNull <T extends Exception> T propagate(@NotNull Throwable e, @NotNull Class<T> allowed) { // if (allowed.isInstance(e)) // return allowed.cast(e); // else // throw propagate(e); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/StringUtils.java // public static boolean isEqualIgnoringCaseAndUnderscores(@NotNull String s1, @NotNull String s2) { // int index1 = 0; // int index2 = 0; // int length1 = s1.length(); // int length2 = s2.length(); // // while (index1 < length1 && index2 < length2) { // char nameChar = s1.charAt(index1++); // if (nameChar == '_') continue; // // char memberNameChar = s2.charAt(index2++); // if (memberNameChar == '_') { // index1--; // continue; // } // // if (toLowerCase(nameChar) != toLowerCase(memberNameChar)) // return false; // } // // // Skip trailing underscores // while (index1 < length1 && s1.charAt(index1) == '_') index1++; // while (index2 < length2 && s2.charAt(index2) == '_') index2++; // // return index1 == length1 && index2 == length2; // }
import java.lang.reflect.Type; import java.util.Optional; import java.util.regex.Pattern; import static java.lang.reflect.Modifier.isPublic; import static org.dalesbred.internal.utils.StringUtils.isEqualIgnoringCaseAndUnderscores; import org.dalesbred.annotation.DalesbredIgnore; import org.dalesbred.internal.utils.Throwables; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
currentClass = field.getType(); } else { Method getter = findGetter(currentClass, segments[i]).orElse(null); if (getter != null) { readers[i] = getter::invoke; currentClass = getter.getReturnType(); } else { return Optional.empty(); } } } Optional<PropertyAccessor> accessor = findFinalAccessor(currentClass, segments[segments.length - 1]); return accessor.map(a -> new NestedPathAccessor(readers, path, a)); } private static @NotNull Optional<PropertyAccessor> findFinalAccessor(@NotNull Class<?> currentClass, @NotNull String name) { Optional<PropertyAccessor> setter = findSetter(currentClass, name).map(SetterPropertyAccessor::new); if (setter.isPresent()) { return setter; } else { return findField(currentClass, name).map(FieldPropertyAccessor::new); } } private static @NotNull Optional<Field> findField(@NotNull Class<?> cl, @NotNull String name) { Field result = null; for (Field field : cl.getFields())
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/Throwables.java // public final class Throwables { // // private Throwables() { } // // public static @NotNull RuntimeException propagate(@NotNull Throwable e) { // if (e instanceof Error) // throw (Error) e; // else if (e instanceof RuntimeException) // return (RuntimeException) e; // else // return new WrappedCheckedException(e); // } // // public static @NotNull <T extends Exception> T propagate(@NotNull Throwable e, @NotNull Class<T> allowed) { // if (allowed.isInstance(e)) // return allowed.cast(e); // else // throw propagate(e); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/StringUtils.java // public static boolean isEqualIgnoringCaseAndUnderscores(@NotNull String s1, @NotNull String s2) { // int index1 = 0; // int index2 = 0; // int length1 = s1.length(); // int length2 = s2.length(); // // while (index1 < length1 && index2 < length2) { // char nameChar = s1.charAt(index1++); // if (nameChar == '_') continue; // // char memberNameChar = s2.charAt(index2++); // if (memberNameChar == '_') { // index1--; // continue; // } // // if (toLowerCase(nameChar) != toLowerCase(memberNameChar)) // return false; // } // // // Skip trailing underscores // while (index1 < length1 && s1.charAt(index1) == '_') index1++; // while (index2 < length2 && s2.charAt(index2) == '_') index2++; // // return index1 == length1 && index2 == length2; // } // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/PropertyAccessor.java import java.lang.reflect.Type; import java.util.Optional; import java.util.regex.Pattern; import static java.lang.reflect.Modifier.isPublic; import static org.dalesbred.internal.utils.StringUtils.isEqualIgnoringCaseAndUnderscores; import org.dalesbred.annotation.DalesbredIgnore; import org.dalesbred.internal.utils.Throwables; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; currentClass = field.getType(); } else { Method getter = findGetter(currentClass, segments[i]).orElse(null); if (getter != null) { readers[i] = getter::invoke; currentClass = getter.getReturnType(); } else { return Optional.empty(); } } } Optional<PropertyAccessor> accessor = findFinalAccessor(currentClass, segments[segments.length - 1]); return accessor.map(a -> new NestedPathAccessor(readers, path, a)); } private static @NotNull Optional<PropertyAccessor> findFinalAccessor(@NotNull Class<?> currentClass, @NotNull String name) { Optional<PropertyAccessor> setter = findSetter(currentClass, name).map(SetterPropertyAccessor::new); if (setter.isPresent()) { return setter; } else { return findField(currentClass, name).map(FieldPropertyAccessor::new); } } private static @NotNull Optional<Field> findField(@NotNull Class<?> cl, @NotNull String name) { Field result = null; for (Field field : cl.getFields())
if (isPublic(field.getModifiers()) && isEqualIgnoringCaseAndUnderscores(name, field.getName()) && !field.isAnnotationPresent(DalesbredIgnore.class)) {
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/instantiation/PropertyAccessor.java
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/Throwables.java // public final class Throwables { // // private Throwables() { } // // public static @NotNull RuntimeException propagate(@NotNull Throwable e) { // if (e instanceof Error) // throw (Error) e; // else if (e instanceof RuntimeException) // return (RuntimeException) e; // else // return new WrappedCheckedException(e); // } // // public static @NotNull <T extends Exception> T propagate(@NotNull Throwable e, @NotNull Class<T> allowed) { // if (allowed.isInstance(e)) // return allowed.cast(e); // else // throw propagate(e); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/StringUtils.java // public static boolean isEqualIgnoringCaseAndUnderscores(@NotNull String s1, @NotNull String s2) { // int index1 = 0; // int index2 = 0; // int length1 = s1.length(); // int length2 = s2.length(); // // while (index1 < length1 && index2 < length2) { // char nameChar = s1.charAt(index1++); // if (nameChar == '_') continue; // // char memberNameChar = s2.charAt(index2++); // if (memberNameChar == '_') { // index1--; // continue; // } // // if (toLowerCase(nameChar) != toLowerCase(memberNameChar)) // return false; // } // // // Skip trailing underscores // while (index1 < length1 && s1.charAt(index1) == '_') index1++; // while (index2 < length2 && s2.charAt(index2) == '_') index2++; // // return index1 == length1 && index2 == length2; // }
import java.lang.reflect.Type; import java.util.Optional; import java.util.regex.Pattern; import static java.lang.reflect.Modifier.isPublic; import static org.dalesbred.internal.utils.StringUtils.isEqualIgnoringCaseAndUnderscores; import org.dalesbred.annotation.DalesbredIgnore; import org.dalesbred.internal.utils.Throwables; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
throw new InstantiationFailureException("Conflicting accessors for property: " + result + " - " + propertyName); result = method; } } return Optional.ofNullable(result); } public static @NotNull Optional<Type> findPropertyType(@NotNull Class<?> cl, @NotNull String name) { return findAccessor(cl, name).map(PropertyAccessor::getType); } private static final class FieldPropertyAccessor extends PropertyAccessor { private final @NotNull Field field; private FieldPropertyAccessor(@NotNull Field field) { this.field = field; } @Override Type getType() { return field.getGenericType(); } @Override void set(@NotNull Object object, Object value) { try { field.set(object, value); } catch (IllegalAccessException e) {
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/Throwables.java // public final class Throwables { // // private Throwables() { } // // public static @NotNull RuntimeException propagate(@NotNull Throwable e) { // if (e instanceof Error) // throw (Error) e; // else if (e instanceof RuntimeException) // return (RuntimeException) e; // else // return new WrappedCheckedException(e); // } // // public static @NotNull <T extends Exception> T propagate(@NotNull Throwable e, @NotNull Class<T> allowed) { // if (allowed.isInstance(e)) // return allowed.cast(e); // else // throw propagate(e); // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/StringUtils.java // public static boolean isEqualIgnoringCaseAndUnderscores(@NotNull String s1, @NotNull String s2) { // int index1 = 0; // int index2 = 0; // int length1 = s1.length(); // int length2 = s2.length(); // // while (index1 < length1 && index2 < length2) { // char nameChar = s1.charAt(index1++); // if (nameChar == '_') continue; // // char memberNameChar = s2.charAt(index2++); // if (memberNameChar == '_') { // index1--; // continue; // } // // if (toLowerCase(nameChar) != toLowerCase(memberNameChar)) // return false; // } // // // Skip trailing underscores // while (index1 < length1 && s1.charAt(index1) == '_') index1++; // while (index2 < length2 && s2.charAt(index2) == '_') index2++; // // return index1 == length1 && index2 == length2; // } // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/PropertyAccessor.java import java.lang.reflect.Type; import java.util.Optional; import java.util.regex.Pattern; import static java.lang.reflect.Modifier.isPublic; import static org.dalesbred.internal.utils.StringUtils.isEqualIgnoringCaseAndUnderscores; import org.dalesbred.annotation.DalesbredIgnore; import org.dalesbred.internal.utils.Throwables; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; throw new InstantiationFailureException("Conflicting accessors for property: " + result + " - " + propertyName); result = method; } } return Optional.ofNullable(result); } public static @NotNull Optional<Type> findPropertyType(@NotNull Class<?> cl, @NotNull String name) { return findAccessor(cl, name).map(PropertyAccessor::getType); } private static final class FieldPropertyAccessor extends PropertyAccessor { private final @NotNull Field field; private FieldPropertyAccessor(@NotNull Field field) { this.field = field; } @Override Type getType() { return field.getGenericType(); } @Override void set(@NotNull Object object, Object value) { try { field.set(object, value); } catch (IllegalAccessException e) {
throw Throwables.propagate(e);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/transaction/AbstractTransactionManager.java
// Path: dalesbred/src/main/java/org/dalesbred/dialect/Dialect.java // public abstract class Dialect { // // private static final String SERIALIZATION_FAILURE = "40001"; // // private static final Logger log = LoggerFactory.getLogger(Dialect.class); // // public @NotNull Object valueToDatabase(@NotNull Object value) { // return value; // } // // public @NotNull <T extends Enum<T>, K> TypeConversionPair<Object,T> createNativeEnumConversions(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction) { // throw new UnsupportedOperationException("native enums are not supported by " + getClass().getName()); // } // // @Override // public @NotNull String toString() { // return getClass().getName(); // } // // public static @NotNull Dialect detect(@NotNull DataSource dataSource) { // return detect(new DataSourceConnectionProvider(dataSource)); // } // // public static @NotNull Dialect detect(@NotNull TransactionManager transactionManager) { // return transactionManager.withTransaction(new TransactionSettings(), // tx -> detect(tx.getConnection()), new DefaultDialect()); // } // // public static @NotNull Dialect detect(@NotNull ConnectionProvider connectionProvider) { // try { // Connection connection = connectionProvider.getConnection(); // try { // return detect(connection); // } finally { // connectionProvider.releaseConnection(connection); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public static @NotNull Dialect detect(@NotNull Connection connection) { // try { // String productName = connection.getMetaData().getDatabaseProductName(); // // switch (productName) { // case "PostgreSQL": // log.debug("Automatically detected dialect PostgreSQL."); // return new PostgreSQLDialect(); // // case "HSQL Database Engine": // log.debug("Automatically detected dialect HSQLDB."); // return new HsqldbDialect(); // // case "H2": // log.debug("Automatically detected dialect H2."); // return new H2Dialect(); // // case "MySQL": // log.debug("Automatically detected dialect MySQL."); // return new MySQLDialect(); // // case "Oracle": // log.debug("Automatically detected dialect Oracle."); // return new OracleDialect(); // // case "Microsoft SQL Server": // log.debug("Automatically detected dialect SQLServer."); // return new SQLServerDialect(); // // default: // log.info("Could not detect dialect for product name '{}', falling back to default.", productName); // return new DefaultDialect(); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public @NotNull DatabaseException convertException(@NotNull SQLException e) { // String sqlState = e.getSQLState(); // if (sqlState == null) // return new DatabaseSQLException(e); // // if (sqlState.equals(SERIALIZATION_FAILURE)) // return new TransactionSerializationException(e); // else if (sqlState.startsWith("40")) // return new TransactionRollbackException(e); // else // return new DatabaseSQLException(e); // } // // public void registerTypeConversions(@NotNull TypeConversionRegistry typeConversionRegistry) { // // } // // /** // * Bind object to {@link PreparedStatement}. Can be overridden by subclasses to // * implement custom argument binding. // * // * @param ps statement to bind object to // * @param index index of the parameter // * @param value to bind // * @throws SQLException if something fails // */ // public void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { // ArgumentBinder.bindArgument(ps, index, value); // } // }
import org.dalesbred.dialect.Dialect; import org.jetbrains.annotations.NotNull; import java.util.Optional;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.transaction; public abstract class AbstractTransactionManager implements TransactionManager { protected abstract @NotNull Optional<DefaultTransaction> getActiveTransaction(); protected abstract <T> T withNewTransaction(@NotNull TransactionCallback<T> callback,
// Path: dalesbred/src/main/java/org/dalesbred/dialect/Dialect.java // public abstract class Dialect { // // private static final String SERIALIZATION_FAILURE = "40001"; // // private static final Logger log = LoggerFactory.getLogger(Dialect.class); // // public @NotNull Object valueToDatabase(@NotNull Object value) { // return value; // } // // public @NotNull <T extends Enum<T>, K> TypeConversionPair<Object,T> createNativeEnumConversions(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction) { // throw new UnsupportedOperationException("native enums are not supported by " + getClass().getName()); // } // // @Override // public @NotNull String toString() { // return getClass().getName(); // } // // public static @NotNull Dialect detect(@NotNull DataSource dataSource) { // return detect(new DataSourceConnectionProvider(dataSource)); // } // // public static @NotNull Dialect detect(@NotNull TransactionManager transactionManager) { // return transactionManager.withTransaction(new TransactionSettings(), // tx -> detect(tx.getConnection()), new DefaultDialect()); // } // // public static @NotNull Dialect detect(@NotNull ConnectionProvider connectionProvider) { // try { // Connection connection = connectionProvider.getConnection(); // try { // return detect(connection); // } finally { // connectionProvider.releaseConnection(connection); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public static @NotNull Dialect detect(@NotNull Connection connection) { // try { // String productName = connection.getMetaData().getDatabaseProductName(); // // switch (productName) { // case "PostgreSQL": // log.debug("Automatically detected dialect PostgreSQL."); // return new PostgreSQLDialect(); // // case "HSQL Database Engine": // log.debug("Automatically detected dialect HSQLDB."); // return new HsqldbDialect(); // // case "H2": // log.debug("Automatically detected dialect H2."); // return new H2Dialect(); // // case "MySQL": // log.debug("Automatically detected dialect MySQL."); // return new MySQLDialect(); // // case "Oracle": // log.debug("Automatically detected dialect Oracle."); // return new OracleDialect(); // // case "Microsoft SQL Server": // log.debug("Automatically detected dialect SQLServer."); // return new SQLServerDialect(); // // default: // log.info("Could not detect dialect for product name '{}', falling back to default.", productName); // return new DefaultDialect(); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public @NotNull DatabaseException convertException(@NotNull SQLException e) { // String sqlState = e.getSQLState(); // if (sqlState == null) // return new DatabaseSQLException(e); // // if (sqlState.equals(SERIALIZATION_FAILURE)) // return new TransactionSerializationException(e); // else if (sqlState.startsWith("40")) // return new TransactionRollbackException(e); // else // return new DatabaseSQLException(e); // } // // public void registerTypeConversions(@NotNull TypeConversionRegistry typeConversionRegistry) { // // } // // /** // * Bind object to {@link PreparedStatement}. Can be overridden by subclasses to // * implement custom argument binding. // * // * @param ps statement to bind object to // * @param index index of the parameter // * @param value to bind // * @throws SQLException if something fails // */ // public void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { // ArgumentBinder.bindArgument(ps, index, value); // } // } // Path: dalesbred/src/main/java/org/dalesbred/transaction/AbstractTransactionManager.java import org.dalesbred.dialect.Dialect; import org.jetbrains.annotations.NotNull; import java.util.Optional; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.transaction; public abstract class AbstractTransactionManager implements TransactionManager { protected abstract @NotNull Optional<DefaultTransaction> getActiveTransaction(); protected abstract <T> T withNewTransaction(@NotNull TransactionCallback<T> callback,
@NotNull Dialect dialect,
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/dialect/PostgreSQLDialect.java
// Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionPair.java // public interface TypeConversionPair<D,J> { // D convertToDatabase(J obj); // J convertFromDatabase(D obj); // } // // Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/EnumUtils.java // public final class EnumUtils { // // private EnumUtils() { } // // public static @NotNull <T extends Enum<T>> T enumByOrdinal(@NotNull Class<T> enumType, int ordinal) { // Enum<?>[] constants = enumType.getEnumConstants(); // if (ordinal >= 0 && ordinal < constants.length) // return enumType.cast(constants[ordinal]); // else // throw new DatabaseException("invalid ordinal " + ordinal + " for enum type " + enumType.getName()); // } // // public static @NotNull <T extends Enum<T>,K> T enumByKey(@NotNull Class<T> enumType, @NotNull Function<T, K> keyFunction, @NotNull K key) { // for (T enumConstant : enumType.getEnumConstants()) // if (Objects.equals(key, keyFunction.apply(enumConstant))) // return enumConstant; // // throw new InstantiationFailureException("could not find enum constant of type " + enumType.getName() + " for " + key); // } // }
import java.util.Date; import java.util.function.Function; import org.dalesbred.conversion.TypeConversionPair; import org.dalesbred.conversion.TypeConversionRegistry; import org.dalesbred.internal.utils.EnumUtils; import org.jetbrains.annotations.NotNull; import org.postgresql.util.PGobject; import java.sql.SQLException; import java.sql.Timestamp;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.dialect; /** * Support for PostgreSQL. */ public class PostgreSQLDialect extends Dialect { @Override
// Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionPair.java // public interface TypeConversionPair<D,J> { // D convertToDatabase(J obj); // J convertFromDatabase(D obj); // } // // Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/EnumUtils.java // public final class EnumUtils { // // private EnumUtils() { } // // public static @NotNull <T extends Enum<T>> T enumByOrdinal(@NotNull Class<T> enumType, int ordinal) { // Enum<?>[] constants = enumType.getEnumConstants(); // if (ordinal >= 0 && ordinal < constants.length) // return enumType.cast(constants[ordinal]); // else // throw new DatabaseException("invalid ordinal " + ordinal + " for enum type " + enumType.getName()); // } // // public static @NotNull <T extends Enum<T>,K> T enumByKey(@NotNull Class<T> enumType, @NotNull Function<T, K> keyFunction, @NotNull K key) { // for (T enumConstant : enumType.getEnumConstants()) // if (Objects.equals(key, keyFunction.apply(enumConstant))) // return enumConstant; // // throw new InstantiationFailureException("could not find enum constant of type " + enumType.getName() + " for " + key); // } // } // Path: dalesbred/src/main/java/org/dalesbred/dialect/PostgreSQLDialect.java import java.util.Date; import java.util.function.Function; import org.dalesbred.conversion.TypeConversionPair; import org.dalesbred.conversion.TypeConversionRegistry; import org.dalesbred.internal.utils.EnumUtils; import org.jetbrains.annotations.NotNull; import org.postgresql.util.PGobject; import java.sql.SQLException; import java.sql.Timestamp; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.dialect; /** * Support for PostgreSQL. */ public class PostgreSQLDialect extends Dialect { @Override
public @NotNull <T extends Enum<T>, K> TypeConversionPair<Object,T> createNativeEnumConversions(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction) {
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/dialect/PostgreSQLDialect.java
// Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionPair.java // public interface TypeConversionPair<D,J> { // D convertToDatabase(J obj); // J convertFromDatabase(D obj); // } // // Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/EnumUtils.java // public final class EnumUtils { // // private EnumUtils() { } // // public static @NotNull <T extends Enum<T>> T enumByOrdinal(@NotNull Class<T> enumType, int ordinal) { // Enum<?>[] constants = enumType.getEnumConstants(); // if (ordinal >= 0 && ordinal < constants.length) // return enumType.cast(constants[ordinal]); // else // throw new DatabaseException("invalid ordinal " + ordinal + " for enum type " + enumType.getName()); // } // // public static @NotNull <T extends Enum<T>,K> T enumByKey(@NotNull Class<T> enumType, @NotNull Function<T, K> keyFunction, @NotNull K key) { // for (T enumConstant : enumType.getEnumConstants()) // if (Objects.equals(key, keyFunction.apply(enumConstant))) // return enumConstant; // // throw new InstantiationFailureException("could not find enum constant of type " + enumType.getName() + " for " + key); // } // }
import java.util.Date; import java.util.function.Function; import org.dalesbred.conversion.TypeConversionPair; import org.dalesbred.conversion.TypeConversionRegistry; import org.dalesbred.internal.utils.EnumUtils; import org.jetbrains.annotations.NotNull; import org.postgresql.util.PGobject; import java.sql.SQLException; import java.sql.Timestamp;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.dialect; /** * Support for PostgreSQL. */ public class PostgreSQLDialect extends Dialect { @Override public @NotNull <T extends Enum<T>, K> TypeConversionPair<Object,T> createNativeEnumConversions(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction) { return new TypeConversionPair<Object, T>() { @Override public Object convertToDatabase(T obj) { return createPgObject(String.valueOf(keyFunction.apply(obj)), typeName); } @Override @SuppressWarnings("unchecked") public T convertFromDatabase(Object obj) {
// Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionPair.java // public interface TypeConversionPair<D,J> { // D convertToDatabase(J obj); // J convertFromDatabase(D obj); // } // // Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/EnumUtils.java // public final class EnumUtils { // // private EnumUtils() { } // // public static @NotNull <T extends Enum<T>> T enumByOrdinal(@NotNull Class<T> enumType, int ordinal) { // Enum<?>[] constants = enumType.getEnumConstants(); // if (ordinal >= 0 && ordinal < constants.length) // return enumType.cast(constants[ordinal]); // else // throw new DatabaseException("invalid ordinal " + ordinal + " for enum type " + enumType.getName()); // } // // public static @NotNull <T extends Enum<T>,K> T enumByKey(@NotNull Class<T> enumType, @NotNull Function<T, K> keyFunction, @NotNull K key) { // for (T enumConstant : enumType.getEnumConstants()) // if (Objects.equals(key, keyFunction.apply(enumConstant))) // return enumConstant; // // throw new InstantiationFailureException("could not find enum constant of type " + enumType.getName() + " for " + key); // } // } // Path: dalesbred/src/main/java/org/dalesbred/dialect/PostgreSQLDialect.java import java.util.Date; import java.util.function.Function; import org.dalesbred.conversion.TypeConversionPair; import org.dalesbred.conversion.TypeConversionRegistry; import org.dalesbred.internal.utils.EnumUtils; import org.jetbrains.annotations.NotNull; import org.postgresql.util.PGobject; import java.sql.SQLException; import java.sql.Timestamp; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.dialect; /** * Support for PostgreSQL. */ public class PostgreSQLDialect extends Dialect { @Override public @NotNull <T extends Enum<T>, K> TypeConversionPair<Object,T> createNativeEnumConversions(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction) { return new TypeConversionPair<Object, T>() { @Override public Object convertToDatabase(T obj) { return createPgObject(String.valueOf(keyFunction.apply(obj)), typeName); } @Override @SuppressWarnings("unchecked") public T convertFromDatabase(Object obj) {
return EnumUtils.enumByKey(enumType, keyFunction, (K) obj);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/dialect/PostgreSQLDialect.java
// Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionPair.java // public interface TypeConversionPair<D,J> { // D convertToDatabase(J obj); // J convertFromDatabase(D obj); // } // // Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/EnumUtils.java // public final class EnumUtils { // // private EnumUtils() { } // // public static @NotNull <T extends Enum<T>> T enumByOrdinal(@NotNull Class<T> enumType, int ordinal) { // Enum<?>[] constants = enumType.getEnumConstants(); // if (ordinal >= 0 && ordinal < constants.length) // return enumType.cast(constants[ordinal]); // else // throw new DatabaseException("invalid ordinal " + ordinal + " for enum type " + enumType.getName()); // } // // public static @NotNull <T extends Enum<T>,K> T enumByKey(@NotNull Class<T> enumType, @NotNull Function<T, K> keyFunction, @NotNull K key) { // for (T enumConstant : enumType.getEnumConstants()) // if (Objects.equals(key, keyFunction.apply(enumConstant))) // return enumConstant; // // throw new InstantiationFailureException("could not find enum constant of type " + enumType.getName() + " for " + key); // } // }
import java.util.Date; import java.util.function.Function; import org.dalesbred.conversion.TypeConversionPair; import org.dalesbred.conversion.TypeConversionRegistry; import org.dalesbred.internal.utils.EnumUtils; import org.jetbrains.annotations.NotNull; import org.postgresql.util.PGobject; import java.sql.SQLException; import java.sql.Timestamp;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.dialect; /** * Support for PostgreSQL. */ public class PostgreSQLDialect extends Dialect { @Override public @NotNull <T extends Enum<T>, K> TypeConversionPair<Object,T> createNativeEnumConversions(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction) { return new TypeConversionPair<Object, T>() { @Override public Object convertToDatabase(T obj) { return createPgObject(String.valueOf(keyFunction.apply(obj)), typeName); } @Override @SuppressWarnings("unchecked") public T convertFromDatabase(Object obj) { return EnumUtils.enumByKey(enumType, keyFunction, (K) obj); } }; } private @NotNull Object createPgObject(@NotNull String value, @NotNull String typeName) { try { PGobject object = new PGobject(); object.setType(typeName); object.setValue(value); return object; } catch (SQLException e) { throw convertException(e); } } @Override
// Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionPair.java // public interface TypeConversionPair<D,J> { // D convertToDatabase(J obj); // J convertFromDatabase(D obj); // } // // Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/EnumUtils.java // public final class EnumUtils { // // private EnumUtils() { } // // public static @NotNull <T extends Enum<T>> T enumByOrdinal(@NotNull Class<T> enumType, int ordinal) { // Enum<?>[] constants = enumType.getEnumConstants(); // if (ordinal >= 0 && ordinal < constants.length) // return enumType.cast(constants[ordinal]); // else // throw new DatabaseException("invalid ordinal " + ordinal + " for enum type " + enumType.getName()); // } // // public static @NotNull <T extends Enum<T>,K> T enumByKey(@NotNull Class<T> enumType, @NotNull Function<T, K> keyFunction, @NotNull K key) { // for (T enumConstant : enumType.getEnumConstants()) // if (Objects.equals(key, keyFunction.apply(enumConstant))) // return enumConstant; // // throw new InstantiationFailureException("could not find enum constant of type " + enumType.getName() + " for " + key); // } // } // Path: dalesbred/src/main/java/org/dalesbred/dialect/PostgreSQLDialect.java import java.util.Date; import java.util.function.Function; import org.dalesbred.conversion.TypeConversionPair; import org.dalesbred.conversion.TypeConversionRegistry; import org.dalesbred.internal.utils.EnumUtils; import org.jetbrains.annotations.NotNull; import org.postgresql.util.PGobject; import java.sql.SQLException; import java.sql.Timestamp; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.dialect; /** * Support for PostgreSQL. */ public class PostgreSQLDialect extends Dialect { @Override public @NotNull <T extends Enum<T>, K> TypeConversionPair<Object,T> createNativeEnumConversions(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction) { return new TypeConversionPair<Object, T>() { @Override public Object convertToDatabase(T obj) { return createPgObject(String.valueOf(keyFunction.apply(obj)), typeName); } @Override @SuppressWarnings("unchecked") public T convertFromDatabase(Object obj) { return EnumUtils.enumByKey(enumType, keyFunction, (K) obj); } }; } private @NotNull Object createPgObject(@NotNull String value, @NotNull String typeName) { try { PGobject object = new PGobject(); object.setType(typeName); object.setValue(value); return object; } catch (SQLException e) { throw convertException(e); } } @Override
public void registerTypeConversions(@NotNull TypeConversionRegistry typeConversionRegistry) {
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/instantiation/ConversionMap.java
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/Primitives.java // public static @NotNull <T> Class<T> wrap(@NotNull Class<T> type) { // Class<?> result = // (type == boolean.class) ? Boolean.class // : (type == byte.class) ? Byte.class // : (type == char.class) ? Character.class // : (type == short.class) ? Short.class // : (type == int.class) ? Integer.class // : (type == long.class) ? Long.class // : (type == float.class) ? Float.class // : (type == double.class) ? Double.class // : type; // // @SuppressWarnings("unchecked") // Class<T> casted = (Class<T>) result; // return casted; // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/TypeUtils.java // public final class TypeUtils { // // private TypeUtils() { } // // public static @NotNull Class<?> rawType(@NotNull Type type) { // if (type instanceof Class<?>) { // return (Class<?>) type; // // } else if (type instanceof ParameterizedType) { // return rawType(((ParameterizedType) type).getRawType()); // // } else if (type instanceof TypeVariable<?>) { // // We could return one of the bounds, but it won't work if there are multiple bounds. // // Therefore just return object. // return Object.class; // // } else if (type instanceof WildcardType) { // return rawType(((WildcardType) type).getUpperBounds()[0]); // // } else if (type instanceof GenericArrayType) { // return arrayType(rawType(((GenericArrayType) type).getGenericComponentType())); // // } else { // throw new IllegalArgumentException("unexpected type: " + type); // } // } // // public static @NotNull Type typeParameter(@NotNull Type type) { // if (type instanceof ParameterizedType) // return ((ParameterizedType) type).getActualTypeArguments()[0]; // // return Object.class; // } // // public static boolean isEnum(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isEnum(); // } // // public static boolean isPrimitive(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isPrimitive(); // } // // public static @NotNull Class<?> arrayType(@NotNull Class<?> type) { // return Array.newInstance(type, 0).getClass(); // } // // public static @Nullable Type genericSuperClass(@NotNull Type type) { // return rawType(type).getGenericSuperclass(); // } // // public static @NotNull Type[] genericInterfaces(@NotNull Type type) { // return rawType(type).getGenericInterfaces(); // } // // public static boolean isAssignable(@NotNull Type target, @NotNull Type source) { // // TODO: implement proper rules for generic types // return isAssignableByBoxing(rawType(target), rawType(source)); // } // // private static boolean isAssignableByBoxing(@NotNull Class<?> target, @NotNull Class<?> source) { // return Primitives.wrap(target).isAssignableFrom(Primitives.wrap(source)); // } // }
import org.jetbrains.annotations.NotNull; import java.lang.reflect.Type; import java.util.*; import static java.util.Collections.emptyList; import static org.dalesbred.internal.utils.Primitives.wrap; import static org.dalesbred.internal.utils.TypeUtils.*;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.instantiation; final class ConversionMap { private final @NotNull Map<Type, List<ConversionRegistration>> mappings = new HashMap<>(); void register(@NotNull Type source, @NotNull Type target, @NotNull TypeConversion conversion) {
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/Primitives.java // public static @NotNull <T> Class<T> wrap(@NotNull Class<T> type) { // Class<?> result = // (type == boolean.class) ? Boolean.class // : (type == byte.class) ? Byte.class // : (type == char.class) ? Character.class // : (type == short.class) ? Short.class // : (type == int.class) ? Integer.class // : (type == long.class) ? Long.class // : (type == float.class) ? Float.class // : (type == double.class) ? Double.class // : type; // // @SuppressWarnings("unchecked") // Class<T> casted = (Class<T>) result; // return casted; // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/TypeUtils.java // public final class TypeUtils { // // private TypeUtils() { } // // public static @NotNull Class<?> rawType(@NotNull Type type) { // if (type instanceof Class<?>) { // return (Class<?>) type; // // } else if (type instanceof ParameterizedType) { // return rawType(((ParameterizedType) type).getRawType()); // // } else if (type instanceof TypeVariable<?>) { // // We could return one of the bounds, but it won't work if there are multiple bounds. // // Therefore just return object. // return Object.class; // // } else if (type instanceof WildcardType) { // return rawType(((WildcardType) type).getUpperBounds()[0]); // // } else if (type instanceof GenericArrayType) { // return arrayType(rawType(((GenericArrayType) type).getGenericComponentType())); // // } else { // throw new IllegalArgumentException("unexpected type: " + type); // } // } // // public static @NotNull Type typeParameter(@NotNull Type type) { // if (type instanceof ParameterizedType) // return ((ParameterizedType) type).getActualTypeArguments()[0]; // // return Object.class; // } // // public static boolean isEnum(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isEnum(); // } // // public static boolean isPrimitive(@NotNull Type type) { // return (type instanceof Class<?>) && ((Class<?>) type).isPrimitive(); // } // // public static @NotNull Class<?> arrayType(@NotNull Class<?> type) { // return Array.newInstance(type, 0).getClass(); // } // // public static @Nullable Type genericSuperClass(@NotNull Type type) { // return rawType(type).getGenericSuperclass(); // } // // public static @NotNull Type[] genericInterfaces(@NotNull Type type) { // return rawType(type).getGenericInterfaces(); // } // // public static boolean isAssignable(@NotNull Type target, @NotNull Type source) { // // TODO: implement proper rules for generic types // return isAssignableByBoxing(rawType(target), rawType(source)); // } // // private static boolean isAssignableByBoxing(@NotNull Class<?> target, @NotNull Class<?> source) { // return Primitives.wrap(target).isAssignableFrom(Primitives.wrap(source)); // } // } // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/ConversionMap.java import org.jetbrains.annotations.NotNull; import java.lang.reflect.Type; import java.util.*; import static java.util.Collections.emptyList; import static org.dalesbred.internal.utils.Primitives.wrap; import static org.dalesbred.internal.utils.TypeUtils.*; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.instantiation; final class ConversionMap { private final @NotNull Map<Type, List<ConversionRegistration>> mappings = new HashMap<>(); void register(@NotNull Type source, @NotNull Type target, @NotNull TypeConversion conversion) {
mappings.computeIfAbsent(wrap(source), a -> new ArrayList<>()).add(new ConversionRegistration(target, conversion));
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/query/NamedParameterSql.java
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/CollectionUtils.java // public static @NotNull <A,B> List<B> mapToList(@NotNull Collection<? extends A> xs, @NotNull Function<? super A, ? extends B> mapper) { // return xs.stream().map(mapper).collect(toListWithCapacity(xs.size())); // }
import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; import java.util.List; import static org.dalesbred.internal.utils.CollectionUtils.mapToList;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.query; final class NamedParameterSql { @Language("SQL") private final @NotNull String sql; private final @NotNull List<String> parameterNames; NamedParameterSql(@NotNull @Language("SQL") String sql, @NotNull List<String> parameterNames) { this.sql = sql; this.parameterNames = parameterNames; } public @NotNull SqlQuery toQuery(@NotNull VariableResolver variableResolver) { return SqlQuery.query(sql, resolveParameterValues(variableResolver)); } private @NotNull List<?> resolveParameterValues(@NotNull VariableResolver variableResolver) {
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/CollectionUtils.java // public static @NotNull <A,B> List<B> mapToList(@NotNull Collection<? extends A> xs, @NotNull Function<? super A, ? extends B> mapper) { // return xs.stream().map(mapper).collect(toListWithCapacity(xs.size())); // } // Path: dalesbred/src/main/java/org/dalesbred/query/NamedParameterSql.java import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; import java.util.List; import static org.dalesbred.internal.utils.CollectionUtils.mapToList; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.query; final class NamedParameterSql { @Language("SQL") private final @NotNull String sql; private final @NotNull List<String> parameterNames; NamedParameterSql(@NotNull @Language("SQL") String sql, @NotNull List<String> parameterNames) { this.sql = sql; this.parameterNames = parameterNames; } public @NotNull SqlQuery toQuery(@NotNull VariableResolver variableResolver) { return SqlQuery.query(sql, resolveParameterValues(variableResolver)); } private @NotNull List<?> resolveParameterValues(@NotNull VariableResolver variableResolver) {
return mapToList(parameterNames, variableResolver::getValue);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/integration/threeten/ThreeTenTypeConversions.java
// Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // }
import org.dalesbred.conversion.TypeConversionRegistry; import org.jetbrains.annotations.NotNull; import org.threeten.bp.*; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.integration.threeten; /** * Conversions for ThreeTen. These are automatically detected if ThreeTen is found on * classpath, so the user doesn't need to do anything to get ThreeTen-support. */ public final class ThreeTenTypeConversions { private static final long MILLIS_PER_SECOND = 1000; private static final int EPOCH_YEAR = 1900; private ThreeTenTypeConversions() { } /** * Returns true if java.time is found on classpath. */ public static boolean hasThreeTen() { try { Class.forName("org.threeten.bp.LocalDate"); return true; } catch (ClassNotFoundException e) { return false; } }
// Path: dalesbred/src/main/java/org/dalesbred/conversion/TypeConversionRegistry.java // public interface TypeConversionRegistry { // // /** // * Registers conversion from given source database type to given target model type. // */ // <S, T> void registerConversionFromDatabase(@NotNull Class<S> source, @NotNull Class<T> target, @NotNull Function<S, T> conversion); // // /** // * Registers conversion from given source model type to database type. // */ // <T> void registerConversionToDatabase(@NotNull Class<T> source, @NotNull Function<T, ?> conversion); // // /** // * Registers conversions from database type to model type and back. // */ // default <D, J> void registerConversions(@NotNull Class<D> databaseType, // @NotNull Class<J> javaType, // @NotNull Function<D, J> fromDatabase, // @NotNull Function<J, D> toDatabase) { // registerConversionFromDatabase(databaseType, javaType, fromDatabase); // registerConversionToDatabase(javaType, toDatabase); // } // // /** // * Registers simple enum conversion that uses keyFunction to produce saved value and uses // * same function on enum constants to convert values back. // */ // <T extends Enum<T>,K> void registerEnumConversion(@NotNull Class<T> enumType, @NotNull Function<T,K> keyFunction); // // /** // * Returns given enum-type to be saved as database native enum of given type name. // */ // default <T extends Enum<T>> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName) { // registerNativeEnumConversion(enumType, typeName, Enum::name); // } // // /** // * Returns given enum-type to be saved as database native enum of given type name. Given function // * can be used to map the enum to the stored value. // */ // <T extends Enum<T>, K> void registerNativeEnumConversion(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction); // } // Path: dalesbred/src/main/java/org/dalesbred/integration/threeten/ThreeTenTypeConversions.java import org.dalesbred.conversion.TypeConversionRegistry; import org.jetbrains.annotations.NotNull; import org.threeten.bp.*; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.integration.threeten; /** * Conversions for ThreeTen. These are automatically detected if ThreeTen is found on * classpath, so the user doesn't need to do anything to get ThreeTen-support. */ public final class ThreeTenTypeConversions { private static final long MILLIS_PER_SECOND = 1000; private static final int EPOCH_YEAR = 1900; private ThreeTenTypeConversions() { } /** * Returns true if java.time is found on classpath. */ public static boolean hasThreeTen() { try { Class.forName("org.threeten.bp.LocalDate"); return true; } catch (ClassNotFoundException e) { return false; } }
public static void register(@NotNull TypeConversionRegistry typeConversionRegistry) {
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/transaction/DefaultTransactionManager.java
// Path: dalesbred/src/main/java/org/dalesbred/connection/ConnectionProvider.java // public interface ConnectionProvider { // // @NotNull // Connection getConnection() throws SQLException; // // void releaseConnection(@NotNull Connection connection) throws SQLException; // } // // Path: dalesbred/src/main/java/org/dalesbred/dialect/Dialect.java // public abstract class Dialect { // // private static final String SERIALIZATION_FAILURE = "40001"; // // private static final Logger log = LoggerFactory.getLogger(Dialect.class); // // public @NotNull Object valueToDatabase(@NotNull Object value) { // return value; // } // // public @NotNull <T extends Enum<T>, K> TypeConversionPair<Object,T> createNativeEnumConversions(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction) { // throw new UnsupportedOperationException("native enums are not supported by " + getClass().getName()); // } // // @Override // public @NotNull String toString() { // return getClass().getName(); // } // // public static @NotNull Dialect detect(@NotNull DataSource dataSource) { // return detect(new DataSourceConnectionProvider(dataSource)); // } // // public static @NotNull Dialect detect(@NotNull TransactionManager transactionManager) { // return transactionManager.withTransaction(new TransactionSettings(), // tx -> detect(tx.getConnection()), new DefaultDialect()); // } // // public static @NotNull Dialect detect(@NotNull ConnectionProvider connectionProvider) { // try { // Connection connection = connectionProvider.getConnection(); // try { // return detect(connection); // } finally { // connectionProvider.releaseConnection(connection); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public static @NotNull Dialect detect(@NotNull Connection connection) { // try { // String productName = connection.getMetaData().getDatabaseProductName(); // // switch (productName) { // case "PostgreSQL": // log.debug("Automatically detected dialect PostgreSQL."); // return new PostgreSQLDialect(); // // case "HSQL Database Engine": // log.debug("Automatically detected dialect HSQLDB."); // return new HsqldbDialect(); // // case "H2": // log.debug("Automatically detected dialect H2."); // return new H2Dialect(); // // case "MySQL": // log.debug("Automatically detected dialect MySQL."); // return new MySQLDialect(); // // case "Oracle": // log.debug("Automatically detected dialect Oracle."); // return new OracleDialect(); // // case "Microsoft SQL Server": // log.debug("Automatically detected dialect SQLServer."); // return new SQLServerDialect(); // // default: // log.info("Could not detect dialect for product name '{}', falling back to default.", productName); // return new DefaultDialect(); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public @NotNull DatabaseException convertException(@NotNull SQLException e) { // String sqlState = e.getSQLState(); // if (sqlState == null) // return new DatabaseSQLException(e); // // if (sqlState.equals(SERIALIZATION_FAILURE)) // return new TransactionSerializationException(e); // else if (sqlState.startsWith("40")) // return new TransactionRollbackException(e); // else // return new DatabaseSQLException(e); // } // // public void registerTypeConversions(@NotNull TypeConversionRegistry typeConversionRegistry) { // // } // // /** // * Bind object to {@link PreparedStatement}. Can be overridden by subclasses to // * implement custom argument binding. // * // * @param ps statement to bind object to // * @param index index of the parameter // * @param value to bind // * @throws SQLException if something fails // */ // public void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { // ArgumentBinder.bindArgument(ps, index, value); // } // }
import static java.util.Objects.requireNonNull; import org.dalesbred.connection.ConnectionProvider; import org.dalesbred.dialect.Dialect; import org.jetbrains.annotations.NotNull; import java.sql.Connection; import java.sql.SQLException; import java.util.Optional;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.transaction; /** * Default transaction manager that handles all transactions by itself. */ public final class DefaultTransactionManager extends AbstractTransactionManager { /** * The current active transaction of this thread, or null */ private final @NotNull ThreadLocal<DefaultTransaction> activeTransaction = new ThreadLocal<>();
// Path: dalesbred/src/main/java/org/dalesbred/connection/ConnectionProvider.java // public interface ConnectionProvider { // // @NotNull // Connection getConnection() throws SQLException; // // void releaseConnection(@NotNull Connection connection) throws SQLException; // } // // Path: dalesbred/src/main/java/org/dalesbred/dialect/Dialect.java // public abstract class Dialect { // // private static final String SERIALIZATION_FAILURE = "40001"; // // private static final Logger log = LoggerFactory.getLogger(Dialect.class); // // public @NotNull Object valueToDatabase(@NotNull Object value) { // return value; // } // // public @NotNull <T extends Enum<T>, K> TypeConversionPair<Object,T> createNativeEnumConversions(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction) { // throw new UnsupportedOperationException("native enums are not supported by " + getClass().getName()); // } // // @Override // public @NotNull String toString() { // return getClass().getName(); // } // // public static @NotNull Dialect detect(@NotNull DataSource dataSource) { // return detect(new DataSourceConnectionProvider(dataSource)); // } // // public static @NotNull Dialect detect(@NotNull TransactionManager transactionManager) { // return transactionManager.withTransaction(new TransactionSettings(), // tx -> detect(tx.getConnection()), new DefaultDialect()); // } // // public static @NotNull Dialect detect(@NotNull ConnectionProvider connectionProvider) { // try { // Connection connection = connectionProvider.getConnection(); // try { // return detect(connection); // } finally { // connectionProvider.releaseConnection(connection); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public static @NotNull Dialect detect(@NotNull Connection connection) { // try { // String productName = connection.getMetaData().getDatabaseProductName(); // // switch (productName) { // case "PostgreSQL": // log.debug("Automatically detected dialect PostgreSQL."); // return new PostgreSQLDialect(); // // case "HSQL Database Engine": // log.debug("Automatically detected dialect HSQLDB."); // return new HsqldbDialect(); // // case "H2": // log.debug("Automatically detected dialect H2."); // return new H2Dialect(); // // case "MySQL": // log.debug("Automatically detected dialect MySQL."); // return new MySQLDialect(); // // case "Oracle": // log.debug("Automatically detected dialect Oracle."); // return new OracleDialect(); // // case "Microsoft SQL Server": // log.debug("Automatically detected dialect SQLServer."); // return new SQLServerDialect(); // // default: // log.info("Could not detect dialect for product name '{}', falling back to default.", productName); // return new DefaultDialect(); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public @NotNull DatabaseException convertException(@NotNull SQLException e) { // String sqlState = e.getSQLState(); // if (sqlState == null) // return new DatabaseSQLException(e); // // if (sqlState.equals(SERIALIZATION_FAILURE)) // return new TransactionSerializationException(e); // else if (sqlState.startsWith("40")) // return new TransactionRollbackException(e); // else // return new DatabaseSQLException(e); // } // // public void registerTypeConversions(@NotNull TypeConversionRegistry typeConversionRegistry) { // // } // // /** // * Bind object to {@link PreparedStatement}. Can be overridden by subclasses to // * implement custom argument binding. // * // * @param ps statement to bind object to // * @param index index of the parameter // * @param value to bind // * @throws SQLException if something fails // */ // public void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { // ArgumentBinder.bindArgument(ps, index, value); // } // } // Path: dalesbred/src/main/java/org/dalesbred/transaction/DefaultTransactionManager.java import static java.util.Objects.requireNonNull; import org.dalesbred.connection.ConnectionProvider; import org.dalesbred.dialect.Dialect; import org.jetbrains.annotations.NotNull; import java.sql.Connection; import java.sql.SQLException; import java.util.Optional; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.transaction; /** * Default transaction manager that handles all transactions by itself. */ public final class DefaultTransactionManager extends AbstractTransactionManager { /** * The current active transaction of this thread, or null */ private final @NotNull ThreadLocal<DefaultTransaction> activeTransaction = new ThreadLocal<>();
private final @NotNull ConnectionProvider connectionProvider;
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/transaction/DefaultTransactionManager.java
// Path: dalesbred/src/main/java/org/dalesbred/connection/ConnectionProvider.java // public interface ConnectionProvider { // // @NotNull // Connection getConnection() throws SQLException; // // void releaseConnection(@NotNull Connection connection) throws SQLException; // } // // Path: dalesbred/src/main/java/org/dalesbred/dialect/Dialect.java // public abstract class Dialect { // // private static final String SERIALIZATION_FAILURE = "40001"; // // private static final Logger log = LoggerFactory.getLogger(Dialect.class); // // public @NotNull Object valueToDatabase(@NotNull Object value) { // return value; // } // // public @NotNull <T extends Enum<T>, K> TypeConversionPair<Object,T> createNativeEnumConversions(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction) { // throw new UnsupportedOperationException("native enums are not supported by " + getClass().getName()); // } // // @Override // public @NotNull String toString() { // return getClass().getName(); // } // // public static @NotNull Dialect detect(@NotNull DataSource dataSource) { // return detect(new DataSourceConnectionProvider(dataSource)); // } // // public static @NotNull Dialect detect(@NotNull TransactionManager transactionManager) { // return transactionManager.withTransaction(new TransactionSettings(), // tx -> detect(tx.getConnection()), new DefaultDialect()); // } // // public static @NotNull Dialect detect(@NotNull ConnectionProvider connectionProvider) { // try { // Connection connection = connectionProvider.getConnection(); // try { // return detect(connection); // } finally { // connectionProvider.releaseConnection(connection); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public static @NotNull Dialect detect(@NotNull Connection connection) { // try { // String productName = connection.getMetaData().getDatabaseProductName(); // // switch (productName) { // case "PostgreSQL": // log.debug("Automatically detected dialect PostgreSQL."); // return new PostgreSQLDialect(); // // case "HSQL Database Engine": // log.debug("Automatically detected dialect HSQLDB."); // return new HsqldbDialect(); // // case "H2": // log.debug("Automatically detected dialect H2."); // return new H2Dialect(); // // case "MySQL": // log.debug("Automatically detected dialect MySQL."); // return new MySQLDialect(); // // case "Oracle": // log.debug("Automatically detected dialect Oracle."); // return new OracleDialect(); // // case "Microsoft SQL Server": // log.debug("Automatically detected dialect SQLServer."); // return new SQLServerDialect(); // // default: // log.info("Could not detect dialect for product name '{}', falling back to default.", productName); // return new DefaultDialect(); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public @NotNull DatabaseException convertException(@NotNull SQLException e) { // String sqlState = e.getSQLState(); // if (sqlState == null) // return new DatabaseSQLException(e); // // if (sqlState.equals(SERIALIZATION_FAILURE)) // return new TransactionSerializationException(e); // else if (sqlState.startsWith("40")) // return new TransactionRollbackException(e); // else // return new DatabaseSQLException(e); // } // // public void registerTypeConversions(@NotNull TypeConversionRegistry typeConversionRegistry) { // // } // // /** // * Bind object to {@link PreparedStatement}. Can be overridden by subclasses to // * implement custom argument binding. // * // * @param ps statement to bind object to // * @param index index of the parameter // * @param value to bind // * @throws SQLException if something fails // */ // public void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { // ArgumentBinder.bindArgument(ps, index, value); // } // }
import static java.util.Objects.requireNonNull; import org.dalesbred.connection.ConnectionProvider; import org.dalesbred.dialect.Dialect; import org.jetbrains.annotations.NotNull; import java.sql.Connection; import java.sql.SQLException; import java.util.Optional;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.transaction; /** * Default transaction manager that handles all transactions by itself. */ public final class DefaultTransactionManager extends AbstractTransactionManager { /** * The current active transaction of this thread, or null */ private final @NotNull ThreadLocal<DefaultTransaction> activeTransaction = new ThreadLocal<>(); private final @NotNull ConnectionProvider connectionProvider; public DefaultTransactionManager(@NotNull ConnectionProvider connectionProvider) { this.connectionProvider = requireNonNull(connectionProvider); } @Override protected <T> T withNewTransaction(@NotNull TransactionCallback<T> callback,
// Path: dalesbred/src/main/java/org/dalesbred/connection/ConnectionProvider.java // public interface ConnectionProvider { // // @NotNull // Connection getConnection() throws SQLException; // // void releaseConnection(@NotNull Connection connection) throws SQLException; // } // // Path: dalesbred/src/main/java/org/dalesbred/dialect/Dialect.java // public abstract class Dialect { // // private static final String SERIALIZATION_FAILURE = "40001"; // // private static final Logger log = LoggerFactory.getLogger(Dialect.class); // // public @NotNull Object valueToDatabase(@NotNull Object value) { // return value; // } // // public @NotNull <T extends Enum<T>, K> TypeConversionPair<Object,T> createNativeEnumConversions(@NotNull Class<T> enumType, @NotNull String typeName, @NotNull Function<T,K> keyFunction) { // throw new UnsupportedOperationException("native enums are not supported by " + getClass().getName()); // } // // @Override // public @NotNull String toString() { // return getClass().getName(); // } // // public static @NotNull Dialect detect(@NotNull DataSource dataSource) { // return detect(new DataSourceConnectionProvider(dataSource)); // } // // public static @NotNull Dialect detect(@NotNull TransactionManager transactionManager) { // return transactionManager.withTransaction(new TransactionSettings(), // tx -> detect(tx.getConnection()), new DefaultDialect()); // } // // public static @NotNull Dialect detect(@NotNull ConnectionProvider connectionProvider) { // try { // Connection connection = connectionProvider.getConnection(); // try { // return detect(connection); // } finally { // connectionProvider.releaseConnection(connection); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public static @NotNull Dialect detect(@NotNull Connection connection) { // try { // String productName = connection.getMetaData().getDatabaseProductName(); // // switch (productName) { // case "PostgreSQL": // log.debug("Automatically detected dialect PostgreSQL."); // return new PostgreSQLDialect(); // // case "HSQL Database Engine": // log.debug("Automatically detected dialect HSQLDB."); // return new HsqldbDialect(); // // case "H2": // log.debug("Automatically detected dialect H2."); // return new H2Dialect(); // // case "MySQL": // log.debug("Automatically detected dialect MySQL."); // return new MySQLDialect(); // // case "Oracle": // log.debug("Automatically detected dialect Oracle."); // return new OracleDialect(); // // case "Microsoft SQL Server": // log.debug("Automatically detected dialect SQLServer."); // return new SQLServerDialect(); // // default: // log.info("Could not detect dialect for product name '{}', falling back to default.", productName); // return new DefaultDialect(); // } // } catch (SQLException e) { // throw new DatabaseSQLException("Failed to auto-detect database dialect: " + e, e); // } // } // // public @NotNull DatabaseException convertException(@NotNull SQLException e) { // String sqlState = e.getSQLState(); // if (sqlState == null) // return new DatabaseSQLException(e); // // if (sqlState.equals(SERIALIZATION_FAILURE)) // return new TransactionSerializationException(e); // else if (sqlState.startsWith("40")) // return new TransactionRollbackException(e); // else // return new DatabaseSQLException(e); // } // // public void registerTypeConversions(@NotNull TypeConversionRegistry typeConversionRegistry) { // // } // // /** // * Bind object to {@link PreparedStatement}. Can be overridden by subclasses to // * implement custom argument binding. // * // * @param ps statement to bind object to // * @param index index of the parameter // * @param value to bind // * @throws SQLException if something fails // */ // public void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException { // ArgumentBinder.bindArgument(ps, index, value); // } // } // Path: dalesbred/src/main/java/org/dalesbred/transaction/DefaultTransactionManager.java import static java.util.Objects.requireNonNull; import org.dalesbred.connection.ConnectionProvider; import org.dalesbred.dialect.Dialect; import org.jetbrains.annotations.NotNull; import java.sql.Connection; import java.sql.SQLException; import java.util.Optional; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.transaction; /** * Default transaction manager that handles all transactions by itself. */ public final class DefaultTransactionManager extends AbstractTransactionManager { /** * The current active transaction of this thread, or null */ private final @NotNull ThreadLocal<DefaultTransaction> activeTransaction = new ThreadLocal<>(); private final @NotNull ConnectionProvider connectionProvider; public DefaultTransactionManager(@NotNull ConnectionProvider connectionProvider) { this.connectionProvider = requireNonNull(connectionProvider); } @Override protected <T> T withNewTransaction(@NotNull TransactionCallback<T> callback,
@NotNull Dialect dialect,
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/result/MapResultSetProcessor.java
// Path: dalesbred/src/main/java/org/dalesbred/internal/jdbc/ResultSetUtils.java // public final class ResultSetUtils { // // private ResultSetUtils() { } // // public static @NotNull NamedTypeList getTypes(@NotNull ResultSetMetaData metaData) throws SQLException { // int columns = metaData.getColumnCount(); // // NamedTypeList.Builder result = NamedTypeList.builder(columns); // // for (int i = 0; i < columns; i++) // result.add(metaData.getColumnLabel(i+1), getColumnType(metaData, i + 1)); // // return result.build(); // } // // public static @NotNull Type getColumnType(@NotNull ResultSetMetaData metaData, int column) throws SQLException { // String className = metaData.getColumnClassName(column); // try { // return Class.forName(className); // } catch (ClassNotFoundException e) { // throw new DatabaseException("Could not find class '" + className + "' specified by ResultSet.", e); // } // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/Primitives.java // public final class Primitives { // // private Primitives() { } // // /** // * Returns the corresponding wrapper type for a primitive type, or the type itself if it is not a primitive type. // */ // public static @NotNull <T> Class<T> wrap(@NotNull Class<T> type) { // Class<?> result = // (type == boolean.class) ? Boolean.class // : (type == byte.class) ? Byte.class // : (type == char.class) ? Character.class // : (type == short.class) ? Short.class // : (type == int.class) ? Integer.class // : (type == long.class) ? Long.class // : (type == float.class) ? Float.class // : (type == double.class) ? Double.class // : type; // // @SuppressWarnings("unchecked") // Class<T> casted = (Class<T>) result; // return casted; // } // // public static @NotNull Type wrap(@NotNull Type type) { // if (type instanceof Class<?>) // return wrap((Class<?>) type); // else // return type; // } // // /** // * Returns the corresponding primitive type for a wrapper type, or the type itself if it is not a wrapper. // */ // public static @NotNull <T> Class<T> unwrap(@NotNull Class<T> type) { // Class<?> result = // (type == Boolean.class) ? boolean.class // : (type == Byte.class) ? byte.class // : (type == Character.class) ? char.class // : (type == Short.class) ? short.class // : (type == Integer.class) ? int.class // : (type == Long.class) ? long.class // : (type == Float.class) ? float.class // : (type == Double.class) ? double.class // : type; // // @SuppressWarnings("unchecked") // Class<T> casted = (Class<T>) result; // return casted; // } // // public static @NotNull Object[] arrayAsObjectArray(@NotNull Object o) { // Class<?> type = o.getClass(); // if (!type.isArray()) throw new IllegalArgumentException("not an array: " + o); // // if (o instanceof Object[]) // return (Object[]) o; // // int length = Array.getLength(o); // Object[] result = (Object[]) Array.newInstance(wrap(type.getComponentType()), length); // // for (int i = 0; i < length; i++) // result[i] = Array.get(o, i); // // return result; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/result/ResultSetProcessor.java // @FunctionalInterface // public interface ResultSetProcessor<T> { // T process(@NotNull ResultSet resultSet) throws SQLException; // } // // Path: dalesbred/src/main/java/org/dalesbred/result/UnexpectedResultException.java // public class UnexpectedResultException extends DatabaseException { // public UnexpectedResultException(@NotNull String message) { // super(message); // } // }
import java.sql.SQLException; import java.util.LinkedHashMap; import java.util.Map; import static java.util.Objects.requireNonNull; import org.dalesbred.internal.instantiation.*; import org.dalesbred.internal.jdbc.ResultSetUtils; import org.dalesbred.internal.utils.Primitives; import org.dalesbred.result.ResultSetProcessor; import org.dalesbred.result.UnexpectedResultException; import org.jetbrains.annotations.NotNull; import java.sql.ResultSet;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.result; /** * ResultSetProcessor that expects results with two columns and creates map from them. * * <p>This processor updates the map in order in which the rows are read. Therefore, if * the keys of the result are not distinct, the result contains the last binding of given key. */ public final class MapResultSetProcessor<K,V> implements ResultSetProcessor<Map<K,V>> { private final @NotNull Class<K> keyType; private final @NotNull Class<V> valueType; private final @NotNull InstantiatorProvider instantiatorRegistry; public MapResultSetProcessor(@NotNull Class<K> keyType, @NotNull Class<V> valueType, @NotNull InstantiatorProvider instantiatorRegistry) {
// Path: dalesbred/src/main/java/org/dalesbred/internal/jdbc/ResultSetUtils.java // public final class ResultSetUtils { // // private ResultSetUtils() { } // // public static @NotNull NamedTypeList getTypes(@NotNull ResultSetMetaData metaData) throws SQLException { // int columns = metaData.getColumnCount(); // // NamedTypeList.Builder result = NamedTypeList.builder(columns); // // for (int i = 0; i < columns; i++) // result.add(metaData.getColumnLabel(i+1), getColumnType(metaData, i + 1)); // // return result.build(); // } // // public static @NotNull Type getColumnType(@NotNull ResultSetMetaData metaData, int column) throws SQLException { // String className = metaData.getColumnClassName(column); // try { // return Class.forName(className); // } catch (ClassNotFoundException e) { // throw new DatabaseException("Could not find class '" + className + "' specified by ResultSet.", e); // } // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/Primitives.java // public final class Primitives { // // private Primitives() { } // // /** // * Returns the corresponding wrapper type for a primitive type, or the type itself if it is not a primitive type. // */ // public static @NotNull <T> Class<T> wrap(@NotNull Class<T> type) { // Class<?> result = // (type == boolean.class) ? Boolean.class // : (type == byte.class) ? Byte.class // : (type == char.class) ? Character.class // : (type == short.class) ? Short.class // : (type == int.class) ? Integer.class // : (type == long.class) ? Long.class // : (type == float.class) ? Float.class // : (type == double.class) ? Double.class // : type; // // @SuppressWarnings("unchecked") // Class<T> casted = (Class<T>) result; // return casted; // } // // public static @NotNull Type wrap(@NotNull Type type) { // if (type instanceof Class<?>) // return wrap((Class<?>) type); // else // return type; // } // // /** // * Returns the corresponding primitive type for a wrapper type, or the type itself if it is not a wrapper. // */ // public static @NotNull <T> Class<T> unwrap(@NotNull Class<T> type) { // Class<?> result = // (type == Boolean.class) ? boolean.class // : (type == Byte.class) ? byte.class // : (type == Character.class) ? char.class // : (type == Short.class) ? short.class // : (type == Integer.class) ? int.class // : (type == Long.class) ? long.class // : (type == Float.class) ? float.class // : (type == Double.class) ? double.class // : type; // // @SuppressWarnings("unchecked") // Class<T> casted = (Class<T>) result; // return casted; // } // // public static @NotNull Object[] arrayAsObjectArray(@NotNull Object o) { // Class<?> type = o.getClass(); // if (!type.isArray()) throw new IllegalArgumentException("not an array: " + o); // // if (o instanceof Object[]) // return (Object[]) o; // // int length = Array.getLength(o); // Object[] result = (Object[]) Array.newInstance(wrap(type.getComponentType()), length); // // for (int i = 0; i < length; i++) // result[i] = Array.get(o, i); // // return result; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/result/ResultSetProcessor.java // @FunctionalInterface // public interface ResultSetProcessor<T> { // T process(@NotNull ResultSet resultSet) throws SQLException; // } // // Path: dalesbred/src/main/java/org/dalesbred/result/UnexpectedResultException.java // public class UnexpectedResultException extends DatabaseException { // public UnexpectedResultException(@NotNull String message) { // super(message); // } // } // Path: dalesbred/src/main/java/org/dalesbred/internal/result/MapResultSetProcessor.java import java.sql.SQLException; import java.util.LinkedHashMap; import java.util.Map; import static java.util.Objects.requireNonNull; import org.dalesbred.internal.instantiation.*; import org.dalesbred.internal.jdbc.ResultSetUtils; import org.dalesbred.internal.utils.Primitives; import org.dalesbred.result.ResultSetProcessor; import org.dalesbred.result.UnexpectedResultException; import org.jetbrains.annotations.NotNull; import java.sql.ResultSet; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.result; /** * ResultSetProcessor that expects results with two columns and creates map from them. * * <p>This processor updates the map in order in which the rows are read. Therefore, if * the keys of the result are not distinct, the result contains the last binding of given key. */ public final class MapResultSetProcessor<K,V> implements ResultSetProcessor<Map<K,V>> { private final @NotNull Class<K> keyType; private final @NotNull Class<V> valueType; private final @NotNull InstantiatorProvider instantiatorRegistry; public MapResultSetProcessor(@NotNull Class<K> keyType, @NotNull Class<V> valueType, @NotNull InstantiatorProvider instantiatorRegistry) {
this.keyType = Primitives.wrap(requireNonNull(keyType));
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/jdbc/ResultSetUtils.java
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/NamedTypeList.java // public final class NamedTypeList { // // private final @NotNull List<String> names; // // private final @NotNull List<Type> types; // // private NamedTypeList(@NotNull List<String> names, @NotNull List<Type> types) { // assert names.size() == types.size(); // this.names = unmodifiableList(names); // this.types = types; // } // // public int size() { // return types.size(); // } // // public @NotNull String getName(int index) { // return names.get(index); // } // // public @NotNull Type getType(int index) { // return types.get(index); // } // // public @NotNull List<String> getNames() { // return names; // } // // public @NotNull NamedTypeList subList(int fromIndex, int toIndex) { // return new NamedTypeList(names.subList(fromIndex, toIndex), types.subList(fromIndex, toIndex)); // } // // @Override // public @NotNull String toString() { // int size = types.size(); // // @SuppressWarnings("MagicNumber") // StringBuilder sb = new StringBuilder(10 + size * 30); // // sb.append('['); // // for (int i = 0; i < size; i++) { // if (i != 0) sb.append(", "); // // sb.append(names.get(i)).append(": ").append(types.get(i).getTypeName()); // } // // sb.append(']'); // // return sb.toString(); // } // // public static @NotNull Builder builder(int size) { // return new Builder(size); // } // // /** // * Builder for {@link NamedTypeList}s. // */ // public static class Builder { // // private boolean built = false; // // private final @NotNull List<String> names; // // private final @NotNull List<Type> types; // // private Builder(int size) { // this.names = new ArrayList<>(size); // this.types = new ArrayList<>(size); // } // // public Builder add(@NotNull String name, @NotNull Type type) { // if (built) throw new IllegalStateException("can't add items to builder that has been built"); // // names.add(requireNonNull(name)); // types.add(requireNonNull(type)); // return this; // } // // public @NotNull NamedTypeList build() { // built = true; // return new NamedTypeList(names, types); // } // } // }
import org.dalesbred.DatabaseException; import org.dalesbred.internal.instantiation.NamedTypeList; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Type; import java.sql.ResultSetMetaData; import java.sql.SQLException;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.jdbc; /** * Utilities for processing {@link java.sql.ResultSet}s. */ public final class ResultSetUtils { private ResultSetUtils() { }
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/NamedTypeList.java // public final class NamedTypeList { // // private final @NotNull List<String> names; // // private final @NotNull List<Type> types; // // private NamedTypeList(@NotNull List<String> names, @NotNull List<Type> types) { // assert names.size() == types.size(); // this.names = unmodifiableList(names); // this.types = types; // } // // public int size() { // return types.size(); // } // // public @NotNull String getName(int index) { // return names.get(index); // } // // public @NotNull Type getType(int index) { // return types.get(index); // } // // public @NotNull List<String> getNames() { // return names; // } // // public @NotNull NamedTypeList subList(int fromIndex, int toIndex) { // return new NamedTypeList(names.subList(fromIndex, toIndex), types.subList(fromIndex, toIndex)); // } // // @Override // public @NotNull String toString() { // int size = types.size(); // // @SuppressWarnings("MagicNumber") // StringBuilder sb = new StringBuilder(10 + size * 30); // // sb.append('['); // // for (int i = 0; i < size; i++) { // if (i != 0) sb.append(", "); // // sb.append(names.get(i)).append(": ").append(types.get(i).getTypeName()); // } // // sb.append(']'); // // return sb.toString(); // } // // public static @NotNull Builder builder(int size) { // return new Builder(size); // } // // /** // * Builder for {@link NamedTypeList}s. // */ // public static class Builder { // // private boolean built = false; // // private final @NotNull List<String> names; // // private final @NotNull List<Type> types; // // private Builder(int size) { // this.names = new ArrayList<>(size); // this.types = new ArrayList<>(size); // } // // public Builder add(@NotNull String name, @NotNull Type type) { // if (built) throw new IllegalStateException("can't add items to builder that has been built"); // // names.add(requireNonNull(name)); // types.add(requireNonNull(type)); // return this; // } // // public @NotNull NamedTypeList build() { // built = true; // return new NamedTypeList(names, types); // } // } // } // Path: dalesbred/src/main/java/org/dalesbred/internal/jdbc/ResultSetUtils.java import org.dalesbred.DatabaseException; import org.dalesbred.internal.instantiation.NamedTypeList; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Type; import java.sql.ResultSetMetaData; import java.sql.SQLException; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.jdbc; /** * Utilities for processing {@link java.sql.ResultSet}s. */ public final class ResultSetUtils { private ResultSetUtils() { }
public static @NotNull NamedTypeList getTypes(@NotNull ResultSetMetaData metaData) throws SQLException {
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/jdbc/ResultSetUtils.java
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/NamedTypeList.java // public final class NamedTypeList { // // private final @NotNull List<String> names; // // private final @NotNull List<Type> types; // // private NamedTypeList(@NotNull List<String> names, @NotNull List<Type> types) { // assert names.size() == types.size(); // this.names = unmodifiableList(names); // this.types = types; // } // // public int size() { // return types.size(); // } // // public @NotNull String getName(int index) { // return names.get(index); // } // // public @NotNull Type getType(int index) { // return types.get(index); // } // // public @NotNull List<String> getNames() { // return names; // } // // public @NotNull NamedTypeList subList(int fromIndex, int toIndex) { // return new NamedTypeList(names.subList(fromIndex, toIndex), types.subList(fromIndex, toIndex)); // } // // @Override // public @NotNull String toString() { // int size = types.size(); // // @SuppressWarnings("MagicNumber") // StringBuilder sb = new StringBuilder(10 + size * 30); // // sb.append('['); // // for (int i = 0; i < size; i++) { // if (i != 0) sb.append(", "); // // sb.append(names.get(i)).append(": ").append(types.get(i).getTypeName()); // } // // sb.append(']'); // // return sb.toString(); // } // // public static @NotNull Builder builder(int size) { // return new Builder(size); // } // // /** // * Builder for {@link NamedTypeList}s. // */ // public static class Builder { // // private boolean built = false; // // private final @NotNull List<String> names; // // private final @NotNull List<Type> types; // // private Builder(int size) { // this.names = new ArrayList<>(size); // this.types = new ArrayList<>(size); // } // // public Builder add(@NotNull String name, @NotNull Type type) { // if (built) throw new IllegalStateException("can't add items to builder that has been built"); // // names.add(requireNonNull(name)); // types.add(requireNonNull(type)); // return this; // } // // public @NotNull NamedTypeList build() { // built = true; // return new NamedTypeList(names, types); // } // } // }
import org.dalesbred.DatabaseException; import org.dalesbred.internal.instantiation.NamedTypeList; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Type; import java.sql.ResultSetMetaData; import java.sql.SQLException;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.jdbc; /** * Utilities for processing {@link java.sql.ResultSet}s. */ public final class ResultSetUtils { private ResultSetUtils() { } public static @NotNull NamedTypeList getTypes(@NotNull ResultSetMetaData metaData) throws SQLException { int columns = metaData.getColumnCount(); NamedTypeList.Builder result = NamedTypeList.builder(columns); for (int i = 0; i < columns; i++) result.add(metaData.getColumnLabel(i+1), getColumnType(metaData, i + 1)); return result.build(); } public static @NotNull Type getColumnType(@NotNull ResultSetMetaData metaData, int column) throws SQLException { String className = metaData.getColumnClassName(column); try { return Class.forName(className); } catch (ClassNotFoundException e) {
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // // Path: dalesbred/src/main/java/org/dalesbred/internal/instantiation/NamedTypeList.java // public final class NamedTypeList { // // private final @NotNull List<String> names; // // private final @NotNull List<Type> types; // // private NamedTypeList(@NotNull List<String> names, @NotNull List<Type> types) { // assert names.size() == types.size(); // this.names = unmodifiableList(names); // this.types = types; // } // // public int size() { // return types.size(); // } // // public @NotNull String getName(int index) { // return names.get(index); // } // // public @NotNull Type getType(int index) { // return types.get(index); // } // // public @NotNull List<String> getNames() { // return names; // } // // public @NotNull NamedTypeList subList(int fromIndex, int toIndex) { // return new NamedTypeList(names.subList(fromIndex, toIndex), types.subList(fromIndex, toIndex)); // } // // @Override // public @NotNull String toString() { // int size = types.size(); // // @SuppressWarnings("MagicNumber") // StringBuilder sb = new StringBuilder(10 + size * 30); // // sb.append('['); // // for (int i = 0; i < size; i++) { // if (i != 0) sb.append(", "); // // sb.append(names.get(i)).append(": ").append(types.get(i).getTypeName()); // } // // sb.append(']'); // // return sb.toString(); // } // // public static @NotNull Builder builder(int size) { // return new Builder(size); // } // // /** // * Builder for {@link NamedTypeList}s. // */ // public static class Builder { // // private boolean built = false; // // private final @NotNull List<String> names; // // private final @NotNull List<Type> types; // // private Builder(int size) { // this.names = new ArrayList<>(size); // this.types = new ArrayList<>(size); // } // // public Builder add(@NotNull String name, @NotNull Type type) { // if (built) throw new IllegalStateException("can't add items to builder that has been built"); // // names.add(requireNonNull(name)); // types.add(requireNonNull(type)); // return this; // } // // public @NotNull NamedTypeList build() { // built = true; // return new NamedTypeList(names, types); // } // } // } // Path: dalesbred/src/main/java/org/dalesbred/internal/jdbc/ResultSetUtils.java import org.dalesbred.DatabaseException; import org.dalesbred.internal.instantiation.NamedTypeList; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Type; import java.sql.ResultSetMetaData; import java.sql.SQLException; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.jdbc; /** * Utilities for processing {@link java.sql.ResultSet}s. */ public final class ResultSetUtils { private ResultSetUtils() { } public static @NotNull NamedTypeList getTypes(@NotNull ResultSetMetaData metaData) throws SQLException { int columns = metaData.getColumnCount(); NamedTypeList.Builder result = NamedTypeList.builder(columns); for (int i = 0; i < columns; i++) result.add(metaData.getColumnLabel(i+1), getColumnType(metaData, i + 1)); return result.build(); } public static @NotNull Type getColumnType(@NotNull ResultSetMetaData metaData, int column) throws SQLException { String className = metaData.getColumnClassName(column); try { return Class.forName(className); } catch (ClassNotFoundException e) {
throw new DatabaseException("Could not find class '" + className + "' specified by ResultSet.", e);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/query/VariableResolver.java
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/ReflectionUtils.java // public final class ReflectionUtils { // // private ReflectionUtils() { // } // // public static @NotNull Optional<Field> findField(@NotNull Class<?> cl, @NotNull String name) { // try { // return Optional.of(cl.getField(name)); // } catch (NoSuchFieldException e) { // return Optional.empty(); // } // } // // public static @NotNull Optional<Method> findGetter(@NotNull Class<?> cl, @NotNull String propertyName) { // String capitalizedName = StringUtils.capitalize(propertyName); // // try { // return Optional.of(cl.getMethod("get" + capitalizedName)); // } catch (NoSuchMethodException e) { // try { // return Optional.of(cl.getMethod("is" + capitalizedName)); // } catch (NoSuchMethodException e1) { // return Optional.empty(); // } // } // } // // public static void makeAccessible(@NotNull Executable obj) throws SecurityException { // if (!isPublic(obj.getModifiers())) // obj.setAccessible(true); // } // }
import org.dalesbred.internal.utils.ReflectionUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.query; /** * Resolves values for variables appearing in SQL queries with named parameters. */ @FunctionalInterface public interface VariableResolver { /** * Returns the value of given variable, which could be null. * * @throws VariableResolutionException if resolution fails */ @Nullable Object getValue(@NotNull String variable); /** * Returns a {@link VariableResolver} that is backed by given map. */ static @NotNull VariableResolver forMap(@NotNull Map<String, ?> variables) { return variable -> { Object value = variables.get(variable); if (value != null || variables.containsKey(variable)) return value; else throw new VariableResolutionException("No value registered for key '" + variable + '\''); }; } /** * Returns a {@link VariableResolver} that is backed by given bean. When variables are looked up, * tries to find a matching getter or accessible field for the variable and returns its value. */ static @NotNull VariableResolver forBean(@NotNull Object object) { return variable -> { try {
// Path: dalesbred/src/main/java/org/dalesbred/internal/utils/ReflectionUtils.java // public final class ReflectionUtils { // // private ReflectionUtils() { // } // // public static @NotNull Optional<Field> findField(@NotNull Class<?> cl, @NotNull String name) { // try { // return Optional.of(cl.getField(name)); // } catch (NoSuchFieldException e) { // return Optional.empty(); // } // } // // public static @NotNull Optional<Method> findGetter(@NotNull Class<?> cl, @NotNull String propertyName) { // String capitalizedName = StringUtils.capitalize(propertyName); // // try { // return Optional.of(cl.getMethod("get" + capitalizedName)); // } catch (NoSuchMethodException e) { // try { // return Optional.of(cl.getMethod("is" + capitalizedName)); // } catch (NoSuchMethodException e1) { // return Optional.empty(); // } // } // } // // public static void makeAccessible(@NotNull Executable obj) throws SecurityException { // if (!isPublic(obj.getModifiers())) // obj.setAccessible(true); // } // } // Path: dalesbred/src/main/java/org/dalesbred/query/VariableResolver.java import org.dalesbred.internal.utils.ReflectionUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.query; /** * Resolves values for variables appearing in SQL queries with named parameters. */ @FunctionalInterface public interface VariableResolver { /** * Returns the value of given variable, which could be null. * * @throws VariableResolutionException if resolution fails */ @Nullable Object getValue(@NotNull String variable); /** * Returns a {@link VariableResolver} that is backed by given map. */ static @NotNull VariableResolver forMap(@NotNull Map<String, ?> variables) { return variable -> { Object value = variables.get(variable); if (value != null || variables.containsKey(variable)) return value; else throw new VariableResolutionException("No value registered for key '" + variable + '\''); }; } /** * Returns a {@link VariableResolver} that is backed by given bean. When variables are looked up, * tries to find a matching getter or accessible field for the variable and returns its value. */ static @NotNull VariableResolver forBean(@NotNull Object object) { return variable -> { try {
Method getter = ReflectionUtils.findGetter(object.getClass(), variable).orElse(null);
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/utils/JndiUtils.java
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // }
import org.dalesbred.DatabaseException; import org.jetbrains.annotations.NotNull; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource;
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.utils; public final class JndiUtils { private JndiUtils() { } public static @NotNull DataSource lookupJndiDataSource(@NotNull String jndiName) { try { InitialContext ctx = new InitialContext(); try { DataSource dataSource = (DataSource) ctx.lookup(jndiName); if (dataSource != null) return dataSource; else
// Path: dalesbred/src/main/java/org/dalesbred/DatabaseException.java // public class DatabaseException extends RuntimeException { // // private final @Nullable SqlQuery query = DebugContext.getCurrentQuery(); // // public DatabaseException(@NotNull String message) { // super(message); // } // // public DatabaseException(@NotNull Throwable cause) { // super(cause); // } // // public DatabaseException(@NotNull String message, @NotNull Throwable cause) { // super(message, cause); // } // // /** // * If this exception was thrown during an execution of a query, returns the query. Otherwise // * returns {@code null}. // */ // public @Nullable SqlQuery getQuery() { // return query; // } // // @Override // public @NotNull String toString() { // String basicToString = super.toString(); // if (query != null) // return basicToString + " (query: " + query + ')'; // else // return basicToString; // } // } // Path: dalesbred/src/main/java/org/dalesbred/internal/utils/JndiUtils.java import org.dalesbred.DatabaseException; import org.jetbrains.annotations.NotNull; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; /* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.internal.utils; public final class JndiUtils { private JndiUtils() { } public static @NotNull DataSource lookupJndiDataSource(@NotNull String jndiName) { try { InitialContext ctx = new InitialContext(); try { DataSource dataSource = (DataSource) ctx.lookup(jndiName); if (dataSource != null) return dataSource; else
throw new DatabaseException("Could not find DataSource '" + jndiName + '\'');
angelozerr/ec4e
org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/validation/marker/MarkerUtils.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/EditorConfigPlugin.java // public class EditorConfigPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.ec4e"; //$NON-NLS-1$ // // // The shared instance // private static EditorConfigPlugin plugin; // // /** // * The constructor // */ // public EditorConfigPlugin() { // } // // @Override // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // IDEEditorConfigManager.getInstance().init(); // } // // @Override // public void stop(BundleContext context) throws Exception { // IDEEditorConfigManager.getInstance().dispose(); // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EditorConfigPlugin getDefault() { // return plugin; // } // // /** // * Utility method to log errors. // * // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, thr.getMessage(), thr)); // } // // /** // * Utility method to log errors. // * // * @param message // * User comprehensible message // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final String message, final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, message, thr)); // } // // @Override // protected void initializeImageRegistry(ImageRegistry registry) { // EditorConfigImages.initalize(registry); // } // }
import java.util.Arrays; import java.util.List; import org.ec4j.core.model.PropertyType; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.ec4e.EditorConfigPlugin; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.RewriteSessionEditProcessor; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.TextEdit; import org.eclipse.text.undo.DocumentUndoManagerRegistry; import org.eclipse.text.undo.IDocumentUndoManager;
return resource.createMarker(EC_PROBLEM_MARKER_TYPE); } public static int getSeverity(org.ec4j.core.parser.ErrorEvent.ErrorType errorType) { return errorType.isSyntaxError() ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING; } /** * Method will apply all edits to document as single modification. Needs to * be executed in UI thread. * * @param document * document to modify * @param edits * list of LSP TextEdits */ public static void applyEdits(IDocument document, TextEdit edit) { if (document == null) { return; } IDocumentUndoManager manager = DocumentUndoManagerRegistry.getDocumentUndoManager(document); if (manager != null) { manager.beginCompoundChange(); } try { RewriteSessionEditProcessor editProcessor = new RewriteSessionEditProcessor(document, edit, org.eclipse.text.edits.TextEdit.NONE); editProcessor.performEdits(); } catch (MalformedTreeException | BadLocationException e) {
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/EditorConfigPlugin.java // public class EditorConfigPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.ec4e"; //$NON-NLS-1$ // // // The shared instance // private static EditorConfigPlugin plugin; // // /** // * The constructor // */ // public EditorConfigPlugin() { // } // // @Override // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // IDEEditorConfigManager.getInstance().init(); // } // // @Override // public void stop(BundleContext context) throws Exception { // IDEEditorConfigManager.getInstance().dispose(); // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EditorConfigPlugin getDefault() { // return plugin; // } // // /** // * Utility method to log errors. // * // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, thr.getMessage(), thr)); // } // // /** // * Utility method to log errors. // * // * @param message // * User comprehensible message // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final String message, final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, message, thr)); // } // // @Override // protected void initializeImageRegistry(ImageRegistry registry) { // EditorConfigImages.initalize(registry); // } // } // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/validation/marker/MarkerUtils.java import java.util.Arrays; import java.util.List; import org.ec4j.core.model.PropertyType; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.ec4e.EditorConfigPlugin; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.RewriteSessionEditProcessor; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.TextEdit; import org.eclipse.text.undo.DocumentUndoManagerRegistry; import org.eclipse.text.undo.IDocumentUndoManager; return resource.createMarker(EC_PROBLEM_MARKER_TYPE); } public static int getSeverity(org.ec4j.core.parser.ErrorEvent.ErrorType errorType) { return errorType.isSyntaxError() ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING; } /** * Method will apply all edits to document as single modification. Needs to * be executed in UI thread. * * @param document * document to modify * @param edits * list of LSP TextEdits */ public static void applyEdits(IDocument document, TextEdit edit) { if (document == null) { return; } IDocumentUndoManager manager = DocumentUndoManagerRegistry.getDocumentUndoManager(document); if (manager != null) { manager.beginCompoundChange(); } try { RewriteSessionEditProcessor editProcessor = new RewriteSessionEditProcessor(document, edit, org.eclipse.text.edits.TextEdit.NONE); editProcessor.performEdits(); } catch (MalformedTreeException | BadLocationException e) {
EditorConfigPlugin.logError(e);
angelozerr/ec4e
org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/validation/ValidateEditorConfigStrategy.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/validation/marker/MarkerUtils.java // public class MarkerUtils { // // private static final String EC_ATTRIBUTE_OPTION_TYPE = "ecOptionType"; //$NON-NLS-1$ // private static final String EC_PROBLEM_MARKER_TYPE = "org.eclipse.ec4e.problem"; //$NON-NLS-1$ // // public static PropertyType<?> getOptionType(IMarker marker) throws CoreException { // return (PropertyType<?>) marker.getAttribute(EC_ATTRIBUTE_OPTION_TYPE); // } // // public static boolean isOptionType(IMarker marker, String name) throws CoreException { // PropertyType<?> type = getOptionType(marker); // return type != null && type.getName().equals(name); // } // // public static void setOptionType(IMarker marker, PropertyType<?> type) throws CoreException { // marker.setAttribute(EC_ATTRIBUTE_OPTION_TYPE, type); // } // // public static boolean isEditorConfigMarker(IMarker marker) { // try { // return EC_PROBLEM_MARKER_TYPE.equals(marker.getType()); // } catch (CoreException e) { // return false; // } // } // // public static List<IMarker> findEditorConfigMarkers(IResource resource) throws CoreException { // return Arrays.asList(resource.findMarkers(EC_PROBLEM_MARKER_TYPE, false, IResource.DEPTH_ONE)); // } // // public static IMarker createEditorConfigMarker(IResource resource) throws CoreException { // return resource.createMarker(EC_PROBLEM_MARKER_TYPE); // } // // public static int getSeverity(org.ec4j.core.parser.ErrorEvent.ErrorType errorType) { // return errorType.isSyntaxError() ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING; // } // // /** // * Method will apply all edits to document as single modification. Needs to // * be executed in UI thread. // * // * @param document // * document to modify // * @param edits // * list of LSP TextEdits // */ // public static void applyEdits(IDocument document, TextEdit edit) { // if (document == null) { // return; // } // // IDocumentUndoManager manager = DocumentUndoManagerRegistry.getDocumentUndoManager(document); // if (manager != null) { // manager.beginCompoundChange(); // } // try { // RewriteSessionEditProcessor editProcessor = new RewriteSessionEditProcessor(document, edit, // org.eclipse.text.edits.TextEdit.NONE); // editProcessor.performEdits(); // } catch (MalformedTreeException | BadLocationException e) { // EditorConfigPlugin.logError(e); // } // if (manager != null) { // manager.endCompoundChange(); // } // } // }
import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Resource; import org.ec4j.core.ide.IdeSupportService; import org.ec4j.core.parser.EditorConfigHandler; import org.ec4j.core.parser.EditorConfigParser; import org.ec4j.core.parser.ErrorEvent; import org.ec4j.core.parser.ErrorHandler; import org.ec4j.core.parser.ParseContext; import org.ec4j.core.parser.ValidatingHandler; import org.eclipse.core.filebuffers.FileBuffers; import org.eclipse.core.filebuffers.ITextFileBuffer; import org.eclipse.core.filebuffers.ITextFileBufferManager; import org.eclipse.core.filebuffers.LocationKind; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.ec4e.internal.validation.marker.MarkerUtils; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.reconciler.DirtyRegion; import org.eclipse.jface.text.reconciler.IReconciler; import org.eclipse.jface.text.reconciler.IReconcilingStrategy; import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension; import org.eclipse.ui.texteditor.MarkerUtilities;
package org.eclipse.ec4e.internal.validation; public class ValidateEditorConfigStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension, IReconciler { private ITextViewer textViewer; private IResource resource; public ValidateEditorConfigStrategy(IResource resource) { this.resource = resource; } @Override public void setProgressMonitor(IProgressMonitor monitor) { } @Override public void initialReconcile() { } @Override public void setDocument(IDocument document) { } @Override public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { if (textViewer == null) { return; } try { IDocument document = textViewer.getDocument();
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/validation/marker/MarkerUtils.java // public class MarkerUtils { // // private static final String EC_ATTRIBUTE_OPTION_TYPE = "ecOptionType"; //$NON-NLS-1$ // private static final String EC_PROBLEM_MARKER_TYPE = "org.eclipse.ec4e.problem"; //$NON-NLS-1$ // // public static PropertyType<?> getOptionType(IMarker marker) throws CoreException { // return (PropertyType<?>) marker.getAttribute(EC_ATTRIBUTE_OPTION_TYPE); // } // // public static boolean isOptionType(IMarker marker, String name) throws CoreException { // PropertyType<?> type = getOptionType(marker); // return type != null && type.getName().equals(name); // } // // public static void setOptionType(IMarker marker, PropertyType<?> type) throws CoreException { // marker.setAttribute(EC_ATTRIBUTE_OPTION_TYPE, type); // } // // public static boolean isEditorConfigMarker(IMarker marker) { // try { // return EC_PROBLEM_MARKER_TYPE.equals(marker.getType()); // } catch (CoreException e) { // return false; // } // } // // public static List<IMarker> findEditorConfigMarkers(IResource resource) throws CoreException { // return Arrays.asList(resource.findMarkers(EC_PROBLEM_MARKER_TYPE, false, IResource.DEPTH_ONE)); // } // // public static IMarker createEditorConfigMarker(IResource resource) throws CoreException { // return resource.createMarker(EC_PROBLEM_MARKER_TYPE); // } // // public static int getSeverity(org.ec4j.core.parser.ErrorEvent.ErrorType errorType) { // return errorType.isSyntaxError() ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING; // } // // /** // * Method will apply all edits to document as single modification. Needs to // * be executed in UI thread. // * // * @param document // * document to modify // * @param edits // * list of LSP TextEdits // */ // public static void applyEdits(IDocument document, TextEdit edit) { // if (document == null) { // return; // } // // IDocumentUndoManager manager = DocumentUndoManagerRegistry.getDocumentUndoManager(document); // if (manager != null) { // manager.beginCompoundChange(); // } // try { // RewriteSessionEditProcessor editProcessor = new RewriteSessionEditProcessor(document, edit, // org.eclipse.text.edits.TextEdit.NONE); // editProcessor.performEdits(); // } catch (MalformedTreeException | BadLocationException e) { // EditorConfigPlugin.logError(e); // } // if (manager != null) { // manager.endCompoundChange(); // } // } // } // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/validation/ValidateEditorConfigStrategy.java import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Resource; import org.ec4j.core.ide.IdeSupportService; import org.ec4j.core.parser.EditorConfigHandler; import org.ec4j.core.parser.EditorConfigParser; import org.ec4j.core.parser.ErrorEvent; import org.ec4j.core.parser.ErrorHandler; import org.ec4j.core.parser.ParseContext; import org.ec4j.core.parser.ValidatingHandler; import org.eclipse.core.filebuffers.FileBuffers; import org.eclipse.core.filebuffers.ITextFileBuffer; import org.eclipse.core.filebuffers.ITextFileBufferManager; import org.eclipse.core.filebuffers.LocationKind; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.ec4e.internal.validation.marker.MarkerUtils; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.reconciler.DirtyRegion; import org.eclipse.jface.text.reconciler.IReconciler; import org.eclipse.jface.text.reconciler.IReconcilingStrategy; import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension; import org.eclipse.ui.texteditor.MarkerUtilities; package org.eclipse.ec4e.internal.validation; public class ValidateEditorConfigStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension, IReconciler { private ITextViewer textViewer; private IResource resource; public ValidateEditorConfigStrategy(IResource resource) { this.resource = resource; } @Override public void setProgressMonitor(IProgressMonitor monitor) { } @Override public void initialReconcile() { } @Override public void setDocument(IDocument document) { } @Override public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { if (textViewer == null) { return; } try { IDocument document = textViewer.getDocument();
Set<IMarker> remainingMarkers = MarkerUtils.findEditorConfigMarkers(resource).stream().filter(marker -> {
angelozerr/ec4e
org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/search/EditorConfigSearchQuery.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/EditorConfigPlugin.java // public class EditorConfigPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.ec4e"; //$NON-NLS-1$ // // // The shared instance // private static EditorConfigPlugin plugin; // // /** // * The constructor // */ // public EditorConfigPlugin() { // } // // @Override // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // IDEEditorConfigManager.getInstance().init(); // } // // @Override // public void stop(BundleContext context) throws Exception { // IDEEditorConfigManager.getInstance().dispose(); // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EditorConfigPlugin getDefault() { // return plugin; // } // // /** // * Utility method to log errors. // * // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, thr.getMessage(), thr)); // } // // /** // * Utility method to log errors. // * // * @param message // * User comprehensible message // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final String message, final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, message, thr)); // } // // @Override // protected void initializeImageRegistry(ImageRegistry registry) { // EditorConfigImages.initalize(registry); // } // } // // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorConfigMessages.java // public class EditorConfigMessages extends NLS { // // private static final String BUNDLE_NAME = "org.eclipse.ec4e.internal.EditorConfigMessages"; //$NON-NLS-1$ // // // Buttons // public static String Browse_button; // // // Wizards // public static String NewEditorConfigWizard_windowTitle; // public static String NewEditorConfigFileWizardPage_title; // public static String NewEditorConfigFileWizardPage_description; // public static String NewEditorConfigFileWizardPage_folderText_Label; // public static String NewEditorConfigFileWizardPage_containerSelectionDialog_title; // public static String NewEditorConfigFileWizardPage_folder_required_error; // public static String NewEditorConfigFileWizardPage_folder_noexists_error; // public static String NewEditorConfigFileWizardPage_project_noaccessible_error; // public static String NewEditorConfigFileWizardPage_folder_already_editorconfig_error; // // // Search // public static String EditorConfigSearchQuery_label; // public static String EditorConfigSearchQuery_singularReference; // public static String EditorConfigSearchQuery_pluralReferences; // // static { // NLS.initializeMessages(BUNDLE_NAME, EditorConfigMessages.class); // } // // }
import org.ec4j.core.model.Section; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceProxy; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.ec4e.EditorConfigPlugin; import org.eclipse.ec4e.internal.EditorConfigMessages; import org.eclipse.osgi.util.NLS; import org.eclipse.search.internal.ui.text.FileMatch; import org.eclipse.search.internal.ui.text.FileSearchQuery; import org.eclipse.search.ui.ISearchQuery; import org.eclipse.search.ui.ISearchResult; import org.eclipse.search.ui.text.AbstractTextSearchResult; import org.eclipse.search.ui.text.Match;
package org.eclipse.ec4e.search; /** * {@link ISearchQuery} implementation for EditorConfig section matching files. * */ public class EditorConfigSearchQuery extends FileSearchQuery { private final Section section; private final IFile configFile; private EditorConfigSearchResult result; private long startTime; /** * EditorConfig section matching files query to "Find matching files" from the * given section * * @param section * @param configFile */ public EditorConfigSearchQuery(Section section, IFile configFile) { super("", false, false, null); //$NON-NLS-1$ this.section = section; this.configFile = configFile; } @Override public IStatus run(IProgressMonitor monitor) throws OperationCanceledException { startTime = System.currentTimeMillis(); AbstractTextSearchResult textResult = (AbstractTextSearchResult) getSearchResult(); textResult.removeAll(); try { IContainer dir = configFile.getParent(); dir.accept(new AbstractSectionPatternVisitor(section) { @Override protected void collect(IResourceProxy proxy) { Match match = new FileMatch((IFile) proxy.requestResource()); result.addMatch(match); } }, IResource.NONE); return Status.OK_STATUS; } catch (Exception ex) {
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/EditorConfigPlugin.java // public class EditorConfigPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.ec4e"; //$NON-NLS-1$ // // // The shared instance // private static EditorConfigPlugin plugin; // // /** // * The constructor // */ // public EditorConfigPlugin() { // } // // @Override // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // IDEEditorConfigManager.getInstance().init(); // } // // @Override // public void stop(BundleContext context) throws Exception { // IDEEditorConfigManager.getInstance().dispose(); // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EditorConfigPlugin getDefault() { // return plugin; // } // // /** // * Utility method to log errors. // * // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, thr.getMessage(), thr)); // } // // /** // * Utility method to log errors. // * // * @param message // * User comprehensible message // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final String message, final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, message, thr)); // } // // @Override // protected void initializeImageRegistry(ImageRegistry registry) { // EditorConfigImages.initalize(registry); // } // } // // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorConfigMessages.java // public class EditorConfigMessages extends NLS { // // private static final String BUNDLE_NAME = "org.eclipse.ec4e.internal.EditorConfigMessages"; //$NON-NLS-1$ // // // Buttons // public static String Browse_button; // // // Wizards // public static String NewEditorConfigWizard_windowTitle; // public static String NewEditorConfigFileWizardPage_title; // public static String NewEditorConfigFileWizardPage_description; // public static String NewEditorConfigFileWizardPage_folderText_Label; // public static String NewEditorConfigFileWizardPage_containerSelectionDialog_title; // public static String NewEditorConfigFileWizardPage_folder_required_error; // public static String NewEditorConfigFileWizardPage_folder_noexists_error; // public static String NewEditorConfigFileWizardPage_project_noaccessible_error; // public static String NewEditorConfigFileWizardPage_folder_already_editorconfig_error; // // // Search // public static String EditorConfigSearchQuery_label; // public static String EditorConfigSearchQuery_singularReference; // public static String EditorConfigSearchQuery_pluralReferences; // // static { // NLS.initializeMessages(BUNDLE_NAME, EditorConfigMessages.class); // } // // } // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/search/EditorConfigSearchQuery.java import org.ec4j.core.model.Section; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceProxy; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.ec4e.EditorConfigPlugin; import org.eclipse.ec4e.internal.EditorConfigMessages; import org.eclipse.osgi.util.NLS; import org.eclipse.search.internal.ui.text.FileMatch; import org.eclipse.search.internal.ui.text.FileSearchQuery; import org.eclipse.search.ui.ISearchQuery; import org.eclipse.search.ui.ISearchResult; import org.eclipse.search.ui.text.AbstractTextSearchResult; import org.eclipse.search.ui.text.Match; package org.eclipse.ec4e.search; /** * {@link ISearchQuery} implementation for EditorConfig section matching files. * */ public class EditorConfigSearchQuery extends FileSearchQuery { private final Section section; private final IFile configFile; private EditorConfigSearchResult result; private long startTime; /** * EditorConfig section matching files query to "Find matching files" from the * given section * * @param section * @param configFile */ public EditorConfigSearchQuery(Section section, IFile configFile) { super("", false, false, null); //$NON-NLS-1$ this.section = section; this.configFile = configFile; } @Override public IStatus run(IProgressMonitor monitor) throws OperationCanceledException { startTime = System.currentTimeMillis(); AbstractTextSearchResult textResult = (AbstractTextSearchResult) getSearchResult(); textResult.removeAll(); try { IContainer dir = configFile.getParent(); dir.accept(new AbstractSectionPatternVisitor(section) { @Override protected void collect(IResourceProxy proxy) { Match match = new FileMatch((IFile) proxy.requestResource()); result.addMatch(match); } }, IResource.NONE); return Status.OK_STATUS; } catch (Exception ex) {
return new Status(IStatus.ERROR, EditorConfigPlugin.PLUGIN_ID, ex.getMessage(), ex);
angelozerr/ec4e
org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/search/EditorConfigSearchQuery.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/EditorConfigPlugin.java // public class EditorConfigPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.ec4e"; //$NON-NLS-1$ // // // The shared instance // private static EditorConfigPlugin plugin; // // /** // * The constructor // */ // public EditorConfigPlugin() { // } // // @Override // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // IDEEditorConfigManager.getInstance().init(); // } // // @Override // public void stop(BundleContext context) throws Exception { // IDEEditorConfigManager.getInstance().dispose(); // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EditorConfigPlugin getDefault() { // return plugin; // } // // /** // * Utility method to log errors. // * // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, thr.getMessage(), thr)); // } // // /** // * Utility method to log errors. // * // * @param message // * User comprehensible message // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final String message, final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, message, thr)); // } // // @Override // protected void initializeImageRegistry(ImageRegistry registry) { // EditorConfigImages.initalize(registry); // } // } // // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorConfigMessages.java // public class EditorConfigMessages extends NLS { // // private static final String BUNDLE_NAME = "org.eclipse.ec4e.internal.EditorConfigMessages"; //$NON-NLS-1$ // // // Buttons // public static String Browse_button; // // // Wizards // public static String NewEditorConfigWizard_windowTitle; // public static String NewEditorConfigFileWizardPage_title; // public static String NewEditorConfigFileWizardPage_description; // public static String NewEditorConfigFileWizardPage_folderText_Label; // public static String NewEditorConfigFileWizardPage_containerSelectionDialog_title; // public static String NewEditorConfigFileWizardPage_folder_required_error; // public static String NewEditorConfigFileWizardPage_folder_noexists_error; // public static String NewEditorConfigFileWizardPage_project_noaccessible_error; // public static String NewEditorConfigFileWizardPage_folder_already_editorconfig_error; // // // Search // public static String EditorConfigSearchQuery_label; // public static String EditorConfigSearchQuery_singularReference; // public static String EditorConfigSearchQuery_pluralReferences; // // static { // NLS.initializeMessages(BUNDLE_NAME, EditorConfigMessages.class); // } // // }
import org.ec4j.core.model.Section; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceProxy; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.ec4e.EditorConfigPlugin; import org.eclipse.ec4e.internal.EditorConfigMessages; import org.eclipse.osgi.util.NLS; import org.eclipse.search.internal.ui.text.FileMatch; import org.eclipse.search.internal.ui.text.FileSearchQuery; import org.eclipse.search.ui.ISearchQuery; import org.eclipse.search.ui.ISearchResult; import org.eclipse.search.ui.text.AbstractTextSearchResult; import org.eclipse.search.ui.text.Match;
textResult.removeAll(); try { IContainer dir = configFile.getParent(); dir.accept(new AbstractSectionPatternVisitor(section) { @Override protected void collect(IResourceProxy proxy) { Match match = new FileMatch((IFile) proxy.requestResource()); result.addMatch(match); } }, IResource.NONE); return Status.OK_STATUS; } catch (Exception ex) { return new Status(IStatus.ERROR, EditorConfigPlugin.PLUGIN_ID, ex.getMessage(), ex); } } @Override public ISearchResult getSearchResult() { if (result == null) { result = new EditorConfigSearchResult(this); } return result; } @Override public String getLabel() {
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/EditorConfigPlugin.java // public class EditorConfigPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.ec4e"; //$NON-NLS-1$ // // // The shared instance // private static EditorConfigPlugin plugin; // // /** // * The constructor // */ // public EditorConfigPlugin() { // } // // @Override // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // IDEEditorConfigManager.getInstance().init(); // } // // @Override // public void stop(BundleContext context) throws Exception { // IDEEditorConfigManager.getInstance().dispose(); // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EditorConfigPlugin getDefault() { // return plugin; // } // // /** // * Utility method to log errors. // * // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, thr.getMessage(), thr)); // } // // /** // * Utility method to log errors. // * // * @param message // * User comprehensible message // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final String message, final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, message, thr)); // } // // @Override // protected void initializeImageRegistry(ImageRegistry registry) { // EditorConfigImages.initalize(registry); // } // } // // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorConfigMessages.java // public class EditorConfigMessages extends NLS { // // private static final String BUNDLE_NAME = "org.eclipse.ec4e.internal.EditorConfigMessages"; //$NON-NLS-1$ // // // Buttons // public static String Browse_button; // // // Wizards // public static String NewEditorConfigWizard_windowTitle; // public static String NewEditorConfigFileWizardPage_title; // public static String NewEditorConfigFileWizardPage_description; // public static String NewEditorConfigFileWizardPage_folderText_Label; // public static String NewEditorConfigFileWizardPage_containerSelectionDialog_title; // public static String NewEditorConfigFileWizardPage_folder_required_error; // public static String NewEditorConfigFileWizardPage_folder_noexists_error; // public static String NewEditorConfigFileWizardPage_project_noaccessible_error; // public static String NewEditorConfigFileWizardPage_folder_already_editorconfig_error; // // // Search // public static String EditorConfigSearchQuery_label; // public static String EditorConfigSearchQuery_singularReference; // public static String EditorConfigSearchQuery_pluralReferences; // // static { // NLS.initializeMessages(BUNDLE_NAME, EditorConfigMessages.class); // } // // } // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/search/EditorConfigSearchQuery.java import org.ec4j.core.model.Section; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceProxy; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.ec4e.EditorConfigPlugin; import org.eclipse.ec4e.internal.EditorConfigMessages; import org.eclipse.osgi.util.NLS; import org.eclipse.search.internal.ui.text.FileMatch; import org.eclipse.search.internal.ui.text.FileSearchQuery; import org.eclipse.search.ui.ISearchQuery; import org.eclipse.search.ui.ISearchResult; import org.eclipse.search.ui.text.AbstractTextSearchResult; import org.eclipse.search.ui.text.Match; textResult.removeAll(); try { IContainer dir = configFile.getParent(); dir.accept(new AbstractSectionPatternVisitor(section) { @Override protected void collect(IResourceProxy proxy) { Match match = new FileMatch((IFile) proxy.requestResource()); result.addMatch(match); } }, IResource.NONE); return Status.OK_STATUS; } catch (Exception ex) { return new Status(IStatus.ERROR, EditorConfigPlugin.PLUGIN_ID, ex.getMessage(), ex); } } @Override public ISearchResult getSearchResult() { if (result == null) { result = new EditorConfigSearchResult(this); } return result; } @Override public String getLabel() {
return EditorConfigMessages.EditorConfigSearchQuery_label;
angelozerr/ec4e
org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/completion/EditorConfigCompletionProposal.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorConfigImages.java // public class EditorConfigImages { // // private static final String ICONS_PATH = "$nl$/icons/full/"; //$NON-NLS-1$ // private static final String OBJECT = ICONS_PATH + "obj16/"; // basic colors - size 16x16 //$NON-NLS-1$ // // public static final String IMG_PROPERTY = "IMG_PROPERTY"; //$NON-NLS-1$ // public static final String IMG_VALUE = "IMG_VALUE"; //$NON-NLS-1$ // // private EditorConfigImages() { // } // // private static ImageRegistry imageRegistry; // // public static void initalize(ImageRegistry registry) { // imageRegistry = registry; // // declareRegistryImage(IMG_PROPERTY, OBJECT + "property.png"); //$NON-NLS-1$ // declareRegistryImage(IMG_VALUE, OBJECT + "value.png"); //$NON-NLS-1$ // } // // private final static void declareRegistryImage(String key, String path) { // ImageDescriptor desc = ImageDescriptor.getMissingImageDescriptor(); // Bundle bundle = Platform.getBundle(EditorConfigPlugin.PLUGIN_ID); // URL url = null; // if (bundle != null) { // url = FileLocator.find(bundle, new Path(path), null); // if (url != null) { // desc = ImageDescriptor.createFromURL(url); // } // } // imageRegistry.put(key, desc); // } // // /** // * Returns the <code>Image</code> identified by the given key, or // * <code>null</code> if it does not exist. // */ // public static Image getImage(String key) { // return getImageRegistry().get(key); // } // // /** // * Returns the <code>ImageDescriptor</code> identified by the given key, or // * <code>null</code> if it does not exist. // */ // public static ImageDescriptor getImageDescriptor(String key) { // return getImageRegistry().getDescriptor(key); // } // // public static ImageRegistry getImageRegistry() { // if (imageRegistry == null) { // imageRegistry = EditorConfigPlugin.getDefault().getImageRegistry(); // } // return imageRegistry; // } // // }
import org.ec4j.core.ide.TokenContext.TokenContextType; import org.ec4j.core.ide.completion.CompletionEntry; import org.ec4j.core.model.PropertyType; import org.eclipse.ec4e.internal.EditorConfigImages; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.contentassist.BoldStylerProvider; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension7; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.link.ILinkedModeListener; import org.eclipse.jface.text.link.InclusivePositionUpdater; import org.eclipse.jface.text.link.LinkedModeModel; import org.eclipse.jface.text.link.LinkedModeUI; import org.eclipse.jface.text.link.LinkedModeUI.ExitFlags; import org.eclipse.jface.text.link.LinkedModeUI.IExitPolicy; import org.eclipse.jface.text.link.LinkedPositionGroup; import org.eclipse.jface.text.link.ProposalPosition; import org.eclipse.jface.viewers.StyledString; import org.eclipse.swt.SWT; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.ui.texteditor.link.EditorLinkedModeUI;
private boolean insertCompletion() { return true; } @Override public Point getSelection(IDocument document) { initIfNeeded(); if (fSelectedRegion == null) { return new Point(getReplacementOffset(), 0); } return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); } @Override public String getAdditionalProposalInfo() { initIfNeeded(); PropertyType<?> optionType = completionEntry.getPropertyType(); return optionType != null ? optionType.getDescription() : null; } @Override public String getDisplayString() { initIfNeeded(); return completionEntry.getName(); } @Override public Image getImage() { switch (completionEntry.getContextType()) { case PROPERTY_NAME:
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorConfigImages.java // public class EditorConfigImages { // // private static final String ICONS_PATH = "$nl$/icons/full/"; //$NON-NLS-1$ // private static final String OBJECT = ICONS_PATH + "obj16/"; // basic colors - size 16x16 //$NON-NLS-1$ // // public static final String IMG_PROPERTY = "IMG_PROPERTY"; //$NON-NLS-1$ // public static final String IMG_VALUE = "IMG_VALUE"; //$NON-NLS-1$ // // private EditorConfigImages() { // } // // private static ImageRegistry imageRegistry; // // public static void initalize(ImageRegistry registry) { // imageRegistry = registry; // // declareRegistryImage(IMG_PROPERTY, OBJECT + "property.png"); //$NON-NLS-1$ // declareRegistryImage(IMG_VALUE, OBJECT + "value.png"); //$NON-NLS-1$ // } // // private final static void declareRegistryImage(String key, String path) { // ImageDescriptor desc = ImageDescriptor.getMissingImageDescriptor(); // Bundle bundle = Platform.getBundle(EditorConfigPlugin.PLUGIN_ID); // URL url = null; // if (bundle != null) { // url = FileLocator.find(bundle, new Path(path), null); // if (url != null) { // desc = ImageDescriptor.createFromURL(url); // } // } // imageRegistry.put(key, desc); // } // // /** // * Returns the <code>Image</code> identified by the given key, or // * <code>null</code> if it does not exist. // */ // public static Image getImage(String key) { // return getImageRegistry().get(key); // } // // /** // * Returns the <code>ImageDescriptor</code> identified by the given key, or // * <code>null</code> if it does not exist. // */ // public static ImageDescriptor getImageDescriptor(String key) { // return getImageRegistry().getDescriptor(key); // } // // public static ImageRegistry getImageRegistry() { // if (imageRegistry == null) { // imageRegistry = EditorConfigPlugin.getDefault().getImageRegistry(); // } // return imageRegistry; // } // // } // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/completion/EditorConfigCompletionProposal.java import org.ec4j.core.ide.TokenContext.TokenContextType; import org.ec4j.core.ide.completion.CompletionEntry; import org.ec4j.core.model.PropertyType; import org.eclipse.ec4e.internal.EditorConfigImages; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.contentassist.BoldStylerProvider; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension7; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.link.ILinkedModeListener; import org.eclipse.jface.text.link.InclusivePositionUpdater; import org.eclipse.jface.text.link.LinkedModeModel; import org.eclipse.jface.text.link.LinkedModeUI; import org.eclipse.jface.text.link.LinkedModeUI.ExitFlags; import org.eclipse.jface.text.link.LinkedModeUI.IExitPolicy; import org.eclipse.jface.text.link.LinkedPositionGroup; import org.eclipse.jface.text.link.ProposalPosition; import org.eclipse.jface.viewers.StyledString; import org.eclipse.swt.SWT; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.ui.texteditor.link.EditorLinkedModeUI; private boolean insertCompletion() { return true; } @Override public Point getSelection(IDocument document) { initIfNeeded(); if (fSelectedRegion == null) { return new Point(getReplacementOffset(), 0); } return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); } @Override public String getAdditionalProposalInfo() { initIfNeeded(); PropertyType<?> optionType = completionEntry.getPropertyType(); return optionType != null ? optionType.getDescription() : null; } @Override public String getDisplayString() { initIfNeeded(); return completionEntry.getName(); } @Override public Image getImage() { switch (completionEntry.getContextType()) { case PROPERTY_NAME:
return EditorConfigImages.getImage(EditorConfigImages.IMG_PROPERTY);
angelozerr/ec4e
org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/EditorConfigPlugin.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorConfigImages.java // public class EditorConfigImages { // // private static final String ICONS_PATH = "$nl$/icons/full/"; //$NON-NLS-1$ // private static final String OBJECT = ICONS_PATH + "obj16/"; // basic colors - size 16x16 //$NON-NLS-1$ // // public static final String IMG_PROPERTY = "IMG_PROPERTY"; //$NON-NLS-1$ // public static final String IMG_VALUE = "IMG_VALUE"; //$NON-NLS-1$ // // private EditorConfigImages() { // } // // private static ImageRegistry imageRegistry; // // public static void initalize(ImageRegistry registry) { // imageRegistry = registry; // // declareRegistryImage(IMG_PROPERTY, OBJECT + "property.png"); //$NON-NLS-1$ // declareRegistryImage(IMG_VALUE, OBJECT + "value.png"); //$NON-NLS-1$ // } // // private final static void declareRegistryImage(String key, String path) { // ImageDescriptor desc = ImageDescriptor.getMissingImageDescriptor(); // Bundle bundle = Platform.getBundle(EditorConfigPlugin.PLUGIN_ID); // URL url = null; // if (bundle != null) { // url = FileLocator.find(bundle, new Path(path), null); // if (url != null) { // desc = ImageDescriptor.createFromURL(url); // } // } // imageRegistry.put(key, desc); // } // // /** // * Returns the <code>Image</code> identified by the given key, or // * <code>null</code> if it does not exist. // */ // public static Image getImage(String key) { // return getImageRegistry().get(key); // } // // /** // * Returns the <code>ImageDescriptor</code> identified by the given key, or // * <code>null</code> if it does not exist. // */ // public static ImageDescriptor getImageDescriptor(String key) { // return getImageRegistry().getDescriptor(key); // } // // public static ImageRegistry getImageRegistry() { // if (imageRegistry == null) { // imageRegistry = EditorConfigPlugin.getDefault().getImageRegistry(); // } // return imageRegistry; // } // // }
import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.ec4e.internal.EditorConfigImages; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext;
/** * Copyright (c) 2017 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.ec4e; /** * The activator class controls the plug-in life cycle */ public class EditorConfigPlugin extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "org.eclipse.ec4e"; //$NON-NLS-1$ // The shared instance private static EditorConfigPlugin plugin; /** * The constructor */ public EditorConfigPlugin() { } @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; IDEEditorConfigManager.getInstance().init(); } @Override public void stop(BundleContext context) throws Exception { IDEEditorConfigManager.getInstance().dispose(); plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static EditorConfigPlugin getDefault() { return plugin; } /** * Utility method to log errors. * * @param thr * The exception through which we noticed the error */ public static void logError(final Throwable thr) { getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, thr.getMessage(), thr)); } /** * Utility method to log errors. * * @param message * User comprehensible message * @param thr * The exception through which we noticed the error */ public static void logError(final String message, final Throwable thr) { getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, message, thr)); } @Override protected void initializeImageRegistry(ImageRegistry registry) {
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorConfigImages.java // public class EditorConfigImages { // // private static final String ICONS_PATH = "$nl$/icons/full/"; //$NON-NLS-1$ // private static final String OBJECT = ICONS_PATH + "obj16/"; // basic colors - size 16x16 //$NON-NLS-1$ // // public static final String IMG_PROPERTY = "IMG_PROPERTY"; //$NON-NLS-1$ // public static final String IMG_VALUE = "IMG_VALUE"; //$NON-NLS-1$ // // private EditorConfigImages() { // } // // private static ImageRegistry imageRegistry; // // public static void initalize(ImageRegistry registry) { // imageRegistry = registry; // // declareRegistryImage(IMG_PROPERTY, OBJECT + "property.png"); //$NON-NLS-1$ // declareRegistryImage(IMG_VALUE, OBJECT + "value.png"); //$NON-NLS-1$ // } // // private final static void declareRegistryImage(String key, String path) { // ImageDescriptor desc = ImageDescriptor.getMissingImageDescriptor(); // Bundle bundle = Platform.getBundle(EditorConfigPlugin.PLUGIN_ID); // URL url = null; // if (bundle != null) { // url = FileLocator.find(bundle, new Path(path), null); // if (url != null) { // desc = ImageDescriptor.createFromURL(url); // } // } // imageRegistry.put(key, desc); // } // // /** // * Returns the <code>Image</code> identified by the given key, or // * <code>null</code> if it does not exist. // */ // public static Image getImage(String key) { // return getImageRegistry().get(key); // } // // /** // * Returns the <code>ImageDescriptor</code> identified by the given key, or // * <code>null</code> if it does not exist. // */ // public static ImageDescriptor getImageDescriptor(String key) { // return getImageRegistry().getDescriptor(key); // } // // public static ImageRegistry getImageRegistry() { // if (imageRegistry == null) { // imageRegistry = EditorConfigPlugin.getDefault().getImageRegistry(); // } // return imageRegistry; // } // // } // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/EditorConfigPlugin.java import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.ec4e.internal.EditorConfigImages; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * Copyright (c) 2017 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.ec4e; /** * The activator class controls the plug-in life cycle */ public class EditorConfigPlugin extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "org.eclipse.ec4e"; //$NON-NLS-1$ // The shared instance private static EditorConfigPlugin plugin; /** * The constructor */ public EditorConfigPlugin() { } @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; IDEEditorConfigManager.getInstance().init(); } @Override public void stop(BundleContext context) throws Exception { IDEEditorConfigManager.getInstance().dispose(); plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static EditorConfigPlugin getDefault() { return plugin; } /** * Utility method to log errors. * * @param thr * The exception through which we noticed the error */ public static void logError(final Throwable thr) { getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, thr.getMessage(), thr)); } /** * Utility method to log errors. * * @param message * User comprehensible message * @param thr * The exception through which we noticed the error */ public static void logError(final String message, final Throwable thr) { getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, message, thr)); } @Override protected void initializeImageRegistry(ImageRegistry registry) {
EditorConfigImages.initalize(registry);
angelozerr/ec4e
org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorConfigImages.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/EditorConfigPlugin.java // public class EditorConfigPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.ec4e"; //$NON-NLS-1$ // // // The shared instance // private static EditorConfigPlugin plugin; // // /** // * The constructor // */ // public EditorConfigPlugin() { // } // // @Override // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // IDEEditorConfigManager.getInstance().init(); // } // // @Override // public void stop(BundleContext context) throws Exception { // IDEEditorConfigManager.getInstance().dispose(); // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EditorConfigPlugin getDefault() { // return plugin; // } // // /** // * Utility method to log errors. // * // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, thr.getMessage(), thr)); // } // // /** // * Utility method to log errors. // * // * @param message // * User comprehensible message // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final String message, final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, message, thr)); // } // // @Override // protected void initializeImageRegistry(ImageRegistry registry) { // EditorConfigImages.initalize(registry); // } // }
import java.net.URL; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.ec4e.EditorConfigPlugin; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; import org.osgi.framework.Bundle;
/** * Copyright (c) 2017 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.ec4e.internal; /** * Images for .editorconfig * */ public class EditorConfigImages { private static final String ICONS_PATH = "$nl$/icons/full/"; //$NON-NLS-1$ private static final String OBJECT = ICONS_PATH + "obj16/"; // basic colors - size 16x16 //$NON-NLS-1$ public static final String IMG_PROPERTY = "IMG_PROPERTY"; //$NON-NLS-1$ public static final String IMG_VALUE = "IMG_VALUE"; //$NON-NLS-1$ private EditorConfigImages() { } private static ImageRegistry imageRegistry; public static void initalize(ImageRegistry registry) { imageRegistry = registry; declareRegistryImage(IMG_PROPERTY, OBJECT + "property.png"); //$NON-NLS-1$ declareRegistryImage(IMG_VALUE, OBJECT + "value.png"); //$NON-NLS-1$ } private final static void declareRegistryImage(String key, String path) { ImageDescriptor desc = ImageDescriptor.getMissingImageDescriptor();
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/EditorConfigPlugin.java // public class EditorConfigPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.ec4e"; //$NON-NLS-1$ // // // The shared instance // private static EditorConfigPlugin plugin; // // /** // * The constructor // */ // public EditorConfigPlugin() { // } // // @Override // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // IDEEditorConfigManager.getInstance().init(); // } // // @Override // public void stop(BundleContext context) throws Exception { // IDEEditorConfigManager.getInstance().dispose(); // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EditorConfigPlugin getDefault() { // return plugin; // } // // /** // * Utility method to log errors. // * // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, thr.getMessage(), thr)); // } // // /** // * Utility method to log errors. // * // * @param message // * User comprehensible message // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final String message, final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, message, thr)); // } // // @Override // protected void initializeImageRegistry(ImageRegistry registry) { // EditorConfigImages.initalize(registry); // } // } // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorConfigImages.java import java.net.URL; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.ec4e.EditorConfigPlugin; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; import org.osgi.framework.Bundle; /** * Copyright (c) 2017 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.ec4e.internal; /** * Images for .editorconfig * */ public class EditorConfigImages { private static final String ICONS_PATH = "$nl$/icons/full/"; //$NON-NLS-1$ private static final String OBJECT = ICONS_PATH + "obj16/"; // basic colors - size 16x16 //$NON-NLS-1$ public static final String IMG_PROPERTY = "IMG_PROPERTY"; //$NON-NLS-1$ public static final String IMG_VALUE = "IMG_VALUE"; //$NON-NLS-1$ private EditorConfigImages() { } private static ImageRegistry imageRegistry; public static void initalize(ImageRegistry registry) { imageRegistry = registry; declareRegistryImage(IMG_PROPERTY, OBJECT + "property.png"); //$NON-NLS-1$ declareRegistryImage(IMG_VALUE, OBJECT + "value.png"); //$NON-NLS-1$ } private final static void declareRegistryImage(String key, String path) { ImageDescriptor desc = ImageDescriptor.getMissingImageDescriptor();
Bundle bundle = Platform.getBundle(EditorConfigPlugin.PLUGIN_ID);
angelozerr/ec4e
org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/outline/EditorConfigContentProvider.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/utils/EditorUtils.java // public class EditorUtils { // // public static boolean isEditorConfigFile(ITextEditor textEditor) { // IFile configFile = EditorUtils.getFile(textEditor); // return isEditorConfigFile(configFile); // } // // public static boolean isEditorConfigFile(IFile configFile) { // return configFile != null && EditorConfigConstants.EDITORCONFIG.equals(configFile.getName()); // } // // public static IFile getFile(ITextEditor textEditor) { // IEditorInput input = textEditor.getEditorInput(); // if (input instanceof IFileEditorInput) { // return ((IFileEditorInput) input).getFile(); // } // return null; // } // }
import java.io.IOException; import java.util.concurrent.CompletableFuture; import org.ec4j.core.EditorConfigConstants; import org.ec4j.core.PropertyTypeRegistry; import org.ec4j.core.Resource.Resources; import org.ec4j.core.model.EditorConfig; import org.ec4j.core.model.Property; import org.ec4j.core.model.Section; import org.ec4j.core.model.Version; import org.ec4j.core.parser.EditorConfigModelHandler; import org.ec4j.core.parser.EditorConfigParser; import org.ec4j.core.parser.ErrorHandler; import org.ec4j.core.parser.LocationAwareModelHandler; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.runtime.CoreException; import org.eclipse.ec4e.utils.EditorUtils; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IMemento; import org.eclipse.ui.navigator.ICommonContentExtensionSite; import org.eclipse.ui.navigator.ICommonContentProvider; import org.eclipse.ui.texteditor.ITextEditor;
package org.eclipse.ec4e.internal.outline; public class EditorConfigContentProvider implements ICommonContentProvider, ITreeContentProvider, IDocumentListener, IResourceChangeListener { public static final Object COMPUTING = new Object(); private TreeViewer viewer; private ITextEditor info; private IFile resource; private EditorConfig editorConfig; private CompletableFuture<EditorConfig> symbols; @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { this.viewer = (TreeViewer) viewer; this.info = (ITextEditor) newInput; getDocument().addDocumentListener(this);
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/utils/EditorUtils.java // public class EditorUtils { // // public static boolean isEditorConfigFile(ITextEditor textEditor) { // IFile configFile = EditorUtils.getFile(textEditor); // return isEditorConfigFile(configFile); // } // // public static boolean isEditorConfigFile(IFile configFile) { // return configFile != null && EditorConfigConstants.EDITORCONFIG.equals(configFile.getName()); // } // // public static IFile getFile(ITextEditor textEditor) { // IEditorInput input = textEditor.getEditorInput(); // if (input instanceof IFileEditorInput) { // return ((IFileEditorInput) input).getFile(); // } // return null; // } // } // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/outline/EditorConfigContentProvider.java import java.io.IOException; import java.util.concurrent.CompletableFuture; import org.ec4j.core.EditorConfigConstants; import org.ec4j.core.PropertyTypeRegistry; import org.ec4j.core.Resource.Resources; import org.ec4j.core.model.EditorConfig; import org.ec4j.core.model.Property; import org.ec4j.core.model.Section; import org.ec4j.core.model.Version; import org.ec4j.core.parser.EditorConfigModelHandler; import org.ec4j.core.parser.EditorConfigParser; import org.ec4j.core.parser.ErrorHandler; import org.ec4j.core.parser.LocationAwareModelHandler; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.runtime.CoreException; import org.eclipse.ec4e.utils.EditorUtils; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IMemento; import org.eclipse.ui.navigator.ICommonContentExtensionSite; import org.eclipse.ui.navigator.ICommonContentProvider; import org.eclipse.ui.texteditor.ITextEditor; package org.eclipse.ec4e.internal.outline; public class EditorConfigContentProvider implements ICommonContentProvider, ITreeContentProvider, IDocumentListener, IResourceChangeListener { public static final Object COMPUTING = new Object(); private TreeViewer viewer; private ITextEditor info; private IFile resource; private EditorConfig editorConfig; private CompletableFuture<EditorConfig> symbols; @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { this.viewer = (TreeViewer) viewer; this.info = (ITextEditor) newInput; getDocument().addDocumentListener(this);
resource = EditorUtils.getFile(info);
angelozerr/ec4e
org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/IDEEditorConfigManager.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/resource/FileResource.java // public class FileResource implements Resource { // final IFile file; // // public FileResource(IFile file) { // super(); // this.file = file; // } // // @Override // public boolean exists() { // return file.exists(); // } // // @Override // public ResourcePath getParent() { // IContainer parent = file.getParent(); // return parent == null ? null : new ContainerResourcePath(parent); // } // // @Override // public Ec4jPath getPath() { // return Ec4jPaths.of(file.getLocation().toString().replaceAll("[\\\\]", "/")); // } // // @Override // public RandomReader openRandomReader() throws IOException { // try (Reader reader = openReader()) { // return org.ec4j.core.Resource.Resources.StringRandomReader.ofReader(reader); // } // } // // @Override // public Reader openReader() throws IOException { // try { // return new InputStreamReader(file.getContents(), Charset.forName(file.getCharset())); // } catch (CoreException e) { // throw new IOException(e); // } // } // // }
import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import org.ec4j.core.Cache; import org.ec4j.core.EditorConfigConstants; import org.ec4j.core.EditorConfigLoader; import org.ec4j.core.PropertyTypeRegistry; import org.ec4j.core.Resource; import org.ec4j.core.ResourceProperties; import org.ec4j.core.ResourcePropertiesService; import org.ec4j.core.ide.IdeSupportService; import org.ec4j.core.model.EditorConfig; import org.ec4j.core.model.Version; import org.ec4j.core.parser.ErrorHandler; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.ec4e.internal.resource.FileResource;
@Override public void resourceChanged(IResourceChangeEvent event) { if (event.getType() == IResourceChangeEvent.POST_CHANGE) { IResourceDelta delta = event.getDelta(); if (delta != null) { try { delta.accept(this); } catch (CoreException e) { EditorConfigPlugin.logError("Error while .editorconfig resource changed", e); } } } } @Override public boolean visit(IResourceDelta delta) throws CoreException { IResource resource = delta.getResource(); if (resource == null) { return false; } switch (resource.getType()) { case IResource.ROOT: case IResource.PROJECT: case IResource.FOLDER: return true; case IResource.FILE: IFile file = (IFile) resource; if (EditorConfigConstants.EDITORCONFIG.equals(file.getName()) && delta.getKind() == IResourceDelta.CHANGED) {
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/resource/FileResource.java // public class FileResource implements Resource { // final IFile file; // // public FileResource(IFile file) { // super(); // this.file = file; // } // // @Override // public boolean exists() { // return file.exists(); // } // // @Override // public ResourcePath getParent() { // IContainer parent = file.getParent(); // return parent == null ? null : new ContainerResourcePath(parent); // } // // @Override // public Ec4jPath getPath() { // return Ec4jPaths.of(file.getLocation().toString().replaceAll("[\\\\]", "/")); // } // // @Override // public RandomReader openRandomReader() throws IOException { // try (Reader reader = openReader()) { // return org.ec4j.core.Resource.Resources.StringRandomReader.ofReader(reader); // } // } // // @Override // public Reader openReader() throws IOException { // try { // return new InputStreamReader(file.getContents(), Charset.forName(file.getCharset())); // } catch (CoreException e) { // throw new IOException(e); // } // } // // } // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/IDEEditorConfigManager.java import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import org.ec4j.core.Cache; import org.ec4j.core.EditorConfigConstants; import org.ec4j.core.EditorConfigLoader; import org.ec4j.core.PropertyTypeRegistry; import org.ec4j.core.Resource; import org.ec4j.core.ResourceProperties; import org.ec4j.core.ResourcePropertiesService; import org.ec4j.core.ide.IdeSupportService; import org.ec4j.core.model.EditorConfig; import org.ec4j.core.model.Version; import org.ec4j.core.parser.ErrorHandler; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.ec4e.internal.resource.FileResource; @Override public void resourceChanged(IResourceChangeEvent event) { if (event.getType() == IResourceChangeEvent.POST_CHANGE) { IResourceDelta delta = event.getDelta(); if (delta != null) { try { delta.accept(this); } catch (CoreException e) { EditorConfigPlugin.logError("Error while .editorconfig resource changed", e); } } } } @Override public boolean visit(IResourceDelta delta) throws CoreException { IResource resource = delta.getResource(); if (resource == null) { return false; } switch (resource.getType()) { case IResource.ROOT: case IResource.PROJECT: case IResource.FOLDER: return true; case IResource.FILE: IFile file = (IFile) resource; if (EditorConfigConstants.EDITORCONFIG.equals(file.getName()) && delta.getKind() == IResourceDelta.CHANGED) {
entries.remove(new FileResource(file));
angelozerr/ec4e
org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/wizards/NewEditorConfigFileWizardPage.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorConfigMessages.java // public class EditorConfigMessages extends NLS { // // private static final String BUNDLE_NAME = "org.eclipse.ec4e.internal.EditorConfigMessages"; //$NON-NLS-1$ // // // Buttons // public static String Browse_button; // // // Wizards // public static String NewEditorConfigWizard_windowTitle; // public static String NewEditorConfigFileWizardPage_title; // public static String NewEditorConfigFileWizardPage_description; // public static String NewEditorConfigFileWizardPage_folderText_Label; // public static String NewEditorConfigFileWizardPage_containerSelectionDialog_title; // public static String NewEditorConfigFileWizardPage_folder_required_error; // public static String NewEditorConfigFileWizardPage_folder_noexists_error; // public static String NewEditorConfigFileWizardPage_project_noaccessible_error; // public static String NewEditorConfigFileWizardPage_folder_already_editorconfig_error; // // // Search // public static String EditorConfigSearchQuery_label; // public static String EditorConfigSearchQuery_singularReference; // public static String EditorConfigSearchQuery_pluralReferences; // // static { // NLS.initializeMessages(BUNDLE_NAME, EditorConfigMessages.class); // } // // }
import org.ec4j.core.EditorConfigConstants; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.ec4e.internal.EditorConfigMessages; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.ContainerSelectionDialog;
/** * Copyright (c) 2017 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.ec4e.internal.wizards; /** * Wizard page to fill information of .editorconfig file to create. * */ public class NewEditorConfigFileWizardPage extends WizardPage { private static final String PAGE_NAME = NewEditorConfigFileWizardPage.class.getName(); private static final IPath EDITOTR_CONFIG_PATH = new Path(EditorConfigConstants.EDITORCONFIG); private Text folderText; private ISelection selection; /** * Constructor for NewEditorConfigFileWizardPage. * * @param pageName */ public NewEditorConfigFileWizardPage(ISelection selection) { super(PAGE_NAME);
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorConfigMessages.java // public class EditorConfigMessages extends NLS { // // private static final String BUNDLE_NAME = "org.eclipse.ec4e.internal.EditorConfigMessages"; //$NON-NLS-1$ // // // Buttons // public static String Browse_button; // // // Wizards // public static String NewEditorConfigWizard_windowTitle; // public static String NewEditorConfigFileWizardPage_title; // public static String NewEditorConfigFileWizardPage_description; // public static String NewEditorConfigFileWizardPage_folderText_Label; // public static String NewEditorConfigFileWizardPage_containerSelectionDialog_title; // public static String NewEditorConfigFileWizardPage_folder_required_error; // public static String NewEditorConfigFileWizardPage_folder_noexists_error; // public static String NewEditorConfigFileWizardPage_project_noaccessible_error; // public static String NewEditorConfigFileWizardPage_folder_already_editorconfig_error; // // // Search // public static String EditorConfigSearchQuery_label; // public static String EditorConfigSearchQuery_singularReference; // public static String EditorConfigSearchQuery_pluralReferences; // // static { // NLS.initializeMessages(BUNDLE_NAME, EditorConfigMessages.class); // } // // } // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/wizards/NewEditorConfigFileWizardPage.java import org.ec4j.core.EditorConfigConstants; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.ec4e.internal.EditorConfigMessages; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.ContainerSelectionDialog; /** * Copyright (c) 2017 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.ec4e.internal.wizards; /** * Wizard page to fill information of .editorconfig file to create. * */ public class NewEditorConfigFileWizardPage extends WizardPage { private static final String PAGE_NAME = NewEditorConfigFileWizardPage.class.getName(); private static final IPath EDITOTR_CONFIG_PATH = new Path(EditorConfigConstants.EDITORCONFIG); private Text folderText; private ISelection selection; /** * Constructor for NewEditorConfigFileWizardPage. * * @param pageName */ public NewEditorConfigFileWizardPage(ISelection selection) { super(PAGE_NAME);
setTitle(EditorConfigMessages.NewEditorConfigFileWizardPage_title);
angelozerr/ec4e
org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorTracker.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/EditorConfigPlugin.java // public class EditorConfigPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.ec4e"; //$NON-NLS-1$ // // // The shared instance // private static EditorConfigPlugin plugin; // // /** // * The constructor // */ // public EditorConfigPlugin() { // } // // @Override // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // IDEEditorConfigManager.getInstance().init(); // } // // @Override // public void stop(BundleContext context) throws Exception { // IDEEditorConfigManager.getInstance().dispose(); // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EditorConfigPlugin getDefault() { // return plugin; // } // // /** // * Utility method to log errors. // * // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, thr.getMessage(), thr)); // } // // /** // * Utility method to log errors. // * // * @param message // * User comprehensible message // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final String message, final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, message, thr)); // } // // @Override // protected void initializeImageRegistry(ImageRegistry registry) { // EditorConfigImages.initalize(registry); // } // }
import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.Assert; import org.eclipse.ec4e.EditorConfigPlugin; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IPageListener; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IWindowListener; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.texteditor.AbstractTextEditor;
/** * Copyright (c) 2017 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.ec4e.internal; /** * Editor tracker used to * * <ul> * <li>update {@link IPreferenceStore} of the opened text editor by adding the * {@link EditorConfigPreferenceStore}.</li> * <li>call {@link EditorConfigPreferenceStore#applyConfig()} when editor has * focus to apply properties coming from .editorconfig files.</li> * </ul> * */ public class EditorTracker implements IWindowListener, IPageListener, IPartListener { private static EditorTracker INSTANCE; private Map<AbstractTextEditor, ApplyEditorConfig> applies = new HashMap<>(); private EditorTracker() { init(); } public static EditorTracker getInstance() { if (INSTANCE == null) { INSTANCE = new EditorTracker(); } return INSTANCE; } private void init() { if (PlatformUI.isWorkbenchRunning()) {
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/EditorConfigPlugin.java // public class EditorConfigPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.ec4e"; //$NON-NLS-1$ // // // The shared instance // private static EditorConfigPlugin plugin; // // /** // * The constructor // */ // public EditorConfigPlugin() { // } // // @Override // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // IDEEditorConfigManager.getInstance().init(); // } // // @Override // public void stop(BundleContext context) throws Exception { // IDEEditorConfigManager.getInstance().dispose(); // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EditorConfigPlugin getDefault() { // return plugin; // } // // /** // * Utility method to log errors. // * // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, thr.getMessage(), thr)); // } // // /** // * Utility method to log errors. // * // * @param message // * User comprehensible message // * @param thr // * The exception through which we noticed the error // */ // public static void logError(final String message, final Throwable thr) { // getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, 0, message, thr)); // } // // @Override // protected void initializeImageRegistry(ImageRegistry registry) { // EditorConfigImages.initalize(registry); // } // } // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/EditorTracker.java import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.Assert; import org.eclipse.ec4e.EditorConfigPlugin; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IPageListener; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IWindowListener; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.texteditor.AbstractTextEditor; /** * Copyright (c) 2017 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.ec4e.internal; /** * Editor tracker used to * * <ul> * <li>update {@link IPreferenceStore} of the opened text editor by adding the * {@link EditorConfigPreferenceStore}.</li> * <li>call {@link EditorConfigPreferenceStore#applyConfig()} when editor has * focus to apply properties coming from .editorconfig files.</li> * </ul> * */ public class EditorTracker implements IWindowListener, IPageListener, IPartListener { private static EditorTracker INSTANCE; private Map<AbstractTextEditor, ApplyEditorConfig> applies = new HashMap<>(); private EditorTracker() { init(); } public static EditorTracker getInstance() { if (INSTANCE == null) { INSTANCE = new EditorTracker(); } return INSTANCE; } private void init() { if (PlatformUI.isWorkbenchRunning()) {
IWorkbench workbench = EditorConfigPlugin.getDefault().getWorkbench();
angelozerr/ec4e
org.eclipse.ec4e.codelens/src/main/java/org/eclipse/ec4e/codelens/EditorConfigCodeLens.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/search/EditorConfigSearchQuery.java // public class EditorConfigSearchQuery extends FileSearchQuery { // // private final Section section; // private final IFile configFile; // // private EditorConfigSearchResult result; // private long startTime; // // /** // * EditorConfig section matching files query to "Find matching files" from the // * given section // * // * @param section // * @param configFile // */ // public EditorConfigSearchQuery(Section section, IFile configFile) { // super("", false, false, null); //$NON-NLS-1$ // this.section = section; // this.configFile = configFile; // } // // @Override // public IStatus run(IProgressMonitor monitor) throws OperationCanceledException { // startTime = System.currentTimeMillis(); // AbstractTextSearchResult textResult = (AbstractTextSearchResult) getSearchResult(); // textResult.removeAll(); // // try { // // IContainer dir = configFile.getParent(); // dir.accept(new AbstractSectionPatternVisitor(section) { // // @Override // protected void collect(IResourceProxy proxy) { // Match match = new FileMatch((IFile) proxy.requestResource()); // result.addMatch(match); // } // }, IResource.NONE); // // return Status.OK_STATUS; // } catch (Exception ex) { // return new Status(IStatus.ERROR, EditorConfigPlugin.PLUGIN_ID, ex.getMessage(), ex); // } // } // // @Override // public ISearchResult getSearchResult() { // if (result == null) { // result = new EditorConfigSearchResult(this); // } // return result; // } // // @Override // public String getLabel() { // return EditorConfigMessages.EditorConfigSearchQuery_label; // } // // @Override // public String getResultLabel(int nMatches) { // long time = 0; // if (startTime > 0) { // time = System.currentTimeMillis() - startTime; // } // if (nMatches == 1) { // return NLS.bind(EditorConfigMessages.EditorConfigSearchQuery_singularReference, // new Object[] { section.getGlob(), time }); // } // return NLS.bind(EditorConfigMessages.EditorConfigSearchQuery_pluralReferences, // new Object[] { section.getGlob(), nMatches, time }); // } // // @Override // public boolean isFileNameSearch() { // return true; // } // }
import org.ec4j.core.model.Section; import org.ec4j.core.parser.Location; import org.eclipse.core.resources.IFile; import org.eclipse.ec4e.search.EditorConfigSearchQuery; import org.eclipse.jface.text.provisional.codelens.CodeLens; import org.eclipse.search.ui.NewSearchUI;
package org.eclipse.ec4e.codelens; public class EditorConfigCodeLens extends CodeLens { private Section section; private final IFile configFile; public EditorConfigCodeLens(Section section, Location sectionStart, IFile configFile) { super(sectionStart.getLine()); this.section = section; this.configFile = configFile; } @Override public void open() { // Execute Search
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/search/EditorConfigSearchQuery.java // public class EditorConfigSearchQuery extends FileSearchQuery { // // private final Section section; // private final IFile configFile; // // private EditorConfigSearchResult result; // private long startTime; // // /** // * EditorConfig section matching files query to "Find matching files" from the // * given section // * // * @param section // * @param configFile // */ // public EditorConfigSearchQuery(Section section, IFile configFile) { // super("", false, false, null); //$NON-NLS-1$ // this.section = section; // this.configFile = configFile; // } // // @Override // public IStatus run(IProgressMonitor monitor) throws OperationCanceledException { // startTime = System.currentTimeMillis(); // AbstractTextSearchResult textResult = (AbstractTextSearchResult) getSearchResult(); // textResult.removeAll(); // // try { // // IContainer dir = configFile.getParent(); // dir.accept(new AbstractSectionPatternVisitor(section) { // // @Override // protected void collect(IResourceProxy proxy) { // Match match = new FileMatch((IFile) proxy.requestResource()); // result.addMatch(match); // } // }, IResource.NONE); // // return Status.OK_STATUS; // } catch (Exception ex) { // return new Status(IStatus.ERROR, EditorConfigPlugin.PLUGIN_ID, ex.getMessage(), ex); // } // } // // @Override // public ISearchResult getSearchResult() { // if (result == null) { // result = new EditorConfigSearchResult(this); // } // return result; // } // // @Override // public String getLabel() { // return EditorConfigMessages.EditorConfigSearchQuery_label; // } // // @Override // public String getResultLabel(int nMatches) { // long time = 0; // if (startTime > 0) { // time = System.currentTimeMillis() - startTime; // } // if (nMatches == 1) { // return NLS.bind(EditorConfigMessages.EditorConfigSearchQuery_singularReference, // new Object[] { section.getGlob(), time }); // } // return NLS.bind(EditorConfigMessages.EditorConfigSearchQuery_pluralReferences, // new Object[] { section.getGlob(), nMatches, time }); // } // // @Override // public boolean isFileNameSearch() { // return true; // } // } // Path: org.eclipse.ec4e.codelens/src/main/java/org/eclipse/ec4e/codelens/EditorConfigCodeLens.java import org.ec4j.core.model.Section; import org.ec4j.core.parser.Location; import org.eclipse.core.resources.IFile; import org.eclipse.ec4e.search.EditorConfigSearchQuery; import org.eclipse.jface.text.provisional.codelens.CodeLens; import org.eclipse.search.ui.NewSearchUI; package org.eclipse.ec4e.codelens; public class EditorConfigCodeLens extends CodeLens { private Section section; private final IFile configFile; public EditorConfigCodeLens(Section section, Location sectionStart, IFile configFile) { super(sectionStart.getLine()); this.section = section; this.configFile = configFile; } @Override public void open() { // Execute Search
EditorConfigSearchQuery query = new EditorConfigSearchQuery(section, configFile);
angelozerr/ec4e
org.eclipse.ec4e.codelens/src/main/java/org/eclipse/ec4e/codelens/EditorConfigCodeLensControllerProvider.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/utils/EditorUtils.java // public class EditorUtils { // // public static boolean isEditorConfigFile(ITextEditor textEditor) { // IFile configFile = EditorUtils.getFile(textEditor); // return isEditorConfigFile(configFile); // } // // public static boolean isEditorConfigFile(IFile configFile) { // return configFile != null && EditorConfigConstants.EDITORCONFIG.equals(configFile.getName()); // } // // public static IFile getFile(ITextEditor textEditor) { // IEditorInput input = textEditor.getEditorInput(); // if (input instanceof IFileEditorInput) { // return ((IFileEditorInput) input).getFile(); // } // return null; // } // }
import org.eclipse.codelens.editors.DefaultCodeLensController; import org.eclipse.codelens.editors.ICodeLensController; import org.eclipse.codelens.editors.ICodeLensControllerFactory; import org.eclipse.ec4e.utils.EditorUtils; import org.eclipse.ui.texteditor.ITextEditor;
package org.eclipse.ec4e.codelens; public class EditorConfigCodeLensControllerProvider implements ICodeLensControllerFactory { @Override public boolean isRelevant(ITextEditor textEditor) {
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/utils/EditorUtils.java // public class EditorUtils { // // public static boolean isEditorConfigFile(ITextEditor textEditor) { // IFile configFile = EditorUtils.getFile(textEditor); // return isEditorConfigFile(configFile); // } // // public static boolean isEditorConfigFile(IFile configFile) { // return configFile != null && EditorConfigConstants.EDITORCONFIG.equals(configFile.getName()); // } // // public static IFile getFile(ITextEditor textEditor) { // IEditorInput input = textEditor.getEditorInput(); // if (input instanceof IFileEditorInput) { // return ((IFileEditorInput) input).getFile(); // } // return null; // } // } // Path: org.eclipse.ec4e.codelens/src/main/java/org/eclipse/ec4e/codelens/EditorConfigCodeLensControllerProvider.java import org.eclipse.codelens.editors.DefaultCodeLensController; import org.eclipse.codelens.editors.ICodeLensController; import org.eclipse.codelens.editors.ICodeLensControllerFactory; import org.eclipse.ec4e.utils.EditorUtils; import org.eclipse.ui.texteditor.ITextEditor; package org.eclipse.ec4e.codelens; public class EditorConfigCodeLensControllerProvider implements ICodeLensControllerFactory { @Override public boolean isRelevant(ITextEditor textEditor) {
return EditorUtils.isEditorConfigFile(textEditor);
angelozerr/ec4e
org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/outline/EditorConfigToOutlineAdapterFactory.java
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/utils/EditorUtils.java // public class EditorUtils { // // public static boolean isEditorConfigFile(ITextEditor textEditor) { // IFile configFile = EditorUtils.getFile(textEditor); // return isEditorConfigFile(configFile); // } // // public static boolean isEditorConfigFile(IFile configFile) { // return configFile != null && EditorConfigConstants.EDITORCONFIG.equals(configFile.getName()); // } // // public static IFile getFile(ITextEditor textEditor) { // IEditorInput input = textEditor.getEditorInput(); // if (input instanceof IFileEditorInput) { // return ((IFileEditorInput) input).getFile(); // } // return null; // } // }
import org.eclipse.core.runtime.IAdapterFactory; import org.eclipse.ec4e.utils.EditorUtils; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
package org.eclipse.ec4e.internal.outline; public class EditorConfigToOutlineAdapterFactory implements IAdapterFactory { @Override public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { if (adapterType == IContentOutlinePage.class && adaptableObject instanceof ITextEditor
// Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/utils/EditorUtils.java // public class EditorUtils { // // public static boolean isEditorConfigFile(ITextEditor textEditor) { // IFile configFile = EditorUtils.getFile(textEditor); // return isEditorConfigFile(configFile); // } // // public static boolean isEditorConfigFile(IFile configFile) { // return configFile != null && EditorConfigConstants.EDITORCONFIG.equals(configFile.getName()); // } // // public static IFile getFile(ITextEditor textEditor) { // IEditorInput input = textEditor.getEditorInput(); // if (input instanceof IFileEditorInput) { // return ((IFileEditorInput) input).getFile(); // } // return null; // } // } // Path: org.eclipse.ec4e/src/main/java/org/eclipse/ec4e/internal/outline/EditorConfigToOutlineAdapterFactory.java import org.eclipse.core.runtime.IAdapterFactory; import org.eclipse.ec4e.utils.EditorUtils; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; package org.eclipse.ec4e.internal.outline; public class EditorConfigToOutlineAdapterFactory implements IAdapterFactory { @Override public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { if (adapterType == IContentOutlinePage.class && adaptableObject instanceof ITextEditor
&& EditorUtils.isEditorConfigFile((ITextEditor) adaptableObject)) {
redferret/planet
test/TaskRunnerTest.java
// Path: src/engine/util/concurrent/TaskRunner.java // public abstract class TaskRunner implements Runnable { // // /** // * The delay speed in milliseconds. // */ // private int miliSeconds; // // /** // * Flag used to determine if the thread is running or not. // */ // protected boolean running; // // /** // * Flag to determine if this thread is finished executing // */ // private boolean executing; // // /** // * Flag that determines if this thread will loop continuously without being // * invoked by another thread to run an iteration. // */ // private boolean continuous; // // /** // * The amount of time that lapsed to process a frame // */ // private final AtomicInteger timeLapse; // // /** // * Barrier for this thread to wait to be signaled by another thread. // */ // private final CyclicBarrier waiter; // // /** // * Creates a new TaskRunner with the given delay and whether this TaskRunner // * is continuous. // * // * @param delay The time in milliseconds to delay for each frame or iteration. // * @param continuous If this Runnable is continuous. // */ // public TaskRunner(int delay, boolean continuous) { // miliSeconds = delay; // this.continuous = continuous; // running = false; // executing = true; // timeLapse = new AtomicInteger(0); // waiter = new CyclicBarrier(2); // } // // /** // * The most recent time that has lapsed. // * // * @return // */ // public int timeLapse() { // return timeLapse.get(); // } // // /** // * Reset the amount of time to delay each frame // * // * @param delay The time to delay each frame in milliseconds. // */ // public void setDelay(int delay) { // miliSeconds = delay; // } // // /** // * Pauses this runner // */ // public void pause() { // running = false; // } // // /** // * Flags the runner to start running again. // */ // public void play() { // running = true; // waiter.reset(); // } // // /** // * Kills the process forever. // */ // public void kill() { // executing = false; // waiter.reset(); // } // // /** // * Whether this runner is paused or not. // * // * @return True if this runner is currently paused. // */ // public boolean isPaused() { // return !running; // } // // /** // * This method will be called by this class on each frame // */ // public abstract void update() throws Exception; // // /** // * Reset this runner as being continuous or not // * // * @param continuous // */ // public void setContinuous(boolean continuous) { // this.continuous = continuous; // } // // @Override // @SuppressWarnings("SleepWhileInLoop") // public void run() { // while (executing) { // try { // if (running) { // long start = System.currentTimeMillis(); // update(); // timeLapse.getAndSet((int) (System.currentTimeMillis() - start)); // } // // Thread.sleep(miliSeconds); // // if (!running || !continuous) { // waiter.await(); // } // } catch (InterruptedException | BrokenBarrierException e) { // } catch (Exception ex) { // System.err.println(Thread.currentThread().getName() + " failed"); // ex.printStackTrace(); // executing = false; // } // } // } // // }
import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Test; import static org.junit.Assert.*; import engine.util.concurrent.TaskRunner;
*/ @Test public void continuousExecutionTest() throws InterruptedException { latch = new CountDownLatch(5); testThread = new TestThread(latch); thread = new Thread(testThread); testThread.setContinuous(true); thread.start(); testThread.play(); boolean signaled = latch.await(100, TimeUnit.MILLISECONDS); assertTrue(signaled); } @After public void tearDown() { testThread.kill(); } } /** * A non-continuous test thread to test the TaskRunner class. * * @author Richard DeSilvey * */
// Path: src/engine/util/concurrent/TaskRunner.java // public abstract class TaskRunner implements Runnable { // // /** // * The delay speed in milliseconds. // */ // private int miliSeconds; // // /** // * Flag used to determine if the thread is running or not. // */ // protected boolean running; // // /** // * Flag to determine if this thread is finished executing // */ // private boolean executing; // // /** // * Flag that determines if this thread will loop continuously without being // * invoked by another thread to run an iteration. // */ // private boolean continuous; // // /** // * The amount of time that lapsed to process a frame // */ // private final AtomicInteger timeLapse; // // /** // * Barrier for this thread to wait to be signaled by another thread. // */ // private final CyclicBarrier waiter; // // /** // * Creates a new TaskRunner with the given delay and whether this TaskRunner // * is continuous. // * // * @param delay The time in milliseconds to delay for each frame or iteration. // * @param continuous If this Runnable is continuous. // */ // public TaskRunner(int delay, boolean continuous) { // miliSeconds = delay; // this.continuous = continuous; // running = false; // executing = true; // timeLapse = new AtomicInteger(0); // waiter = new CyclicBarrier(2); // } // // /** // * The most recent time that has lapsed. // * // * @return // */ // public int timeLapse() { // return timeLapse.get(); // } // // /** // * Reset the amount of time to delay each frame // * // * @param delay The time to delay each frame in milliseconds. // */ // public void setDelay(int delay) { // miliSeconds = delay; // } // // /** // * Pauses this runner // */ // public void pause() { // running = false; // } // // /** // * Flags the runner to start running again. // */ // public void play() { // running = true; // waiter.reset(); // } // // /** // * Kills the process forever. // */ // public void kill() { // executing = false; // waiter.reset(); // } // // /** // * Whether this runner is paused or not. // * // * @return True if this runner is currently paused. // */ // public boolean isPaused() { // return !running; // } // // /** // * This method will be called by this class on each frame // */ // public abstract void update() throws Exception; // // /** // * Reset this runner as being continuous or not // * // * @param continuous // */ // public void setContinuous(boolean continuous) { // this.continuous = continuous; // } // // @Override // @SuppressWarnings("SleepWhileInLoop") // public void run() { // while (executing) { // try { // if (running) { // long start = System.currentTimeMillis(); // update(); // timeLapse.getAndSet((int) (System.currentTimeMillis() - start)); // } // // Thread.sleep(miliSeconds); // // if (!running || !continuous) { // waiter.await(); // } // } catch (InterruptedException | BrokenBarrierException e) { // } catch (Exception ex) { // System.err.println(Thread.currentThread().getName() + " failed"); // ex.printStackTrace(); // executing = false; // } // } // } // // } // Path: test/TaskRunnerTest.java import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Test; import static org.junit.Assert.*; import engine.util.concurrent.TaskRunner; */ @Test public void continuousExecutionTest() throws InterruptedException { latch = new CountDownLatch(5); testThread = new TestThread(latch); thread = new Thread(testThread); testThread.setContinuous(true); thread.start(); testThread.play(); boolean signaled = latch.await(100, TimeUnit.MILLISECONDS); assertTrue(signaled); } @After public void tearDown() { testThread.kill(); } } /** * A non-continuous test thread to test the TaskRunner class. * * @author Richard DeSilvey * */
class TestThread extends TaskRunner {
redferret/planet
src/worlds/planet/geosphere/Layer.java
// Path: src/worlds/planet/PlanetCell.java // public class PlanetCell extends GeoCell { // // public static int area, length; // // static { // length = 1; // area = 1; // } // // public PlanetCell() { // this(0, 0); // } // // public PlanetCell(int x, int y) { // super(x, y); // } // // } // // Path: src/worlds/planet/Surface.java // public abstract class Surface extends SurfaceMap<PlanetCell> { // // /** // * The number of years that pass for each step of erosion // */ // public static long GEOUPDATE; // private long geologicalTimeStamp; // // /** // * The age of the planet in years // */ // public static AtomicLong planetAge; // // /** // * The number of years that pass for each update to the geosphere // */ // public static long timeStep; // // public final static int HEIGHTMAP = 0; // public final static int STRATAMAP = 1; // public final static int LANDOCEAN = 2; // // private static final int DEFAULT_THREAD_DELAY = 50; // // private final MinMaxHeightFactory mhFactory; // // static { // timeStep = 7125000; // } // // /** // * Constructs a new Surface with an empty map. // * // * @param totalSize The size of the surface // * @param threadsDelay The amount of time to delay each frame in milliseconds. // * @param threadCount The number of threads that will work on the map // */ // public Surface(int totalSize, int threadsDelay, int threadCount) { // super(totalSize, DEFAULT_THREAD_DELAY); // setupThreads(threadCount, threadsDelay); // setupDefaultMap(threadCount); // mhFactory = new MinMaxHeightFactory(this); // produceTasks(mhFactory); // reset(); // } // // /** // * Resets the surface to an empty map and resets the planet's age. This method // * should be calling the <code>buildMap()</code> method. // */ // @Override // public final void reset() { // planetAge = new AtomicLong(0); // geologicalTimeStamp = 0; // pauseThreads(); // buildMap(); // addTaskToThreads(new SetParentThreads()); // playThreads(); // } // // public long getPlanetAge() { // return planetAge.get(); // } // // public void updatePlanetAge() { // long curPlanetAge = planetAge.getAndAdd(timeStep); // if (curPlanetAge - geologicalTimeStamp > GEOUPDATE) { // geologicalTimeStamp = curPlanetAge; // } // } // // @Override // public PlanetCell generateCell(int x, int y) { // return new PlanetCell(x, y); // } // // public float getHighestHeight() { // return mhFactory.getHighestHeight(); // } // // public float getLowestHeight() { // return mhFactory.getLowestHeight(); // } // // }
import java.util.HashSet; import java.util.Set; import worlds.planet.PlanetCell; import worlds.planet.Surface;
this.materials = new HashSet<>(); update(); } /** * Copy constructor * @param layer A Deep copy of this Layer and the Materials inside it. */ public Layer(Layer layer) { this.bottom = layer.bottom; this.top = layer.top; this.materials = layer.copyMaterials(); this.averageDensity = layer.averageDensity; this.averageErosionFactor = layer.averageErosionFactor; this.granularity = layer.granularity; this.temperature = layer.temperature; this.totalMass = layer.totalMass; this.type = layer.type; } public Layer(Set<LayerMaterial> materials) { this.materials = new HashSet<>(); this.materials.addAll(materials); update(); } /** * Sets the age of this cell to the time stamp given. */ public void recordTime() {
// Path: src/worlds/planet/PlanetCell.java // public class PlanetCell extends GeoCell { // // public static int area, length; // // static { // length = 1; // area = 1; // } // // public PlanetCell() { // this(0, 0); // } // // public PlanetCell(int x, int y) { // super(x, y); // } // // } // // Path: src/worlds/planet/Surface.java // public abstract class Surface extends SurfaceMap<PlanetCell> { // // /** // * The number of years that pass for each step of erosion // */ // public static long GEOUPDATE; // private long geologicalTimeStamp; // // /** // * The age of the planet in years // */ // public static AtomicLong planetAge; // // /** // * The number of years that pass for each update to the geosphere // */ // public static long timeStep; // // public final static int HEIGHTMAP = 0; // public final static int STRATAMAP = 1; // public final static int LANDOCEAN = 2; // // private static final int DEFAULT_THREAD_DELAY = 50; // // private final MinMaxHeightFactory mhFactory; // // static { // timeStep = 7125000; // } // // /** // * Constructs a new Surface with an empty map. // * // * @param totalSize The size of the surface // * @param threadsDelay The amount of time to delay each frame in milliseconds. // * @param threadCount The number of threads that will work on the map // */ // public Surface(int totalSize, int threadsDelay, int threadCount) { // super(totalSize, DEFAULT_THREAD_DELAY); // setupThreads(threadCount, threadsDelay); // setupDefaultMap(threadCount); // mhFactory = new MinMaxHeightFactory(this); // produceTasks(mhFactory); // reset(); // } // // /** // * Resets the surface to an empty map and resets the planet's age. This method // * should be calling the <code>buildMap()</code> method. // */ // @Override // public final void reset() { // planetAge = new AtomicLong(0); // geologicalTimeStamp = 0; // pauseThreads(); // buildMap(); // addTaskToThreads(new SetParentThreads()); // playThreads(); // } // // public long getPlanetAge() { // return planetAge.get(); // } // // public void updatePlanetAge() { // long curPlanetAge = planetAge.getAndAdd(timeStep); // if (curPlanetAge - geologicalTimeStamp > GEOUPDATE) { // geologicalTimeStamp = curPlanetAge; // } // } // // @Override // public PlanetCell generateCell(int x, int y) { // return new PlanetCell(x, y); // } // // public float getHighestHeight() { // return mhFactory.getHighestHeight(); // } // // public float getLowestHeight() { // return mhFactory.getLowestHeight(); // } // // } // Path: src/worlds/planet/geosphere/Layer.java import java.util.HashSet; import java.util.Set; import worlds.planet.PlanetCell; import worlds.planet.Surface; this.materials = new HashSet<>(); update(); } /** * Copy constructor * @param layer A Deep copy of this Layer and the Materials inside it. */ public Layer(Layer layer) { this.bottom = layer.bottom; this.top = layer.top; this.materials = layer.copyMaterials(); this.averageDensity = layer.averageDensity; this.averageErosionFactor = layer.averageErosionFactor; this.granularity = layer.granularity; this.temperature = layer.temperature; this.totalMass = layer.totalMass; this.type = layer.type; } public Layer(Set<LayerMaterial> materials) { this.materials = new HashSet<>(); this.materials.addAll(materials); update(); } /** * Sets the age of this cell to the time stamp given. */ public void recordTime() {
this.depositTimeStamp = Surface.planetAge.get();
redferret/planet
src/worlds/planet/geosphere/Layer.java
// Path: src/worlds/planet/PlanetCell.java // public class PlanetCell extends GeoCell { // // public static int area, length; // // static { // length = 1; // area = 1; // } // // public PlanetCell() { // this(0, 0); // } // // public PlanetCell(int x, int y) { // super(x, y); // } // // } // // Path: src/worlds/planet/Surface.java // public abstract class Surface extends SurfaceMap<PlanetCell> { // // /** // * The number of years that pass for each step of erosion // */ // public static long GEOUPDATE; // private long geologicalTimeStamp; // // /** // * The age of the planet in years // */ // public static AtomicLong planetAge; // // /** // * The number of years that pass for each update to the geosphere // */ // public static long timeStep; // // public final static int HEIGHTMAP = 0; // public final static int STRATAMAP = 1; // public final static int LANDOCEAN = 2; // // private static final int DEFAULT_THREAD_DELAY = 50; // // private final MinMaxHeightFactory mhFactory; // // static { // timeStep = 7125000; // } // // /** // * Constructs a new Surface with an empty map. // * // * @param totalSize The size of the surface // * @param threadsDelay The amount of time to delay each frame in milliseconds. // * @param threadCount The number of threads that will work on the map // */ // public Surface(int totalSize, int threadsDelay, int threadCount) { // super(totalSize, DEFAULT_THREAD_DELAY); // setupThreads(threadCount, threadsDelay); // setupDefaultMap(threadCount); // mhFactory = new MinMaxHeightFactory(this); // produceTasks(mhFactory); // reset(); // } // // /** // * Resets the surface to an empty map and resets the planet's age. This method // * should be calling the <code>buildMap()</code> method. // */ // @Override // public final void reset() { // planetAge = new AtomicLong(0); // geologicalTimeStamp = 0; // pauseThreads(); // buildMap(); // addTaskToThreads(new SetParentThreads()); // playThreads(); // } // // public long getPlanetAge() { // return planetAge.get(); // } // // public void updatePlanetAge() { // long curPlanetAge = planetAge.getAndAdd(timeStep); // if (curPlanetAge - geologicalTimeStamp > GEOUPDATE) { // geologicalTimeStamp = curPlanetAge; // } // } // // @Override // public PlanetCell generateCell(int x, int y) { // return new PlanetCell(x, y); // } // // public float getHighestHeight() { // return mhFactory.getHighestHeight(); // } // // public float getLowestHeight() { // return mhFactory.getLowestHeight(); // } // // }
import java.util.HashSet; import java.util.Set; import worlds.planet.PlanetCell; import worlds.planet.Surface;
found = true; break; } } if (!found) { materials.add(material); } update(); } public float getMass() { return totalMass; } /** * Returns the volume of this stratum in cubic meters * * @return The volume of this stratum */ public float getVolume() { return getMass() / averageDensity; } /** * The thickness is calculated based on the volume of the stratum and the area * of a cell. This is also the same as height. * * @return The thickness of this stratum. */ public float getThickness() {
// Path: src/worlds/planet/PlanetCell.java // public class PlanetCell extends GeoCell { // // public static int area, length; // // static { // length = 1; // area = 1; // } // // public PlanetCell() { // this(0, 0); // } // // public PlanetCell(int x, int y) { // super(x, y); // } // // } // // Path: src/worlds/planet/Surface.java // public abstract class Surface extends SurfaceMap<PlanetCell> { // // /** // * The number of years that pass for each step of erosion // */ // public static long GEOUPDATE; // private long geologicalTimeStamp; // // /** // * The age of the planet in years // */ // public static AtomicLong planetAge; // // /** // * The number of years that pass for each update to the geosphere // */ // public static long timeStep; // // public final static int HEIGHTMAP = 0; // public final static int STRATAMAP = 1; // public final static int LANDOCEAN = 2; // // private static final int DEFAULT_THREAD_DELAY = 50; // // private final MinMaxHeightFactory mhFactory; // // static { // timeStep = 7125000; // } // // /** // * Constructs a new Surface with an empty map. // * // * @param totalSize The size of the surface // * @param threadsDelay The amount of time to delay each frame in milliseconds. // * @param threadCount The number of threads that will work on the map // */ // public Surface(int totalSize, int threadsDelay, int threadCount) { // super(totalSize, DEFAULT_THREAD_DELAY); // setupThreads(threadCount, threadsDelay); // setupDefaultMap(threadCount); // mhFactory = new MinMaxHeightFactory(this); // produceTasks(mhFactory); // reset(); // } // // /** // * Resets the surface to an empty map and resets the planet's age. This method // * should be calling the <code>buildMap()</code> method. // */ // @Override // public final void reset() { // planetAge = new AtomicLong(0); // geologicalTimeStamp = 0; // pauseThreads(); // buildMap(); // addTaskToThreads(new SetParentThreads()); // playThreads(); // } // // public long getPlanetAge() { // return planetAge.get(); // } // // public void updatePlanetAge() { // long curPlanetAge = planetAge.getAndAdd(timeStep); // if (curPlanetAge - geologicalTimeStamp > GEOUPDATE) { // geologicalTimeStamp = curPlanetAge; // } // } // // @Override // public PlanetCell generateCell(int x, int y) { // return new PlanetCell(x, y); // } // // public float getHighestHeight() { // return mhFactory.getHighestHeight(); // } // // public float getLowestHeight() { // return mhFactory.getLowestHeight(); // } // // } // Path: src/worlds/planet/geosphere/Layer.java import java.util.HashSet; import java.util.Set; import worlds.planet.PlanetCell; import worlds.planet.Surface; found = true; break; } } if (!found) { materials.add(material); } update(); } public float getMass() { return totalMass; } /** * Returns the volume of this stratum in cubic meters * * @return The volume of this stratum */ public float getVolume() { return getMass() / averageDensity; } /** * The thickness is calculated based on the volume of the stratum and the area * of a cell. This is also the same as height. * * @return The thickness of this stratum. */ public float getThickness() {
return getVolume() / PlanetCell.area;
redferret/planet
src/worlds/planet/geosphere/Geosphere.java
// Path: src/worlds/planet/Surface.java // public abstract class Surface extends SurfaceMap<PlanetCell> { // // /** // * The number of years that pass for each step of erosion // */ // public static long GEOUPDATE; // private long geologicalTimeStamp; // // /** // * The age of the planet in years // */ // public static AtomicLong planetAge; // // /** // * The number of years that pass for each update to the geosphere // */ // public static long timeStep; // // public final static int HEIGHTMAP = 0; // public final static int STRATAMAP = 1; // public final static int LANDOCEAN = 2; // // private static final int DEFAULT_THREAD_DELAY = 50; // // private final MinMaxHeightFactory mhFactory; // // static { // timeStep = 7125000; // } // // /** // * Constructs a new Surface with an empty map. // * // * @param totalSize The size of the surface // * @param threadsDelay The amount of time to delay each frame in milliseconds. // * @param threadCount The number of threads that will work on the map // */ // public Surface(int totalSize, int threadsDelay, int threadCount) { // super(totalSize, DEFAULT_THREAD_DELAY); // setupThreads(threadCount, threadsDelay); // setupDefaultMap(threadCount); // mhFactory = new MinMaxHeightFactory(this); // produceTasks(mhFactory); // reset(); // } // // /** // * Resets the surface to an empty map and resets the planet's age. This method // * should be calling the <code>buildMap()</code> method. // */ // @Override // public final void reset() { // planetAge = new AtomicLong(0); // geologicalTimeStamp = 0; // pauseThreads(); // buildMap(); // addTaskToThreads(new SetParentThreads()); // playThreads(); // } // // public long getPlanetAge() { // return planetAge.get(); // } // // public void updatePlanetAge() { // long curPlanetAge = planetAge.getAndAdd(timeStep); // if (curPlanetAge - geologicalTimeStamp > GEOUPDATE) { // geologicalTimeStamp = curPlanetAge; // } // } // // @Override // public PlanetCell generateCell(int x, int y) { // return new PlanetCell(x, y); // } // // public float getHighestHeight() { // return mhFactory.getHighestHeight(); // } // // public float getLowestHeight() { // return mhFactory.getLowestHeight(); // } // // } // // Path: src/worlds/planet/geosphere/tasks/MantleConduction.java // public class MantleConduction extends Task { // // private final Geosphere surface; // private final Delay delay; // // public MantleConduction(Geosphere surface) { // this.surface = surface; // delay = new Delay(250); // } // // @Override // public void construct() {} // // @Override // public boolean check() throws Exception { // return delay.check(); // } // // @Override // public void before() throws Exception { // } // // @Override // public void perform(int x, int y) throws Exception { // GeoCell cell = surface.getCellAt(x, y); // Vec2[] cells = Util.getCellIndexesFrom(cell.getGridPosition(), surface.getTerrainSize()); // float temp = cell.getMantleTemperature(); // for (Vec2 pos : cells) { // GeoCell neighborCell = surface.getCellAt(pos); // float cellTemp = neighborCell.getMantleTemperature(); // float tempChange = (PlanetCell.length * (temp - cellTemp)) / (1e7f); // cell.addToMantleHeat(-tempChange); // } // } // // @Override // public void after() throws Exception { // } // // } // // Path: src/worlds/planet/geosphere/tasks/MantleRadiation.java // public class MantleRadiation extends Task { // // private final Geosphere geosphere; // private final Delay delay; // // // public MantleRadiation(Geosphere geosphere) { // this.geosphere = geosphere; // delay = new Delay(400); // } // // @Override // public void before() { // } // // @Override // public void perform(int x, int y) { // GeoCell cell = geosphere.getCellAt(x, y); // float heatFromMantle = Util.calcHeatRadiation(cell.getMantleTemperature()); // float denom = (cell.getTotalMass() * cell.getSpecificHeat()); // denom = denom == 0 ? 1 : denom; // float tempChangeToMantle = heatFromMantle / denom; // // cell.addToMantleHeat(-tempChangeToMantle * 0.001f); // } // // @Override // public void after() { // } // // @Override // public void construct() { // } // // @Override // public boolean check() { // return delay.check(); // } // // }
import worlds.planet.Surface; import worlds.planet.geosphere.tasks.MantleConduction; import worlds.planet.geosphere.tasks.MantleRadiation;
package worlds.planet.geosphere; /** * Contains all logic that works on the geology of the planet. * * @author Richard DeSilvey */ public abstract class Geosphere extends Surface { private long ageStamp; public Geosphere(int totalSize, int threadsDelay, int threadCount) { super(totalSize, threadsDelay, threadCount); ageStamp = 0; produceTasks(() -> {
// Path: src/worlds/planet/Surface.java // public abstract class Surface extends SurfaceMap<PlanetCell> { // // /** // * The number of years that pass for each step of erosion // */ // public static long GEOUPDATE; // private long geologicalTimeStamp; // // /** // * The age of the planet in years // */ // public static AtomicLong planetAge; // // /** // * The number of years that pass for each update to the geosphere // */ // public static long timeStep; // // public final static int HEIGHTMAP = 0; // public final static int STRATAMAP = 1; // public final static int LANDOCEAN = 2; // // private static final int DEFAULT_THREAD_DELAY = 50; // // private final MinMaxHeightFactory mhFactory; // // static { // timeStep = 7125000; // } // // /** // * Constructs a new Surface with an empty map. // * // * @param totalSize The size of the surface // * @param threadsDelay The amount of time to delay each frame in milliseconds. // * @param threadCount The number of threads that will work on the map // */ // public Surface(int totalSize, int threadsDelay, int threadCount) { // super(totalSize, DEFAULT_THREAD_DELAY); // setupThreads(threadCount, threadsDelay); // setupDefaultMap(threadCount); // mhFactory = new MinMaxHeightFactory(this); // produceTasks(mhFactory); // reset(); // } // // /** // * Resets the surface to an empty map and resets the planet's age. This method // * should be calling the <code>buildMap()</code> method. // */ // @Override // public final void reset() { // planetAge = new AtomicLong(0); // geologicalTimeStamp = 0; // pauseThreads(); // buildMap(); // addTaskToThreads(new SetParentThreads()); // playThreads(); // } // // public long getPlanetAge() { // return planetAge.get(); // } // // public void updatePlanetAge() { // long curPlanetAge = planetAge.getAndAdd(timeStep); // if (curPlanetAge - geologicalTimeStamp > GEOUPDATE) { // geologicalTimeStamp = curPlanetAge; // } // } // // @Override // public PlanetCell generateCell(int x, int y) { // return new PlanetCell(x, y); // } // // public float getHighestHeight() { // return mhFactory.getHighestHeight(); // } // // public float getLowestHeight() { // return mhFactory.getLowestHeight(); // } // // } // // Path: src/worlds/planet/geosphere/tasks/MantleConduction.java // public class MantleConduction extends Task { // // private final Geosphere surface; // private final Delay delay; // // public MantleConduction(Geosphere surface) { // this.surface = surface; // delay = new Delay(250); // } // // @Override // public void construct() {} // // @Override // public boolean check() throws Exception { // return delay.check(); // } // // @Override // public void before() throws Exception { // } // // @Override // public void perform(int x, int y) throws Exception { // GeoCell cell = surface.getCellAt(x, y); // Vec2[] cells = Util.getCellIndexesFrom(cell.getGridPosition(), surface.getTerrainSize()); // float temp = cell.getMantleTemperature(); // for (Vec2 pos : cells) { // GeoCell neighborCell = surface.getCellAt(pos); // float cellTemp = neighborCell.getMantleTemperature(); // float tempChange = (PlanetCell.length * (temp - cellTemp)) / (1e7f); // cell.addToMantleHeat(-tempChange); // } // } // // @Override // public void after() throws Exception { // } // // } // // Path: src/worlds/planet/geosphere/tasks/MantleRadiation.java // public class MantleRadiation extends Task { // // private final Geosphere geosphere; // private final Delay delay; // // // public MantleRadiation(Geosphere geosphere) { // this.geosphere = geosphere; // delay = new Delay(400); // } // // @Override // public void before() { // } // // @Override // public void perform(int x, int y) { // GeoCell cell = geosphere.getCellAt(x, y); // float heatFromMantle = Util.calcHeatRadiation(cell.getMantleTemperature()); // float denom = (cell.getTotalMass() * cell.getSpecificHeat()); // denom = denom == 0 ? 1 : denom; // float tempChangeToMantle = heatFromMantle / denom; // // cell.addToMantleHeat(-tempChangeToMantle * 0.001f); // } // // @Override // public void after() { // } // // @Override // public void construct() { // } // // @Override // public boolean check() { // return delay.check(); // } // // } // Path: src/worlds/planet/geosphere/Geosphere.java import worlds.planet.Surface; import worlds.planet.geosphere.tasks.MantleConduction; import worlds.planet.geosphere.tasks.MantleRadiation; package worlds.planet.geosphere; /** * Contains all logic that works on the geology of the planet. * * @author Richard DeSilvey */ public abstract class Geosphere extends Surface { private long ageStamp; public Geosphere(int totalSize, int threadsDelay, int threadCount) { super(totalSize, threadsDelay, threadCount); ageStamp = 0; produceTasks(() -> {
return new MantleRadiation(this);
redferret/planet
src/worlds/planet/geosphere/Geosphere.java
// Path: src/worlds/planet/Surface.java // public abstract class Surface extends SurfaceMap<PlanetCell> { // // /** // * The number of years that pass for each step of erosion // */ // public static long GEOUPDATE; // private long geologicalTimeStamp; // // /** // * The age of the planet in years // */ // public static AtomicLong planetAge; // // /** // * The number of years that pass for each update to the geosphere // */ // public static long timeStep; // // public final static int HEIGHTMAP = 0; // public final static int STRATAMAP = 1; // public final static int LANDOCEAN = 2; // // private static final int DEFAULT_THREAD_DELAY = 50; // // private final MinMaxHeightFactory mhFactory; // // static { // timeStep = 7125000; // } // // /** // * Constructs a new Surface with an empty map. // * // * @param totalSize The size of the surface // * @param threadsDelay The amount of time to delay each frame in milliseconds. // * @param threadCount The number of threads that will work on the map // */ // public Surface(int totalSize, int threadsDelay, int threadCount) { // super(totalSize, DEFAULT_THREAD_DELAY); // setupThreads(threadCount, threadsDelay); // setupDefaultMap(threadCount); // mhFactory = new MinMaxHeightFactory(this); // produceTasks(mhFactory); // reset(); // } // // /** // * Resets the surface to an empty map and resets the planet's age. This method // * should be calling the <code>buildMap()</code> method. // */ // @Override // public final void reset() { // planetAge = new AtomicLong(0); // geologicalTimeStamp = 0; // pauseThreads(); // buildMap(); // addTaskToThreads(new SetParentThreads()); // playThreads(); // } // // public long getPlanetAge() { // return planetAge.get(); // } // // public void updatePlanetAge() { // long curPlanetAge = planetAge.getAndAdd(timeStep); // if (curPlanetAge - geologicalTimeStamp > GEOUPDATE) { // geologicalTimeStamp = curPlanetAge; // } // } // // @Override // public PlanetCell generateCell(int x, int y) { // return new PlanetCell(x, y); // } // // public float getHighestHeight() { // return mhFactory.getHighestHeight(); // } // // public float getLowestHeight() { // return mhFactory.getLowestHeight(); // } // // } // // Path: src/worlds/planet/geosphere/tasks/MantleConduction.java // public class MantleConduction extends Task { // // private final Geosphere surface; // private final Delay delay; // // public MantleConduction(Geosphere surface) { // this.surface = surface; // delay = new Delay(250); // } // // @Override // public void construct() {} // // @Override // public boolean check() throws Exception { // return delay.check(); // } // // @Override // public void before() throws Exception { // } // // @Override // public void perform(int x, int y) throws Exception { // GeoCell cell = surface.getCellAt(x, y); // Vec2[] cells = Util.getCellIndexesFrom(cell.getGridPosition(), surface.getTerrainSize()); // float temp = cell.getMantleTemperature(); // for (Vec2 pos : cells) { // GeoCell neighborCell = surface.getCellAt(pos); // float cellTemp = neighborCell.getMantleTemperature(); // float tempChange = (PlanetCell.length * (temp - cellTemp)) / (1e7f); // cell.addToMantleHeat(-tempChange); // } // } // // @Override // public void after() throws Exception { // } // // } // // Path: src/worlds/planet/geosphere/tasks/MantleRadiation.java // public class MantleRadiation extends Task { // // private final Geosphere geosphere; // private final Delay delay; // // // public MantleRadiation(Geosphere geosphere) { // this.geosphere = geosphere; // delay = new Delay(400); // } // // @Override // public void before() { // } // // @Override // public void perform(int x, int y) { // GeoCell cell = geosphere.getCellAt(x, y); // float heatFromMantle = Util.calcHeatRadiation(cell.getMantleTemperature()); // float denom = (cell.getTotalMass() * cell.getSpecificHeat()); // denom = denom == 0 ? 1 : denom; // float tempChangeToMantle = heatFromMantle / denom; // // cell.addToMantleHeat(-tempChangeToMantle * 0.001f); // } // // @Override // public void after() { // } // // @Override // public void construct() { // } // // @Override // public boolean check() { // return delay.check(); // } // // }
import worlds.planet.Surface; import worlds.planet.geosphere.tasks.MantleConduction; import worlds.planet.geosphere.tasks.MantleRadiation;
package worlds.planet.geosphere; /** * Contains all logic that works on the geology of the planet. * * @author Richard DeSilvey */ public abstract class Geosphere extends Surface { private long ageStamp; public Geosphere(int totalSize, int threadsDelay, int threadCount) { super(totalSize, threadsDelay, threadCount); ageStamp = 0; produceTasks(() -> { return new MantleRadiation(this); }); produceTasks(() -> {
// Path: src/worlds/planet/Surface.java // public abstract class Surface extends SurfaceMap<PlanetCell> { // // /** // * The number of years that pass for each step of erosion // */ // public static long GEOUPDATE; // private long geologicalTimeStamp; // // /** // * The age of the planet in years // */ // public static AtomicLong planetAge; // // /** // * The number of years that pass for each update to the geosphere // */ // public static long timeStep; // // public final static int HEIGHTMAP = 0; // public final static int STRATAMAP = 1; // public final static int LANDOCEAN = 2; // // private static final int DEFAULT_THREAD_DELAY = 50; // // private final MinMaxHeightFactory mhFactory; // // static { // timeStep = 7125000; // } // // /** // * Constructs a new Surface with an empty map. // * // * @param totalSize The size of the surface // * @param threadsDelay The amount of time to delay each frame in milliseconds. // * @param threadCount The number of threads that will work on the map // */ // public Surface(int totalSize, int threadsDelay, int threadCount) { // super(totalSize, DEFAULT_THREAD_DELAY); // setupThreads(threadCount, threadsDelay); // setupDefaultMap(threadCount); // mhFactory = new MinMaxHeightFactory(this); // produceTasks(mhFactory); // reset(); // } // // /** // * Resets the surface to an empty map and resets the planet's age. This method // * should be calling the <code>buildMap()</code> method. // */ // @Override // public final void reset() { // planetAge = new AtomicLong(0); // geologicalTimeStamp = 0; // pauseThreads(); // buildMap(); // addTaskToThreads(new SetParentThreads()); // playThreads(); // } // // public long getPlanetAge() { // return planetAge.get(); // } // // public void updatePlanetAge() { // long curPlanetAge = planetAge.getAndAdd(timeStep); // if (curPlanetAge - geologicalTimeStamp > GEOUPDATE) { // geologicalTimeStamp = curPlanetAge; // } // } // // @Override // public PlanetCell generateCell(int x, int y) { // return new PlanetCell(x, y); // } // // public float getHighestHeight() { // return mhFactory.getHighestHeight(); // } // // public float getLowestHeight() { // return mhFactory.getLowestHeight(); // } // // } // // Path: src/worlds/planet/geosphere/tasks/MantleConduction.java // public class MantleConduction extends Task { // // private final Geosphere surface; // private final Delay delay; // // public MantleConduction(Geosphere surface) { // this.surface = surface; // delay = new Delay(250); // } // // @Override // public void construct() {} // // @Override // public boolean check() throws Exception { // return delay.check(); // } // // @Override // public void before() throws Exception { // } // // @Override // public void perform(int x, int y) throws Exception { // GeoCell cell = surface.getCellAt(x, y); // Vec2[] cells = Util.getCellIndexesFrom(cell.getGridPosition(), surface.getTerrainSize()); // float temp = cell.getMantleTemperature(); // for (Vec2 pos : cells) { // GeoCell neighborCell = surface.getCellAt(pos); // float cellTemp = neighborCell.getMantleTemperature(); // float tempChange = (PlanetCell.length * (temp - cellTemp)) / (1e7f); // cell.addToMantleHeat(-tempChange); // } // } // // @Override // public void after() throws Exception { // } // // } // // Path: src/worlds/planet/geosphere/tasks/MantleRadiation.java // public class MantleRadiation extends Task { // // private final Geosphere geosphere; // private final Delay delay; // // // public MantleRadiation(Geosphere geosphere) { // this.geosphere = geosphere; // delay = new Delay(400); // } // // @Override // public void before() { // } // // @Override // public void perform(int x, int y) { // GeoCell cell = geosphere.getCellAt(x, y); // float heatFromMantle = Util.calcHeatRadiation(cell.getMantleTemperature()); // float denom = (cell.getTotalMass() * cell.getSpecificHeat()); // denom = denom == 0 ? 1 : denom; // float tempChangeToMantle = heatFromMantle / denom; // // cell.addToMantleHeat(-tempChangeToMantle * 0.001f); // } // // @Override // public void after() { // } // // @Override // public void construct() { // } // // @Override // public boolean check() { // return delay.check(); // } // // } // Path: src/worlds/planet/geosphere/Geosphere.java import worlds.planet.Surface; import worlds.planet.geosphere.tasks.MantleConduction; import worlds.planet.geosphere.tasks.MantleRadiation; package worlds.planet.geosphere; /** * Contains all logic that works on the geology of the planet. * * @author Richard DeSilvey */ public abstract class Geosphere extends Surface { private long ageStamp; public Geosphere(int totalSize, int threadsDelay, int threadCount) { super(totalSize, threadsDelay, threadCount); ageStamp = 0; produceTasks(() -> { return new MantleRadiation(this); }); produceTasks(() -> {
return new MantleConduction(this);
redferret/planet
test/MapThreadAndTaskTest.java
// Path: src/engine/util/task/Boundaries.java // public final class Boundaries { // // private int lowerXBound, upperXBound, lowerYBound, upperYBound; // // /** // * Constructs boundaries where both axis have the same ranges. // * // * @param lowerBound The lower bounds // * @param upperBound The upper bounds // */ // public Boundaries(int lowerBound, int upperBound) { // this(lowerBound, upperBound, lowerBound, upperBound); // } // // public Boundaries(int lowerXBound, int upperXBound, int lowerYBound, int upperYBound) { // // if (lowerXBound < 0 || upperXBound < 0) { // throw new IllegalArgumentException("Can't have negative bounds"); // } // if (lowerYBound < 0 || upperYBound < 0) { // throw new IllegalArgumentException("Can't have negative bounds"); // } // // this.lowerXBound = lowerXBound; // this.upperXBound = upperXBound; // this.lowerYBound = lowerYBound; // this.upperYBound = upperYBound; // } // // public int getLowerXBound() { // return lowerXBound; // } // // public int getLowerYBound() { // return lowerYBound; // } // // public int getUpperXBound() { // return upperXBound; // } // // public int getUpperYBound() { // return upperYBound; // } // // } // // Path: src/engine/util/concurrent/MThread.java // public class MThread extends TaskRunner { // // private final TaskManager manager; // /** // * Other threads may want to update or apply an event to other cells // * not belonging to that thread. The other thread will post an update to // * this thread to process the event using the queue. // */ // private final ConcurrentLinkedDeque<Event> eventQueue; // // private static final boolean CONTINUOUS = true; // // private final CyclicBarrier waitingGate; // // public MThread(int delay) { // this(delay, new Boundaries(0, 0), new CyclicBarrier(1)); // } // // public MThread(int delay, Boundaries bounds) { // this(delay, bounds, new CyclicBarrier(1)); // } // // /** // * Constructs a new MapThread. // * // * @param delay The amount of time to delay each frame in milliseconds // * @param bounds The surface boundaries // * @param waitingGate The CyclicBarrier to synchronize with other threads // */ // public MThread(int delay, Boundaries bounds, CyclicBarrier waitingGate) { // super(delay, CONTINUOUS); // this.waitingGate = waitingGate; // manager = new TaskManager(bounds); // eventQueue = new ConcurrentLinkedDeque<>(); // } // // @Override // public final void update() throws Exception { // waitingGate.await(); // processEventQueue(); // manager.performTasks(); // manager.trimTasks(); // } // // public void pushEvent(Event event) { // eventQueue.push(event); // } // // public void processEventQueue() { // eventQueue.forEach(event -> { // event.execute(); // }); // } // // public final void addTask(Task task) { // task.setThread(this); // manager.addTask(task); // } // // public TaskManager getManager() { // return manager; // } // } // // Path: src/engine/util/task/Task.java // public abstract class Task { // // /** // * A public, mutable, reference to the thread working on this task. If this // * object reference is null then this task is not part of a TaskFactory. // */ // private MThread parentThread = null; // // /** // * Marks this Task as being a single task to run only once. By default // * this is set to false. // */ // protected boolean singleTask = false; // // public void setThread(MThread thread) { // parentThread = thread; // } // // public final MThread getThread() { // return parentThread; // } // // public boolean isNotChildCell(Cell cell) { // return cell.getParentThread() != parentThread; // } // // public boolean isSingleTask() { // return singleTask; // } // // /** // * This method is called when a task is added to a TaskManager. This method is // * used because in some instances the rest of the framework hasn't been // * initialized yet. CompoundTasks that add subtasks would use this method // * instead of a constructor, otherwise the constructor is called then // * this method is called. // */ // public abstract void construct(); // // /** // * This method is called before updating each cell on the surface. If this // * method returns false then perform on the current frame won't be called. // * // * @return true if <code>perform(x, y)</code> is to be invoked, false will // * skip the current frame. // * @throws java.lang.Exception // */ // public abstract boolean check() throws Exception; // // /** // * An optional before-processing method called before all calls to perform(x, // * y) or the single call to perform() finishes. // */ // public abstract void before() throws Exception; // // /** // * This method will be called for each cell on the surface. This method will // * only be called if <code>check()</code> returns true. Both x and y are // * bounded by [0, w) where w is the width of the map. // * // * @param x The x coordinate of the cell. // * @param y The y coordinate of the cell. // */ // public abstract void perform(int x, int y) throws Exception; // // /** // * An optional after-processing method called after all calls to perform(x, y) // * or the single call to perform() finishes. // */ // public abstract void after() throws Exception; // // }
import java.util.concurrent.CyclicBarrier; import org.junit.After; import org.junit.Before; import org.junit.Test; import engine.util.task.Boundaries; import engine.util.concurrent.MThread; import engine.util.task.Task; import static org.junit.Assert.*;
/** * Runs tests on using Tasks in a SurfaceThread. * * @author Richard DeSilvey */ public class MapThreadAndTaskTest { private CyclicBarrier waitingGate; private MThread testThread;
// Path: src/engine/util/task/Boundaries.java // public final class Boundaries { // // private int lowerXBound, upperXBound, lowerYBound, upperYBound; // // /** // * Constructs boundaries where both axis have the same ranges. // * // * @param lowerBound The lower bounds // * @param upperBound The upper bounds // */ // public Boundaries(int lowerBound, int upperBound) { // this(lowerBound, upperBound, lowerBound, upperBound); // } // // public Boundaries(int lowerXBound, int upperXBound, int lowerYBound, int upperYBound) { // // if (lowerXBound < 0 || upperXBound < 0) { // throw new IllegalArgumentException("Can't have negative bounds"); // } // if (lowerYBound < 0 || upperYBound < 0) { // throw new IllegalArgumentException("Can't have negative bounds"); // } // // this.lowerXBound = lowerXBound; // this.upperXBound = upperXBound; // this.lowerYBound = lowerYBound; // this.upperYBound = upperYBound; // } // // public int getLowerXBound() { // return lowerXBound; // } // // public int getLowerYBound() { // return lowerYBound; // } // // public int getUpperXBound() { // return upperXBound; // } // // public int getUpperYBound() { // return upperYBound; // } // // } // // Path: src/engine/util/concurrent/MThread.java // public class MThread extends TaskRunner { // // private final TaskManager manager; // /** // * Other threads may want to update or apply an event to other cells // * not belonging to that thread. The other thread will post an update to // * this thread to process the event using the queue. // */ // private final ConcurrentLinkedDeque<Event> eventQueue; // // private static final boolean CONTINUOUS = true; // // private final CyclicBarrier waitingGate; // // public MThread(int delay) { // this(delay, new Boundaries(0, 0), new CyclicBarrier(1)); // } // // public MThread(int delay, Boundaries bounds) { // this(delay, bounds, new CyclicBarrier(1)); // } // // /** // * Constructs a new MapThread. // * // * @param delay The amount of time to delay each frame in milliseconds // * @param bounds The surface boundaries // * @param waitingGate The CyclicBarrier to synchronize with other threads // */ // public MThread(int delay, Boundaries bounds, CyclicBarrier waitingGate) { // super(delay, CONTINUOUS); // this.waitingGate = waitingGate; // manager = new TaskManager(bounds); // eventQueue = new ConcurrentLinkedDeque<>(); // } // // @Override // public final void update() throws Exception { // waitingGate.await(); // processEventQueue(); // manager.performTasks(); // manager.trimTasks(); // } // // public void pushEvent(Event event) { // eventQueue.push(event); // } // // public void processEventQueue() { // eventQueue.forEach(event -> { // event.execute(); // }); // } // // public final void addTask(Task task) { // task.setThread(this); // manager.addTask(task); // } // // public TaskManager getManager() { // return manager; // } // } // // Path: src/engine/util/task/Task.java // public abstract class Task { // // /** // * A public, mutable, reference to the thread working on this task. If this // * object reference is null then this task is not part of a TaskFactory. // */ // private MThread parentThread = null; // // /** // * Marks this Task as being a single task to run only once. By default // * this is set to false. // */ // protected boolean singleTask = false; // // public void setThread(MThread thread) { // parentThread = thread; // } // // public final MThread getThread() { // return parentThread; // } // // public boolean isNotChildCell(Cell cell) { // return cell.getParentThread() != parentThread; // } // // public boolean isSingleTask() { // return singleTask; // } // // /** // * This method is called when a task is added to a TaskManager. This method is // * used because in some instances the rest of the framework hasn't been // * initialized yet. CompoundTasks that add subtasks would use this method // * instead of a constructor, otherwise the constructor is called then // * this method is called. // */ // public abstract void construct(); // // /** // * This method is called before updating each cell on the surface. If this // * method returns false then perform on the current frame won't be called. // * // * @return true if <code>perform(x, y)</code> is to be invoked, false will // * skip the current frame. // * @throws java.lang.Exception // */ // public abstract boolean check() throws Exception; // // /** // * An optional before-processing method called before all calls to perform(x, // * y) or the single call to perform() finishes. // */ // public abstract void before() throws Exception; // // /** // * This method will be called for each cell on the surface. This method will // * only be called if <code>check()</code> returns true. Both x and y are // * bounded by [0, w) where w is the width of the map. // * // * @param x The x coordinate of the cell. // * @param y The y coordinate of the cell. // */ // public abstract void perform(int x, int y) throws Exception; // // /** // * An optional after-processing method called after all calls to perform(x, y) // * or the single call to perform() finishes. // */ // public abstract void after() throws Exception; // // } // Path: test/MapThreadAndTaskTest.java import java.util.concurrent.CyclicBarrier; import org.junit.After; import org.junit.Before; import org.junit.Test; import engine.util.task.Boundaries; import engine.util.concurrent.MThread; import engine.util.task.Task; import static org.junit.Assert.*; /** * Runs tests on using Tasks in a SurfaceThread. * * @author Richard DeSilvey */ public class MapThreadAndTaskTest { private CyclicBarrier waitingGate; private MThread testThread;
private static final Boundaries BOUNDS = new Boundaries(0, 100, 0, 100);
redferret/planet
src/engine/util/task/Task.java
// Path: src/engine/surface/Cell.java // public abstract class Cell { // // private final Vec2 gridPosition, actualPosition; // private MThread parentThread; // // public Cell(int x, int y) { // gridPosition = new Vec2(x, y); // actualPosition = new Vec2(x, y); // } // // public void setParentThread(MThread parentThread) { // this.parentThread = parentThread; // } // // public MThread getParentThread() { // return parentThread; // } // // public int getX() { // return (int) gridPosition.getX(); // } // // public int getY() { // return (int) gridPosition.getY(); // } // // /** // * The position in the hash map as x and y componets. // * // * @return The copy of the cell position object. // */ // public Vec2 getGridPosition() { // return gridPosition.copy(); // } // // /** // * The actual position of this cell. By default this position will be equal to // * it's grid position. // * // * @return // */ // public Vec2 getActualPosition() { // return actualPosition; // } // // // public abstract List<Integer[]> render(List<Integer[]> settings); // // public String toString() { // return "[" + gridPosition.getX() + ", " + gridPosition.getY() + "]" // + "[" + actualPosition.getX() + ", " + actualPosition.getY() + "]"; // } // // } // // Path: src/engine/util/concurrent/MThread.java // public class MThread extends TaskRunner { // // private final TaskManager manager; // /** // * Other threads may want to update or apply an event to other cells // * not belonging to that thread. The other thread will post an update to // * this thread to process the event using the queue. // */ // private final ConcurrentLinkedDeque<Event> eventQueue; // // private static final boolean CONTINUOUS = true; // // private final CyclicBarrier waitingGate; // // public MThread(int delay) { // this(delay, new Boundaries(0, 0), new CyclicBarrier(1)); // } // // public MThread(int delay, Boundaries bounds) { // this(delay, bounds, new CyclicBarrier(1)); // } // // /** // * Constructs a new MapThread. // * // * @param delay The amount of time to delay each frame in milliseconds // * @param bounds The surface boundaries // * @param waitingGate The CyclicBarrier to synchronize with other threads // */ // public MThread(int delay, Boundaries bounds, CyclicBarrier waitingGate) { // super(delay, CONTINUOUS); // this.waitingGate = waitingGate; // manager = new TaskManager(bounds); // eventQueue = new ConcurrentLinkedDeque<>(); // } // // @Override // public final void update() throws Exception { // waitingGate.await(); // processEventQueue(); // manager.performTasks(); // manager.trimTasks(); // } // // public void pushEvent(Event event) { // eventQueue.push(event); // } // // public void processEventQueue() { // eventQueue.forEach(event -> { // event.execute(); // }); // } // // public final void addTask(Task task) { // task.setThread(this); // manager.addTask(task); // } // // public TaskManager getManager() { // return manager; // } // }
import engine.surface.Cell; import engine.util.concurrent.MThread;
package engine.util.task; /** * A Task is something the simulation will perform given a condition. * * @author Richard DeSilvey */ public abstract class Task { /** * A public, mutable, reference to the thread working on this task. If this * object reference is null then this task is not part of a TaskFactory. */ private MThread parentThread = null; /** * Marks this Task as being a single task to run only once. By default * this is set to false. */ protected boolean singleTask = false; public void setThread(MThread thread) { parentThread = thread; } public final MThread getThread() { return parentThread; }
// Path: src/engine/surface/Cell.java // public abstract class Cell { // // private final Vec2 gridPosition, actualPosition; // private MThread parentThread; // // public Cell(int x, int y) { // gridPosition = new Vec2(x, y); // actualPosition = new Vec2(x, y); // } // // public void setParentThread(MThread parentThread) { // this.parentThread = parentThread; // } // // public MThread getParentThread() { // return parentThread; // } // // public int getX() { // return (int) gridPosition.getX(); // } // // public int getY() { // return (int) gridPosition.getY(); // } // // /** // * The position in the hash map as x and y componets. // * // * @return The copy of the cell position object. // */ // public Vec2 getGridPosition() { // return gridPosition.copy(); // } // // /** // * The actual position of this cell. By default this position will be equal to // * it's grid position. // * // * @return // */ // public Vec2 getActualPosition() { // return actualPosition; // } // // // public abstract List<Integer[]> render(List<Integer[]> settings); // // public String toString() { // return "[" + gridPosition.getX() + ", " + gridPosition.getY() + "]" // + "[" + actualPosition.getX() + ", " + actualPosition.getY() + "]"; // } // // } // // Path: src/engine/util/concurrent/MThread.java // public class MThread extends TaskRunner { // // private final TaskManager manager; // /** // * Other threads may want to update or apply an event to other cells // * not belonging to that thread. The other thread will post an update to // * this thread to process the event using the queue. // */ // private final ConcurrentLinkedDeque<Event> eventQueue; // // private static final boolean CONTINUOUS = true; // // private final CyclicBarrier waitingGate; // // public MThread(int delay) { // this(delay, new Boundaries(0, 0), new CyclicBarrier(1)); // } // // public MThread(int delay, Boundaries bounds) { // this(delay, bounds, new CyclicBarrier(1)); // } // // /** // * Constructs a new MapThread. // * // * @param delay The amount of time to delay each frame in milliseconds // * @param bounds The surface boundaries // * @param waitingGate The CyclicBarrier to synchronize with other threads // */ // public MThread(int delay, Boundaries bounds, CyclicBarrier waitingGate) { // super(delay, CONTINUOUS); // this.waitingGate = waitingGate; // manager = new TaskManager(bounds); // eventQueue = new ConcurrentLinkedDeque<>(); // } // // @Override // public final void update() throws Exception { // waitingGate.await(); // processEventQueue(); // manager.performTasks(); // manager.trimTasks(); // } // // public void pushEvent(Event event) { // eventQueue.push(event); // } // // public void processEventQueue() { // eventQueue.forEach(event -> { // event.execute(); // }); // } // // public final void addTask(Task task) { // task.setThread(this); // manager.addTask(task); // } // // public TaskManager getManager() { // return manager; // } // } // Path: src/engine/util/task/Task.java import engine.surface.Cell; import engine.util.concurrent.MThread; package engine.util.task; /** * A Task is something the simulation will perform given a condition. * * @author Richard DeSilvey */ public abstract class Task { /** * A public, mutable, reference to the thread working on this task. If this * object reference is null then this task is not part of a TaskFactory. */ private MThread parentThread = null; /** * Marks this Task as being a single task to run only once. By default * this is set to false. */ protected boolean singleTask = false; public void setThread(MThread thread) { parentThread = thread; } public final MThread getThread() { return parentThread; }
public boolean isNotChildCell(Cell cell) {
redferret/planet
src/engine/surface/Cell.java
// Path: src/engine/util/Vec2.java // public class Vec2 { // // private float x, y; // // public Vec2() { // this(0, 0); // } // // public Vec2(Vec2 toCopy) { // this(toCopy.x, toCopy.y); // } // // public Vec2(float x, float y) { // this.x = x; // this.y = y; // } // // public float getX() { // return x; // } // // public float getY() { // return y; // } // // public Vec2 copy() { // return new Vec2(this); // } // // public void add(Vec2 p) { // this.x += p.x; // this.y += p.y; // } // // public void mul(Vec2 p) { // this.x *= p.x; // this.y *= p.y; // } // // public void div(float n) { // this.x /= n; // this.y /= n; // } // // public void normalize() { // float mag = mag(); // if (mag != 0) { // div(mag); // } // } // // public void set(Vec2 p) { // this.x = p.x; // this.y = p.y; // } // // public void neg() { // x = -x; // y = -y; // } // // public float mag() { // return (float) Math.sqrt((x * x + y * y)); // } // // public Vec2 truncate() { // return new Vec2((int) x, (int) y); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || !(obj instanceof Vec2)) { // return false; // } else { // Vec2 o = (Vec2) obj; // return o.x == x && o.y == y; // } // } // // @Override // public int hashCode() { // int hash = 5; // hash = 17 * hash + (int) this.x; // hash = 17 * hash + (int) this.y; // return hash; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // str.append("[").append(x).append(", ").append(y).append("]"); // return str.toString(); // } // // public boolean isZero() { // return mag() == 0; // } // // public void zero() { // this.set(new Vec2()); // } // // } // // Path: src/engine/util/concurrent/MThread.java // public class MThread extends TaskRunner { // // private final TaskManager manager; // /** // * Other threads may want to update or apply an event to other cells // * not belonging to that thread. The other thread will post an update to // * this thread to process the event using the queue. // */ // private final ConcurrentLinkedDeque<Event> eventQueue; // // private static final boolean CONTINUOUS = true; // // private final CyclicBarrier waitingGate; // // public MThread(int delay) { // this(delay, new Boundaries(0, 0), new CyclicBarrier(1)); // } // // public MThread(int delay, Boundaries bounds) { // this(delay, bounds, new CyclicBarrier(1)); // } // // /** // * Constructs a new MapThread. // * // * @param delay The amount of time to delay each frame in milliseconds // * @param bounds The surface boundaries // * @param waitingGate The CyclicBarrier to synchronize with other threads // */ // public MThread(int delay, Boundaries bounds, CyclicBarrier waitingGate) { // super(delay, CONTINUOUS); // this.waitingGate = waitingGate; // manager = new TaskManager(bounds); // eventQueue = new ConcurrentLinkedDeque<>(); // } // // @Override // public final void update() throws Exception { // waitingGate.await(); // processEventQueue(); // manager.performTasks(); // manager.trimTasks(); // } // // public void pushEvent(Event event) { // eventQueue.push(event); // } // // public void processEventQueue() { // eventQueue.forEach(event -> { // event.execute(); // }); // } // // public final void addTask(Task task) { // task.setThread(this); // manager.addTask(task); // } // // public TaskManager getManager() { // return manager; // } // }
import engine.util.Vec2; import engine.util.concurrent.MThread;
package engine.surface; /** * The cell is a base class for each cell contained in a SurfaceMap. The Cell * has two representations for position. It's grid position which is immutable * and the actual position. The actual position is mutable and can be used as a * way to describe an 'out of resolution' position. * * @author Richard DeSilvey */ public abstract class Cell { private final Vec2 gridPosition, actualPosition;
// Path: src/engine/util/Vec2.java // public class Vec2 { // // private float x, y; // // public Vec2() { // this(0, 0); // } // // public Vec2(Vec2 toCopy) { // this(toCopy.x, toCopy.y); // } // // public Vec2(float x, float y) { // this.x = x; // this.y = y; // } // // public float getX() { // return x; // } // // public float getY() { // return y; // } // // public Vec2 copy() { // return new Vec2(this); // } // // public void add(Vec2 p) { // this.x += p.x; // this.y += p.y; // } // // public void mul(Vec2 p) { // this.x *= p.x; // this.y *= p.y; // } // // public void div(float n) { // this.x /= n; // this.y /= n; // } // // public void normalize() { // float mag = mag(); // if (mag != 0) { // div(mag); // } // } // // public void set(Vec2 p) { // this.x = p.x; // this.y = p.y; // } // // public void neg() { // x = -x; // y = -y; // } // // public float mag() { // return (float) Math.sqrt((x * x + y * y)); // } // // public Vec2 truncate() { // return new Vec2((int) x, (int) y); // } // // @Override // public boolean equals(Object obj) { // if (obj == null || !(obj instanceof Vec2)) { // return false; // } else { // Vec2 o = (Vec2) obj; // return o.x == x && o.y == y; // } // } // // @Override // public int hashCode() { // int hash = 5; // hash = 17 * hash + (int) this.x; // hash = 17 * hash + (int) this.y; // return hash; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // str.append("[").append(x).append(", ").append(y).append("]"); // return str.toString(); // } // // public boolean isZero() { // return mag() == 0; // } // // public void zero() { // this.set(new Vec2()); // } // // } // // Path: src/engine/util/concurrent/MThread.java // public class MThread extends TaskRunner { // // private final TaskManager manager; // /** // * Other threads may want to update or apply an event to other cells // * not belonging to that thread. The other thread will post an update to // * this thread to process the event using the queue. // */ // private final ConcurrentLinkedDeque<Event> eventQueue; // // private static final boolean CONTINUOUS = true; // // private final CyclicBarrier waitingGate; // // public MThread(int delay) { // this(delay, new Boundaries(0, 0), new CyclicBarrier(1)); // } // // public MThread(int delay, Boundaries bounds) { // this(delay, bounds, new CyclicBarrier(1)); // } // // /** // * Constructs a new MapThread. // * // * @param delay The amount of time to delay each frame in milliseconds // * @param bounds The surface boundaries // * @param waitingGate The CyclicBarrier to synchronize with other threads // */ // public MThread(int delay, Boundaries bounds, CyclicBarrier waitingGate) { // super(delay, CONTINUOUS); // this.waitingGate = waitingGate; // manager = new TaskManager(bounds); // eventQueue = new ConcurrentLinkedDeque<>(); // } // // @Override // public final void update() throws Exception { // waitingGate.await(); // processEventQueue(); // manager.performTasks(); // manager.trimTasks(); // } // // public void pushEvent(Event event) { // eventQueue.push(event); // } // // public void processEventQueue() { // eventQueue.forEach(event -> { // event.execute(); // }); // } // // public final void addTask(Task task) { // task.setThread(this); // manager.addTask(task); // } // // public TaskManager getManager() { // return manager; // } // } // Path: src/engine/surface/Cell.java import engine.util.Vec2; import engine.util.concurrent.MThread; package engine.surface; /** * The cell is a base class for each cell contained in a SurfaceMap. The Cell * has two representations for position. It's grid position which is immutable * and the actual position. The actual position is mutable and can be used as a * way to describe an 'out of resolution' position. * * @author Richard DeSilvey */ public abstract class Cell { private final Vec2 gridPosition, actualPosition;
private MThread parentThread;
redferret/planet
src/engine/util/concurrent/MThread.java
// Path: src/engine/util/task/Boundaries.java // public final class Boundaries { // // private int lowerXBound, upperXBound, lowerYBound, upperYBound; // // /** // * Constructs boundaries where both axis have the same ranges. // * // * @param lowerBound The lower bounds // * @param upperBound The upper bounds // */ // public Boundaries(int lowerBound, int upperBound) { // this(lowerBound, upperBound, lowerBound, upperBound); // } // // public Boundaries(int lowerXBound, int upperXBound, int lowerYBound, int upperYBound) { // // if (lowerXBound < 0 || upperXBound < 0) { // throw new IllegalArgumentException("Can't have negative bounds"); // } // if (lowerYBound < 0 || upperYBound < 0) { // throw new IllegalArgumentException("Can't have negative bounds"); // } // // this.lowerXBound = lowerXBound; // this.upperXBound = upperXBound; // this.lowerYBound = lowerYBound; // this.upperYBound = upperYBound; // } // // public int getLowerXBound() { // return lowerXBound; // } // // public int getLowerYBound() { // return lowerYBound; // } // // public int getUpperXBound() { // return upperXBound; // } // // public int getUpperYBound() { // return upperYBound; // } // // } // // Path: src/engine/util/task/Task.java // public abstract class Task { // // /** // * A public, mutable, reference to the thread working on this task. If this // * object reference is null then this task is not part of a TaskFactory. // */ // private MThread parentThread = null; // // /** // * Marks this Task as being a single task to run only once. By default // * this is set to false. // */ // protected boolean singleTask = false; // // public void setThread(MThread thread) { // parentThread = thread; // } // // public final MThread getThread() { // return parentThread; // } // // public boolean isNotChildCell(Cell cell) { // return cell.getParentThread() != parentThread; // } // // public boolean isSingleTask() { // return singleTask; // } // // /** // * This method is called when a task is added to a TaskManager. This method is // * used because in some instances the rest of the framework hasn't been // * initialized yet. CompoundTasks that add subtasks would use this method // * instead of a constructor, otherwise the constructor is called then // * this method is called. // */ // public abstract void construct(); // // /** // * This method is called before updating each cell on the surface. If this // * method returns false then perform on the current frame won't be called. // * // * @return true if <code>perform(x, y)</code> is to be invoked, false will // * skip the current frame. // * @throws java.lang.Exception // */ // public abstract boolean check() throws Exception; // // /** // * An optional before-processing method called before all calls to perform(x, // * y) or the single call to perform() finishes. // */ // public abstract void before() throws Exception; // // /** // * This method will be called for each cell on the surface. This method will // * only be called if <code>check()</code> returns true. Both x and y are // * bounded by [0, w) where w is the width of the map. // * // * @param x The x coordinate of the cell. // * @param y The y coordinate of the cell. // */ // public abstract void perform(int x, int y) throws Exception; // // /** // * An optional after-processing method called after all calls to perform(x, y) // * or the single call to perform() finishes. // */ // public abstract void after() throws Exception; // // } // // Path: src/engine/util/task/TaskManager.java // public class TaskManager { // // private final List<Task> tasks; // protected Boundaries bounds; // // public TaskManager(Boundaries bounds) { // tasks = new ArrayList<>(); // this.bounds = bounds; // } // // /** // * Adding a task to a manager will invoke the Task's 'construct' method. // * // * @param task The task being added to this manager. // */ // public void addTask(Task task) { // task.construct(); // tasks.add(task); // } // // public Boundaries getBounds() { // return bounds; // } // // public void performTasks() throws Exception { // int lowerYBound = bounds.getLowerYBound(); // int upperYBound = bounds.getUpperYBound(); // int lowerXBound = bounds.getLowerXBound(); // int upperXBound = bounds.getUpperXBound(); // // for (Task task : tasks) { // if (task.check()) { // task.before(); // // for (int x = lowerXBound; x < upperXBound; x++) { // for (int y = lowerYBound; y < upperYBound; y++){ // task.perform(x, y); // } // } // task.after(); // } // } // } // // public void trimTasks() { // tasks.removeIf(task -> task.isSingleTask()); // } // }
import java.util.concurrent.CyclicBarrier; import engine.util.task.Boundaries; import engine.util.task.Task; import engine.util.task.TaskManager; import java.util.concurrent.ConcurrentLinkedDeque;
package engine.util.concurrent; /** * A surface can be broken up into sections where a MThread can modify and control that section. * * @author Richard DeSilvey */ public class MThread extends TaskRunner { private final TaskManager manager; /** * Other threads may want to update or apply an event to other cells * not belonging to that thread. The other thread will post an update to * this thread to process the event using the queue. */ private final ConcurrentLinkedDeque<Event> eventQueue; private static final boolean CONTINUOUS = true; private final CyclicBarrier waitingGate; public MThread(int delay) {
// Path: src/engine/util/task/Boundaries.java // public final class Boundaries { // // private int lowerXBound, upperXBound, lowerYBound, upperYBound; // // /** // * Constructs boundaries where both axis have the same ranges. // * // * @param lowerBound The lower bounds // * @param upperBound The upper bounds // */ // public Boundaries(int lowerBound, int upperBound) { // this(lowerBound, upperBound, lowerBound, upperBound); // } // // public Boundaries(int lowerXBound, int upperXBound, int lowerYBound, int upperYBound) { // // if (lowerXBound < 0 || upperXBound < 0) { // throw new IllegalArgumentException("Can't have negative bounds"); // } // if (lowerYBound < 0 || upperYBound < 0) { // throw new IllegalArgumentException("Can't have negative bounds"); // } // // this.lowerXBound = lowerXBound; // this.upperXBound = upperXBound; // this.lowerYBound = lowerYBound; // this.upperYBound = upperYBound; // } // // public int getLowerXBound() { // return lowerXBound; // } // // public int getLowerYBound() { // return lowerYBound; // } // // public int getUpperXBound() { // return upperXBound; // } // // public int getUpperYBound() { // return upperYBound; // } // // } // // Path: src/engine/util/task/Task.java // public abstract class Task { // // /** // * A public, mutable, reference to the thread working on this task. If this // * object reference is null then this task is not part of a TaskFactory. // */ // private MThread parentThread = null; // // /** // * Marks this Task as being a single task to run only once. By default // * this is set to false. // */ // protected boolean singleTask = false; // // public void setThread(MThread thread) { // parentThread = thread; // } // // public final MThread getThread() { // return parentThread; // } // // public boolean isNotChildCell(Cell cell) { // return cell.getParentThread() != parentThread; // } // // public boolean isSingleTask() { // return singleTask; // } // // /** // * This method is called when a task is added to a TaskManager. This method is // * used because in some instances the rest of the framework hasn't been // * initialized yet. CompoundTasks that add subtasks would use this method // * instead of a constructor, otherwise the constructor is called then // * this method is called. // */ // public abstract void construct(); // // /** // * This method is called before updating each cell on the surface. If this // * method returns false then perform on the current frame won't be called. // * // * @return true if <code>perform(x, y)</code> is to be invoked, false will // * skip the current frame. // * @throws java.lang.Exception // */ // public abstract boolean check() throws Exception; // // /** // * An optional before-processing method called before all calls to perform(x, // * y) or the single call to perform() finishes. // */ // public abstract void before() throws Exception; // // /** // * This method will be called for each cell on the surface. This method will // * only be called if <code>check()</code> returns true. Both x and y are // * bounded by [0, w) where w is the width of the map. // * // * @param x The x coordinate of the cell. // * @param y The y coordinate of the cell. // */ // public abstract void perform(int x, int y) throws Exception; // // /** // * An optional after-processing method called after all calls to perform(x, y) // * or the single call to perform() finishes. // */ // public abstract void after() throws Exception; // // } // // Path: src/engine/util/task/TaskManager.java // public class TaskManager { // // private final List<Task> tasks; // protected Boundaries bounds; // // public TaskManager(Boundaries bounds) { // tasks = new ArrayList<>(); // this.bounds = bounds; // } // // /** // * Adding a task to a manager will invoke the Task's 'construct' method. // * // * @param task The task being added to this manager. // */ // public void addTask(Task task) { // task.construct(); // tasks.add(task); // } // // public Boundaries getBounds() { // return bounds; // } // // public void performTasks() throws Exception { // int lowerYBound = bounds.getLowerYBound(); // int upperYBound = bounds.getUpperYBound(); // int lowerXBound = bounds.getLowerXBound(); // int upperXBound = bounds.getUpperXBound(); // // for (Task task : tasks) { // if (task.check()) { // task.before(); // // for (int x = lowerXBound; x < upperXBound; x++) { // for (int y = lowerYBound; y < upperYBound; y++){ // task.perform(x, y); // } // } // task.after(); // } // } // } // // public void trimTasks() { // tasks.removeIf(task -> task.isSingleTask()); // } // } // Path: src/engine/util/concurrent/MThread.java import java.util.concurrent.CyclicBarrier; import engine.util.task.Boundaries; import engine.util.task.Task; import engine.util.task.TaskManager; import java.util.concurrent.ConcurrentLinkedDeque; package engine.util.concurrent; /** * A surface can be broken up into sections where a MThread can modify and control that section. * * @author Richard DeSilvey */ public class MThread extends TaskRunner { private final TaskManager manager; /** * Other threads may want to update or apply an event to other cells * not belonging to that thread. The other thread will post an update to * this thread to process the event using the queue. */ private final ConcurrentLinkedDeque<Event> eventQueue; private static final boolean CONTINUOUS = true; private final CyclicBarrier waitingGate; public MThread(int delay) {
this(delay, new Boundaries(0, 0), new CyclicBarrier(1));
redferret/planet
src/engine/util/concurrent/MThread.java
// Path: src/engine/util/task/Boundaries.java // public final class Boundaries { // // private int lowerXBound, upperXBound, lowerYBound, upperYBound; // // /** // * Constructs boundaries where both axis have the same ranges. // * // * @param lowerBound The lower bounds // * @param upperBound The upper bounds // */ // public Boundaries(int lowerBound, int upperBound) { // this(lowerBound, upperBound, lowerBound, upperBound); // } // // public Boundaries(int lowerXBound, int upperXBound, int lowerYBound, int upperYBound) { // // if (lowerXBound < 0 || upperXBound < 0) { // throw new IllegalArgumentException("Can't have negative bounds"); // } // if (lowerYBound < 0 || upperYBound < 0) { // throw new IllegalArgumentException("Can't have negative bounds"); // } // // this.lowerXBound = lowerXBound; // this.upperXBound = upperXBound; // this.lowerYBound = lowerYBound; // this.upperYBound = upperYBound; // } // // public int getLowerXBound() { // return lowerXBound; // } // // public int getLowerYBound() { // return lowerYBound; // } // // public int getUpperXBound() { // return upperXBound; // } // // public int getUpperYBound() { // return upperYBound; // } // // } // // Path: src/engine/util/task/Task.java // public abstract class Task { // // /** // * A public, mutable, reference to the thread working on this task. If this // * object reference is null then this task is not part of a TaskFactory. // */ // private MThread parentThread = null; // // /** // * Marks this Task as being a single task to run only once. By default // * this is set to false. // */ // protected boolean singleTask = false; // // public void setThread(MThread thread) { // parentThread = thread; // } // // public final MThread getThread() { // return parentThread; // } // // public boolean isNotChildCell(Cell cell) { // return cell.getParentThread() != parentThread; // } // // public boolean isSingleTask() { // return singleTask; // } // // /** // * This method is called when a task is added to a TaskManager. This method is // * used because in some instances the rest of the framework hasn't been // * initialized yet. CompoundTasks that add subtasks would use this method // * instead of a constructor, otherwise the constructor is called then // * this method is called. // */ // public abstract void construct(); // // /** // * This method is called before updating each cell on the surface. If this // * method returns false then perform on the current frame won't be called. // * // * @return true if <code>perform(x, y)</code> is to be invoked, false will // * skip the current frame. // * @throws java.lang.Exception // */ // public abstract boolean check() throws Exception; // // /** // * An optional before-processing method called before all calls to perform(x, // * y) or the single call to perform() finishes. // */ // public abstract void before() throws Exception; // // /** // * This method will be called for each cell on the surface. This method will // * only be called if <code>check()</code> returns true. Both x and y are // * bounded by [0, w) where w is the width of the map. // * // * @param x The x coordinate of the cell. // * @param y The y coordinate of the cell. // */ // public abstract void perform(int x, int y) throws Exception; // // /** // * An optional after-processing method called after all calls to perform(x, y) // * or the single call to perform() finishes. // */ // public abstract void after() throws Exception; // // } // // Path: src/engine/util/task/TaskManager.java // public class TaskManager { // // private final List<Task> tasks; // protected Boundaries bounds; // // public TaskManager(Boundaries bounds) { // tasks = new ArrayList<>(); // this.bounds = bounds; // } // // /** // * Adding a task to a manager will invoke the Task's 'construct' method. // * // * @param task The task being added to this manager. // */ // public void addTask(Task task) { // task.construct(); // tasks.add(task); // } // // public Boundaries getBounds() { // return bounds; // } // // public void performTasks() throws Exception { // int lowerYBound = bounds.getLowerYBound(); // int upperYBound = bounds.getUpperYBound(); // int lowerXBound = bounds.getLowerXBound(); // int upperXBound = bounds.getUpperXBound(); // // for (Task task : tasks) { // if (task.check()) { // task.before(); // // for (int x = lowerXBound; x < upperXBound; x++) { // for (int y = lowerYBound; y < upperYBound; y++){ // task.perform(x, y); // } // } // task.after(); // } // } // } // // public void trimTasks() { // tasks.removeIf(task -> task.isSingleTask()); // } // }
import java.util.concurrent.CyclicBarrier; import engine.util.task.Boundaries; import engine.util.task.Task; import engine.util.task.TaskManager; import java.util.concurrent.ConcurrentLinkedDeque;
* * @param delay The amount of time to delay each frame in milliseconds * @param bounds The surface boundaries * @param waitingGate The CyclicBarrier to synchronize with other threads */ public MThread(int delay, Boundaries bounds, CyclicBarrier waitingGate) { super(delay, CONTINUOUS); this.waitingGate = waitingGate; manager = new TaskManager(bounds); eventQueue = new ConcurrentLinkedDeque<>(); } @Override public final void update() throws Exception { waitingGate.await(); processEventQueue(); manager.performTasks(); manager.trimTasks(); } public void pushEvent(Event event) { eventQueue.push(event); } public void processEventQueue() { eventQueue.forEach(event -> { event.execute(); }); }
// Path: src/engine/util/task/Boundaries.java // public final class Boundaries { // // private int lowerXBound, upperXBound, lowerYBound, upperYBound; // // /** // * Constructs boundaries where both axis have the same ranges. // * // * @param lowerBound The lower bounds // * @param upperBound The upper bounds // */ // public Boundaries(int lowerBound, int upperBound) { // this(lowerBound, upperBound, lowerBound, upperBound); // } // // public Boundaries(int lowerXBound, int upperXBound, int lowerYBound, int upperYBound) { // // if (lowerXBound < 0 || upperXBound < 0) { // throw new IllegalArgumentException("Can't have negative bounds"); // } // if (lowerYBound < 0 || upperYBound < 0) { // throw new IllegalArgumentException("Can't have negative bounds"); // } // // this.lowerXBound = lowerXBound; // this.upperXBound = upperXBound; // this.lowerYBound = lowerYBound; // this.upperYBound = upperYBound; // } // // public int getLowerXBound() { // return lowerXBound; // } // // public int getLowerYBound() { // return lowerYBound; // } // // public int getUpperXBound() { // return upperXBound; // } // // public int getUpperYBound() { // return upperYBound; // } // // } // // Path: src/engine/util/task/Task.java // public abstract class Task { // // /** // * A public, mutable, reference to the thread working on this task. If this // * object reference is null then this task is not part of a TaskFactory. // */ // private MThread parentThread = null; // // /** // * Marks this Task as being a single task to run only once. By default // * this is set to false. // */ // protected boolean singleTask = false; // // public void setThread(MThread thread) { // parentThread = thread; // } // // public final MThread getThread() { // return parentThread; // } // // public boolean isNotChildCell(Cell cell) { // return cell.getParentThread() != parentThread; // } // // public boolean isSingleTask() { // return singleTask; // } // // /** // * This method is called when a task is added to a TaskManager. This method is // * used because in some instances the rest of the framework hasn't been // * initialized yet. CompoundTasks that add subtasks would use this method // * instead of a constructor, otherwise the constructor is called then // * this method is called. // */ // public abstract void construct(); // // /** // * This method is called before updating each cell on the surface. If this // * method returns false then perform on the current frame won't be called. // * // * @return true if <code>perform(x, y)</code> is to be invoked, false will // * skip the current frame. // * @throws java.lang.Exception // */ // public abstract boolean check() throws Exception; // // /** // * An optional before-processing method called before all calls to perform(x, // * y) or the single call to perform() finishes. // */ // public abstract void before() throws Exception; // // /** // * This method will be called for each cell on the surface. This method will // * only be called if <code>check()</code> returns true. Both x and y are // * bounded by [0, w) where w is the width of the map. // * // * @param x The x coordinate of the cell. // * @param y The y coordinate of the cell. // */ // public abstract void perform(int x, int y) throws Exception; // // /** // * An optional after-processing method called after all calls to perform(x, y) // * or the single call to perform() finishes. // */ // public abstract void after() throws Exception; // // } // // Path: src/engine/util/task/TaskManager.java // public class TaskManager { // // private final List<Task> tasks; // protected Boundaries bounds; // // public TaskManager(Boundaries bounds) { // tasks = new ArrayList<>(); // this.bounds = bounds; // } // // /** // * Adding a task to a manager will invoke the Task's 'construct' method. // * // * @param task The task being added to this manager. // */ // public void addTask(Task task) { // task.construct(); // tasks.add(task); // } // // public Boundaries getBounds() { // return bounds; // } // // public void performTasks() throws Exception { // int lowerYBound = bounds.getLowerYBound(); // int upperYBound = bounds.getUpperYBound(); // int lowerXBound = bounds.getLowerXBound(); // int upperXBound = bounds.getUpperXBound(); // // for (Task task : tasks) { // if (task.check()) { // task.before(); // // for (int x = lowerXBound; x < upperXBound; x++) { // for (int y = lowerYBound; y < upperYBound; y++){ // task.perform(x, y); // } // } // task.after(); // } // } // } // // public void trimTasks() { // tasks.removeIf(task -> task.isSingleTask()); // } // } // Path: src/engine/util/concurrent/MThread.java import java.util.concurrent.CyclicBarrier; import engine.util.task.Boundaries; import engine.util.task.Task; import engine.util.task.TaskManager; import java.util.concurrent.ConcurrentLinkedDeque; * * @param delay The amount of time to delay each frame in milliseconds * @param bounds The surface boundaries * @param waitingGate The CyclicBarrier to synchronize with other threads */ public MThread(int delay, Boundaries bounds, CyclicBarrier waitingGate) { super(delay, CONTINUOUS); this.waitingGate = waitingGate; manager = new TaskManager(bounds); eventQueue = new ConcurrentLinkedDeque<>(); } @Override public final void update() throws Exception { waitingGate.await(); processEventQueue(); manager.performTasks(); manager.trimTasks(); } public void pushEvent(Event event) { eventQueue.push(event); } public void processEventQueue() { eventQueue.forEach(event -> { event.execute(); }); }
public final void addTask(Task task) {
redferret/planet
test/DelayTest.java
// Path: src/engine/util/Delay.java // public class Delay implements Serializable { // // private int delayTime; // private int maxDelay; // // private boolean reset; // // public Delay(int frames) { // delayTime = 0; // this.maxDelay = frames; // reset = true; // } // // public Delay(int frames, boolean reset) { // delayTime = 0; // this.maxDelay = frames; // this.reset = reset; // } // // public void allowReset(boolean b) { // reset = b; // } // // /** // * Unlike check(), testDelay() will not increment // * // * @return // */ // public boolean testDelay() { // return delayTime >= maxDelay; // } // // public void reset() { // delayTime = 0; // } // // public void setDelay(int delayTime) { // this.maxDelay = delayTime; // reset(); // } // // /** // * Increment then check to see if this delay has reached it's trigger delay // * (max delay defined by constructor) // * // * @return If the delay is triggered // */ // public boolean check() { // if (++delayTime >= maxDelay) { // // if (!reset) { // delayTime = maxDelay; // } else { // reset(); // } // // return true; // // } else { // return false; // } // } // // }
import org.junit.Test; import engine.util.Delay; import static org.junit.Assert.*;
/** * Tests the Delay class. * * @author Richard DeSilvey */ public class DelayTest { private static final int FRAMES_TO_SKIP = 3; @Test public void noResetOnDelayTest() { final boolean reset = false;
// Path: src/engine/util/Delay.java // public class Delay implements Serializable { // // private int delayTime; // private int maxDelay; // // private boolean reset; // // public Delay(int frames) { // delayTime = 0; // this.maxDelay = frames; // reset = true; // } // // public Delay(int frames, boolean reset) { // delayTime = 0; // this.maxDelay = frames; // this.reset = reset; // } // // public void allowReset(boolean b) { // reset = b; // } // // /** // * Unlike check(), testDelay() will not increment // * // * @return // */ // public boolean testDelay() { // return delayTime >= maxDelay; // } // // public void reset() { // delayTime = 0; // } // // public void setDelay(int delayTime) { // this.maxDelay = delayTime; // reset(); // } // // /** // * Increment then check to see if this delay has reached it's trigger delay // * (max delay defined by constructor) // * // * @return If the delay is triggered // */ // public boolean check() { // if (++delayTime >= maxDelay) { // // if (!reset) { // delayTime = maxDelay; // } else { // reset(); // } // // return true; // // } else { // return false; // } // } // // } // Path: test/DelayTest.java import org.junit.Test; import engine.util.Delay; import static org.junit.Assert.*; /** * Tests the Delay class. * * @author Richard DeSilvey */ public class DelayTest { private static final int FRAMES_TO_SKIP = 3; @Test public void noResetOnDelayTest() { final boolean reset = false;
Delay testDelay = new Delay(FRAMES_TO_SKIP, reset);
yu-kopylov/shared-mq
src/test/java/org/sharedmq/primitives/MemoryMappedFileTest.java
// Path: src/test/java/org/sharedmq/test/CommonTests.java // public interface CommonTests { // } // // Path: src/test/java/org/sharedmq/test/TestFolder.java // public class TestFolder implements Closeable { // // private final File root; // // /** // * Creates an new folder in the default temporary-file directory. // * // * @param prefix The prefix for the new folder name. // * @param suffix The suffix for the new folder name. // * @throws IOException If folder creation fails. // */ // public TestFolder(String prefix, String suffix) throws IOException { // root = File.createTempFile(prefix, suffix); // if (!root.delete() || !root.mkdir()) { // throw new IOException("Failed to prepare test folder."); // } // } // // /** // * Returns a {@link File} object matching this folder location. // */ // public File getRoot() { // return root; // } // // /** // * Returns an {@link File} instance for the file with the given name in this test folder. // * // * @param filename The name of the faile. // */ // public File getFile(String filename) { // return new File(root, filename); // } // // /** // * Deletes this test folder and all its content. // * // * @throws IOException // */ // @Override // public void close() throws IOException { // // // A mapped byte buffer and the file mapping that it represents // // remain valid until the buffer itself is garbage-collected. // System.gc(); // // IOUtils.deleteTree(root); // } // }
import org.junit.Test; import org.junit.experimental.categories.Category; import org.sharedmq.test.CommonTests; import org.sharedmq.test.TestFolder; import java.io.IOException; import java.util.Arrays; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
package org.sharedmq.primitives; @Category(CommonTests.class) public class MemoryMappedFileTest { @Test public void testDataTypes() throws IOException { try (
// Path: src/test/java/org/sharedmq/test/CommonTests.java // public interface CommonTests { // } // // Path: src/test/java/org/sharedmq/test/TestFolder.java // public class TestFolder implements Closeable { // // private final File root; // // /** // * Creates an new folder in the default temporary-file directory. // * // * @param prefix The prefix for the new folder name. // * @param suffix The suffix for the new folder name. // * @throws IOException If folder creation fails. // */ // public TestFolder(String prefix, String suffix) throws IOException { // root = File.createTempFile(prefix, suffix); // if (!root.delete() || !root.mkdir()) { // throw new IOException("Failed to prepare test folder."); // } // } // // /** // * Returns a {@link File} object matching this folder location. // */ // public File getRoot() { // return root; // } // // /** // * Returns an {@link File} instance for the file with the given name in this test folder. // * // * @param filename The name of the faile. // */ // public File getFile(String filename) { // return new File(root, filename); // } // // /** // * Deletes this test folder and all its content. // * // * @throws IOException // */ // @Override // public void close() throws IOException { // // // A mapped byte buffer and the file mapping that it represents // // remain valid until the buffer itself is garbage-collected. // System.gc(); // // IOUtils.deleteTree(root); // } // } // Path: src/test/java/org/sharedmq/primitives/MemoryMappedFileTest.java import org.junit.Test; import org.junit.experimental.categories.Category; import org.sharedmq.test.CommonTests; import org.sharedmq.test.TestFolder; import java.io.IOException; import java.util.Arrays; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; package org.sharedmq.primitives; @Category(CommonTests.class) public class MemoryMappedFileTest { @Test public void testDataTypes() throws IOException { try (
TestFolder testFolder = new TestFolder("MemoryMappedFileTest", "testDataTypes");
yu-kopylov/shared-mq
src/test/java/org/sharedmq/util/IOUtilsTest.java
// Path: src/test/java/org/sharedmq/test/CommonTests.java // public interface CommonTests { // } // // Path: src/test/java/org/sharedmq/test/TestFolder.java // public class TestFolder implements Closeable { // // private final File root; // // /** // * Creates an new folder in the default temporary-file directory. // * // * @param prefix The prefix for the new folder name. // * @param suffix The suffix for the new folder name. // * @throws IOException If folder creation fails. // */ // public TestFolder(String prefix, String suffix) throws IOException { // root = File.createTempFile(prefix, suffix); // if (!root.delete() || !root.mkdir()) { // throw new IOException("Failed to prepare test folder."); // } // } // // /** // * Returns a {@link File} object matching this folder location. // */ // public File getRoot() { // return root; // } // // /** // * Returns an {@link File} instance for the file with the given name in this test folder. // * // * @param filename The name of the faile. // */ // public File getFile(String filename) { // return new File(root, filename); // } // // /** // * Deletes this test folder and all its content. // * // * @throws IOException // */ // @Override // public void close() throws IOException { // // // A mapped byte buffer and the file mapping that it represents // // remain valid until the buffer itself is garbage-collected. // System.gc(); // // IOUtils.deleteTree(root); // } // } // // Path: src/test/java/org/sharedmq/test/TestUtils.java // public static <T extends Exception> void assertThrows( // Class<T> errorClass, // String expectedMessagePart, // TestedAction action // ) { // try { // action.invoke(); // fail("an exception was expected"); // } catch (AssertionError e) { // throw e; // } catch (Throwable e) { // if (!errorClass.isInstance(e)) { // throw new AssertionError("Expected '" + errorClass.getName() + "'" + // ", but encountered '" + e.getClass().getName() + "'." // , e); // } // if (expectedMessagePart != null) { // String message = e.getMessage(); // if (message == null || !message.contains(expectedMessagePart)) { // throw new AssertionError("Expected an exception" + // " with the message '..." + expectedMessagePart + "...'" + // ", but encountered '" + e.getMessage() + "'." // , e); // } // } // } // }
import org.sharedmq.test.CommonTests; import org.sharedmq.test.TestFolder; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.*; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import static org.sharedmq.test.TestUtils.assertThrows; import static org.junit.Assert.*;
package org.sharedmq.util; @Category(CommonTests.class) public class IOUtilsTest { @Test public void testDelete() throws IOException, InterruptedException {
// Path: src/test/java/org/sharedmq/test/CommonTests.java // public interface CommonTests { // } // // Path: src/test/java/org/sharedmq/test/TestFolder.java // public class TestFolder implements Closeable { // // private final File root; // // /** // * Creates an new folder in the default temporary-file directory. // * // * @param prefix The prefix for the new folder name. // * @param suffix The suffix for the new folder name. // * @throws IOException If folder creation fails. // */ // public TestFolder(String prefix, String suffix) throws IOException { // root = File.createTempFile(prefix, suffix); // if (!root.delete() || !root.mkdir()) { // throw new IOException("Failed to prepare test folder."); // } // } // // /** // * Returns a {@link File} object matching this folder location. // */ // public File getRoot() { // return root; // } // // /** // * Returns an {@link File} instance for the file with the given name in this test folder. // * // * @param filename The name of the faile. // */ // public File getFile(String filename) { // return new File(root, filename); // } // // /** // * Deletes this test folder and all its content. // * // * @throws IOException // */ // @Override // public void close() throws IOException { // // // A mapped byte buffer and the file mapping that it represents // // remain valid until the buffer itself is garbage-collected. // System.gc(); // // IOUtils.deleteTree(root); // } // } // // Path: src/test/java/org/sharedmq/test/TestUtils.java // public static <T extends Exception> void assertThrows( // Class<T> errorClass, // String expectedMessagePart, // TestedAction action // ) { // try { // action.invoke(); // fail("an exception was expected"); // } catch (AssertionError e) { // throw e; // } catch (Throwable e) { // if (!errorClass.isInstance(e)) { // throw new AssertionError("Expected '" + errorClass.getName() + "'" + // ", but encountered '" + e.getClass().getName() + "'." // , e); // } // if (expectedMessagePart != null) { // String message = e.getMessage(); // if (message == null || !message.contains(expectedMessagePart)) { // throw new AssertionError("Expected an exception" + // " with the message '..." + expectedMessagePart + "...'" + // ", but encountered '" + e.getMessage() + "'." // , e); // } // } // } // } // Path: src/test/java/org/sharedmq/util/IOUtilsTest.java import org.sharedmq.test.CommonTests; import org.sharedmq.test.TestFolder; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.*; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import static org.sharedmq.test.TestUtils.assertThrows; import static org.junit.Assert.*; package org.sharedmq.util; @Category(CommonTests.class) public class IOUtilsTest { @Test public void testDelete() throws IOException, InterruptedException {
try (TestFolder testFolder = new TestFolder("IOUtilsTest", "testDelete")) {
yu-kopylov/shared-mq
src/test/java/org/sharedmq/util/IOUtilsTest.java
// Path: src/test/java/org/sharedmq/test/CommonTests.java // public interface CommonTests { // } // // Path: src/test/java/org/sharedmq/test/TestFolder.java // public class TestFolder implements Closeable { // // private final File root; // // /** // * Creates an new folder in the default temporary-file directory. // * // * @param prefix The prefix for the new folder name. // * @param suffix The suffix for the new folder name. // * @throws IOException If folder creation fails. // */ // public TestFolder(String prefix, String suffix) throws IOException { // root = File.createTempFile(prefix, suffix); // if (!root.delete() || !root.mkdir()) { // throw new IOException("Failed to prepare test folder."); // } // } // // /** // * Returns a {@link File} object matching this folder location. // */ // public File getRoot() { // return root; // } // // /** // * Returns an {@link File} instance for the file with the given name in this test folder. // * // * @param filename The name of the faile. // */ // public File getFile(String filename) { // return new File(root, filename); // } // // /** // * Deletes this test folder and all its content. // * // * @throws IOException // */ // @Override // public void close() throws IOException { // // // A mapped byte buffer and the file mapping that it represents // // remain valid until the buffer itself is garbage-collected. // System.gc(); // // IOUtils.deleteTree(root); // } // } // // Path: src/test/java/org/sharedmq/test/TestUtils.java // public static <T extends Exception> void assertThrows( // Class<T> errorClass, // String expectedMessagePart, // TestedAction action // ) { // try { // action.invoke(); // fail("an exception was expected"); // } catch (AssertionError e) { // throw e; // } catch (Throwable e) { // if (!errorClass.isInstance(e)) { // throw new AssertionError("Expected '" + errorClass.getName() + "'" + // ", but encountered '" + e.getClass().getName() + "'." // , e); // } // if (expectedMessagePart != null) { // String message = e.getMessage(); // if (message == null || !message.contains(expectedMessagePart)) { // throw new AssertionError("Expected an exception" + // " with the message '..." + expectedMessagePart + "...'" + // ", but encountered '" + e.getMessage() + "'." // , e); // } // } // } // }
import org.sharedmq.test.CommonTests; import org.sharedmq.test.TestFolder; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.*; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import static org.sharedmq.test.TestUtils.assertThrows; import static org.junit.Assert.*;
fileLocked.await(); long deleteStarted = System.currentTimeMillis(); IOUtils.delete(file); long deleteTime = System.currentTimeMillis() - deleteStarted; assertFalse(file.exists()); System.out.println("Locked file was deleted within " + deleteTime + "ms."); } } @Test public void testCreateFolder() throws IOException, InterruptedException { try (TestFolder testFolder = new TestFolder("IOUtilsTest", "testCreateFolder")) { File folder = testFolder.getFile("folder"); IOUtils.createFolder(folder); assertTrue(folder.exists()); assertTrue(folder.isDirectory()); File fileInFolder = new File(folder, "test.dat"); assertTrue(fileInFolder.createNewFile()); IOUtils.createFolder(folder); assertTrue(folder.exists()); assertTrue(folder.isDirectory()); assertTrue(fileInFolder.exists());
// Path: src/test/java/org/sharedmq/test/CommonTests.java // public interface CommonTests { // } // // Path: src/test/java/org/sharedmq/test/TestFolder.java // public class TestFolder implements Closeable { // // private final File root; // // /** // * Creates an new folder in the default temporary-file directory. // * // * @param prefix The prefix for the new folder name. // * @param suffix The suffix for the new folder name. // * @throws IOException If folder creation fails. // */ // public TestFolder(String prefix, String suffix) throws IOException { // root = File.createTempFile(prefix, suffix); // if (!root.delete() || !root.mkdir()) { // throw new IOException("Failed to prepare test folder."); // } // } // // /** // * Returns a {@link File} object matching this folder location. // */ // public File getRoot() { // return root; // } // // /** // * Returns an {@link File} instance for the file with the given name in this test folder. // * // * @param filename The name of the faile. // */ // public File getFile(String filename) { // return new File(root, filename); // } // // /** // * Deletes this test folder and all its content. // * // * @throws IOException // */ // @Override // public void close() throws IOException { // // // A mapped byte buffer and the file mapping that it represents // // remain valid until the buffer itself is garbage-collected. // System.gc(); // // IOUtils.deleteTree(root); // } // } // // Path: src/test/java/org/sharedmq/test/TestUtils.java // public static <T extends Exception> void assertThrows( // Class<T> errorClass, // String expectedMessagePart, // TestedAction action // ) { // try { // action.invoke(); // fail("an exception was expected"); // } catch (AssertionError e) { // throw e; // } catch (Throwable e) { // if (!errorClass.isInstance(e)) { // throw new AssertionError("Expected '" + errorClass.getName() + "'" + // ", but encountered '" + e.getClass().getName() + "'." // , e); // } // if (expectedMessagePart != null) { // String message = e.getMessage(); // if (message == null || !message.contains(expectedMessagePart)) { // throw new AssertionError("Expected an exception" + // " with the message '..." + expectedMessagePart + "...'" + // ", but encountered '" + e.getMessage() + "'." // , e); // } // } // } // } // Path: src/test/java/org/sharedmq/util/IOUtilsTest.java import org.sharedmq.test.CommonTests; import org.sharedmq.test.TestFolder; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.*; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import static org.sharedmq.test.TestUtils.assertThrows; import static org.junit.Assert.*; fileLocked.await(); long deleteStarted = System.currentTimeMillis(); IOUtils.delete(file); long deleteTime = System.currentTimeMillis() - deleteStarted; assertFalse(file.exists()); System.out.println("Locked file was deleted within " + deleteTime + "ms."); } } @Test public void testCreateFolder() throws IOException, InterruptedException { try (TestFolder testFolder = new TestFolder("IOUtilsTest", "testCreateFolder")) { File folder = testFolder.getFile("folder"); IOUtils.createFolder(folder); assertTrue(folder.exists()); assertTrue(folder.isDirectory()); File fileInFolder = new File(folder, "test.dat"); assertTrue(fileInFolder.createNewFile()); IOUtils.createFolder(folder); assertTrue(folder.exists()); assertTrue(folder.isDirectory()); assertTrue(fileInFolder.exists());
assertThrows(