answer
stringlengths
17
10.2M
package org.wisdom.engine.server; import akka.dispatch.OnComplete; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.multipart.*; import io.netty.handler.codec.http.websocketx.*; import io.netty.handler.stream.ChunkedStream; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.wisdom.api.bodies.NoHttpBody; import org.wisdom.api.content.ContentCodec; import org.wisdom.api.content.ContentSerializer; import org.wisdom.api.http.*; import org.wisdom.api.router.Route; import org.wisdom.engine.wrapper.ContextFromNetty; import org.wisdom.engine.wrapper.cookies.CookieHelper; import scala.concurrent.Future; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Map; import java.util.concurrent.Callable; import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive; /** * The Wisdom Channel Handler. * Every connection has it's own handler. */ public class WisdomHandler extends SimpleChannelInboundHandler<Object> { // Disk if size exceed. private static final HttpDataFactory DATA_FACTORY = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); private static final Logger LOGGER = LoggerFactory.getLogger("wisdom-engine"); private final ServiceAccessor accessor; private WebSocketServerHandshaker handshaker; static { DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) DiskFileUpload.baseDirectory = null; // system temp directory DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) DiskAttribute.baseDirectory = null; // system temp directory } private ContextFromNetty context; private HttpRequest request; private HttpPostRequestDecoder decoder; public WisdomHandler(ServiceAccessor accessor) { this.accessor = accessor; } private static String getWebSocketLocation(HttpRequest req) { //TODO Support wss return "ws://" + req.headers().get(HOST) + req.getUri(); } @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpObject) { handleHttpRequest(ctx, (HttpObject) msg); } else if (msg instanceof WebSocketFrame) { handleWebSocketFrame(ctx, (WebSocketFrame) msg); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { accessor.getDispatcher().removeWebSocket(strip(handshaker.uri()), ctx); handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Make a copy of the result to avoid to be cleaned on cleanup. // The getBytes method return a new byte array. final byte[] content = ((TextWebSocketFrame) frame).text().getBytes(); accessor.getSystem().dispatch(new Callable<Void>() { @Override public Void call() throws Exception { accessor.getDispatcher().received(strip(handshaker.uri()), content, ctx); return null; } }, accessor.getSystem().system().dispatcher()); } else if (frame instanceof BinaryWebSocketFrame) { final byte[] content = Arrays.copyOf(frame.content().array(), frame.content().array().length); accessor.getSystem().dispatch(new Callable<Void>() { @Override public Void call() throws Exception { accessor.getDispatcher().received(strip(handshaker.uri()), content, ctx); return null; } }, accessor.getSystem().system().dispatcher()); } } private static String strip(String uri) { try { return new URI(uri).getRawPath(); } catch (URISyntaxException e) { //NOSONAR return null; } } private void handleHttpRequest(ChannelHandlerContext ctx, HttpObject req) { if (req instanceof HttpRequest) { request = (HttpRequest) req; context = new ContextFromNetty(accessor, ctx, request); switch (handshake(ctx)) { case HANDSHAKE_UNSUPPORTED: CommonResponses.sendUnsupportedWebSocketVersionResponse(ctx.channel()); return; case HANDSHAKE_ERROR : CommonResponses.sendWebSocketHandshakeErrorResponse(ctx.channel()); return; case HANDSHAKE_OK : // Handshake ok, just return return; case NO_HANDSHAKE : default: // No handshake attempted, continue. break; } } if (req instanceof HttpContent) { // Only valid for put and post. if (request.getMethod().equals(HttpMethod.POST) || request.getMethod().equals(HttpMethod.PUT)) { if (decoder == null) { decoder = new HttpPostRequestDecoder(DATA_FACTORY, request); } context.decodeContent(request, (HttpContent) req, decoder); } } if (req instanceof LastHttpContent) { // End of transmission. boolean isAsync = dispatch(ctx); if (!isAsync) { cleanup(); } } } /** * Constant telling that the websocket handshake has not be attempted as the request did not include the headers. */ private final static int NO_HANDSHAKE = 0; /** Constant telling that the websocket handshake has been made successfully. */ private final static int HANDSHAKE_OK = 1; /** Constant telling that the websocket handshake has been attempted but failed. */ private final static int HANDSHAKE_ERROR = 2; /** * Constant telling that the websocket handshake has failed because the version specified in the request is not * supported. In this case the error method is already written in the channel. */ private final static int HANDSHAKE_UNSUPPORTED = 3; /** * Manages the websocket handshake. * * @param ctx the current context * @return an integer representing the handshake state. */ private int handshake(ChannelHandlerContext ctx) { if (HttpHeaders.Values.UPGRADE.equalsIgnoreCase(request.headers().get(CONNECTION)) || HttpHeaders.Values.WEBSOCKET.equalsIgnoreCase(request.headers().get(HttpHeaders.Names.UPGRADE))) { WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(request), accessor.getConfiguration().getWithDefault("wisdom.websocket.subprotocols", null), true); handshaker = wsFactory.newHandshaker(request); if (handshaker == null) { return HANDSHAKE_UNSUPPORTED; } else { try { handshaker.handshake(ctx.channel(), new FakeFullHttpRequest(request)); accessor.getDispatcher().addWebSocket(strip(handshaker.uri()), ctx); LOGGER.debug("Handshake completed on {}", strip(handshaker.uri())); return HANDSHAKE_OK; } catch (Exception e) { LOGGER.error("The websocket handshake failed for {}", getWebSocketLocation(request), e); return HANDSHAKE_ERROR; } } } return NO_HANDSHAKE; } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { // Do we have a web socket opened ? if (handshaker != null) { accessor.getDispatcher().removeWebSocket(strip(handshaker.uri()), ctx); handshaker = null; } if (decoder != null) { try { decoder.cleanFiles(); decoder.destroy(); } catch (IllegalStateException e) { //NOSONAR // Decoder already destroyed. } finally { decoder = null; } } if (context != null) { context.cleanup(); } Context.CONTEXT.remove(); context = null; ctx.close(); } private void cleanup() { // Release all resources, especially uploaded file. request = null; context.cleanup(); if (decoder != null) { try { decoder.cleanFiles(); decoder.destroy(); } catch (IllegalStateException e) { //NOSONAR // Decoder already destroyed. } finally { decoder = null; } } Context.CONTEXT.remove(); context = null; } private boolean dispatch(ChannelHandlerContext ctx) { LOGGER.debug("Dispatching {} {}", context.request().method(), context.path()); // 2 Register context Context.CONTEXT.set(context); // 3 Get route for context Route route = accessor.getRouter().getRouteFor(context.request().method(), context.path()); Result result; if (route == null) { // 3.1 : no route to destination // Should never return null, but an unbound route instead. LOGGER.error("The router has returned 'null' instead of an unbound route for " + context.path()); // If we open a websocket in the same request, just ignore it. if (handshaker != null) { return false; } result = Results.notFound(); } else { // 3.2 : route found context.setRoute(route); result = invoke(route); // We have this weird case where we don't have controller (unbound), but are just there to complete the // websocket handshake. if (route.isUnbound() && handshaker != null) { return false; } if (result instanceof AsyncResult) { // Asynchronous operation in progress. handleAsyncResult(ctx, request, context, (AsyncResult) result); return true; } } // Synchronous processing. try { return writeResponse(ctx, request, context, result, true, false); } catch (Exception e) { LOGGER.error("Cannot write response", e); result = Results.internalServerError(e); try { return writeResponse(ctx, request, context, result, false, false); } catch (Exception e1) { LOGGER.error("Cannot even write the error response...", e1); // Ignore. } } // If we reach this point, it means we did not write anything... Annoying. return false; } /** * Handling an async result. * The controller has returned an async task ( {@link java.util.concurrent.Callable} ) that will be computed * asynchronously using the Akka system dispatcher. * The callable is not called using the Netty worker thread. * * @param ctx the channel context * @param request the request * @param context the context * @param result the async result */ private void handleAsyncResult( final ChannelHandlerContext ctx, final HttpRequest request, final Context context, AsyncResult result) { Future<Result> future = accessor.getSystem().dispatchResultWithContext(result.callable(), context); future.onComplete(new OnComplete<Result>() { public void onComplete(Throwable failure, Result result) { if (failure != null) { //We got a failure, handle it here writeResponse(ctx, request, context, Results.internalServerError(failure), false, true); } else { // We got a result, write it here. writeResponse(ctx, request, context, result, true, true); } } }, accessor.getSystem().fromThread()); } private InputStream processResult(Result result) throws Exception { Renderable<?> renderable = result.getRenderable(); if (renderable == null) { renderable = new NoHttpBody(); } if (renderable.requireSerializer()) { ContentSerializer serializer = null; if (result.getContentType() != null) { serializer = accessor.getContentEngines().getContentSerializerForContentType(result .getContentType()); } if (serializer == null) { // Try with the Accept type String fromRequest = context.request().contentType(); serializer = accessor.getContentEngines().getContentSerializerForContentType(fromRequest); } if (serializer != null) { serializer.serialize(renderable); } } return renderable.render(context, result); } private boolean writeResponse( final ChannelHandlerContext ctx, final HttpRequest request, Context context, Result result, boolean handleFlashAndSessionCookie, boolean fromAsync) { //TODO Refactor this method. // Render the result. InputStream stream; boolean success = true; Renderable<?> renderable = result.getRenderable(); if (renderable == null) { renderable = new NoHttpBody(); } try { stream = processResult(result); } catch (Exception e) { LOGGER.error("Cannot render the response to " + request.getUri(), e); stream = new ByteArrayInputStream(NoHttpBody.EMPTY); success = false; } if(accessor.getContentEngines().getContentEncodingHelper().shouldEncode(context, result, renderable)){ ContentCodec codec = null; for(String encoding : accessor.getContentEngines().getContentEncodingHelper().parseAcceptEncodingHeader(context.request().getHeader(HeaderNames.ACCEPT_ENCODING))){ codec = accessor.getContentEngines().getContentCodecForEncodingType(encoding); if(codec != null) break; } if(codec != null){ // Encode Async result.with(CONTENT_ENCODING, codec.getEncodingType()); proceedAsyncEncoding(codec, stream, ctx, result, success, handleFlashAndSessionCookie, fromAsync); return true; } //No encoding possible, do the finalize } return finalizeWriteReponse(ctx, result, stream, success, handleFlashAndSessionCookie, fromAsync); } private void proceedAsyncEncoding( final ContentCodec codec, final InputStream stream, final ChannelHandlerContext ctx, final Result result, final boolean success, final boolean handleFlashAndSessionCookie, final boolean fromAsync){ Future<InputStream> future = accessor.getSystem().dispatchInputStream(new Callable<InputStream>() { @Override public InputStream call() throws Exception { return codec.encode(stream); } }); future.onComplete(new OnComplete<InputStream>(){ @Override public void onComplete(Throwable arg0, InputStream encodedStream) throws Throwable { finalizeWriteReponse(ctx, result, encodedStream, success, handleFlashAndSessionCookie, true); } }, accessor.getSystem().fromThread()); } private boolean finalizeWriteReponse( final ChannelHandlerContext ctx, Result result, InputStream stream, boolean success, boolean handleFlashAndSessionCookie, boolean fromAsync){ Renderable<?> renderable = result.getRenderable(); if (renderable == null) { renderable = new NoHttpBody(); } final InputStream content = stream; // Decide whether to close the connection or not. boolean keepAlive = isKeepAlive(request); // Build the response object. HttpResponse response; Object res; boolean isChunked = renderable.mustBeChunked(); if (isChunked) { response = new DefaultHttpResponse(request.getProtocolVersion(), getStatusFromResult(result, success)); if (renderable.length() > 0) { response.headers().set(CONTENT_LENGTH, renderable.length()); } // Can't determine the size, so switch to chunked. response.headers().set(TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); // In addition, we can't keep the connection open. response.headers().set(CONNECTION, HttpHeaders.Values.CLOSE); //keepAlive = false; res = new ChunkedStream(content); } else { DefaultFullHttpResponse resp = new DefaultFullHttpResponse(request.getProtocolVersion(), getStatusFromResult(result, success)); byte[] cont = new byte[0]; try { cont = IOUtils.toByteArray(content); } catch (IOException e) { LOGGER.error("Cannot copy the response to " + request.getUri(), e); } resp.headers().set(CONTENT_LENGTH, cont.length); res = Unpooled.copiedBuffer(cont); if (keepAlive) { // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection resp.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } resp.content().writeBytes(cont); response = resp; } for (Map.Entry<String, String> header : result.getHeaders().entrySet()) { response.headers().set(header.getKey(), header.getValue()); } String fullContentType = result.getFullContentType(); if (fullContentType == null) { response.headers().set(CONTENT_TYPE, renderable.mimetype()); } else { response.headers().set(CONTENT_TYPE, fullContentType); } // copy cookies / flash and session if (handleFlashAndSessionCookie) { context.flash().save(context, result); context.session().save(context, result); } // copy cookies for (org.wisdom.api.cookies.Cookie cookie : result.getCookies()) { response.headers().add(SET_COOKIE, CookieHelper .convertWisdomCookieToNettyCookie(cookie)); } // Send the response and close the connection if necessary. ctx.write(response); final ChannelFuture writeFuture; if (isChunked) { writeFuture = ctx.write(res); } else { writeFuture = ctx.writeAndFlush(res); } writeFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { IOUtils.closeQuietly(content); } }); if (isChunked) { // Write the end marker ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (! keepAlive) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } } else { if (! keepAlive) { // Close the connection when the whole content is written out. writeFuture.addListener(ChannelFutureListener.CLOSE); } } if(fromAsync){ cleanup(); } return false; } private HttpResponseStatus getStatusFromResult(Result result, boolean success) { if (!success) { return HttpResponseStatus.BAD_REQUEST; } else { return HttpResponseStatus.valueOf(result.getStatusCode()); } } private Result invoke(Route route) { try { return route.invoke(); } catch (Throwable e) { //NOSONAR if (e.getCause() != null) { // We don't really care about the parent exception, dump the cause only. LOGGER.error("An error occurred during route invocation", e.getCause()); return Results.internalServerError(e.getCause()); } else { LOGGER.error("An error occurred during route invocation", e); return Results.internalServerError(e); } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOGGER.error("Exception caught in channel", cause); ctx.close(); } }
package org.knowm.xchange; import java.util.HashMap; import java.util.Map; /** * <p> * Specification to provide the following to {@link ExchangeFactory}: * </p> * <ul> * <li>Provision of required exchangeSpecificParameters for creating an {@link Exchange}</li> * <li>Provision of optional exchangeSpecificParameters for additional configuration</li> * </ul> */ public class ExchangeSpecification { private String exchangeName; private String exchangeDescription; private String userName; private String password; private String secretKey; private String apiKey; private String sslUri; private String plainTextUri; private String host; private int port = 80; private int httpConnTimeout = 0; // default rescu configuration will be used if value not changed private int httpReadTimeout = 0; // default rescu configuration will be used if value not changed private String metaDataJsonFileOverride = null; private boolean shouldLoadRemoteMetaData = true; // default value private final String exchangeClassName; /** * arbitrary exchange params that can be set for unique cases */ private Map<String, Object> exchangeSpecificParameters = new HashMap<>(); /** * Dynamic binding * * @param exchangeClassName The exchange class name (e.g. "org.knowm.xchange.mtgox.v1.MtGoxExchange") */ public ExchangeSpecification(String exchangeClassName) { this.exchangeClassName = exchangeClassName; } /** * Static binding * * @param exchangeClass The exchange class */ public ExchangeSpecification(Class<? extends Exchange> exchangeClass) { this.exchangeClassName = exchangeClass.getCanonicalName(); } /** * @return The exchange class name for loading at runtime */ public String getExchangeClassName() { return exchangeClassName; } /** * @param key The key into the parameter map (recommend using the provided standard static entries) * @return Any additional exchangeSpecificParameters that the {@link Exchange} may consume to configure services */ public Object getParameter(String key) { return exchangeSpecificParameters.get(key); } /** * Get the host name of the server providing data (e.g. "mtgox.com"). * * @return the host name */ public String getHost() { return host; } /** * Set the host name of the server providing data. * * @param host the host name */ public void setHost(String host) { this.host = host; } /** * Get the API key. For MtGox this would be the "Rest-Key" field. * * @return the API key */ public String getApiKey() { return apiKey; } /** * Set the API key. For MtGox this would be the "Rest-Key" field. * * @param apiKey the API key */ public void setApiKey(String apiKey) { this.apiKey = apiKey; } /** * Get the port number of the server providing direct socket data (e.g. "1337"). * * @return the port number */ public int getPort() { return port; } /** * Set the http connection timeout for the connection. If not supplied the default rescu timeout will be used. Check the exchange code to see if * this option has been implemented. (This value can also be set globally in "rescu.properties" by setting the property * "rescu.http.connTimeoutMillis".) * * @param milliseconds the http read timeout in milliseconds */ public void setHttpConnTimeout(int milliseconds) { this.httpConnTimeout = milliseconds; } /** * Get the http connection timeout for the connection. If the default value of zero is returned then the default rescu timeout will be applied. * Check the exchange code to see if this option has been implemented. * * @return the http read timeout in milliseconds */ public int getHttpConnTimeout() { return httpConnTimeout; } /** * Set the http read timeout for the connection. If not supplied the default rescu timeout will be used. Check the exchange code to see if this * option has been implemented. (This value can also be set globally in "rescu.properties" by setting the property "rescu.http.readTimeoutMillis".) * * @param milliseconds the http read timeout in milliseconds */ public void setHttpReadTimeout(int milliseconds) { this.httpReadTimeout = milliseconds; } /** * Get the http read timeout for the connection. If the default value of zero is returned then the default rescu timeout will be applied. Check the * exchange code to see if this option has been implemented. * * @return the http read timeout in milliseconds */ public int getHttpReadTimeout() { return httpReadTimeout; } /** * Set the port number of the server providing direct socket data (e.g. "1337"). * * @param port the port number */ public void setPort(int port) { this.port = port; } /** * Get the API secret key typically used in HMAC signing of requests. For MtGox this would be the "Rest-Sign" field. * * @return the secret key */ public String getSecretKey() { return secretKey; } /** * Set the API secret key typically used in HMAC signing of requests. For MtGox this would be the "Rest-Sign" field. * * @param secretKey the secret key */ public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getSslUri() { return sslUri; } public void setSslUri(String uri) { this.sslUri = uri; } public String getPlainTextUri() { return plainTextUri; } public void setPlainTextUri(String plainTextUri) { this.plainTextUri = plainTextUri; } /** * Get the arbitrary exchange-specific parameters to be passed to the exchange implementation. * * @return a Map of named exchange-specific parameter values */ public Map<String, Object> getExchangeSpecificParameters() { return exchangeSpecificParameters; } /** * Set the arbitrary exchange-specific parameters to be passed to the exchange implementation. * * @param exchangeSpecificParameters a Map of named exchange-specific parameter values */ public void setExchangeSpecificParameters(Map<String, Object> exchangeSpecificParameters) { this.exchangeSpecificParameters = exchangeSpecificParameters; } /** * Get an item from the arbitrary exchange-specific parameters to be passed to the exchange implementation. * * @return a Map of named exchange-specific parameter values */ public Object getExchangeSpecificParametersItem(String key) { return exchangeSpecificParameters.get(key); } /** * Set an item in the arbitrary exchange-specific parameters to be passed to the exchange implementation. */ public void setExchangeSpecificParametersItem(String key, Object value) { this.exchangeSpecificParameters.put(key, value); } /** * Get the password for authentication. * * @return the password */ public String getPassword() { return password; } /** * Set the password for authentication. * * @param password the password */ public void setPassword(String password) { this.password = password; } /** * Get the username for authentication. * * @return the username */ public String getUserName() { return userName; } /** * Set the username for authentication. * * @param userName the username */ public void setUserName(String userName) { this.userName = userName; } /** * Get the exchange name. * * @return the exchange name (e.g. "Mt Gox") */ public String getExchangeName() { return exchangeName; } /** * Set the exchange name (e.g. "Mt Gox"). * * @param exchangeName the exchange name */ public void setExchangeName(String exchangeName) { this.exchangeName = exchangeName; } /** * Get the exchange description (e.g. "Major exchange specialising in USD, EUR, GBP"). * * @return the exchange description */ public String getExchangeDescription() { return exchangeDescription; } /** * Set the exchange description (e.g. "Major exchange specialising in USD, EUR, GBP"). * * @param exchangeDescription the exchange description */ public void setExchangeDescription(String exchangeDescription) { this.exchangeDescription = exchangeDescription; } /** * Get the override file for generating the {@link org.knowm.xchange.dto.meta.ExchangeMetaData} object. By default, the * {@link org.knowm.xchange.dto.meta.ExchangeMetaData} object is loaded at startup from a json file on the classpath with the same name as the name * of the exchange as defined in {@link ExchangeSpecification}. With this parameter, you can override that file with a file of your choice located * outside of the classpath. * * @return */ public String getMetaDataJsonFileOverride() { return metaDataJsonFileOverride; } /** * Set the override file for generating the {@link org.knowm.xchange.dto.meta.ExchangeMetaData} object. By default, the * {@link org.knowm.xchange.dto.meta.ExchangeMetaData} object is loaded at startup from a json file on the classpath with the same name as the name * of the exchange as defined in {@link ExchangeSpecification}. With this parameter, you can override that file with a file of your choice located * outside of the classpath. * * @return */ public void setMetaDataJsonFileOverride(String metaDataJsonFileOverride) { this.metaDataJsonFileOverride = metaDataJsonFileOverride; } /** * By default, some meta data from the exchange is remotely loaded (if implemented). * * @return */ public boolean isShouldLoadRemoteMetaData() { return shouldLoadRemoteMetaData; } /** * By default, some meta data from the exchange is remotely loaded (if implemented). Here you can set this default behavior. * * @param shouldLoadRemoteMetaData */ public void setShouldLoadRemoteMetaData(boolean shouldLoadRemoteMetaData) { this.shouldLoadRemoteMetaData = shouldLoadRemoteMetaData; } }
package org.knowm.xchange.dto.marketdata; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import static org.knowm.xchange.dto.marketdata.Trades.TradeSortType.SortByID; import java.io.Serializable; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** DTO representing a collection of trades */ public class Trades implements Serializable { private static final long serialVersionUID = 5790082783307641329L; private static final TradeIDComparator TRADE_ID_COMPARATOR = new TradeIDComparator(); private static final TradeTimestampComparator TRADE_TIMESTAMP_COMPARATOR = new TradeTimestampComparator(); private final List<Trade> trades; private final long lastID; private final String nextPageCursor; private final TradeSortType tradeSortType; /** * Constructor Default sort is SortByID * * @param trades List of trades */ public Trades(List<Trade> trades) { this(trades, 0L, SortByID); } /** * Constructor * * @param trades List of trades * @param tradeSortType Trade sort type */ @JsonCreator public Trades(@JsonProperty("trades") List<Trade> trades, @JsonProperty("tradeSortType") TradeSortType tradeSortType) { this(trades, 0L, tradeSortType); } /** * Constructor * * @param trades A list of trades * @param lastID Last Unique ID * @param tradeSortType Trade sort type */ public Trades(List<Trade> trades, long lastID, TradeSortType tradeSortType) { this(trades, lastID, tradeSortType, null); } /** * Constructor * * @param trades A list of trades * @param lastID Last Unique ID * @param tradeSortType Trade sort type * @param nextPageCursor a marker that lets you receive the next page of trades using * TradeHistoryParamNextPageCursor */ public Trades( List<Trade> trades, long lastID, TradeSortType tradeSortType, String nextPageCursor) { this.trades = new ArrayList<>(trades); this.lastID = lastID; this.tradeSortType = tradeSortType; this.nextPageCursor = nextPageCursor; switch (tradeSortType) { case SortByTimestamp: Collections.sort(this.trades, TRADE_TIMESTAMP_COMPARATOR); break; case SortByID: Collections.sort(this.trades, TRADE_ID_COMPARATOR); break; default: break; } } /** @return A list of trades ordered by id */ public List<Trade> getTrades() { return trades; } /** @return a Unique ID for the fetched trades */ public long getlastID() { return lastID; } public TradeSortType getTradeSortType() { return tradeSortType; } public String getNextPageCursor() { return nextPageCursor; } @Override public String toString() { StringBuilder sb = new StringBuilder("Trades\n"); sb.append("lastID= ").append(lastID).append("\n"); for (Trade trade : getTrades()) { sb.append("[trade=").append(trade.toString()).append("]\n"); } sb.append("nextPageCursor= ").append(nextPageCursor).append("\n"); return sb.toString(); } public enum TradeSortType { SortByTimestamp, SortByID } public static class TradeTimestampComparator implements Comparator<Trade> { @Override public int compare(Trade trade1, Trade trade2) { return trade1.getTimestamp().compareTo(trade2.getTimestamp()); } } public static class TradeIDComparator implements Comparator<Trade> { private static final int[] ALLOWED_RADIXES = {10, 16}; @Override public int compare(Trade trade1, Trade trade2) { for (int radix : ALLOWED_RADIXES) { try { BigInteger id1 = new BigInteger(trade1.getId(), radix); BigInteger id2 = new BigInteger(trade2.getId(), radix); return id1.compareTo(id2); } catch (NumberFormatException ignored) { } } return trade1.getId().compareTo(trade2.getId()); } } }
package x2x.translator.xcodeml.xelement; public class XelementName { // helpers public static final String TRUE = "true"; public static final String FALSE = "false"; public static final String SUPPORTED_VERSION = "1.0"; public static final String SUPPORTED_LANGUAGE = "Fortran"; // Element attributes public static final String ATTR_COMPILER_INFO = "compiler-info"; public static final String ATTR_FILE = "file"; public static final String ATTR_IS_PROGRAM = "is_program"; public static final String ATTR_INTENT = "intent"; public static final String ATTR_IS_ALLOCATABLE = "is_allocatable"; public static final String ATTR_IS_EXTERNAL = "is_external"; public static final String ATTR_IS_INTRINSIC = "is_intrinsic"; public static final String ATTR_IS_OPTIONAL = "is_optional"; public static final String ATTR_IS_PARAMETER = "is_parameter"; public static final String ATTR_IS_POINTER = "is_pointer"; public static final String ATTR_IS_PRIVATE = "is_private"; public static final String ATTR_IS_PUBLIC = "is_public"; public static final String ATTR_IS_SAVE = "is_save"; public static final String ATTR_IS_TARGET = "is_target"; public static final String ATTR_LANGUAGE = "language"; public static final String ATTR_LINENO = "lineno"; public static final String ATTR_REF = "ref"; public static final String ATTR_RETURN_TYPE = "return_type"; public static final String ATTR_SCLASS = "sclass"; public static final String ATTR_SCOPE = "scope"; public static final String ATTR_SOURCE = "source"; public static final String ATTR_TIME = "time"; public static final String ATTR_TYPE = "type"; public static final String ATTR_VERSION = "version"; // Element names public static final String BASIC_TYPE = "FbasicType"; public static final String BODY = "body"; public static final String DECLARATIONS = "declarations"; public static final String DO_STMT = "FdoStatement"; public static final String EXPR_STMT = "exprStatement"; public static final String FCT_DEFINITION = "FfunctionDefinition"; public static final String FCT_TYPE = "FfunctionType"; public static final String ID = "id"; public static final String INDEX_RANGE = "indexRange"; public static final String INT_CONST = "FintConstant"; public static final String LENGTH = "len"; public static final String LOWER_BOUND = "lowerBound"; public static final String NAME = "name"; public static final String PRAGMA_STMT = "FpragmaStatement"; public static final String STEP = "step"; public static final String SYMBOLS = "symbols"; public static final String TYPE_TABLE = "typeTable"; public static final String UPPER_BOUND = "upperBound"; public static final String VAR = "Var"; public static final String VAR_DECL = "varDecl"; public static final String VALUE = "value"; public static final String X_CODE_PROGRAM = "XcodeProgram"; }
package org.codehaus.xfire.plexus; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.Properties; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.embed.Embedder; import org.codehaus.xfire.XFire; import org.codehaus.xfire.XFireFactory; import org.codehaus.xfire.XFireRuntimeException; /** * <p> * The StandaloneXFire class allows you to embed a Plexus managed version * of XFire within your application. Use the XFireFactory to access it. * </p> * <p> * If you are not using the StandaloneXFireServlet or PlexusXFireServlet, * you must register this factory: * </p> * <pre> * XFireFactory.register(PlexusXFireFactory.class, true); * </pre> * @author <a href="mailto:[email protected]">Dan Diephouse</a> */ public class PlexusXFireFactory extends XFireFactory { private static PlexusXFireFactory standalone; protected Embedder embed; protected PlexusXFireFactory() { try { URL resource = getPlexusConfiguration(); embed = new Embedder(); embed.setConfiguration( resource ); Properties contextProperties = new Properties(); embed.setProperties(contextProperties); embed.start(); } catch (Exception e) { throw new XFireRuntimeException("Couldn't load plexus embedder.", e); } } public static XFireFactory createInstance() { if ( standalone == null ) { synchronized( PlexusXFireFactory.class ) { standalone = new PlexusXFireFactory(); } } return standalone; } /** * @return */ private URL getPlexusConfiguration() { URL resource = null; String configFileName = System.getProperty("xfire.plexusConfig"); if ( configFileName != null ) { File file = new File(configFileName); if ( file.exists() ) { try { resource = file.toURL(); } catch (MalformedURLException e) { throw new RuntimeException("Couldn't get plexus configuration.", e); } } else { resource = getClass().getResource(configFileName); } } if ( resource == null ) { resource = getClass().getResource("/org/codehaus/xfire/plexus/StandaloneXFire.xml"); } return resource; } public XFire getXFire() { try { return (XFire) embed.lookup( XFire.ROLE ); } catch (ComponentLookupException e) { throw new XFireRuntimeException("Couldn't lookup xfire component.", e); } } protected void finalize() throws Throwable { embed.stop(); super.finalize(); } }
package hm.binkley.annotation.processing; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.lang.model.element.Element; import javax.lang.model.element.Name; import java.util.AbstractMap; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.AbstractSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.regex.Pattern; import static hm.binkley.annotation.processing.Utils.typeFor; import static hm.binkley.annotation.processing.Utils.valueFor; import static java.util.Collections.emptyMap; import static java.util.Collections.unmodifiableList; import static java.util.regex.Pattern.compile; import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.StringEscapeUtils.escapeJava; /** * Represents YAML class/enum definitions immutably and accessible from * FreeMarker. Typical: <pre> * Foo: * .meta: * doc: I am the one and only Foo! * bar: * doc: I am bar * value: 0</pre> * * @author <a href="mailto:[email protected]">B. K. Oxley (binkley)</a> * @todo Enums */ public final class YModel { private static abstract class YDocumented { private static final Pattern DQUOTE = compile("\""); public final String name; public final String doc; public final String escapedDoc; protected YDocumented(final String name, final String doc) { this.name = name; this.doc = doc; escapedDoc = null == doc ? null : DQUOTE.matcher(escapeJava(doc)).replaceAll("\\\""); } } public static List<YType> classes(@Nonnull final Element root, @Nonnull final Name packaj, @Nonnull final Map<String, Map<String, Map<String, Object>>> raw, @Nonnull final Consumer<Function<YamlGenerateMesseger, YamlGenerateMesseger>> out) { return unmodifiableList(raw.entrySet().stream(). map(e -> { out.accept(o -> o.atYamlBlock(e)); final ZisZuper names = ZisZuper .from(packaj, e.getKey(), root); return YGenerate.ENUM == YGenerate.from(names) ? YEnum .of(names, e.getValue(), out) : YClass.of(names, e.getValue(), out); }). collect(toList())); } public static abstract class YType extends YDocumented { public final ZisZuper names; public final YGenerate type; protected YType(final ZisZuper names, final Map<String, Map<String, Object>> raw) { super(names.zis.fullName, (String) raw.get(".meta").get("doc")); this.names = names; type = YGenerate.from(names); } } public static final class YEnum extends YType implements Iterable<YValue> { private final List<YValue> values; public static YEnum of(final ZisZuper names, final Map<String, Map<String, Object>> raw, final Consumer<Function<YamlGenerateMesseger, YamlGenerateMesseger>> out) { return new YEnum(names, new WithMetaMap(null == raw ? emptyMap() : raw), out); } private YEnum(final ZisZuper names, final Map<String, Map<String, Object>> raw, final Consumer<Function<YamlGenerateMesseger, YamlGenerateMesseger>> out) { super(names, raw); values = YNode.asList(raw, YValue::new, out); } @Override public Iterator<YValue> iterator() { return values.iterator(); } } public static final class YClass extends YType implements Iterable<YMethod> { private final List<YMethod> methods; @Nonnull public static YClass of(@Nonnull final ZisZuper names, @Nullable final Map<String, Map<String, Object>> raw, final Consumer<Function<YamlGenerateMesseger, YamlGenerateMesseger>> out) { return new YClass(names, new WithMetaMap(null == raw ? emptyMap() : raw), out); } private YClass(final ZisZuper names, final Map<String, Map<String, Object>> raw, final Consumer<Function<YamlGenerateMesseger, YamlGenerateMesseger>> out) { super(names, raw); this.methods = YNode.asList(raw, YMethod::new, out); } @Nonnull @Override public Iterator<YMethod> iterator() { return methods.iterator(); } } public static final class YValue extends YNode { protected YValue(final Map.Entry<String, Map<String, Object>> raw) { super(raw); } } public static final class YMethod extends YNode implements Iterable<YProperty> { public final String rtype; public final Object value; private final List<YProperty> properties; private YMethod(final Map.Entry<String, Map<String, Object>> raw) { super(raw); final Map<String, Object> values = raw.getValue(); rtype = (String) values .getOrDefault("type", typeFor(values.get("value"))); value = values.getOrDefault("value", valueFor(rtype)); properties = unmodifiableList(values.entrySet().stream(). map(YProperty::new). collect(toList())); } @Nonnull @Override public Iterator<YProperty> iterator() { return properties.iterator(); } } private static abstract class YNode extends YDocumented { protected YNode(final Map.Entry<String, Map<String, Object>> raw) { super(raw.getKey(), doc(raw)); } private static String doc( final Map.Entry<String, Map<String, Object>> raw) { final Map<String, Object> properties = raw.getValue(); return null == properties ? null : (String) properties.get("doc"); } private static <T extends YNode> List<T> asList( final Map<String, Map<String, Object>> raw, final Function<Entry<String, Map<String, Object>>, T> ctor, final Consumer<Function<YamlGenerateMesseger, YamlGenerateMesseger>> out) { return unmodifiableList(raw.entrySet().stream(). filter(e -> !".meta".equals(e.getKey())). map(e -> { out.accept(o -> o.atYamlBlock(e)); return ctor.apply(e); }). collect(toList())); } } public static final class YProperty extends YDocumented { @Nullable public final Object value; private YProperty(final Map.Entry<String, Object> raw) { super(raw.getKey(), null); this.value = raw.getValue(); } } private static class WithMetaMap extends AbstractMap<String, Map<String, Object>> { private final Map<String, Map<String, Object>> raw; private WithMetaMap(final Map<String, Map<String, Object>> raw) { this.raw = raw; } @Nonnull @Override public Set<Entry<String, Map<String, Object>>> entrySet() { return new WithMetaSet(raw.entrySet(), raw.containsKey(".meta") ? raw.size() : raw.size() + 1); } } private static class WithMetaSet extends AbstractSet<Entry<String, Map<String, Object>>> { private final Set<Entry<String, Map<String, Object>>> raw; private final int size; private WithMetaSet(final Set<Entry<String, Map<String, Object>>> raw, final int size) { this.raw = raw; this.size = size; } @Nonnull @Override public Iterator<Entry<String, Map<String, Object>>> iterator() { return new WithMetaIterator(raw.iterator()); } @Override public int size() { return size; } } private static class WithMetaIterator implements Iterator<Entry<String, Map<String, Object>>> { private static final Entry<String, Map<String, Object>> meta = new SimpleImmutableEntry<>(".meta", emptyMap()); private final Iterator<Entry<String, Map<String, Object>>> it; private boolean sawMeta; private WithMetaIterator( final Iterator<Entry<String, Map<String, Object>>> it) { this.it = it; } @Override public boolean hasNext() { return it.hasNext() || !sawMeta; } @Nonnull @Override public Entry<String, Map<String, Object>> next() { try { final Entry<String, Map<String, Object>> next = it.next(); if (".meta".equals(next.getKey())) sawMeta = true; return next; } catch (final NoSuchElementException e) { sawMeta = true; return meta; } } } }
package foam.lib.parse; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; public class ErrorReportingPStream extends ProxyPStream { public static final List<Character> ASCII_CHARS = IntStream.rangeClosed(0, 255) .mapToObj(i -> (char) i) .collect(Collectors.toList()); protected Parser errParser = null; protected ParserContext errContext = null; protected ErrorReportingNodePStream errStream = null; protected ErrorReportingNodePStream tail_ = null; protected Set<Character> validCharacters = new HashSet<>(); public ErrorReportingPStream(PStream delegate) { setDelegate(delegate); } @Override public PStream tail() { // tail becomes new node with increased position if ( tail_ == null ) tail_ = new ErrorReportingNodePStream(this, super.tail(), 1); return tail_; } @Override public PStream setValue(Object value) { // create a new node return new ErrorReportingNodePStream(this, super.setValue(value), 0); } @Override public PStream apply(Parser parser, ParserContext x) { PStream result = parser.parse(this, x); if ( result == null ) { // if result is null then self report this.report(new ErrorReportingNodePStream(this, getDelegate(), 0), parser, x); } return result; } public void report(ErrorReportingNodePStream ernps, Parser parser, ParserContext x) { // get the report with the furthest position if ( errStream == null || errStream.pos <= ernps.pos ) { errStream = ernps; errParser = parser; errContext = x; } } public void reportValidCharacter(Character character) { validCharacters.add(character); } public String getMessage() { // check if err is valid and print the char, if not print EOF String invalid = ( errStream.valid() ) ? String.valueOf(errStream.head()) : "EOF"; // get a list of valid characters TrapPStream trap = new TrapPStream(this); Iterator i = ASCII_CHARS.iterator(); while ( i.hasNext() ) { Character character = (Character) i.next(); trap.setHead(character); trap.apply(errParser, errContext); } return "Invalid character '" + invalid + "' found at " + errStream.pos + "\n" + "Valid characters include: " + validCharacters.stream() .map(e -> "'" + e.toString() + "'") .collect(Collectors.joining(",")); } }
package org.voltdb.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import jline.ConsoleReader; import jline.SimpleCompletor; import org.voltdb.VoltTable; import org.voltdb.VoltType; import org.voltdb.client.Client; import org.voltdb.client.ClientConfig; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; import org.voltdb.client.NoConnectionsException; import org.voltdb.client.ProcCallException; import com.google.common.collect.ImmutableMap; public class SQLCommand { // SQL Parsing private static final Pattern EscapedSingleQuote = Pattern.compile("''", Pattern.MULTILINE); private static final Pattern SingleLineComments = Pattern.compile("^\\s*(\\/\\/|--).*$", Pattern.MULTILINE); private static final Pattern Extract = Pattern.compile("'[^']*'", Pattern.MULTILINE); private static final Pattern AutoSplit = Pattern.compile("\\s(select|insert|update|delete|exec|execute|explain|explainproc)\\s", Pattern.MULTILINE + Pattern.CASE_INSENSITIVE); private static final Pattern AutoSplitParameters = Pattern.compile("[\\s,]+", Pattern.MULTILINE); private static final String readme = "SQLCommandReadme.txt"; public static String getReadme() { return readme; } public static Pattern getExecuteCall() { return ExecuteCall; } public static List<String> parseQuery(String query) { if (query == null) return null; String[] command = new String[] {"exec", "execute", "explain", "explainproc"}; String[] keyword = new String[] {"select", "insert", "update", "delete"}; for(int i = 0;i<command.length;i++) { for(int j = 0;j<keyword.length;j++) { Pattern r = Pattern.compile("\\s*(" + command[i].replace(" ","\\s+") + ")\\s+(" + keyword[j] + ")\\s*", Pattern.MULTILINE + Pattern.CASE_INSENSITIVE); query = r.matcher(query).replaceAll(" $1 #SQL_PARSER_STRING_KEYWORD#$2 "); } } query = SingleLineComments.matcher(query).replaceAll(""); query = EscapedSingleQuote.matcher(query).replaceAll("#(SQL_PARSER_ESCAPE_SINGLE_QUOTE)"); Matcher stringFragmentMatcher = Extract.matcher(query); ArrayList<String> stringFragments = new ArrayList<String>(); int i = 0; while(stringFragmentMatcher.find()) { stringFragments.add(stringFragmentMatcher.group()); query = stringFragmentMatcher.replaceFirst("#(SQL_PARSER_STRING_FRAGMENT#" + i + ")"); stringFragmentMatcher = Extract.matcher(query); i++; } query = AutoSplit.matcher(query).replaceAll(";$1 "); String[] sqlFragments = query.split("\\s*;+\\s*"); ArrayList<String> queries = new ArrayList<String>(); for(int j = 0;j<sqlFragments.length;j++) { sqlFragments[j] = sqlFragments[j].trim(); if (sqlFragments[j].length() != 0) { if(sqlFragments[j].indexOf("#(SQL_PARSER_STRING_FRAGMENT#") > -1) for(int k = 0;k<stringFragments.size();k++) sqlFragments[j] = sqlFragments[j].replace("#(SQL_PARSER_STRING_FRAGMENT#" + k + ")", stringFragments.get(k)); sqlFragments[j] = sqlFragments[j].replace("#(SQL_PARSER_ESCAPE_SINGLE_QUOTE)", "''"); sqlFragments[j] = sqlFragments[j].replace("#SQL_PARSER_STRING_KEYWORD#",""); queries.add(sqlFragments[j]); } } return queries; } public static List<String> parseQueryProcedureCallParameters(String query) { if (query == null) return null; query = SingleLineComments.matcher(query).replaceAll(""); query = EscapedSingleQuote.matcher(query).replaceAll("#(SQL_PARSER_ESCAPE_SINGLE_QUOTE)"); Matcher stringFragmentMatcher = Extract.matcher(query); ArrayList<String> stringFragments = new ArrayList<String>(); int i = 0; while(stringFragmentMatcher.find()) { stringFragments.add(stringFragmentMatcher.group()); query = stringFragmentMatcher.replaceFirst("#(SQL_PARSER_STRING_FRAGMENT#" + i + ")"); stringFragmentMatcher = Extract.matcher(query); i++; } query = AutoSplitParameters.matcher(query).replaceAll(","); String[] sqlFragments = query.split("\\s*,+\\s*"); ArrayList<String> queries = new ArrayList<String>(); for(int j = 0;j<sqlFragments.length;j++) { sqlFragments[j] = sqlFragments[j].trim(); if (sqlFragments[j].length() != 0) { if(sqlFragments[j].indexOf("#(SQL_PARSER_STRING_FRAGMENT#") > -1) for(int k = 0;k<stringFragments.size();k++) sqlFragments[j] = sqlFragments[j].replace("#(SQL_PARSER_STRING_FRAGMENT#" + k + ")", stringFragments.get(k)); sqlFragments[j] = sqlFragments[j].replace("#(SQL_PARSER_ESCAPE_SINGLE_QUOTE)", "''"); sqlFragments[j] = sqlFragments[j].trim(); queries.add(sqlFragments[j]); } } return queries; } // Command line interaction private static ConsoleReader Input = null; private static final Pattern GoToken = Pattern.compile("^\\s*go;*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern ExitToken = Pattern.compile("^\\s*(exit|quit);*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern ListToken = Pattern.compile("^\\s*(list proc|list procedures);*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern ListTablesToken = Pattern.compile("^\\s*(list tables);*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern SemicolonToken = Pattern.compile("^.*\\s*;+\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern RecallToken = Pattern.compile("^\\s*recall\\s*([^;]+)\\s*;*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern FileToken = Pattern.compile("^\\s*file\\s*['\"]*([^;'\"]+)['\"]*\\s*;*\\s*", Pattern.CASE_INSENSITIVE); private static int LineIndex = 1; private static List<String> Lines = new ArrayList<String>(); private static List<String> getQuery(boolean interactive) throws Exception { StringBuilder query = new StringBuilder(); boolean isRecall = false; String line = null; do { if (interactive) { if (isRecall) { isRecall = false; line = Input.readLine(""); } else line = Input.readLine((LineIndex++) + "> "); } else line = Input.readLine(); if (line == null) { if (query == null) return null; else return parseQuery(query.toString()); } // Process recall commands - ONLY in interactive mode if (interactive && RecallToken.matcher(line).matches()) { Matcher m = RecallToken.matcher(line); if (m.find()) { int recall = -1; try { recall = Integer.parseInt(m.group(1))-1; } catch(Exception x){} if (recall > -1 && recall < Lines.size()) { line = Lines.get(recall); Input.putString(line); out.flush(); isRecall = true; continue; } else System.out.printf("%s> Invalid RECALL reference: '" + m.group(1) + "'.\n", LineIndex-1); } else System.out.printf("%s> Invalid RECALL command: '" + line + "'.\n", LineIndex-1); } // Strip out invalid recall commands if (RecallToken.matcher(line).matches()) line = ""; // Queue up the line to the recall stack - ONLY in interactive mode if (interactive) Lines.add(line); // EXIT command - ONLY in interactive mode, exit immediately (without running any queued statements) if (ExitToken.matcher(line).matches()) { if (interactive) return null; } // EXIT command - ONLY in interactive mode, exit immediately (without running any queued statements) else if (ListToken.matcher(line).matches()) { if (interactive) { List<String> list = new LinkedList<String>(Procedures.keySet()); Collections.sort(list); int padding = 0; for(String procedure : list) if (padding < procedure.length()) padding = procedure.length(); padding++; String format = "%1$-" + padding + "s"; for(int i = 0;i<2;i++) { int j = 0; for(String procedure : list) { if (i == 0 && procedure.startsWith("@")) continue; else if (i == 1 && !procedure.startsWith("@")) continue; if (j == 0) { if (i == 0) System.out.println("\n else System.out.println("\n } for (List<String> parameterSet : Procedures.get(procedure).values()) { System.out.printf(format, procedure); System.out.print("\t"); int pidx = 0; for(String paramType : parameterSet) { if (pidx > 0) System.out.print(", "); System.out.print(paramType); pidx++; } System.out.print("\n"); } j++; } } System.out.print("\n"); } } // EXIT command - ONLY in interactive mode, exit immediately (without running any queued statements) else if (ListTablesToken.matcher(line).matches()) { if (interactive) { Object[] lists = GetTableList(); for(int i=0;i<3;i++) { if (i == 0) System.out.println("\n else if (i == 1) System.out.println("\n else System.out.println("\n @SuppressWarnings("unchecked") Iterator<String> list = ((TreeSet<String>)lists[i]).iterator(); while(list.hasNext()) System.out.println(list.next()); System.out.print("\n"); } System.out.print("\n"); } } // GO commands - ONLY in interactive mode, close batch and parse for execution else if (GoToken.matcher(line).matches()) { if (interactive) return parseQuery(query.toString().trim()); } // FILE command - include the content of the file into the query else if (FileToken.matcher(line).matches()) { boolean executeImmediate = false; if (interactive && SemicolonToken.matcher(line).matches()) executeImmediate = true; Matcher m = FileToken.matcher(line); if (m.find()) { line = readScriptFile(m.group(1)); if (line == null) { if (!interactive) return null; } else { query.append(line); query.append("\n"); if (executeImmediate) return parseQuery(query.toString().trim()); } } else { System.err.print("Invalid FILE command: '" + line + "'."); // In non-interactive mode, a failure aborts the entire batch // In interactive mode, we'll just ignore that specific failed command. if (!interactive) return null; } } else { query.append(line); query.append("\n"); if (interactive && SemicolonToken.matcher(line).matches()) return parseQuery(query.toString().trim()); } line = null; } while(true); } public static String readScriptFile(String filePath) { try { StringBuilder query = new StringBuilder(); BufferedReader script = new BufferedReader(new FileReader(filePath)); String line; while ((line = script.readLine()) != null) { // Strip out RECALL, EXIT and GO commands if (!(RecallToken.matcher(line).matches() || ExitToken.matcher(line).matches() || GoToken.matcher(line).matches())) { // Recursively process FILE commands, any failure will cause a recursive failure if (FileToken.matcher(line).matches()) { Matcher m = FileToken.matcher(line); if (m.find()) { line = readScriptFile(m.group(1)); if (line == null) return null; query.append(line); query.append("\n"); } else { System.err.print("Invalid FILE command: '" + line + "'."); return null; } } else { query.append(line); query.append("\n"); } } } script.close(); return query.toString().trim(); } catch(FileNotFoundException e) { System.err.println("Script file '" + filePath + "' could not be found."); return null; } catch(Exception x) { System.err.println(x.getMessage()); return null; } } // Query Execution private static final Pattern ExecuteCall = Pattern.compile("^(exec|execute) ", Pattern.MULTILINE + Pattern.CASE_INSENSITIVE); private static final Pattern ExplainCall = Pattern.compile("^explain ", Pattern.MULTILINE + Pattern.CASE_INSENSITIVE); private static final Pattern ExplainProcCall = Pattern.compile("^explainProc ", Pattern.MULTILINE + Pattern.CASE_INSENSITIVE); private static final Pattern StripCRLF = Pattern.compile("[\r\n]+", Pattern.MULTILINE); private static final Pattern IsNull = Pattern.compile("null", Pattern.CASE_INSENSITIVE); private static final SimpleDateFormat DateParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private static final Pattern Unquote = Pattern.compile("^'|'$", Pattern.MULTILINE); private static void executeQuery(String query) throws Exception { if (ExecuteCall.matcher(query).find()) { query = ExecuteCall.matcher(query).replaceFirst(""); List<String> params = parseQueryProcedureCallParameters(query); String procedure = params.remove(0); if (!Procedures.containsKey(procedure)) throw new Exception("Undefined procedure: " + procedure); List<String> paramTypes = Procedures.get(procedure).get(params.size()); if (paramTypes == null || params.size() != paramTypes.size()) { String expectedSizes = ""; for (Integer expectedSize : Procedures.get(procedure).keySet()) { expectedSizes += expectedSize + ", "; } throw new Exception("Invalid parameter count for procedure: " + procedure + "(expected: " + expectedSizes + " received: " + params.size() + ")"); } Object[] objectParams = new Object[params.size()]; if (procedure.equals("@SnapshotDelete")) { objectParams[0] = new String[] { Unquote.matcher(params.get(0)).replaceAll("").replace("''","'") }; objectParams[1] = new String[] { Unquote.matcher(params.get(1)).replaceAll("").replace("''","'") }; } else { for(int i = 0;i<params.size();i++) { String paramType = paramTypes.get(i); String param = params.get(i); if (paramType.equals("bit")) { if(param.equals("yes") || param.equals("true") || param.equals("1")) objectParams[i] = (byte)1; else objectParams[i] = (byte)0; } else if (paramType.equals("tinyint")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_TINYINT; else { try { objectParams[i] = Byte.parseByte(param); } catch (NumberFormatException nfe) { throw new Exception("Invalid parameter: Expected a byte numeric value, got '" + param + "' (param " + (i+1) + ")."); } } } else if (paramType.equals("smallint")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_SMALLINT; else { try { objectParams[i] = Short.parseShort(param); } catch (NumberFormatException nfe) { throw new Exception("Invalid parameter: Expected a short numeric value, got '" + param + "' (param " + (i+1) + ")."); } } } else if (paramType.equals("int") || paramType.equals("integer")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_INTEGER; else { try { objectParams[i] = Integer.parseInt(param); } catch (NumberFormatException nfe) { throw new Exception("Invalid parameter: Expected a numeric value, got '" + param + "' (param " + (i+1) + ")."); } } } else if (paramType.equals("bigint")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_BIGINT; else { try { objectParams[i] = Long.parseLong(param); } catch (NumberFormatException nfe) { throw new Exception("Invalid parameter: Expected a numeric value, got '" + param + "' (param " + (i+1) + ")."); } } } else if (paramType.equals("float")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_FLOAT; else { try { objectParams[i] = Double.parseDouble(param); } catch (NumberFormatException nfe) { throw new Exception("Invalid parameter: Expected a float value, got '" + param + "' (param " + (i+1) + ")."); } } } else if (paramType.equals("varchar")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_STRING_OR_VARBINARY; else objectParams[i] = Unquote.matcher(param).replaceAll("").replace("''","'"); } else if (paramType.equals("decimal")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_DECIMAL; else objectParams[i] = new BigDecimal(param); } else if (paramType.equals("timestamp")) { if (IsNull.matcher(param).matches()) { objectParams[i] = VoltType.NULL_TIMESTAMP; } else { // Remove any quotes around the timestamp value. ENG-2623 objectParams[i] = DateParser.parse(param.replaceAll("^\"|\"$", "").replaceAll("^'|'$", "")); } } else if (paramType.equals("statisticscomponent")) { String p = preprocessParam(param); if (!StatisticsComponents.contains(p)) throw new Exception("Invalid Statistics Component: " + param); objectParams[i] = p; } else if (paramType.equals("sysinfoselector")) { String p = preprocessParam(param); if (!SysInfoSelectors.contains(p)) throw new Exception("Invalid SysInfo Selector: " + param); objectParams[i] = p; } else if (paramType.equals("metadataselector")) { String p = preprocessParam(param); if (!MetaDataSelectors.contains(p)) throw new Exception("Invalid Meta-Data Selector: " + param); objectParams[i] = p; } else if (paramType.equals("varbinary") || paramType.equals("tinyint_array")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_STRING_OR_VARBINARY; else { // Make sure we have an even amount of characters, otherwise it is an invalid hex string if (param.length() % 2 == 1) throw new Exception("Invalid varbinary value: input must have an even amount of characters to be a valid hex string."); String val = Unquote.matcher(param).replaceAll("").replace("''","'"); objectParams[i] = hexStringToByteArray(val); } } else throw new Exception("Unsupported Data Type: " + paramType); } } if (procedure.equals("@UpdateApplicationCatalog")) { printResponse(VoltDB.updateApplicationCatalog(new File((String) objectParams[0]), new File((String) objectParams[1]))); } else { printResponse(VoltDB.callProcedure(procedure, objectParams)); } } else if (ExplainCall.matcher(query).find()) { query = query.substring("explain ".length()); query = StripCRLF.matcher(query).replaceAll(" "); printResponse(VoltDB.callProcedure("@Explain", query)); } else if (ExplainProcCall.matcher(query).find()) { query = query.substring("explainProc ".length()); query = StripCRLF.matcher(query).replaceAll(" "); printResponse(VoltDB.callProcedure("@ExplainProc", query)); } else // Ad hoc query { query = StripCRLF.matcher(query).replaceAll(" "); printResponse(VoltDB.callProcedure("@AdHoc", query)); } return; } // Uppercase param. // Remove any quotes. // Trim private static String preprocessParam(String param) { param = param.toUpperCase(); if (param.startsWith("'") && param.endsWith("'")) param = param.substring(1, param.length()-1); if (param.charAt(0)=='"' && param.charAt(param.length()-1)=='"') param = param.substring(1, param.length()-1); param = param.trim(); return param; } private static String byteArrayToHexString(byte[] data) { StringBuffer hexString = new StringBuffer(); for (int i=0;i<data.length;i++) { String hex = Integer.toHexString(0xFF & data[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } private static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); return data; } // Output generation private static String OutputFormat = "fixed"; private static boolean OutputShowMetadata = true; public static String paddingString(String s, int n, char c, boolean paddingLeft) { if (s == null) return s; int add = n - s.length(); if(add <= 0) return s; StringBuffer str = new StringBuffer(s); char[] ch = new char[add]; Arrays.fill(ch, c); if(paddingLeft) str.insert(0, ch); else str.append(ch); return str.toString(); } private static boolean isUpdateResult(VoltTable table) { return ((table.getColumnName(0).length() == 0 || table.getColumnName(0).equals("modified_tuples"))&& table.getRowCount() == 1 && table.getColumnCount() == 1 && table.getColumnType(0) == VoltType.BIGINT); } private static void printResponse(ClientResponse response) throws Exception { if (response.getStatus() != ClientResponse.SUCCESS) throw new Exception("Execution Error: " + response.getStatusString()); if (OutputFormat.equals("fixed")) { for(VoltTable t : response.getResults()) { if (isUpdateResult(t)) { if(OutputShowMetadata) System.out.printf("\n\n(%d row(s) affected)\n", t.fetchRow(0).getLong(0)); continue; } int columnCount = t.getColumnCount(); int[] padding = new int[columnCount]; String[] fmt = new String[columnCount]; for (int i = 0; i < columnCount; i++) padding[i] = OutputShowMetadata ? t.getColumnName(i).length() : 0; t.resetRowPosition(); while(t.advanceRow()) { for (int i = 0; i < columnCount; i++) { Object v = t.get(i, t.getColumnType(i)); if (t.wasNull()) v = "NULL"; int l = 0; // length if (t.getColumnType(i) == VoltType.VARBINARY && !t.wasNull()) { l = ((byte[])v).length*2; } else { l= v.toString().length(); } if (padding[i] < l) padding[i] = l; } } for (int i = 0; i < columnCount; i++) { padding[i] += 1; fmt[i] = "%1$" + ((t.getColumnType(i) == VoltType.STRING || t.getColumnType(i) == VoltType.TIMESTAMP || t.getColumnType(i) == VoltType.VARBINARY) ? "-" : "") + padding[i] + "s"; } if (OutputShowMetadata) { for (int i = 0; i < columnCount; i++) { System.out.printf("%1$-" + padding[i] + "s", t.getColumnName(i)); if (i < columnCount - 1) System.out.print(" "); } System.out.print("\n"); for (int i = 0; i < columnCount; i++) { System.out.print(paddingString("", padding[i], '-', false)); if (i < columnCount - 1) System.out.print(" "); } System.out.print("\n"); } t.resetRowPosition(); while(t.advanceRow()) { for (int i = 0; i < columnCount; i++) { Object v = t.get(i, t.getColumnType(i)); if (t.wasNull()) v = "NULL"; else if (t.getColumnType(i) == VoltType.VARBINARY) v = byteArrayToHexString((byte[])v); else v = v.toString(); System.out.printf(fmt[i], v); if (i < columnCount - 1) System.out.print(" "); } System.out.print("\n"); } if (OutputShowMetadata) System.out.printf("\n\n(%d row(s) affected)\n", t.getRowCount()); } } else { String separator = OutputFormat.equals("csv") ? "," : "\t"; for(VoltTable t : response.getResults()) { if (isUpdateResult(t)) { if(OutputShowMetadata) System.out.printf("\n\n(%d row(s) affected)\n", t.fetchRow(0).getLong(0)); continue; } int columnCount = t.getColumnCount(); if (OutputShowMetadata) { for (int i = 0; i < columnCount; i++) { if (i > 0) System.out.print(separator); System.out.print(t.getColumnName(i)); } System.out.print("\n"); } t.resetRowPosition(); while(t.advanceRow()) { for (int i = 0; i < columnCount; i++) { if (i > 0) System.out.print(separator); Object v = t.get(i, t.getColumnType(i)); if (t.wasNull()) v = "NULL"; else if (t.getColumnType(i) == VoltType.VARBINARY) v = byteArrayToHexString((byte[])v); else v = v.toString(); System.out.print(v); } System.out.print("\n"); } if (OutputShowMetadata) System.out.printf("\n\n(%d row(s) affected)\n", t.getRowCount()); } } } // VoltDB connection support private static Client VoltDB; private static final List<String> StatisticsComponents = Arrays.asList("INDEX","INITIATOR","IOSTATS","MANAGEMENT","MEMORY","PROCEDURE","TABLE","PARTITIONCOUNT","STARVATION","LIVECLIENTS", "DR", "TOPO"); private static final List<String> SysInfoSelectors = Arrays.asList("OVERVIEW","DEPLOYMENT"); private static final List<String> MetaDataSelectors = Arrays.asList("TABLES", "COLUMNS", "INDEXINFO", "PRIMARYKEYS", "PROCEDURES", "PROCEDURECOLUMNS"); private static Map<String,Map<Integer, List<String>>> Procedures = Collections.synchronizedMap(new HashMap<String,Map<Integer, List<String>>>()); private static void loadSystemProcedures() { Procedures.put("@Pause", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@Quiesce", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@Resume", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@Shutdown", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@SnapshotDelete", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build() ); Procedures.put("@SnapshotRestore", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build() ); Procedures.put("@SnapshotSave", ImmutableMap.<Integer, List<String>>builder().put( 3, Arrays.asList("varchar", "varchar", "bit")). put( 1, Arrays.asList("varchar")).build() ); Procedures.put("@SnapshotScan", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@Statistics", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("statisticscomponent", "bit")).build()); Procedures.put("@SystemCatalog", ImmutableMap.<Integer, List<String>>builder().put( 1,Arrays.asList("metadataselector")).build()); Procedures.put("@SystemInformation", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("sysinfoselector")).build()); Procedures.put("@UpdateApplicationCatalog", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build()); Procedures.put("@UpdateLogging", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@Promote", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@SnapshotStatus", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@AdHoc_RO_MP", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@AdHoc_RO_SP", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "bigint")).build()); Procedures.put("@AdHoc_RW_MP", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@AdHoc_RW_SP", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "bigint")).build()); Procedures.put("@Explain", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@ExplainProc", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); } public static Client getClient(ClientConfig config, String[] servers, int port) throws Exception { final Client client = ClientFactory.createClient(config); for (String server : servers) client.createConnection(server.trim(), port); return client; } // General application support private static void printUsage(String msg) { System.out.print(msg); System.out.println("\n"); printUsage(-1); } private static void printUsage(int exitCode) { System.out.println( "Usage: sqlcmd --help\n" + " or sqlcmd [--servers=comma_separated_server_list]\n" + " [--port=port_number]\n" + " [--user=user]\n" + " [--password=password]\n" + " [--output-format=(fixed|csv|tab)]\n" + " [--output-skip-metadata]\n" + "\n" + "[--servers=comma_separated_server_list]\n" + " List of servers to connect to.\n" + " Default: localhost.\n" + "\n" + "[--port=port_number]\n" + " Client port to connect to on cluster nodes.\n" + " Default: 21212.\n" + "\n" + "[--user=user]\n" + " Name of the user for database login.\n" + " Default: (not defined - connection made without credentials).\n" + "\n" + "[--password=password]\n" + " Password of the user for database login.\n" + " Default: (not defined - connection made without credentials).\n" + "\n" + "[--output-format=(fixed|csv|tab)]\n" + " Format of returned resultset data (Fixed-width, CSV or Tab-delimited).\n" + " Default: fixed.\n" + "\n" + "[--output-skip-metadata]\n" + " Removes metadata information such as column headers and row count from\n" + " produced output.\n" + "\n" + "[--debug]\n" + " Causes the utility to print out stack traces for all exceptions.\n" ); System.exit(exitCode); } // printHelp() can print readme either to a file or to the screen // depending on the argument passed in public static void printHelp(OutputStream prtStr) { try { InputStream is = SQLCommand.class.getResourceAsStream(readme); while(is.available() > 0) { byte[] bytes = new byte[is.available()]; // Fix for ENG-3440 is.read(bytes, 0, bytes.length); prtStr.write(bytes); // For JUnit test } } catch(Exception x) { System.err.println(x.getMessage()); System.exit(-1); } } private static Object[] GetTableList() throws Exception { VoltTable tableData = VoltDB.callProcedure("@SystemCatalog", "TABLES").getResults()[0]; TreeSet<String> tables = new TreeSet<String>(); TreeSet<String> exports = new TreeSet<String>(); TreeSet<String> views = new TreeSet<String>(); for(int i = 0; i < tableData.getRowCount(); i++) { String tableName = tableData.fetchRow(i).getString("TABLE_NAME"); String tableType = tableData.fetchRow(i).getString("TABLE_TYPE"); if (tableType.equalsIgnoreCase("EXPORT")) { exports.add(tableName); } else if (tableType.equalsIgnoreCase("VIEW")) { views.add(tableName); } else { tables.add(tableName); } } return new Object[] {tables, views, exports}; } private static void loadStoredProcedures(Map<String,Map<Integer, List<String>>> procedures) { VoltTable procs = null; VoltTable params = null; try { procs = VoltDB.callProcedure("@SystemCatalog", "PROCEDURES").getResults()[0]; params = VoltDB.callProcedure("@SystemCatalog", "PROCEDURECOLUMNS").getResults()[0]; } catch (NoConnectionsException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } catch (ProcCallException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } Map<String, Integer> proc_param_counts = Collections.synchronizedMap(new HashMap<String, Integer>()); while (params.advanceRow()) { String this_proc = params.getString("PROCEDURE_NAME"); if (!proc_param_counts.containsKey(this_proc)) { proc_param_counts.put(this_proc, 0); } int curr_val = proc_param_counts.get(this_proc); proc_param_counts.put(this_proc, ++curr_val); } params.resetRowPosition(); while (procs.advanceRow()) { String proc_name = procs.getString("PROCEDURE_NAME"); ArrayList<String> this_params = new ArrayList<String>(); // prepopulate it to make sure the size is right if (proc_param_counts.get(proc_name) != null) { for (int i = 0; i < proc_param_counts.get(procs.getString("PROCEDURE_NAME")); i++) { this_params.add(null); } } HashMap<Integer, List<String>> argLists = new HashMap<Integer, List<String>>(); if (proc_param_counts.containsKey(proc_name)) { argLists.put(proc_param_counts.get(proc_name), this_params); } else { argLists.put(0, this_params); } procedures.put(procs.getString("PROCEDURE_NAME"), argLists); } // Retrieve the parameter types. Note we have to do some special checking // for array types. ENG-3101 params.resetRowPosition(); while (params.advanceRow()) { Map<Integer, List<String>> argLists = procedures.get(params.getString("PROCEDURE_NAME")); assert(argLists.size() == 1); List<String> this_params = argLists.values().iterator().next(); int idx = (int)params.getLong("ORDINAL_POSITION") - 1; String param_type = params.getString("TYPE_NAME").toLowerCase(); // Detect if this parameter is supposed to be an array. It's kind of clunky, we have to // look in the remarks column... String param_remarks = params.getString("REMARKS"); if (null != param_remarks) { param_type += (param_remarks.equalsIgnoreCase("ARRAY_PARAMETER") ? "_array" : ""); } this_params.set(idx, param_type); } } static public void mockVoltDBForTest(Client testVoltDB) { VoltDB = testVoltDB; } private static InputStream in = null; private static Writer out = null; // Application entry point public static void main(String args[]) { TimeZone.setDefault(TimeZone.getTimeZone("GMT+0")); boolean debug = false; try { // Initialize parameter defaults String serverList = "localhost"; int port = 21212; String user = ""; String password = ""; // Parse out parameters for(int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.startsWith("--servers=")) serverList = arg.split("=")[1]; else if (arg.startsWith("--port=")) port = Integer.valueOf(arg.split("=")[1]); else if (arg.startsWith("--user=")) user = arg.split("=")[1]; else if (arg.startsWith("--password=")) password = arg.split("=")[1]; else if (arg.startsWith("--output-format=")) { if (Pattern.compile("(fixed|csv|tab)", Pattern.CASE_INSENSITIVE).matcher(arg.split("=")[1].toLowerCase()).matches()) OutputFormat = arg.split("=")[1].toLowerCase(); else printUsage("Invalid value for --output-format"); } else if (arg.equals("--output-skip-metadata")) OutputShowMetadata = false; else if (arg.equals("--debug")) debug = true; else if (arg.equals("--help")) { printHelp(System.out); // Print readme to the screen System.out.println("\n\n"); printUsage(0); } else if ((arg.equals("--usage")) || (arg.equals("-?"))) printUsage(0); else printUsage("Invalid Parameter: " + arg); } // Split server list String[] servers = serverList.split(","); // Load system procedures loadSystemProcedures(); // Don't ask... Java is such a crippled language! DateParser.setLenient(true); // Create connection ClientConfig config = new ClientConfig(user, password); config.setProcedureCallTimeout(0); // Set procedure all to infinite timeout, see ENG-2670 VoltDB = getClient(config, servers, port); // Load user stored procs loadStoredProcedures(Procedures); List<String> queries = null; in = new FileInputStream(FileDescriptor.in); out = new PrintWriter(new OutputStreamWriter(System.out, System.getProperty("jline.WindowsTerminal.output.encoding", System.getProperty("file.encoding")))); Input = new ConsoleReader(in, out); Input.setBellEnabled(false); Input.addCompletor(new SimpleCompletor(new String[] {"select", "update", "insert", "delete", "exec", "file", "recall", "SELECT", "UPDATE", "INSERT", "DELETE", "EXEC", "FILE", "RECALL" })); // If Standard input comes loaded with data, run in non-interactive mode if (System.in.available() > 0) { queries = getQuery(false); if (queries == null) System.exit(0); else for(int i = 0;i<queries.size();i++) executeQuery(queries.get(i)); } else { // Print out welcome message System.out.printf("SQL Command :: %s%s:%d\n", (user == "" ? "" : user + "@"), serverList, port); while((queries = getQuery(true)) != null) { try { for(int i = 0;i<queries.size();i++) executeQuery(queries.get(i)); } catch(Exception x) { System.err.println(x.getMessage()); if (debug) x.printStackTrace(System.err); } } } } catch (Exception e) { System.err.println(e.getMessage()); if (debug) e.printStackTrace(System.err); System.exit(-1); } finally { try { VoltDB.close(); } catch(Exception _) {} } } }
package com.proyecto.front.util; /* * Ejemplo de clase. Podemos aceptar todo tipo de excepciones */ public class AccesoServiciosException extends Exception { public AccesoServiciosException(WebApplicationException e) { super(e); } public AccesoServiciosException(ServerWebApplicationException e) { super(e); } public AccesoServiciosException(ClientWebApplicationException e) { super(e); } public AccesoServiciosException(BusinessServiceException e) { super(e); } public AccesoServiciosException(String string) { super(string); } private static final long serialVersionUID = 1L; }
package ca.corefacility.bioinformatics.irida.database.changesets; import ca.corefacility.bioinformatics.irida.config.data.IridaApiJdbcDataSourceConfig; import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowNotFoundException; import ca.corefacility.bioinformatics.irida.model.workflow.IridaWorkflow; import ca.corefacility.bioinformatics.irida.model.workflow.analysis.type.BuiltInAnalysisTypes; import ca.corefacility.bioinformatics.irida.model.workflow.description.IridaWorkflowParameter; import ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowsService; import liquibase.change.custom.CustomSqlChange; import liquibase.database.Database; import liquibase.exception.CustomChangeException; import liquibase.exception.SetupException; import liquibase.exception.ValidationErrors; import liquibase.resource.ResourceAccessor; import liquibase.statement.SqlStatement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import javax.sql.DataSource; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Liquibase update to convert the project settings for automated Assembly and SISTR checkboxes to analysis templates. */ public class AutomatedAnalysisToTemplate implements CustomSqlChange { private static final Logger logger = LoggerFactory.getLogger(AutomatedAnalysisToTemplate.class); private IridaWorkflowsService workflowsService; private DataSource dataSource; @Override public SqlStatement[] generateStatements(Database database) throws CustomChangeException { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); IridaWorkflow assemblyWorkflow = null; IridaWorkflow sistrWorkflow = null; //get the workflow information from the service try { assemblyWorkflow = workflowsService.getDefaultWorkflowByType(BuiltInAnalysisTypes.ASSEMBLY_ANNOTATION); logger.debug("Updating automated assembly project settings"); //get the workflow identifiers UUID assemblyId = assemblyWorkflow.getWorkflowIdentifier(); //get the default parameters List<IridaWorkflowParameter> defaultAssemblyParams = assemblyWorkflow.getWorkflowDescription() .getParameters(); //insert the assembly insertWorkflow(jdbcTemplate, "Automated AssemblyAnnotation", true, assemblyId, "p.assemble_uploads=1", defaultAssemblyParams); } catch (IridaWorkflowNotFoundException e) { logger.warn( "Assembly workflow not found. Automated assemblies will not be converted to analysis templates."); //Note this will definitely happen in the galaxy CI tests as only SNVPhyl and a test workflow are configured. } //get the workflow information from the service try { sistrWorkflow = workflowsService.getDefaultWorkflowByType(BuiltInAnalysisTypes.SISTR_TYPING); logger.debug("Updating automated SISTR project settings"); //get the workflow identifiers UUID sistrId = sistrWorkflow.getWorkflowIdentifier(); //get the default params List<IridaWorkflowParameter> defaultSistrParams = sistrWorkflow.getWorkflowDescription() .getParameters(); //insert the sistr entries without metadata insertWorkflow(jdbcTemplate, "Automated SISTR Typing", false, sistrId, "p.sistr_typing_uploads='AUTO'", defaultSistrParams); //insert the sistr entries with metadata insertWorkflow(jdbcTemplate, "Automated SISTR Typing", true, sistrId, "p.sistr_typing_uploads='AUTO_METADATA'", defaultSistrParams); } catch (IridaWorkflowNotFoundException e) { logger.warn("SISTR workflow not found. Automated SISTR will not be converted to analysis templates."); //Note this will definitely happen in the galaxy CI tests as only SNVPhyl and a test workflow are configured. } return new SqlStatement[0]; } private void insertWorkflow(JdbcTemplate jdbcTemplate, String name, boolean updateSamples, UUID workflowId, String where, List<IridaWorkflowParameter> params) { /* * we're borrowing the 'automated' flag here to mark entries we need to add params to later. at this point * there'll be nothing with a '1' in the automated flag. we'll clear it later. */ //first get the project ids that have an automated submission String idSql = "SELECT p.id FROM project p WHERE " + where; List<Long> projectIds = jdbcTemplate.queryForList(idSql, Long.class); //build the params for the insert submission List<Object[]> queryParams = projectIds.stream() .map(p -> { return new Object[] { name, updateSamples, workflowId.toString(), p }; }) .collect(Collectors.toList()); //then insert the submisisons for each project String submissionInsert = "INSERT INTO analysis_submission (DTYPE, name, created_date, priority, update_samples, workflow_id, submitter, submitted_project_id, automated) VALUES ('AnalysisSubmissionTemplate', ?, now(), 'LOW', ?, ?, 1, ?, 1)"; int[] updates = jdbcTemplate.batchUpdate(submissionInsert, queryParams); //check if we did any updates int update = IntStream.of(updates) .sum(); //if we added anything, add the params if (update > 0) { // Insert the default params for the analysis type for (IridaWorkflowParameter p : params) { //first get the analysis submission ids we're inserting for String paramSelect = "SELECT a.id FROM analysis_submission a WHERE a.name=? AND a.automated=1"; List<Long> submissionIds = jdbcTemplate.queryForList(paramSelect, Long.class, name); //build the argument list for the query List<Object[]> submissionParamArgs = submissionIds.stream() .map(i -> { return new Object[] { i, p.getName(), p.getDefaultValue() }; }) .collect(Collectors.toList()); //then insert the params for each submission String paramInsert = "INSERT INTO analysis_submission_parameters (id, name,value) VALUES (?, ?, ?)"; jdbcTemplate.batchUpdate(paramInsert, submissionParamArgs); } // remove the automated=1 String removeAutomatedSql = "UPDATE analysis_submission SET automated=null WHERE DTYPE = 'AnalysisSubmissionTemplate' AND name=?"; jdbcTemplate.update(removeAutomatedSql, name); } else { logger.debug("No automated analyeses added for " + name); } } @Override public String getConfirmationMessage() { return "Converted automated SISTR and AssemblyAnnotation project settings to analysis templates"; } @Override public void setUp() throws SetupException { logger.info("Converting automated SISTR and AssemblyAnnotation project settings to analysis templates"); } @Override public void setFileOpener(ResourceAccessor resourceAccessor) { logger.info("The resource accessor is of type [" + resourceAccessor.getClass() + "]"); final ApplicationContext applicationContext; if (resourceAccessor instanceof IridaApiJdbcDataSourceConfig.ApplicationContextAwareSpringLiquibase.ApplicationContextSpringResourceOpener) { applicationContext = ((IridaApiJdbcDataSourceConfig.ApplicationContextAwareSpringLiquibase.ApplicationContextSpringResourceOpener) resourceAccessor).getApplicationContext(); } else { applicationContext = null; } if (applicationContext != null) { logger.info("We're running inside of a spring instance, getting the existing application context."); this.workflowsService = applicationContext.getBean(IridaWorkflowsService.class); this.dataSource = applicationContext.getBean(DataSource.class); } else { logger.error( "This changeset *must* be run from a servlet container as it requires access to Spring's application context."); throw new IllegalStateException( "This changeset *must* be run from a servlet container as it requires access to Spring's application context."); } } @Override public ValidationErrors validate(Database database) { return null; } }
package ca.corefacility.bioinformatics.irida.database.changesets; import ca.corefacility.bioinformatics.irida.config.data.IridaApiJdbcDataSourceConfig; import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowNotFoundException; import ca.corefacility.bioinformatics.irida.model.workflow.IridaWorkflow; import ca.corefacility.bioinformatics.irida.model.workflow.analysis.type.BuiltInAnalysisTypes; import ca.corefacility.bioinformatics.irida.model.workflow.description.IridaWorkflowParameter; import ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowsService; import liquibase.change.custom.CustomSqlChange; import liquibase.database.Database; import liquibase.exception.CustomChangeException; import liquibase.exception.SetupException; import liquibase.exception.ValidationErrors; import liquibase.resource.ResourceAccessor; import liquibase.statement.SqlStatement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Liquibase update to convert the project settings for automated Assembly and SISTR checkboxes to analysis templates. */ public class AutomatedAnalysisToTemplate implements CustomSqlChange { private static final Logger logger = LoggerFactory.getLogger(AutomatedAnalysisToTemplate.class); private IridaWorkflowsService workflowsService; private DataSource dataSource; @Override public SqlStatement[] generateStatements(Database database) throws CustomChangeException { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); IridaWorkflow assemblyWorkflow = null; IridaWorkflow sistrWorkflow = null; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date today = new Date(); //get the workflow information from the service try { assemblyWorkflow = workflowsService.getDefaultWorkflowByType(BuiltInAnalysisTypes.ASSEMBLY_ANNOTATION); logger.debug("Updating automated assembly project settings"); //get the workflow identifiers UUID assemblyId = assemblyWorkflow.getWorkflowIdentifier(); //get the default parameters List<IridaWorkflowParameter> defaultAssemblyParams = assemblyWorkflow.getWorkflowDescription() .getParameters(); //insert the assembly insertWorkflow(jdbcTemplate, "Automated AssemblyAnnotation", "Converted from automated assembly project setting on " + dateFormat.format(today), true, assemblyId, "p.assemble_uploads=1", defaultAssemblyParams); } catch (IridaWorkflowNotFoundException e) { logger.warn( "Assembly workflow not found. Automated assemblies will not be converted to analysis templates."); //Note this will definitely happen in the galaxy CI tests as only SNVPhyl and a test workflow are configured. } //get the workflow information from the service try { sistrWorkflow = workflowsService.getDefaultWorkflowByType(BuiltInAnalysisTypes.SISTR_TYPING); logger.debug("Updating automated SISTR project settings"); //get the workflow identifiers UUID sistrId = sistrWorkflow.getWorkflowIdentifier(); //get the default params List<IridaWorkflowParameter> defaultSistrParams = sistrWorkflow.getWorkflowDescription() .getParameters(); //insert the sistr entries without metadata insertWorkflow(jdbcTemplate, "Automated SISTR Typing", "Converted from automated SISTR typing project setting on " + dateFormat.format(today), false, sistrId, "p.sistr_typing_uploads='AUTO'", defaultSistrParams); //insert the sistr entries with metadata insertWorkflow(jdbcTemplate, "Automated SISTR Typing", "Converted from automated SISTR typing project setting on " + dateFormat.format(today), true, sistrId, "p.sistr_typing_uploads='AUTO_METADATA'", defaultSistrParams); } catch (IridaWorkflowNotFoundException e) { logger.warn("SISTR workflow not found. Automated SISTR will not be converted to analysis templates."); //Note this will definitely happen in the galaxy CI tests as only SNVPhyl and a test workflow are configured. } return new SqlStatement[0]; } private void insertWorkflow(JdbcTemplate jdbcTemplate, String name, String description, boolean updateSamples, UUID workflowId, String where, List<IridaWorkflowParameter> params) { /* * we're borrowing the 'automated' flag here to mark entries we need to add params to later. at this point * there'll be nothing with a '1' in the automated flag. we'll clear it later. */ //first get the project ids that have an automated submission String idSql = "SELECT p.id FROM project p WHERE " + where; List<Long> projectIds = jdbcTemplate.queryForList(idSql, Long.class); //build the params for the insert submission List<Object[]> queryParams = projectIds.stream() .map(p -> { return new Object[] { name, description, updateSamples, workflowId.toString(), p }; }) .collect(Collectors.toList()); //then insert the submisisons for each project String submissionInsert = "INSERT INTO analysis_submission (DTYPE, name, analysis_description, created_date, priority, update_samples, workflow_id, submitter, submitted_project_id, automated) VALUES ('AnalysisSubmissionTemplate', ?, ?, now(), 'LOW', ?, ?, 1, ?, 1)"; int[] updates = jdbcTemplate.batchUpdate(submissionInsert, queryParams); //check if we did any updates int update = IntStream.of(updates) .sum(); //if we added anything, add the params if (update > 0) { // Insert the default params for the analysis type for (IridaWorkflowParameter p : params) { //first get the analysis submission ids we're inserting for String paramSelect = "SELECT a.id FROM analysis_submission a WHERE a.name=? AND a.automated=1"; List<Long> submissionIds = jdbcTemplate.queryForList(paramSelect, Long.class, name); //build the argument list for the query List<Object[]> submissionParamArgs = submissionIds.stream() .map(i -> { return new Object[] { i, p.getName(), p.getDefaultValue() }; }) .collect(Collectors.toList()); //then insert the params for each submission String paramInsert = "INSERT INTO analysis_submission_parameters (id, name,value) VALUES (?, ?, ?)"; jdbcTemplate.batchUpdate(paramInsert, submissionParamArgs); } // remove the automated=1 String removeAutomatedSql = "UPDATE analysis_submission SET automated=null WHERE DTYPE = 'AnalysisSubmissionTemplate' AND name=?"; jdbcTemplate.update(removeAutomatedSql, name); } else { logger.debug("No automated analyeses added for " + name); } } @Override public String getConfirmationMessage() { return "Converted automated SISTR and AssemblyAnnotation project settings to analysis templates"; } @Override public void setUp() throws SetupException { logger.info("Converting automated SISTR and AssemblyAnnotation project settings to analysis templates"); } @Override public void setFileOpener(ResourceAccessor resourceAccessor) { logger.info("The resource accessor is of type [" + resourceAccessor.getClass() + "]"); final ApplicationContext applicationContext; if (resourceAccessor instanceof IridaApiJdbcDataSourceConfig.ApplicationContextAwareSpringLiquibase.ApplicationContextSpringResourceOpener) { applicationContext = ((IridaApiJdbcDataSourceConfig.ApplicationContextAwareSpringLiquibase.ApplicationContextSpringResourceOpener) resourceAccessor).getApplicationContext(); } else { applicationContext = null; } if (applicationContext != null) { logger.info("We're running inside of a spring instance, getting the existing application context."); this.workflowsService = applicationContext.getBean(IridaWorkflowsService.class); this.dataSource = applicationContext.getBean(DataSource.class); } else { logger.error( "This changeset *must* be run from a servlet container as it requires access to Spring's application context."); throw new IllegalStateException( "This changeset *must* be run from a servlet container as it requires access to Spring's application context."); } } @Override public ValidationErrors validate(Database database) { return null; } }
package org.helioviewer.jhv.plugins.swhvhekplugin; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.swing.ImageIcon; import org.helioviewer.base.astronomy.Position; import org.helioviewer.base.astronomy.Sun; import org.helioviewer.base.math.GL3DMat4d; import org.helioviewer.base.math.GL3DVec3d; import org.helioviewer.jhv.data.datatype.event.JHVCoordinateSystem; import org.helioviewer.jhv.data.datatype.event.JHVEvent; import org.helioviewer.jhv.data.datatype.event.JHVEventParameter; import org.helioviewer.jhv.data.datatype.event.JHVPoint; import org.helioviewer.jhv.data.datatype.event.JHVPositionInformation; import org.helioviewer.jhv.display.Displayer; import org.helioviewer.jhv.opengl.GLTexture; import org.helioviewer.jhv.renderable.gui.Renderable; import org.helioviewer.jhv.renderable.viewport.GL3DViewport; import com.jogamp.opengl.GL2; public class SWHVHEKPluginRenderable implements Renderable { private static final float LINEWIDTH = 1f; private static final float LINEWIDTH_HI = 2f; private static HashMap<String, GLTexture> iconCacheId = new HashMap<String, GLTexture>(); private boolean isVisible = true; private void bindTexture(GL2 gl, String key, ImageIcon icon) { GLTexture tex = iconCacheId.get(key); if (tex == null) { BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); Graphics graph = bi.createGraphics(); icon.paintIcon(null, graph, 0, 0); graph.dispose(); tex = new GLTexture(gl); tex.bind(gl, GL2.GL_TEXTURE_2D); tex.copyBufferedImage2D(gl, bi); iconCacheId.put(key, tex); } tex.bind(gl, GL2.GL_TEXTURE_2D); } private void drawCactusArc(GL2 gl, JHVEvent evt, Date now) { Collection<JHVEventParameter> params = evt.getAllEventParameters().values(); double principleAngle = 0; double angularWidth = 0; double distSun = 1.; for (JHVEventParameter param : params) { String name = param.getParameterName(); String value = param.getParameterValue(); if (name.equals("cme_angularwidth")) { angularWidth = Double.parseDouble(value) * Math.PI / 180.; } if (name.equals("event_coord1")) { principleAngle = Math.PI / 2. - Double.parseDouble(value) * Math.PI / 180.; } if (name.equals("event_coord2")) { distSun = Double.parseDouble(value); } } double arcResolution = 100; int lineResolution = 2; Date date = new Date((evt.getStartDate().getTime() + evt.getEndDate().getTime()) / 2); Position.Latitudinal p = Sun.getEarth(date); double thetaDelta = p.lat; double thetaStart = principleAngle - angularWidth / 2.; double thetaEnd = principleAngle + angularWidth / 2.; double phi = -Math.PI / 2. - p.lon; Color color = evt.getEventRelationShip().getRelationshipColor(); if (color == null) { color = evt.getColor(); } gl.glColor3f(color.getRed() / 255f, color.getGreen() / 255f, color.getBlue() / 255f); if (evt.isHighlighted()) { gl.glLineWidth(LINEWIDTH_HI); } else { gl.glLineWidth(LINEWIDTH); } double r, alpha, theta = thetaStart; double x, y, z; double xrot, yrot, zrot; gl.glDisable(GL2.GL_TEXTURE_2D); gl.glBegin(GL2.GL_LINE_STRIP); for (int i = 0; i <= lineResolution; i++) { alpha = 1. - i / arcResolution; r = alpha * distSun + (1 - alpha) * (distSun + 5); theta = thetaStart; x = r * Math.cos(theta) * Math.sin(phi); z = r * Math.cos(theta) * Math.cos(phi); y = r * Math.sin(theta); yrot = y * Math.cos(thetaDelta) + z * Math.sin(thetaDelta); zrot = -y * Math.sin(thetaDelta) + z * Math.cos(thetaDelta); xrot = x; gl.glVertex3f((float) xrot, (float) yrot, (float) zrot); } for (int i = 0; i < (int) (arcResolution / 2); i++) { alpha = 1. - i / arcResolution; theta = alpha * thetaStart + (1 - alpha) * thetaEnd; x = distSun * Math.cos(theta) * Math.sin(phi); z = distSun * Math.cos(theta) * Math.cos(phi); y = distSun * Math.sin(theta); yrot = y * Math.cos(thetaDelta) + z * Math.sin(thetaDelta); zrot = -y * Math.sin(thetaDelta) + z * Math.cos(thetaDelta); xrot = x; gl.glVertex3f((float) xrot, (float) yrot, (float) zrot); } for (int i = 0; i <= lineResolution / 2; i++) { alpha = 1. - i / arcResolution; r = alpha * distSun + (1 - alpha) * (distSun + 5); x = r * Math.cos(theta) * Math.sin(phi); z = r * Math.cos(theta) * Math.cos(phi); y = r * Math.sin(theta); yrot = y * Math.cos(thetaDelta) + z * Math.sin(thetaDelta); zrot = -y * Math.sin(thetaDelta) + z * Math.cos(thetaDelta); xrot = x; gl.glVertex3f((float) xrot, (float) yrot, (float) zrot); } for (int i = (int) (arcResolution / 2); i <= arcResolution; i++) { alpha = 1. - i / arcResolution; theta = alpha * thetaStart + (1 - alpha) * thetaEnd; x = distSun * Math.cos(theta) * Math.sin(phi); z = distSun * Math.cos(theta) * Math.cos(phi); y = distSun * Math.sin(theta); yrot = y * Math.cos(thetaDelta) + z * Math.sin(thetaDelta); zrot = -y * Math.sin(thetaDelta) + z * Math.cos(thetaDelta); xrot = x; gl.glVertex3f((float) xrot, (float) yrot, (float) zrot); } for (int i = 0; i <= lineResolution; i++) { alpha = 1. - i / arcResolution; r = alpha * distSun + (1 - alpha) * (distSun + 5); theta = thetaEnd; x = r * Math.cos(theta) * Math.sin(phi); z = r * Math.cos(theta) * Math.cos(phi); y = r * Math.sin(theta); yrot = y * Math.cos(thetaDelta) + z * Math.sin(thetaDelta); zrot = -y * Math.sin(thetaDelta) + z * Math.cos(thetaDelta); xrot = x; gl.glVertex3f((float) xrot, (float) yrot, (float) zrot); } gl.glEnd(); gl.glEnable(GL2.GL_TEXTURE_2D); } private void drawPolygon(GL2 gl, JHVEvent evt, Date now) { HashMap<JHVCoordinateSystem, JHVPositionInformation> pi = evt.getPositioningInformation(); if (!pi.containsKey(JHVCoordinateSystem.JHV)) { return; } JHVPositionInformation el = pi.get(JHVCoordinateSystem.JHV); List<JHVPoint> points = el.getBoundCC(); if (points == null || points.size() == 0) { points = el.getBoundBox(); if (points == null || points.size() == 0) { return; } } Color color = evt.getEventRelationShip().getRelationshipColor(); if (color == null) { color = evt.getColor(); } gl.glColor3f(color.getRed() / 255f, color.getGreen() / 255f, color.getBlue() / 255f); if (evt.isHighlighted()) { gl.glLineWidth(LINEWIDTH_HI); } else { gl.glLineWidth(LINEWIDTH); } // draw bounds JHVPoint oldBoundaryPoint3d = null; gl.glDisable(GL2.GL_TEXTURE_2D); for (JHVPoint point : points) { int divpoints = 10; gl.glBegin(GL2.GL_LINE_STRIP); if (oldBoundaryPoint3d != null) { for (int j = 0; j <= divpoints; j++) { double alpha = 1. - j / (double) divpoints; double xnew = alpha * oldBoundaryPoint3d.getCoordinate1() + (1 - alpha) * point.getCoordinate1(); double ynew = alpha * oldBoundaryPoint3d.getCoordinate2() + (1 - alpha) * point.getCoordinate2(); double znew = alpha * oldBoundaryPoint3d.getCoordinate3() + (1 - alpha) * point.getCoordinate3(); double r = Math.sqrt(xnew * xnew + ynew * ynew + znew * znew); gl.glVertex3f((float) (xnew / r), (float) -(ynew / r), (float) (znew / r)); } } gl.glEnd(); oldBoundaryPoint3d = point; } gl.glEnable(GL2.GL_TEXTURE_2D); } private void drawIcon(GL2 gl, JHVEvent evt, Date now) { String type = evt.getJHVEventType().getEventType(); HashMap<JHVCoordinateSystem, JHVPositionInformation> pi = evt.getPositioningInformation(); if (pi.containsKey(JHVCoordinateSystem.JHV)) { JHVPositionInformation el = pi.get(JHVCoordinateSystem.JHV); if (el.centralPoint() != null) { JHVPoint pt = el.centralPoint(); bindTexture(gl, type, evt.getIcon()); if (evt.isHighlighted()) { this.drawImage3d(gl, pt.getCoordinate1(), pt.getCoordinate2(), pt.getCoordinate3(), 0.16, 0.16); } else { this.drawImage3d(gl, pt.getCoordinate1(), pt.getCoordinate2(), pt.getCoordinate3(), 0.1, 0.1); } } } } private void drawImage3d(GL2 gl, double x, double y, double z, double width, double height) { y = -y; gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR); gl.glColor3f(1f, 1f, 1f); double width2 = width / 2.; double height2 = height / 2.; GL3DVec3d sourceDir = new GL3DVec3d(0, 0, 1); GL3DVec3d targetDir = new GL3DVec3d(x, y, z); GL3DVec3d axis = sourceDir.cross(targetDir); axis.normalize(); GL3DMat4d r = GL3DMat4d.rotation(Math.atan2(x, z), GL3DVec3d.YAxis); r.rotate(-Math.asin(y / targetDir.length()), GL3DVec3d.XAxis); GL3DVec3d p0 = new GL3DVec3d(-width2, -height2, 0); GL3DVec3d p1 = new GL3DVec3d(-width2, height2, 0); GL3DVec3d p2 = new GL3DVec3d(width2, height2, 0); GL3DVec3d p3 = new GL3DVec3d(width2, -height2, 0); p0 = r.multiply(p0); p1 = r.multiply(p1); p2 = r.multiply(p2); p3 = r.multiply(p3); p0.add(targetDir); p1.add(targetDir); p2.add(targetDir); p3.add(targetDir); gl.glEnable(GL2.GL_CULL_FACE); gl.glBegin(GL2.GL_QUADS); { gl.glTexCoord2f(1f, 1f); gl.glVertex3d(p3.x, p3.y, p3.z); gl.glTexCoord2f(1f, 0f); gl.glVertex3d(p2.x, p2.y, p2.z); gl.glTexCoord2f(0f, 0f); gl.glVertex3d(p1.x, p1.y, p1.z); gl.glTexCoord2f(0f, 1f); gl.glVertex3d(p0.x, p0.y, p0.z); } gl.glEnd(); gl.glDisable(GL2.GL_CULL_FACE); } @Override public void render(GL2 gl, GL3DViewport vp) { if (isVisible) { Date currentTime = Displayer.getLastUpdatedTimestamp(); ArrayList<JHVEvent> toDraw = SWHVHEKData.getSingletonInstance().getActiveEvents(currentTime); for (JHVEvent evt : toDraw) { if (evt.getName().equals("Coronal Mass Ejection")) { drawCactusArc(gl, evt, currentTime); } else { drawPolygon(gl, evt, currentTime); gl.glDisable(GL2.GL_DEPTH_TEST); drawIcon(gl, evt, currentTime); gl.glEnable(GL2.GL_DEPTH_TEST); } } SWHVHEKSettings.resetCactusColor(); } } @Override public void remove(GL2 gl) { dispose(gl); } @Override public Component getOptionsPanel() { return null; } @Override public String getName() { return "SWEK events"; } @Override public boolean isVisible() { return isVisible; } @Override public void setVisible(boolean isVisible) { this.isVisible = isVisible; } @Override public String getTimeString() { return null; } @Override public boolean isDeletable() { return false; } @Override public boolean isActiveImageLayer() { return false; } @Override public void init(GL2 gl) { } @Override public void dispose(GL2 gl) { for (GLTexture el : iconCacheId.values()) { el.delete(gl); } iconCacheId.clear(); } @Override public void renderMiniview(GL2 gl, GL3DViewport vp) { } }
package org.apereo.cas.consent; import lombok.AllArgsConstructor; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apereo.cas.authentication.Authentication; import org.apereo.cas.authentication.principal.Service; import org.apereo.cas.services.RegisteredService; import org.apereo.cas.util.RandomUtils; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; import java.util.stream.Collectors; /** * This is {@link BaseConsentRepository}. * * @author Misagh Moayyed * @since 5.2.0 */ @Slf4j @Setter @RequiredArgsConstructor @AllArgsConstructor public abstract class BaseConsentRepository implements ConsentRepository { private static final long serialVersionUID = 1736846688546785564L; private Set<ConsentDecision> consentDecisions = new LinkedHashSet<>(); @Override public ConsentDecision findConsentDecision(final Service service, final RegisteredService registeredService, final Authentication authentication) { return this.consentDecisions.stream() .filter(d -> d.getPrincipal().equals(authentication.getPrincipal().getId()) && d.getService().equals(service.getId())) .findFirst() .orElse(null); } @Override public Collection<ConsentDecision> findConsentDecisions(final String principal) { return this.consentDecisions.stream() .filter(d -> d.getPrincipal().equals(principal)) .collect(Collectors.toSet()); } @Override public Collection<ConsentDecision> findConsentDecisions() { return new ArrayList<>(this.consentDecisions); } @Override public boolean storeConsentDecision(final ConsentDecision decision) { val consent = getConsentDecisions() .stream() .filter(d -> d.getId() == decision.getId()) .findFirst() .orElse(null); if (consent != null) { getConsentDecisions().remove(decision); } else { decision.setId(Math.abs(RandomUtils.getNativeInstance().nextInt())); } getConsentDecisions().add(decision); return true; } @Override public boolean deleteConsentDecision(final long decisionId, final String principal) { val decisions = findConsentDecisions(principal); val result = decisions.stream().filter(d -> d.getId() == decisionId).findFirst(); result.ifPresent(value -> this.consentDecisions.remove(value)); return result.isPresent(); } protected Set<ConsentDecision> getConsentDecisions() { return this.consentDecisions; } }
package com.github.verhagen.textadventure.story; import static java.util.regex.Pattern.compile; import java.util.Locale; import java.util.regex.Matcher; import org.jbehave.core.Embeddable; import org.jbehave.core.io.StoryPathResolver; import org.jbehave.core.io.UnderscoredCamelCaseResolver; /** * Implements {@link StoryPathResolver} which can read dash separated story names. * Similar as the {@link UnderscoredCamelCaseResolver} which is not really configurable, * for different separator characters. * It also is not final, but the fields {@code resolutionPattern, locale, wordToRemove}, * can not be used from an extended class. * No idea why there is a wordToRemote at all. And when it would be necessary, it would be * nicer to have it as a filter. And create a proxy chain, in case the filter is needed. */ public class DashCamelCaseResolver extends UnderscoredCamelCaseResolver { private static final String SEPARATOR = "-"; private final String resolutionPattern = NUMBERS_AS_UPPER_CASE_LETTERS_PATTERN; private final Locale locale = Locale.getDefault(); private String wordToRemove = ""; @Override protected String resolveName( Class<? extends Embeddable> embeddableClass) { String simpleName = embeddableClass.getSimpleName(); simpleName = simpleName.replace(wordToRemove, ""); Matcher matcher = compile(resolutionPattern).matcher( simpleName); int startAt = 0; StringBuilder builder = new StringBuilder(); while (matcher.find(startAt)) { builder.append(matcher.group(1).toLowerCase(locale)); builder.append(SEPARATOR); startAt = matcher.start(2); } return builder.substring(0, builder.length() - 1); } }
package com.linkedin.thirdeye.anomaly.detection; import com.linkedin.thirdeye.anomalydetection.alertFilterAutotune.AlertFilterAutoTune; import com.linkedin.thirdeye.anomalydetection.alertFilterAutotune.AlertFilterAutotuneFactory; import com.linkedin.thirdeye.client.ThirdEyeCacheRegistry; import com.linkedin.thirdeye.client.ThirdEyeClient; import com.linkedin.thirdeye.datalayer.bao.MergedAnomalyResultManager; import com.linkedin.thirdeye.datalayer.bao.RawAnomalyResultManager; import com.linkedin.thirdeye.datalayer.dto.MergedAnomalyResultDTO; import com.linkedin.thirdeye.datalayer.dto.RawAnomalyResultDTO; import com.linkedin.thirdeye.detector.email.filter.AlertFilter; import com.linkedin.thirdeye.detector.email.filter.AlertFilterFactory; import com.linkedin.thirdeye.detector.email.filter.AlertFilterEvaluationUtil; import com.linkedin.thirdeye.util.SeverityComputationUtil; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; import javax.validation.constraints.NotNull; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; import com.linkedin.thirdeye.client.DAORegistry; import com.linkedin.thirdeye.datalayer.bao.AnomalyFunctionManager; import com.linkedin.thirdeye.datalayer.dto.AnomalyFunctionDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Path("/detection-job") @Produces(MediaType.APPLICATION_JSON) public class DetectionJobResource { private final DetectionJobScheduler detectionJobScheduler; private final AnomalyFunctionManager anomalyFunctionSpecDAO; private final AnomalyFunctionManager anomalyFunctionDAO; private final MergedAnomalyResultManager mergedAnomalyResultDAO; private final RawAnomalyResultManager rawAnomalyResultDAO; private static final DAORegistry DAO_REGISTRY = DAORegistry.getInstance(); private static final ThirdEyeCacheRegistry CACHE_REGISTRY_INSTANCE = ThirdEyeCacheRegistry.getInstance(); private final AlertFilterAutotuneFactory alertFilterAutotuneFactory; private final AlertFilterFactory alertFilterFactory; private static final Logger LOG = LoggerFactory.getLogger(DetectionJobResource.class); public DetectionJobResource(DetectionJobScheduler detectionJobScheduler, AlertFilterFactory alertFilterFactory, AlertFilterAutotuneFactory alertFilterAutotuneFactory) { this.detectionJobScheduler = detectionJobScheduler; this.anomalyFunctionSpecDAO = DAO_REGISTRY.getAnomalyFunctionDAO(); this.anomalyFunctionDAO = DAO_REGISTRY.getAnomalyFunctionDAO(); this.mergedAnomalyResultDAO = DAO_REGISTRY.getMergedAnomalyResultDAO(); this.rawAnomalyResultDAO = DAO_REGISTRY.getRawAnomalyResultDAO(); this.alertFilterAutotuneFactory = alertFilterAutotuneFactory; this.alertFilterFactory = alertFilterFactory; } @POST @Path("/{id}") public Response enable(@PathParam("id") Long id) throws Exception { toggleActive(id, true); return Response.ok().build(); } @POST @Path("/{id}/ad-hoc") public Response adHoc(@PathParam("id") Long id, @QueryParam("start") String startTimeIso, @QueryParam("end") String endTimeIso) throws Exception { Long startTime = null; Long endTime = null; if (StringUtils.isBlank(startTimeIso) || StringUtils.isBlank(endTimeIso)) { throw new IllegalStateException("startTimeIso and endTimeIso must not be null"); } startTime = ISODateTimeFormat.dateTimeParser().parseDateTime(startTimeIso).getMillis(); endTime = ISODateTimeFormat.dateTimeParser().parseDateTime(endTimeIso).getMillis(); detectionJobScheduler.runAdhocAnomalyFunction(id, startTime, endTime); return Response.ok().build(); } @DELETE @Path("/{id}") public Response disable(@PathParam("id") Long id) throws Exception { toggleActive(id, false); return Response.ok().build(); } private void toggleActive(Long id, boolean state) { AnomalyFunctionDTO anomalyFunctionSpec = anomalyFunctionSpecDAO.findById(id); if(anomalyFunctionSpec == null) { throw new NullArgumentException("Function spec not found"); } anomalyFunctionSpec.setIsActive(state); anomalyFunctionSpecDAO.update(anomalyFunctionSpec); } @POST @Path("/requiresCompletenessCheck/enable/{id}") public Response enableRequiresCompletenessCheck(@PathParam("id") Long id) throws Exception { toggleRequiresCompletenessCheck(id, true); return Response.ok().build(); } @POST @Path("/requiresCompletenessCheck/disable/{id}") public Response disableRequiresCompletenessCheck(@PathParam("id") Long id) throws Exception { toggleRequiresCompletenessCheck(id, false); return Response.ok().build(); } private void toggleRequiresCompletenessCheck(Long id, boolean state) { AnomalyFunctionDTO anomalyFunctionSpec = anomalyFunctionSpecDAO.findById(id); if(anomalyFunctionSpec == null) { throw new NullArgumentException("Function spec not found"); } anomalyFunctionSpec.setRequiresCompletenessCheck(state); anomalyFunctionSpecDAO.update(anomalyFunctionSpec); } /** * Returns the weight of the metric at the given window. The calculation of baseline (history) data is specified by * seasonal period (in days) and season count. Seasonal period is the difference of duration from one window to the * other. For instance, to use the data that is one week before current window, set seasonal period to 7. The season * count specify how many seasons of history data to retrieve. If there are more than 1 season, then the baseline is * the average of all seasons. * * Examples of the configuration of baseline: * 1. Week-Over-Week: seasonalPeriodInDays = 7, seasonCount = 1 * 2. Week-Over-4-Weeks-Mean: seasonalPeriodInDays = 7, seasonCount = 4 * 3. Month-Over-Month: seasonalPeriodInDays = 30, seasonCount = 1 * * @param collectionName the collection to which the metric belong * @param metricName the metric name * @param startTimeIso start time of current window, inclusive * @param endTimeIso end time of current window, exclusive * @param seasonalPeriodInDays the difference of duration between the start time of each window * @param seasonCount the number of history windows * * @return the weight of the metric at the given window * @throws Exception */ @POST @Path("/anomaly-weight") public Response computeSeverity(@NotNull @QueryParam("collection") String collectionName, @NotNull @QueryParam("metric") String metricName, @NotNull @QueryParam("start") String startTimeIso, @NotNull @QueryParam("end") String endTimeIso, @QueryParam("period") String seasonalPeriodInDays, @QueryParam("seasonCount") String seasonCount) throws Exception { DateTime startTime = null; DateTime endTime = null; if (StringUtils.isNotBlank(startTimeIso)) { startTime = ISODateTimeFormat.dateTimeParser().parseDateTime(startTimeIso); } if (StringUtils.isNotBlank(endTimeIso)) { endTime = ISODateTimeFormat.dateTimeParser().parseDateTime(endTimeIso); } long currentWindowStart = startTime.getMillis(); long currentWindowEnd = endTime.getMillis(); // Default is using one week data priors current values for calculating weight long seasonalPeriodMillis = TimeUnit.DAYS.toMillis(7); if (StringUtils.isNotBlank(seasonalPeriodInDays)) { seasonalPeriodMillis = TimeUnit.DAYS.toMillis(Integer.parseInt(seasonalPeriodInDays)); } int seasonCountInt = 1; if (StringUtils.isNotBlank(seasonCount)) { seasonCountInt = Integer.parseInt(seasonCount); } ThirdEyeClient thirdEyeClient = CACHE_REGISTRY_INSTANCE.getQueryCache().getClient(); SeverityComputationUtil util = new SeverityComputationUtil(thirdEyeClient, collectionName, metricName); Map<String, Object> severity = util.computeSeverity(currentWindowStart, currentWindowEnd, seasonalPeriodMillis, seasonCountInt); return Response.ok(severity.toString(), MediaType.TEXT_PLAIN_TYPE).build(); } /** * Breaks down the given range into consecutive monitoring windows as per function definition * Regenerates anomalies for each window separately * * As the anomaly result regeneration is a heavy job, we move the function from Dashboard to worker * @param id anomaly function id * @param startTimeIso The start time of the monitoring window (in ISO Format), ex: 2016-5-23T00:00:00Z * @param endTimeIso The start time of the monitoring window (in ISO Format) * @param isForceBackfill false to resume backfill from the latest left off * @return HTTP response of this request * @throws Exception */ @POST @Path("/{id}/generateAnomaliesInRange") public Response generateAnomaliesInRange(@PathParam("id") String id, @QueryParam("start") String startTimeIso, @QueryParam("end") String endTimeIso, @QueryParam("force") @DefaultValue("false") String isForceBackfill) throws Exception { long functionId = Long.valueOf(id); boolean forceBackfill = Boolean.valueOf(isForceBackfill); AnomalyFunctionDTO anomalyFunction = anomalyFunctionDAO.findById(functionId); if (anomalyFunction == null) { return Response.noContent().build(); } // Check if the timestamps are available DateTime startTime = null; DateTime endTime = null; if (startTimeIso == null || startTimeIso.isEmpty()) { throw new IllegalArgumentException(String.format("[functionId %s] Monitoring start time is not found", id)); } if (endTimeIso == null || endTimeIso.isEmpty()) { throw new IllegalArgumentException(String.format("[functionId %s] Monitoring end time is not found", id)); } startTime = ISODateTimeFormat.dateTimeParser().parseDateTime(startTimeIso); endTime = ISODateTimeFormat.dateTimeParser().parseDateTime(endTimeIso); if(startTime.isAfter(endTime)){ throw new IllegalArgumentException(String.format( "[functionId %s] Monitoring start time is after monitoring end time", id)); } if(endTime.isAfterNow()){ throw new IllegalArgumentException(String.format( "[functionId %s] Monitor end time {} should not be in the future", id, endTime.toString())); } // Check if the merged anomaly results have been cleaned up before regeneration List<MergedAnomalyResultDTO> mergedResults = mergedAnomalyResultDAO.findByStartTimeInRangeAndFunctionId(startTime.getMillis(), endTime.getMillis(), functionId); if (CollectionUtils.isNotEmpty(mergedResults) && !forceBackfill) { throw new IllegalArgumentException(String.format( "[functionId %s] Merged anomaly results should be cleaned up before regeneration", id)); } // Check if the raw anomaly results have been cleaned up before regeneration List<RawAnomalyResultDTO> rawResults = rawAnomalyResultDAO.findAllByTimeAndFunctionId(startTime.getMillis(), endTime.getMillis(), functionId); if(CollectionUtils.isNotEmpty(rawResults) && !forceBackfill){ throw new IllegalArgumentException(String.format( "[functionId {}] Raw anomaly results should be cleaned up before regeneration", id)); } // Check if the anomaly function is active if (!anomalyFunction.getIsActive()) { throw new IllegalArgumentException(String.format("Skipping deactivated function %s", id)); } String response = null; DateTime innerStartTime = startTime; DateTime innerEndTime = endTime; new Thread(new Runnable() { @Override public void run() { detectionJobScheduler.runBackfill(functionId, innerStartTime, innerEndTime, forceBackfill); } }).start(); return Response.ok().build(); } /** * * @param id anomaly function id * @param startTime start time of anomalies to tune alert filter * @param endTime end time of anomalies to tune alert filter * @param autoTuneType the type of auto tune to invoke (default is "AUTOTUNE") * @return HTTP response of request: string of alert filter */ @POST @Path("/autotune/filter/{functionId}") public Response tuneAlertFilter(@PathParam("functionId") long id, @QueryParam("startTime") long startTime, @QueryParam("endTime") long endTime, @QueryParam("autoTuneType") String autoTuneType) { // get anomalies by function id, start time and end time AnomalyFunctionDTO anomalyFunctionSpec = DAO_REGISTRY.getAnomalyFunctionDAO().findById(id); AnomalyFunctionManager anomalyFunctionDAO = DAO_REGISTRY.getAnomalyFunctionDAO(); MergedAnomalyResultManager anomalyMergedResultDAO = DAO_REGISTRY.getMergedAnomalyResultDAO(); List<MergedAnomalyResultDTO> anomalyResultDTOS = anomalyMergedResultDAO.findByStartTimeInRangeAndFunctionId(startTime, endTime, id); // create alert filter and evaluator AlertFilter alertFilter = alertFilterFactory.fromSpec(anomalyFunctionSpec.getAlertFilter()); AlertFilterEvaluationUtil evaluator = new AlertFilterEvaluationUtil(alertFilter); // create alert filter auto tune AlertFilterAutoTune alertFilterAutotune = alertFilterAutotuneFactory.fromSpec(autoTuneType); LOG.info("initiated alertFilterAutoTune of Type {}", alertFilterAutotune.getClass().toString()); try { //evaluate current alert filter (calculate current precision and recall) evaluator.updatePrecisionAndRecall(anomalyResultDTOS); LOG.info("AlertFilter of Type {}, has been evaluated with precision: {}, recall: {}", alertFilter.getClass().toString(), evaluator.getPrecision(), evaluator.getRecall()); // get tuned alert filter Map<String,String> tunedAlertFilter = alertFilterAutotune.tuneAlertFilter(anomalyResultDTOS, evaluator.getPrecision(), evaluator.getRecall()); LOG.info("tuned AlertFilter"); // if alert filter auto tune has updated alert filter, over write alert filter to anomaly function spec // otherwise do nothing and return alert filter if (alertFilterAutotune.isUpdated()){ anomalyFunctionSpec.setAlertFilter(tunedAlertFilter); anomalyFunctionDAO.update(anomalyFunctionSpec); LOG.info("Model has been updated"); } else { LOG.info("Model hasn't been updated because tuned model cannot beat original model"); } } catch (Exception e) { LOG.warn("AutoTune throws exception due to: {}", e.getMessage()); } return Response.ok(alertFilterAutotune.isUpdated()).build(); } /** * The endpoint to evaluate alert filter * @param id: function ID * @param startTime: startTime of merged anomaly * @param endTime: endTime of merged anomaly * @return feedback summary, precision and recall as json object * @throws Exception when data has no positive label or model has no positive prediction */ @POST @Path("/eval/filter/{functionId}") public Response evaluateAlertFilterByFunctionId(@PathParam("functionId") long id, @QueryParam("startTime") long startTime, @QueryParam("endTime") long endTime) { // get anomalies by function id, start time and end time AnomalyFunctionDTO anomalyFunctionSpec = DAO_REGISTRY.getAnomalyFunctionDAO().findById(id); MergedAnomalyResultManager anomalyMergedResultDAO = DAO_REGISTRY.getMergedAnomalyResultDAO(); List<MergedAnomalyResultDTO> anomalyResultDTOS = anomalyMergedResultDAO.findByStartTimeInRangeAndFunctionId(startTime, endTime, id); // create alert filter and evaluator AlertFilter alertFilter = alertFilterFactory.fromSpec(anomalyFunctionSpec.getAlertFilter()); AlertFilterEvaluationUtil evaluator = new AlertFilterEvaluationUtil(alertFilter); try{ //evaluate current alert filter (calculate current precision and recall) evaluator.updatePrecisionAndRecall(anomalyResultDTOS); LOG.info("AlertFilter of Type {}, has been evaluated with precision: {}, recall:{}", alertFilter.getClass().toString(), evaluator.getPrecision(), evaluator.getRecall()); } catch (Exception e) { LOG.warn("Updating precision and recall failed because: {}", e.getMessage()); } // get anomaly summary from merged anomaly results evaluator.updateFeedbackSummary(anomalyResultDTOS); return Response.ok(evaluator.toProperties().toString()).build(); } }
package tlc2.value.impl; import java.io.EOFException; import java.io.IOException; import java.util.Arrays; import java.util.Map; import tla2sany.semantic.OpDeclNode; import tlc2.output.EC; import tlc2.output.MP; import tlc2.tool.FingerprintException; import tlc2.tool.TLCState; import tlc2.tool.coverage.CostModel; import tlc2.util.FP64; import tlc2.value.IMVPerm; import tlc2.value.IValue; import tlc2.value.IValueInputStream; import tlc2.value.IValueOutputStream; import tlc2.value.Values; import util.Assert; import util.TLAConstants; import util.UniqueString; public class RecordValue extends Value implements Applicable { public final UniqueString[] names; // the field names public final Value[] values; // the field values private boolean isNorm; public static final RecordValue EmptyRcd = new RecordValue(new UniqueString[0], new Value[0], true); /* Constructor */ public RecordValue(UniqueString[] names, Value[] values, boolean isNorm) { this.names = names; this.values = values; this.isNorm = isNorm; } public RecordValue(UniqueString[] names, Value[] values, boolean isNorm, CostModel cm) { this(names, values, isNorm); this.cm = cm; } public RecordValue(UniqueString name, Value v, boolean isNorm) { this(new UniqueString[] {name}, new Value[] {v}, isNorm); } public RecordValue(UniqueString name, Value v) { this(new UniqueString[] {name}, new Value[] {v}, false); } public RecordValue(final TLCState state) { final OpDeclNode[] vars = state.getVars(); this.names = new UniqueString[vars.length]; this.values = new Value[vars.length]; for (int i = 0; i < vars.length; i++) { this.names[i] = vars[i].getName(); this.values[i] = (Value) state.lookup(this.names[i]); } this.isNorm = false; } @Override public final byte getKind() { return RECORDVALUE; } @Override public final int compareTo(Object obj) { try { RecordValue rcd = obj instanceof Value ? (RecordValue) ((Value)obj).toRcd() : null; if (rcd == null) { if (obj instanceof ModelValue) return 1; Assert.fail("Attempted to compare record:\n" + Values.ppr(this.toString()) + "\nwith non-record\n" + Values.ppr(obj.toString())); } this.normalize(); rcd.normalize(); int len = this.names.length; int cmp = len - rcd.names.length; if (cmp == 0) { for (int i = 0; i < len; i++) { cmp = this.names[i].compareTo(rcd.names[i]); if (cmp != 0) break; cmp = this.values[i].compareTo(rcd.values[i]); if (cmp != 0) break; } } return cmp; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } public final boolean equals(Object obj) { try { RecordValue rcd = obj instanceof Value ? (RecordValue) ((Value)obj).toRcd() : null; if (rcd == null) { if (obj instanceof ModelValue) return ((ModelValue) obj).modelValueEquals(this) ; Assert.fail("Attempted to check equality of record:\n" + Values.ppr(this.toString()) + "\nwith non-record\n" + Values.ppr(obj.toString())); } this.normalize(); rcd.normalize(); int len = this.names.length; if (len != rcd.names.length) return false; for (int i = 0; i < len; i++) { if ((!(this.names[i].equals(rcd.names[i]))) || (!(this.values[i].equals(rcd.values[i])))) return false; } return true; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final boolean member(Value elem) { try { Assert.fail("Attempted to check if element:\n" + Values.ppr(elem.toString()) + "\nis in the record:\n" + Values.ppr(this.toString())); return false; // make compiler happy } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final boolean isFinite() { return true; } @Override public final Value takeExcept(ValueExcept ex) { try { if (ex.idx < ex.path.length) { int rlen = this.names.length; Value[] newValues = new Value[rlen]; Value arcVal = ex.path[ex.idx]; if (arcVal instanceof StringValue) { UniqueString arc = ((StringValue)arcVal).val; for (int i = 0; i < rlen; i++) { if (this.names[i].equals(arc)) { ex.idx++; newValues[i] = this.values[i].takeExcept(ex); } else { newValues[i] = this.values[i]; } } UniqueString[] newNames = this.names; if (!this.isNorm) { newNames = new UniqueString[rlen]; for (int i = 0; i < rlen; i++) { newNames[i] = this.names[i]; } } return new RecordValue(newNames, newValues, this.isNorm); } else { MP.printWarning(EC.TLC_WRONG_RECORD_FIELD_NAME, new String[]{Values.ppr(arcVal.toString())}); } } return ex.value; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final Value takeExcept(ValueExcept[] exs) { try { Value res = this; for (int i = 0; i < exs.length; i++) { res = res.takeExcept(exs[i]); } return res; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final Value toRcd() { return this; } @Override public final Value toTuple() { return size() == 0 ? TupleValue.EmptyTuple : super.toTuple(); } @Override public final Value toFcnRcd() { this.normalize(); Value[] dom = new Value[this.names.length]; for (int i = 0; i < this.names.length; i++) { dom[i] = new StringValue(this.names[i], cm); } if (coverage) {cm.incSecondary(dom.length);} return new FcnRcdValue(dom, this.values, this.isNormalized(), cm); } @Override public final int size() { try { return this.names.length; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final Value apply(Value arg, int control) { try { if (!(arg instanceof StringValue)) { Assert.fail("Attempted to apply record to a non-string value " + Values.ppr(arg.toString()) + "."); } UniqueString name = ((StringValue)arg).getVal(); int rlen = this.names.length; for (int i = 0; i < rlen; i++) { if (name.equals(this.names[i])) { return this.values[i]; } } Assert.fail("Attempted to apply the record\n" + Values.ppr(this.toString()) + "\nto nonexistent record field " + name + "."); return null; // make compiler happy } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final Value apply(Value[] args, int control) { try { if (args.length != 1) { Assert.fail("Attempted to apply record to more than one arguments."); } return this.apply(args[0], control); } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } /* This method returns the named component of the record. */ @Override public final Value select(Value arg) { try { if (!(arg instanceof StringValue)) { Assert.fail("Attempted to apply record to a non-string argument " + Values.ppr(arg.toString()) + "."); } UniqueString name = ((StringValue)arg).getVal(); int rlen = this.names.length; for (int i = 0; i < rlen; i++) { if (name.equals(this.names[i])) { return this.values[i]; } } return null; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final Value getDomain() { try { Value[] dElems = new Value[this.names.length]; for (int i = 0; i < this.names.length; i++) { dElems[i] = new StringValue(this.names[i]); } return new SetEnumValue(dElems, this.isNormalized()); } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } public final boolean assign(UniqueString name, Value val) { try { for (int i = 0; i < this.names.length; i++) { if (name.equals(this.names[i])) { if (this.values[i] == UndefValue.ValUndef || this.values[i].equals(val)) { this.values[i] = val; return true; } return false; } } Assert.fail("Attempted to assign to nonexistent record field " + name + "."); return false; // make compiler happy } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final boolean isNormalized() { return this.isNorm; } @Override public final Value normalize() { try { if (!this.isNorm) { int len = this.names.length; for (int i = 1; i < len; i++) { int cmp = this.names[0].compareTo(this.names[i]); if (cmp == 0) { Assert.fail("Field name " + this.names[i] + " occurs multiple times in record."); } else if (cmp > 0) { UniqueString ts = this.names[0]; this.names[0] = this.names[i]; this.names[i] = ts; Value tv = this.values[0]; this.values[0] = this.values[i]; this.values[i] = tv; } } for (int i = 2; i < len; i++) { int j = i; UniqueString st = this.names[i]; Value val = this.values[i]; int cmp; while ((cmp = st.compareTo(this.names[j-1])) < 0) { this.names[j] = this.names[j-1]; this.values[j] = this.values[j-1]; j } if (cmp == 0) { Assert.fail("Field name " + this.names[i] + " occurs multiple times in record."); } this.names[j] = st; this.values[j] = val; } this.isNorm = true; } return this; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final void deepNormalize() { try { for (int i = 0; i < values.length; i++) { values[i].deepNormalize(); } normalize(); } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final boolean isDefined() { try { boolean defined = true; for (int i = 0; i < this.values.length; i++) { defined = defined && this.values[i].isDefined(); } return defined; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final IValue deepCopy() { try { Value[] vals = new Value[this.values.length]; for (int i = 0; i < this.values.length; i++) { vals[i] = (Value) this.values[i].deepCopy(); } // Following code modified 16 June 2015 by adding Arrays.copyOf to fix // the following bug that seems to have manifested itself only in TLC.Print and // TLC.PrintT: Calling normalize on the original modifies the // order of the names array in the deepCopy (and vice-versa) without doing the // corresponding modification on the values array. Thus, the names are // copied too to prevent any modification/normalization done to the // original to appear in the deepCopy. return new RecordValue(Arrays.copyOf(this.names, this.names.length), vals, this.isNorm); } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final boolean assignable(Value val) { try { boolean canAssign = ((val instanceof RecordValue) && this.names.length == ((RecordValue)val).names.length); if (!canAssign) return false; for (int i = 0; i < this.values.length; i++) { canAssign = (canAssign && this.names[i].equals(((RecordValue)val).names[i]) && this.values[i].assignable(((RecordValue)val).values[i])); } return canAssign; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final void write(final IValueOutputStream vos) throws IOException { final int index = vos.put(this); if (index == -1) { vos.writeByte(RECORDVALUE); final int len = names.length; vos.writeInt((isNormalized()) ? len : -len); for (int i = 0; i < len; i++) { final int index1 = vos.put(names[i]); if (index1 == -1) { vos.writeByte(STRINGVALUE); names[i].write(vos.getOutputStream()); } else { vos.writeByte(DUMMYVALUE); vos.writeNat(index1); } values[i].write(vos); } } else { vos.writeByte(DUMMYVALUE); vos.writeNat(index); } } /* The fingerprint methods. */ @Override public final long fingerPrint(long fp) { try { this.normalize(); int rlen = this.names.length; fp = FP64.Extend(fp, FCNRCDVALUE); fp = FP64.Extend(fp, rlen); for (int i = 0; i < rlen; i++) { String str = this.names[i].toString(); fp = FP64.Extend(fp, STRINGVALUE); fp = FP64.Extend(fp, str.length()); fp = FP64.Extend(fp, str); fp = this.values[i].fingerPrint(fp); } return fp; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } @Override public final IValue permute(IMVPerm perm) { try { this.normalize(); int rlen = this.names.length; Value[] vals = new Value[rlen]; boolean changed = false; for (int i = 0; i < rlen; i++) { vals[i] = (Value) this.values[i].permute(perm); changed = changed || (vals[i] != this.values[i]); } if (changed) { return new RecordValue(this.names, vals, true); } return this; } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } /* The string representation */ @Override public final StringBuffer toString(StringBuffer sb, int offset, boolean swallow) { try { int len = this.names.length; sb.append("["); if (len > 0) { sb.append(this.names[0] + TLAConstants.RECORD_ARROW); sb = this.values[0].toString(sb, offset, swallow); } for (int i = 1; i < len; i++) { sb.append(", "); sb.append(this.names[i] + TLAConstants.RECORD_ARROW); sb = this.values[i].toString(sb, offset, swallow); } return sb.append("]"); } catch (RuntimeException | OutOfMemoryError e) { if (hasSource()) { throw FingerprintException.getNewHead(this, e); } else { throw e; } } } public static IValue createFrom(final IValueInputStream vos) throws EOFException, IOException { final int index = vos.getIndex(); boolean isNorm = true; int len = vos.readInt(); if (len < 0) { len = -len; isNorm = false; } final UniqueString[] names = new UniqueString[len]; final Value[] vals = new Value[len]; for (int i = 0; i < len; i++) { final byte kind1 = vos.readByte(); if (kind1 == DUMMYVALUE) { final int index1 = vos.readNat(); names[i] = vos.getValue(index1); } else { final int index1 = vos.getIndex(); names[i] = UniqueString.read(vos.getInputStream()); vos.assign(names[i], index1); } vals[i] = (Value) vos.read(); } final Value res = new RecordValue(names, vals, isNorm); vos.assign(res, index); return res; } public static IValue createFrom(final IValueInputStream vos, final Map<String, UniqueString> tbl) throws EOFException, IOException { final int index = vos.getIndex(); boolean isNorm = true; int len = vos.readInt(); if (len < 0) { len = -len; isNorm = false; } final UniqueString[] names = new UniqueString[len]; final Value[] vals = new Value[len]; for (int i = 0; i < len; i++) { final byte kind1 = vos.readByte(); if (kind1 == DUMMYVALUE) { final int index1 = vos.readNat(); names[i] = vos.getValue(index1); } else { final int index1 = vos.getIndex(); names[i] = UniqueString.read(vos.getInputStream(), tbl); vos.assign(names[i], index1); } vals[i] = (Value) vos.read(); } final Value res = new RecordValue(names, vals, isNorm); vos.assign(res, index); return res; } }
package org.openoffice.xmerge.converter.xml.sxc.pexcel; import java.awt.Color; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Element; import java.io.IOException; import org.openoffice.xmerge.Document; import org.openoffice.xmerge.ConvertData; import org.openoffice.xmerge.ConvertException; import org.openoffice.xmerge.converter.xml.sxc.Format; import org.openoffice.xmerge.converter.xml.sxc.SxcDocumentSerializer; import org.openoffice.xmerge.converter.xml.sxc.pexcel.records.Workbook; import org.openoffice.xmerge.converter.xml.StyleCatalog; /** * <p>Pocket Excel implementation of <code>SxcDocumentDeserializer</code> * for the {@link * org.openoffice.xmerge.converter.xml.sxc.pexcel.PluginFactoryImpl * PluginFactoryImpl}.</p> * * <p>This converts StarOffice XML format to a set of files in * Pocket Excel PXL format.</p> * * @author Paul Rank * @author Mark Murnane */ public final class SxcDocumentSerializerImpl extends SxcDocumentSerializer { /** * Constructor. * * @param document The <code>Document</code> to convert. */ public SxcDocumentSerializerImpl(Document document) { super(document); } public ConvertData serialize() throws ConvertException, IOException { // Get the server side document name. This value should not // contain a path or the file extension. String docName = sxcDoc.getName(); // TODO - get real values for password when implemnted in XML // Passwords are not currently stored in StarCalc XML format. String password = null; encoder = new PocketExcelEncoder(docName, password); // get dom document org.w3c.dom.Document domDoc = sxcDoc.getContentDOM(); // load the styles loadStyles(sxcDoc); // Traverse to the office:body element. // There should only be one. NodeList list = domDoc.getElementsByTagName(TAG_OFFICE_BODY); int len = list.getLength(); if (len > 0) { Node node = list.item(0); traverseBody(node); } // get settings for this document org.w3c.dom.Document settingsDoc = sxcDoc.getSettingsDOM(); if(settingsDoc!=null) { NodeList settingsList = settingsDoc.getElementsByTagName(TAG_OFFICE_SETTINGS); int slen = settingsList.getLength(); if (slen > 0) { Node settingsNode = settingsList.item(0); traverseSettings(settingsNode); } } // Get the number of sheets in the workbook // This will equal the number of PDBs we need ConvertData cd = new ConvertData(); Workbook wb = ((PocketExcelEncoder) encoder).getWorkbook(); cd.addDocument(wb); return cd; } /** * A cell reference in a StarOffice formula looks like * [.C2] (for cell C2). MiniCalc is expecting cell references * to look like C2. This method strips out the braces and * the period. * * @param formula A StarOffice formula <code>String</code>. * * @return A MiniCalc formula <code>String</code>. */ protected String parseFormula(String formula) { return null; } }
package org.splevo.diffing.emfcompare.similarity; import org.apache.log4j.Logger; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmt.modisco.java.AbstractMethodDeclaration; import org.eclipse.gmt.modisco.java.AbstractTypeDeclaration; import org.eclipse.gmt.modisco.java.Annotation; import org.eclipse.gmt.modisco.java.AnnotationMemberValuePair; import org.eclipse.gmt.modisco.java.AnonymousClassDeclaration; import org.eclipse.gmt.modisco.java.ArrayAccess; import org.eclipse.gmt.modisco.java.ArrayCreation; import org.eclipse.gmt.modisco.java.ArrayInitializer; import org.eclipse.gmt.modisco.java.ArrayLengthAccess; import org.eclipse.gmt.modisco.java.ArrayType; import org.eclipse.gmt.modisco.java.Assignment; import org.eclipse.gmt.modisco.java.Block; import org.eclipse.gmt.modisco.java.BooleanLiteral; import org.eclipse.gmt.modisco.java.CastExpression; import org.eclipse.gmt.modisco.java.CatchClause; import org.eclipse.gmt.modisco.java.CharacterLiteral; import org.eclipse.gmt.modisco.java.ClassInstanceCreation; import org.eclipse.gmt.modisco.java.CompilationUnit; import org.eclipse.gmt.modisco.java.ConditionalExpression; import org.eclipse.gmt.modisco.java.Expression; import org.eclipse.gmt.modisco.java.ExpressionStatement; import org.eclipse.gmt.modisco.java.FieldAccess; import org.eclipse.gmt.modisco.java.FieldDeclaration; import org.eclipse.gmt.modisco.java.ForStatement; import org.eclipse.gmt.modisco.java.IfStatement; import org.eclipse.gmt.modisco.java.ImportDeclaration; import org.eclipse.gmt.modisco.java.InfixExpression; import org.eclipse.gmt.modisco.java.InstanceofExpression; import org.eclipse.gmt.modisco.java.Javadoc; import org.eclipse.gmt.modisco.java.MethodDeclaration; import org.eclipse.gmt.modisco.java.MethodInvocation; import org.eclipse.gmt.modisco.java.Model; import org.eclipse.gmt.modisco.java.Modifier; import org.eclipse.gmt.modisco.java.NamedElement; import org.eclipse.gmt.modisco.java.NullLiteral; import org.eclipse.gmt.modisco.java.NumberLiteral; import org.eclipse.gmt.modisco.java.Package; import org.eclipse.gmt.modisco.java.PackageAccess; import org.eclipse.gmt.modisco.java.ParameterizedType; import org.eclipse.gmt.modisco.java.ParenthesizedExpression; import org.eclipse.gmt.modisco.java.PostfixExpression; import org.eclipse.gmt.modisco.java.PrefixExpression; import org.eclipse.gmt.modisco.java.PrimitiveType; import org.eclipse.gmt.modisco.java.ReturnStatement; import org.eclipse.gmt.modisco.java.SingleVariableAccess; import org.eclipse.gmt.modisco.java.SingleVariableDeclaration; import org.eclipse.gmt.modisco.java.StringLiteral; import org.eclipse.gmt.modisco.java.SuperConstructorInvocation; import org.eclipse.gmt.modisco.java.SuperMethodInvocation; import org.eclipse.gmt.modisco.java.TagElement; import org.eclipse.gmt.modisco.java.ThisExpression; import org.eclipse.gmt.modisco.java.TryStatement; import org.eclipse.gmt.modisco.java.Type; import org.eclipse.gmt.modisco.java.TypeAccess; import org.eclipse.gmt.modisco.java.TypeLiteral; import org.eclipse.gmt.modisco.java.TypeParameter; import org.eclipse.gmt.modisco.java.UnresolvedTypeDeclaration; import org.eclipse.gmt.modisco.java.VariableDeclaration; import org.eclipse.gmt.modisco.java.VariableDeclarationExpression; import org.eclipse.gmt.modisco.java.VariableDeclarationFragment; import org.eclipse.gmt.modisco.java.VariableDeclarationStatement; import org.eclipse.gmt.modisco.java.WildCardType; import org.eclipse.gmt.modisco.java.emf.util.JavaSwitch; import org.splevo.diffing.emfcompare.util.JavaModelUtil; /** * Internal switch class to prove element similarity. * * The similarity case methods do not need to check for null values. It is assumed that the calling * class does a null value check for the elements to compare in advanced, such as done by the * SimilarityChecker class. * * */ public class SimilaritySwitch extends JavaSwitch<Boolean> { /** The logger for this class. */ private Logger logger = Logger.getLogger(SimilaritySwitch.class); /** The object to compare the switched element with. */ private EObject compareElement = null; /** Internal similarity checker to compare container elements etc. */ private SimilarityChecker similarityChecker = new SimilarityChecker(); /** * Constructor requiring the element to compare with. * * @param compareElement * The element to check the similarity with. */ public SimilaritySwitch(EObject compareElement) { this.compareElement = compareElement; } /** * Check expression statement similarity.<br> * Similarity is checked by * <ul> * <li>similarity statements expressions</li> * </ul> * * @param expressionStatement1 * The expression statement to compare with the compare element. * @return True/False if the expression statements are similar or not. */ @Override public Boolean caseExpressionStatement(ExpressionStatement expressionStatement1) { ExpressionStatement expressionStatement2 = (ExpressionStatement) compareElement; Expression expression1 = expressionStatement1.getExpression(); Expression expression2 = expressionStatement2.getExpression(); Boolean expressionSimilarity = similarityChecker.isSimilar(expression1, expression2); if (expressionSimilarity != null && expressionSimilarity == Boolean.FALSE) { return expressionSimilarity; } return Boolean.TRUE; } /** * Check return statement similarity.<br> * Similarity is checked by * <ul> * <li>expressions similarity</li> * </ul> * * @param returnStatement1 * The return statement to compare with the compare element. * @return True/False if the return statements are similar or not. */ @Override public Boolean caseReturnStatement(ReturnStatement returnStatement1) { ReturnStatement returnStatement2 = (ReturnStatement) compareElement; Expression exp1 = returnStatement1.getExpression(); Expression exp2 = returnStatement2.getExpression(); return similarityChecker.isSimilar(exp1, exp2); } /** * Check import declaration similarity.<br> * Similarity is checked by * <ul> * <li>similarity of the imported element.<br> * This is one of: * <ul> * <li>Type similarity</li> * <li>Package similarity</li> * <li>Method similarity</li> * </ul> * </li> * </ul> * * @param importStatement * The import statement to compare with the compare element. * @return True/False if the import statements are similar or not. */ @Override public Boolean caseImportDeclaration(ImportDeclaration importStatement) { NamedElement importedElement1 = importStatement.getImportedElement(); NamedElement importedElement2 = ((ImportDeclaration) compareElement).getImportedElement(); if (importedElement1 instanceof AbstractTypeDeclaration && importedElement2 instanceof AbstractTypeDeclaration) { AbstractTypeDeclaration atd1 = (AbstractTypeDeclaration) importedElement1; AbstractTypeDeclaration atd2 = (AbstractTypeDeclaration) importedElement2; return similarityChecker.isSimilar(atd1, atd2); } if (importedElement1 instanceof Package && importedElement2 instanceof Package) { Package atd1 = (Package) importedElement1; Package atd2 = (Package) importedElement2; return checkPackageSimilarity(atd1, atd2); } if (importedElement1 instanceof MethodDeclaration && importedElement2 instanceof MethodDeclaration) { MethodDeclaration method1 = (MethodDeclaration) importedElement1; MethodDeclaration method2 = (MethodDeclaration) importedElement2; return similarityChecker.isSimilar(method1, method2); } logger.warn("Unhandled import type detected: " + importedElement1); return null; } /** * Check modifier similarity.<br> * Similarity is checked by * <ul> * <li>visibility modifier similarity</li> * <li>inheritance modifier similarity</li> * </ul> * * @param modifier1 * The modifier to compare with the compare element. * @return True/False if the modifiers are similar or not. */ @Override public Boolean caseModifier(Modifier modifier1) { Modifier modifier2 = (Modifier) compareElement; // check visibility modifier if (modifier1.getVisibility() != null) { if (modifier2.getVisibility() == modifier1.getVisibility()) { return Boolean.TRUE; } else { return Boolean.FALSE; } } // check inheritance modifier if (modifier1.getInheritance() != null) { if (modifier2.getInheritance() == modifier1.getInheritance()) { return Boolean.TRUE; } else { return Boolean.FALSE; } } logger.warn("Unknown Modifier type: " + modifier1); return Boolean.FALSE; } /** * Check array type similarity.<br> * Similarity is checked by * <ul> * <li>type of array elements</li> * </ul> * * @param arrayType * The array type to compare with the compare element. * @return True/False if the array types are similar or not. */ @Override public Boolean caseArrayType(ArrayType arrayType) { ArrayType arrayType1 = arrayType; ArrayType arrayType2 = (ArrayType) compareElement; return similarityChecker .isSimilar(arrayType1.getElementType().getType(), arrayType2.getElementType().getType()); } /** * Check wild card type similarity.<br> * Similarity is checked by * <ul> * <li>wild card name</li> * <li>wild card bound similarity</li> * </ul> * * @param wildCardType1 * The array type to compare with the compare element. * @return True/False if the array types are similar or not. */ @Override public Boolean caseWildCardType(WildCardType wildCardType1) { WildCardType wildCardType2 = (WildCardType) compareElement; if (wildCardType1.getName() != null && !wildCardType1.getName().equals(wildCardType2.getName())) { return Boolean.FALSE; } return similarityChecker.isSimilar(wildCardType1.getBound(), wildCardType2.getBound()); } /** * Check variable declaration similarity.<br> * Similarity is checked by * <ul> * <li>variable name</li> * <li>variable container (name space)</li> * </ul> * * @param variableDeclaration1 * The variable declaration to compare with the compare element. * @return True/False if the variable declarations are similar or not. */ @Override public Boolean caseVariableDeclaration(VariableDeclaration variableDeclaration1) { VariableDeclaration variableDeclaration2 = (VariableDeclaration) compareElement; // check the variables name equality if (!variableDeclaration1.getName().equals(variableDeclaration2.getName())) { return Boolean.FALSE; } // check variable declaration container Boolean similarity = similarityChecker.isSimilar(variableDeclaration1.eContainer(), variableDeclaration2.eContainer()); if (similarity != null) { return similarity; } else { return Boolean.TRUE; } } /** * Check abstract method declaration similarity. Similarity is checked by * <ul> * <li>name</li> * <li>parameter list size</li> * <li>parameter types</li> * <li>name</li> * <li>container for * <ul> * <li>AbstractTypeDeclaration</li> * <li>AnonymousClassDeclaration</li> * <li>Model</li> * </ul> * </li> * </ul> * * @param method1 * The abstract method declaration to compare with the compare element. * @return True/False if the abstract method declarations are similar or not. */ @Override public Boolean caseAbstractMethodDeclaration(AbstractMethodDeclaration method1) { AbstractMethodDeclaration method2 = (AbstractMethodDeclaration) compareElement; // if methods have different names they are not similar. if (!method1.getName().equals(method2.getName())) { return false; } if (method1.getParameters().size() != method2.getParameters().size()) { return Boolean.FALSE; } for (int i = 0; i < method1.getParameters().size(); i++) { SingleVariableDeclaration var1 = method1.getParameters().get(i); SingleVariableDeclaration var2 = method2.getParameters().get(i); Type type1 = var1.getType().getType(); Type type2 = var2.getType().getType(); Boolean tS = similarityChecker.isSimilar(type1, type2); if (tS != null && tS == Boolean.FALSE) { return Boolean.FALSE; } } if (method1.getAbstractTypeDeclaration() != null) { AbstractTypeDeclaration type1 = method1.getAbstractTypeDeclaration(); AbstractTypeDeclaration type2 = method2.getAbstractTypeDeclaration(); return similarityChecker.isSimilar(type1, type2); } if (method1.getAnonymousClassDeclarationOwner() != null) { AnonymousClassDeclaration type1 = method1.getAnonymousClassDeclarationOwner(); AnonymousClassDeclaration type2 = method2.getAnonymousClassDeclarationOwner(); Boolean result = checkAnonymousClassDeclarationSimilarity(type1, type2); if (result != null) { return result; } } if (method1.eContainer() instanceof Model) { if (method2.eContainer() instanceof Model) { return Boolean.TRUE; } else { logger.warn("Methods with the same name contained in different containers: " + method2.eContainer().getClass().getSimpleName()); return Boolean.FALSE; } } logger.warn("MethodDeclaration in unknown container: " + method1.getName() + " : " + method1.eContainer().getClass().getSimpleName()); return super.caseAbstractMethodDeclaration(method1); } /** * Check class instance creation similarity.<br> * Similarity is checked by * <ul> * <li>instance type similarity</li> * <li>number of constructor arguments</li> * <li>types of constructor arguments</li> * <li>container of the class instance creation</li> * </ul> * * @param cic1 * The class instance creation to compare with the compare element. * @return True/False if the class instance creations are similar or not. */ @Override public Boolean caseClassInstanceCreation(ClassInstanceCreation cic1) { ClassInstanceCreation cic2 = (ClassInstanceCreation) compareElement; // check the class instance types Boolean typeSimilarity = similarityChecker.isSimilar(cic1.getType().getType(), cic2.getType().getType()); if (typeSimilarity != null && typeSimilarity == Boolean.FALSE) { return Boolean.FALSE; } // check number of type arguments EList<Expression> cic1Args = cic1.getArguments(); EList<Expression> cic2Args = cic2.getArguments(); if (cic1Args.size() != cic2Args.size()) { return Boolean.FALSE; } // check the argument similarity for (int i = 0; i < cic1Args.size(); i++) { Boolean argumentSimilarity = similarityChecker.isSimilar(cic1Args.get(i), cic2Args.get(i)); if (Boolean.FALSE.equals(argumentSimilarity)) { return Boolean.FALSE; } } // container similarity if (cic1.eContainer() instanceof AbstractTypeDeclaration) { AbstractTypeDeclaration type1 = (AbstractTypeDeclaration) cic1.eContainer(); AbstractTypeDeclaration type2 = (AbstractTypeDeclaration) cic2.eContainer(); Boolean containerSimilarity = similarityChecker.isSimilar(type1, type2); if (containerSimilarity != null && containerSimilarity == Boolean.FALSE) { return Boolean.FALSE; } } return Boolean.TRUE; } /** * Check the similarity of two CompilationUnits.<br> * Similarity is checked by * <ul> * <li>Comparing their names</li> * </ul> * * @param compUnit * The compilation unit to compare with the compareElement. * @return True/False whether they are similar or not. */ @Override public Boolean caseCompilationUnit(CompilationUnit compUnit) { CompilationUnit compareCompUnit = (CompilationUnit) compareElement; // The compilation unit name must be the same. if (!compUnit.getName().equals(compareCompUnit.getName())) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check package similarity.<br> * Similarity is checked by * <ul> * <li>full qualifies package path</li> * </ul> * * @param packageElement * The package to compare with the compare element. * @return True/False if the packages are similar or not. */ @Override public Boolean casePackage(Package packageElement) { Package referencePackage = (Package) compareElement; return checkPackageSimilarity(packageElement, referencePackage); } /** * Check package access similarity.<br> * Similarity is checked by * <ul> * <li>accessed package similarity</li> * <li>compilation unit (location) similarity</li> * </ul> * * @param packageAccess1 * The package access to compare with the compare element. * @return True/False if the package accesses are similar or not. */ @Override public Boolean casePackageAccess(PackageAccess packageAccess1) { PackageAccess packageAccess2 = (PackageAccess) compareElement; Boolean packageSimilarity = checkPackageSimilarity(packageAccess2.getPackage(), packageAccess1.getPackage()); if (packageSimilarity != null && packageSimilarity == Boolean.FALSE) { return Boolean.FALSE; } Boolean compUnitSimilarity = similarityChecker.isSimilar(packageAccess1.getOriginalCompilationUnit(), packageAccess2.getOriginalCompilationUnit()); if (compUnitSimilarity != null && packageSimilarity == Boolean.FALSE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check single variable declaration similarity.<br> * Similarity is checked by * <ul> * <li>variable name</li> * <li>variable container (name space)</li> * </ul> * * @param varDeclaration1 * The single variable declaration to compare with the compare element. * @return True/False if the single variable declarations are similar or not. */ @Override public Boolean caseSingleVariableDeclaration(SingleVariableDeclaration varDeclaration1) { SingleVariableDeclaration varDeclaration2 = (SingleVariableDeclaration) compareElement; // Check name similarity if (varDeclaration1.getName() != null && !varDeclaration1.getName().equals(varDeclaration2.getName())) { return Boolean.FALSE; } // check container similarity Boolean containerSimilarity = similarityChecker.isSimilar(varDeclaration1.eContainer(), varDeclaration2.eContainer()); if (containerSimilarity != null && containerSimilarity == Boolean.FALSE) { return Boolean.FALSE; } return Boolean.TRUE; } @Override public Boolean caseVariableDeclarationStatement(VariableDeclarationStatement varDeclStatement1) { VariableDeclarationStatement varDeclStatement2 = (VariableDeclarationStatement) compareElement; // check fragment count if (varDeclStatement1.getFragments().size() != varDeclStatement2.getFragments().size()) { return Boolean.FALSE; } // check container similarity Boolean containerSimilarity = similarityChecker.isSimilar(varDeclStatement1.eContainer(), varDeclStatement2.eContainer()); if (containerSimilarity != null && containerSimilarity == Boolean.FALSE) { return Boolean.FALSE; } // check declared fragments for (int i = 0; i < varDeclStatement1.getFragments().size(); i++) { VariableDeclarationFragment frag1 = varDeclStatement1.getFragments().get(i); VariableDeclarationFragment frag2 = varDeclStatement2.getFragments().get(i); if (frag1.getName() != null && !frag1.getName().equals(frag2.getName())) { return Boolean.FALSE; } else if (frag1.getName() == null && frag2.getName() != null) { return Boolean.FALSE; } } // TODO: Check VariableDeclarationStatement position in container return Boolean.TRUE; } /** * Check if two if statements are similar. * * Similarity is checked by: * <ul> * <li>similarity of the expressions</li> * </ul> * * The then and else statements are not checked as part of the if statement check because this * is only about the container if statement similarity. The contained statements are checked in * a separate step of the compare process if the enclosing if statement matches. * * @param ifStatement1 * The statement to compare with the compare element. * @return True/False whether they are similar or not. */ @Override public Boolean caseIfStatement(IfStatement ifStatement1) { IfStatement ifStatement2 = (IfStatement) compareElement; Expression expression1 = ifStatement1.getExpression(); Expression expression2 = ifStatement2.getExpression(); Boolean expressionSimilarity = similarityChecker.isSimilar(expression1, expression2); if (expressionSimilarity != null && expressionSimilarity == Boolean.FALSE) { return expressionSimilarity; } return Boolean.TRUE; } /** * Check if two for statements are similar. * * Similarity is checked by: * <ul> * <li>number of initializer similarity</li> * <li>number of updater similarity</li> * <li>expression similarity</li> * </ul> * * TODO Add updater and initializer checks * * The body is not checked as part of the for statement check because this is only about the * container for statement similarity. The contained statements are checked in a separate step * of the compare process if the enclosing for statement matches. * * @param forStatement1 * The statement to compare with the compare element. * @return True/False whether they are similar or not. */ @Override public Boolean caseForStatement(ForStatement forStatement1) { ForStatement forStatement2 = (ForStatement) compareElement; if (forStatement1.getInitializers().size() != forStatement2.getInitializers().size()) { return Boolean.FALSE; } if (forStatement1.getUpdaters().size() != forStatement2.getUpdaters().size()) { return Boolean.FALSE; } Boolean expressionSimilarity = similarityChecker.isSimilar(forStatement1.getExpression(), forStatement2.getExpression()); if (expressionSimilarity != null && expressionSimilarity == Boolean.FALSE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check if two if catch clauses are similar. * * Similarity is checked by: * <ul> * <li>similarity of the caught exception type</li> * <li>container similarity</li> * </ul> * * The then and else statements are not checked as part of the if statement check because this * is only about the container if statement similarity. The contained statements are checked in * a separate step of the compare process if the enclosing if statement matches. * * @param cc1 * The catch clause to compare with the compare element. * @return True/False whether they are similar or not. */ @Override public Boolean caseCatchClause(CatchClause cc1) { CatchClause cc2 = (CatchClause) compareElement; SingleVariableDeclaration varDecl1 = cc1.getException(); SingleVariableDeclaration varDecl2 = cc2.getException(); Boolean exceptionTypeSimilarity = similarityChecker.isSimilar(varDecl1.getType().getType(), varDecl2.getType() .getType()); if (exceptionTypeSimilarity != null && exceptionTypeSimilarity == Boolean.FALSE) { return Boolean.FALSE; } Boolean containerSimilarity = similarityChecker.isSimilar(cc1.eContainer(), cc2.eContainer()); if (containerSimilarity != null && containerSimilarity == Boolean.FALSE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check infix expression similarity. Similarity is checked by * <ul> * <li>similarity of the operator</li> * <li>similarity of the left operand</li> * <li>similarity of the right operand</li> * </ul> * * Not supported: Extended Operands. * * @param exp1 * The infix expression to compare with the compare element. * @return True/False if the infix expressions are similar or not. */ @Override public Boolean caseInfixExpression(InfixExpression exp1) { InfixExpression exp2 = (InfixExpression) compareElement; if (exp1.getOperator().compareTo(exp2.getOperator()) != 0) { return Boolean.FALSE; } Boolean leftOpSimilarity = similarityChecker.isSimilar(exp2.getLeftOperand(), exp1.getLeftOperand()); if (leftOpSimilarity != Boolean.TRUE) { return Boolean.FALSE; } Boolean rightOpSimilarity = similarityChecker.isSimilar(exp2.getRightOperand(), exp1.getRightOperand()); if (rightOpSimilarity != Boolean.TRUE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check instance of expression similarity. Similarity is checked by * <ul> * <li>similarity of the left operand</li> * <li>similarity of the right operand</li> * </ul> * * @param exp1 * The instance of expression to compare with the compare element. * @return True/False if the instance of expressions are similar or not. */ @Override public Boolean caseInstanceofExpression(InstanceofExpression exp1) { InstanceofExpression exp2 = (InstanceofExpression) compareElement; Boolean leftOpSimilarity = similarityChecker.isSimilar(exp2.getLeftOperand(), exp1.getLeftOperand()); if (leftOpSimilarity != Boolean.TRUE) { return Boolean.FALSE; } Boolean rightOpSimilarity = similarityChecker.isSimilar(exp2.getRightOperand(), exp1.getRightOperand()); if (rightOpSimilarity != Boolean.TRUE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check assignment expression similarity. Similarity is checked by * <ul> * <li>similarity of the operator</li> * <li>similarity of the left hand side</li> * <li>similarity of the right hand side</li> * </ul> * * @param ass1 * The assignment expression to compare with the compare element. * @return True/False if the assignment expressions are similar or not. */ @Override public Boolean caseAssignment(Assignment ass1) { Assignment ass2 = (Assignment) compareElement; if (ass1.getOperator().compareTo(ass1.getOperator()) != 0) { return Boolean.FALSE; } Boolean leftSimilarity = similarityChecker.isSimilar(ass1.getLeftHandSide(), ass2.getLeftHandSide()); if (leftSimilarity != Boolean.TRUE) { return Boolean.FALSE; } Boolean rightSimilarity = similarityChecker.isSimilar(ass1.getRightHandSide(), ass2.getRightHandSide()); if (rightSimilarity != Boolean.TRUE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check parenthesized expression similarity. * * Similarity is checked by * <ul> * <li>similarity of the inner expression</li> * </ul> * * @param exp1 * The parenthesized expression to compare with the compare element. * @return True/False if the parenthesized expressions are similar or not. */ @Override public Boolean caseParenthesizedExpression(ParenthesizedExpression exp1) { ParenthesizedExpression exp2 = (ParenthesizedExpression) compareElement; return similarityChecker.isSimilar(exp1.getExpression(), exp2.getExpression()); } /** * Check number literal similarity. Similarity is checked by * <ul> * <li>similarity of token value</li> * </ul> * * @param literal1 * The number literal to compare with the compare element. * @return True/False if the number literals are similar or not. */ @Override public Boolean caseNumberLiteral(NumberLiteral literal1) { NumberLiteral literal2 = (NumberLiteral) compareElement; return literal1.getTokenValue().equals(literal2.getTokenValue()); } /** * Check character literal similarity. Similarity is checked by * <ul> * <li>similarity of escaped value</li> * </ul> * * @param literal1 * The character literal to compare with the compare element. * @return True/False if the character literals are similar or not. */ @Override public Boolean caseCharacterLiteral(CharacterLiteral literal1) { CharacterLiteral literal2 = (CharacterLiteral) compareElement; return literal1.getEscapedValue().equals(literal2.getEscapedValue()); } /** * Check string literal similarity. Similarity is checked by * <ul> * <li>similarity of escaped value</li> * </ul> * * @param literal1 * The string literal to compare with the compare element. * @return True/False if the string literals are similar or not. */ @Override public Boolean caseStringLiteral(StringLiteral literal1) { StringLiteral literal2 = (StringLiteral) compareElement; return literal1.getEscapedValue().equals(literal2.getEscapedValue()); } /** * Check type literal similarity. Similarity is checked by * <ul> * <li>similarity of the boolean value</li> * </ul> * * @param literal1 * The type literal to compare with the compare element. * @return True/False if the type literals are similar or not. */ @Override public Boolean caseTypeLiteral(TypeLiteral literal1) { TypeLiteral literal2 = (TypeLiteral) compareElement; Boolean typeSimilarity = similarityChecker.isSimilar(literal1.getType(), literal2.getType()); if (typeSimilarity == null && typeSimilarity == Boolean.FALSE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check boolean literal similarity. Similarity is checked by * <ul> * <li>similarity of the boolean value</li> * </ul> * * @param literal1 * The boolean literal to compare with the compare element. * @return True/False if the boolean literals are similar or not. */ @Override public Boolean caseBooleanLiteral(BooleanLiteral literal1) { BooleanLiteral literal2 = (BooleanLiteral) compareElement; return literal1.isValue() == literal2.isValue(); } /** * Check cast expression similarity. Similarity is checked by * <ul> * <li>similarity of the type to case to</li> * <li>similarity of the expression that is casted</li> * </ul> * * @param exp1 * The cast expression to compare with the compare element. * @return True/False if the cast expressions are similar or not. */ @Override public Boolean caseCastExpression(CastExpression exp1) { CastExpression exp2 = (CastExpression) compareElement; Type type1 = exp1.getType().getType(); Type type2 = exp2.getType().getType(); Boolean typeSimilarity = similarityChecker.isSimilar(type1, type2); if (typeSimilarity) { return typeSimilarity; } return similarityChecker.isSimilar(exp1.getExpression(), exp2.getExpression()); } /** * Check field access similarity. Similarity is checked by * <ul> * <li>field variable name</li> * </ul> * * @param access1 * The field access to compare with the compare element. * @return True/False if the field accesses are similar or not. */ @Override public Boolean caseFieldAccess(FieldAccess access1) { FieldAccess access2 = (FieldAccess) compareElement; SingleVariableAccess var1 = access1.getField(); SingleVariableAccess var2 = access2.getField(); return similarityChecker.isSimilar(var1, var2); } /** * Check single variable access similarity. Similarity is checked by * <ul> * <li>accessed variable declaration</li> * </ul> * * @param varAccess1 * The single variable access to compare with the compare element. * @return True/False if the single variable accesses are similar or not. */ @Override public Boolean caseSingleVariableAccess(SingleVariableAccess varAccess1) { SingleVariableAccess varAccess2 = (SingleVariableAccess) compareElement; VariableDeclaration decl1 = varAccess1.getVariable(); VariableDeclaration decl2 = varAccess2.getVariable(); Boolean varDeclSimilarity = similarityChecker.isSimilar(decl1, decl2); if (varDeclSimilarity != null && varDeclSimilarity == Boolean.FALSE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check type access similarity. * * Similarity is checked by * <ul> * <li>name of the accessed type</li> * </ul> * * @param typeAccess1 * The type access to compare with the compare element. * @return True/False if the type accesses are similar or not. */ @Override public Boolean caseTypeAccess(TypeAccess typeAccess1) { TypeAccess typeAccess2 = (TypeAccess) compareElement; // check the similarity of the accessed type Type type1 = typeAccess1.getType(); Type type2 = typeAccess2.getType(); if (!type1.getClass().equals(type2.getClass())) { return Boolean.FALSE; } if (type1.getName() == null) { if (type2.getName() != null) { return Boolean.FALSE; } } else if (!type1.getName().equals(type2.getName())) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check variable declaration fragment similarity.<br> * Similarity is checked by * <ul> * <li>variable name</li> * <li>declaration container</li> * </ul> * * @param varDeclFrag * The variable declaration fragment to compare with the compare element. * @return True/False if the variable declaration fragments are similar or not. */ @Override public Boolean caseVariableDeclarationFragment(VariableDeclarationFragment varDeclFrag) { VariableDeclarationFragment varDeclFrag2 = (VariableDeclarationFragment) compareElement; // name check if (varDeclFrag.getName() != null && !varDeclFrag.getName().equals(varDeclFrag2.getName())) { return Boolean.FALSE; } // container check Boolean containerSimilarity = similarityChecker.isSimilar(varDeclFrag.getVariablesContainer(), varDeclFrag2.getVariablesContainer()); if (containerSimilarity != null) { return containerSimilarity; } logger.warn("variable declaration fragment container not supported: " + varDeclFrag.getVariablesContainer()); return Boolean.TRUE; } /** * Check variable declaration expression similarity.<br> * Similarity is checked by * <ul> * <li>number of contained variable declaration fragments</li> * <li>declaration container</li> * </ul> * * @param varDeclExp1 * The variable declaration expression to compare with the compare element. * @return True/False if the variable declaration expressions are similar or not. */ @Override public Boolean caseVariableDeclarationExpression(VariableDeclarationExpression varDeclExp1) { VariableDeclarationExpression varDeclExp2 = (VariableDeclarationExpression) compareElement; if (varDeclExp1.getFragments().size() != varDeclExp2.getFragments().size()) { return Boolean.FALSE; } for (int i = 0; i < varDeclExp1.getFragments().size(); i++) { VariableDeclarationFragment varDeclFrag1 = varDeclExp1.getFragments().get(i); VariableDeclarationFragment varDeclFrag2 = varDeclExp2.getFragments().get(i); if (varDeclFrag1.getName() != null && !varDeclFrag1.getName().equals(varDeclFrag2.getName())) { return Boolean.FALSE; } else if (varDeclFrag1.getName() == null && varDeclFrag2.getName() != null) { return Boolean.FALSE; } } return Boolean.TRUE; } /** * Check field declaration similarity.<br> * Similarity is checked by * <ul> * <li>number of fragments</li> * <li>fragment names</li> * <li>declared type</li> * <li>Container (name space)</li> * </ul> * * @param fDecl * The field declaration to compare with the compare element. * @return True/False if the field declaration are similar or not. */ @Override public Boolean caseFieldDeclaration(FieldDeclaration fDecl) { FieldDeclaration fDecl2 = (FieldDeclaration) compareElement; // fragment check if (fDecl.getFragments().size() != fDecl2.getFragments().size()) { return Boolean.FALSE; } for (int i = 0; i < fDecl.getFragments().size(); i++) { VariableDeclarationFragment fragment1 = fDecl.getFragments().get(i); VariableDeclarationFragment fragment2 = fDecl2.getFragments().get(i); if (!fragment1.getName().equals(fragment2.getName())) { return Boolean.FALSE; } } // type check similarity // first check type access availability to prevent null pointer exceptions if (fDecl.getType() != null && fDecl2.getType() != null) { Boolean typeSimilarity = similarityChecker.isSimilar(fDecl.getType().getType(), fDecl2.getType().getType()); if (typeSimilarity != null && typeSimilarity == Boolean.FALSE) { return Boolean.FALSE; } } else if ((fDecl.getType() != null && fDecl2.getType() == null) || (fDecl.getType() == null && fDecl2.getType() != null)) { return Boolean.FALSE; } // container check Boolean containerSimilarity = similarityChecker.isSimilar(fDecl.eContainer(), fDecl2.eContainer()); if (containerSimilarity != null) { return containerSimilarity; } return Boolean.TRUE; } /** * Check abstract type declaration similarity.<br> * Similarity is checked by * <ul> * <li>name</li> * <li>package</li> * <li>Container (in case of inner classes)</li> * </ul> * * @param type1 * The type declaration to compare with the compare element. * @return True/False if the type declarations are similar or not. */ @Override public Boolean caseAbstractTypeDeclaration(AbstractTypeDeclaration type1) { AbstractTypeDeclaration type2 = (AbstractTypeDeclaration) compareElement; // if the types names are different then they do not match if (type1.getName() != null && !type1.getName().equals(type2.getName())) { return Boolean.FALSE; } Package package1 = type1.getPackage(); Package package2 = type2.getPackage(); // if only one containing package is null: FALSE if ((package1 == null && package2 != null) || (package1 != null && package2 == null)) { return Boolean.FALSE; // if none is null check the package names } else if (package1 != null && checkPackageSimilarity(package1, package2)) { return Boolean.TRUE; // if both packages are null check if both types are // inner class of the same enclosing class } else if (package1 == null && type1.eContainer() instanceof AbstractTypeDeclaration && type2.eContainer() instanceof AbstractTypeDeclaration) { AbstractTypeDeclaration enclosingAtd1 = (AbstractTypeDeclaration) type1.eContainer(); AbstractTypeDeclaration enclosingAtd2 = (AbstractTypeDeclaration) type2.eContainer(); return similarityChecker.isSimilar(enclosingAtd1, enclosingAtd2); } return Boolean.FALSE; } /** * Check anonymous class declaration similarity.<br> * Similarity is checked by * <ul> * <li>instance creation similarity</li> * </ul> * * @param aClassDecl1 * The class creation to compare with the compare element. * @return True/False if the anonymous class declarations are similar or not. */ @Override public Boolean caseAnonymousClassDeclaration(AnonymousClassDeclaration aClassDecl1) { AnonymousClassDeclaration aClassDecl2 = (AnonymousClassDeclaration) compareElement; ClassInstanceCreation ci1 = aClassDecl1.getClassInstanceCreation(); ClassInstanceCreation ci2 = aClassDecl2.getClassInstanceCreation(); Boolean creationSimilarity = similarityChecker.isSimilar(ci1, ci2); if (creationSimilarity != null && creationSimilarity == Boolean.FALSE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check annotation similarity.<br> * Similarity is checked by * <ul> * <li>number of values</li> * <li>annotation type</li> * <li>values similarity</li> * </ul> * * @param annotation1 * The annotation to compare with the compare element. * @return True/False if the annotations are similar or not. */ @Override public Boolean caseAnnotation(Annotation annotation1) { Annotation annotation2 = (Annotation) compareElement; if (annotation1.getValues().size() != annotation2.getValues().size()) { return Boolean.FALSE; } Type type1 = annotation1.getType().getType(); Type type2 = annotation2.getType().getType(); Boolean typeSimilarity = similarityChecker.isSimilar(type1, type2); if (typeSimilarity != null && typeSimilarity == Boolean.FALSE) { return Boolean.FALSE; } for (int i = 0; i < annotation1.getValues().size(); i++) { AnnotationMemberValuePair valuePair1 = annotation1.getValues().get(i); AnnotationMemberValuePair valuePair2 = annotation2.getValues().get(i); Boolean valueSimilarity = similarityChecker.isSimilar(valuePair1, valuePair2); if (valueSimilarity != null && valueSimilarity == Boolean.FALSE) { return Boolean.FALSE; } } return Boolean.TRUE; } /** * Check annotation member value pair similarity.<br> * Similarity is checked by * <ul> * <li>member name</li> * <li>member value expression</li> * </ul> * * @param valuePair1 * The annotation member value pair to compare with the compare element. * @return True/False if the annotation member value pairs are similar or not. */ @Override public Boolean caseAnnotationMemberValuePair(AnnotationMemberValuePair valuePair1) { AnnotationMemberValuePair valuePair2 = (AnnotationMemberValuePair) compareElement; if (valuePair1.getName() != null && !valuePair1.getName().equals(valuePair2.getName())) { return Boolean.FALSE; } Boolean valueSimilarity = similarityChecker.isSimilar(valuePair1.getValue(), valuePair2.getValue()); if (valueSimilarity != null && valueSimilarity == Boolean.FALSE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check parameterized type similarity.<br> * * Similarity is checked by * <ul> * <li>name</li> * <li>length of the argument list</li> * <li>pairwise argument type similarity</li> * </ul> * * @param type1 * The parameterized type to compare with the compare element. * @return True/False if the parameterized types are similar or not. */ @Override public Boolean caseParameterizedType(ParameterizedType type1) { ParameterizedType type2 = (ParameterizedType) compareElement; // check that the names are equal if (!type1.getName().equals(type2.getName())) { return Boolean.FALSE; } // check that the type has the same number of arguments if (type1.getTypeArguments().size() != type2.getTypeArguments().size()) { return Boolean.FALSE; } // for each argument of type1, check it's equal to the corresponding // one in the second type. // type arguments must be ordered. for (int i = 0; i < type1.getTypeArguments().size(); i++) { Type accessedType1 = type1.getTypeArguments().get(i).getType(); Type accessedType2 = type2.getTypeArguments().get(i).getType(); if (accessedType1.getName() == null) { if (accessedType2.getName() != null) { return false; } } else if (!accessedType1.getName().equals(accessedType2.getName())) { return false; } } return Boolean.TRUE; } /** * Check primitive type similarity.<br> * * Similarity is checked by * <ul> * <li>name</li> * </ul> * * @param type1 * The parameterized type to compare with the compare element. * @return True/False if the parameterized types are similar or not. */ @Override public Boolean casePrimitiveType(PrimitiveType type1) { PrimitiveType type2 = (PrimitiveType) compareElement; if (type1.getName() != null && !type1.getName().equals(type2.getName())) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check type parameter similarity.<br> * * Type parameters are always considered as similar. They might differ because of their type * restriction (e.g. List<T extends ...>) but this is ignored for now. * * @param param1 * The type parameter to compare with the compare element. * @return True/False if the type parameter are similar or not. */ @Override public Boolean caseTypeParameter(TypeParameter param1) { return Boolean.TRUE; } /** * Check if two array length accesses are similar. * * Similarity is checked by: * <ul> * <li>similarity of the accessed arrays</li> * </ul> * * @param access1 * The array length access to compare with the compare element. * @return True/False whether they are similar or not. */ @Override public Boolean caseArrayLengthAccess(ArrayLengthAccess access1) { ArrayLengthAccess access2 = (ArrayLengthAccess) compareElement; return similarityChecker.isSimilar(access1.getArray(), access2.getArray()); } /** * Check if two array accesses are similar. * * Similarity is checked by: * <ul> * <li>accessed array</li> * <li>accessed index</li> * </ul> * * @param access1 * The statement to compare with the compare element. * @return True/False whether they are similar or not. */ @Override public Boolean caseArrayAccess(ArrayAccess access1) { ArrayAccess access2 = (ArrayAccess) compareElement; Boolean arraySimilarity = similarityChecker.isSimilar(access1.getArray(), access2.getArray()); if (arraySimilarity != null && arraySimilarity == Boolean.FALSE) { return Boolean.FALSE; } Boolean indexSimilarity = similarityChecker.isSimilar(access1.getIndex(), access2.getIndex()); if (indexSimilarity != null && indexSimilarity == Boolean.FALSE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check if two array creation expressions are similar. * * Similarity is checked by: * <ul> * <li>array type</li> * </ul> * * @param ac1 * The array creation expression to compare with the compare element. * @return True/False whether they are similar or not. */ @Override public Boolean caseArrayCreation(ArrayCreation ac1) { ArrayCreation ac2 = (ArrayCreation) compareElement; TypeAccess ta1 = ac1.getType(); TypeAccess ta2 = ac2.getType(); return similarityChecker.isSimilar(ta1, ta2); } /** * Check if two array initializers are similar. * * Similarity is checked by: * <ul> * <li>number of initializing expressions</li> * <li>container similarity</li> * </ul> * * @param initializer1 * The array initializer to compare with the compare element. * @return True/False whether they are similar or not. */ @Override public Boolean caseArrayInitializer(ArrayInitializer initializer1) { ArrayInitializer initializer2 = (ArrayInitializer) compareElement; if (initializer1.getExpressions().size() != initializer2.getExpressions().size()) { return Boolean.FALSE; } Boolean parentSimilarity = similarityChecker.isSimilar(initializer1.eContainer(), compareElement.eContainer()); return parentSimilarity; } /** * Check if two conditional expressions are similar. * * Similarity is checked by: * <ul> * <li>condition expression</li> * <li>then expression</li> * <li>else expression</li> * </ul> * * @param exp1 * The conditional expression to compare with the compare element. * @return True/False whether they are similar or not. */ @Override public Boolean caseConditionalExpression(ConditionalExpression exp1) { ConditionalExpression exp2 = (ConditionalExpression) compareElement; Boolean expSimilarity = similarityChecker.isSimilar(exp1.getExpression(), exp2.getExpression()); if (expSimilarity != null && expSimilarity == Boolean.FALSE) { return Boolean.FALSE; } Boolean expElseSimilarity = similarityChecker.isSimilar(exp1.getElseExpression(), exp2.getElseExpression()); if (expElseSimilarity != null && expElseSimilarity == Boolean.FALSE) { return Boolean.FALSE; } Boolean expThenSimilarity = similarityChecker.isSimilar(exp1.getThenExpression(), exp2.getThenExpression()); if (expThenSimilarity != null && expThenSimilarity == Boolean.FALSE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * This expressions are always assumed to be true. * * Note: The type referenced by "this" might differ. But this is not checked at the moment. * * @param thisExp * The this expression to compare with the compare element. * @return True as a this expression is always assumed to be the same. */ @Override public Boolean caseThisExpression(ThisExpression thisExp) { return Boolean.TRUE; } /** * Check if two prefix expressions are similar. * * Similarity is checked by: * <ul> * <li>the prefix operand</li> * <li>the prefixed expression</li> * </ul> * * @param exp1 * The prefix expression to compare with the compare element. * @return True/False whether they are similar or not. */ @Override public Boolean casePrefixExpression(PrefixExpression exp1) { PrefixExpression exp2 = (PrefixExpression) compareElement; if (exp1.getOperator().compareTo(exp2.getOperator()) != 0) { return Boolean.FALSE; } Expression prefixExp1 = exp1.getOperand(); Expression prefixExp2 = exp1.getOperand(); Boolean operandSimilarity = similarityChecker.isSimilar(prefixExp1, prefixExp2); if (operandSimilarity != null && operandSimilarity == Boolean.FALSE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check if two postfix expressions are similar. * * Similarity is checked by: * <ul> * <li>the postfix operand</li> * <li>the postfixed expression</li> * </ul> * * @param exp1 * The postfix expression to compare with the compare element. * @return True/False whether they are similar or not. */ @Override public Boolean casePostfixExpression(PostfixExpression exp1) { PostfixExpression exp2 = (PostfixExpression) compareElement; if (exp1.getOperator().compareTo(exp2.getOperator()) != 0) { return Boolean.FALSE; } Expression prefixExp1 = exp1.getOperand(); Expression prefixExp2 = exp1.getOperand(); Boolean operandSimilarity = similarityChecker.isSimilar(prefixExp1, prefixExp2); if (operandSimilarity != null && operandSimilarity == Boolean.FALSE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check if two method invocations are similar.<br> * This checks * <ul> * <li>the method name</li> * <li>the method declaring type</li> * <li>the method parameters</li> * <li>the method return type</li> * </ul> * * @param methodInvocation * the method invocation to check * @return the boolean */ @Override public Boolean caseMethodInvocation(MethodInvocation methodInvocation) { MethodInvocation methodInvocation2 = (MethodInvocation) compareElement; // check the methods names AbstractMethodDeclaration method1 = methodInvocation.getMethod(); AbstractMethodDeclaration method2 = methodInvocation2.getMethod(); Boolean methodSimilarity = similarityChecker.isSimilar(method1, method2); if (methodSimilarity != null && methodSimilarity == Boolean.FALSE) { return Boolean.FALSE; } // TODO check the variable access for (int i = 0; i < methodInvocation.getArguments().size(); i++) { Expression methodArgument1 = methodInvocation.getArguments().get(i); Expression methodArgument2 = methodInvocation2.getArguments().get(i); Boolean argumentSimilarity = similarityChecker.isSimilar(methodArgument1, methodArgument2); if (argumentSimilarity != null && argumentSimilarity == Boolean.FALSE) { return Boolean.FALSE; } } Expression exp1 = methodInvocation.getExpression(); Expression exp2 = methodInvocation2.getExpression(); Boolean expSimilarity = similarityChecker.isSimilar(exp1, exp2); if (expSimilarity != null && expSimilarity == Boolean.FALSE) { return Boolean.FALSE; } return Boolean.TRUE; } /** * Check super constructor invocation similarity.<br> * * Similarity is checked by * <ul> * <li>length of the argument list</li> * <li>pairwise argument similarity</li> * </ul> * * @param sci1 * The super constructor invocation to compare with the compare element. * @return True/False if the super constructor invocations are similar or not. */ @Override public Boolean caseSuperConstructorInvocation(SuperConstructorInvocation sci1) { SuperConstructorInvocation sci2 = (SuperConstructorInvocation) compareElement; if (sci1.getArguments().size() != sci2.getArguments().size()) { return Boolean.FALSE; } for (int i = 0; i < sci1.getArguments().size(); i++) { Boolean argSimilarity = similarityChecker.isSimilar(sci1.getArguments().get(i), sci2.getArguments().get(i)); if (argSimilarity != null && argSimilarity == Boolean.FALSE) { return Boolean.FALSE; } } return Boolean.TRUE; } /** * Check super method invocation similarity.<br> * Similarity is checked by * <ul> * <li>invoked method similarity</li> * <li>length of the argument list</li> * <li>pairwise argument similarity</li> * </ul> * * @param smi1 * The super method invocation to compare with the compare element. * @return True/False if the super method invocations are similar or not. */ @Override public Boolean caseSuperMethodInvocation(SuperMethodInvocation smi1) { SuperMethodInvocation smi2 = (SuperMethodInvocation) compareElement; AbstractMethodDeclaration md1 = smi1.getMethod(); AbstractMethodDeclaration md2 = smi2.getMethod(); Boolean methodSimilarity = similarityChecker.isSimilar(md1, md2); if (methodSimilarity != null && methodSimilarity == Boolean.FALSE) { return Boolean.FALSE; } if (smi1.getArguments().size() != smi2.getArguments().size()) { return Boolean.FALSE; } for (int i = 0; i < smi1.getArguments().size(); i++) { Boolean argSimilarity = similarityChecker.isSimilar(smi1.getArguments().get(i), smi2.getArguments().get(i)); if (argSimilarity != null && argSimilarity == Boolean.FALSE) { return Boolean.FALSE; } } return Boolean.TRUE; } /** * Check null literal similarity.<br> * * Null literals are always assumed to be similar. * * @param literal * The null literal to compare with the compare element. * @return True As null always means null. */ @Override public Boolean caseNullLiteral(NullLiteral literal) { return Boolean.TRUE; } /** * Check unresolved type declaration similarity.<br> * Similarity is checked by * <ul> * <li>name</li> * </ul> * * @param type1 * The unresolved type declaration to compare with the compare element. * @return True/False if the unresolved type declarations are similar or not. */ @Override public Boolean caseUnresolvedTypeDeclaration(UnresolvedTypeDeclaration type1) { UnresolvedTypeDeclaration type2 = (UnresolvedTypeDeclaration) compareElement; if (type1.getName().equals(type2.getName())) { return Boolean.TRUE; } // TODO Add package similarity check return Boolean.FALSE; } /** * Check block similarity.<br> * Similarity is checked by * <ul> * <li>container similarity</li> * </ul> * * @param block * The block to compare with the compare element. * @return True/False if the blocks are similar or not. */ @Override public Boolean caseBlock(Block block) { Boolean parentSimilarity = similarityChecker.isSimilar(block.eContainer(), ((Block) compareElement).eContainer()); return parentSimilarity; } /** * Check try statement similarity.<br> * Similarity is checked by * <ul> * <li>container similarity</li> * </ul> * * @param tryStatement * The try statement to compare with the compare element. * @return True/False if the try statements are similar or not. */ @Override public Boolean caseTryStatement(TryStatement tryStatement) { Boolean parentSimilarity = similarityChecker.isSimilar(tryStatement.eContainer(), ((TryStatement) compareElement).eContainer()); return parentSimilarity; } @Override public Boolean caseModel(Model object) { return Boolean.TRUE; } /** * JavaDoc elements are always ignored and true is returned. {@inheritDoc} */ @Override public Boolean caseJavadoc(Javadoc object) { return Boolean.TRUE; } /** * TagElement elements are always ignored and true is returned. {@inheritDoc} */ @Override public Boolean caseTagElement(TagElement object) { return Boolean.TRUE; } /** * The default case for not explicitly handled elements always returns null to identify the open * decision. * * @param object * The object to compare with the compare element. * @return null */ @Override public Boolean defaultCase(EObject object) { logger.warn("Unsupported element type: " + object.getClass()); return null; } /** * Check anonymous type declaration similarity.<br> * Similarity is checked by * <ul> * <li>name</li> * </ul> * * @param type1 * The first anonymous type declaration to compare. * @param type2 * The second anonymous type declaration to compare. * @return True/False if the anonymous type declarations are similar or not. */ private Boolean checkAnonymousClassDeclarationSimilarity(AnonymousClassDeclaration type1, AnonymousClassDeclaration type2) { // if both types null: they are similar if (type1 == null && type2 == null) { return true; } // if only one is null: they are different if ((type1 == null && type2 != null) || (type1 != null && type2 == null)) { return false; } // if the parent class is again an anonymous one: recursively check this one if (type1.eContainer() instanceof AnonymousClassDeclaration) { return checkAnonymousClassDeclarationSimilarity((AnonymousClassDeclaration) type1.eContainer(), (AnonymousClassDeclaration) type2.eContainer()); } // if parent class are regular classes, return their similarity if (type1.eContainer() instanceof AbstractTypeDeclaration) { AbstractTypeDeclaration atd1 = (AbstractTypeDeclaration) type1.eContainer(); AbstractTypeDeclaration atd2 = (AbstractTypeDeclaration) type2.eContainer(); similarityChecker.isSimilar(atd1, atd2); } // if container is a class instance creation if (type1.eContainer() instanceof ClassInstanceCreation) { ClassInstanceCreation cic1 = (ClassInstanceCreation) type1.eContainer(); ClassInstanceCreation cic2 = (ClassInstanceCreation) type2.eContainer(); return similarityChecker.isSimilar(cic1, cic2); } logger.warn("Unknown anonymous class declaration container: [" + type1 + "] contained in [" + type1.eContainer() + "]"); return null; } /** * ICheck two package elements for similarity. * * Check - package name - package path * * @param packageElement * the package element * @param referencePackage * the reference package * @return the check result. */ private Boolean checkPackageSimilarity(Package packageElement, Package referencePackage) { // similar packages are similar by default. if (packageElement == referencePackage) { return true; // packages with same name and same parent packages name are considered as similar. } else if (packageElement != null && referencePackage != null) { String packagePath1 = JavaModelUtil.buildPackagePath(packageElement); String packagePath2 = JavaModelUtil.buildPackagePath(referencePackage); if (packagePath1.equals(packagePath2)) { return Boolean.TRUE; } else { return Boolean.FALSE; } } return false; } }
package com.limpoxe.fairy.core.proxy.systemservice; import android.app.Notification; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.graphics.drawable.Icon; import android.os.Build; import com.limpoxe.fairy.content.PluginDescriptor; import com.limpoxe.fairy.core.PluginIntentResolver; import com.limpoxe.fairy.core.PluginLoader; import com.limpoxe.fairy.core.android.HackNotificationManager; import com.limpoxe.fairy.core.android.HackPendingIntent; import com.limpoxe.fairy.core.android.HackRemoteViews; import com.limpoxe.fairy.core.proxy.MethodDelegate; import com.limpoxe.fairy.core.proxy.MethodProxy; import com.limpoxe.fairy.core.proxy.ProxyUtil; import com.limpoxe.fairy.manager.PluginManagerHelper; import com.limpoxe.fairy.util.FileUtil; import com.limpoxe.fairy.util.LogUtil; import com.limpoxe.fairy.util.RefInvoker; import com.limpoxe.fairy.util.ResourceUtil; import java.io.File; import java.lang.reflect.Method; public class AndroidAppINotificationManager extends MethodProxy { static { sMethods.put("enqueueNotification", new enqueueNotification()); sMethods.put("enqueueNotificationWithTag", new enqueueNotificationWithTag()); sMethods.put("enqueueNotificationWithTagPriority", new enqueueNotificationWithTagPriority()); } public static void installProxy() { LogUtil.d("NotificationManagerProxy"); Object androidAppINotificationStubProxy = HackNotificationManager.getService(); Object androidAppINotificationStubProxyProxy = ProxyUtil.createProxy(androidAppINotificationStubProxy, new AndroidAppINotificationManager()); HackNotificationManager.setService(androidAppINotificationStubProxyProxy); LogUtil.d(""); } public static class enqueueNotification extends MethodDelegate { @Override public Object beforeInvoke(Object target, Method method, Object[] args) { LogUtil.v("beforeInvoke", method.getName()); args[0] = PluginLoader.getApplication().getPackageName(); for(Object obj: args) { if (obj instanceof Notification) { resolveRemoteViews((Notification)obj); break; } } return super.beforeInvoke(target, method, args); } } public static class enqueueNotificationWithTag extends MethodDelegate { @Override public Object beforeInvoke(Object target, Method method, Object[] args) { LogUtil.v("beforeInvoke", method.getName()); args[0] = PluginLoader.getApplication().getPackageName(); for(Object obj: args) { if (obj instanceof Notification) { resolveRemoteViews((Notification)obj); break; } } return super.beforeInvoke(target, method, args); } } public static class enqueueNotificationWithTagPriority extends MethodDelegate { @Override public Object beforeInvoke(Object target, Method method, Object[] args) { LogUtil.v("beforeInvoke", method.getName()); args[0] = PluginLoader.getApplication().getPackageName(); for(Object obj: args) { if (obj instanceof Notification) { resolveRemoteViews((Notification)obj); break; } } return super.beforeInvoke(target, method, args); } } private static void resolveRemoteViews(Notification notification) { String hostPackageName = PluginLoader.getApplication().getPackageName(); if (Build.VERSION.SDK_INT >= 23) { Icon mSmallIcon = (Icon)RefInvoker.getField(notification, Notification.class, "mSmallIcon"); Icon mLargeIcon = (Icon)RefInvoker.getField(notification, Notification.class, "mLargeIcon"); if (mSmallIcon != null) { RefInvoker.setField(mSmallIcon, Icon.class, "mString1", hostPackageName); } if (mLargeIcon != null) { RefInvoker.setField(mLargeIcon, Icon.class, "mString1", hostPackageName); } } if (Build.VERSION.SDK_INT >= 21) { int layoutId = 0; if (notification.tickerView != null) { layoutId = new HackRemoteViews(notification.tickerView).getLayoutId(); } if (layoutId == 0) { if (notification.contentView != null) { layoutId = new HackRemoteViews(notification.contentView).getLayoutId(); } } if (layoutId == 0) { if (notification.bigContentView != null) { layoutId = new HackRemoteViews(notification.bigContentView).getLayoutId(); } } if (layoutId == 0) { if (notification.headsUpContentView != null) { layoutId = new HackRemoteViews(notification.headsUpContentView).getLayoutId(); } } if (layoutId == 0) { return; } if (ResourceUtil.isMainResId(layoutId)) { return; } if (layoutId >> 24 == 0x1f) { return; } ApplicationInfo newInfo = new ApplicationInfo(); String packageName = null; if (notification.tickerView != null) { packageName = notification.tickerView.getPackage(); new HackRemoteViews(notification.tickerView).setApplicationInfo(newInfo); } if (notification.contentView != null) { if (packageName == null) { packageName = notification.contentView.getPackage(); } new HackRemoteViews(notification.contentView).setApplicationInfo(newInfo); } if (notification.bigContentView != null) { if (packageName == null) { packageName = notification.bigContentView.getPackage(); } new HackRemoteViews(notification.bigContentView).setApplicationInfo(newInfo); } if (notification.headsUpContentView != null) { if (packageName == null) { packageName = notification.headsUpContentView.getPackage(); } new HackRemoteViews(notification.headsUpContentView).setApplicationInfo(newInfo); } ApplicationInfo applicationInfo = PluginLoader.getApplication().getApplicationInfo(); newInfo.packageName = applicationInfo.packageName; newInfo.sourceDir = applicationInfo.sourceDir; newInfo.dataDir = applicationInfo.dataDir; if (packageName != null && !packageName.equals(hostPackageName)) { PluginDescriptor pluginDescriptor = PluginManagerHelper.getPluginDescriptorByPluginId(packageName); newInfo.packageName = pluginDescriptor.getPackageName(); //publicSourceDirSystemUI newInfo.publicSourceDir = prepareNotificationResourcePath(pluginDescriptor.getInstalledPath(), PluginLoader.getApplication().getExternalCacheDir().getAbsolutePath() + "/notification_res.apk"); } else if (packageName != null && packageName.equals(hostPackageName)) { //packageNamelayoutidnotifications if (notification.contentIntent != null) {//contentIntent Intent intent = new HackPendingIntent(notification.contentIntent).getIntent(); if (intent != null && intent.getAction() != null && intent.getAction().contains(PluginIntentResolver.CLASS_SEPARATOR)) { String className = intent.getAction().split(PluginIntentResolver.CLASS_SEPARATOR)[0]; PluginDescriptor pluginDescriptor = PluginManagerHelper.getPluginDescriptorByClassName(className); newInfo.packageName = pluginDescriptor.getPackageName(); //publicSourceDirSystemUI newInfo.publicSourceDir = prepareNotificationResourcePath(pluginDescriptor.getInstalledPath(), PluginLoader.getApplication().getExternalCacheDir().getAbsolutePath() + "/notification_res.apk"); } } } } else if (Build.VERSION.SDK_INT >= 11) { if (notification.tickerView != null) { new HackRemoteViews(notification.tickerView).setPackage(hostPackageName); } if (notification.contentView != null) { new HackRemoteViews(notification.contentView).setPackage(hostPackageName); } } } private static String prepareNotificationResourcePath(String pluginInstalledPath, String worldReadablePath) { LogUtil.w(""); File worldReadableFile = new File(worldReadablePath); if (FileUtil.copyFile(pluginInstalledPath, worldReadableFile.getAbsolutePath())) { LogUtil.w("SystemUi", worldReadableFile.getAbsolutePath()); return worldReadableFile.getAbsolutePath(); } else { LogUtil.e("SystemUi"); return pluginInstalledPath; } } }
package devopsdistilled.operp.client.business.sales.controllers.impl; import javax.inject.Inject; import devopsdistilled.operp.client.abstracts.EntityOperation; import devopsdistilled.operp.client.business.sales.controllers.SaleController; import devopsdistilled.operp.client.business.sales.panes.controllers.SalePaneController; import devopsdistilled.operp.server.data.entity.business.Sale; public class SaleControllerImpl implements SaleController { @Inject private SalePaneController salePaneController; @Override public void create() { salePaneController.init(new Sale(), EntityOperation.Create); } @Override public void edit(Sale entity) { // TODO Auto-generated method stub } @Override public void list() { // TODO Auto-generated method stub } @Override public void delete(Sale entity) { // TODO Auto-generated method stub } @Override public void showDetails(Sale entity) { // TODO Auto-generated method stub } }
package hex.tree.drf; import org.junit.*; import static org.junit.Assert.assertEquals; import water.*; import water.fvec.Frame; import water.fvec.RebalanceDataSet; import water.fvec.Vec; import water.util.Log; import java.util.Arrays; public class DRFTest extends TestUtil { @BeforeClass public static void stall() { stall_till_cloudsize(1); } abstract static class PrepData { abstract int prep(Frame fr); } static String[] s(String...arr) { return arr; } static long[] a(long ...arr) { return arr; } static long[][] a(long[] ...arr) { return arr; } @Test public void testClassIris1() throws Throwable { // iris ntree=1 // the DRF should use only subset of rows since it is using oob validation basicDRFTestOOBE_Classification( "./smalldata/iris/iris.csv", "iris.hex", new PrepData() { @Override int prep(Frame fr) { return fr.numCols() - 1; } }, 1, a(a(25, 0, 0), a(0, 17, 1), a(2, 1, 15)), s("Iris-setosa", "Iris-versicolor", "Iris-virginica")); } @Test public void testClassIris5() throws Throwable { // iris ntree=50 basicDRFTestOOBE_Classification( "./smalldata/iris/iris.csv", "iris5.hex", new PrepData() { @Override int prep(Frame fr) { return fr.numCols() - 1; } }, 5, a(a(41, 0, 0), a(1, 39, 2), a(1, 3, 41)), s("Iris-setosa", "Iris-versicolor", "Iris-virginica")); } @Test public void testClassCars1() throws Throwable { // cars ntree=1 basicDRFTestOOBE_Classification( "./smalldata/junit/cars.csv", "cars.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("name").remove(); return fr.find("cylinders"); } }, 1, a(a(0, 0, 0, 0, 0), a(3,64, 0, 2, 0), a(0, 1, 0, 0, 0), a(0, 0, 1,30, 0), a(0, 0, 0, 1,39)), s("3", "4", "5", "6", "8")); } @Test public void testClassCars5() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/junit/cars.csv", "cars5.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("name").remove(); return fr.find("cylinders"); } }, 5, a(a(3, 0, 0, 0, 0), a(2, 177, 1, 4, 0), a(0, 1, 1, 0, 0), a(0, 2, 2, 69, 1), a(0, 0, 0, 3, 87)), s("3", "4", "5", "6", "8")); } @Test public void testConstantCols() throws Throwable { try { basicDRFTestOOBE_Classification( "./smalldata/poker/poker100", "poker.hex", new PrepData() { @Override int prep(Frame fr) { for (int i = 0; i < 7; i++) { fr.remove(3).remove(); } return 3; } }, 1, null, null); Assert.fail(); } catch( IllegalArgumentException iae ) { /*pass*/ } } @Ignore @Test public void testBadData() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/junit/drf_infinities.csv", "infinitys.hex", new PrepData() { @Override int prep(Frame fr) { return fr.find("DateofBirth"); } }, 1, a(a(6, 0), a(9, 1)), s("0", "1")); } //@Test public void testCreditSample1() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/kaggle/creditsample-training.csv.gz", "credit.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("MonthlyIncome").remove(); return fr.find("SeriousDlqin2yrs"); } }, 1, a(a(46294, 202), a( 3187, 107)), s("0", "1")); } @Test public void testCreditProstate1() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/logreg/prostate.csv", "prostate.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("ID").remove(); return fr.find("CAPSULE"); } }, 1, a(a(0, 81), a(0, 53)), s("0", "1")); } @Test public void testCreditProstateRegression1() throws Throwable { basicDRFTestOOBE_Regression( "./smalldata/logreg/prostate.csv", "prostateRegression.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("ID").remove(); return fr.find("AGE"); } }, 1, 84.83960821204235 ); } @Test public void testCreditProstateRegression5() throws Throwable { basicDRFTestOOBE_Regression( "./smalldata/logreg/prostate.csv", "prostateRegression5.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("ID").remove(); return fr.find("AGE"); } }, 5, 62.34506879389341 ); } @Test public void testCreditProstateRegression50() throws Throwable { basicDRFTestOOBE_Regression( "./smalldata/logreg/prostate.csv", "prostateRegression50.hex", new PrepData() { @Override int prep(Frame fr) { fr.remove("ID").remove(); return fr.find("AGE"); } }, 50, 48.16452593965962 ); } @Ignore //HEXDEV-294 @Test public void testCzechboard() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/gbm_test/czechboard_300x300.csv", "czechboard_300x300.hex", new PrepData() { @Override int prep(Frame fr) { fr.vecs()[1] = fr.vecs()[1].toEnum(); return fr.find("C3"); } }, 50, a(a(45000, 0), a(0, 45000)), s("0", "1")); } @Test public void testAlphabet() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/gbm_test/alphabet_cattest.csv", "alphabetClassification.hex", new PrepData() { @Override int prep(Frame fr) { return fr.find("y"); } }, 1, a(a(664, 0), a(0, 702)), s("0", "1")); } @Test public void testAlphabetRegression() throws Throwable { basicDRFTestOOBE_Regression( "./smalldata/gbm_test/alphabet_cattest.csv", "alphabetRegression.hex", new PrepData() { @Override int prep(Frame fr) { return fr.find("y"); } }, 1, 0.0); } @Ignore //1-vs-5 node discrepancy (parsing into different number of chunks?) @Test public void testAirlines() throws Throwable { basicDRFTestOOBE_Classification( "./smalldata/airlines/allyears2k_headers.zip", "airlines.hex", new PrepData() { @Override int prep(Frame fr) { for (String s : new String[]{ "DepTime", "ArrTime", "ActualElapsedTime", "AirTime", "ArrDelay", "DepDelay", "Cancelled", "CancellationCode", "CarrierDelay", "WeatherDelay", "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed" }) { fr.remove(s).remove(); } return fr.find("IsDepDelayed"); } }, 7, a(a(7958, 11707), //1-node a(2709, 19024)), // a(a(7841, 11822), //5-node // a(2666, 19053)), s("NO", "YES")); } // Put response as the last vector in the frame and return possible frames to clean up later // Also fill DRF. static Vec unifyFrame(DRFModel.DRFParameters drf, Frame fr, PrepData prep, boolean classification) { int idx = prep.prep(fr); if( idx < 0 ) { idx = ~idx; } String rname = fr._names[idx]; drf._response_column = fr.names()[idx]; Vec resp = fr.vecs()[idx]; Vec ret = null; if (classification) { ret = fr.remove(idx); fr.add(rname,resp.toEnum()); } else { fr.remove(idx); fr.add(rname,resp); } return ret; } public void basicDRFTestOOBE_Classification(String fnametrain, String hexnametrain, PrepData prep, int ntree, long[][] expCM, String[] expRespDom) throws Throwable { basicDRF(fnametrain, hexnametrain, null, prep, ntree, expCM, expRespDom, -1, 10/*max_depth*/, 20/*nbins*/, true); } public void basicDRFTestOOBE_Regression(String fnametrain, String hexnametrain, PrepData prep, int ntree, double expMSE) throws Throwable { basicDRF(fnametrain, hexnametrain, null, prep, ntree, null, null, expMSE, 10/*max_depth*/, 20/*nbins*/, false); } public void basicDRF(String fnametrain, String hexnametrain, String fnametest, PrepData prep, int ntree, long[][] expCM, String[] expRespDom, double expMSE, int max_depth, int nbins, boolean classification) throws Throwable { Scope.enter(); DRFModel.DRFParameters drf = new DRFModel.DRFParameters(); Frame frTest = null, pred = null; Frame frTrain = null; Frame test = null, res = null; DRFModel model = null; try { frTrain = parse_test_file(fnametrain); Vec removeme = unifyFrame(drf, frTrain, prep, classification); if (removeme != null) Scope.track(removeme._key); DKV.put(frTrain._key, frTrain); // Configure DRF drf._train = frTrain._key; drf._response_column = ((Frame)DKV.getGet(drf._train)).lastVecName(); drf._ntrees = ntree; drf._max_depth = max_depth; drf._min_rows = 1; // = nodesize drf._nbins = nbins; drf._mtries = -1; drf._sample_rate = 0.66667f; // Simulated sampling with replacement drf._seed = (1L<<32)|2; drf._model_id = Key.make("DRF_model_4_" + hexnametrain); // Invoke DRF and block till the end DRF job = null; try { job = new DRF(drf); // Get the model model = job.trainModel().get(); Log.info(model._output); } finally { if (job != null) job.remove(); } Assert.assertTrue(job._state == water.Job.JobState.DONE); //HEX-1817 hex.ModelMetrics mm; if (fnametest != null) { frTest = parse_test_file(fnametest); pred = model.score(frTest); mm = hex.ModelMetrics.getFromDKV(model, frTest); // Check test set CM } else { mm = hex.ModelMetrics.getFromDKV(model, frTrain); } Assert.assertEquals("Number of trees differs!", ntree, model._output._ntrees); test = parse_test_file(fnametrain); res = model.score(test); if (classification) { Assert.assertTrue("Expected: " + Arrays.deepToString(expCM) + ", Got: " + Arrays.deepToString(mm.cm()._cm), Arrays.deepEquals(mm.cm()._cm, expCM)); String[] cmDom = model._output._domains[model._output._domains.length - 1]; Assert.assertArrayEquals("CM domain differs!", expRespDom, cmDom); Log.info("\nOOB Training CM:\n" + mm.cm().toASCII()); Log.info("\nTraining CM:\n" + hex.ModelMetrics.getFromDKV(model, test).cm().toASCII()); } else { Assert.assertTrue("Expected: " + expMSE + ", Got: " + mm.mse(), expMSE == mm.mse()); Log.info("\nOOB Training MSE: " + mm.mse()); Log.info("\nTraining MSE: " + hex.ModelMetrics.getFromDKV(model, test).mse()); } hex.ModelMetrics.getFromDKV(model, test); // Build a POJO, validate same results Assert.assertTrue(model.testJavaScoring(test,res,1e-15)); } finally { if (frTrain!=null) frTrain.remove(); if (frTest!=null) frTest.remove(); if( model != null ) model.delete(); // Remove the model if( pred != null ) pred.delete(); if( test != null ) test.delete(); if( res != null ) res.delete(); Scope.exit(); } } // HEXDEV-194 Check reproducibility for the same # of chunks (i.e., same # of nodes) and same parameters @Test public void testReproducibility() { Frame tfr=null; final int N = 5; double[] mses = new double[N]; Scope.enter(); try { // Load data, hack frames tfr = parse_test_file("smalldata/covtype/covtype.20k.data"); // rebalance to 256 chunks Key dest = Key.make("df.rebalanced.hex"); RebalanceDataSet rb = new RebalanceDataSet(tfr, dest, 256); H2O.submitTask(rb); rb.join(); tfr.delete(); tfr = DKV.get(dest).get(); // Scope.track(tfr.replace(54, tfr.vecs()[54].toEnum())._key); // DKV.put(tfr); for (int i=0; i<N; ++i) { DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "C55"; parms._nbins = 1000; parms._ntrees = 1; parms._max_depth = 8; parms._mtries = -1; parms._min_rows = 10; parms._seed = 1234; // Build a first model; all remaining models should be equal DRF job = new DRF(parms); DRFModel drf = job.trainModel().get(); assertEquals(drf._output._ntrees, parms._ntrees); mses[i] = drf._output._mse_train[drf._output._mse_train.length-1]; job.remove(); drf.delete(); } } finally{ if (tfr != null) tfr.remove(); } Scope.exit(); for (int i=0; i<mses.length; ++i) { Log.info("trial: " + i + " -> MSE: " + mses[i]); } for(double mse : mses) assertEquals(mse, mses[0], 1e-15); } // PUBDEV-557 Test dependency on # nodes (for small number of bins, but fixed number of chunks) @Test public void testReprodubilityAirline() { Frame tfr=null; final int N = 1; double[] mses = new double[N]; Scope.enter(); try { // Load data, hack frames tfr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip"); // rebalance to fixed number of chunks Key dest = Key.make("df.rebalanced.hex"); RebalanceDataSet rb = new RebalanceDataSet(tfr, dest, 256); H2O.submitTask(rb); rb.join(); tfr.delete(); tfr = DKV.get(dest).get(); // Scope.track(tfr.replace(54, tfr.vecs()[54].toEnum())._key); // DKV.put(tfr); for (String s : new String[]{ "DepTime", "ArrTime", "ActualElapsedTime", "AirTime", "ArrDelay", "DepDelay", "Cancelled", "CancellationCode", "CarrierDelay", "WeatherDelay", "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed" }) { tfr.remove(s).remove(); } DKV.put(tfr); for (int i=0; i<N; ++i) { DRFModel.DRFParameters parms = new DRFModel.DRFParameters(); parms._train = tfr._key; parms._response_column = "IsDepDelayed"; parms._nbins = 10; parms._ntrees = 7; parms._max_depth = 10; parms._mtries = -1; parms._min_rows = 1; parms._sample_rate = 0.66667f; // Simulated sampling with replacement parms._balance_classes = true; parms._seed = (1L<<32)|2; // Build a first model; all remaining models should be equal DRF job = new DRF(parms); DRFModel drf = job.trainModel().get(); assertEquals(drf._output._ntrees, parms._ntrees); mses[i] = drf._output._mse_train[drf._output._mse_train.length-1]; job.remove(); drf.delete(); } } finally{ if (tfr != null) tfr.remove(); } Scope.exit(); for (int i=0; i<mses.length; ++i) { Log.info("trial: " + i + " -> MSE: " + mses[i]); } for (int i=0; i<mses.length; ++i) { assertEquals(0.20462305452536414, mses[i], 1e-4); //check for the same result on 1 nodes and 5 nodes } } }
package water.jdbc; import water.*; import water.fvec.*; import water.parser.BufferedString; import water.parser.ParseDataset; import water.util.Log; import java.math.BigDecimal; import java.sql.*; import java.util.concurrent.ArrayBlockingQueue; import static water.fvec.Vec.makeCon; public class SQLManager { private final static String TEMP_TABLE_NAME = "table_for_h2o_import"; //upper bound on number of connections to database private final static int MAX_CONNECTIONS = 100; private static final String NETEZZA_DB_TYPE = "netezza"; private static final String ORACLE_DB_TYPE = "oracle"; private static final String SQL_SERVER_DB_TYPE = "sqlserver"; private static final String NETEZZA_JDBC_DRIVER_CLASS = "org.netezza.Driver"; /** * @param connection_url (Input) * @param table (Input) * @param select_query (Input) * @param username (Input) * @param password (Input) * @param columns (Input) * @param optimize (Input) */ public static Job<Frame> importSqlTable(final String connection_url, String table, final String select_query, final String username, final String password, final String columns, boolean optimize) { Connection conn = null; Statement stmt = null; ResultSet rs = null; /** Pagination in following Databases: SQL Server, Oracle 12c: OFFSET x ROWS FETCH NEXT y ROWS ONLY SQL Server, Vertica may need ORDER BY MySQL, PostgreSQL, MariaDB: LIMIT y OFFSET x ? Teradata (and possibly older Oracle): SELECT * FROM ( SELECT ROW_NUMBER() OVER () AS RowNum_, <table>.* FROM <table> ) QUALIFY RowNum_ BETWEEN x and x+y; */ String databaseType = connection_url.split(":", 3)[1]; initializeDatabaseDriver(databaseType); final boolean needFetchClause = ORACLE_DB_TYPE.equals(databaseType) || SQL_SERVER_DB_TYPE.equals(databaseType); int catcols = 0, intcols = 0, bincols = 0, realcols = 0, timecols = 0, stringcols = 0; final int numCol; long numRow = 0; final String[] columnNames; final byte[] columnH2OTypes; try { conn = DriverManager.getConnection(connection_url, username, password); stmt = conn.createStatement(); //set fetch size for improved performance stmt.setFetchSize(1); //if select_query has been specified instead of table if (table.equals("")) { if (!select_query.toLowerCase().startsWith("select")) { throw new IllegalArgumentException("The select_query must start with `SELECT`, but instead is: " + select_query); } table = SQLManager.TEMP_TABLE_NAME; //returns number of rows, but as an int, not long. if int max value is exceeded, result is negative numRow = stmt.executeUpdate("CREATE TABLE " + table + " AS " + select_query); } else if (table.equals(SQLManager.TEMP_TABLE_NAME)) { //tables with this name are assumed to be created here temporarily and are dropped throw new IllegalArgumentException("The specified table cannot be named: " + SQLManager.TEMP_TABLE_NAME); } //get number of rows. check for negative row count if (numRow <= 0) { rs = stmt.executeQuery("SELECT COUNT(1) FROM " + table); rs.next(); numRow = rs.getLong(1); rs.close(); } //get H2O column names and types if (needFetchClause) rs = stmt.executeQuery("SELECT " + columns + " FROM " + table + " FETCH NEXT 1 ROWS ONLY"); else rs = stmt.executeQuery("SELECT " + columns + " FROM " + table + " LIMIT 1"); ResultSetMetaData rsmd = rs.getMetaData(); numCol = rsmd.getColumnCount(); columnNames = new String[numCol]; columnH2OTypes = new byte[numCol]; rs.next(); for (int i = 0; i < numCol; i++) { columnNames[i] = rsmd.getColumnName(i + 1); //must iterate through sql types instead of getObject bc object could be null switch (rsmd.getColumnType(i + 1)) { case Types.NUMERIC: case Types.REAL: case Types.DOUBLE: case Types.FLOAT: case Types.DECIMAL: columnH2OTypes[i] = Vec.T_NUM; realcols += 1; break; case Types.INTEGER: case Types.TINYINT: case Types.SMALLINT: case Types.BIGINT: columnH2OTypes[i] = Vec.T_NUM; intcols += 1; break; case Types.BIT: case Types.BOOLEAN: columnH2OTypes[i] = Vec.T_NUM; bincols += 1; break; case Types.VARCHAR: case Types.NVARCHAR: case Types.CHAR: case Types.NCHAR: case Types.LONGVARCHAR: case Types.LONGNVARCHAR: columnH2OTypes[i] = Vec.T_STR; stringcols += 1; break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: columnH2OTypes[i] = Vec.T_TIME; timecols += 1; break; default: Log.warn("Unsupported column type: " + rsmd.getColumnTypeName(i + 1)); columnH2OTypes[i] = Vec.T_BAD; } } } catch (SQLException ex) { throw new RuntimeException("SQLException: " + ex.getMessage() + "\nFailed to connect and read from SQL database with connection_url: " + connection_url); } finally { // release resources in a finally{} block in reverse-order of their creation if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) {} // ignore rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) {} // ignore stmt = null; } if (conn != null) { try { conn.close(); } catch (SQLException sqlEx) {} // ignore conn = null; } } double binary_ones_fraction = 0.5; //estimate //create template vectors in advance and run MR long totSize = (long)((float)(catcols+intcols)*numRow*4 //4 bytes for categoricals and integers +(float)bincols *numRow*1*binary_ones_fraction //sparse uses a fraction of one byte (or even less) +(float)(realcols+timecols+stringcols) *numRow*8); //8 bytes for real and time (long) values final Vec _v; if (optimize) { _v = makeCon(totSize, numRow); } else { double rows_per_chunk = FileVec.calcOptimalChunkSize(totSize, numCol, numCol * 4, Runtime.getRuntime().availableProcessors(), H2O.getCloudSize(), false, false); _v = makeCon(0, numRow, (int) Math.ceil(Math.log1p(rows_per_chunk)), false); } Log.info("Number of chunks: " + _v.nChunks()); //create frame final Key destination_key = Key.make(table + "_sql_to_hex"); final Job<Frame> j = new Job(destination_key, Frame.class.getName(), "Import SQL Table"); final String finalTable = table; H2O.H2OCountedCompleter work = new H2O.H2OCountedCompleter() { @Override public void compute2() { Frame fr = new SqlTableToH2OFrame(connection_url, finalTable, needFetchClause, username, password, columns, numCol, _v.nChunks(), j).doAll(columnH2OTypes, _v) .outputFrame(destination_key, columnNames, null); DKV.put(fr); _v.remove(); ParseDataset.logParseResults(fr); if (finalTable.equals(SQLManager.TEMP_TABLE_NAME)) dropTempTable(connection_url, username, password); tryComplete(); } }; j.start(work, _v.nChunks()); return j; } /** * Initializes database driver for databases with JDBC driver version lower than 4.0 * * @param databaseType Name of target database from JDBC connection string */ private static void initializeDatabaseDriver(String databaseType) { switch (databaseType) { case NETEZZA_DB_TYPE: try { Class.forName(NETEZZA_JDBC_DRIVER_CLASS); } catch (ClassNotFoundException e) { throw new RuntimeException("Connection to Netezza database is not possible due to missing JDBC driver."); } } } private static class SqlTableToH2OFrame extends MRTask<SqlTableToH2OFrame> { final String _url, _table, _user, _password, _columns; final int _numCol, _nChunks; final boolean _needFetchClause; final Job _job; transient ArrayBlockingQueue<Connection> sqlConn; public SqlTableToH2OFrame(String url, String table, boolean needFetchClause, String user, String password, String columns, int numCol, int nChunks, Job job) { _url = url; _table = table; _needFetchClause = needFetchClause; _user = user; _password = password; _columns = columns; _numCol = numCol; _nChunks = nChunks; _job = job; } @Override protected void setupLocal() { int conPerNode = (int) Math.min(Math.ceil((double) _nChunks / H2O.getCloudSize()), Runtime.getRuntime().availableProcessors()); conPerNode = Math.min(conPerNode, SQLManager.MAX_CONNECTIONS / H2O.getCloudSize()); Log.info("Database connections per node: " + conPerNode); sqlConn = new ArrayBlockingQueue<>(conPerNode); try { for (int i = 0; i < conPerNode; i++) { Connection conn = DriverManager.getConnection(_url, _user, _password); sqlConn.add(conn); } } catch (SQLException ex) { throw new RuntimeException("SQLException: " + ex.getMessage() + "\nFailed to connect to SQL database with url: " + _url); } } @Override public void map(Chunk[] cs, NewChunk[] ncs) { if (isCancelled() || _job != null && _job.stop_requested()) return; //fetch data from sql table with limit and offset Connection conn = null; Statement stmt = null; ResultSet rs = null; Chunk c0 = cs[0]; String sqlText = "SELECT " + _columns + " FROM " + _table; if (_needFetchClause) sqlText += " OFFSET " + c0.start() + " ROWS FETCH NEXT " + c0._len + " ROWS ONLY"; else sqlText += " LIMIT " + c0._len + " OFFSET " + c0.start(); try { conn = sqlConn.take(); stmt = conn.createStatement(); //set fetch size for best performance stmt.setFetchSize(c0._len); rs = stmt.executeQuery(sqlText); while (rs.next()) { for (int i = 0; i < _numCol; i++) { Object res = rs.getObject(i + 1); if (res == null) ncs[i].addNA(); else { switch (res.getClass().getSimpleName()) { case "Double": ncs[i].addNum((double) res); break; case "Integer": ncs[i].addNum((long) (int) res, 0); break; case "Long": ncs[i].addNum((long) res, 0); break; case "Float": ncs[i].addNum((double) (float) res); break; case "Short": ncs[i].addNum((long) (short) res, 0); break; case "Byte": ncs[i].addNum((long) (byte) res, 0); break; case "BigDecimal": ncs[i].addNum(((BigDecimal) res).doubleValue()); break; case "Boolean": ncs[i].addNum(((boolean) res ? 1 : 0), 0); break; case "String": ncs[i].addStr(new BufferedString((String) res)); break; case "Date": ncs[i].addNum(((Date) res).getTime(), 0); break; case "Time": ncs[i].addNum(((Time) res).getTime(), 0); break; case "Timestamp": ncs[i].addNum(((Timestamp) res).getTime(), 0); break; default: ncs[i].addNA(); } } } } } catch (SQLException ex) { throw new RuntimeException("SQLException: " + ex.getMessage() + "\nFailed to read SQL data"); } catch (InterruptedException e) { e.printStackTrace(); throw new RuntimeException("Interrupted exception when trying to take connection from pool"); } finally { //close result set if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { } // ignore rs = null; } //close statement if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { } // ignore stmt = null; } //return connection to pool sqlConn.add(conn); } if (_job != null) _job.update(1); } @Override protected void closeLocal() { try { for (Connection conn : sqlConn) { conn.close(); } } catch (Exception ex) { } // ignore } } private static void dropTempTable(String connection_url, String username, String password) { Connection conn = null; Statement stmt = null; String drop_table_query = "DROP TABLE " + SQLManager.TEMP_TABLE_NAME; try { conn = DriverManager.getConnection(connection_url, username, password); stmt = conn.createStatement(); stmt.executeUpdate(drop_table_query); } catch (SQLException ex) { throw new RuntimeException("SQLException: " + ex.getMessage() + "\nFailed to execute SQL query: " + drop_table_query); } finally { // release resources in a finally{} block in reverse-order of their creation if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { } // ignore stmt = null; } if (conn != null) { try { conn.close(); } catch (SQLException sqlEx) { } // ignore conn = null; } } } }
package ch.eth.scu.importer.common.version; public class VersionInfo { // Program version public static final String version = "0.4.0"; // Version status: "alpha", "beta", or "" for a stable release public static final String status = ""; // Properties (XML) file version public static final int propertiesVersion = 4; }
package com.xlythe.textmanager; /** * Represents a person who can send or receive messages. */ public interface User { String sender = ""; int PhoneNumber = 0; /** * Return the user's name * */ public String getName(String sender, int PhoneNumber); }
package com.krishagni.catissueplus.core.biospecimen.services.impl; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.hibernate.SessionFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import com.fasterxml.jackson.databind.ObjectMapper; import com.krishagni.catissueplus.core.administrative.domain.Site; import com.krishagni.catissueplus.core.administrative.domain.StorageContainer; import com.krishagni.catissueplus.core.administrative.domain.User; import com.krishagni.catissueplus.core.administrative.events.SiteSummary; import com.krishagni.catissueplus.core.audit.services.impl.DeleteLogUtil; import com.krishagni.catissueplus.core.biospecimen.ConfigParams; import com.krishagni.catissueplus.core.biospecimen.WorkflowUtil; import com.krishagni.catissueplus.core.biospecimen.domain.AliquotSpecimensRequirement; import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocol; import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocolEvent; import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocolRegistration; import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocolSavedEvent; import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocolSite; import com.krishagni.catissueplus.core.biospecimen.domain.ConsentStatement; import com.krishagni.catissueplus.core.biospecimen.domain.CpConsentTier; import com.krishagni.catissueplus.core.biospecimen.domain.CpReportSettings; import com.krishagni.catissueplus.core.biospecimen.domain.CpWorkflowConfig; import com.krishagni.catissueplus.core.biospecimen.domain.CpWorkflowConfig.Workflow; import com.krishagni.catissueplus.core.biospecimen.domain.DerivedSpecimenRequirement; import com.krishagni.catissueplus.core.biospecimen.domain.Participant; import com.krishagni.catissueplus.core.biospecimen.domain.Specimen; import com.krishagni.catissueplus.core.biospecimen.domain.SpecimenRequirement; import com.krishagni.catissueplus.core.biospecimen.domain.Visit; import com.krishagni.catissueplus.core.biospecimen.domain.factory.CollectionProtocolFactory; import com.krishagni.catissueplus.core.biospecimen.domain.factory.ConsentStatementErrorCode; import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpErrorCode; import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpReportSettingsFactory; import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpeErrorCode; import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpeFactory; import com.krishagni.catissueplus.core.biospecimen.domain.factory.CprErrorCode; import com.krishagni.catissueplus.core.biospecimen.domain.factory.SpecimenRequirementFactory; import com.krishagni.catissueplus.core.biospecimen.domain.factory.SrErrorCode; import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolDetail; import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolEventDetail; import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolRegistrationDetail; import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolSummary; import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierDetail; import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierOp; import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierOp.OP; import com.krishagni.catissueplus.core.biospecimen.events.CopyCpOpDetail; import com.krishagni.catissueplus.core.biospecimen.events.CopyCpeOpDetail; import com.krishagni.catissueplus.core.biospecimen.events.CpQueryCriteria; import com.krishagni.catissueplus.core.biospecimen.events.CpReportSettingsDetail; import com.krishagni.catissueplus.core.biospecimen.events.CpWorkflowCfgDetail; import com.krishagni.catissueplus.core.biospecimen.events.FileDetail; import com.krishagni.catissueplus.core.biospecimen.events.MergeCpDetail; import com.krishagni.catissueplus.core.biospecimen.events.SpecimenPoolRequirements; import com.krishagni.catissueplus.core.biospecimen.events.SpecimenRequirementDetail; import com.krishagni.catissueplus.core.biospecimen.events.WorkflowDetail; import com.krishagni.catissueplus.core.biospecimen.repository.CollectionProtocolDao; import com.krishagni.catissueplus.core.biospecimen.repository.CpListCriteria; import com.krishagni.catissueplus.core.biospecimen.repository.CprListCriteria; import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory; import com.krishagni.catissueplus.core.biospecimen.repository.impl.BiospecimenDaoHelper; import com.krishagni.catissueplus.core.biospecimen.services.CollectionProtocolService; import com.krishagni.catissueplus.core.common.PlusTransactional; import com.krishagni.catissueplus.core.common.Tuple; import com.krishagni.catissueplus.core.common.access.AccessCtrlMgr; import com.krishagni.catissueplus.core.common.access.AccessCtrlMgr.ParticipantReadAccess; import com.krishagni.catissueplus.core.common.access.SiteCpPair; import com.krishagni.catissueplus.core.common.domain.Notification; import com.krishagni.catissueplus.core.common.errors.ErrorType; import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException; import com.krishagni.catissueplus.core.common.events.BulkDeleteEntityOp; import com.krishagni.catissueplus.core.common.events.BulkDeleteEntityResp; import com.krishagni.catissueplus.core.common.events.DependentEntityDetail; import com.krishagni.catissueplus.core.common.events.RequestEvent; import com.krishagni.catissueplus.core.common.events.ResponseEvent; import com.krishagni.catissueplus.core.common.service.ObjectAccessor; import com.krishagni.catissueplus.core.common.service.StarredItemService; import com.krishagni.catissueplus.core.common.service.impl.EventPublisher; import com.krishagni.catissueplus.core.common.util.AuthUtil; import com.krishagni.catissueplus.core.common.util.ConfigUtil; import com.krishagni.catissueplus.core.common.util.EmailUtil; import com.krishagni.catissueplus.core.common.util.MessageUtil; import com.krishagni.catissueplus.core.common.util.NotifUtil; import com.krishagni.catissueplus.core.common.util.Status; import com.krishagni.catissueplus.core.common.util.Utility; import com.krishagni.catissueplus.core.de.domain.DeObject; import com.krishagni.catissueplus.core.exporter.domain.ExportJob; import com.krishagni.catissueplus.core.exporter.services.ExportService; import com.krishagni.catissueplus.core.init.AppProperties; import com.krishagni.catissueplus.core.query.Column; import com.krishagni.catissueplus.core.query.ListConfig; import com.krishagni.catissueplus.core.query.ListDetail; import com.krishagni.catissueplus.core.query.ListService; import com.krishagni.catissueplus.core.query.Row; import com.krishagni.rbac.common.errors.RbacErrorCode; import com.krishagni.rbac.events.SubjectRoleOpNotif; import com.krishagni.rbac.service.RbacService; public class CollectionProtocolServiceImpl implements CollectionProtocolService, ObjectAccessor, InitializingBean { private ThreadPoolTaskExecutor taskExecutor; private CollectionProtocolFactory cpFactory; private CpeFactory cpeFactory; private SpecimenRequirementFactory srFactory; private DaoFactory daoFactory; private RbacService rbacSvc; private ListService listSvc; private CpReportSettingsFactory rptSettingsFactory; private SessionFactory sessionFactory; private StarredItemService starredItemSvc; private ExportService exportSvc; public void setTaskExecutor(ThreadPoolTaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } public void setCpFactory(CollectionProtocolFactory cpFactory) { this.cpFactory = cpFactory; } public void setCpeFactory(CpeFactory cpeFactory) { this.cpeFactory = cpeFactory; } public void setSrFactory(SpecimenRequirementFactory srFactory) { this.srFactory = srFactory; } public void setDaoFactory(DaoFactory daoFactory) { this.daoFactory = daoFactory; } public void setRbacSvc(RbacService rbacSvc) { this.rbacSvc = rbacSvc; } public void setListSvc(ListService listSvc) { this.listSvc = listSvc; } public void setRptSettingsFactory(CpReportSettingsFactory rptSettingsFactory) { this.rptSettingsFactory = rptSettingsFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void setStarredItemSvc(StarredItemService starredItemSvc) { this.starredItemSvc = starredItemSvc; } public void setExportSvc(ExportService exportSvc) { this.exportSvc = exportSvc; } @Override @PlusTransactional public ResponseEvent<List<CollectionProtocolSummary>> getProtocols(RequestEvent<CpListCriteria> req) { try { CpListCriteria crit = addCpListCriteria(req.getPayload()); if (crit == null) { return ResponseEvent.response(Collections.emptyList()); } return ResponseEvent.response(daoFactory.getCollectionProtocolDao().getCollectionProtocols(crit)); } catch (OpenSpecimenException oce) { return ResponseEvent.error(oce); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<Long> getProtocolsCount(RequestEvent<CpListCriteria> req) { try { CpListCriteria crit = addCpListCriteria(req.getPayload()); if (crit == null) { return ResponseEvent.response(0L); } return ResponseEvent.response(daoFactory.getCollectionProtocolDao().getCpCount(crit)); } catch (OpenSpecimenException oce) { return ResponseEvent.error(oce); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<CollectionProtocolDetail> getCollectionProtocol(RequestEvent<CpQueryCriteria> req) { try { CpQueryCriteria crit = req.getPayload(); CollectionProtocol cp = getCollectionProtocol(crit.getId(), crit.getTitle(), crit.getShortTitle()); AccessCtrlMgr.getInstance().ensureReadCpRights(cp); return ResponseEvent.response(CollectionProtocolDetail.from(cp, crit.isFullObject())); } catch (OpenSpecimenException oce) { return ResponseEvent.error(oce); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<List<SiteSummary>> getSites(RequestEvent<CpQueryCriteria> req) { try { CpQueryCriteria crit = req.getPayload(); CollectionProtocol cp = getCollectionProtocol(crit.getId(), crit.getTitle(), crit.getShortTitle()); AccessCtrlMgr.getInstance().ensureReadCpRights(cp); List<Site> sites = cp.getSites().stream().map(CollectionProtocolSite::getSite).collect(Collectors.toList()); return ResponseEvent.response(SiteSummary.from(sites)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<List<CollectionProtocolRegistrationDetail>> getRegisteredParticipants(RequestEvent<CprListCriteria> req) { try { CprListCriteria listCrit = addCprListCriteria(req.getPayload()); if (listCrit == null) { return ResponseEvent.response(Collections.emptyList()); } List<CollectionProtocolRegistration> cprs = daoFactory.getCprDao().getCprs(listCrit); createExtensions(cprs); Map<CollectionProtocol, Boolean> phiAccess = new HashMap<>(); List<CollectionProtocolRegistrationDetail> result = new ArrayList<>(); for (CollectionProtocolRegistration cpr : cprs) { boolean includePhi = listCrit.includePhi(); if (includePhi && CollectionUtils.isNotEmpty(listCrit.phiSiteCps())) { CollectionProtocol cp = cpr.getCollectionProtocol(); if (!phiAccess.containsKey(cp)) { phiAccess.put(cp, AccessCtrlMgr.getInstance().isAccessAllowed(listCrit.phiSiteCps(), cp)); } includePhi = phiAccess.get(cp); } result.add(CollectionProtocolRegistrationDetail.from(cpr, !includePhi)); } return ResponseEvent.response(result); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<Long> getRegisteredParticipantsCount(RequestEvent<CprListCriteria> req) { try { CprListCriteria listCrit = addCprListCriteria(req.getPayload()); if (listCrit == null) { return ResponseEvent.response(0L); } return ResponseEvent.response(daoFactory.getCprDao().getCprCount(listCrit)); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<CollectionProtocolDetail> createCollectionProtocol(RequestEvent<CollectionProtocolDetail> req) { try { CollectionProtocol cp = createCollectionProtocol(req.getPayload(), null, false); notifyUsersOnCpCreate(cp); EventPublisher.getInstance().publish(new CollectionProtocolSavedEvent(cp)); return ResponseEvent.response(CollectionProtocolDetail.from(cp)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<CollectionProtocolDetail> updateCollectionProtocol(RequestEvent<CollectionProtocolDetail> req) { try { CollectionProtocolDetail detail = req.getPayload(); CollectionProtocol existingCp = daoFactory.getCollectionProtocolDao().getById(detail.getId()); if (existingCp == null) { return ResponseEvent.userError(CpErrorCode.NOT_FOUND); } AccessCtrlMgr.getInstance().ensureUpdateCpRights(existingCp); CollectionProtocol cp = cpFactory.createCollectionProtocol(detail); AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp); ensureUsersBelongtoCpSites(cp); OpenSpecimenException ose = new OpenSpecimenException(ErrorType.USER_ERROR); ensureUniqueTitle(existingCp, cp, ose); ensureUniqueShortTitle(existingCp, cp, ose); ensureUniqueCode(existingCp, cp, ose); ensureUniqueCpSiteCode(cp, ose); if (existingCp.isConsentsWaived() != cp.isConsentsWaived()) { ensureConsentTierIsEmpty(existingCp, ose); } ose.checkAndThrow(); Set<Site> addedSites = Utility.subtract(cp.getRepositories(), existingCp.getRepositories()); Set<Site> removedSites = Utility.subtract(existingCp.getRepositories(), cp.getRepositories()); ensureSitesAreNotInUse(existingCp, removedSites); existingCp.update(cp); existingCp.addOrUpdateExtension(); fixSopDocumentName(existingCp); notifyUsersOnCpUpdate(existingCp, addedSites, removedSites); EventPublisher.getInstance().publish(new CollectionProtocolSavedEvent(existingCp)); return ResponseEvent.response(CollectionProtocolDetail.from(existingCp)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<CollectionProtocolDetail> copyCollectionProtocol(RequestEvent<CopyCpOpDetail> req) { try { CopyCpOpDetail opDetail = req.getPayload(); Long cpId = opDetail.getCpId(); CollectionProtocol existing = daoFactory.getCollectionProtocolDao().getById(cpId); if (existing == null) { throw OpenSpecimenException.userError(CpErrorCode.NOT_FOUND); } AccessCtrlMgr.getInstance().ensureReadCpRights(existing); CollectionProtocol cp = createCollectionProtocol(opDetail.getCp(), existing, true); notifyUsersOnCpCreate(cp); EventPublisher.getInstance().publish(new CollectionProtocolSavedEvent(cp)); return ResponseEvent.response(CollectionProtocolDetail.from(cp)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<MergeCpDetail> mergeCollectionProtocols(RequestEvent<MergeCpDetail> req) { AccessCtrlMgr.getInstance().ensureUserIsAdmin(); CollectionProtocol srcCp = getCollectionProtocol(req.getPayload().getSrcCpShortTitle()); CollectionProtocol tgtCp = getCollectionProtocol(req.getPayload().getTgtCpShortTitle()); ensureMergeableCps(srcCp, tgtCp); int maxRecords = 30; boolean moreRecords = true; while (moreRecords) { List<CollectionProtocolRegistration> cprs = daoFactory.getCprDao().getCprsByCpId(srcCp.getId(), 0, maxRecords); for (CollectionProtocolRegistration srcCpr: cprs) { mergeCprIntoCp(srcCpr, tgtCp); } if (cprs.size() < maxRecords) { moreRecords = false; } } return ResponseEvent.response(req.getPayload()); } @PlusTransactional public ResponseEvent<CollectionProtocolDetail> updateConsentsWaived(RequestEvent<CollectionProtocolDetail> req) { try { CollectionProtocolDetail detail = req.getPayload(); CollectionProtocol existingCp = daoFactory.getCollectionProtocolDao().getById(detail.getId()); if (existingCp == null) { return ResponseEvent.userError(CpErrorCode.NOT_FOUND); } AccessCtrlMgr.getInstance().ensureUpdateCpRights(existingCp); if (CollectionUtils.isNotEmpty(existingCp.getConsentTier())) { return ResponseEvent.userError(CpErrorCode.CONSENT_TIER_FOUND, existingCp.getShortTitle()); } existingCp.setConsentsWaived(detail.getConsentsWaived()); EventPublisher.getInstance().publish(new CollectionProtocolSavedEvent(existingCp)); return ResponseEvent.response(CollectionProtocolDetail.from(existingCp)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @PlusTransactional public ResponseEvent<List<DependentEntityDetail>> getCpDependentEntities(RequestEvent<Long> req) { try { CollectionProtocol existingCp = daoFactory.getCollectionProtocolDao().getById(req.getPayload()); if (existingCp == null) { return ResponseEvent.userError(CpErrorCode.NOT_FOUND); } return ResponseEvent.response(existingCp.getDependentEntities()); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<BulkDeleteEntityResp<CollectionProtocolDetail>> deleteCollectionProtocols(RequestEvent<BulkDeleteEntityOp> req) { try { BulkDeleteEntityOp crit = req.getPayload(); Set<Long> cpIds = crit.getIds(); List<CollectionProtocol> cps = daoFactory.getCollectionProtocolDao().getByIds(cpIds); if (crit.getIds().size() != cps.size()) { cps.forEach(cp -> cpIds.remove(cp.getId())); throw OpenSpecimenException.userError(CpErrorCode.DOES_NOT_EXIST, cpIds); } cps.forEach(cp -> AccessCtrlMgr.getInstance().ensureDeleteCpRights(cp)); boolean completed = crit.isForceDelete() ? forceDeleteCps(cps, crit.getReason()) : deleteCps(cps, crit.getReason()); BulkDeleteEntityResp<CollectionProtocolDetail> resp = new BulkDeleteEntityResp<>(); resp.setCompleted(completed); resp.setEntities(CollectionProtocolDetail.from(cps)); return ResponseEvent.response(resp); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<File> getSopDocument(RequestEvent<Long> req) { try { Long cpId = req.getPayload(); CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId); if (cp == null) { return ResponseEvent.userError(CprErrorCode.NOT_FOUND); } AccessCtrlMgr.getInstance().ensureReadCpRights(cp); String filename = cp.getSopDocumentName(); File file = null; if (StringUtils.isBlank(filename)) { file = ConfigUtil.getInstance().getFileSetting(ConfigParams.MODULE, ConfigParams.CP_SOP_DOC, null); } else { file = new File(getSopDocDir() + filename); if (!file.exists()) { filename = filename.split("_", 2)[1]; return ResponseEvent.userError(CpErrorCode.SOP_DOC_MOVED_OR_DELETED, cp.getShortTitle(), filename); } } if (file == null) { return ResponseEvent.userError(CpErrorCode.SOP_DOC_NOT_FOUND, cp.getShortTitle()); } return ResponseEvent.response(file); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override public ResponseEvent<String> uploadSopDocument(RequestEvent<FileDetail> req) { OutputStream out = null; try { FileDetail detail = req.getPayload(); String filename = UUID.randomUUID() + "_" + detail.getFilename(); File file = new File(getSopDocDir() + filename); out = new FileOutputStream(file); IOUtils.copy(detail.getFileIn(), out); return ResponseEvent.response(filename); } catch (Exception e) { return ResponseEvent.serverError(e); } finally { IOUtils.closeQuietly(out); } } @Override @PlusTransactional public ResponseEvent<CollectionProtocolDetail> importCollectionProtocol(RequestEvent<CollectionProtocolDetail> req) { try { CollectionProtocolDetail cpDetail = req.getPayload(); cpDetail.setDistributionProtocols(null); ResponseEvent<CollectionProtocolDetail> resp = createCollectionProtocol(req); resp.throwErrorIfUnsuccessful(); Long cpId = resp.getPayload().getId(); importConsents(cpId, cpDetail.getConsents()); importEvents(cpDetail.getTitle(), cpDetail.getEvents()); importWorkflows(cpId, cpDetail.getWorkflows()); return resp; } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<Boolean> isSpecimenBarcodingEnabled() { try { boolean isEnabled = ConfigUtil.getInstance().getBoolSetting( ConfigParams.MODULE, ConfigParams.ENABLE_SPMN_BARCODING, false); if (!isEnabled) { isEnabled = daoFactory.getCollectionProtocolDao().anyBarcodingEnabledCpExists(); } return ResponseEvent.response(isEnabled); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<List<ConsentTierDetail>> getConsentTiers(RequestEvent<Long> req) { Long cpId = req.getPayload(); try { CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId); if (cp == null) { return ResponseEvent.userError(CpErrorCode.NOT_FOUND); } AccessCtrlMgr.getInstance().ensureReadCpRights(cp); return ResponseEvent.response(ConsentTierDetail.from(cp.getConsentTier())); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<ConsentTierDetail> updateConsentTier(RequestEvent<ConsentTierOp> req) { try { ConsentTierOp opDetail = req.getPayload(); CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(opDetail.getCpId()); if (cp == null) { return ResponseEvent.userError(CpErrorCode.NOT_FOUND); } AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp); if (cp.isConsentsWaived()) { return ResponseEvent.userError(CpErrorCode.CONSENTS_WAIVED, cp.getShortTitle()); } ConsentTierDetail input = opDetail.getConsentTier(); CpConsentTier resp = null; ConsentStatement stmt = null; switch (opDetail.getOp()) { case ADD: ensureUniqueConsentStatement(input, cp); stmt = getStatement(input.getStatementId(), input.getStatementCode(), input.getStatement()); resp = cp.addConsentTier(getConsentTierObj(input.getId(), stmt)); break; case UPDATE: ensureUniqueConsentStatement(input, cp); stmt = getStatement(input.getStatementId(), input.getStatementCode(), input.getStatement()); resp = cp.updateConsentTier(getConsentTierObj(input.getId(), stmt)); break; case REMOVE: resp = cp.removeConsentTier(input.getId()); break; } if (resp != null) { daoFactory.getCollectionProtocolDao().saveOrUpdate(cp, true); } return ResponseEvent.response(ConsentTierDetail.from(resp)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<List<DependentEntityDetail>> getConsentDependentEntities(RequestEvent<ConsentTierDetail> req) { try { ConsentTierDetail consentTierDetail = req.getPayload(); CpConsentTier consentTier = getConsentTier(consentTierDetail); return ResponseEvent.response(consentTier.getDependentEntities()); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch(Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<List<CollectionProtocolEventDetail>> getProtocolEvents(RequestEvent<Long> req) { Long cpId = req.getPayload(); try { CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId); if (cp == null) { return ResponseEvent.userError(CpErrorCode.NOT_FOUND); } AccessCtrlMgr.getInstance().ensureReadCpRights(cp); return ResponseEvent.response(CollectionProtocolEventDetail.from(cp.getOrderedCpeList())); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<CollectionProtocolEventDetail> getProtocolEvent(RequestEvent<Long> req) { Long cpeId = req.getPayload(); try { CollectionProtocolEvent cpe = daoFactory.getCollectionProtocolDao().getCpe(cpeId); if (cpe == null) { return ResponseEvent.userError(CpeErrorCode.NOT_FOUND, cpeId, 1); } CollectionProtocol cp = cpe.getCollectionProtocol(); AccessCtrlMgr.getInstance().ensureReadCpRights(cp); if (cpe.getEventPoint() != null) { CollectionProtocolEvent firstEvent = cp.firstEvent(); if (firstEvent.getEventPoint() != null) { cpe.setOffset(firstEvent.getEventPoint()); cpe.setOffsetUnit(firstEvent.getEventPointUnit()); } } return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<CollectionProtocolEventDetail> addEvent(RequestEvent<CollectionProtocolEventDetail> req) { try { CollectionProtocolEvent cpe = cpeFactory.createCpe(req.getPayload()); CollectionProtocol cp = cpe.getCollectionProtocol(); AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp); cp.addCpe(cpe); daoFactory.getCollectionProtocolDao().saveOrUpdate(cp, true); return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<CollectionProtocolEventDetail> updateEvent(RequestEvent<CollectionProtocolEventDetail> req) { try { CollectionProtocolEvent cpe = cpeFactory.createCpe(req.getPayload()); CollectionProtocol cp = cpe.getCollectionProtocol(); AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp); cp.updateCpe(cpe); return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<CollectionProtocolEventDetail> copyEvent(RequestEvent<CopyCpeOpDetail> req) { try { CollectionProtocolDao cpDao = daoFactory.getCollectionProtocolDao(); CopyCpeOpDetail opDetail = req.getPayload(); String cpTitle = opDetail.getCollectionProtocol(); String eventLabel = opDetail.getEventLabel(); CollectionProtocolEvent existing = null; Object key = null; if (opDetail.getEventId() != null) { existing = cpDao.getCpe(opDetail.getEventId()); key = opDetail.getEventId(); } else if (!StringUtils.isBlank(eventLabel) && !StringUtils.isBlank(cpTitle)) { existing = cpDao.getCpeByEventLabel(cpTitle, eventLabel); key = eventLabel; } if (existing == null) { throw OpenSpecimenException.userError(CpeErrorCode.NOT_FOUND, key, 1); } CollectionProtocol cp = existing.getCollectionProtocol(); AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp); CollectionProtocolEvent cpe = cpeFactory.createCpeCopy(opDetail.getCpe(), existing); existing.copySpecimenRequirementsTo(cpe); cp.addCpe(cpe); cpDao.saveOrUpdate(cp, true); return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<CollectionProtocolEventDetail> deleteEvent(RequestEvent<Long> req) { try { Long cpeId = req.getPayload(); CollectionProtocolEvent cpe = daoFactory.getCollectionProtocolDao().getCpe(cpeId); if (cpe == null) { throw OpenSpecimenException.userError(CpeErrorCode.NOT_FOUND, cpeId, 1); } CollectionProtocol cp = cpe.getCollectionProtocol(); AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp); cpe.delete(); daoFactory.getCollectionProtocolDao().saveCpe(cpe); return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<List<SpecimenRequirementDetail>> getSpecimenRequirments(RequestEvent<Tuple> req) { try { Tuple tuple = req.getPayload(); Long cpId = tuple.element(0); Long cpeId = tuple.element(1); String cpeLabel = tuple.element(2); boolean includeChildren = tuple.element(3) == null || (Boolean) tuple.element(3); CollectionProtocolEvent cpe = null; Object key = null; if (cpeId != null) { cpe = daoFactory.getCollectionProtocolDao().getCpe(cpeId); key = cpeId; } else if (StringUtils.isNotBlank(cpeLabel)) { if (cpId == null) { throw OpenSpecimenException.userError(CpErrorCode.REQUIRED); } cpe = daoFactory.getCollectionProtocolDao().getCpeByEventLabel(cpId, cpeLabel); key = cpeLabel; } if (key == null) { return ResponseEvent.response(Collections.emptyList()); } else if (cpe == null) { return ResponseEvent.userError(CpeErrorCode.NOT_FOUND, key, 1); } AccessCtrlMgr.getInstance().ensureReadCpRights(cpe.getCollectionProtocol()); return ResponseEvent.response(SpecimenRequirementDetail.from(cpe.getTopLevelAnticipatedSpecimens(), includeChildren)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<SpecimenRequirementDetail> getSpecimenRequirement(RequestEvent<Long> req) { Long reqId = req.getPayload(); try { SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(reqId); if (sr == null) { return ResponseEvent.userError(SrErrorCode.NOT_FOUND); } AccessCtrlMgr.getInstance().ensureReadCpRights(sr.getCollectionProtocol()); return ResponseEvent.response(SpecimenRequirementDetail.from(sr)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<SpecimenRequirementDetail> addSpecimenRequirement(RequestEvent<SpecimenRequirementDetail> req) { try { SpecimenRequirement requirement = srFactory.createSpecimenRequirement(req.getPayload()); CollectionProtocolEvent cpe = requirement.getCollectionProtocolEvent(); AccessCtrlMgr.getInstance().ensureUpdateCpRights(cpe.getCollectionProtocol()); cpe.addSpecimenRequirement(requirement); daoFactory.getCollectionProtocolDao().saveCpe(cpe, true); return ResponseEvent.response(SpecimenRequirementDetail.from(requirement)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<List<SpecimenRequirementDetail>> addSpecimenPoolReqs(RequestEvent<SpecimenPoolRequirements> req) { try { List<SpecimenRequirement> spmnPoolReqs = srFactory.createSpecimenPoolReqs(req.getPayload()); SpecimenRequirement pooledReq = spmnPoolReqs.iterator().next().getPooledSpecimenRequirement(); AccessCtrlMgr.getInstance().ensureUpdateCpRights(pooledReq.getCollectionProtocol()); pooledReq.getCollectionProtocolEvent().ensureUniqueSrCodes(spmnPoolReqs); pooledReq.addSpecimenPoolReqs(spmnPoolReqs); daoFactory.getSpecimenRequirementDao().saveOrUpdate(pooledReq, true); return ResponseEvent.response(SpecimenRequirementDetail.from(spmnPoolReqs)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<List<SpecimenRequirementDetail>> createAliquots(RequestEvent<AliquotSpecimensRequirement> req) { try { return ResponseEvent.response(SpecimenRequirementDetail.from(createAliquots(req.getPayload()))); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<SpecimenRequirementDetail> createDerived(RequestEvent<DerivedSpecimenRequirement> req) { try { DerivedSpecimenRequirement requirement = req.getPayload(); SpecimenRequirement derived = srFactory.createDerived(requirement); AccessCtrlMgr.getInstance().ensureUpdateCpRights(derived.getCollectionProtocol()); ensureSrIsNotClosed(derived.getParentSpecimenRequirement()); if (StringUtils.isNotBlank(derived.getCode())) { if (derived.getCollectionProtocolEvent().getSrByCode(derived.getCode()) != null) { return ResponseEvent.userError(SrErrorCode.DUP_CODE, derived.getCode()); } } daoFactory.getSpecimenRequirementDao().saveOrUpdate(derived, true); return ResponseEvent.response(SpecimenRequirementDetail.from(derived)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<SpecimenRequirementDetail> updateSpecimenRequirement(RequestEvent<SpecimenRequirementDetail> req) { try { SpecimenRequirementDetail detail = req.getPayload(); Long srId = detail.getId(); SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(srId); if (sr == null) { throw OpenSpecimenException.userError(SrErrorCode.NOT_FOUND); } AccessCtrlMgr.getInstance().ensureUpdateCpRights(sr.getCollectionProtocol()); SpecimenRequirement partial = srFactory.createForUpdate(sr.getLineage(), detail); if (isSpecimenClassOrTypeChanged(sr, partial)) { ensureSpecimensNotCollected(sr); } sr.update(partial); return ResponseEvent.response(SpecimenRequirementDetail.from(sr)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<SpecimenRequirementDetail> copySpecimenRequirement(RequestEvent<Long> req) { try { Long srId = req.getPayload(); SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(srId); if (sr == null) { throw OpenSpecimenException.userError(SrErrorCode.NOT_FOUND); } AccessCtrlMgr.getInstance().ensureUpdateCpRights(sr.getCollectionProtocol()); SpecimenRequirement copy = sr.deepCopy(null); daoFactory.getSpecimenRequirementDao().saveOrUpdate(copy, true); return ResponseEvent.response(SpecimenRequirementDetail.from(copy)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<SpecimenRequirementDetail> deleteSpecimenRequirement(RequestEvent<Long> req) { try { Long srId = req.getPayload(); SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(srId); if (sr == null) { throw OpenSpecimenException.userError(SrErrorCode.NOT_FOUND); } AccessCtrlMgr.getInstance().ensureUpdateCpRights(sr.getCollectionProtocol()); sr.delete(); daoFactory.getSpecimenRequirementDao().saveOrUpdate(sr); return ResponseEvent.response(SpecimenRequirementDetail.from(sr)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<Integer> getSrSpecimensCount(RequestEvent<Long> req) { try { Long srId = req.getPayload(); SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(srId); if (sr == null) { throw OpenSpecimenException.userError(SrErrorCode.NOT_FOUND); } return ResponseEvent.response( daoFactory.getSpecimenRequirementDao().getSpecimensCount(srId)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<CpReportSettingsDetail> getReportSettings(RequestEvent<CpQueryCriteria> req) { try { CpReportSettings settings = getReportSetting(req.getPayload()); if (settings == null) { return ResponseEvent.response(null); } AccessCtrlMgr.getInstance().ensureReadCpRights(settings.getCp()); return ResponseEvent.response(CpReportSettingsDetail.from(settings)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<CpReportSettingsDetail> saveReportSettings(RequestEvent<CpReportSettingsDetail> req) { try { CpReportSettings settings = rptSettingsFactory.createSettings(req.getPayload()); CollectionProtocol cp = settings.getCp(); AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp); CpReportSettings existing = daoFactory.getCpReportSettingsDao().getByCp(cp.getId()); if (existing == null) { existing = settings; } else { existing.update(settings); } daoFactory.getCpReportSettingsDao().saveOrUpdate(existing); return ResponseEvent.response(CpReportSettingsDetail.from(existing)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<CpReportSettingsDetail> deleteReportSettings(RequestEvent<CpQueryCriteria> req) { try { CpReportSettings settings = getReportSetting(req.getPayload()); if (settings == null) { return ResponseEvent.response(null); } AccessCtrlMgr.getInstance().ensureUpdateCpRights(settings.getCp()); settings.delete(); return ResponseEvent.response(CpReportSettingsDetail.from(settings)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<Boolean> generateReport(RequestEvent<CpQueryCriteria> req) { try { CpQueryCriteria crit = req.getPayload(); CollectionProtocol cp = getCollectionProtocol(crit.getId(), crit.getTitle(), crit.getShortTitle()); AccessCtrlMgr.getInstance().ensureReadCpRights(cp); CpReportSettings cpSettings = daoFactory.getCpReportSettingsDao().getByCp(cp.getId()); if (cpSettings != null && !cpSettings.isEnabled()) { return ResponseEvent.userError(CpErrorCode.RPT_DISABLED, cp.getShortTitle()); } taskExecutor.execute(new CpReportTask(cp.getId())); return ResponseEvent.response(true); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<File> getReportFile(Long cpId, String fileId) { try { CollectionProtocol cp = getCollectionProtocol(cpId, null, null); AccessCtrlMgr.getInstance().ensureReadCpRights(cp); File file = new CpReportGenerator().getDataFile(cpId, fileId); if (file == null) { return ResponseEvent.userError(CpErrorCode.RPT_FILE_NOT_FOUND); } return ResponseEvent.response(file); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<CpWorkflowCfgDetail> getWorkflows(RequestEvent<Long> req) { Long cpId = req.getPayload(); CollectionProtocol cp = null; CpWorkflowConfig cfg; if (cpId == null || cpId == -1L) { cfg = WorkflowUtil.getInstance().getSysWorkflows(); } else { cp = daoFactory.getCollectionProtocolDao().getById(cpId); if (cp == null) { return ResponseEvent.userError(CpErrorCode.NOT_FOUND); } cfg = daoFactory.getCollectionProtocolDao().getCpWorkflows(cpId); } if (cfg == null) { cfg = new CpWorkflowConfig(); cfg.setCp(cp); } return ResponseEvent.response(CpWorkflowCfgDetail.from(cfg)); } @Override @PlusTransactional public ResponseEvent<CpWorkflowCfgDetail> saveWorkflows(RequestEvent<CpWorkflowCfgDetail> req) { try { CpWorkflowCfgDetail input = req.getPayload(); CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(input.getCpId()); if (cp == null) { return ResponseEvent.userError(CpErrorCode.NOT_FOUND); } AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp); CpWorkflowConfig cfg = saveWorkflows(cp, input); return ResponseEvent.response(CpWorkflowCfgDetail.from(cfg)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<List<CollectionProtocolSummary>> getRegisterEnabledCps( List<String> siteNames, String searchTitle, int maxResults) { try { Set<Long> cpIds = AccessCtrlMgr.getInstance().getRegisterEnabledCpIds(siteNames); CpListCriteria crit = new CpListCriteria().title(searchTitle).maxResults(maxResults); if (cpIds != null && cpIds.isEmpty()) { return ResponseEvent.response(Collections.<CollectionProtocolSummary>emptyList()); } else if (cpIds != null) { crit.ids(new ArrayList<>(cpIds)); } return ResponseEvent.response(daoFactory.getCollectionProtocolDao().getCollectionProtocols(crit)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } } @Override @PlusTransactional public ResponseEvent<ListConfig> getCpListCfg(RequestEvent<Map<String, Object>> req) { return listSvc.getListCfg(req); } @Override @PlusTransactional public ResponseEvent<ListDetail> getList(RequestEvent<Map<String, Object>> req) { return listSvc.getList(req); } @Override @PlusTransactional public ResponseEvent<Integer> getListSize(RequestEvent<Map<String, Object>> req) { return listSvc.getListSize(req); } @Override @PlusTransactional public ResponseEvent<Collection<Object>> getListExprValues(RequestEvent<Map<String, Object>> req) { return listSvc.getListExprValues(req); } @Override @PlusTransactional public boolean toggleStarredCp(Long cpId, boolean starred) { try { CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId); if (cp == null) { throw OpenSpecimenException.userError(CpErrorCode.NOT_FOUND, cpId); } AccessCtrlMgr.getInstance().ensureReadCpRights(cp); if (starred) { starredItemSvc.save(getObjectName(), cp.getId()); } else { starredItemSvc.delete(getObjectName(), cp.getId()); } return true; } catch (Exception e) { if (e instanceof OpenSpecimenException) { throw e; } throw OpenSpecimenException.serverError(e); } } @Override public String getObjectName() { return CollectionProtocol.getEntityName(); } @Override @PlusTransactional public Map<String, Object> resolveUrl(String key, Object value) { if (key.equals("id")) { value = Long.valueOf(value.toString()); } return daoFactory.getCollectionProtocolDao().getCpIds(key, value); } @Override public String getAuditTable() { return "CAT_COLLECTION_PROTOCOL_AUD"; } @Override public void ensureReadAllowed(Long id) { CollectionProtocol cp = getCollectionProtocol(id, null, null); AccessCtrlMgr.getInstance().ensureReadCpRights(cp); } @Override public void afterPropertiesSet() throws Exception { listSvc.registerListConfigurator("cp-list-view", this::getCpListConfig); listSvc.registerListConfigurator("participant-list-view", this::getParticipantsListConfig); listSvc.registerListConfigurator("specimen-list-view", this::getSpecimenListConfig); exportSvc.registerObjectsGenerator("cpe", this::getEventsGenerator); exportSvc.registerObjectsGenerator("sr", this::getSpecimenRequirementsGenerator); } @Override public CpWorkflowConfig saveWorkflows(CollectionProtocol cp, CpWorkflowCfgDetail input) { CpWorkflowConfig cfg = daoFactory.getCollectionProtocolDao().getCpWorkflows(cp.getId()); if (cfg == null) { cfg = new CpWorkflowConfig(); cfg.setCp(cp); } if (!input.isPatch()) { cfg.getWorkflows().clear(); } if (input.getWorkflows() != null) { for (WorkflowDetail detail : input.getWorkflows().values()) { Workflow wf = new Workflow(); BeanUtils.copyProperties(detail, wf); cfg.getWorkflows().put(wf.getName(), wf); } } daoFactory.getCollectionProtocolDao().saveCpWorkflows(cfg); return cfg; } private CpListCriteria addCpListCriteria(CpListCriteria crit) { Set<SiteCpPair> siteCps = AccessCtrlMgr.getInstance().getReadableSiteCps(); return siteCps != null && siteCps.isEmpty() ? null : crit.siteCps(siteCps); } private CprListCriteria addCprListCriteria(CprListCriteria listCrit) { ParticipantReadAccess access = AccessCtrlMgr.getInstance().getParticipantReadAccess(listCrit.cpId()); if (!access.admin) { if (access.noAccessibleSites() || (!access.phiAccess && listCrit.hasPhiFields())) { return null; } } return listCrit.includePhi(access.phiAccess) .phiSiteCps(access.phiSiteCps) .siteCps(access.siteCps) .useMrnSites(AccessCtrlMgr.getInstance().isAccessRestrictedBasedOnMrn()); } private CollectionProtocol createCollectionProtocol(CollectionProtocolDetail detail, CollectionProtocol existing, boolean createCopy) { CollectionProtocol cp = null; if (!createCopy) { cp = cpFactory.createCollectionProtocol(detail); } else { cp = cpFactory.createCpCopy(detail, existing); } AccessCtrlMgr.getInstance().ensureCreateCpRights(cp); ensureUsersBelongtoCpSites(cp); OpenSpecimenException ose = new OpenSpecimenException(ErrorType.USER_ERROR); ensureUniqueTitle(null, cp, ose); ensureUniqueShortTitle(null, cp, ose); ensureUniqueCode(null, cp, ose); ensureUniqueCpSiteCode(cp, ose); ose.checkAndThrow(); daoFactory.getCollectionProtocolDao().saveOrUpdate(cp, true); cp.addOrUpdateExtension(); fixSopDocumentName(cp); copyWorkflows(existing, cp); return cp; } private void ensureUsersBelongtoCpSites(CollectionProtocol cp) { ensureCreatorBelongToCpSites(cp); } private void ensureCreatorBelongToCpSites(CollectionProtocol cp) { User user = AuthUtil.getCurrentUser(); if (user.isAdmin()) { return; } Set<Site> cpSites = cp.getRepositories(); if (cpSites.stream().anyMatch(cpSite -> !cpSite.getInstitute().equals(AuthUtil.getCurrentUserInstitute()))) { throw OpenSpecimenException.userError(CpErrorCode.CREATOR_DOES_NOT_BELONG_CP_REPOS); } } private void ensureUniqueTitle(CollectionProtocol existingCp, CollectionProtocol cp, OpenSpecimenException ose) { String title = cp.getTitle(); if (existingCp != null && existingCp.getTitle().equals(title)) { return; } CollectionProtocol dbCp = daoFactory.getCollectionProtocolDao().getCollectionProtocol(title); if (dbCp != null) { ose.addError(CpErrorCode.DUP_TITLE, title); } } private void ensureUniqueShortTitle(CollectionProtocol existingCp, CollectionProtocol cp, OpenSpecimenException ose) { String shortTitle = cp.getShortTitle(); if (existingCp != null && existingCp.getShortTitle().equals(shortTitle)) { return; } CollectionProtocol dbCp = daoFactory.getCollectionProtocolDao().getCpByShortTitle(shortTitle); if (dbCp != null) { ose.addError(CpErrorCode.DUP_SHORT_TITLE, shortTitle); } } private void ensureUniqueCode(CollectionProtocol existingCp, CollectionProtocol cp, OpenSpecimenException ose) { String code = cp.getCode(); if (StringUtils.isBlank(code)) { return; } if (existingCp != null && code.equals(existingCp.getCode())) { return; } CollectionProtocol dbCp = daoFactory.getCollectionProtocolDao().getCpByCode(code); if (dbCp != null) { ose.addError(CpErrorCode.DUP_CODE, code); } } private void ensureUniqueCpSiteCode(CollectionProtocol cp, OpenSpecimenException ose) { List<String> codes = Utility.<List<String>>collect(cp.getSites(), "code"); codes.removeAll(Arrays.asList(new String[] {null, ""})); Set<String> uniqueCodes = new HashSet<String>(codes); if (codes.size() != uniqueCodes.size()) { ose.addError(CpErrorCode.DUP_CP_SITE_CODES, codes); } } private void ensureSitesAreNotInUse(CollectionProtocol cp, Collection<Site> sites) { if (sites.isEmpty()) { return; } List<Long> siteIds = sites.stream().map(Site::getId).collect(Collectors.toList()); Map<String, Integer> counts = daoFactory.getCprDao().getParticipantsBySite(cp.getId(), siteIds); if (!counts.isEmpty()) { String siteLabels = counts.keySet().stream().collect(Collectors.joining(", ")); throw OpenSpecimenException.userError(CpErrorCode.USED_SITES, siteLabels, counts.size()); } } private void fixSopDocumentName(CollectionProtocol cp) { if (StringUtils.isBlank(cp.getSopDocumentName())) { return; } String[] nameParts = cp.getSopDocumentName().split("_", 2); if (nameParts[0].equals(cp.getId().toString())) { return; } try { UUID uuid = UUID.fromString(nameParts[0]); } catch (Exception e) { throw OpenSpecimenException.userError(CpErrorCode.INVALID_SOP_DOC, cp.getSopDocumentName()); } if (StringUtils.isBlank(nameParts[1])) { throw OpenSpecimenException.userError(CpErrorCode.INVALID_SOP_DOC, cp.getSopDocumentName()); } File src = new File(getSopDocDir() + File.separator + cp.getSopDocumentName()); if (!src.exists()) { throw OpenSpecimenException.userError(CpErrorCode.SOP_DOC_MOVED_OR_DELETED, cp.getSopDocumentName(), cp.getShortTitle()); } cp.setSopDocumentName(cp.getId() + "_" + nameParts[1]); File dest = new File(getSopDocDir() + File.separator + cp.getSopDocumentName()); src.renameTo(dest); } private void ensureConsentTierIsEmpty(CollectionProtocol existingCp, OpenSpecimenException ose) { if (CollectionUtils.isNotEmpty(existingCp.getConsentTier())) { ose.addError(CpErrorCode.CONSENT_TIER_FOUND, existingCp.getShortTitle()); } } private void importConsents(Long cpId, List<ConsentTierDetail> consents) { if (CollectionUtils.isEmpty(consents)) { return; } for (ConsentTierDetail consent : consents) { ConsentTierOp addOp = new ConsentTierOp(); addOp.setConsentTier(consent); addOp.setCpId(cpId); addOp.setOp(OP.ADD); ResponseEvent<ConsentTierDetail> resp = updateConsentTier(new RequestEvent<>(addOp)); resp.throwErrorIfUnsuccessful(); } } private void importEvents(String cpTitle, List<CollectionProtocolEventDetail> events) { if (CollectionUtils.isEmpty(events)) { return; } for (CollectionProtocolEventDetail event : events) { if (Status.isClosedOrDisabledStatus(event.getActivityStatus())) { continue; } event.setCollectionProtocol(cpTitle); ResponseEvent<CollectionProtocolEventDetail> resp = addEvent(new RequestEvent<>(event)); resp.throwErrorIfUnsuccessful(); Long eventId = resp.getPayload().getId(); importSpecimenReqs(eventId, null, event.getSpecimenRequirements()); } } private void importSpecimenReqs(Long eventId, Long parentSrId, List<SpecimenRequirementDetail> srs) { if (CollectionUtils.isEmpty(srs)) { return; } for (SpecimenRequirementDetail sr : srs) { if (Status.isClosedOrDisabledStatus(sr.getActivityStatus())) { continue; } sr.setEventId(eventId); if (sr.getLineage().equals(Specimen.NEW)) { ResponseEvent<SpecimenRequirementDetail> resp = addSpecimenRequirement(new RequestEvent<>(sr)); resp.throwErrorIfUnsuccessful(); importSpecimenReqs(eventId, resp.getPayload().getId(), sr.getChildren()); } else if (parentSrId != null && sr.getLineage().equals(Specimen.ALIQUOT)) { AliquotSpecimensRequirement aliquotReq = sr.toAliquotRequirement(parentSrId, 1); List<SpecimenRequirement> aliquots = createAliquots(aliquotReq); if (StringUtils.isNotBlank(sr.getCode())) { aliquots.get(0).setCode(sr.getCode()); } importSpecimenReqs(eventId, aliquots.get(0).getId(), sr.getChildren()); } else if (parentSrId != null && sr.getLineage().equals(Specimen.DERIVED)) { DerivedSpecimenRequirement derivedReq = sr.toDerivedRequirement(parentSrId); ResponseEvent<SpecimenRequirementDetail> resp = createDerived(new RequestEvent<DerivedSpecimenRequirement>(derivedReq)); resp.throwErrorIfUnsuccessful(); importSpecimenReqs(eventId, resp.getPayload().getId(), sr.getChildren()); } } } private void ensureSrIsNotClosed(SpecimenRequirement sr) { if (!sr.isClosed()) { return; } String key = sr.getCode(); if (StringUtils.isBlank(key)) { key = sr.getName(); } if (StringUtils.isBlank(key)) { key = sr.getId().toString(); } throw OpenSpecimenException.userError(SrErrorCode.CLOSED, key); } private List<SpecimenRequirement> createAliquots(AliquotSpecimensRequirement requirement) { List<SpecimenRequirement> aliquots = srFactory.createAliquots(requirement); SpecimenRequirement aliquot = aliquots.iterator().next(); AccessCtrlMgr.getInstance().ensureUpdateCpRights(aliquot.getCollectionProtocol()); SpecimenRequirement parent = aliquot.getParentSpecimenRequirement(); if (StringUtils.isNotBlank(requirement.getCode())) { setAliquotCode(parent, aliquots, requirement.getCode()); } parent.addChildRequirements(aliquots); daoFactory.getSpecimenRequirementDao().saveOrUpdate(parent, true); return aliquots; } private void importWorkflows(Long cpId, Map<String, WorkflowDetail> workflows) { CpWorkflowCfgDetail input = new CpWorkflowCfgDetail(); input.setCpId(cpId); input.setWorkflows(workflows); ResponseEvent<CpWorkflowCfgDetail> resp = saveWorkflows(new RequestEvent<>(input)); resp.throwErrorIfUnsuccessful(); } private void copyWorkflows(CollectionProtocol srcCp, CollectionProtocol dstCp) { if (srcCp == null) { return; } CpWorkflowConfig srcWfCfg = daoFactory.getCollectionProtocolDao().getCpWorkflows(srcCp.getId()); if (srcWfCfg != null) { CpWorkflowConfig newConfig = new CpWorkflowConfig(); newConfig.setCp(dstCp); newConfig.setWorkflows(srcWfCfg.getWorkflows()); daoFactory.getCollectionProtocolDao().saveCpWorkflows(newConfig); } } private CpConsentTier getConsentTier(ConsentTierDetail consentTierDetail) { CollectionProtocolDao cpDao = daoFactory.getCollectionProtocolDao(); CpConsentTier consentTier = null; if (consentTierDetail.getId() != null) { consentTier = cpDao.getConsentTier(consentTierDetail.getId()); } else if (StringUtils.isNotBlank(consentTierDetail.getStatement()) && consentTierDetail.getCpId() != null ) { consentTier = cpDao.getConsentTierByStatement(consentTierDetail.getCpId(), consentTierDetail.getStatement()); } if (consentTier == null) { throw OpenSpecimenException.userError(CpErrorCode.CONSENT_TIER_NOT_FOUND); } return consentTier; } private void ensureUniqueConsentStatement(ConsentTierDetail consentTierDetail, CollectionProtocol cp) { Predicate<CpConsentTier> findFn; if (consentTierDetail.getStatementId() != null) { findFn = (t) -> t.getStatement().getId().equals(consentTierDetail.getStatementId()); } else if (StringUtils.isNotBlank(consentTierDetail.getStatementCode())) { findFn = (t) -> t.getStatement().getCode().equals(consentTierDetail.getStatementCode()); } else if (StringUtils.isNotBlank(consentTierDetail.getStatement())) { findFn = (t) -> t.getStatement().getStatement().equals(consentTierDetail.getStatement()); } else { throw OpenSpecimenException.userError(ConsentStatementErrorCode.CODE_REQUIRED); } CpConsentTier tier = cp.getConsentTier().stream().filter(findFn).findFirst().orElse(null); if (tier != null && !tier.getId().equals(consentTierDetail.getId())) { throw OpenSpecimenException.userError(CpErrorCode.DUP_CONSENT, tier.getStatement().getCode(), cp.getShortTitle()); } } private CpConsentTier getConsentTierObj(Long id, ConsentStatement stmt) { CpConsentTier tier = new CpConsentTier(); tier.setId(id); tier.setStatement(stmt); return tier; } private void ensureSpecimensNotCollected(SpecimenRequirement sr) { int count = daoFactory.getSpecimenRequirementDao().getSpecimensCount(sr.getId()); if (count > 0) { throw OpenSpecimenException.userError(SrErrorCode.CANNOT_CHANGE_CLASS_OR_TYPE); } } private boolean isSpecimenClassOrTypeChanged(SpecimenRequirement existingSr, SpecimenRequirement sr) { return !existingSr.getSpecimenClass().equals(sr.getSpecimenClass()) || !existingSr.getSpecimenType().equals(sr.getSpecimenType()); } private void setAliquotCode(SpecimenRequirement parent, List<SpecimenRequirement> aliquots, String code) { Set<String> codes = new HashSet<String>(); CollectionProtocolEvent cpe = parent.getCollectionProtocolEvent(); for (SpecimenRequirement sr : cpe.getSpecimenRequirements()) { if (StringUtils.isNotBlank(sr.getCode())) { codes.add(sr.getCode()); } } int count = 1; for (SpecimenRequirement sr : aliquots) { while (!codes.add(code + count)) { count++; } sr.setCode(code + count++); } } private CollectionProtocol getCollectionProtocol(String shortTitle) { return getCollectionProtocol(null, null, shortTitle); } private CollectionProtocol getCollectionProtocol(Long id, String title, String shortTitle) { CollectionProtocol cp = null; if (id != null) { cp = daoFactory.getCollectionProtocolDao().getById(id); } else if (StringUtils.isNotBlank(title)) { cp = daoFactory.getCollectionProtocolDao().getCollectionProtocol(title); } else if (StringUtils.isNoneBlank(shortTitle)) { cp = daoFactory.getCollectionProtocolDao().getCpByShortTitle(shortTitle); } if (cp == null) { throw OpenSpecimenException.userError(CpErrorCode.NOT_FOUND); } return cp; } private void mergeCprIntoCp(CollectionProtocolRegistration srcCpr, CollectionProtocol tgtCp) { // Step 1: Get a matching CPR either by PPID or participant ID CollectionProtocolRegistration tgtCpr = daoFactory.getCprDao().getCprByPpid(tgtCp.getId(), srcCpr.getPpid()); if (tgtCpr == null) { tgtCpr = srcCpr.getParticipant().getCpr(tgtCp); } // Step 2: Map all visits of source CP registrations to first event of target CP // Further mark all created specimens as unplanned CollectionProtocolEvent firstCpe = tgtCp.firstEvent(); for (Visit visit : srcCpr.getVisits()) { visit.setCpEvent(firstCpe); visit.getSpecimens().forEach(s -> s.setSpecimenRequirement(null)); } // Step 3: Attach registrations to target CP if (tgtCpr == null) { // case 1: No matching registration was found in target CP; therefore make source // registration as part of target CP srcCpr.setCollectionProtocol(tgtCp); } else { // case 2: Matching registration was found in target CP; therefore do following // 2.1 Move all visits of source CP registration to target CP registration // 2.2 Finally delete source CP registration tgtCpr.addVisits(srcCpr.getVisits()); srcCpr.getVisits().clear(); srcCpr.delete(); } } private void ensureMergeableCps(CollectionProtocol srcCp, CollectionProtocol tgtCp) { ArrayList<String> notSameLabels = new ArrayList<>(); ensureBlankOrSame(srcCp.getPpidFormat(), tgtCp.getPpidFormat(), PPID_MSG, notSameLabels); ensureBlankOrSame(srcCp.getVisitNameFormat(), tgtCp.getVisitNameFormat(), VISIT_NAME_MSG, notSameLabels); ensureBlankOrSame(srcCp.getSpecimenLabelFormat(), tgtCp.getSpecimenLabelFormat(), SPECIMEN_LABEL_MSG, notSameLabels); ensureBlankOrSame(srcCp.getDerivativeLabelFormat(), tgtCp.getDerivativeLabelFormat(), DERIVATIVE_LABEL_MSG, notSameLabels); ensureBlankOrSame(srcCp.getAliquotLabelFormat(), tgtCp.getAliquotLabelFormat(), ALIQUOT_LABEL_MSG, notSameLabels); if (!notSameLabels.isEmpty()) { throw OpenSpecimenException.userError( CpErrorCode.CANNOT_MERGE_FMT_DIFFERS, srcCp.getShortTitle(), tgtCp.getShortTitle(), notSameLabels); } } private void ensureBlankOrSame(String srcLabelFmt, String tgtLabelFmt, String labelKey, List<String> notSameLabels) { if (!StringUtils.isBlank(tgtLabelFmt) && !tgtLabelFmt.equals(srcLabelFmt)) { notSameLabels.add(getMsg(labelKey)); } } private boolean forceDeleteCps(final List<CollectionProtocol> cps, final String reason) throws Exception { final Authentication auth = AuthUtil.getAuth(); Future<Boolean> result = taskExecutor.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { SecurityContextHolder.getContext().setAuthentication(auth); cps.forEach(cp -> forceDeleteCp(cp, reason)); return true; } }); boolean completed = false; try { completed = result.get(30, TimeUnit.SECONDS); } catch (TimeoutException ex) { completed = false; } return completed; } private void forceDeleteCp(CollectionProtocol cp, String reason) { while (deleteRegistrations(cp)); deleteCp(cp, reason); } private boolean deleteCps(List<CollectionProtocol> cps, String reason) { cps.forEach(cp -> deleteCp(cp, reason)); return true; } @PlusTransactional private boolean deleteCp(CollectionProtocol cp, String reason) { boolean success = false; String stackTrace = null; CollectionProtocol deletedCp = new CollectionProtocol(); try { // refresh cp, as it could have been fetched in another transaction // if in same transaction, then it will be obtained from session cp = daoFactory.getCollectionProtocolDao().getById(cp.getId()); BeanUtils.copyProperties(cp, deletedCp); removeContainerRestrictions(cp); removeCpRoles(cp); cp.setOpComments(reason); cp.delete(); DeleteLogUtil.getInstance().log(cp); EventPublisher.getInstance().publish(new CollectionProtocolSavedEvent(cp)); success = true; } catch (Exception ex) { stackTrace = ExceptionUtils.getStackTrace(ex); if (ex instanceof OpenSpecimenException) { throw ex; } else { throw OpenSpecimenException.serverError(ex); } } finally { notifyUsersOnCpDelete(deletedCp, success, stackTrace); } return true; } @PlusTransactional private boolean deleteRegistrations(CollectionProtocol cp) { List<CollectionProtocolRegistration> cprs = daoFactory.getCprDao().getCprsByCpId(cp.getId(), 0, 10); cprs.forEach(cpr -> cpr.delete(false)); return cprs.size() == 10; } private void removeContainerRestrictions(CollectionProtocol cp) { Set<StorageContainer> containers = cp.getStorageContainers(); for (StorageContainer container : containers) { container.removeCpRestriction(cp); } cp.setStorageContainers(Collections.EMPTY_SET); } private void removeCpRoles(CollectionProtocol cp) { rbacSvc.removeCpRoles(cp.getId()); } private void notifyUsersOnCpCreate(CollectionProtocol cp) { notifyUsersOnCpOp(cp, cp.getRepositories(), OP_CP_CREATED); } private void notifyUsersOnCpUpdate(CollectionProtocol cp, Collection<Site> addedSites, Collection<Site> removedSites) { notifyUsersOnCpOp(cp, removedSites, OP_CP_SITE_REMOVED); notifyUsersOnCpOp(cp, addedSites, OP_CP_SITE_ADDED); } private void notifyUsersOnCpDelete(CollectionProtocol cp, boolean success, String stackTrace) { if (success) { notifyUsersOnCpOp(cp, cp.getRepositories(), OP_CP_DELETED); } else { User currentUser = AuthUtil.getCurrentUser(); String[] rcpts = {currentUser.getEmailAddress(), cp.getPrincipalInvestigator().getEmailAddress()}; String[] subjParams = new String[] {cp.getShortTitle()}; Map<String, Object> props = new HashMap<>(); props.put("cp", cp); props.put("$subject", subjParams); props.put("user", currentUser); props.put("error", stackTrace); EmailUtil.getInstance().sendEmail(CP_DELETE_FAILED_EMAIL_TMPL, rcpts, null, props); } } private void notifyUsersOnCpOp(CollectionProtocol cp, Collection<Site> sites, int op) { Map<String, Object> emailProps = new HashMap<>(); emailProps.put("$subject", new Object[] {cp.getShortTitle(), op}); emailProps.put("cp", cp); emailProps.put("op", op); emailProps.put("currentUser", AuthUtil.getCurrentUser()); emailProps.put("ccAdmin", false); if (op == OP_CP_CREATED || op == OP_CP_DELETED) { List<User> superAdmins = AccessCtrlMgr.getInstance().getSuperAdmins(); notifyUsers(superAdmins, CP_OP_EMAIL_TMPL, emailProps, (op == OP_CP_CREATED) ? "CREATE" : "DELETE"); } for (Site site : sites) { String siteName = site.getName(); emailProps.put("siteName", siteName); emailProps.put("$subject", new Object[] {siteName, op, cp.getShortTitle()}); notifyUsers(site.getCoordinators(), CP_SITE_UPDATED_EMAIL_TMPL, emailProps, "UPDATE"); } } private void notifyUsers(Collection<User> users, String template, Map<String, Object> emailProps, String notifOp) { for (User rcpt : users) { emailProps.put("rcpt", rcpt); EmailUtil.getInstance().sendEmail(template, new String[] {rcpt.getEmailAddress()}, null, emailProps); } CollectionProtocol cp = (CollectionProtocol)emailProps.get("cp"); Object[] subjParams = (Object[])emailProps.get("$subject"); Notification notif = new Notification(); notif.setEntityType(CollectionProtocol.getEntityName()); notif.setEntityId(cp.getId()); notif.setOperation(notifOp); notif.setCreatedBy(AuthUtil.getCurrentUser()); notif.setCreationTime(Calendar.getInstance().getTime()); notif.setMessage(MessageUtil.getInstance().getMessage(template + "_subj", subjParams)); NotifUtil.getInstance().notify(notif, Collections.singletonMap("cp-overview", users)); } private SubjectRoleOpNotif getNotifReq(CollectionProtocol cp, String role, List<User> notifUsers, User user, String cpOp, String roleOp) { SubjectRoleOpNotif notifReq = new SubjectRoleOpNotif(); notifReq.setAdmins(notifUsers); notifReq.setAdminNotifMsg("cp_admin_notif_role_" + roleOp.toLowerCase()); notifReq.setAdminNotifParams(new Object[] { user.getFirstName(), user.getLastName(), role, cp.getShortTitle(), user.getInstitute().getName() }); notifReq.setUser(user); if (cpOp.equals("DELETE")) { notifReq.setSubjectNotifMsg("cp_delete_user_notif_role"); notifReq.setSubjectNotifParams(new Object[] { cp.getShortTitle(), role }); } else { notifReq.setSubjectNotifMsg("cp_user_notif_role_" + roleOp.toLowerCase()); notifReq.setSubjectNotifParams(new Object[] { role, cp.getShortTitle(), user.getInstitute().getName() }); } notifReq.setEndUserOp(cpOp); return notifReq; } private String getMsg(String code) { return MessageUtil.getInstance().getMessage(code); } private String getSopDocDir() { String defDir = ConfigUtil.getInstance().getDataDir() + File.separator + "cp-sop-documents"; String dir = ConfigUtil.getInstance().getStrSetting(ConfigParams.MODULE, ConfigParams.CP_SOP_DOCS_DIR, defDir); new File(dir).mkdirs(); return dir + File.separator; } private CpReportSettings getReportSetting(CpQueryCriteria crit) { CpReportSettings settings = null; if (crit.getId() != null) { settings = daoFactory.getCpReportSettingsDao().getByCp(crit.getId()); } else if (StringUtils.isNotBlank(crit.getShortTitle())) { settings = daoFactory.getCpReportSettingsDao().getByCp(crit.getShortTitle()); } return settings; } private ListConfig getSpecimenListConfig(Map<String, Object> listReq) { ListConfig cfg = getListConfig(listReq, "specimen-list-view", "Specimen"); if (cfg == null) { return null; } Column id = new Column(); id.setExpr("Specimen.id"); id.setCaption("specimenId"); cfg.setPrimaryColumn(id); Column type = new Column(); type.setExpr("Specimen.type"); type.setCaption("specimenType"); Column specimenClass = new Column(); specimenClass.setExpr("Specimen.class"); specimenClass.setCaption("specimenClass"); List<Column> hiddenColumns = new ArrayList<>(); hiddenColumns.add(id); hiddenColumns.add(type); hiddenColumns.add(specimenClass); cfg.setHiddenColumns(hiddenColumns); Long cpId = (Long)listReq.get("cpId"); List<SiteCpPair> siteCps = AccessCtrlMgr.getInstance().getReadAccessSpecimenSiteCps(cpId); if (siteCps == null) { // Admin; hence no additional restrictions return cfg; } if (siteCps.isEmpty()) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } boolean useMrnSites = AccessCtrlMgr.getInstance().isAccessRestrictedBasedOnMrn(); String restrictions = BiospecimenDaoHelper.getInstance().getSiteCpsCondAql(siteCps, useMrnSites); cfg.setRestriction(restrictions); cfg.setDistinct(true); return cfg; } private ListConfig getCpListConfig(Map<String, Object> listReq) { ListConfig cfg = getListConfig(listReq, "cp-list-view", "CollectionProtocol"); if (cfg == null) { return null; } List<Column> hiddenColumns = new ArrayList<>(); Column id = new Column(); id.setExpr("CollectionProtocol.id"); id.setCaption("cpId"); cfg.setPrimaryColumn(id); hiddenColumns.add(id); Column catalogId = new Column(); catalogId.setExpr("CollectionProtocol.catalogId"); catalogId.setCaption("catalogId"); hiddenColumns.add(catalogId); Column starred = new Column(); starred.setExpr("CollectionProtocol.__userLabels.userId"); starred.setCaption("starred"); starred.setDirection(isOracle() ? "asc" : "desc"); hiddenColumns.add(starred); cfg.setHiddenColumns(hiddenColumns); List<Column> fixedColumns = new ArrayList<>(); Column participantsCount = new Column(); participantsCount.setCaption("Participants"); participantsCount.setExpr("count(Participant.id)"); fixedColumns.add(participantsCount); Column specimensCount = new Column(); specimensCount.setCaption("Specimens"); specimensCount.setExpr("count(Specimen.id)"); fixedColumns.add(specimensCount); cfg.setFixedColumns(fixedColumns); cfg.setFixedColumnsGenerator( (rows) -> { if (rows == null || rows.isEmpty()) { return rows; } Map<Long, Row> cpRows = new HashMap<>(); for (Row row : rows) { Long cpId = Long.parseLong((String) row.getHidden().get("cpId")); cpRows.put(cpId, row); } List<Object[]> dbRows = sessionFactory.getCurrentSession() .getNamedQuery(CollectionProtocol.class.getName() + ".getParticipantAndSpecimenCount") .setParameterList("cpIds", cpRows.keySet()) .list(); for (Object[] dbRow : dbRows) { int idx = -1; Long cpId = ((Number) dbRow[++idx]).longValue(); cpRows.get(cpId).setFixedData(new Object[] {dbRow[++idx], dbRow[++idx]}); } return rows; } ); List<Column> orderBy = cfg.getOrderBy(); if (orderBy == null) { orderBy = new ArrayList<>(); cfg.setOrderBy(orderBy); } orderBy.add(0, starred); cfg.setRestriction(String.format(USR_LABELS_RESTRICTION, AuthUtil.getCurrentUser().getId())); Set<SiteCpPair> cpSites = AccessCtrlMgr.getInstance().getReadableSiteCps(); if (cpSites == null) { return cfg; } if (cpSites.isEmpty()) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } String cpSitesRestriction = BiospecimenDaoHelper.getInstance().getSiteCpsCondAqlForCps(cpSites); if (StringUtils.isNotBlank(cpSitesRestriction)) { cfg.setRestriction(String.format(AND_COND, cfg.getRestriction(), cpSitesRestriction)); cfg.setDistinct(true); } return cfg; } private ListConfig getParticipantsListConfig(Map<String, Object> listReq) { ListConfig cfg = getListConfig(listReq, "participant-list-view", "Participant"); if (cfg == null) { return null; } Column id = new Column(); id.setExpr("Participant.id"); id.setCaption("cprId"); cfg.setPrimaryColumn(id); cfg.setHiddenColumns(Collections.singletonList(id)); Long cpId = (Long)listReq.get("cpId"); ParticipantReadAccess access = AccessCtrlMgr.getInstance().getParticipantReadAccess(cpId); if (access.admin) { return cfg; } if (access.siteCps == null || access.siteCps.isEmpty()) { throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED); } boolean useMrnSites = AccessCtrlMgr.getInstance().isAccessRestrictedBasedOnMrn(); cfg.setRestriction(BiospecimenDaoHelper.getInstance().getSiteCpsCondAql(access.siteCps, useMrnSites)); cfg.setDistinct(true); return cfg; } private ListConfig getListConfig(Map<String, Object> listReq, String listName, String drivingForm) { Long cpId = (Long) listReq.get("cpId"); if (cpId == null) { cpId = (Long) listReq.get("objectId"); } Workflow workflow = getWorkFlow(cpId, listName); if (workflow == null) { return null; } ListConfig listCfg = new ObjectMapper().convertValue(workflow.getData(), ListConfig.class); listCfg.setCpId(cpId); listCfg.setDrivingForm(drivingForm); setListLimit(listReq, listCfg); Boolean includeCount = (Boolean)listReq.get("includeCount"); listCfg.setIncludeCount(includeCount == null ? false : includeCount); return listCfg; } private Workflow getWorkFlow(Long cpId, String name) { Workflow workflow = null; CpWorkflowConfig cfg = null; if (cpId != null) { cfg = daoFactory.getCollectionProtocolDao().getCpWorkflows(cpId); } if (cfg != null) { workflow = cfg.getWorkflows().get(name); } if (workflow == null) { workflow = getSysWorkflow(name); } return workflow; } private Workflow getSysWorkflow(String name) { return WorkflowUtil.getInstance().getSysWorkflow(name); } private void setListLimit(Map<String, Object> listReq, ListConfig cfg) { Integer startAt = (Integer)listReq.get("startAt"); if (startAt == null) { startAt = 0; } Integer maxResults = (Integer)listReq.get("maxResults"); if (maxResults == null) { maxResults = 100; } cfg.setStartAt(startAt); cfg.setMaxResults(maxResults); } private ConsentStatement getStatement(Long id, String code, String statement) { ConsentStatement stmt = null; Object key = null; if (id != null) { key = id; stmt = daoFactory.getConsentStatementDao().getById(id); } else if (StringUtils.isNotBlank(code)) { key = code; stmt = daoFactory.getConsentStatementDao().getByCode(code); } else if (StringUtils.isNotBlank(statement)) { key = statement; stmt = daoFactory.getConsentStatementDao().getByStatement(statement); } if (key == null) { throw OpenSpecimenException.userError(ConsentStatementErrorCode.CODE_REQUIRED); } else if (stmt == null) { throw OpenSpecimenException.userError(ConsentStatementErrorCode.NOT_FOUND, key); } return stmt; } private boolean isOracle() { String dbType = AppProperties.getInstance().getProperties() .getProperty("database.type", "mysql") .toLowerCase(); return dbType.equalsIgnoreCase("oracle"); } private void createExtensions(List<CollectionProtocolRegistration> cprs) { Map<CollectionProtocol, List<CollectionProtocolRegistration>> cpRegs = new HashMap<>(); cprs.forEach(cpr -> cpRegs.computeIfAbsent(cpr.getCollectionProtocol(), (k) -> new ArrayList<>()).add(cpr)); cpRegs.forEach((cp, regs) -> DeObject.createExtensions( true, Participant.EXTN, cp.getId(), regs.stream().map(CollectionProtocolRegistration::getParticipant).collect(Collectors.toList()) ) ); } private Function<ExportJob, List<? extends Object>> getEventsGenerator() { return new Function<ExportJob, List<? extends Object>>() { private boolean endOfEvents; @Override public List<CollectionProtocolEventDetail> apply(ExportJob job) { String cpIdStr = job.param("cpId"); if (endOfEvents || StringUtils.isBlank(cpIdStr)) { return Collections.emptyList(); } Long cpId = Long.parseLong(cpIdStr); CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId); endOfEvents = true; return CollectionProtocolEventDetail.from(cp.getOrderedCpeList(), false); } }; } private Function<ExportJob, List<? extends Object>> getSpecimenRequirementsGenerator() { return new Function<ExportJob, List<? extends Object>>() { private boolean endOfSrs; @Override public List<SpecimenRequirementDetail> apply(ExportJob job) { String cpIdStr = job.param("cpId"); if (endOfSrs || StringUtils.isBlank(cpIdStr)) { return Collections.emptyList(); } Long cpId = Long.parseLong(cpIdStr); CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId); List<SpecimenRequirementDetail> result = new ArrayList<>(); for (CollectionProtocolEvent cpe : cp.getOrderedCpeList()) { List<SpecimenRequirement> parents = new ArrayList<>(cpe.getOrderedTopLevelAnticipatedSpecimens()); while (!parents.isEmpty()) { SpecimenRequirement sr = parents.remove(0); parents.addAll(0, sr.getOrderedChildRequirements()); SpecimenRequirementDetail detail = SpecimenRequirementDetail.from(sr, false); detail.setCpShortTitle(cp.getShortTitle()); detail.setEventLabel(cpe.getEventLabel()); result.add(detail); } } endOfSrs = true; return result; } }; } private static final String PPID_MSG = "cp_ppid"; private static final String VISIT_NAME_MSG = "cp_visit_name"; private static final String SPECIMEN_LABEL_MSG = "cp_specimen_label"; private static final String DERIVATIVE_LABEL_MSG = "cp_derivative_label"; private static final String ALIQUOT_LABEL_MSG = "cp_aliquot_label"; private static final String CP_OP_EMAIL_TMPL = "cp_op"; private static final String CP_DELETE_FAILED_EMAIL_TMPL = "cp_delete_failed"; private static final String CP_SITE_UPDATED_EMAIL_TMPL = "cp_site_updated"; private static final int OP_CP_SITE_ADDED = -1; private static final int OP_CP_SITE_REMOVED = 1; private static final int OP_CP_CREATED = 0; private static final int OP_CP_DELETED = 2; private static final String USR_LABELS_RESTRICTION = "(CollectionProtocol.__userLabels.userId not exists or CollectionProtocol.__userLabels.userId = %d)"; private static final String AND_COND = "(%s) and (%s)"; }
package gov.nih.nci.cananolab.util; import java.util.HashMap; import java.util.Map; public class Constants { public static final String DOMAIN_MODEL_NAME = "caNanoLab"; public static final String SDK_BEAN_JAR = "caNanoLabSDK-beans.jar"; public static final String CSM_APP_NAME = "caNanoLab"; public static final String DATE_FORMAT = "MM/dd/yyyy"; public static final String ACCEPT_DATE_FORMAT = "MM/dd/yy"; // File upload public static final String FILEUPLOAD_PROPERTY = "caNanoLab.properties"; public static final String UNCOMPRESSED_FILE_DIRECTORY = "decompressedFiles"; public static final String EMPTY = "N/A"; // caNanoLab property file public static final String CANANOLAB_PROPERTY = "caNanoLab.properties"; public static final String BOOLEAN_YES = "Yes"; public static final String BOOLEAN_NO = "No"; public static final String[] BOOLEAN_CHOICES = new String[] { BOOLEAN_YES, BOOLEAN_NO }; public static final String DEFAULT_SAMPLE_PREFIX = "NANO-"; public static final String DEFAULT_APP_OWNER = "NCICB"; public static final String APP_OWNER; public static final String VIEW_COL_DELIMITER = "~~~"; public static final String VIEW_CLASSNAME_DELIMITER = "!!!"; static { String appOwner = PropertyUtils.getProperty(CANANOLAB_PROPERTY, "applicationOwner").trim(); if (appOwner == null || appOwner.length() == 0) appOwner = DEFAULT_APP_OWNER; APP_OWNER = appOwner; } public static final String SAMPLE_PREFIX; static { String samplePrefix = PropertyUtils.getProperty(CANANOLAB_PROPERTY, "samplePrefix"); if (samplePrefix == null || samplePrefix.length() == 0) samplePrefix = DEFAULT_SAMPLE_PREFIX; SAMPLE_PREFIX = samplePrefix; } public static final String GRID_INDEX_SERVICE_URL; static { String gridIndexServiceURL = PropertyUtils.getProperty( CANANOLAB_PROPERTY, "gridIndexServiceURL").trim(); GRID_INDEX_SERVICE_URL = gridIndexServiceURL; } /* * The following Strings are nano specific * */ public static final String[] DEFAULT_CHARACTERIZATION_SOURCES = new String[] { APP_OWNER }; public static final String ASSOCIATED_FILE = "Other Associated File"; public static final String PROTOCOL_FILE = "Protocol File"; public static final String FOLDER_PARTICLE = "particles"; // public static final String FOLDER_REPORT = "reports"; public static final String FOLDER_PUBLICATION = "publications"; public static final String FOLDER_PROTOCOL = "protocols"; public static final String[] DEFAULT_POLYMER_INITIATORS = new String[] { "Free Radicals", "Peroxide" }; public static final String CHARACTERIZATION_FILE = "characterizationFile"; public static final int MAX_VIEW_TITLE_LENGTH = 23; public static final String CSM_DATA_CURATOR = APP_OWNER + "_DataCurator"; public static final String CSM_RESEARCHER = APP_OWNER + "_Researcher"; public static final String CSM_ADMIN = APP_OWNER + "_Administrator"; public static final String CSM_PUBLIC_GROUP = "Public"; public static final String[] VISIBLE_GROUPS = new String[] { CSM_DATA_CURATOR, CSM_RESEARCHER }; public static final String AUTO_COPY_ANNOTATION_PREFIX = "COPY"; public static final String AUTO_COPY_ANNNOTATION_VIEW_COLOR = "red"; public static final String CSM_READ_ROLE = "R"; public static final String CSM_DELETE_ROLE = "D"; public static final String CSM_EXECUTE_ROLE = "E"; public static final String CSM_CURD_ROLE = "CURD"; public static final String CSM_CUR_ROLE = "CUR"; public static final String CSM_READ_PRIVILEGE = "READ"; public static final String CSM_EXECUTE_PRIVILEGE = "EXECUTE"; public static final String CSM_DELETE_PRIVILEGE = "DELETE"; public static final String CSM_CREATE_PRIVILEGE = "CREATE"; public static final String CSM_PG_PROTOCOL = "protocol"; public static final String CSM_PG_PARTICLE = "nanoparticle"; public static final String CSM_PG_PUBLICATION = "publication"; public static final String PHYSICAL_CHARACTERIZATION_CLASS_NAME = "Physical Characterization"; public static final String IN_VITRO_CHARACTERIZATION_CLASS_NAME = "In Vitro Characterization"; public static final short CHARACTERIZATION_ROOT_DISPLAY_ORDER = 0; // This is a hack to querying based on .class to work in case of multi-level // inheritance with joined-subclass // TODO check the order generated in the hibernate mapping file for each // release public static final Map<String, Integer> FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP = new HashMap<String, Integer>(); static { FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP.put(new String( "OtherFunctionalizingEntity"), new Integer(0)); FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP.put(new String("Biopolymer"), new Integer(1)); FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP.put(new String("Antibody"), new Integer(2)); FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP.put(new String( "SmallMolecule"), new Integer(3)); } /* image file name extension */ public static final String[] IMAGE_FILE_EXTENSIONS = { "AVS", "BMP", "CIN", "DCX", "DIB", "DPX", "FITS", "GIF", "ICO", "JFIF", "JIF", "JPE", "JPEG", "JPG", "MIFF", "OTB", "P7", "PALM", "PAM", "PBM", "PCD", "PCDS", "PCL", "PCX", "PGM", "PICT", "PNG", "PNM", "PPM", "PSD", "RAS", "SGI", "SUN", "TGA", "TIF", "TIFF", "WMF", "XBM", "XPM", "YUV", "CGM", "DXF", "EMF", "EPS", "MET", "MVG", "ODG", "OTG", "STD", "SVG", "SXD", "WMF" }; public static final String[] PRIVATE_DISPATCHES = { "create", "delete", "setupNew", "setupUpdate", "summaryEdit", "add", "remove", "save" }; public static final String PHYSICOCHEMICAL_ASSAY_PROTOCOL = "physico-chemical assay"; public static final String INVITRO_ASSAY_PROTOCOL = "in vitro assay"; public static final String NODE_UNAVAILABLE = "Unable to connect to the grid location that you selected"; // default discovery internal for grid index server public static final int DEFAULT_GRID_DISCOVERY_INTERVAL_IN_MINS = 20; public static final String DOMAIN_MODEL_VERSION = "1.4"; public static final String GRID_SERVICE_PATH = "wsrf-canano/services/cagrid/CaNanoLabService"; // Default date format for exported file name. public static final String EXPORT_FILE_DATE_FORMAT = "yyyyMMdd_HH-mm-ss-SSS"; // String for local search. public static final String LOCAL_SITE = APP_OWNER; // String for file repository entry in property file. public static final String FILE_REPOSITORY_DIR = "fileRepositoryDir"; // String for site name entry in property file. public static final String SITE_NAME = "siteName"; // String for site logo entry in property file. public static final String SITE_LOGO = "siteLogo"; // File name of site logo. public static final String SITE_LOGO_FILENAME = "siteLogo.gif"; // Maximum file size of site logo. public static final int MAX_LOGO_SIZE = 65536; // LOCATION public static final String LOCATION = "location"; }
package io.hawt.sample; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import io.hawt.sample.infinispan.InfinispanDemo; import org.apache.camel.CamelException; import org.apache.camel.util.CamelContextHelper; import org.eclipse.jetty.jmx.MBeanContainer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Slf4jLog; import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.WebInfConfiguration; import org.eclipse.jetty.webapp.WebXmlConfiguration; import org.fusesource.fabric.service.FabricServiceImpl; import org.fusesource.fabric.zookeeper.IZKClient; import org.fusesource.fabric.zookeeper.spring.ZKClientFactoryBean; import org.mortbay.jetty.plugin.JettyWebAppContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.management.MBeanServer; import java.io.File; import java.lang.management.ManagementFactory; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * A simple bootstrap class */ public class Main { private static final transient Logger LOG = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { try { System.setProperty("org.eclipse.jetty.util.log.class", Slf4jLog.class.getName()); Log.setLog(new Slf4jLog("jetty")); int port = Integer.parseInt(System.getProperty("jettyPort", "8080")); String contextPath = System.getProperty("context", "/sample"); String path = System.getProperty("webapp-outdir", "src/main/webapp"); String webXml = path + "/WEB-INF/web.xml"; require(fileExists(webXml), "No web.xml could be found for $webXml"); println("Connect via http://localhost:" + port + contextPath + " using web app source path: " + path); String pathSeparator = File.pathSeparator; String classpath = System.getProperty("java.class.path", ""); ImmutableList<String> classpaths = ImmutableList.copyOf(classpath.split(pathSeparator)); Iterable<String> jarNames = Iterables.filter(classpaths, new Predicate<String>() { public boolean apply(String path) { return isScannedWebInfLib(path); } }); Iterable<File> allFiles = Iterables.transform(jarNames, new Function<String, File>() { public File apply(String path) { return new File(path); } }); Iterable<File> files = Iterables.filter(allFiles, new Predicate<File>() { public boolean apply(File file) { return file != null && file.exists(); } }); Iterable<File> jars = Iterables.filter(files, new Predicate<File>() { public boolean apply(File file) { return file.isFile(); } }); Iterable<File> extraClassDirs = Iterables.filter(files, new Predicate<File>() { public boolean apply(File file) { return file.isDirectory(); } }); JettyWebAppContext context = new JettyWebAppContext(); context.setWebInfLib(ImmutableList.copyOf(jars)); Configuration[] contextConfigs = {new WebXmlConfiguration(), new WebInfConfiguration()}; context.setConfigurations(contextConfigs); context.setDescriptor(webXml); context.setResourceBase(path); context.setContextPath(contextPath); context.setParentLoaderPriority(true); Server server = new Server(port); server.setHandler(context); // enable JMX MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); MBeanContainer mbeanContainer = new MBeanContainer(mbeanServer); if (server.getContainer() != null) { server.getContainer().addEventListener(mbeanContainer); } server.addBean(mbeanContainer); if (args.length == 0 || !args[0].equals("nospring")) { // now lets startup a spring application context LOG.info("starting spring application context"); ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml"); Object activemq = appContext.getBean("activemq"); LOG.info("created activemq: " + activemq); appContext.start(); Object logQuery = appContext.getBean("logQuery"); LOG.info("created logQuery: " + logQuery); LOG.warn("Don't run with scissors!"); LOG.error("Someone somewhere is not using Fuse! :)", new CamelException("My exception message")); // now lets force an exception with a stack trace from camel... try { CamelContextHelper.getMandatoryEndpoint(null, null); } catch (Throwable e) { LOG.error("Expected exception for testing: " + e, e); } } // TODO temporary hack until we've got blueprint servlet listener to load blueprint services try { Class<?> aetherClass = Class.forName("org.fusesource.insight.maven.aether.AetherFacade"); Object aether = aetherClass.newInstance(); Method initMethod = aetherClass.getMethod("init"); Object[] methodArgs = new Object[0]; initMethod.invoke(aether, methodArgs); } catch (InvocationTargetException e) { Throwable target = e.getTargetException(); LOG.warn("Failed to initialise AetherFacade due to : " + e, e); } catch (Throwable e) { LOG.warn("Could not load the AetherFacade; only available in snapshots for now: " + e, e); } // lets connect to fabric String fabricUrl = System.getProperty("fabricUrl", ""); String fabricPassword = System.getProperty("fabricPassword", "admin"); if (fabricUrl != null && fabricUrl.length() > 0) { LOG.info("Connecting to Fuse Fabric at " + fabricUrl); ZKClientFactoryBean factory = new ZKClientFactoryBean(); factory.setPassword(fabricPassword); factory.setConnectString(fabricUrl); IZKClient zooKeeper = factory.getObject(); FabricServiceImpl impl = new FabricServiceImpl(); impl.setMbeanServer(mbeanServer); impl.setZooKeeper(zooKeeper); impl.init(); } // lets initialise infinispan new InfinispanDemo().run(); LOG.info("starting jetty"); server.start(); server.join(); } catch (Throwable e) { LOG.error(e.getMessage(), e); } } /** * Returns true if the file exists */ public static boolean fileExists(String path) { File file = new File(path); return file.exists() && file.isFile(); } /** * Returns true if the directory exists */ public static boolean directoryExists(String path) { File file = new File(path); return file.exists() && file.isDirectory(); } public static void require(boolean flag, String message) { if (!flag) { throw new IllegalStateException(message); } } /** * Returns true if we should scan this lib for annotations */ public static boolean isScannedWebInfLib(String path) { return path.endsWith("kool/website/target/classes"); //return path.contains("kool") //return true } public static void println(Object message) { System.out.println(message); } }
package com.facebook.flipper.plugins.network; import android.text.TextUtils; import android.util.Pair; import com.facebook.flipper.core.FlipperArray; import com.facebook.flipper.core.FlipperConnection; import com.facebook.flipper.core.FlipperObject; import com.facebook.flipper.core.FlipperReceiver; import com.facebook.flipper.core.FlipperResponder; import com.facebook.flipper.plugins.common.BufferingFlipperPlugin; import com.facebook.flipper.plugins.network.NetworkReporter.RequestInfo; import com.facebook.flipper.plugins.network.NetworkReporter.ResponseInfo; import java.io.IOException; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.annotation.Nullable; import okhttp3.Headers; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import okio.BufferedSource; public class FlipperOkhttpInterceptor implements Interceptor, BufferingFlipperPlugin.MockResponseConnectionListener { // By default, limit body size (request or response) reporting to 100KB to avoid OOM private static final long DEFAULT_MAX_BODY_BYTES = 100 * 1024; private final long mMaxBodyBytes; private final NetworkFlipperPlugin mPlugin; private static class PartialRequestInfo extends Pair<String, String> { PartialRequestInfo(String url, String method) { super(url, method); } } // pair of request url and method private Map<PartialRequestInfo, ResponseInfo> mMockResponseMap = new HashMap<>(0); private boolean mIsMockResponseSupported; public FlipperOkhttpInterceptor(NetworkFlipperPlugin plugin) { this(plugin, DEFAULT_MAX_BODY_BYTES, false); } /** If you want to change the number of bytes displayed for the body, use this constructor */ public FlipperOkhttpInterceptor(NetworkFlipperPlugin plugin, long maxBodyBytes) { this(plugin, maxBodyBytes, false); } public FlipperOkhttpInterceptor(NetworkFlipperPlugin plugin, boolean isMockResponseSupported) { this(plugin, DEFAULT_MAX_BODY_BYTES, isMockResponseSupported); } public FlipperOkhttpInterceptor( NetworkFlipperPlugin plugin, long maxBodyBytes, boolean isMockResponseSupported) { mPlugin = plugin; mMaxBodyBytes = maxBodyBytes; mIsMockResponseSupported = isMockResponseSupported; if (isMockResponseSupported) { mPlugin.setConnectionListener(this); } } @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request request = chain.request(); final Pair<Request, Buffer> requestWithClonedBody = cloneBodyAndInvalidateRequest(request); request = requestWithClonedBody.first; final String identifier = UUID.randomUUID().toString(); mPlugin.reportRequest(convertRequest(request, requestWithClonedBody.second, identifier)); // Check if there is a mock response final Response mockResponse = mIsMockResponseSupported ? getMockResponse(request) : null; final Response response = mockResponse != null ? mockResponse : chain.proceed(request); final Buffer responseBody = cloneBodyForResponse(response, mMaxBodyBytes); final ResponseInfo responseInfo = convertResponse(response, responseBody, identifier, mockResponse != null); mPlugin.reportResponse(responseInfo); return response; } private static byte[] bodyBufferToByteArray(final Buffer bodyBuffer, final long maxBodyBytes) throws IOException { return bodyBuffer.readByteArray(Math.min(bodyBuffer.size(), maxBodyBytes)); } /// This method return original Request and body Buffer, while the original Request may be /// invalidated because body may not be read more than once private static Pair<Request, Buffer> cloneBodyAndInvalidateRequest(final Request request) throws IOException { if (request.body() != null) { final Request.Builder builder = request.newBuilder(); final MediaType mediaType = request.body().contentType(); final Buffer originalBuffer = new Buffer(); request.body().writeTo(originalBuffer); final Buffer clonedBuffer = originalBuffer.clone(); final RequestBody newOriginalBody = RequestBody.create(mediaType, originalBuffer.readByteString()); return new Pair<>(builder.method(request.method(), newOriginalBody).build(), clonedBuffer); } return new Pair<>(request, null); } private RequestInfo convertRequest( Request request, final Buffer bodyBuffer, final String identifier) throws IOException { final List<NetworkReporter.Header> headers = convertHeader(request.headers()); final RequestInfo info = new RequestInfo(); info.requestId = identifier; info.timeStamp = System.currentTimeMillis(); info.headers = headers; info.method = request.method(); info.uri = request.url().toString(); if (bodyBuffer != null) { info.body = bodyBufferToByteArray(bodyBuffer, mMaxBodyBytes); bodyBuffer.close(); } return info; } private static Buffer cloneBodyForResponse(final Response response, long maxBodyBytes) throws IOException { if (response.body() != null && response.body().source() != null && response.body().source().buffer() != null) { final BufferedSource source = response.body().source(); source.request(maxBodyBytes); return source.buffer().clone(); } return null; } private ResponseInfo convertResponse( Response response, Buffer bodyBuffer, String identifier, boolean isMock) throws IOException { final List<NetworkReporter.Header> headers = convertHeader(response.headers()); final ResponseInfo info = new ResponseInfo(); info.requestId = identifier; info.timeStamp = response.receivedResponseAtMillis(); info.statusCode = response.code(); info.headers = headers; info.isMock = isMock; if (bodyBuffer != null) { info.body = bodyBufferToByteArray(bodyBuffer, mMaxBodyBytes); bodyBuffer.close(); } return info; } private static List<NetworkReporter.Header> convertHeader(Headers headers) { final List<NetworkReporter.Header> list = new ArrayList<>(headers.size()); final Set<String> keys = headers.names(); for (final String key : keys) { list.add(new NetworkReporter.Header(key, headers.get(key))); } return list; } private void registerMockResponse(PartialRequestInfo partialRequest, ResponseInfo response) { if (!mMockResponseMap.containsKey(partialRequest)) { mMockResponseMap.put(partialRequest, response); } } @Nullable private Response getMockResponse(Request request) { final String url = request.url().toString(); final String method = request.method(); final PartialRequestInfo partialRequest = new PartialRequestInfo(url, method); if (!mMockResponseMap.containsKey(partialRequest)) { return null; } ResponseInfo mockResponse = mMockResponseMap.get(partialRequest); if (mockResponse == null) { return null; } final Response.Builder builder = new Response.Builder(); builder .request(request) .protocol(Protocol.HTTP_1_1) .code(mockResponse.statusCode) .message(mockResponse.statusReason) .receivedResponseAtMillis(System.currentTimeMillis()) .body(ResponseBody.create(MediaType.parse("application/text"), mockResponse.body)); if (mockResponse.headers != null && !mockResponse.headers.isEmpty()) { for (final NetworkReporter.Header header : mockResponse.headers) { if (!TextUtils.isEmpty(header.name) && !TextUtils.isEmpty(header.value)) { builder.header(header.name, header.value); } } } return builder.build(); } @Nullable private ResponseInfo convertFlipperObjectRouteToResponseInfo(FlipperObject route) { final String data = route.getString("data"); final String requestUrl = route.getString("requestUrl"); final String method = route.getString("method"); FlipperArray headersArray = route.getArray("headers"); if (TextUtils.isEmpty(requestUrl) || TextUtils.isEmpty(method)) { return null; } final ResponseInfo mockResponse = new ResponseInfo(); mockResponse.body = data.getBytes(); mockResponse.statusCode = HttpURLConnection.HTTP_OK; mockResponse.statusReason = "OK"; if (headersArray != null) { final List<NetworkReporter.Header> headers = new ArrayList<>(); for (int j = 0; j < headersArray.length(); j++) { final FlipperObject header = headersArray.getObject(j); headers.add(new NetworkReporter.Header(header.getString("key"), header.getString("value"))); } mockResponse.headers = headers; } return mockResponse; } @Override public void onConnect(FlipperConnection connection) { connection.receive( "mockResponses", new FlipperReceiver() { @Override public void onReceive(FlipperObject params, FlipperResponder responder) throws Exception { FlipperArray array = params.getArray("routes"); mMockResponseMap.clear(); for (int i = 0; i < array.length(); i++) { final FlipperObject route = array.getObject(i); final String requestUrl = route.getString("requestUrl"); final String method = route.getString("method"); ResponseInfo mockResponse = convertFlipperObjectRouteToResponseInfo(route); if (mockResponse != null) { registerMockResponse(new PartialRequestInfo(requestUrl, method), mockResponse); } } responder.success(); } }); } @Override public void onDisconnect() { mMockResponseMap.clear(); } }
package org.ovirt.engine.core.bll.network.dc; import java.util.List; import org.ovirt.engine.core.bll.ValidationResult; import org.ovirt.engine.core.bll.network.cluster.NetworkClusterHelper; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.AddNetworkStoragePoolParameters; import org.ovirt.engine.core.common.businessentities.network.Network; import org.ovirt.engine.core.common.businessentities.network.NetworkCluster; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.validation.group.UpdateEntity; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.NGuid; import org.ovirt.engine.core.dal.VdcBllMessages; @SuppressWarnings("serial") public class UpdateNetworkCommand<T extends AddNetworkStoragePoolParameters> extends NetworkCommon<T> { private Network oldNetwork; public UpdateNetworkCommand(T parameters) { super(parameters); } @Override protected void executeCommand() { getNetworkDAO().update(getNetwork()); for (NetworkCluster clusterAttachment : getClusterAttachments()) { NetworkClusterHelper.setStatus(clusterAttachment.getClusterId(), getNetwork()); } setSucceeded(true); } @Override protected void setActionMessageParameters() { super.setActionMessageParameters(); addCanDoActionMessage(VdcBllMessages.VAR__ACTION__UPDATE); } @Override protected boolean canDoAction() { return validate(storagePoolExists()) && validate(vmNetworkSetCorrectly()) && validate(stpForVmNetworkOnly()) && validate(mtuValid()) && validate(networkPrefixValid()) && validate(vlanIsFree()) && validate(networkExists(getOldNetwork())) && validate(notChangingManagementNetworkName()) && validate(networkNameNotUsed()) && validate(networkNotUsedByVms(getOldNetwork())) && validate(networkNotUsedByTemplates(getOldNetwork())) && validate(networkNotUsedByHosts(getOldNetwork())); } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.NETWORK_UPDATE_NETWORK : AuditLogType.NETWORK_UPDATE_NETWORK_FAILED; } @Override protected List<Class<?>> getValidationGroups() { addValidationGroup(UpdateEntity.class); return super.getValidationGroups(); } private Network getOldNetwork(){ if (oldNetwork == null) { oldNetwork = getNetworkById(getNetworks()); } return oldNetwork; } private Network getNetworkById(List<Network> networks) { Guid networkId = getNetwork().getId(); for (Network network : networks) { if (network.getId().equals(networkId)) { return network; } } return null; } private ValidationResult networkNameNotUsed() { Network networkWithSameName = getOtherNetworkWithSameName(getNetworks()); return networkWithSameName != null ? new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_NETWORK_NAME_IN_USE) : ValidationResult.VALID; } private Network getOtherNetworkWithSameName(List<Network> networks) { String networkName = getNetworkName().toLowerCase(); Guid networkId = getNetwork().getId(); NGuid dataCenterId = getNetwork().getDataCenterId(); for (Network network : networks) { if (network.getName().toLowerCase().equals(networkName) && !network.getId().equals(networkId) && dataCenterId.equals(network.getDataCenterId())) { return network; } } return null; } private ValidationResult notChangingManagementNetworkName() { String managementNetwork = Config.<String> GetValue(ConfigValues.ManagementNetwork); return getOldNetwork().getName().equals(managementNetwork) && !getNetworkName().equals(managementNetwork) ? new ValidationResult(VdcBllMessages.NETWORK_CAN_NOT_REMOVE_DEFAULT_NETWORK) : ValidationResult.VALID; } }
package org.ovirt.engine.core.common.businessentities; import java.io.Serializable; import java.util.Map; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.ovirt.engine.core.common.utils.ObjectUtils; import org.ovirt.engine.core.common.validation.annotation.ValidI18NName; import org.ovirt.engine.core.common.validation.annotation.ValidVdsGroup; import org.ovirt.engine.core.common.validation.group.CreateEntity; import org.ovirt.engine.core.common.validation.group.UpdateEntity; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.Version; @ValidVdsGroup(groups = { CreateEntity.class }) public class VDSGroup extends IVdcQueryable implements Serializable, BusinessEntity<Guid>, HasStoragePool<Guid>, Nameable { private static final long serialVersionUID = 5659359762655478095L; public static final Guid DEFAULT_VDS_GROUP_ID = new Guid("99408929-82CF-4DC7-A532-9D998063FA95"); private Guid id; @NotNull(message = "VALIDATION.VDS_GROUP.NAME.NOT_NULL", groups = { CreateEntity.class, UpdateEntity.class }) @Size(min = 1, max = BusinessEntitiesDefinitions.CLUSTER_NAME_SIZE, message = "VALIDATION.VDS_GROUP.NAME.MAX", groups = { CreateEntity.class, UpdateEntity.class }) @ValidI18NName(message = "VALIDATION.VDS_GROUP.NAME.INVALID", groups = { CreateEntity.class, UpdateEntity.class }) private String name = ""; // GREGM Prevents NPE @Size(max = BusinessEntitiesDefinitions.GENERAL_MAX_SIZE) private String description; @Size(max = BusinessEntitiesDefinitions.CLUSTER_CPU_NAME_SIZE) private String cpu_name; private VdsSelectionAlgorithm selection_algorithm = VdsSelectionAlgorithm.None; private int high_utilization = 0; private int low_utilization = 0; private int cpu_over_commit_duration_minutes = 0; private Guid storagePoolId; @Size(max = BusinessEntitiesDefinitions.DATACENTER_NAME_SIZE) private String storagePoolName; private int max_vds_memory_over_commit = 0; private boolean countThreadsAsCores = false; @Size(max = BusinessEntitiesDefinitions.GENERAL_VERSION_SIZE) private String compatibility_version; private Version compatVersion; private boolean transparentHugepages; @NotNull(message = "VALIDATION.VDS_GROUP.MigrateOnError.NOT_NULL") private MigrateOnErrorOptions migrateOnError; private boolean virtService = true; private boolean glusterService = false; private boolean tunnelMigration = false; private String emulatedMachine; private boolean trustedService = false; private Guid clusterPolicyId; private Map<String, String> clusterPolicyProperties; public VDSGroup() { selection_algorithm = VdsSelectionAlgorithm.None; high_utilization = -1; low_utilization = -1; cpu_over_commit_duration_minutes = -1; migrateOnError = MigrateOnErrorOptions.YES; } public VDSGroup(String name, String description, String cpu_name) { this(); this.name = name; this.description = description; this.cpu_name = cpu_name; } @Override public Guid getId() { return id; } @Override public void setId(Guid value) { id = value; } public void setvds_group_id(Guid value) { setId(value); } @Override public String getName() { return name; } public void setName(String value) { name = value; } public String getdescription() { return description; } public void setdescription(String value) { description = value; } public String getcpu_name() { return this.cpu_name; } public void setcpu_name(String value) { this.cpu_name = value; } public VdsSelectionAlgorithm getselection_algorithm() { return selection_algorithm; } public void setselection_algorithm(VdsSelectionAlgorithm value) { selection_algorithm = value; } public int gethigh_utilization() { return this.high_utilization; } public void sethigh_utilization(int value) { this.high_utilization = value; } public int getlow_utilization() { return this.low_utilization; } public void setlow_utilization(int value) { this.low_utilization = value; } public int getcpu_over_commit_duration_minutes() { return this.cpu_over_commit_duration_minutes; } public void setcpu_over_commit_duration_minutes(int value) { this.cpu_over_commit_duration_minutes = value; } @Override public Guid getStoragePoolId() { return storagePoolId; } @Override public void setStoragePoolId(Guid storagePool) { this.storagePoolId = storagePool; } public String getStoragePoolName() { return this.storagePoolName; } public void setStoragePoolName(String value) { this.storagePoolName = value; } public int getmax_vds_memory_over_commit() { return this.max_vds_memory_over_commit; } public void setmax_vds_memory_over_commit(int value) { this.max_vds_memory_over_commit = value; } public boolean getCountThreadsAsCores() { return this.countThreadsAsCores; } public void setCountThreadsAsCores(boolean value) { this.countThreadsAsCores = value; } public Version getcompatibility_version() { return compatVersion; } public boolean getTransparentHugepages() { return this.transparentHugepages; } public void setTransparentHugepages(boolean value) { this.transparentHugepages = value; } public void setcompatibility_version(Version value) { compatibility_version = value.getValue(); compatVersion = value; } @Override public Object getQueryableId() { return getId(); } public void setMigrateOnError(MigrateOnErrorOptions migrateOnError) { this.migrateOnError = migrateOnError; } public MigrateOnErrorOptions getMigrateOnError() { return migrateOnError; } public void setVirtService(boolean virtService) { this.virtService = virtService; } public boolean supportsVirtService() { return virtService; } public void setGlusterService(boolean glusterService) { this.glusterService = glusterService; } public boolean supportsGlusterService() { return glusterService; } public boolean isTunnelMigration() { return tunnelMigration; } public void setTunnelMigration(boolean value) { tunnelMigration = value; } public String getEmulatedMachine() { return emulatedMachine; } public void setEmulatedMachine(String emulatedMachine) { this.emulatedMachine = emulatedMachine; } public void setTrustedService(boolean trustedService) { this.trustedService = trustedService; } public boolean supportsTrustedService() { return trustedService; } public Guid getClusterPolicyId() { return clusterPolicyId; } public void setClusterPolicyId(Guid clusterPolicyId) { this.clusterPolicyId = clusterPolicyId; } public Map<String, String> getClusterPolicyProperties() { return clusterPolicyProperties; } public void setClusterPolicyProperties(Map<String, String> clusterPolicyProperties) { this.clusterPolicyProperties = clusterPolicyProperties; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((compatVersion == null) ? 0 : compatVersion.hashCode()); result = prime * result + ((compatibility_version == null) ? 0 : compatibility_version.hashCode()); result = prime * result + ((cpu_name == null) ? 0 : cpu_name.hashCode()); result = prime * result + cpu_over_commit_duration_minutes; result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + high_utilization; result = prime * result + low_utilization; result = prime * result + max_vds_memory_over_commit; result = prime * result + (countThreadsAsCores ? 1231 : 1237); result = prime * result + ((migrateOnError == null) ? 0 : migrateOnError.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((selection_algorithm == null) ? 0 : selection_algorithm.hashCode()); result = prime * result + ((storagePoolId == null) ? 0 : storagePoolId.hashCode()); result = prime * result + ((storagePoolName == null) ? 0 : storagePoolName.hashCode()); result = prime * result + (transparentHugepages ? 1231 : 1237); result = prime * result + (virtService ? 1231 : 1237); result = prime * result + (glusterService ? 1231 : 1237); result = prime * result + (tunnelMigration ? 1231 : 1237); result = prime * result + (emulatedMachine == null ? 0 : emulatedMachine.hashCode()); result = prime * result + (trustedService ? 1231 : 1237); result = prime * result + ((clusterPolicyId == null) ? 0 : clusterPolicyId.hashCode()); result = prime * result + (clusterPolicyProperties == null ? 0 : clusterPolicyProperties.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } VDSGroup other = (VDSGroup) obj; return (ObjectUtils.objectsEqual(id, other.id) && ObjectUtils.objectsEqual(compatVersion, other.compatVersion) && ObjectUtils.objectsEqual(compatibility_version, other.compatibility_version) && ObjectUtils.objectsEqual(cpu_name, other.cpu_name) && cpu_over_commit_duration_minutes == other.cpu_over_commit_duration_minutes && ObjectUtils.objectsEqual(description, other.description) && high_utilization == other.high_utilization && low_utilization == other.low_utilization && max_vds_memory_over_commit == other.max_vds_memory_over_commit && countThreadsAsCores == other.countThreadsAsCores && migrateOnError == other.migrateOnError && ObjectUtils.objectsEqual(name, other.name) && ObjectUtils.objectsEqual(selection_algorithm, other.selection_algorithm) && ObjectUtils.objectsEqual(storagePoolId, other.storagePoolId) && ObjectUtils.objectsEqual(storagePoolName, other.storagePoolName) && transparentHugepages == other.transparentHugepages && virtService == other.virtService && glusterService == other.glusterService && tunnelMigration == other.tunnelMigration && ObjectUtils.objectsEqual(emulatedMachine, other.emulatedMachine) && trustedService == other.trustedService && ObjectUtils.objectsEqual(clusterPolicyId, other.clusterPolicyId) && ObjectUtils.objectsEqual(clusterPolicyProperties, other.clusterPolicyProperties)); } }
package org.intermine.bio.dataconversion; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.FormattedTextParser; import org.intermine.xml.full.Item; /** * * @author Julie Sullivan */ public class Drosophila2ProbeConverter extends BioFileConverter { protected static final Logger LOG = Logger.getLogger(Drosophila2ProbeConverter.class); protected String dataSource, dataSet; private String orgRefId; protected Map<String, String> bioentities = new HashMap<String, String>(); protected IdResolverFactory resolverFactory; private static final String TAXON_ID = "7227"; private static final String DATASET_PREFIX = "Affymetrix array: "; private Map<String, String> chromosomes = new HashMap<String, String>(); private Map<String, ProbeSetHolder> holders = new HashMap<String, ProbeSetHolder>(); List<Item> delayedItems = new ArrayList<Item>(); /** * Constructor * @param writer the ItemWriter used to handle the resultant items * @param model the data model * @throws ObjectStoreException if an error occurs in storing */ public Drosophila2ProbeConverter(ItemWriter writer, Model model) throws ObjectStoreException { super(writer, model, null, null); dataSource = getDataSource("Ensembl"); orgRefId = getOrganism(TAXON_ID); // only construct factory here so can be replaced by mock factory in tests resolverFactory = new FlyBaseIdResolverFactory("gene"); } /** * Read each line from flat file. * * {@inheritDoc} */ public void process(Reader reader) throws Exception { Iterator<String[]> lineIter = FormattedTextParser.parseTabDelimitedReader(reader); while (lineIter.hasNext()) { String[] line = lineIter.next(); dataSet = getDataSet(DATASET_PREFIX + line[0], dataSource); String probesetIdentifier = line[1]; String transcriptIdentifier = line[2]; String fbgn = line[3]; String chromosomeIdentifier = line[4]; String startString = line[5]; String endString = line[6]; String strand = line[7]; String chromosomeRefId = createChromosome(chromosomeIdentifier); String geneRefId = createGene(fbgn); if (geneRefId != null) { String transcriptRefId = createBioentity("Transcript", transcriptIdentifier, geneRefId); ProbeSetHolder holder = getHolder(probesetIdentifier); holder.transcripts.add(transcriptRefId); holder.genes.add(geneRefId); holder.datasets.add(dataSet); try { Integer start = new Integer(startString); Integer end = new Integer(endString); holder.addLocation(chromosomeRefId, start, end, strand); } catch (NumberFormatException e) { throw new RuntimeException("bad start/end values"); } } } } /** * * {@inheritDoc} */ public void close() throws Exception { for (ProbeSetHolder holder : holders.values()) { storeProbeSet(holder); } for (Item item : delayedItems) { store(item); } } private void storeProbeSet(ProbeSetHolder holder) throws ObjectStoreException { Item probeSet = createItem("ProbeSet"); probeSet.setAttribute("primaryIdentifier", holder.probesetIdentifier); probeSet.setAttribute("name", holder.probesetIdentifier); probeSet.setReference("organism", orgRefId); probeSet.setCollection("dataSets", holder.datasets); probeSet.setCollection("transcripts", holder.transcripts); probeSet.setCollection("genes", holder.genes); probeSet.setCollection("locations", holder.createLocations(probeSet.getIdentifier(), holder.datasets)); store(probeSet); } /** * Holds information about the probeset until all probes have been processed and we know the * start and end * @author Julie Sullivan */ public class ProbeSetHolder { protected String probesetIdentifier; protected List<String> genes = new ArrayList<String>(); private List<String> locations = new ArrayList<String>(); protected List<String> transcripts = new ArrayList<String>(); protected Map<String, LocationHolder> locationHolders = new HashMap<String, LocationHolder>(); protected List<String> datasets = new ArrayList<String>(); /** * @param identifier probeset identifier */ public ProbeSetHolder(String identifier) { probesetIdentifier = identifier; } /** * @param chromosomeRefId id representing a chromosome object * @param start start of location * @param end end of location * @param strand strand, eg -1 or 1 */ protected void addLocation(String chromosomeRefId, Integer start, Integer end, String strand) { String key = chromosomeRefId + "|" + start.toString() + "|" + end.toString() + "|" + strand; if (locationHolders.get(key) == null) { LocationHolder location = new LocationHolder(chromosomeRefId, start, end, strand); locationHolders.put(key, location); } } /** * when all of the probes for this probeset have been processed, create and store all * related locations * @param probeSetRefId id representing probeset object * @param dataSets list of IDs reresenting dataset objects * @return reference list of location objects * @throws ObjectStoreException if something goes wrong storing locations */ protected List<String> createLocations(String probeSetRefId, List<String> dataSets) throws ObjectStoreException { for (LocationHolder holder : locationHolders.values()) { locations.add(createLocation(holder, probeSetRefId, dataSets)); } return locations; } } /** * holds information about a location */ public class LocationHolder { protected Integer start = new Integer(-1); protected Integer end = new Integer(-1); protected String strand; protected String chromosomeRefID; /** * @param chromosomeRefId id representing a chromosome object * @param start start of location * @param end end of location * @param strand strand, eg -1 or 1 */ public LocationHolder(String chromosomeRefId, Integer start, Integer end, String strand) { this.chromosomeRefID = chromosomeRefId; this.start = start; this.end = end; this.strand = strand; } } private String createGene(String id) throws ObjectStoreException { String identifier = id; IdResolver resolver = resolverFactory.getIdResolver(); int resCount = resolver.countResolutions(TAXON_ID, identifier); if (resCount != 1) { LOG.info("RESOLVER: failed to resolve gene to one identifier, ignoring gene: " + identifier + " count: " + resCount + " FBgn: " + resolver.resolveId(TAXON_ID, identifier)); return null; } identifier = resolver.resolveId(TAXON_ID, identifier).iterator().next(); return createBioentity("Gene", identifier, null); } private String createBioentity(String type, String identifier, String geneRefId) throws ObjectStoreException { String refId = bioentities.get(identifier); if (refId == null) { Item bioentity = createItem(type); bioentity.setAttribute("primaryIdentifier", identifier); bioentity.setReference("organism", orgRefId); if ("Transcript".equals(type)) { bioentity.setReference("gene", geneRefId); } bioentity.addToCollection("dataSets", dataSet); refId = bioentity.getIdentifier(); store(bioentity); bioentities.put(identifier, refId); } return refId; } private String createChromosome(String identifier) throws ObjectStoreException { String refId = chromosomes.get(identifier); if (refId == null) { Item item = createItem("Chromosome"); item.setAttribute("primaryIdentifier", identifier); item.setReference("organism", orgRefId); chromosomes.put(identifier, item.getIdentifier()); store(item); refId = item.getIdentifier(); } return refId; } private String createLocation(LocationHolder holder, String probeset, List<String> dataSets) { String strand = null; if (holder.strand != null) { strand = holder.strand; } else { LOG.warn("probeset " + probeset + " has no strand"); } Item location = makeLocation(holder.chromosomeRefID, probeset, holder.start.toString(), holder.end.toString(), strand, false); location.setCollection("dataSets", dataSets); delayedItems.add(location); return location.getIdentifier(); } private ProbeSetHolder getHolder(String identifier) { ProbeSetHolder holder = holders.get(identifier); if (holder == null) { holder = new ProbeSetHolder(identifier); holders.put(identifier, holder); } return holder; } }
package com.perm.kate.api; import java.io.Serializable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Photo implements Serializable { private static final long serialVersionUID = 1L; public long pid; public long aid; public String owner_id; public String src;//photo_130 public String src_small;//photo_75 public String src_big;//photo_604 public String src_xbig;//photo_807 public String src_xxbig;//photo_1280 public String src_xxxbig;//photo_2560 public String phototext; public long created; public Integer like_count; public Boolean user_likes; public Integer comments_count; public Integer tags_count; public Boolean can_comment; public int width;//0 means value is unknown public int height;//0 means value is unknown public String access_key; public String user_id; //for group public static Photo parse(JSONObject o) throws NumberFormatException, JSONException{ Photo p = new Photo(); p.pid = o.getLong("id"); p.aid = o.optLong("album_id"); p.owner_id = o.getString("owner_id"); p.src = o.optString("photo_130"); p.src_small = o.optString("photo_75"); p.src_big = o.optString("photo_604"); p.src_xbig = o.optString("photo_807"); p.src_xxbig = o.optString("photo_1280"); p.src_xxxbig = o.optString("photo_2560"); p.phototext = Api.unescape(o.optString("text")); p.created = o.optLong("date"); //date instead created for api v 5.0 and higher p.user_id = o.optString("user_id"); if (o.has("likes")) { JSONObject jlikes = o.getJSONObject("likes"); p.like_count = jlikes.optInt("count"); p.user_likes = jlikes.optInt("user_likes")==1; } if (o.has("comments")) { JSONObject jcomments = o.getJSONObject("comments"); p.comments_count = jcomments.optInt("count"); } if (o.has("tags")) { JSONObject jtags = o.getJSONObject("tags"); p.tags_count = jtags.optInt("count"); } if (o.has("can_comment")) p.can_comment = o.optInt("can_comment")==1; p.width = o.optInt("width"); p.height = o.optInt("height"); p.access_key=o.optString("access_key"); return p; } public Photo(){ } public Photo(Long id, String owner_id, String src, String src_big){ this.pid=id; this.owner_id=owner_id; this.src=src; this.src_big=src_big; } public static Photo parseCounts(JSONObject o) throws NumberFormatException, JSONException{ Photo p = new Photo(); JSONArray pid_array = o.optJSONArray("pid"); if (pid_array != null && pid_array.length() > 0) { p.pid = pid_array.getLong(0); } JSONArray likes_array = o.optJSONArray("likes"); if (likes_array != null && likes_array.length() > 0) { JSONObject jlikes = likes_array.getJSONObject(0); p.like_count = jlikes.optInt("count"); p.user_likes = jlikes.optInt("user_likes")==1; } JSONArray comments_array = o.optJSONArray("comments"); if (comments_array != null && comments_array.length() > 0) { JSONObject jcomments = comments_array.getJSONObject(0); p.comments_count = jcomments.optInt("count"); } JSONArray tags_array = o.optJSONArray("tags"); if (tags_array != null && tags_array.length() > 0) { JSONObject jtags = tags_array.getJSONObject(0); p.tags_count = jtags.optInt("count"); } JSONArray can_comment_array = o.optJSONArray("can_comment"); if (can_comment_array != null && can_comment_array.length() > 0) { p.can_comment = can_comment_array.getInt(0)==1; } JSONArray user_id_array = o.optJSONArray("user_id"); if (user_id_array != null && user_id_array.length() > 0) { p.user_id = user_id_array.getString(0); } return p; } }
package com.rackspacecloud.blueflood.service; import com.rackspacecloud.blueflood.rollup.Granularity; import com.rackspacecloud.blueflood.rollup.SlotKey; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class ScheduleContextAreKeysRunningTest { @Test public void noneScheduledOrRunningReturnsFalse() { // given long currentTime = 1234000L; final int shard = 0; List<Integer> managedShards = new ArrayList<Integer>() {{ add(shard); }}; ScheduleContext ctx = new ScheduleContext(currentTime, managedShards); int slot = Granularity.MIN_5.slot(currentTime); SlotKey slotkey = SlotKey.of(Granularity.MIN_5, slot, shard); // when boolean areKeysRunning = ctx.areChildKeysOrSelfKeyScheduledOrRunning(slotkey); // then assertFalse(areKeysRunning); } @Test public void slotScheduledReturnsTrue() { // given long currentTime = 1234000L; final int shard = 0; List<Integer> managedShards = new ArrayList<Integer>() {{ add(shard); }}; ScheduleContext ctx = new ScheduleContext(currentTime, managedShards); ctx.update(currentTime - 2, shard); ctx.scheduleEligibleSlots(1, 7200000); int slot = Granularity.MIN_5.slot(currentTime); SlotKey slotkey = SlotKey.of(Granularity.MIN_5, slot, shard); // when boolean areKeysRunning = ctx.areChildKeysOrSelfKeyScheduledOrRunning(slotkey); // then assertTrue(areKeysRunning); } @Test public void childSlotScheduledReturnsTrue() { // given long currentTime = 1234000L; final int shard = 0; List<Integer> managedShards = new ArrayList<Integer>() {{ add(shard); }}; ScheduleContext ctx = new ScheduleContext(currentTime, managedShards); ctx.update(currentTime - 2, shard); ctx.scheduleEligibleSlots(1, 7200000); int slot = Granularity.MIN_20.slot(currentTime); SlotKey slotkey = SlotKey.of(Granularity.MIN_20, slot, shard); // when boolean areKeysRunning = ctx.areChildKeysOrSelfKeyScheduledOrRunning(slotkey); // then assertTrue(areKeysRunning); } @Test public void unrelatedSlotScheduledReturnsFalse() { // given long currentTime = 1234000L; final int shard = 0; List<Integer> managedShards = new ArrayList<Integer>() {{ add(shard); }}; ScheduleContext ctx = new ScheduleContext(currentTime, managedShards); ctx.update(currentTime - 2, shard); ctx.scheduleEligibleSlots(1, 7200000); int slot = Granularity.MIN_5.slot(currentTime - 5*60*1000); // check the previous slot from 5 minutes ago SlotKey slotkey = SlotKey.of(Granularity.MIN_5, slot, shard); // when boolean areKeysRunning = ctx.areChildKeysOrSelfKeyScheduledOrRunning(slotkey); // then assertFalse(areKeysRunning); } @Test public void slotRunningReturnsTrue() { // given long currentTime = 1234000L; final int shard = 0; List<Integer> managedShards = new ArrayList<Integer>() {{ add(shard); }}; ScheduleContext ctx = new ScheduleContext(currentTime, managedShards); ctx.update(currentTime - 2, shard); ctx.scheduleEligibleSlots(1, 7200000); int slot = Granularity.MIN_5.slot(currentTime); SlotKey slotkey = SlotKey.of(Granularity.MIN_5, slot, shard); SlotKey runningSlot = ctx.getNextScheduled(); // precondition assertEquals(slotkey, runningSlot); // when boolean areKeysRunning = ctx.areChildKeysOrSelfKeyScheduledOrRunning(slotkey); // then assertTrue(areKeysRunning); } @Test public void childSlotRunningReturnsTrue() { // given long currentTime = 1234000L; final int shard = 0; List<Integer> managedShards = new ArrayList<Integer>() {{ add(shard); }}; ScheduleContext ctx = new ScheduleContext(currentTime, managedShards); ctx.update(currentTime - 2, shard); ctx.scheduleEligibleSlots(1, 7200000); int slot = Granularity.MIN_20.slot(currentTime); SlotKey slotkey = SlotKey.of(Granularity.MIN_20, slot, shard); SlotKey runningSlot = ctx.getNextScheduled(); // when boolean areKeysRunning = ctx.areChildKeysOrSelfKeyScheduledOrRunning(slotkey); // then assertTrue(areKeysRunning); } }
package gov.nih.nci.cabig.caaers.web.participant; import gov.nih.nci.cabig.caaers.CaaersContextLoader; import gov.nih.nci.cabig.caaers.dao.ParticipantDao; import gov.nih.nci.cabig.caaers.dao.query.OrganizationFromStudySiteQuery; import gov.nih.nci.cabig.caaers.dao.query.OrganizationQuery; import gov.nih.nci.cabig.caaers.domain.*; import gov.nih.nci.cabig.caaers.domain.repository.OrganizationRepository; import gov.nih.nci.cabig.caaers.security.CaaersSecurityFacade; import gov.nih.nci.cabig.caaers.security.CaaersSecurityFacadeImpl; import gov.nih.nci.cabig.caaers.security.SecurityTestUtils; import gov.nih.nci.cabig.caaers.security.SecurityUtilsTest; import gov.nih.nci.cabig.caaers.web.utils.ConfigPropertyHelper; import org.springframework.context.ApplicationContext; import org.springframework.validation.FieldError; import org.springframework.web.servlet.ModelAndView; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Biju Joseph * @author Ion C. Olaru */ @SuppressWarnings("unchecked") public class CreateParticipantTabTest extends AbstractTabTestCase<CreateParticipantTab, ParticipantInputCommand> { private CreateParticipantTab createParticipantTab; private ParticipantInputCommand newParticipantCommand; private CaaersSecurityFacade facade; @Override protected void setUp() throws Exception { super.setUp(); createParticipantTab = createTab(); ConfigPropertyHelper.putParticipantIdentifiersType(configProperty); newParticipantCommand.setStudy(new LocalStudy()); } @Override protected void tearDown() throws Exception { super.tearDown(); } @Override protected CreateParticipantTab createTab() { createParticipantTab = new CreateParticipantTab(); createParticipantTab.setOrganizationRepository(new OrganizationRepository(){ public void create(Organization organization) { // TODO Auto-generated method stub } public void createOrUpdate(Organization organization) { // TODO Auto-generated method stub } public List<Organization> getOrganizationsHavingStudySites() { return new ArrayList<Organization>(); } public List<Organization> getApplicableOrganizationsFromStudySites(String text, Integer studyId){ return new ArrayList<Organization>(); } public void convertToRemote(Organization localOrganization, Organization remoteOrganization) { // TODO Auto-generated method stub } public List<Organization> getAll() { // TODO Auto-generated method stub return null; } public List<Organization> restrictBySubnames(String[] subnames, boolean b, boolean c, boolean d) { // TODO Auto-generated method stub return null; } public List<Organization> restrictBySubnames(String[] subnames) { // TODO Auto-generated method stub return null; } public List<Organization> searchOrganization(OrganizationQuery query) { // TODO Auto-generated method stub return null; } public List<Organization> searchRemoteOrganization(String coppaSearchText, String sType) { // TODO Auto-generated method stub return null; } public List<Organization> getLocalOrganizations(OrganizationQuery query) { // TODO Auto-generated method stub return null; } public List<Organization> getAllOrganizations() { // TODO Auto-generated method stub return null; } public List<Organization> getAllNciInstitueCodes() { // TODO Auto-generated method stub return null; } public void saveImportedOrganization(Organization organization) { // TODO Auto-generated method stub } public List<StudyOrganization> getApplicableOrganizationsFromStudyOrganizations(final String text, Integer studyId) { return null; } public Organization getById(int id) { // TODO Auto-generated method stub return null; } public void evict(Organization org) { // TODO Auto-generated method stub } }); createParticipantTab.setListValues(listValues); createParticipantTab.setConfigurationProperty(configProperty); createParticipantTab.setParticipantDao((ParticipantDao)getDeployedApplicationContext().getBean("participantDao")); return createParticipantTab; } @Override protected ParticipantInputCommand createCommand() { newParticipantCommand = new ParticipantInputCommand(); newParticipantCommand.setParticipant(new Participant()); newParticipantCommand.setOrganization(new LocalOrganization()); newParticipantCommand.getOrganization().setId(-1); newParticipantCommand.setTargetPage(2); return newParticipantCommand; } public void testGroupDisplayNames() throws Exception { assertDisplayNameForFieldGroup(null, "site"); assertDisplayNameForFieldGroup(null, "participant"); } public void testSiteFields() throws Exception { assertFieldProperties("site", "organization"); } public void testParticipantFields() throws Exception { assertFieldProperties("participant", "participant.firstName", "participant.lastName", "participant.maidenName", "participant.middleName", "participant.dateOfBirth", "participant.gender", "participant.ethnicity", "participant.race" ); } @Override protected Map<String, Object> createReferenceData() { Map<String, Object> referenceData = getTab().referenceData(getCommand()); return referenceData; } public void testValidateDateOfBirth() throws Exception { newParticipantCommand.getParticipant().setDateOfBirth(new DateValue(2011)); doValidate(); assertEquals("Wrong number of errors for " + "participant.dateOfBirth", 0, errors.getFieldErrorCount("participant.dateOfBirth")); } public void testValidateIdentifiers() throws Exception { newParticipantCommand.getParticipant().getIdentifiers().add(new SystemAssignedIdentifier()); doValidate(); assertEquals("Wrong number of errors for " + "participant.identifiers", 0, errors.getFieldErrorCount("participant.identifiers")); } /* * The Participant has 2 organization identifiers with the same value, organization and type * This should throw an error about duplicate identifiers * * */ public void testValidateUniqueness1() throws Exception { OrganizationAssignedIdentifier i1 = new OrganizationAssignedIdentifier(); i1.setOrganization(new LocalOrganization()); i1.getOrganization().setNciInstituteCode("O1"); i1.setType("T1"); i1.setValue("V1"); OrganizationAssignedIdentifier i2 = new OrganizationAssignedIdentifier(); i2.setOrganization(new LocalOrganization()); i2.getOrganization().setNciInstituteCode("O1"); i2.setType("T1"); i2.setValue("V1"); newParticipantCommand.getParticipant().addIdentifier(i1); newParticipantCommand.getParticipant().addIdentifier(i2); doValidate(); assertEquals(7, errors.getErrorCount()); assertEquals("Wrong number of errors: ", 1, errors.getFieldErrorCount("participant.firstName")); assertEquals("Wrong number of errors: ", 1, errors.getFieldErrorCount("participant.lastName")); assertEquals("Wrong number of errors: ", 1, errors.getFieldErrorCount("participant.gender")); assertEquals("Wrong number of errors: ", 1, errors.getFieldErrorCount("participant.ethnicity")); assertEquals("Wrong number of errors: ", 1, errors.getFieldErrorCount("participant.race")); assertEquals("Wrong number of errors: ", 1, errors.getFieldErrorCount("participant.dateOfBirth")); /* System.out.println("err1=" + errors.getErrorCount()); for (Object err : errors.getAllErrors()) { System.out.println(((FieldError)err).getField()); } */ assertEquals("Wrong number of errors: ", 1, errors.getFieldErrorCount("participant.organizationIdentifiers[1].value")); } /* * The Participant has 2 organization identifiers with the same value, organization and different type * This should not throw an error about duplicate identifiers * * */ public void testValidateUniqueness2() throws Exception { OrganizationAssignedIdentifier i1 = new OrganizationAssignedIdentifier(); i1.setOrganization(new LocalOrganization()); i1.getOrganization().setNciInstituteCode("O1"); i1.setType("T1"); i1.setValue("V1"); OrganizationAssignedIdentifier i2 = new OrganizationAssignedIdentifier(); i2.setOrganization(new LocalOrganization()); i2.getOrganization().setNciInstituteCode("O1"); i2.setType("T2"); i2.setValue("V1"); newParticipantCommand.getParticipant().getIdentifiers().add(i1); newParticipantCommand.getParticipant().getIdentifiers().add(i2); doValidate(); assertEquals(6, errors.getErrorCount()); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.firstName")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.lastName")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.gender")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.ethnicity")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.race")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.dateOfBirth")); assertEquals("Wrong number of errors: ", 0, errors.getFieldErrorCount("study.organizationIdentifiers[1].value")); } /* * The Participant has 2 system identifiers with the same value, system and type * This should throw an error about duplicate identifiers * * */ public void testValidateUniqueness3() throws Exception { SystemAssignedIdentifier i1 = new SystemAssignedIdentifier(); i1.setSystemName("S1"); i1.setType("T1"); i1.setValue("V1"); SystemAssignedIdentifier i2 = new SystemAssignedIdentifier(); i2.setSystemName("S1"); i2.setType("T1"); i2.setValue("V1"); newParticipantCommand.getParticipant().addIdentifier(i1); newParticipantCommand.getParticipant().addIdentifier(i2); doValidate(); assertEquals(7, errors.getErrorCount()); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.firstName")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.lastName")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.gender")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.ethnicity")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.race")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.dateOfBirth")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.systemAssignedIdentifiers[1].value")); } /* * The Participant has 2 system identifiers with the same value, different system and teh same type * This should not throw an error about duplicate identifiers * * */ public void testValidateUniqueness4() throws Exception { SystemAssignedIdentifier i1 = new SystemAssignedIdentifier(); i1.setSystemName("S1"); i1.setType("T1"); i1.setValue("V1"); SystemAssignedIdentifier i2 = new SystemAssignedIdentifier(); i2.setSystemName("S2"); i2.setType("T1"); i2.setValue("V1"); newParticipantCommand.getParticipant().addIdentifier(i1); newParticipantCommand.getParticipant().addIdentifier(i2); doValidate(); assertEquals(6, errors.getErrorCount()); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.firstName")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.lastName")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.gender")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.ethnicity")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.race")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.dateOfBirth")); assertEquals("Wrong number of errors", 0, errors.getFieldErrorCount("participant.systemAssignedIdentifiers[1].value")); } /* * The Participant has 3 identifiers * This should not throw an error about duplicate identifiers * * */ public void testValidateUniqueness5() throws Exception { OrganizationAssignedIdentifier i1 = new OrganizationAssignedIdentifier(); i1.setOrganization(new LocalOrganization()); i1.getOrganization().setNciInstituteCode("O3"); i1.setType("T1"); i1.setValue("V1"); SystemAssignedIdentifier i2 = new SystemAssignedIdentifier(); i2.setSystemName("S1"); i2.setType("T1"); i2.setValue("V1"); SystemAssignedIdentifier i3 = new SystemAssignedIdentifier(); i3.setSystemName("S2"); i3.setType("T1"); i3.setValue("V1"); newParticipantCommand.getParticipant().addIdentifier(i1); newParticipantCommand.getParticipant().addIdentifier(i2); newParticipantCommand.getParticipant().addIdentifier(i3); doValidate(); assertEquals(6, errors.getErrorCount()); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.firstName")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.lastName")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.gender")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.ethnicity")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.race")); assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount("participant.dateOfBirth")); assertEquals("Wrong number of errors", 0, errors.getFieldErrorCount("participant.systemAssignedIdentifiers[1].value")); assertEquals("Wrong number of errors", 0, errors.getFieldErrorCount("participant.organizationAssignedIdentifiers[1].value")); } public void testOnBind() { assertEquals(0,newParticipantCommand.getParticipant().getOrganizationIdentifiers().size()); newParticipantCommand.getParticipant().getIdentifiers().add(new OrganizationAssignedIdentifier()); createParticipantTab.onBind(request, newParticipantCommand, errors); assertEquals(newParticipantCommand.getParticipant().getOrganizationIdentifiers().get(0).getOrganization(),newParticipantCommand.getOrganization()); assertTrue(newParticipantCommand.getParticipant().getOrganizationIdentifiers().get(0).getPrimaryIndicator()); } public void testReferenceData(){ Map<Object,Object> refData = createParticipantTab.referenceData(request, newParticipantCommand); assertEquals("New",(String)refData.get("action")); } public synchronized ApplicationContext getDeployedApplicationContext() { return CaaersContextLoader.getApplicationContext(); } }
package org.jboss.as.clustering.jgroups.subsystem; import java.util.Iterator; import java.util.ServiceLoader; import org.jboss.as.clustering.dmr.ModelNodes; import org.jboss.as.clustering.naming.BinderServiceBuilder; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.registry.Resource; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.msc.service.ServiceTarget; import org.jgroups.Channel; import org.wildfly.clustering.jgroups.spi.ChannelFactory; import org.wildfly.clustering.jgroups.spi.service.ChannelBuilder; import org.wildfly.clustering.jgroups.spi.service.ChannelConnectorBuilder; import org.wildfly.clustering.jgroups.spi.service.ChannelServiceName; import org.wildfly.clustering.jgroups.spi.service.ChannelServiceNameFactory; import org.wildfly.clustering.jgroups.spi.service.ProtocolStackServiceName; import org.wildfly.clustering.service.AliasServiceBuilder; import org.wildfly.clustering.service.Builder; import org.wildfly.clustering.spi.ClusteredGroupBuilderProvider; import org.wildfly.clustering.spi.GroupBuilderProvider; /** * Add operation handler for fork resources. * @author Paul Ferraro */ public class ForkAddHandler extends AbstractAddStepHandler { @Override protected void performRuntime(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException { installRuntimeServices(context, operation, resource.getModel()); } static void installRuntimeServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { PathAddress address = context.getCurrentAddress(); String name = address.getElement(address.size() - 1).getValue(); String channel = address.getElement(address.size() - 2).getValue(); ServiceTarget target = context.getServiceTarget(); ForkChannelFactoryBuilder builder = new ForkChannelFactoryBuilder(name); if (model.hasDefined(ProtocolResourceDefinition.WILDCARD_PATH.getKey())) { for (Property property : model.get(ProtocolResourceDefinition.WILDCARD_PATH.getKey()).asPropertyList()) { String protocolName = property.getName(); ModelNode protocol = property.getValue(); ProtocolConfigurationBuilder protocolBuilder = builder.addProtocol(protocolName) .setModule(ModelNodes.asModuleIdentifier(ProtocolResourceDefinition.MODULE.resolveModelAttribute(context, protocol))) .setSocketBinding(ModelNodes.asString(ProtocolResourceDefinition.SOCKET_BINDING.resolveModelAttribute(context, protocol))); StackAddHandler.addProtocolProperties(context, protocol, protocolBuilder).build(target).install(); } } builder.build(target).install(); // Install channel factory alias new AliasServiceBuilder<>(ChannelServiceName.FACTORY.getServiceName(name), ProtocolStackServiceName.CHANNEL_FACTORY.getServiceName(channel), ChannelFactory.class).build(target).install(); // Install channel new ChannelBuilder(name).build(target).install(); // Install channel connector new ChannelConnectorBuilder(name).build(target).install(); // Install channel jndi binding new BinderServiceBuilder<>(JGroupsBindingFactory.createChannelBinding(name), ChannelServiceName.CHANNEL.getServiceName(name), Channel.class).build(target).install(); for (GroupBuilderProvider provider : ServiceLoader.load(ClusteredGroupBuilderProvider.class, ClusteredGroupBuilderProvider.class.getClassLoader())) { Iterator<Builder<?>> groupBuilders = provider.getBuilders(channel, null).iterator(); for (Builder<?> groupBuilder : provider.getBuilders(name, null)) { new AliasServiceBuilder<>(groupBuilder.getServiceName(), groupBuilders.next().getServiceName(), Object.class).build(target).install(); } } } static void removeRuntimeServices(OperationContext context, ModelNode operation, ModelNode model) { String name = context.getCurrentAddressValue(); for (GroupBuilderProvider provider : ServiceLoader.load(ClusteredGroupBuilderProvider.class, ClusteredGroupBuilderProvider.class.getClassLoader())) { for (Builder<?> builder : provider.getBuilders(name, null)) { context.removeService(builder.getServiceName()); } } context.removeService(JGroupsBindingFactory.createChannelBinding(name).getBinderServiceName()); for (ChannelServiceNameFactory factory : ChannelServiceName.values()) { context.removeService(factory.getServiceName(name)); } } }
package org.wildfly.clustering.service.concurrent; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.concurrent.ThreadFactory; /** * {@link ThreadFactory} decorator that associates a specific class loader to created threads. * @author Paul Ferraro * @deprecated Use {@link org.jboss.as.clustering.context.DefaultThreadFactory} instead. */ @Deprecated public class ClassLoaderThreadFactory implements ThreadFactory { private final ThreadFactory factory; private final ClassLoader loader; public ClassLoaderThreadFactory(ThreadFactory factory, ClassLoader loader) { this.factory = factory; this.loader = loader; } @Override public Thread newThread(Runnable r) { Runnable task = () -> { try { r.run(); } finally { // Defensively reset the TCCL this.setContextClassLoader(Thread.currentThread()); } }; return this.setContextClassLoader(this.factory.newThread(task)); } private Thread setContextClassLoader(Thread thread) { PrivilegedAction<Thread> action = () -> { thread.setContextClassLoader(this.loader); return thread; }; return AccessController.doPrivileged(action); } }
package com.codenvy.ide.ext.datasource.client; import static com.codenvy.ide.api.ui.action.Anchor.BEFORE; import static com.codenvy.ide.api.ui.action.IdeActions.GROUP_MAIN_MENU; import static com.codenvy.ide.api.ui.action.IdeActions.GROUP_WINDOW; import com.codenvy.ide.api.extension.Extension; import com.codenvy.ide.api.ui.action.ActionManager; import com.codenvy.ide.api.ui.action.Constraints; import com.codenvy.ide.api.ui.action.DefaultActionGroup; import com.codenvy.ide.api.ui.keybinding.KeyBindingAgent; import com.codenvy.ide.api.ui.keybinding.KeyBuilder; import com.codenvy.ide.api.ui.wizard.DefaultWizard; import com.codenvy.ide.api.ui.workspace.PartStackType; import com.codenvy.ide.api.ui.workspace.WorkspaceAgent; import com.codenvy.ide.collections.Array; import com.codenvy.ide.collections.Collections; import com.codenvy.ide.ext.datasource.client.explorer.DatasourceExplorerPartPresenter; import com.codenvy.ide.ext.datasource.client.newdatasource.NewDatasourceAction; import com.codenvy.ide.ext.datasource.client.newdatasource.NewDatasourceWizardPagePresenter; import com.codenvy.ide.ext.datasource.client.newdatasource.NewDatasourceWizardQualifier; import com.codenvy.ide.ext.datasource.client.newdatasource.connector.AbstractNewDatasourceConnectorPage; import com.codenvy.ide.ext.datasource.client.newdatasource.connector.NewDatasourceConnectorAgent; import com.codenvy.ide.ext.datasource.client.newdatasource.connector.mssqlserver.MssqlserverDatasourceConnectorPage; import com.codenvy.ide.ext.datasource.client.newdatasource.connector.mysql.MysqlDatasourceConnectorPage; import com.codenvy.ide.ext.datasource.client.newdatasource.connector.oracle.OracleDatasourceConnectorPage; import com.codenvy.ide.ext.datasource.client.newdatasource.connector.postgres.PostgresDatasourceConnectorPage; import com.codenvy.ide.ext.datasource.client.sqllauncher.ExecuteSqlAction; import com.codenvy.ide.util.input.CharCodeWithModifiers; import com.codenvy.ide.util.input.KeyCodeMap; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; /** * Extension definition for the datasource plugin. */ @Singleton @Extension(title = "Datasource Extension", version = "1.0.0") public class DatasourceExtension { public static boolean SHOW_ITEM = true; public static String DS_GROUP_MAIN_MENU = "DatasourceMainMenu"; private static String DS_ACTION_SHORTCUT_EXECUTE = "DatasourceActionExecute"; @Inject public DatasourceExtension(WorkspaceAgent workspaceAgent, DatasourceExplorerPartPresenter dsExplorer, ActionManager actionManager, NewDatasourceAction newDSConnectionAction, Provider<NewDatasourceWizardPagePresenter> newDatasourcePageProvider, @NewDatasourceWizardQualifier DefaultWizard wizard, NewDatasourceConnectorAgent connectorAgent, DatasourceUiResources resources, Provider<PostgresDatasourceConnectorPage> pgConnectorPageProvider, Provider<MysqlDatasourceConnectorPage> mysqlConnectorPageProvider, Provider<OracleDatasourceConnectorPage> oracleConnectorPageProvider, Provider<MssqlserverDatasourceConnectorPage> mssqlserverConnectorPageProvider, AvailableJdbcDriversService availableJdbcDrivers, ExecuteSqlAction executeSqlAction, KeyBindingAgent keyBindingAgent) { workspaceAgent.openPart(dsExplorer, PartStackType.NAVIGATION); // create de "Datasource" menu in menubar and insert it DefaultActionGroup mainMenu = (DefaultActionGroup)actionManager .getAction(GROUP_MAIN_MENU); DefaultActionGroup defaultDatasourceMainGroup = new DefaultActionGroup( "Datasource", true, actionManager); actionManager.registerAction(DS_GROUP_MAIN_MENU, defaultDatasourceMainGroup); Constraints beforeWindow = new Constraints(BEFORE, GROUP_WINDOW); mainMenu.add(defaultDatasourceMainGroup, beforeWindow); // add submenu "New datasource" to Datasource menu actionManager.registerAction("NewDSConnection", newDSConnectionAction); defaultDatasourceMainGroup.add(newDSConnectionAction); wizard.addPage(newDatasourcePageProvider); // fetching available drivers list from the server availableJdbcDrivers.fetch(); // inject CSS resources.datasourceUiCSS().ensureInjected(); // add a new postgres connector Array<Provider< ? extends AbstractNewDatasourceConnectorPage>> pgWizardPages = Collections.createArray(); pgWizardPages.add(pgConnectorPageProvider); connectorAgent.register(PostgresDatasourceConnectorPage.PG_DB_ID, "PostgreSQL", resources.getPostgreSqlLogo(), "org.postgresql.Driver", pgWizardPages); // Add a new mysql connector Array<Provider< ? extends AbstractNewDatasourceConnectorPage>> mysqlWizardPages = Collections.createArray(); mysqlWizardPages.add(mysqlConnectorPageProvider); connectorAgent.register(MysqlDatasourceConnectorPage.MYSQL_DB_ID, "MySQL", resources.getMySqlLogo(), "com.mysql.jdbc.Driver", mysqlWizardPages); // add a new oracle connector Array<Provider< ? extends AbstractNewDatasourceConnectorPage>> oracleWizardPages = Collections.createArray(); oracleWizardPages.add(oracleConnectorPageProvider); connectorAgent.register(OracleDatasourceConnectorPage.ORACLE_DB_ID, "Oracle", resources.getOracleLogo(), "oracle.jdbc.OracleDriver", oracleWizardPages); // add a new SQLserver connector Array<Provider< ? extends AbstractNewDatasourceConnectorPage>> sqlServerWizardPages = Collections.createArray(); sqlServerWizardPages.add(mssqlserverConnectorPageProvider); connectorAgent.register(MssqlserverDatasourceConnectorPage.SQLSERVER_DB_ID, "MsSqlServer", resources.getSqlServerLogo(), "net.sourceforge.jtds.jdbc.Driver", sqlServerWizardPages); // Add execute shortcut actionManager.registerAction(DS_ACTION_SHORTCUT_EXECUTE, executeSqlAction); final CharCodeWithModifiers key = new KeyBuilder().action().charCode(KeyCodeMap.ENTER).build(); keyBindingAgent.getGlobal().addKey(key, DS_ACTION_SHORTCUT_EXECUTE); } }
package com.codenvy.api.workspace; import org.eclipse.che.api.account.server.dao.AccountDao; import org.eclipse.che.api.core.ForbiddenException; import org.eclipse.che.api.core.ServerException; import org.eclipse.che.api.core.rest.permission.Operation; import org.eclipse.che.api.core.rest.permission.PermissionManager; import javax.inject.Inject; import javax.inject.Singleton; import java.util.Map; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static org.eclipse.che.api.workspace.server.Constants.START_WORKSPACE; /** * Rejects/allows workspace service related operations. * * @author Eugene Voevodin */ @Singleton public class WorkspacePermissionManager implements PermissionManager { private final AccountDao accountDao; @Inject public WorkspacePermissionManager(AccountDao accountDao) { this.accountDao = accountDao; } @Override public void checkPermission(Operation operation, String userId, Map<String, String> params) throws ForbiddenException, ServerException { requireNonNull(operation, "Operation must not be null"); requireNonNull(userId, "User id must not be null"); requireNonNull(params, "Parameters must not be null"); final String accountId = params.get("accountId"); if (START_WORKSPACE.equals(operation)) { if (accountDao.getMembers(accountId) .stream() .noneMatch(member -> userId.equals(member.getUserId()) && member.getRoles().contains("account/owner"))) { throw new ForbiddenException(format("Workspace start rejected. User '%s' doesn't own account '%s'", userId, accountId)); } } } }
package org.kuali.coeus.propdev.impl.person; import org.apache.commons.lang3.StringUtils; import org.kuali.coeus.common.notification.impl.NotificationHelper; import org.kuali.coeus.common.notification.impl.bo.KcNotification; import org.kuali.coeus.common.notification.impl.bo.NotificationTypeRecipient; import org.kuali.coeus.common.view.wizard.framework.WizardControllerService; import org.kuali.coeus.common.view.wizard.framework.WizardResultsDto; import org.kuali.coeus.propdev.impl.core.*; import org.kuali.coeus.common.questionnaire.framework.answer.Answer; import org.kuali.coeus.common.questionnaire.framework.answer.AnswerHeader; import org.kuali.coeus.propdev.impl.core.ProposalDevelopmentViewHelperServiceImpl; import org.kuali.coeus.propdev.impl.notification.ProposalDevelopmentNotificationContext; import org.kuali.coeus.propdev.impl.notification.ProposalDevelopmentNotificationRenderer; import org.kuali.coeus.propdev.impl.person.attachment.ProposalPersonBiography; import org.kuali.coeus.common.framework.person.PersonTypeConstants; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KeyConstants; import org.kuali.rice.krad.service.KualiRuleService; import org.kuali.rice.krad.uif.UifConstants; import org.kuali.rice.krad.uif.UifParameters; import org.kuali.rice.krad.uif.util.ObjectPropertyUtils; import org.kuali.rice.krad.web.controller.MethodAccessible; import org.kuali.rice.krad.web.form.DocumentFormBase; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; @Controller public class ProposalDevelopmentPersonnelController extends ProposalDevelopmentControllerBase { public static final String PROPOSAL_PERSONS_PATH = "document.developmentProposal.proposalPersons"; public static final String CERTIFICATION_UPDATE_FEATURE_FLAG = "CERTIFICATION_UPDATE_FEATURE_FLAG"; public static final String CERTIFICATION_ACTION_TYPE_CODE = "104"; public static final String CERTIFY_NOTIFICATION = "Certify Notification"; public static final String KEY_PERSON_PROJECT_ROLE = "keyPersonProjectRole"; public static final String PERSON_ROLE = "personRole"; @Autowired @Qualifier("wizardControllerService") private WizardControllerService wizardControllerService; @Autowired @Qualifier("keyPersonnelService") private KeyPersonnelService keyPersonnelService; @Autowired @Qualifier("kualiRuleService") private KualiRuleService kualiRuleService; @Transactional @RequestMapping(value = "/proposalDevelopment", params={"methodToCall=navigate", "actionParameters[navigateToPageId]=PropDev-PersonnelPage"}) public ModelAndView navigateToPersonnel(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception { for (ProposalPerson person : form.getProposalDevelopmentDocument().getDevelopmentProposal().getProposalPersons()) { //workaround for the document associated with the OJB retrived dev prop not having a workflow doc. person.setDevelopmentProposal(form.getProposalDevelopmentDocument().getDevelopmentProposal()); person.getQuestionnaireHelper().populateAnswers(); } return super.navigate(form, result, request, response); } @Transactional @RequestMapping(value = "/proposalDevelopment", params={"methodToCall=checkForNewerVersionOfCertification"}) public ModelAndView checkForNewerVersionOfCertification(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form) { Boolean certificationUpdateFeatureFlag = getParameterService().getParameterValueAsBoolean(Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT, Constants.PARAMETER_COMPONENT_DOCUMENT, CERTIFICATION_UPDATE_FEATURE_FLAG); if (certificationUpdateFeatureFlag && isNewerVersionPublished(form)) { return getModelAndViewService().showDialog(ProposalDevelopmentConstants.KradConstants.PROP_DEV_PERSONNEL_PAGE_UPDATE_CERTIFICATION_DIALOG,false,form); } return null; } protected boolean isNewerVersionPublished(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form) { for (ProposalPerson person : form.getProposalDevelopmentDocument().getDevelopmentProposal().getProposalPersons()) { if (person.getQuestionnaireHelper().getAnswerHeaders().get(0).isNewerVersionPublished()) { return true; } } return false; } @Transactional @RequestMapping(value = "/proposalDevelopment", params = "methodToCall=updateCertification") public ModelAndView updateCertification(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form) throws Exception { for (ProposalPerson person : form.getProposalDevelopmentDocument().getDevelopmentProposal().getProposalPersons()) { int index = 0; for (AnswerHeader answerHeader : person.getQuestionnaireHelper().getAnswerHeaders()) { answerHeader.setUpdateOption(form.getUpdateAnswerHeader().getUpdateOption()); person.getQuestionnaireHelper().updateQuestionnaireAnswer(index); index++; } } form.setUpdateAnswerHeader(new AnswerHeader()); return super.save(form); } @Transactional @RequestMapping(value = "/proposalDevelopment", params={"methodToCall=prepareAddPersonDialog"}) public ModelAndView prepareAddPersonDialog(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form) { form.getAddKeyPersonHelper().setLineType(PersonTypeConstants.EMPLOYEE.getCode()); return getModelAndViewService().showDialog(ProposalDevelopmentConstants.KradConstants.PROP_DEV_PERSONNEL_PAGE_WIZARD, true, form); } @Transactional @RequestMapping(value = "/proposalDevelopment", params={"methodToCall=navigateToPersonError"}) public ModelAndView navigateToPersonError(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception { form.setAjaxReturnType("update-page"); return navigateToPersonnel(form, result, request, response); } @Transactional @RequestMapping(value = "/proposalDevelopment", params={"methodToCall=save", "pageId=PropDev-PersonnelPage"}) public ModelAndView save(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentDocumentForm pdForm = (ProposalDevelopmentDocumentForm) form; ModelAndView mv = super.save(form); return mv; } @Transactional @RequestMapping(value = "/proposalDevelopment", params="methodToCall=performPersonnelSearch") public ModelAndView performPersonnelSearch(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception { form.getAddKeyPersonHelper().getResults().clear(); List<Object> results = new ArrayList<Object>(); for (Object object : getWizardControllerService().performWizardSearch(form.getAddKeyPersonHelper().getLookupFieldValues(),form.getAddKeyPersonHelper().getLineType())) { WizardResultsDto wizardResult = (WizardResultsDto) object; String personId = wizardResult.getKcPerson() != null ? wizardResult.getKcPerson().getPersonId() : wizardResult.getRolodex().getRolodexId().toString(); if (!personAlreadyExists(personId,form.getDevelopmentProposal().getProposalPersons())) { results.add(object); } } form.getAddKeyPersonHelper().setResults(results); return getRefreshControllerService().refresh(form); } @Transactional @RequestMapping(value = "/proposalDevelopment", params="methodToCall=addPerson") public ModelAndView addPerson(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalPerson newProposalPerson = new ProposalPerson(); for (Object object : form.getAddKeyPersonHelper().getResults()) { WizardResultsDto wizardResult = (WizardResultsDto) object; if (wizardResult.isSelected() == true) { if (wizardResult.getKcPerson() != null) { newProposalPerson.setPersonId(wizardResult.getKcPerson().getPersonId()); newProposalPerson.setFullName(wizardResult.getKcPerson().getFullName()); newProposalPerson.setUserName(wizardResult.getKcPerson().getUserName()); } else if (wizardResult.getRolodex() != null) { newProposalPerson.setRolodexId(wizardResult.getRolodex().getRolodexId()); newProposalPerson.setFullName(wizardResult.getRolodex().getFullName()); } break; } } newProposalPerson.setProposalPersonRoleId((String) form.getAddKeyPersonHelper().getParameter(PERSON_ROLE)); if (form.getAddKeyPersonHelper().getParameterMap().containsKey(KEY_PERSON_PROJECT_ROLE)) { newProposalPerson.setProjectRole((String) form.getAddKeyPersonHelper().getParameter(KEY_PERSON_PROJECT_ROLE)); } if (!getKualiRuleService().applyRules(new AddKeyPersonEvent(form.getProposalDevelopmentDocument(),newProposalPerson))) { return reportKeyPersonError(form); } getKeyPersonnelService().addProposalPerson(newProposalPerson, form.getProposalDevelopmentDocument()); Collections.sort(form.getProposalDevelopmentDocument().getDevelopmentProposal().getProposalPersons(), new ProposalPersonRoleComparator()); form.getAddKeyPersonHelper().reset(); form.setAjaxReturnType(UifConstants.AjaxReturnTypes.UPDATEPAGE.getKey()); super.save(form); return getKcCommonControllerService().closeDialog(ProposalDevelopmentConstants.KradConstants.PROP_DEV_PERSONNEL_PAGE_WIZARD, form); } protected ModelAndView reportKeyPersonError(ProposalDevelopmentDocumentForm form) { form.setAjaxReturnType(UifConstants.AjaxReturnTypes.UPDATECOMPONENT.getKey()); form.setUpdateComponentId(ProposalDevelopmentConstants.KradConstants.PROP_DEV_PERSONNEL_PAGE_WIZARD); return getModelAndViewService().getModelAndView(form); } @Transactional @RequestMapping(value = "/proposalDevelopment", params={"methodToCall=navigate", "actionParameters[navigateToPageId]=PropDev-CreditAllocationPage"}) public ModelAndView navigateToCreditAllocation(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mv = super.navigate(form,result,request,response); ((ProposalDevelopmentViewHelperServiceImpl) form.getViewHelperService()).populateCreditSplits(form); return mv; } @Transactional @RequestMapping(value = "/proposalDevelopment", params={"methodToCall=deleteLine", "pageId=PropDev-PersonnelPage"}) public ModelAndView deletePerson(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, @RequestParam("actionParameters[" + UifParameters.SELECTED_COLLECTION_PATH + "]") String selectedCollectionPath, @RequestParam("actionParameters[" + UifParameters.SELECTED_LINE_INDEX + "]") String selectedLine) throws Exception { if (selectedCollectionPath.equals(PROPOSAL_PERSONS_PATH)) { Collection<Object> collection = ObjectPropertyUtils.getPropertyValue(form, selectedCollectionPath); Object deleteLine = ((List<Object>) collection).get(Integer.parseInt(selectedLine)); deleteProposalPersonBios(form.getDevelopmentProposal(), (ProposalPerson) deleteLine); } return getCollectionControllerService().deleteLine(form); } private void deleteProposalPersonBios(DevelopmentProposal proposal, ProposalPerson deleteLine) { List<ProposalPersonBiography> tmpBios= new ArrayList<>(); String personIdOfDeletedLine = deleteLine.getPersonId(); for (ProposalPersonBiography biography : proposal.getPropPersonBios()) { if (personIdOfDeletedLine == null) { Integer rolodexId = deleteLine.getRolodexId(); if (biography.getRolodexId() == null || rolodexId.compareTo(biography.getRolodexId()) != 0) { tmpBios.add(biography); } } else { if (!biography.getPersonId().equals(personIdOfDeletedLine)) tmpBios.add(biography); } } proposal.setPropPersonBios(tmpBios); } @Transactional @RequestMapping(value = "/proposalDevelopment", params = "methodToCall=clearAnswers") public ModelAndView clearAnswers(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentDocumentForm pdForm = (ProposalDevelopmentDocumentForm) form; String personNumber = pdForm.getActionParamaterValue("personNumber"); for (ProposalPerson person : pdForm.getProposalDevelopmentDocument().getDevelopmentProposal().getProposalPersons()) { if (StringUtils.equals(personNumber, person.getProposalPersonNumber().toString())) { //get the certification questions AnswerHeader ah = person.getQuestionnaireHelper().getAnswerHeaders().get(0); for (Answer answer : ah.getAnswers()) { answer.setAnswer(null); } } } saveAnswerHeaders(pdForm,request.getParameter(UifParameters.PAGE_ID)); ModelAndView mv = this.save(pdForm, result, request, response); return mv; } @Transactional @RequestMapping(value = "/proposalDevelopment", params = "methodToCall=certificationToggle") public ModelAndView certificationToggle(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentDocumentForm pdForm = (ProposalDevelopmentDocumentForm) form; String personNumber = pdForm.getActionParamaterValue("personNumber"); for (ProposalPerson person : pdForm.getProposalDevelopmentDocument().getDevelopmentProposal().getProposalPersons()) { if (StringUtils.equals(personNumber, person.getProposalPersonNumber().toString())) { person.setOptInCertificationStatus(!person.getOptInCertificationStatus()); if (!person.getOptInCertificationStatus()){ return clearAnswers(form, result, request, response); } } } return getRefreshControllerService().refresh(form); } @Transactional @RequestMapping(value = "/proposalDevelopment", params = "methodToCall=viewCertification") public ModelAndView viewCertification(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, @RequestParam("actionParameters[" + UifParameters.SELECTED_LINE_INDEX + "]") String selectedLine) throws Exception { ProposalPerson person = form.getDevelopmentProposal().getProposalPerson(Integer.parseInt(selectedLine)); person.getQuestionnaireHelper().populateAnswers(); form.setProposalPersonQuestionnaireHelper(person.getQuestionnaireHelper()); return getModelAndViewService().showDialog("PropDev-SubmitPage-CertificationDetail",true,form); } @Transactional @RequestMapping(value = "/proposalDevelopment", params = "methodToCall=prepareVerifyCertificationDialog") public ModelAndView prepareVerifyCertificationDialog(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, @RequestParam("actionParameters[" + UifParameters.SELECTED_LINE_INDEX + "]") String selectedLine) throws Exception { ProposalPerson person = form.getDevelopmentProposal().getProposalPerson(Integer.parseInt(selectedLine)); prepareNoticationHelper(form, person); if (form.getNotificationHelper().getPromptUserForNotificationEditor(form.getNotificationHelper().getNotificationContext())) { return getModelAndViewService().showDialog(ProposalDevelopmentConstants.KradConstants.PROP_DEV_PERSONNEL_PAGE_VERIFY_NOTIFICATION_DIALOG, true, form); } else { return sendCertificationNotification(form); } } protected void prepareNoticationHelper(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, ProposalPerson person) { NotificationHelper<ProposalDevelopmentNotificationContext> notificationHelper = form.getNotificationHelper(); notificationHelper.setNotification(getKcNotificationService().createNotificationObject(createNotificationContext(form.getDevelopmentProposal(), person))); notificationHelper.setNotificationContext(createNotificationContext(form.getDevelopmentProposal(), person)); notificationHelper.setNotificationRecipients(createRecipientFromPerson(person)); notificationHelper.setNewPersonId(person.getPersonId()); } protected ProposalDevelopmentNotificationContext createNotificationContext(DevelopmentProposal developmentProposal, ProposalPerson person) { ProposalDevelopmentNotificationContext context = new ProposalDevelopmentNotificationContext(developmentProposal, CERTIFICATION_ACTION_TYPE_CODE, CERTIFY_NOTIFICATION); ProposalDevelopmentNotificationRenderer renderer = (ProposalDevelopmentNotificationRenderer) context.getRenderer(); renderer.setDevelopmentProposal(developmentProposal); renderer.setProposalPerson(person); return context; } protected List<NotificationTypeRecipient> createRecipientFromPerson(ProposalPerson person) { List<NotificationTypeRecipient> notificationRecipients = new ArrayList<>(); NotificationTypeRecipient recipient = new NotificationTypeRecipient(); recipient.setPersonId(person.getPersonId()); recipient.setFullName(person.getFullName()); notificationRecipients.add(recipient); return notificationRecipients; } @Transactional @RequestMapping(value = "/proposalDevelopment", params = "methodToCall=sendCertificationNotification") public ModelAndView sendCertificationNotification(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form) throws Exception { NotificationHelper<ProposalDevelopmentNotificationContext> notificationHelper = form.getNotificationHelper(); ProposalPerson person =((ProposalDevelopmentNotificationRenderer) notificationHelper.getNotificationContext().getRenderer()).getProposalPerson(); getKcNotificationService().sendNotification(notificationHelper.getNotificationContext(), notificationHelper.getNotification(), notificationHelper.getNotificationRecipients()); getGlobalVariableService().getMessageMap().putInfoForSectionId(ProposalDevelopmentConstants.KradConstants.PROP_DEV_PERSONNEL_PAGE_COLLECTION, KeyConstants.INFO_NOTIFICATIONS_SENT, person.getFullName() + " " + notificationHelper.getNotification().getCreateTimestamp()); person.setLastNotification(getDateTimeService().getCurrentTimestamp()); return super.save(form); } @Transactional @RequestMapping(value = "/proposalDevelopment", params = "methodToCall=sendAllCertificationNotifications") public ModelAndView sendAllCertificationNotifications(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form) throws Exception { int index = 0; for (ProposalPerson proposalPerson : form.getDevelopmentProposal().getProposalPersons()) { if (proposalPerson.isSelectedPerson() && !isCertificationComplete(proposalPerson) ) { sendPersonNotification(form, String.valueOf(index)); } index++; } return super.save(form); } protected boolean isCertificationComplete(ProposalPerson proposalPerson) { boolean certificationComplete = true; for (AnswerHeader answerHeader : proposalPerson.getQuestionnaireHelper().getAnswerHeaders()) { certificationComplete &= answerHeader.isCompleted(); } return certificationComplete; } public void sendPersonNotification(ProposalDevelopmentDocumentForm form, String selectedLine) throws Exception { ProposalPerson person = form.getDevelopmentProposal().getProposalPerson(Integer.parseInt(selectedLine)); ProposalDevelopmentNotificationContext context = createNotificationContext(form.getDevelopmentProposal(), person); KcNotification notification = getKcNotificationService().createNotificationObject(context); getKcNotificationService().sendNotification(context, notification, createRecipientFromPerson(person)); getGlobalVariableService().getMessageMap().putInfoForSectionId(ProposalDevelopmentConstants.KradConstants.PROP_DEV_PERSONNEL_PAGE_COLLECTION, KeyConstants.INFO_NOTIFICATIONS_SENT, person.getFullName() + " " + notification.getCreateTimestamp()); person.setLastNotification(getDateTimeService().getCurrentTimestamp()); } @Transactional @RequestMapping(value = "/proposalDevelopment", params={"methodToCall=movePersonUp"}) public ModelAndView movePersonUp(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, @RequestParam("actionParameters[" + UifParameters.SELECTED_LINE_INDEX + "]") String selectedLine) throws Exception { swapAdjacentPersonnel(form.getDevelopmentProposal().getProposalPersons(), Integer.parseInt(selectedLine), MoveOperationEnum.MOVING_PERSON_UP); return getRefreshControllerService().refresh(form); } @Transactional @RequestMapping(value = "/proposalDevelopment", params={"methodToCall=movePersonDown"}) public ModelAndView movePersonDown(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, @RequestParam("actionParameters[" + UifParameters.SELECTED_LINE_INDEX + "]") String selectedLine) throws Exception { swapAdjacentPersonnel(form.getDevelopmentProposal().getProposalPersons(), Integer.parseInt(selectedLine), MoveOperationEnum.MOVING_PERSON_DOWN); return getRefreshControllerService().refresh(form); } @MethodAccessible @Transactional @RequestMapping(value = "/proposalDevelopment", params = "methodToCall=certifyAnswers") public ModelAndView certifyAnswers(@ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form) throws Exception{ String selectedPersonId = form.getProposalPersonQuestionnaireHelper().getProposalPerson().getPersonId(); for (ProposalPerson proposalPerson : form.getDevelopmentProposal().getProposalPersons()) { if (StringUtils.equals(proposalPerson.getPersonId(),selectedPersonId)) { proposalPerson.setQuestionnaireHelper(form.getProposalPersonQuestionnaireHelper()); } } return super.save(form); } private enum MoveOperationEnum { MOVING_PERSON_DOWN (1), MOVING_PERSON_UP(-1); private int offset; private MoveOperationEnum(int offset) { this.offset = offset; } public int getOffset() { return offset; } }; private void swapAdjacentPersonnel(List<ProposalPerson> keyPersonnel, int index1, MoveOperationEnum op) { ProposalPerson movingPerson = keyPersonnel.get(index1); if ((op == MoveOperationEnum.MOVING_PERSON_DOWN && movingPerson.isMoveDownAllowed()) || (op == MoveOperationEnum.MOVING_PERSON_UP && movingPerson.isMoveUpAllowed())) { int index2 = index1 + op.getOffset(); keyPersonnel.set(index1, keyPersonnel.get(index2)); keyPersonnel.set(index2, movingPerson); } } protected boolean personAlreadyExists(String personId, List<ProposalPerson> existingPersons) { for (ProposalPerson existingPerson: existingPersons ) { if (personId.equals(existingPerson.getPersonId())) { return true; } } return false; } protected KeyPersonnelService getKeyPersonnelService() { return keyPersonnelService; } public void setKeyPersonnelService(KeyPersonnelService keyPersonnelService) { this.keyPersonnelService = keyPersonnelService; } public WizardControllerService getWizardControllerService() { return wizardControllerService; } public void setWizardControllerService(WizardControllerService wizardControllerService) { this.wizardControllerService = wizardControllerService; } public static class ProposalPersonRoleComparator implements Comparator<ProposalPerson> { @Override public int compare(ProposalPerson person1, ProposalPerson person2) { int retval = 0; if (person1.isInvestigator() || person2.isInvestigator()) { if (person1.isPrincipalInvestigator() || person2.isPrincipalInvestigator()) { if (person1.isPrincipalInvestigator()) { retval } if (person2.isPrincipalInvestigator()) { retval++; } } if (retval == 0) { if (person1.isMultiplePi() || person2.isMultiplePi()) { if (person1.isMultiplePi()) { retval } if (person2.isMultiplePi()) { retval++; } } } } if (retval == 0) { if (person1.isCoInvestigator() || person2.isCoInvestigator()) { if (person1.isCoInvestigator()) { retval } if (person2.isCoInvestigator()) { retval++; } } } if (retval == 0) { if (person1.isKeyPerson() || person2.isKeyPerson()) { if (person1.isKeyPerson()) { retval } if (person2.isKeyPerson()) { retval++; } } } return retval; } } public KualiRuleService getKualiRuleService() { return kualiRuleService; } public void setKualiRuleService(KualiRuleService kualiRuleService) { this.kualiRuleService = kualiRuleService; } }
package com.sap.core.odata.processor.jpa.access; import java.math.BigDecimal; import java.util.Calendar; import java.util.Date; import java.util.UUID; import com.sap.core.odata.api.edm.EdmSimpleTypeKind; public class JPATypeConvertor { public static EdmSimpleTypeKind convertToEdmSimpleType(Class<?> jpaType){ if (jpaType.equals(String.class)) return EdmSimpleTypeKind.String; else if (jpaType.equals(Long.class) || jpaType.equals(long.class)) return EdmSimpleTypeKind.Int64; else if (jpaType.equals(Short.class) || jpaType.equals(short.class)) return EdmSimpleTypeKind.Int16; else if (jpaType.equals(Integer.class) || jpaType.equals(int.class)) return EdmSimpleTypeKind.Int32; else if (jpaType.equals(Double.class) || jpaType.equals(double.class)) return EdmSimpleTypeKind.Double; else if (jpaType.equals(Float.class) || jpaType.equals(float.class)) return EdmSimpleTypeKind.Single; else if (jpaType.equals(BigDecimal.class)) return EdmSimpleTypeKind.Decimal; else if (jpaType.equals(byte[].class)) return EdmSimpleTypeKind.Binary; else if (jpaType.equals(Byte.class)) return EdmSimpleTypeKind.Byte; else if (jpaType.equals(Byte[].class)) return EdmSimpleTypeKind.Binary; else if (jpaType.equals(Boolean.class)) return EdmSimpleTypeKind.Boolean; else if (jpaType.equals(Date.class)) return EdmSimpleTypeKind.DateTime; else if (jpaType.equals(Calendar.class)) return EdmSimpleTypeKind.DateTime; else if (jpaType.equals(UUID.class)) return EdmSimpleTypeKind.Guid; return null; } }
package com.diluv.catalejo.java.lib; import java.util.HashMap; import java.util.Map; /** * A basic enumeration that allows for java variables to be mapped to their * major version number. * * @author Tyler Hancock (Darkhax) */ public enum JavaVersion { JAVA_1_1("JDK 1.1", 0x2D), JAVA_1_2("JDK 1.2", 0x2E), JAVA_1_3("JDK 1.3", 0x2F), JAVA_1_4("JDK 1.4", 0x30), JAVA_1_5("Java SE 5.0", 0x31), JAVA_1_6("Java SE 6.0", 0x32), JAVA_1_7("Java SE 7", 0x33), JAVA_1_8("Java SE 8", 0x34), JAVA_1_9("Java SE 9", 0x35), JAVA_1_10("Java SE 10", 0x36), JAVA_1_11("Java SE 11", 0x37), JAVA_1_12("Java SE 12", 0x38), JAVA_1_13("Java SE 13", 0x39), JAVA_1_14("Java SE 14", 0x3A); /** * A map of version numbers to localizations. */ private static final Map<Integer, String> VERSION_TO_LOCAL = new HashMap<>(); /** * A map of localizations to version numbers. */ private static final Map<String, Integer> LOCAL_TO_VERSION = new HashMap<>(); static { for (final JavaVersion version : JavaVersion.values()) { VERSION_TO_LOCAL.put(version.getNumber(), version.getLocal()); LOCAL_TO_VERSION.put(version.getLocal(), version.getNumber()); } } /** * Gets a localization for a major version integer. * * @param version The major version number. * @return The localization value. */ public static String getLocal (int version) { final String local = VERSION_TO_LOCAL.get(version); return local == null ? "unknown" : local; } /** * The localization. */ private final String local; /** * The major version number. */ private final int number; JavaVersion (String local, int number) { this.local = local; this.number = number; } /** * Gets the localization. * * @return The localization. */ public String getLocal () { return this.local; } /** * Gets the major version number. * * @return The major version number. */ public int getNumber () { return this.number; } }
package info.tregmine.database.db; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import info.tregmine.quadtree.Rectangle; import info.tregmine.zones.Zone; import info.tregmine.zones.Lot; import info.tregmine.database.IZonesDAO; import info.tregmine.database.DAOException; public class DBZonesDAO implements IZonesDAO { private Connection conn; public DBZonesDAO(Connection conn) { this.conn = conn; } private List<Rectangle> getZoneRectangles(int zoneId) throws DAOException { String sql = "SELECT * FROM zone_rect WHERE zone_id = ?"; List<Rectangle> rects = new ArrayList<Rectangle>(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, zoneId); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { while (rs.next()) { int x1 = rs.getInt("rect_x1"); int y1 = rs.getInt("rect_y1"); int x2 = rs.getInt("rect_x2"); int y2 = rs.getInt("rect_y2"); rects.add(new Rectangle(x1, y1, x2, y2)); } } } catch (SQLException e) { throw new DAOException(sql, e); } return rects; } private Map<Integer, Zone.Permission> getZonePermissions(int zoneId) throws DAOException { String sql = "SELECT * FROM zone_user " + "WHERE zone_id = ?"; Map<Integer, Zone.Permission> permissions = new HashMap<>(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, zoneId); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { while (rs.next()) { int playerId = rs.getInt("user_id"); Zone.Permission permission = Zone.Permission.fromString(rs.getString("user_perm")); permissions.put(playerId, permission); } } } catch (SQLException e) { throw new DAOException(sql, e); } return permissions; } @Override public List<Zone> getZones(String world) throws DAOException { String sql = "SELECT * FROM zone WHERE zone_world = ?"; List<Zone> zones = new ArrayList<Zone>(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, world); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { while (rs.next()) { Zone zone = new Zone(); zone.setId(rs.getInt("zone_id")); zone.setWorld(rs.getString("zone_world")); zone.setName(rs.getString("zone_name")); zone.setEnterDefault("1".equals(rs.getString("zone_enterdefault"))); zone.setPlaceDefault("1".equals(rs.getString("zone_placedefault"))); zone.setDestroyDefault("1".equals(rs.getString("zone_destroydefault"))); zone.setPvp("1".equals(rs.getString("zone_pvp"))); zone.setHostiles("1".equals(rs.getString("zone_hostiles"))); zone.setCommunist("1".equals(rs.getString("zone_communist"))); zone.setPublicProfile("1".equals(rs.getString("zone_publicprofile"))); zone.setTextEnter(rs.getString("zone_entermessage")); zone.setTextExit(rs.getString("zone_exitmessage")); zone.setTexture(rs.getString("zone_texture")); zone.setMainOwner(rs.getString("zone_owner")); int flags = rs.getInt("zone_flags"); for (Zone.Flags flag : Zone.Flags.values()) { if ((flags & (1 << flag.ordinal())) != 0) { zone.setFlag(flag); } } zones.add(zone); } } } catch (SQLException e) { throw new DAOException(sql, e); } for (Zone zone : zones) { zone.setRects(getZoneRectangles(zone.getId())); zone.setUsers(getZonePermissions(zone.getId())); } return zones; } @Override public int createZone(Zone zone) throws DAOException { String sql = "INSERT INTO zone (zone_world, zone_name, " + "zone_enterdefault, zone_placedefault, zone_destroydefault, " + "zone_pvp, zone_hostiles, zone_communist, zone_publicprofile, " + "zone_entermessage, zone_exitmessage, zone_owner) "; sql += "VALUES (?, ?,?,?,?,?,?,?,?,?,?,?)"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, zone.getWorld()); stmt.setString(2, zone.getName()); stmt.setString(3, zone.getEnterDefault() ? "1" : "0"); stmt.setString(4, zone.getPlaceDefault() ? "1" : "0"); stmt.setString(5, zone.getDestroyDefault() ? "1" : "0"); stmt.setString(6, zone.isPvp() ? "1" : "0"); stmt.setString(7, zone.hasHostiles() ? "1" : "0"); stmt.setString(8, zone.isCommunist() ? "1" : "0"); stmt.setString(9, zone.hasPublicProfile() ? "1" : "0"); stmt.setString(10, zone.getTextEnter()); stmt.setString(11, zone.getTextExit()); stmt.setString(12, zone.getMainOwner()); stmt.execute(); stmt.execute("SELECT LAST_INSERT_ID()"); try (ResultSet rs = stmt.getResultSet()) { if (!rs.next()) { return 0; } zone.setId(rs.getInt(1)); return zone.getId(); } } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public void updateZone(Zone zone) throws DAOException { String sql = "UPDATE zone SET zone_world = ?, zone_name = ?, " + "zone_enterdefault = ?, zone_placedefault = ?, " + "zone_destroydefault = ?, zone_pvp = ?, zone_hostiles = ?, " + "zone_communist = ?, zone_publicprofile = ?, " + "zone_entermessage = ?, zone_exitmessage = ?, " + "zone_flags = ? " + "WHERE zone_id = ?"; int flags = 0; for (Zone.Flags flag : Zone.Flags.values()) { flags |= zone.hasFlag(flag) ? 1 << flag.ordinal() : 0; } try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, zone.getWorld()); stmt.setString(2, zone.getName()); stmt.setString(3, zone.getEnterDefault() ? "1" : "0"); stmt.setString(4, zone.getPlaceDefault() ? "1" : "0"); stmt.setString(5, zone.getDestroyDefault() ? "1" : "0"); stmt.setString(6, zone.isPvp() ? "1" : "0"); stmt.setString(7, zone.hasHostiles() ? "1" : "0"); stmt.setString(8, zone.isCommunist() ? "1" : "0"); stmt.setString(9, zone.hasPublicProfile() ? "1" : "0"); stmt.setString(10, zone.getTextEnter()); stmt.setString(11, zone.getTextExit()); stmt.setInt(12, flags); stmt.setInt(13, zone.getId()); stmt.execute(); } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public void deleteZone(int id) throws DAOException { String sqlDeleteZone = "DELETE FROM zone WHERE zone_id = ?"; try (PreparedStatement stmt = conn.prepareStatement(sqlDeleteZone)) { stmt.setInt(1, id); stmt.execute(); } catch (SQLException e) { throw new DAOException(sqlDeleteZone, e); } String sqlDeleteRect = "DELETE FROM zone_rect WHERE zone_id = ?"; try (PreparedStatement stmt = conn.prepareStatement(sqlDeleteRect)) { stmt.setInt(1, id); stmt.execute(); } catch (SQLException e) { throw new DAOException(sqlDeleteRect, e); } String sqlDeleteUser = "DELETE FROM zone_user WHERE zone_id = ?"; try (PreparedStatement stmt = conn.prepareStatement(sqlDeleteUser)) { stmt.setInt(1, id); stmt.execute(); } catch (SQLException e) { throw new DAOException(sqlDeleteUser, e); } } @Override public void addRectangle(int zoneId, Rectangle rect) throws DAOException { String sql = "INSERT INTO zone_rect (zone_id, rect_x1, rect_y1, " + "rect_x2, rect_y2) VALUES (?, ?, ?, ?, ?)"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, zoneId); stmt.setInt(2, rect.getLeft()); stmt.setInt(3, rect.getTop()); stmt.setInt(4, rect.getRight()); stmt.setInt(5, rect.getBottom()); stmt.execute(); } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public void addUser(int zoneId, int userId, Zone.Permission perm) throws DAOException { String sql = "INSERT INTO zone_user (zone_id, user_id, user_perm) "; sql += "VALUES (?,?,?)"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, zoneId); stmt.setInt(2, userId); stmt.setString(3, perm.toString()); stmt.execute(); } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public void deleteUser(int zoneId, int userId) throws DAOException { String sql = "DELETE FROM zone_user WHERE zone_id = ? AND user_id = ? "; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, zoneId); stmt.setInt(2, userId); stmt.execute(); } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public List<Lot> getLots(String world) throws DAOException { String sql = "SELECT zone_lot.* FROM zone_lot " + "INNER JOIN zone USING (zone_id) WHERE zone_world = ?"; List<Lot> lots = new ArrayList<Lot>(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, world); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { while (rs.next()) { Lot lot = new Lot(); lot.setId(rs.getInt("lot_id")); lot.setName(rs.getString("lot_name")); lot.setZoneId(rs.getInt("zone_id")); int x1 = rs.getInt("lot_x1"); int y1 = rs.getInt("lot_y1"); int x2 = rs.getInt("lot_x2"); int y2 = rs.getInt("lot_y2"); lot.setRect(new Rectangle(x1, y1, x2, y2)); int flags = rs.getInt("lot_flags"); for (Lot.Flags flag : Lot.Flags.values()) { if ((flags & (1 << flag.ordinal())) != 0) { lot.setFlag(flag); } } lots.add(lot); } } } catch (SQLException e) { throw new DAOException(sql, e); } for (Lot lot : lots) { lot.setOwner(getLotOwners(lot.getId())); } return lots; } @Override public List<Integer> getLotOwners(int lotId) throws DAOException { String sql = "SELECT * FROM zone_lotuser " + "WHERE lot_id = ?"; List<Integer> owners = new ArrayList<>(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, lotId); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { while (rs.next()) { owners.add(rs.getInt("user_id")); } } } catch (SQLException e) { throw new DAOException(sql, e); } return owners; } @Override public void addLot(Lot lot) throws DAOException { String sql = "INSERT INTO zone_lot (zone_id, lot_name, lot_x1, " + "lot_y1, lot_x2, lot_y2) VALUES (?,?,?,?,?,?)"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, lot.getZoneId()); stmt.setString(2, lot.getName()); Rectangle rect = lot.getRect(); stmt.setInt(3, rect.getLeft()); stmt.setInt(4, rect.getTop()); stmt.setInt(5, rect.getRight()); stmt.setInt(6, rect.getBottom()); stmt.execute(); stmt.execute("SELECT LAST_INSERT_ID()"); try (ResultSet rs = stmt.getResultSet()) { if (rs.next()) { lot.setId(rs.getInt(1)); } } } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public void updateLotFlags(Lot lot) throws DAOException { String sql = "UPDATE zone_lot SET lot_flags = ? WHERE lot_id = ?"; int flags = 0; for (Lot.Flags flag : Lot.Flags.values()) { flags |= lot.hasFlag(flag) ? 1 << flag.ordinal() : 0; } try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, flags); stmt.setInt(2, lot.getId()); stmt.execute(); } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public void deleteLot(int lotId) throws DAOException { String sql = "DELETE FROM zone_lot WHERE lot_id = ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, lotId); stmt.execute(); } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public void addLotUser(int lotId, int userId) throws DAOException { String sql = "INSERT INTO zone_lotuser (lot_id, user_id) "; sql += "VALUES (?,?)"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, lotId); stmt.setInt(2, userId); stmt.execute(); } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public void deleteLotUsers(int lotId) throws DAOException { String sql = "DELETE FROM zone_lotuser WHERE lot_id = ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, lotId); stmt.execute(); } catch (SQLException e) { throw new DAOException(sql, e); } } @Override public void deleteLotUser(int lotId, int userId) throws DAOException { String sql = "DELETE FROM zone_lotuser WHERE lot_id = ? AND user_id = ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, lotId); stmt.setInt(2, userId); stmt.execute(); } catch (SQLException e) { throw new DAOException(sql, e); } } }
package com.censoredsoftware.Demigods; import java.net.URL; import java.security.CodeSource; import java.util.ArrayList; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.event.HandlerList; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import com.bekvon.bukkit.residence.Residence; import com.censoredsoftware.Demigods.API.*; import com.censoredsoftware.Demigods.Handlers.Abstract.DemigodsPlugin; import com.censoredsoftware.Demigods.Handlers.DCommandHandler; import com.censoredsoftware.Demigods.Handlers.DMetricsEventCreator; import com.censoredsoftware.Demigods.Handlers.DScheduler; import com.censoredsoftware.Demigods.Handlers.Database.DFlatFile; import com.censoredsoftware.Demigods.Libraries.Objects.DisconnectReasonFilter; import com.censoredsoftware.Demigods.Listeners.*; import com.massivecraft.factions.P; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; public class Demigods extends JavaPlugin { // This plugin public static Demigods INSTANCE = null; // Soft dependencies public static WorldGuardPlugin WORLDGUARD = null; public static P FACTIONS = null; public static Residence RESIDENCE = null; // API public AbilityAPI ability = null; public AdminAPI admin = null; public BattleAPI battle = null; public BlockAPI block = null; public CharAPI character = null; public ConfigAPI config = null; public DataAPI data = null; public DeityAPI deity = null; public InstanceAPI instance = null; public InvAPI inventory = null; public ItemAPI item = null; public MetricsAPI metrics = null; public MiscAPI misc = null; public ObjAPI object = null; public PlayerAPI player = null; public PluginAPI plugin = null; public QuestAPI quest = null; public TaskAPI task = null; public UpdateAPI update = null; public ValueAPI value = null; public WarpAPI warp = null; public ZoneAPI zone = null; // Deity ClassPath List public final ArrayList<String> DEITYLIST = new ArrayList<String>(); // Did dependencies load correctly? final boolean okayToLoad = true; @Override public void onEnable() { // Define the instance instance = new InstanceAPI(this); INSTANCE = instance.getInstance(); // Initialize API initializeAPI(); // Initialize Configuration config.initializeConfig(); loadDependencies(); loadExpansions(); if(okayToLoad) { loadDeities(); // Data loading DFlatFile.load(); DScheduler.startThreads(); loadListeners(); loadCommands(); loadTasks(); // checkUpdate(); misc.getLog().setFilter(new DisconnectReasonFilter()); misc.info("Enabled!"); } else { misc.severe("Demigods cannot enable correctly because at least one required dependency was not found."); getPluginLoader().disablePlugin(getServer().getPluginManager().getPlugin("Demigods")); } } @Override public void onDisable() { if(okayToLoad) { // Disable Plugin HandlerList.unregisterAll(this); DScheduler.stopThreads(); DFlatFile.save(); misc.info("Disabled!"); } } /* * loadTestCode() : Loads the code upon plugin enable. */ @SuppressWarnings("unused") private void loadTestCode() { // Don't remove the header and footer of the test code. misc.info("====== Begin Test Code ============================="); // K, thanks misc.info("====== End Test Code ==============================="); } /* * initializeAPI() : Creates a new instance of each API, for easy access. */ private void initializeAPI() { ability = new AbilityAPI(); admin = new AdminAPI(); battle = new BattleAPI(); block = new BlockAPI(); character = new CharAPI(); config = new ConfigAPI(); data = new DataAPI(); deity = new DeityAPI(); inventory = new InvAPI(); item = new ItemAPI(); metrics = new MetricsAPI(); misc = new MiscAPI(); object = new ObjAPI(); player = new PlayerAPI(); plugin = new PluginAPI(); task = new TaskAPI(); quest = new QuestAPI(); update = new UpdateAPI(); value = new ValueAPI(); warp = new WarpAPI(); zone = new ZoneAPI(); } /* * loadListeners() : Loads all plugin listeners. */ private void loadListeners() { /* Debug Listener */ getServer().getPluginManager().registerEvents(new DDebugListener(), this); /* Ability Listener */ getServer().getPluginManager().registerEvents(new DAbilityListener(), this); /* General Player Listener */ getServer().getPluginManager().registerEvents(new DPlayerListener(), this); /* General Entity Listener */ getServer().getPluginManager().registerEvents(new DEntityListener(), this); /* Command Listener */ getServer().getPluginManager().registerEvents(new DCommandListener(), this); /* Chunk Listener */ getServer().getPluginManager().registerEvents(new DChunkListener(), this); /* Chat Listener */ getServer().getPluginManager().registerEvents(new DChatListener(), this); /* Altar Listener */ getServer().getPluginManager().registerEvents(new DAltarListener(), this); /* Shrine Listener */ getServer().getPluginManager().registerEvents(new DShrineListener(), this); /* Character Listener */ getServer().getPluginManager().registerEvents(new DCharacterListener(), this); /* Block Listener */ getServer().getPluginManager().registerEvents(new DBlockListener(), this); /* Event Creator */ getServer().getPluginManager().registerEvents(new DMetricsEventCreator(), this); } /* * loadCommands() : Loads all plugin commands and sets their executors. */ private void loadCommands() { // Define Main CommandExecutor DCommandHandler ce = new DCommandHandler(); // Define General Commands getCommand("dg").setExecutor(ce); getCommand("check").setExecutor(ce); getCommand("owner").setExecutor(ce); getCommand("removechar").setExecutor(ce); getCommand("test1").setExecutor(ce); getCommand("viewmaps").setExecutor(ce); getCommand("viewblocks").setExecutor(ce); getCommand("viewtasks").setExecutor(ce); } /* * loadDeities() : Loads the deities. */ @SuppressWarnings("unchecked") public void loadDeities() { misc.info("Loading deities..."); // Find all deities CodeSource demigodsSrc = Demigods.class.getProtectionDomain().getCodeSource(); if(demigodsSrc != null) { try { URL demigodsJar = demigodsSrc.getLocation(); ZipInputStream demigodsZip = new ZipInputStream(demigodsJar.openStream()); ZipEntry demigodsFile; // Define variables long startTimer = System.currentTimeMillis(); while((demigodsFile = demigodsZip.getNextEntry()) != null) { if(demigodsFile.getName().contains("$")) continue; String deityName = demigodsFile.getName().replace("/", ".").replace(".class", "").replaceAll("\\d*$", ""); if(deityName.contains("_deity")) { DEITYLIST.add(deityName); } } for(String deityPath : DEITYLIST) { ClassLoader loader = deity.getClassLoader(deityPath); // Load everything else for the Deity (Listener, etc.) String message = (String) deity.invokeDeityMethod(deityPath, loader, "loadDeity"); String name = (String) deity.invokeDeityMethod(deityPath, loader, "getName"); String alliance = (String) deity.invokeDeityMethod(deityPath, loader, "getAlliance"); ChatColor color = (ChatColor) deity.invokeDeityMethod(deityPath, loader, "getColor"); ArrayList<String> commands = (ArrayList<String>) deity.invokeDeityMethod(deityPath, loader, "getCommands"); ArrayList<Material> claimItems = (ArrayList<Material>) deity.invokeDeityMethod(deityPath, loader, "getClaimItems"); // Add to HashMap data.savePluginData("temp_deity_classes", name, deityPath); data.savePluginData("temp_deity_alliances", name, alliance); data.savePluginData("temp_deity_colors", name, color); data.savePluginData("temp_deity_commands", name, commands); data.savePluginData("temp_deity_claim_items", name, claimItems); // Display the success message misc.info(message); } // Stop the timer long stopTimer = System.currentTimeMillis(); double totalTime = (double) (stopTimer - startTimer); misc.info("All deities loaded in " + totalTime / 1000 + " seconds."); } catch(Exception e) { misc.severe("There was a problem while loading deities!"); e.printStackTrace(); } } } /* * loadDependencies() : Loads all dependencies. */ public void loadDependencies() { // Check for the WorldGuard plugin (optional) Plugin pg = getServer().getPluginManager().getPlugin("WorldGuard"); if((pg != null) && (pg instanceof WorldGuardPlugin)) { WORLDGUARD = (WorldGuardPlugin) pg; if(config.getSettingBoolean("use_dynamic_pvp_zones") && !config.getSettingBoolean("allow_skills_everywhere")) { misc.warning("WorldGuard no-PVP Flags are not compatible with dynamic pvp zones."); misc.warning("Instead of using flags, please name all no-PVP zones 'REGION_nopvp'."); misc.warning("Players will be invincible in no-PVP zones."); } if(!config.getSettingBoolean("allow_skills_everywhere")) misc.info("WorldGuard detected. Certain skills are disabled in no-PvP zones."); } // Check for the Factions plugin (optional) pg = getServer().getPluginManager().getPlugin("Factions"); if((pg != null) && (pg instanceof P)) { FACTIONS = (P) pg; if(config.getSettingBoolean("use_dynamic_pvp_zones") && !config.getSettingBoolean("allow_skills_everywhere")) { misc.warning("Factions is not compatible with dynamic pvp zones!"); misc.warning("Please either change the settings of Demigods, or remove Factions!"); } else if(!config.getSettingBoolean("allow_skills_everywhere")) misc.info("Factions detected. Certain skills are disabled in safe zones zones."); } // Check for the Residence plugin (optional) pg = getServer().getPluginManager().getPlugin("Residence"); if((pg != null) && (pg instanceof Residence)) RESIDENCE = (Residence) pg; } /* * loadExpansions() : Loads all expansions. */ public void loadExpansions() { // Check for expansions for(Plugin expansion : getServer().getPluginManager().getPlugins()) { if(expansion instanceof DemigodsPlugin) { DemigodsPlugin EXPANSION = (DemigodsPlugin) expansion; EXPANSION.loadAPI(); for(String deityPath : EXPANSION.getDeityPaths()) { if(!DEITYLIST.contains(deityPath)) { DEITYLIST.add(deityPath); data.savePluginData("temp_deity_classloader", deityPath, EXPANSION.getClass().getClassLoader()); // TODO OLD (Convert Deities First) } } } } } public void loadTasks() { Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(INSTANCE, new Runnable() { @Override public void run() { try { task.invokeAllTasks(); misc.info("Tasks have finished loading!"); } catch(Exception e) { misc.severe("There was an error while loading tasks."); e.printStackTrace(); } } }, 30); } @SuppressWarnings("unused") private void checkUpdate() { // Check for updates, and then update if need be if(update.shouldUpdate() && config.getSettingBoolean("auto_update")) update.demigodsUpdate(); } }
package org.ihtsdo.buildcloud.service.inputfile.prepare; import static org.ihtsdo.buildcloud.service.inputfile.prepare.ReportType.ERROR; import static org.ihtsdo.buildcloud.service.inputfile.prepare.ReportType.INFO; import static org.ihtsdo.buildcloud.service.inputfile.prepare.ReportType.WARNING; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.security.NoSuchAlgorithmException; import java.text.Normalizer; import java.text.Normalizer.Form; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.JAXBException; import org.apache.commons.codec.DecoderException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.CharEncoding; import org.ihtsdo.buildcloud.dao.helper.BuildS3PathHelper; import org.ihtsdo.buildcloud.entity.Product; import org.ihtsdo.buildcloud.manifest.FieldType; import org.ihtsdo.buildcloud.manifest.FileType; import org.ihtsdo.buildcloud.manifest.FolderType; import org.ihtsdo.buildcloud.manifest.ListingType; import org.ihtsdo.buildcloud.manifest.RefsetType; import org.ihtsdo.buildcloud.service.build.RF2Constants; import org.ihtsdo.buildcloud.service.file.ManifestXmlFileParser; import org.ihtsdo.otf.dao.s3.helper.FileHelper; import org.ihtsdo.otf.rest.exception.BusinessServiceException; import org.ihtsdo.otf.rest.exception.ResourceNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import com.google.common.io.Files; public class InputSourceFileProcessor { private static final String TAB = "\t"; private static final String NO_LANGUAGE_CODE_IS_CONFIGURED_MSG = "No language code is configured in the manifest.xml."; private static final String NO_DATA_FOUND = "No data found apart from header line."; private static final String README_HEADER_FILE_NAME = "readme-header.txt"; private static final String UNPROCESSABLE_MSG = "Can't be processed as the %s appears in multiple sources and no source is configured in the manifest.xml."; private final Logger logger = LoggerFactory.getLogger(InputSourceFileProcessor.class); private static final String HEADER_REFSETS = "id\teffectiveTime\tactive\tmoduleId\trefsetId\treferencedComponentId"; private static final String HEADER_TERM_DESCRIPTION = "id\teffectiveTime\tactive\tmoduleId\tconceptId\tlanguageCode\ttypeId\tterm\tcaseSignificanceId"; private static final int REFSETID_COL = 4; private static final int DESCRIPTION_LANGUAGE_CODE_COL = 5; private static final String INPUT_FILE_TYPE_REFSET = "Refset"; private static final String INPUT_FILE_TYPE_DESCRIPTION = "Description_"; private static final String INPUT_FILE_TYPE_TEXT_DEFINITON = "TextDefinition"; private static final String OUT_DIR = "out"; private static final int DESCRIPTION_TYPE_COL = 6; private static final String TEXT_DEFINITION_TYPE_ID = "900000000000550004"; private InputStream manifestStream; private FileHelper fileHelper; private BuildS3PathHelper buildS3PathHelper; private Product product; private File localDir; private File outDir; private boolean foundTextDefinitionFile = false; private boolean copyFilesDefinedInManifest = false; private Set<String> availableSources; private Map<String, List<String>> sourceFilesMap; private SourceFileProcessingReport fileProcessingReport; private Map<String,List<String>> skippedSourceFiles; private MultiValueMap<String, String> fileOrKeyWithMultipleSources; //processing instructions from the manifest.xml private Map<String, FileProcessingConfig> refsetFileProcessingConfigs; private Map<String, FileProcessingConfig> descriptionFileProcessingConfigs; private Map<String, FileProcessingConfig> textDefinitionFileProcessingConfigs; private MultiValueMap<String, String> filesToCopyFromSource; private MultiValueMap<String, String> refsetWithAdditionalFields; public InputSourceFileProcessor(InputStream manifestStream, FileHelper fileHelper, BuildS3PathHelper buildS3PathHelper, Product product, boolean copyFilesDefinedInManifest) { this.manifestStream = manifestStream; this.fileHelper = fileHelper; this.buildS3PathHelper = buildS3PathHelper; this.product = product; this.sourceFilesMap = new HashMap<>(); this.refsetFileProcessingConfigs = new HashMap<>(); this.descriptionFileProcessingConfigs = new HashMap<>(); this.textDefinitionFileProcessingConfigs = new HashMap<>(); this.availableSources = new HashSet<>(); this.copyFilesDefinedInManifest = copyFilesDefinedInManifest; this.skippedSourceFiles = new HashMap<>(); this.filesToCopyFromSource = new LinkedMultiValueMap<>(); this.refsetWithAdditionalFields = new LinkedMultiValueMap<>(); this.fileProcessingReport = new SourceFileProcessingReport(); this.fileOrKeyWithMultipleSources = new LinkedMultiValueMap<>(); } public SourceFileProcessingReport processFiles(List<String> sourceFileLists) throws BusinessServiceException { try { initLocalDirs(); copySourceFilesToLocal(sourceFileLists); loadFileProcessConfigsFromManifest(); prepareSourceFiles(); if (this.copyFilesDefinedInManifest) { fileProcessingReport.addReportDetails(copyFilesToOutputDir()); } verifyRefsetFiles(); uploadOutFilesToProductInputFiles(); } catch (Exception e) { StringBuilder msgBuilder = new StringBuilder(); msgBuilder.append("Error encountered when preparing input files."); if (e.getCause() != null) { msgBuilder.append("Cause:" + e.getCause().getMessage()); } else { msgBuilder.append("Failure message:" + e.getMessage()); } logger.error(msgBuilder.toString(), e); fileProcessingReport.add(ReportType.ERROR, msgBuilder.toString() ); throw new BusinessServiceException(msgBuilder.toString(), e); } finally { if (!FileUtils.deleteQuietly(localDir)) { logger.warn("Failed to delete local directory {}", localDir.getAbsolutePath()); } } return fileProcessingReport; } private void verifyRefsetFiles() throws IOException { File[] filesPrepared = outDir.listFiles(); Collection<FileProcessingConfig> configs = refsetFileProcessingConfigs.values(); Set<String> refSetFilesToCreate = new HashSet<>(); for (FileProcessingConfig config : configs) { refSetFilesToCreate.add(config.getTargetFileName()); } for (String refsetFileName : refSetFilesToCreate) { refsetFileName = refsetFileName.startsWith(RF2Constants.BETA_RELEASE_PREFIX) ? refsetFileName.substring(1) : refsetFileName; boolean isRefsetFilePrepared = false; StringBuilder headerLine = new StringBuilder(); headerLine.append(HEADER_REFSETS); boolean checkAdditionalFields = false; if (refsetWithAdditionalFields.get(refsetFileName) != null && !refsetWithAdditionalFields.get(refsetFileName).isEmpty()) { checkAdditionalFields = true; for (String fieldName : refsetWithAdditionalFields.get(refsetFileName)) { headerLine.append(TAB); headerLine.append(fieldName); } } for (File file : filesPrepared) { String fileName = file.getName(); fileName = fileName.startsWith(RF2Constants.BETA_RELEASE_PREFIX) ? fileName.substring(1) : fileName; if (fileName.equals(refsetFileName)) { isRefsetFilePrepared = true; //check refset contains additional fields if (checkAdditionalFields) { String header = getHeaderLine(file); if (header == null || !header.equals(headerLine.toString())) { fileProcessingReport.add(ReportType.ERROR, refsetFileName, null, null, "Refset file does not contain a valid header according to the manifest. Actual:" + header + " while expecting:" + headerLine.toString()); } } break; } } if (!isRefsetFilePrepared) { //create empty delta and add warning message File refsetDeltFile = new File(outDir,refsetFileName); if (!refsetDeltFile .exists()) { refsetDeltFile.createNewFile(); FileUtils.writeLines(refsetDeltFile, CharEncoding.UTF_8, Arrays.asList(headerLine.toString()), RF2Constants.LINE_ENDING); fileProcessingReport.add(ReportType.WARNING, refsetFileName, null, null, "No refset data found in any source therefore an empty delta file with header line only is created instead."); } } } } private String getHeaderLine(File preparedFile) throws IOException { try ( BufferedReader reader = new BufferedReader(new FileReader(preparedFile))) { return reader.readLine(); } } private void initLocalDirs() { localDir = Files.createTempDir(); outDir = new File(localDir, OUT_DIR); outDir.mkdir(); } private File copySourceFilesToLocal(List<String> sourceFileLists) throws BusinessServiceException { for (String sourceFilePath : sourceFileLists) { //Copy files from S3 to local for processing InputStream sourceFileStream = fileHelper.getFileStream(buildS3PathHelper.getProductSourcesPath(product).append(sourceFilePath).toString()); if (sourceFileStream == null) { throw new BusinessServiceException("Source file not found:" + sourceFilePath); } String sourceName = sourceFilePath.substring(0, sourceFilePath.indexOf("/")); //Keep track of the sources directories that are used availableSources.add(sourceName); File sourceDir = new File(localDir, sourceName); if (!sourceDir.exists()) { sourceDir.mkdir(); } String fileName = FilenameUtils.getName(sourceFilePath); fileName = fileName.startsWith(RF2Constants.BETA_RELEASE_PREFIX) ? fileName.substring(1) : fileName; File outFile = new File(localDir + "/" + sourceName, fileName); try { FileUtils.copyInputStreamToFile(sourceFileStream, outFile); } catch (IOException e) { String errorMsg = String.format("Failed to copy source file {} to local disk {}", sourceFilePath, outFile); throw new BusinessServiceException(errorMsg, e); } logger.info("Successfully created temp source file {}", outFile.getAbsolutePath()); if (!sourceFilesMap.containsKey(sourceName)) { sourceFilesMap.put(sourceName, new ArrayList<String>()); } sourceFilesMap.get(sourceName).add(outFile.getAbsolutePath()); fileOrKeyWithMultipleSources.add(fileName, sourceName); } for (String sourceName : sourceFilesMap.keySet()) { fileProcessingReport.addSoureFiles(sourceName, sourceFilesMap.get(sourceName)); } return localDir; } void loadFileProcessConfigsFromManifest() throws JAXBException, ResourceNotFoundException, IOException { if (manifestStream == null) { fileProcessingReport.add(ReportType.ERROR, "Failed to load manifest"); throw new ResourceNotFoundException("Failed to load manifest"); } ManifestXmlFileParser manifestXmlFileParser = new ManifestXmlFileParser(); ListingType listingType = manifestXmlFileParser.parse(manifestStream); loadProcessConfig(listingType); } private void loadProcessConfig(ListingType listingType) { FolderType rootFolder = listingType.getFolder(); getDeltaFilesFromFolder(rootFolder); } private void getDeltaFilesFromFolder(FolderType folder) { if (folder != null) { if (folder.getFile() != null ) { for (FileType fileType : folder.getFile()) { if (fileType.getName().contains(RF2Constants.SNAPSHOT) || fileType.getName().contains(RF2Constants.FULL)) { continue; } if (fileType.getName().contains(INPUT_FILE_TYPE_TEXT_DEFINITON)) { initTextDefinitionProcessingConfig(fileType); } else if (fileType.getContainsReferenceSets() != null && fileType.getContainsReferenceSets().getRefset() != null) { initRefsetProcessingConfig(fileType); } else if (fileType.getName().contains(INPUT_FILE_TYPE_DESCRIPTION)) { initDescripionProcessingConfig(fileType); } else { if(this.copyFilesDefinedInManifest) { String deltaFileName = fileType.getName(); logger.debug("Add file to copy:" + deltaFileName); deltaFileName = (deltaFileName.startsWith(RF2Constants.BETA_RELEASE_PREFIX)) ? deltaFileName.replaceFirst(RF2Constants.BETA_RELEASE_PREFIX, "") : deltaFileName; if (fileType.getSources() != null) { this.filesToCopyFromSource.put(deltaFileName, fileType.getSources().getSource()); } else { this.filesToCopyFromSource.put(deltaFileName, Collections.emptyList()); } } } } } if (folder.getFolder() != null) { for (FolderType subFolder : folder.getFolder()) { getDeltaFilesFromFolder(subFolder); } } } } void initDescripionProcessingConfig(FileType fileType) { if (fileType.getContainsLanguageCodes() != null && fileType.getContainsLanguageCodes().getCode() != null) { for (String languageCode : fileType.getContainsLanguageCodes().getCode()) { FileProcessingConfig config = new FileProcessingConfig(INPUT_FILE_TYPE_DESCRIPTION, languageCode, fileType.getName()); if (!descriptionFileProcessingConfigs.containsKey(languageCode)) { descriptionFileProcessingConfigs.put(config.getKey(), config); } if (fileType.getSources() != null && !fileType.getSources().getSource().isEmpty()) { config.setSpecificSources(new HashSet<String>(fileType.getSources().getSource())); } } } else { //add error reporting manifest.xml is not configured properly fileProcessingReport.add(ReportType.ERROR, fileType.getName(), null, null, NO_LANGUAGE_CODE_IS_CONFIGURED_MSG); } } void initRefsetProcessingConfig(FileType fileType) { if (fileType.getContainsAdditionalFields() != null && fileType.getContainsAdditionalFields().getField() != null ) { for (FieldType field : fileType.getContainsAdditionalFields().getField()) { String refsetFileName = fileType.getName(); refsetFileName = (refsetFileName.startsWith(RF2Constants.BETA_RELEASE_PREFIX)) ? refsetFileName.replaceFirst(RF2Constants.BETA_RELEASE_PREFIX, "") : refsetFileName; refsetWithAdditionalFields.add(refsetFileName, field.getName()); } } for (RefsetType refsetType : fileType.getContainsReferenceSets().getRefset()) { String refsetId = refsetType.getId().toString(); FileProcessingConfig fileProcessingConfig = new FileProcessingConfig(INPUT_FILE_TYPE_REFSET, refsetType.getId().toString(), fileType.getName()); if (!refsetFileProcessingConfigs.containsKey(refsetId)) { refsetFileProcessingConfigs.put(fileProcessingConfig.getKey(), fileProcessingConfig); } if (refsetType.getSources() != null && refsetType.getSources().getSource() != null && !refsetType.getSources().getSource().isEmpty()) { fileProcessingConfig.setSpecificSources(new HashSet<String>(refsetType.getSources().getSource())); } else { if (fileType.getSources() != null && !fileType.getSources().getSource().isEmpty()) { fileProcessingConfig.setSpecificSources(new HashSet<String>(fileType.getSources().getSource())); } } } } void initTextDefinitionProcessingConfig(FileType fileType) { foundTextDefinitionFile = true; if (fileType.getContainsLanguageCodes() != null && fileType.getContainsLanguageCodes().getCode() != null) { for (String languageCode : fileType.getContainsLanguageCodes().getCode()) { FileProcessingConfig config = new FileProcessingConfig(INPUT_FILE_TYPE_TEXT_DEFINITON, languageCode, fileType.getName()); if (fileType.getSources() != null && !fileType.getSources().getSource().isEmpty()) { config.setSpecificSources(new HashSet<String>(fileType.getSources().getSource())); } if (!textDefinitionFileProcessingConfigs.containsKey(languageCode)) { textDefinitionFileProcessingConfigs.put(config.getKey(), config); } } } else { //add error reporting manifest.xml is not configured properly fileProcessingReport.add(ReportType.ERROR, fileType.getName(), null, null, NO_LANGUAGE_CODE_IS_CONFIGURED_MSG); } } private void prepareSourceFiles() throws IOException { List<FileProcessingReportDetail> fileProcessingReportDetails = new ArrayList<>(); for (String source : sourceFilesMap.keySet()) { List<String> fileList = sourceFilesMap.get(source); for (String fileName : fileList) { logger.info("Start processing file {}", fileName); File sourceFile = new File(fileName); List<String> lines = FileUtils.readLines(sourceFile, CharEncoding.UTF_8); if (lines != null && !lines.isEmpty()) { String header = lines.get(0); //remove header before processing lines.remove(0); if (header.startsWith(HEADER_REFSETS)) { processRefsetFiles(fileProcessingReportDetails,lines, source, fileName, outDir, header); } else if (header.startsWith(HEADER_TERM_DESCRIPTION)) { //create delta file with header writeHeaderToFile(outDir,header, descriptionFileProcessingConfigs.values()); if (foundTextDefinitionFile) { writeHeaderToFile(outDir,header, textDefinitionFileProcessingConfigs.values()); } processDescriptionsAndTextDefinitions(lines, source, fileName, outDir, header); } else { addFileToSkippedList(source, fileName); } } logger.info("Finish processing file {}", fileName); } } fileProcessingReport.addReportDetails(fileProcessingReportDetails); } private void processRefsetFiles(List<FileProcessingReportDetail> fileProcessingReportDetails, List<String> lines, String sourceName, String inFileName, File outDir, String header) throws IOException { String inputFilename = FilenameUtils.getName(inFileName); if (lines == null || lines.isEmpty()) { fileProcessingReport.add(INFO, inputFilename, null, sourceName, NO_DATA_FOUND); } if (filesToCopyFromSource.containsKey(inputFilename) && (filesToCopyFromSource.get(inputFilename).isEmpty() || filesToCopyFromSource.get(inputFilename).contains(sourceName))) { writeToFile(outDir, header, lines, inputFilename); } else { //map lines by refset id MultiValueMap<String, String> linesByRefsetId = new LinkedMultiValueMap<>(); for (String line : lines) { String[] splits = line.split(TAB); String refsetId = splits[REFSETID_COL]; linesByRefsetId.add(refsetId, line); } for (String refsetId : linesByRefsetId.keySet()) { fileOrKeyWithMultipleSources.add(refsetId, sourceName); FileProcessingConfig fileProcessingConfig = refsetFileProcessingConfigs.get(refsetId); if (fileProcessingConfig == null) { if (!filesToCopyFromSource.containsKey(inputFilename)) { String warningMsg = String.format("Found lines %d with refset id %s in source file " + "but is not used by the manifest configuration", linesByRefsetId.get(refsetId).size(), refsetId); fileProcessingReport.add(ReportType.WARNING, inputFilename, refsetId, sourceName, warningMsg); } } else { if (fileProcessingConfig.getSpecificSources().contains(sourceName) || (fileProcessingConfig.getSpecificSources().isEmpty() && fileOrKeyWithMultipleSources.get(refsetId).size() == 1)) { writeToFile(outDir, header, linesByRefsetId.get(refsetId), fileProcessingConfig.getTargetFileName()); String infoMessage = String.format("Added source %s/%s", sourceName, FilenameUtils.getName(inFileName)); fileProcessingReportDetails.add(new FileProcessingReportDetail(INFO, fileProcessingConfig.getTargetFileName(), refsetId, sourceName, infoMessage)); } else if (fileProcessingConfig.getSpecificSources().isEmpty() && fileOrKeyWithMultipleSources.get(refsetId).size() > 1) { String errorMsg = String.format(UNPROCESSABLE_MSG, "refset id"); fileProcessingReport.add(ERROR, inputFilename, refsetId, sourceName, errorMsg); } else { String warningMessage = String.format("Source %s is not specified in the manifest.xml therefore is skipped.", sourceName); fileProcessingReport.add(WARNING, inputFilename, refsetId, sourceName, warningMessage); } } } } } private void addFileToSkippedList(String sourceName, String filename) { if (skippedSourceFiles.get(sourceName) == null) { List<String> files = new ArrayList<String>(); files.add(filename); skippedSourceFiles.put(sourceName, files ); } else { skippedSourceFiles.get(sourceName).add(filename); } } private void processDataByLanguageCode(Map<String,FileProcessingConfig> fileProcessingConfigs, String sourceName, Map<String, List<String>> rows, String inputFilename, String header, boolean isTextDefinition) throws IOException { for (String languageCode : rows.keySet()) { FileProcessingConfig fileProcessingConfig = fileProcessingConfigs.get(languageCode); if (fileProcessingConfig != null) { String key = isTextDefinition ? INPUT_FILE_TYPE_TEXT_DEFINITON + languageCode : INPUT_FILE_TYPE_DESCRIPTION + languageCode; if (fileProcessingConfig.getSpecificSources().contains(sourceName) || (fileProcessingConfig.getSpecificSources().isEmpty() && fileOrKeyWithMultipleSources.get(key).size() == 1)) { writeToFile(outDir, header, rows.get(languageCode), fileProcessingConfig.getTargetFileName()); } else if (fileProcessingConfig.getSpecificSources().isEmpty() && fileOrKeyWithMultipleSources.get(key).size() > 1) { String errorMsg = String.format(UNPROCESSABLE_MSG, "language code " + languageCode); fileProcessingReport.add(ERROR, inputFilename, null, sourceName, errorMsg); } else { String warningMsg = String.format("Source %s is not specified in the manifest.xml therefore is skipped.", sourceName); fileProcessingReport.add(WARNING, inputFilename , null, sourceName, warningMsg); } } else { String msg = String.format("Found language code: %s in source file but not specified in the manifest.xml", languageCode); fileProcessingReport.add(ERROR, inputFilename , null, sourceName, msg); } } } private void processDescriptionsAndTextDefinitions(List<String> lines, String sourceName, String inFileName, File outDir, String header) throws IOException { Map<String, List<String>> descriptionRows = new HashMap<>(); Map<String, List<String>> textDefinitionRows = new HashMap<>(); String inputFilename = FilenameUtils.getName(inFileName); if (lines == null || lines.isEmpty()) { fileProcessingReport.add(WARNING, inputFilename, null, sourceName, NO_DATA_FOUND); } else { for (String line : lines) { String[] splits = line.split(TAB); String languageCode = splits[DESCRIPTION_LANGUAGE_CODE_COL]; String descriptionTypeValue = splits[DESCRIPTION_TYPE_COL]; boolean isTextDefinition = false; if (foundTextDefinitionFile && TEXT_DEFINITION_TYPE_ID.equals(descriptionTypeValue)) { isTextDefinition = true; if (!textDefinitionRows.containsKey(languageCode)) { textDefinitionRows.put(languageCode, new ArrayList<String>()); } textDefinitionRows.get(languageCode).add(line); } else { if (!descriptionRows.containsKey(languageCode)) { descriptionRows.put(languageCode, new ArrayList<String>()); } descriptionRows.get(languageCode).add(line); } String key = isTextDefinition ? INPUT_FILE_TYPE_TEXT_DEFINITON + languageCode : INPUT_FILE_TYPE_DESCRIPTION + languageCode; if (!fileOrKeyWithMultipleSources.containsKey(key) || !fileOrKeyWithMultipleSources.get(key).contains(sourceName)) { fileOrKeyWithMultipleSources.add(key, sourceName); } } processDataByLanguageCode(descriptionFileProcessingConfigs, sourceName, descriptionRows, inputFilename, header, false); if (foundTextDefinitionFile) { processDataByLanguageCode(textDefinitionFileProcessingConfigs, sourceName, textDefinitionRows, inputFilename, header, true); } } } private void writeHeaderToFile(File outDir, String headerLine, Collection<FileProcessingConfig> configs) throws IOException { if (configs != null) { Set<String> fileNamesToCreate = new HashSet<>(); for (FileProcessingConfig config : configs) { fileNamesToCreate.add(config.getTargetFileName()); } for (String fileName : fileNamesToCreate) { File file = new File(outDir, fileName); if (!file.exists()) { file.createNewFile(); FileUtils.writeLines(file, CharEncoding.UTF_8, Arrays.asList(headerLine), RF2Constants.LINE_ENDING); } } } } private void writeToFile(File outDir, String header, List<String> lines, String targetOutputFileName) throws IOException { if (targetOutputFileName != null && header != null) { File outFile = new File(outDir, targetOutputFileName); if (!outFile.exists()) { outFile.createNewFile(); List<String> headers = new ArrayList<>(); headers.add(header); FileUtils.writeLines(outFile, CharEncoding.UTF_8, headers, RF2Constants.LINE_ENDING); } if (lines != null && !lines.isEmpty()) { FileUtils.writeLines(outFile, CharEncoding.UTF_8, lines, RF2Constants.LINE_ENDING, true); logger.debug("Copied {} lines to {}", lines.size(), outFile.getAbsolutePath()); } } } private FileProcessingReportDetail copyFilesWhenIgnoringCountryAndNamespace(String sourceFileName, String source, String sourceFilePath, Map<String,String> fileNameMapWithoutNamespace) throws IOException { // ignores country and name space token check FileProcessingReportDetail reportDetail = null; String fileNameSpecifiedByManifest = fileNameMapWithoutNamespace.get(getFileNameWithoutCountryNameSpaceToken(sourceFileName)); if (fileNameSpecifiedByManifest != null) { if (filesToCopyFromSource.containsKey(fileNameSpecifiedByManifest) && filesToCopyFromSource.get(fileNameSpecifiedByManifest).contains(source)) { File inFile = new File(sourceFilePath); File outFile = new File(outDir, fileNameSpecifiedByManifest); copyOrAppend(inFile, outFile); logger.info("Renamed {} to {}", inFile.getAbsolutePath(), outFile.getAbsolutePath()); reportDetail = new FileProcessingReportDetail(INFO, sourceFileName, source, null, "Copied to:" + fileNameSpecifiedByManifest); } else { //source file is not required by the manifest String msg = "Skipped as not required by the manifest:" + sourceFileName; logger.info(msg); reportDetail = new FileProcessingReportDetail(INFO, sourceFileName, source, null, msg); } } else { if (!sourceFileName.equals(README_HEADER_FILE_NAME)) { String msg = "Skipped as can't find any match in the manifest. " + "Please check the file name is specified in the manifest and has the same release date as the source file."; reportDetail = new FileProcessingReportDetail(ReportType.WARNING, sourceFileName, null, source, msg); } } return reportDetail; } private List<FileProcessingReportDetail> copyFilesToOutputDir() throws IOException { List<FileProcessingReportDetail> reportDetails = new ArrayList<>(); Map<String,String> fileNameMapWithoutNamespace = getFileNameMapWithoutNamespaceToken(); for (String source : skippedSourceFiles.keySet()) { for (String sourceFilePath : skippedSourceFiles.get(source)) { String sourceFileName = FilenameUtils.getName(sourceFilePath); sourceFileName = sourceFileName.startsWith(RF2Constants.BETA_RELEASE_PREFIX) ? sourceFileName.substring(1) : sourceFileName; if (!filesToCopyFromSource.containsKey(sourceFileName)) { FileProcessingReportDetail reportDetail = copyFilesWhenIgnoringCountryAndNamespace(sourceFileName, source, sourceFilePath, fileNameMapWithoutNamespace); if (reportDetail != null) { reportDetails.add(reportDetail); } } else { boolean toCopy = false; if (filesToCopyFromSource.get(sourceFileName).contains(source)) { //copy as specified by manifest reportDetails.add(new FileProcessingReportDetail(INFO, sourceFileName, null, source, "Copied as file name and source matched with the manifest exactly.")); toCopy = true; } else { if (filesToCopyFromSource.get(sourceFileName).isEmpty()) { if (fileOrKeyWithMultipleSources.containsKey(sourceFileName) && fileOrKeyWithMultipleSources.get(sourceFileName).size() > 1) { //source is not specified. To check whether the same file exists in multiple sources. String errorMsg = String.format(UNPROCESSABLE_MSG, "file name"); reportDetails.add(new FileProcessingReportDetail(ERROR, sourceFileName, null, source, errorMsg )); } else { //copy only one source toCopy = true; reportDetails.add(new FileProcessingReportDetail(INFO, sourceFileName, null, source, "Copied as the file name matched even though no source is specfied in the manifest.xml as it appears only in one source.")); } } else { // skip it as is not from the given source specified by the manifest reportDetails.add(new FileProcessingReportDetail(INFO, sourceFileName, null, source , "Skipped as only the file name matched with the manifest but not the source.")); } } if (toCopy) { File inFile = new File(sourceFilePath); File outFile = new File(outDir, sourceFileName); copyOrAppend(inFile, outFile); logger.info("Copied {} to {}", inFile.getAbsolutePath(), outFile.getAbsolutePath()); } } } skippedSourceFiles.get(source).clear(); } return reportDetails; } private void copyOrAppend(File sourceFile, File destinationFile) throws IOException { if (destinationFile.exists()) { //remove header line and append List<String> lines = FileUtils.readLines(sourceFile, CharEncoding.UTF_8); if (!lines.isEmpty() && lines.size() > 0) { lines.remove(0); FileUtils.writeLines(destinationFile, CharEncoding.UTF_8, lines, RF2Constants.LINE_ENDING, true); logger.debug("Appending " + sourceFile.getName() + " to " + destinationFile.getAbsolutePath()); } } else { destinationFile.createNewFile(); FileUtils.copyFile(sourceFile, destinationFile); logger.debug("Copying " + sourceFile.getName() + " to " + destinationFile.getAbsolutePath()); } } private String getFileNameWithoutCountryNameSpaceToken(String rf2FileName) { rf2FileName = rf2FileName.startsWith(RF2Constants.BETA_RELEASE_PREFIX) ? rf2FileName.replaceFirst(RF2Constants.BETA_RELEASE_PREFIX, "") : rf2FileName; String[] splits = rf2FileName.split(RF2Constants.FILE_NAME_SEPARATOR); StringBuilder key = new StringBuilder(); for (int i=0; i < splits.length ;i++) { if (i == 3) { continue; } if ( i > 0) { key.append(RF2Constants.FILE_NAME_SEPARATOR); } key.append(splits[i]); } return key.toString(); } private Map<String, String> getFileNameMapWithoutNamespaceToken() { Map<String, String> result = new HashMap<>(); for (String fileName : filesToCopyFromSource.keySet()) { result.put(getFileNameWithoutCountryNameSpaceToken(fileName), fileName); } return result; } private void uploadOutFilesToProductInputFiles() throws NoSuchAlgorithmException, IOException, DecoderException { File[] files = outDir.listFiles(); List<String> filesPrepared = new ArrayList<>(); logger.debug("Found {} prepared files in directory {} to upload to the input-files folder in S3", files.length, outDir.getAbsolutePath()); for (File file : files) { String inputFileName = file.getName(); filesPrepared.add(inputFileName); if (file.getName().startsWith(RF2Constants.BETA_RELEASE_PREFIX)) { inputFileName = file.getName().replaceFirst(RF2Constants.BETA_RELEASE_PREFIX, ""); } inputFileName = inputFileName.replace("der2", "rel2").replace("sct2", "rel2"); if (!Normalizer.isNormalized(inputFileName, Form.NFC)) { inputFileName = Normalizer.normalize(inputFileName, Form.NFC); } String filePath = buildS3PathHelper.getProductInputFilesPath(product) + inputFileName; fileProcessingReport.add(ReportType.INFO,inputFileName, null, null, "Uploaded to product input files directory"); fileHelper.putFile(file,filePath); logger.info("Uploaded {} to product input files directory with name {}", file.getName(), inputFileName); } for (String filename : filesToCopyFromSource.keySet()) { if (!filesPrepared.contains(filename) && !filename.startsWith("Readme") && !filename.startsWith("release")) { String message = null; if (filesToCopyFromSource.get(filename).isEmpty()) { message = String.format("Required by manifest but not found in any source."); } else { message = String.format("Required by manifest but not found in source %s", filesToCopyFromSource.get(filename)); } fileProcessingReport.add(ERROR, filename, null, null, message); } } } public Map<String, List<String>> getSkippedSourceFiles() { return skippedSourceFiles; } public Set<String> getAvailableSources() { return availableSources; } public Map<String, FileProcessingConfig> getRefsetFileProcessingConfigs() { return refsetFileProcessingConfigs; } public Map<String, FileProcessingConfig> getDescriptionFileProcessingConfigs() { return descriptionFileProcessingConfigs; } public Map<String, FileProcessingConfig> getTextDefinitionFileProcessingConfigs() { return textDefinitionFileProcessingConfigs; } public MultiValueMap<String, String> getFilesToCopyFromSource() { return filesToCopyFromSource; } public Map<String, List<String>> getSourceFilesMap() { return sourceFilesMap; } public MultiValueMap<String, String> getRefsetWithAdditionalFields() { return refsetWithAdditionalFields; } }
package edu.berkeley.cs160.DeansOfDesign.cookease; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.telephony.SmsManager; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckedTextView; import android.widget.ListView; import android.widget.TextView; import edu.berkeley.cs160.DeansOfDesign.cookease.BoilingWaterDetector.OnBoilingEventListener; public class MainActivity extends Fragment implements OnBoilingEventListener { public final static String EXTRA_MESSAGE = "edu.berkeley.cs160.DeansOfDesign.MESSAGE"; private static TextView analyticsText = null; private static TextView settingsText = null; private static TextView instructionText = null; public String alert_message = "Your water is boiling!\nYour microwave is done!"; public String alert_title = "CookEase Alert"; public String water = "Water boiling"; public String microDone = "Microwave Done"; public String microExplo = "Microwave Explosion"; public String other = "Other Kitchen Tasks"; String greyBg = "#84a689"; String purpleBg = "#a684a1"; String white = "#ffffff"; private Mail sendMail; String sendOkay = ""; public String friends_title = "Who do you want to alert?"; public HashMap<String, Boolean> tasksToSelected = new HashMap<String, Boolean>(); public ListView taskList; StableArrayAdapter adapter = null; Activity act; // For audio processing private BoilingWaterDetector boilingWaterDetector; private boolean alerted = false; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); act = this.getActivity(); act.setContentView(R.layout.activity_main); // Make a mail object to send email with //make a Mail object to email with sendMail = new Mail("[email protected]", "deansofdesign"); // Restore preferences SharedPreferences settings = act.getSharedPreferences("settings", 0); tasksToSelected.put(water, settings.getBoolean(water, false)); tasksToSelected.put(microDone, settings.getBoolean(microDone, false)); tasksToSelected.put(microExplo,settings.getBoolean(microExplo, false)); tasksToSelected.put(other,settings.getBoolean(other, false)); // Demo, click the instructions for alert! instructionText = (TextView) act.findViewById(R.id.textView6); instructionText.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { alert(microDone); //hardcoded microDone for testing } } ); // Setup audio processing boilingWaterDetector = new BoilingWaterDetector(act, 0.1); boilingWaterDetector.setOnBoilingEventListener(this); if (tasksToSelected.get(water)) { boilingWaterDetector.startDetection(); } taskList = (ListView) act.findViewById(R.id.listView1); String tasks[] ={water, microDone, microExplo, other}; final ArrayList<String> list = new ArrayList<String>(); for (int i = 0; i < tasks.length; ++i) { list.add(tasks[i]); } adapter = new StableArrayAdapter(act, android.R.layout.simple_list_item_multiple_choice, list); taskList.setAdapter(adapter); taskList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @SuppressLint("NewApi") @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { CheckedTextView item = (CheckedTextView) view; String itemText = (String) parent.getItemAtPosition(position); if (tasksToSelected.get(itemText)) { //selected already //item.setBackgroundColor(Color.parseColor(greyBg)); //item.setTextColor(Color.parseColor(white)); item.setChecked(false); tasksToSelected.put(itemText, false); if (itemText == water) { boilingWaterDetector.stopDetection(); } } else { //not selected yet //item.setBackgroundColor(Color.parseColor(purpleBg)); //item.setTextColor(Color.parseColor(white)); item.setChecked(true); tasksToSelected.put(itemText, true); if (itemText == water) { alerted = false; boilingWaterDetector.startDetection(); } } } }); taskList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); taskList.setItemChecked(0, tasksToSelected.get(water)); taskList.setItemChecked(1, tasksToSelected.get(microDone)); taskList.setItemChecked(2, tasksToSelected.get(microExplo)); taskList.setItemChecked(3, tasksToSelected.get(other)); /* int wantedPosition = 10; // Whatever position you're looking for int wantedChild = wantedPosition - firstPosition; // Say, first visible position is 8, you want position 10, wantedChild will now be 2 // So that means your view is child #2 in the ViewGroup: if (wantedChild < 0 || wantedChild >= listView.getChildCount()) { Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen."); return; } // Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead. View wantedView = listView.getChildAt(wantedChild);*/ return inflater.inflate(R.layout.activity_main, container, false); } private class StableArrayAdapter extends ArrayAdapter<String> { HashMap<String, Integer> mIdMap = new HashMap<String, Integer>(); Context c; public StableArrayAdapter(Context context, int textViewResourceId, List<String> objects) { super(context, textViewResourceId, objects); this.c = context; for (int i = 0; i < objects.size(); ++i) { mIdMap.put(objects.get(i), i); } } @Override public long getItemId(int position) { String item = getItem(position); return mIdMap.get(item); } @Override public boolean hasStableIds() { return true; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if( view == null ){ //We must create a View: LayoutInflater inflater=act.getLayoutInflater(); view = inflater.inflate(R.layout.custom_row, parent, false); } CheckedTextView temp = (CheckedTextView) view.findViewById(R.id.text1); if (position == 0) { temp.setText(water); } else if (position == 1) { temp.setText(microDone); } else if (position == 2) { temp.setText(microExplo); } else if (position == 3) { temp.setText(other); } /*if ((position == 0 && tasksToSelected.get(water)) || (position == 1 && tasksToSelected.get(microDone)) || (position == 2 && tasksToSelected.get(microExplo)) || (position == 3 && tasksToSelected.get(other))) { view.setBackgroundColor(Color.parseColor(purpleBg)); } else { view.setBackgroundColor(Color.parseColor(greyBg)); }*/ adapter.notifyDataSetChanged(); return view; } } // This now pops up the alerts toast in addition to sending an email/text (we can use this to test messaging capabilities for now) public void alert(String task) { new AlertDialog.Builder(act) .setTitle(alert_title) .setMessage(alert_message) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // continue } }) .show(); // sends a test email to the currently selected email address sendMessage(1); // sends a test text to the currently selected phone number sendMessage(2); if (task == water) { tasksToSelected.put(water, false); taskList.setItemChecked(0, tasksToSelected.get(water)); } else if (task == microDone) { tasksToSelected.put(microDone, false); taskList.setItemChecked(1, tasksToSelected.get(microDone)); } else if (task == microExplo) { tasksToSelected.put(microExplo, false); taskList.setItemChecked(2, tasksToSelected.get(microExplo)); } else if (task == other) { tasksToSelected.put(other, false); taskList.setItemChecked(3, tasksToSelected.get(other)); } } // Send email or text message, depending on which argument you pass in - 1 is email, 2 is text (phone number) public void sendMessage(int mtype) { SharedPreferences texts = act.getSharedPreferences("texts", 0); if (mtype == 1) { String email = texts.getString(NotificationsActivity.email, NotificationsActivity.selectedEmail); Log.d("EMAIL SENT TO:", email); String[] toArr = {email}; // You can add more emails here if necessary Log.d("EMAIL IS NOW:", toArr[0]); sendMail.setTo(toArr); // load array to setTo function sendMail.setFrom("[email protected]"); // who is sending the email sendMail.setSubject("Your water is boiling!"); sendMail.setBody("Your water is boiling."); Runnable r = new Runnable() { @Override public void run() { try { sendMail.send(); } catch(Exception e) { // Can't figure out how to alter things while in this thread - every time I try to do something it crashes // Eventually handling this exception would be nice } } }; Thread t = new Thread(r); t.start(); } else { final String textnum = texts.getString(NotificationsActivity.text, NotificationsActivity.selectedText); //Text message send function. The phone number is stored in textnum variable. Runnable r = new Runnable() { @Override public void run() { try { sendSMS(textnum, "Your water is boiling!"); //sendSMS("5554", "Your water is boiling!"); //for emulator testing } catch(Exception e) { // Can't figure out how to alter things while in this thread - every time I try to do something it crashes // Eventually handling this exception would be nice } } }; Thread t = new Thread(r); t.start(); } } private void sendSMS(String phoneNumber, String message) { SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null, message, null, null); } /*@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. act.getMenuInflater().inflate(R.menu.main, menu); return true; }*/ @Override public void onResume(){ super.onResume(); // Restore preferences SharedPreferences settings = act.getSharedPreferences("settings", 0); tasksToSelected = new HashMap<String, Boolean>(); tasksToSelected.put(water, settings.getBoolean(water, false)); tasksToSelected.put(microDone, settings.getBoolean(microDone, false)); tasksToSelected.put(microExplo,settings.getBoolean(microExplo, false)); tasksToSelected.put(other,settings.getBoolean(other, false)); } @Override public void onPause(){ super.onPause(); // We need an Editor object to make preference changes. // All objects are from android.context.Context SharedPreferences settings = act.getSharedPreferences("settings", 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(water, tasksToSelected.get(water)); editor.putBoolean(microDone, tasksToSelected.get(microDone)); editor.putBoolean(microExplo, tasksToSelected.get(microExplo)); editor.putBoolean(other, tasksToSelected.get(other)); // Commit the edits! editor.commit(); } @Override public void onDestroy(){ super.onDestroy(); // Stop listening for things! boilingWaterDetector.stopDetection(); } @Override public void processBoilingEvent() { if (!alerted) { alerted = true; act.runOnUiThread(new Runnable() { public void run() { alert(water); } }); } } }
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; /** * run/stop/etc buttons for the ide */ public class EditorToolbar extends JComponent implements MouseInputListener, KeyListener { /** Rollover titles for each button. */ static final String title[] = { "Verify", "Upload", "New", "Open", "Save", "Serial Monitor" }; /** Titles for each button when the shift key is pressed. */ static final String titleShift[] = { "Verify", "Upload Using Programmer", "New Editor Window", "Open in Another Window", "Save", "Serial Monitor" }; static final int BUTTON_COUNT = title.length; /** Width of each toolbar button. */ static final int BUTTON_WIDTH = 27; /** Height of each toolbar button. */ static final int BUTTON_HEIGHT = 32; /** The amount of space between groups of buttons on the toolbar. */ static final int BUTTON_GAP = 5; /** Size of the button image being chopped up. */ static final int BUTTON_IMAGE_SIZE = 33; static final int RUN = 0; static final int EXPORT = 1; static final int NEW = 2; static final int OPEN = 3; static final int SAVE = 4; static final int SERIAL = 5; static final int INACTIVE = 0; static final int ROLLOVER = 1; static final int ACTIVE = 2; Editor editor; Image offscreen; int width, height; Color bgcolor; static Image[][] buttonImages; int currentRollover; JPopupMenu popup; JMenu menu; int buttonCount; int[] state = new int[BUTTON_COUNT]; Image[] stateImage; int which[]; // mapping indices to implementation int x1[], x2[]; int y1, y2; Font statusFont; Color statusColor; boolean shiftPressed; public EditorToolbar(Editor editor, JMenu menu) { this.editor = editor; this.menu = menu; buttonCount = 0; which = new int[BUTTON_COUNT]; //which[buttonCount++] = NOTHING; which[buttonCount++] = RUN; which[buttonCount++] = EXPORT; which[buttonCount++] = NEW; which[buttonCount++] = OPEN; which[buttonCount++] = SAVE; which[buttonCount++] = SERIAL; currentRollover = -1; bgcolor = Theme.getColor("buttons.bgcolor"); statusFont = Theme.getFont("buttons.status.font"); statusColor = Theme.getColor("buttons.status.color"); addMouseListener(this); addMouseMotionListener(this); } protected void loadButtons() { Image allButtons = Base.getThemeImage("buttons.gif", this); buttonImages = new Image[BUTTON_COUNT][3]; for (int i = 0; i < BUTTON_COUNT; i++) { for (int state = 0; state < 3; state++) { Image image = createImage(BUTTON_WIDTH, BUTTON_HEIGHT); Graphics g = image.getGraphics(); g.drawImage(allButtons, -(i*BUTTON_IMAGE_SIZE) - 3, (-2 + state)*BUTTON_IMAGE_SIZE, null); buttonImages[i][state] = image; } } } @Override public void paintComponent(Graphics screen) { // this data is shared by all EditorToolbar instances if (buttonImages == null) { loadButtons(); } // this happens once per instance of EditorToolbar if (stateImage == null) { state = new int[buttonCount]; stateImage = new Image[buttonCount]; for (int i = 0; i < buttonCount; i++) { setState(i, INACTIVE, false); } y1 = 0; y2 = BUTTON_HEIGHT; x1 = new int[buttonCount]; x2 = new int[buttonCount]; } Dimension size = getSize(); if ((offscreen == null) || (size.width != width) || (size.height != height)) { offscreen = createImage(size.width, size.height); width = size.width; height = size.height; int offsetX = 3; for (int i = 0; i < buttonCount; i++) { x1[i] = offsetX; if (i == 2 || i == 6) x1[i] += BUTTON_GAP; x2[i] = x1[i] + BUTTON_WIDTH; offsetX = x2[i]; } // Serial button must be on the right x1[SERIAL] = width - BUTTON_WIDTH - 3; x2[SERIAL] = width - 3; } Graphics g = offscreen.getGraphics(); g.setColor(bgcolor); //getBackground()); g.fillRect(0, 0, width, height); for (int i = 0; i < buttonCount; i++) { g.drawImage(stateImage[i], x1[i], y1, null); } g.setColor(statusColor); g.setFont(statusFont); /* // if i ever find the guy who wrote the java2d api, i will hurt him. * * whereas I love the Java2D API. --jdf. lol. * Graphics2D g2 = (Graphics2D) g; FontRenderContext frc = g2.getFontRenderContext(); float statusW = (float) statusFont.getStringBounds(status, frc).getWidth(); float statusX = (getSize().width - statusW) / 2; g2.drawString(status, statusX, statusY); */ if (currentRollover != -1) { int statusY = (BUTTON_HEIGHT + g.getFontMetrics().getAscent()) / 2; String status = shiftPressed ? titleShift[currentRollover] : title[currentRollover]; g.drawString(status, buttonCount * BUTTON_WIDTH + 3 * BUTTON_GAP, statusY); } screen.drawImage(offscreen, 0, 0, null); if (!isEnabled()) { screen.setColor(new Color(0,0,0,100)); screen.fillRect(0, 0, getWidth(), getHeight()); } } public void mouseMoved(MouseEvent e) { if (!isEnabled()) return; // mouse events before paint(); if (state == null) return; if (state[OPEN] != INACTIVE) { // avoid flicker, since there will probably be an update event setState(OPEN, INACTIVE, false); } handleMouse(e); } public void mouseDragged(MouseEvent e) { } public void handleMouse(MouseEvent e) { int x = e.getX(); int y = e.getY(); if (currentRollover != -1) { if ((x > x1[currentRollover]) && (y > y1) && (x < x2[currentRollover]) && (y < y2)) { return; } else { setState(currentRollover, INACTIVE, true); currentRollover = -1; } } int sel = findSelection(x, y); if (sel == -1) return; if (state[sel] != ACTIVE) { setState(sel, ROLLOVER, true); currentRollover = sel; } } private int findSelection(int x, int y) { // if app loads slowly and cursor is near the buttons // when it comes up, the app may not have time to load if ((x1 == null) || (x2 == null)) return -1; for (int i = 0; i < buttonCount; i++) { if ((y > y1) && (x > x1[i]) && (y < y2) && (x < x2[i])) { //System.out.println("sel is " + i); return i; } } return -1; } private void setState(int slot, int newState, boolean updateAfter) { state[slot] = newState; stateImage[slot] = buttonImages[which[slot]][newState]; if (updateAfter) { repaint(); } } public void mouseEntered(MouseEvent e) { handleMouse(e); } public void mouseExited(MouseEvent e) { // if the popup menu for is visible, don't register this, // because the popup being set visible will fire a mouseExited() event if ((popup != null) && popup.isVisible()) return; if (state[OPEN] != INACTIVE) { setState(OPEN, INACTIVE, true); } handleMouse(e); } int wasDown = -1; public void mousePressed(MouseEvent e) { // jdf if (!isEnabled()) return; final int x = e.getX(); final int y = e.getY(); int sel = findSelection(x, y); ///if (sel == -1) return false; if (sel == -1) return; currentRollover = -1; switch (sel) { case RUN: editor.handleRun(false); break; // case STOP: // editor.handleStop(); // break; case OPEN: popup = menu.getPopupMenu(); popup.show(EditorToolbar.this, x, y); break; case NEW: if (shiftPressed) { editor.base.handleNew(); } else { editor.base.handleNewReplace(); } break; case SAVE: editor.handleSave(false); break; case EXPORT: editor.handleExport(e.isShiftDown()); break; case SERIAL: editor.handleSerial(); break; } } public void mouseClicked(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } /** * Set a particular button to be active. */ public void activate(int what) { if (buttonImages != null) { setState(what, ACTIVE, true); } } /** * Set a particular button to be active. */ public void deactivate(int what) { if (buttonImages != null) { setState(what, INACTIVE, true); } } public Dimension getPreferredSize() { return getMinimumSize(); } public Dimension getMinimumSize() { return new Dimension((BUTTON_COUNT + 1)*BUTTON_WIDTH, BUTTON_HEIGHT); } public Dimension getMaximumSize() { return new Dimension(3000, BUTTON_HEIGHT); } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SHIFT) { shiftPressed = true; repaint(); } } public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SHIFT) { shiftPressed = false; repaint(); } } public void keyTyped(KeyEvent e) { } }
package com.github.dreamsnatcher; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer; import com.badlogic.gdx.utils.Disposable; import com.github.dreamsnatcher.entities.GameObject; import com.github.dreamsnatcher.utils.Assets; import com.github.dreamsnatcher.utils.Constants; import java.util.concurrent.TimeUnit; public class WorldRenderer implements Disposable { public OrthographicCamera camera; public OrthographicCamera cameraGUI; private SpriteBatch batch; private SpriteBatch nightmareBatch; private WorldController worldController; private Box2DDebugRenderer debugRenderer; private BitmapFont font; private TextureRegion background0; private TextureRegion background1; private TextureRegion background2; private TextureRegion background3; private TextureRegion energybar; private TextureRegion energypixel; private TextureRegion beerpixel; private TextureRegion penaltypixel; private TextureRegion schaumkrone; private TextureRegion[][] bgs; private int[] rotation; private TextureRegion finishPicture; public int beercounter = 0; public float timer = 0; public final float MAXTIMER = 0.02f; int minX = -10; int minY = -10; int maxX = 10; int maxY = 10; public WorldRenderer(WorldController worldController) { this.worldController = worldController; init(); } private void init() { debugRenderer = new Box2DDebugRenderer(); batch = new SpriteBatch(); nightmareBatch = new SpriteBatch(); camera = new OrthographicCamera(Constants.VIEWPORT_WIDTH, Constants.VIEWPORT_HEIGHT); camera.position.set(0, 0, 0); camera.update(); rotation = new int[100]; for (int i = 0; i < rotation.length; i++) { rotation[i] = (int) (Math.random() * 16) + 1; } background0 = Assets.stars0; background1 = Assets.stars1; background2 = Assets.stars2; background3 = Assets.stars3; energybar = Assets.energyBar; energypixel = Assets.energyPixel; penaltypixel = Assets.penaltyPixel; beerpixel = Assets.bierpixel; schaumkrone = Assets.schaumkrone; //GUI camera cameraGUI = new OrthographicCamera(Constants.VIEWPORT_GUI_WIDTH, Constants.VIEWPORT_GUI_HEIGHT); cameraGUI.position.set(0, 0, 0); cameraGUI.setToOrtho(true); //flip y-axis cameraGUI.update(); font = new BitmapFont(Gdx.files.internal("fonts/superfont.fnt"), Gdx.files.internal("fonts/superfont.png"), true); font = new BitmapFont(Gdx.files.internal("fonts/candlestick.fnt"), Gdx.files.internal("fonts/candlestick.png"), true); font.setColor(Color.GREEN); finishPicture = Assets.finishWookie; finishPicture.flip(false, true); } public void calculateBackground() { for (GameObject o : worldController.gameWorld.objects) { if (o.position.x < minX) { minX = (int) o.position.x; } if (o.position.y < minY) { minY = (int) o.position.y; } if (o.position.y > maxY) { maxY = (int) o.position.y; } if (o.position.x > maxX) { maxX = (int) o.position.x; } } minX -= 10; minY -= 10; maxX += 10; maxY += 10; bgs = new TextureRegion[maxX - minX][maxY - minY]; int k = 0; TextureRegion textureRegion; for (int i = 0; i < bgs.length; i++) { for (int j = 0; j < bgs[i].length; j++) { k++; switch (rotation[k % rotation.length]) { case 1: textureRegion = new TextureRegion(background0); break; case 2: textureRegion = new TextureRegion(background0); textureRegion.flip(true, false); break; case 3: textureRegion = new TextureRegion(background0); textureRegion.flip(true, true); break; case 4: textureRegion = new TextureRegion(background0); textureRegion.flip(false, true); break; case 5: textureRegion = new TextureRegion(background1); break; case 6: textureRegion = new TextureRegion(background1); textureRegion.flip(true, false); break; case 7: textureRegion = new TextureRegion(background1); textureRegion.flip(true, true); break; case 8: textureRegion = new TextureRegion(background1); textureRegion.flip(false, true); break; case 9: textureRegion = new TextureRegion(background2); break; case 10: textureRegion = new TextureRegion(background2); textureRegion.flip(true, false); break; case 11: textureRegion = new TextureRegion(background2); textureRegion.flip(true, true); break; case 12: textureRegion = new TextureRegion(background2); textureRegion.flip(false, true); break; case 13: textureRegion = new TextureRegion(background3); break; case 14: textureRegion = new TextureRegion(background3); textureRegion.flip(true, false); break; case 15: textureRegion = new TextureRegion(background3); textureRegion.flip(true, true); break; case 16: textureRegion = new TextureRegion(background3); textureRegion.flip(false, true); break; default: textureRegion = background0; } bgs[i][j] = textureRegion; } } } public void renderGUI(SpriteBatch batch) { batch.setProjectionMatrix(cameraGUI.combined); batch.begin(); String mmss = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(worldController.timeElapsed) % TimeUnit.HOURS.toMinutes(1), TimeUnit.MILLISECONDS.toSeconds(worldController.timeElapsed) % TimeUnit.MINUTES.toSeconds(1)); String lastHighscore = "No highscore yet"; long highScoreVal = worldController.getHighscore(); if (highScoreVal > -1) { lastHighscore = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(highScoreVal) % TimeUnit.HOURS.toMinutes(1), TimeUnit.MILLISECONDS.toSeconds(highScoreVal) % TimeUnit.MINUTES.toSeconds(1)); } font.draw(batch, mmss, 10, 10); font.draw(batch, "Highscore: " + lastHighscore, 100, 10); batch.draw(Assets.indicator, 10, 20, Assets.indicator.getRegionWidth() / 2, Assets.indicator.getRegionHeight() / 2, Assets.indicator.getRegionWidth(), Assets.indicator.getRegionHeight(), 0.5f, 0.5f, getCurrentIndicatorAngle()); batch.draw(energybar, 760, 100, 40, 400); if (!worldController.isFinish()) { for (int i = 1; i <= this.worldController.gameWorld.spaceShip.getEnergy(); i++) { if (this.worldController.gameWorld.spaceShip.getPenaltyTime() <= 0) { batch.draw(new TextureRegion(energypixel), 760, 500 - i * 4, 40, 4); } else { batch.draw(new TextureRegion(penaltypixel), 760, 500 - i * 4, 40, 4); } } if (this.worldController.gameWorld.spaceShip.getPenaltyTime() > 0) { this.worldController.gameWorld.spaceShip.lowerPenaltyTime(Gdx.graphics.getDeltaTime()); } } if (worldController.isFinish()) { timer += Gdx.graphics.getDeltaTime(); if (timer > MAXTIMER) { timer = 0; if (beercounter <= 400) { beercounter++; } } for (int i = 1; i <= beercounter; i++) { batch.draw(new TextureRegion(beerpixel), 760, 500 - i, 40, 4); } batch.draw(new TextureRegion(schaumkrone), 755, 500 - beercounter - 3, 50, 20); } if (beercounter >= 400) { batch.draw(new TextureRegion(finishPicture), 100, 300, finishPicture.getRegionWidth(), finishPicture.getRegionHeight()); worldController.finalAnimationFinished = true; } batch.draw(Assets.back, 710, 2, Assets.back.getRegionWidth() / 2, Assets.back.getRegionHeight() / 2); batch.end(); } private float getCurrentIndicatorAngle() { Vector2 shipPos = worldController.gameWorld.spaceShip.getBody().getPosition(); Vector2 barPos = worldController.gameWorld.spacebar.getBody().getPosition(); Vector2 shipBarDistance = new Vector2(shipPos.x - barPos.x, shipPos.y - barPos.y); return 180 - shipBarDistance.angle(); } public void render() { worldController.cameraHelper.applyTo(camera); batch.setProjectionMatrix(camera.combined); batch.begin(); renderBackground(); for (GameObject object : worldController.gameWorld.objects) { object.render(batch); } worldController.gameWorld.spaceShip.render(batch); batch.end(); showNightmare(worldController.gameWorld.spaceShip.getEnergy()); renderGUI(batch); if (worldController.isDebug()) { debugRenderer.render(worldController.getB2World(), camera.combined); } } private void renderBackground() { for (int i = 0; i < maxX-minX; i++) { for (int j = 0; j < maxY-minY; j++) { batch.draw(bgs[i][j], i+minX, j+minY, 1, 1); } } } public void resize(int width, int height) { camera.viewportWidth = (Constants.VIEWPORT_HEIGHT / height) * width; //calculate aspect ratio camera.update(); cameraGUI.viewportWidth = (Constants.VIEWPORT_GUI_HEIGHT / height) * width; //calculate aspect ratio cameraGUI.update(); } public void showNightmare(float energy) { float alpha = 0.0f; if (energy < 0f) { energy = 0f; } if (!worldController.isFinish() && energy < 20) { alpha = (20 - energy) / 20f; } else if (worldController.isFinish()) { alpha = 0.0f; } nightmareBatch.setProjectionMatrix(cameraGUI.combined); nightmareBatch.begin(); Color c = nightmareBatch.getColor(); nightmareBatch.setColor(c.r, c.g, c.b, alpha); nightmareBatch.draw(Assets.nightmare, 0, 0, cameraGUI.viewportWidth, cameraGUI.viewportHeight); nightmareBatch.end(); } @Override public void dispose() { batch.dispose(); } }
package com.kumuluz.ee; import com.kumuluz.ee.common.ServletServer; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.utils.ResourceUtils; import com.kumuluz.ee.loaders.ComponentLoader; import com.kumuluz.ee.loaders.ServerLoader; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 1.0.0 */ public class EeApplication { private Logger log = Logger.getLogger(EeApplication.class.getSimpleName()); private ServletServer server; private EeConfig eeConfig; public EeApplication() { this.eeConfig = new EeConfig(); initialize(); } public EeApplication(EeConfig eeConfig) { this.eeConfig = eeConfig; initialize(); } public static void main(String args[]) { EeApplication app = new EeApplication(); } public void initialize() { log.info("Initializing KumuluzEE"); log.info("Checking for requirements"); checkRequirements(); log.info("Checks passed"); ServerLoader sl = new ServerLoader(); server = sl.loadServletServer(); server.setServerConfig(eeConfig.getServerConfig()); server.initServer(); server.initWebContext(); ComponentLoader cp = new ComponentLoader(server, eeConfig); cp.loadComponents(); server.startServer(); log.info("KumuluzEE started successfully"); } public void checkRequirements() { if (ResourceUtils.getProjectWebResources() == null) { throw new IllegalStateException("No 'webapp' directory found in the projects " + "resources folder. Please add it to your resources even if it will be empty " + "so that the servlet server can bind to it. If you have added it and still " + "see this error please make sure you have at least one file/class in your " + "projects as some IDEs don't build the project if its empty"); } if (ResourceUtils.isRunningInJar()) { throw new RuntimeException("Running in a jar is currently not supported yet. Please " + "build the application with the 'maven-dependency' plugin to explode your app" + " with dependencies. Then run it with 'java -cp " +
package hudson.model; import hudson.Extension; import hudson.ExtensionList; import hudson.ExtensionListListener; import hudson.ExtensionPoint; import hudson.ProxyConfiguration; import hudson.init.InitMilestone; import hudson.init.Initializer; import hudson.util.FormValidation; import hudson.util.FormValidation.Kind; import hudson.util.QuotedStringTokenizer; import hudson.util.TextFile; import static hudson.util.TimeUnit2.DAYS; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import jenkins.model.DownloadSettings; import jenkins.model.Jenkins; import jenkins.util.JSONSignatureValidator; import net.sf.json.JSONException; import net.sf.json.JSONObject; import org.apache.commons.io.IOUtils; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; /** * Service for plugins to periodically retrieve update data files * (like the one in the update center) through browsers. * * <p> * Because the retrieval of the file goes through XmlHttpRequest, * we cannot reliably pass around binary. * * @author Kohsuke Kawaguchi */ @Extension public class DownloadService extends PageDecorator { /** * Builds up an HTML fragment that starts all the download jobs. */ public String generateFragment() { if (!DownloadSettings.usePostBack()) { return ""; } if (neverUpdate) return ""; if (doesNotSupportPostMessage()) return ""; StringBuilder buf = new StringBuilder(); if(Jenkins.getInstance().hasPermission(Jenkins.READ)) { long now = System.currentTimeMillis(); for (Downloadable d : Downloadable.all()) { if(d.getDue()<now && d.lastAttempt+10*1000<now) { buf.append("<script>") .append("Behaviour.addLoadEvent(function() {") .append(" downloadService.download(") .append(QuotedStringTokenizer.quote(d.getId())) .append(',') .append(QuotedStringTokenizer.quote(mapHttps(d.getUrl()))) .append(',') .append("{version:"+QuotedStringTokenizer.quote(Jenkins.VERSION)+'}') .append(',') .append(QuotedStringTokenizer.quote(Stapler.getCurrentRequest().getContextPath()+'/'+getUrl()+"/byId/"+d.getId()+"/postBack")) .append(',') .append("null);") .append("});") .append("</script>"); d.lastAttempt = now; } } } return buf.toString(); } private boolean doesNotSupportPostMessage() { StaplerRequest req = Stapler.getCurrentRequest(); if (req==null) return false; String ua = req.getHeader("User-Agent"); if (ua==null) return false; // according to http://caniuse.com/#feat=x-doc-messaging, IE <=7 doesn't support pstMessage // we want to err on the cautious side here. // Because of JENKINS-15105, we can't serve signed metadata from JSON, which means we need to be // using a modern browser as a vehicle to request these data. This check is here to prevent Jenkins // from using older browsers that are known not to support postMessage as the vehicle. return ua.contains("Windows") && (ua.contains(" MSIE 5.") || ua.contains(" MSIE 6.") || ua.contains(" MSIE 7.")); } private String mapHttps(String url) { /* HACKISH: Loading scripts in HTTP from HTTPS pages cause browsers to issue a warning dialog. The elegant way to solve the problem is to always load update center from HTTPS, but our backend mirroring scheme isn't ready for that. So this hack serves regular traffic in HTTP server, and only use HTTPS update center for Jenkins in HTTPS. We'll monitor the traffic to see if we can sustain this added traffic. */ if (url.startsWith("http://updates.jenkins-ci.org/") && Jenkins.getInstance().isRootUrlSecure()) return "https"+url.substring(4); return url; } /** * Gets {@link Downloadable} by its ID. * Used to bind them to URL. */ public Downloadable getById(String id) { for (Downloadable d : Downloadable.all()) if(d.getId().equals(id)) return d; return null; } /** * Loads JSON from a JSONP URL. * Metadata for downloadables and update centers is offered in two formats, both designed for download from the browser (predating {@link DownloadSettings}): * HTML using {@code postMessage} for newer browsers, and JSONP as a fallback. * Confusingly, the JSONP files are given the {@code *.json} file extension, when they are really JavaScript and should be {@code *.js}. * This method extracts the JSON from a JSONP URL, since that is what we actually want when we download from the server. * (Currently the true JSON is not published separately, and extracting from the {@code *.json.html} is more work.) * @param src a URL to a JSONP file (typically including {@code id} and {@code version} query parameters) * @return the embedded JSON text * @throws IOException if either downloading or processing failed */ @Restricted(NoExternalUse.class) public static String loadJSON(URL src) throws IOException { InputStream is = ProxyConfiguration.open(src).getInputStream(); try { String jsonp = IOUtils.toString(is, "UTF-8"); int start = jsonp.indexOf('{'); int end = jsonp.lastIndexOf('}'); if (start >= 0 && end > start) { return jsonp.substring(start, end + 1); } else { throw new IOException("Could not find JSON in " + src); } } finally { is.close(); } } /** * Loads JSON from a JSON-with-{@code postMessage} URL. * @param src a URL to a JSON HTML file (typically including {@code id} and {@code version} query parameters) * @return the embedded JSON text * @throws IOException if either downloading or processing failed */ @Restricted(NoExternalUse.class) public static String loadJSONHTML(URL src) throws IOException { InputStream is = ProxyConfiguration.open(src).getInputStream(); try { String jsonp = IOUtils.toString(is, "UTF-8"); String preamble = "window.parent.postMessage(JSON.stringify("; int start = jsonp.indexOf(preamble); int end = jsonp.lastIndexOf("),'*');"); if (start >= 0 && end > start) { return jsonp.substring(start + preamble.length(), end).trim(); } else { throw new IOException("Could not find JSON in " + src); } } finally { is.close(); } } /** * This installs itself as a listener to changes to the Downloadable extension list and will download the metadata * for any newly added Downloadables. */ @Restricted(NoExternalUse.class) public static class DownloadableListener extends ExtensionListListener { /** * Install this listener to the Downloadable extension list after all extensions have been loaded; we only * care about those that are added after initialization */ @Initializer(after = InitMilestone.EXTENSIONS_AUGMENTED) public static void installListener() { ExtensionList.lookup(Downloadable.class).addListener(new DownloadableListener()); } /** * Look for Downloadables that have no data, and update them. */ @Override public void onChange() { for (Downloadable d : Downloadable.all()) { TextFile f = d.getDataFile(); if (f == null || !f.exists()) { LOGGER.log(Level.FINE, "Updating metadata for " + d.getId()); try { d.updateNow(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to update metadata for " + d.getId(), e); } } else { LOGGER.log(Level.FINER, "Skipping update of metadata for " + d.getId()); } } } private static final Logger LOGGER = Logger.getLogger(DownloadableListener.class.getName()); } /** * Represents a periodically updated JSON data file obtained from a remote URL. * * <p> * This mechanism is one of the basis of the update center, which involves fetching * up-to-date data file. * * @since 1.305 */ public static class Downloadable implements ExtensionPoint { private final String id; private final String url; private final long interval; private volatile long due=0; private volatile long lastAttempt=Long.MIN_VALUE; public Downloadable(String id, String url, long interval) { this.id = id; this.url = url; this.interval = interval; } public Downloadable() { this.id = getClass().getName().replace('$','.'); this.url = this.id+".json"; this.interval = DEFAULT_INTERVAL; } /** * Uses the class name as an ID. */ public Downloadable(Class id) { this(id.getName().replace('$','.')); } public Downloadable(String id) { this(id,id+".json"); } public Downloadable(String id, String url) { this(id,url, DEFAULT_INTERVAL); } public String getId() { return id; } /** * URL to download. */ public String getUrl() { return Jenkins.getInstance().getUpdateCenter().getDefaultBaseUrl()+"updates/"+url; } /** * URLs to download from. */ public List<String> getUrls() { List<String> updateSites = new ArrayList<String>(); for (UpdateSite site : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) { String siteUrl = site.getUrl(); int baseUrlEnd = siteUrl.indexOf("update-center.json"); if (baseUrlEnd != -1) { String siteBaseUrl = siteUrl.substring(0, baseUrlEnd); updateSites.add(siteBaseUrl + "updates/" + url); } else { LOGGER.log(Level.WARNING, "Url {0} does not look like an update center:", siteUrl); } } return updateSites; } /** * How often do we retrieve the new image? * * @return * number of milliseconds between retrieval. */ public long getInterval() { return interval; } /** * This is where the retrieved file will be stored. */ public TextFile getDataFile() { return new TextFile(new File(Jenkins.getInstance().getRootDir(),"updates/"+id)); } /** * When shall we retrieve this file next time? */ public long getDue() { if(due==0) // if the file doesn't exist, this code should result // in a very small (but >0) due value, which should trigger // the retrieval immediately. due = getDataFile().file.lastModified()+interval; return due; } /** * Loads the current file into JSON and returns it, or null * if no data exists. */ public JSONObject getData() throws IOException { TextFile df = getDataFile(); if(df.exists()) try { return JSONObject.fromObject(df.read()); } catch (JSONException e) { df.delete(); // if we keep this file, it will cause repeated failures throw new IOException("Failed to parse "+df+" into JSON",e); } return null; } /** * This is where the browser sends us the data. */ public void doPostBack(StaplerRequest req, StaplerResponse rsp) throws IOException { DownloadSettings.checkPostBackAccess(); long dataTimestamp = System.currentTimeMillis(); due = dataTimestamp+getInterval(); // success or fail, don't try too often String json = IOUtils.toString(req.getInputStream(),"UTF-8"); FormValidation e = load(json, dataTimestamp); if (e.kind != Kind.OK) { LOGGER.severe(e.renderHtml()); throw e; } rsp.setContentType("text/plain"); // So browser won't try to parse response } private FormValidation load(String json, long dataTimestamp) throws IOException { TextFile df = getDataFile(); df.write(json); df.file.setLastModified(dataTimestamp); LOGGER.info("Obtained the updated data file for "+id); return FormValidation.ok(); } @Restricted(NoExternalUse.class) public FormValidation updateNow() throws IOException { List<JSONObject> jsonList = new ArrayList<>(); boolean toolInstallerMetadataExists = false; for (String site : getUrls()) { String jsonString; try { jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))); toolInstallerMetadataExists = true; } catch (Exception e) { LOGGER.log(Level.WARNING, "Could not load json from " + site, e ); continue; } JSONObject o = JSONObject.fromObject(jsonString); if (signatureCheck) { FormValidation e = new JSONSignatureValidator("downloadable '"+id+"'").verifySignature(o); if (e.kind!= Kind.OK) { LOGGER.log(Level.WARNING, "signature check failed for " + site, e ); continue; } } jsonList.add(o); } if (jsonList.size() == 0 && toolInstallerMetadataExists) { return FormValidation.warning("None of the tool installer metadata passed the signature check"); } else if (!toolInstallerMetadataExists) { LOGGER.log(Level.WARNING, "No tool installer metadata found for " + id); return FormValidation.ok(); } JSONObject reducedJson = reduce(jsonList); return load(reducedJson.toString(), System.currentTimeMillis()); } /** * Function that takes multiple JSONObjects and returns a single one. * @param jsonList to be processed * @return a single JSONObject */ public JSONObject reduce(List<JSONObject> jsonList) { return jsonList.get(0); } /** * check if the list of update center entries has duplicates * @param genericList list of entries coming from multiple update centers * @param comparator the unique ID of an entry * @param <T> the generic class * @return true if the list has duplicates, false otherwise */ public static <T> boolean hasDuplicates (List<T> genericList, String comparator) { if (genericList.isEmpty()) { return false; } Field field; try { field = genericList.get(0).getClass().getDeclaredField(comparator); } catch (NoSuchFieldException e) { LOGGER.warning("comparator: " + comparator + "does not exist for " + genericList.get(0).getClass() + ", " + e); return false; } for (int i = 0; i < genericList.size(); i ++ ) { T data1 = genericList.get(i); for (int j = i + 1; j < genericList.size(); j ++ ) { T data2 = genericList.get(j); try { if (field.get(data1).equals(field.get(data2))) { return true; } } catch (IllegalAccessException e) { LOGGER.warning("could not access field: " + comparator + ", " + e); } } } return false; } /** * Returns all the registered {@link Downloadable}s. */ public static ExtensionList<Downloadable> all() { return ExtensionList.lookup(Downloadable.class); } /** * Returns the {@link Downloadable} that has the given ID. */ public static Downloadable get(String id) { for (Downloadable d : all()) { if(d.id.equals(id)) return d; } return null; } private static final Logger LOGGER = Logger.getLogger(Downloadable.class.getName()); private static final long DEFAULT_INTERVAL = Long.getLong(Downloadable.class.getName()+".defaultInterval", DAYS.toMillis(1)); } public static boolean neverUpdate = Boolean.getBoolean(DownloadService.class.getName()+".never"); /** * May be used to temporarily disable signature checking on {@link DownloadService} and {@link UpdateCenter}. * Useful when upstream signatures are broken, such as due to expired certificates. * Should only be used when {@link DownloadSettings#isUseBrowser}; * disabling signature checks for in-browser downloads is <em>very dangerous</em> as unprivileged users could submit spoofed metadata! */ public static boolean signatureCheck = !Boolean.getBoolean(DownloadService.class.getName()+".noSignatureCheck"); }
package org.monarchinitiative.exomiser.core.phenotype; import org.junit.jupiter.api.Test; import org.monarchinitiative.exomiser.core.phenotype.service.OntologyService; import org.monarchinitiative.exomiser.core.prioritisers.service.TestPriorityServiceFactory; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * @author Jules Jacobsen <[email protected]> */ public class PhenotypeMatchServiceTest { private OntologyService ontologyService = TestPriorityServiceFactory.testOntologyService(); @Test public void testIntegrationWithModelScorer() { PhenotypeMatchService instance = new PhenotypeMatchService(ontologyService); List<String> hpoIds = TestPriorityServiceFactory.pfeifferSyndromePhenotypes() .stream() .map(PhenotypeTerm::getId) .collect(toList()); List<PhenotypeTerm> queryTerms = instance.makePhenotypeTermsFromHpoIds(hpoIds); PhenotypeMatcher hpHpQueryMatcher = instance.getHumanPhenotypeMatcherForTerms(queryTerms); ModelScorer<TestModel> modelScorer = PhenodigmModelScorer.forSameSpecies(hpHpQueryMatcher); TestModel exactMatch = new TestModel("EXACT_MATCH", hpoIds); TestModel noMatch = new TestModel("NO_MATCH", Collections.emptyList()); List<ModelPhenotypeMatch> matches = Stream.of(exactMatch, noMatch) .map(modelScorer::scoreModel) .sorted() .collect(toList()); ModelPhenotypeMatch topScore = matches.get(0); assertThat(topScore.getScore(), equalTo(1d)); assertThat(topScore.getModel(), equalTo(exactMatch)); ModelPhenotypeMatch bottomScore = matches.get(1); assertThat(bottomScore.getScore(), equalTo(0d)); assertThat(bottomScore.getModel(), equalTo(noMatch)); } /** * Simple class to enable testing the ModelScorer. */ private static class TestModel implements Model { private final String id; private final List<String> phenotypes; public TestModel(String id, List<String> phenotypes) { this.id = id; this.phenotypes = phenotypes; } @Override public String getId() { return id; } @Override public List<String> getPhenotypeIds() { return phenotypes; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TestModel testModel = (TestModel) o; return Objects.equals(id, testModel.id) && Objects.equals(phenotypes, testModel.phenotypes); } @Override public int hashCode() { return Objects.hash(id, phenotypes); } @Override public String toString() { return "TestModel{" + "id='" + id + '\'' + ", phenotypes=" + phenotypes + '}'; } } }
package hudson.scm; import hudson.model.AbstractProject; import hudson.model.Hudson; /** * Maintains the automatically infered {@link RepositoryBrowser} instance. * * <p> * To reduce the user's work, Hudson tries to infer applicable {@link RepositoryBrowser} * from configurations of other jobs. But this needs caution &mdash; for example, * such infered {@link RepositoryBrowser} must be recalculated whenever * a job configuration changes somewhere. * * <p> * This class makes such tracking easy by hiding this logic. */ final class AutoBrowserHolder { private int cacheGeneration; private RepositoryBrowser cache; private SCM owner; public AutoBrowserHolder(SCM owner) { this.owner = owner; } public RepositoryBrowser get() { int g = owner.getDescriptor().generation; if(g!=cacheGeneration) { cacheGeneration = g; cache = infer(); } return cache; } /** * Picks up a {@link CVSRepositoryBrowser} that matches the * given {@link CVSSCM} from existing other jobs. * * @return * null if no applicable configuration was found. */ private RepositoryBrowser infer() { for( AbstractProject p : Hudson.getInstance().getAllItems(AbstractProject.class) ) { SCM scm = p.getScm(); if (scm!=null && scm.getClass()==owner.getClass() && scm.getBrowser()!=null && ((SCMDescriptor)scm.getDescriptor()).isBrowserReusable(scm,owner)) { return scm.getBrowser(); } } return null; } }
package hudson.security; import hudson.model.Hudson; import java.io.IOException; import java.util.logging.Logger; import static java.util.logging.Level.SEVERE; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.acegisecurity.AuthenticationManager; import org.acegisecurity.ui.rememberme.RememberMeServices; import org.acegisecurity.userdetails.UserDetailsService; public class HudsonFilter implements Filter { /** * The SecurityRealm specific filter. */ private volatile Filter filter; /** * The {@link #init(FilterConfig)} may be called before the Hudson instance is up (which is * required for initialization of the filter). So we store the * filterConfig for later lazy-initialization of the filter. */ private FilterConfig filterConfig; /** * {@link AuthenticationManager} proxy so that the acegi filter chain can stay the same * even when security setting is reconfigured. * * @deprecated in 1.271. * This proxy always delegate to {@code Hudson.getInstance().getSecurityRealm().getSecurityComponents().manager}, * so use that instead. */ public static final AuthenticationManagerProxy AUTHENTICATION_MANAGER = new AuthenticationManagerProxy(); /** * {@link UserDetailsService} proxy so that the acegi filter chain can stay the same * even when security setting is reconfigured. * * @deprecated in 1.271. * This proxy always delegate to {@code Hudson.getInstance().getSecurityRealm().getSecurityComponents().userDetails}, * so use that instead. */ public static final UserDetailsServiceProxy USER_DETAILS_SERVICE_PROXY = new UserDetailsServiceProxy(); /** * {@link RememberMeServices} proxy so that the acegi filter chain can stay the same * even when security setting is reconfigured. * * @deprecated in 1.271. * This proxy always delegate to {@code Hudson.getInstance().getSecurityRealm().getSecurityComponents().rememberMe}, * so use that instead. */ public static final RememberMeServicesProxy REMEMBER_ME_SERVICES_PROXY = new RememberMeServicesProxy(); public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; // this is how we make us available to the rest of Hudson. filterConfig.getServletContext().setAttribute(HudsonFilter.class.getName(),this); try { Hudson hudson = Hudson.getInstance(); if (hudson != null) { // looks like we are initialized after Hudson came into being. initialize it now. See #3069 LOGGER.fine("Security wasn't initialized; Initializing it..."); SecurityRealm securityRealm = hudson.getSecurityRealm(); reset(securityRealm); LOGGER.fine("securityRealm is " + securityRealm); LOGGER.fine("Security initialized"); } } catch (ExceptionInInitializerError e) { // see HUDSON-4592. In some containers this happens before // WebAppMain.contextInitialized kicks in, which makes // the whole thing fail hard before a nicer error check // in WebAppMain.contextInitialized. So for now, // just report it here, and let the WebAppMain handle the failure gracefully. LOGGER.log(SEVERE, "Failed to initialize Hudson",e); } } /** * Gets the {@link HudsonFilter} created for the given {@link ServletContext}. */ public static HudsonFilter get(ServletContext context) { return (HudsonFilter)context.getAttribute(HudsonFilter.class.getName()); } /** * Reset the proxies and filter for a change in {@link SecurityRealm}. */ public void reset(SecurityRealm securityRealm) throws ServletException { if (securityRealm != null) { SecurityRealm.SecurityComponents sc = securityRealm.getSecurityComponents(); AUTHENTICATION_MANAGER.setDelegate(sc.manager); USER_DETAILS_SERVICE_PROXY.setDelegate(sc.userDetails); REMEMBER_ME_SERVICES_PROXY.setDelegate(sc.rememberMe); // make sure this.filter is always a valid filter. Filter oldf = this.filter; Filter newf = securityRealm.createFilter(this.filterConfig); newf.init(this.filterConfig); this.filter = newf; if(oldf!=null) oldf.destroy(); } else { // no security related filter needed. AUTHENTICATION_MANAGER.setDelegate(null); USER_DETAILS_SERVICE_PROXY.setDelegate(null); REMEMBER_ME_SERVICES_PROXY.setDelegate(null); filter = null; } } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { LOGGER.entering(HudsonFilter.class.getName(), "doFilter"); // to deal with concurrency, we need to capture the object. Filter f = filter; if(f==null) { // Hudson is starting up. chain.doFilter(request,response); } else { f.doFilter(request,response,chain); } } public void destroy() { // the filter can be null if the filter is not initialized yet. if(filter != null) filter.destroy(); } private static final Logger LOGGER = Logger.getLogger(HudsonFilter.class.getName()); }
package org.fedorahosted.flies.webtrans.client.rpc; import java.util.ArrayList; import org.fedorahosted.flies.gwt.model.TransMemory; import org.fedorahosted.flies.gwt.rpc.GetTranslationMemory; import org.fedorahosted.flies.gwt.rpc.GetTranslationMemoryResult; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.rpc.AsyncCallback; public class DummyGetTranslationMemoryCommand implements Command { private final GetTranslationMemory action; private final AsyncCallback<GetTranslationMemoryResult> callback; public DummyGetTranslationMemoryCommand(GetTranslationMemory action, AsyncCallback<GetTranslationMemoryResult> callback) { this.action = action; this.callback = callback; } @Override public void execute() { String query = action.getQuery(); boolean fuzzy = action.getFuzzy(); ArrayList<TransMemory> matches = new ArrayList<TransMemory>(); matches.add(new TransMemory(fuzzy?"fuzzy1":"source1", "target1", "doc1", 100)); matches.add(new TransMemory(query, "target2", "doc1", 90)); matches.add(new TransMemory("source3", "target3", "doc2", 85)); matches.add(new TransMemory("<source4/>", "<target4/>", "doc3", 60)); callback.onSuccess(new GetTranslationMemoryResult(matches)); } }
package hudson.tasks; import hudson.FilePath; import hudson.Launcher; import hudson.Util; import hudson.model.Action; import hudson.model.Build; import hudson.model.BuildListener; import hudson.model.Descriptor; import hudson.model.DirectoryBrowserSupport; import hudson.model.Project; import hudson.model.ProminentProjectAction; import hudson.model.Result; import hudson.model.Actionable; import hudson.model.AbstractItem; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; /** * Saves Javadoc for the project and publish them. * * @author Kohsuke Kawaguchi */ public class JavadocArchiver extends Publisher { /** * Path to the Javadoc directory in the workspace. */ private final String javadocDir; public JavadocArchiver(String javadocDir) { this.javadocDir = javadocDir; } public String getJavadocDir() { return javadocDir; } /** * Gets the directory where the Javadoc is stored for the given project. */ private static File getJavadocDir(AbstractItem project) { return new File(project.getRootDir(),"javadoc"); } public boolean perform(Build build, Launcher launcher, BuildListener listener) throws InterruptedException { listener.getLogger().println("Publishing Javadoc"); FilePath javadoc = build.getParent().getWorkspace().child(javadocDir); FilePath target = new FilePath(getJavadocDir(build.getParent())); try { javadoc.copyRecursiveTo("**/*",target); } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace(listener.fatalError("Unable to copy Javadoc from "+javadoc+" to "+target)); build.setResult(Result.FAILURE); } return true; } public Action getProjectAction(Project project) { return new JavadocAction(project); } public Descriptor<Publisher> getDescriptor() { return DESCRIPTOR; } public static final Descriptor<Publisher> DESCRIPTOR = new Descriptor<Publisher>(JavadocArchiver.class) { public String getDisplayName() { return "Publish Javadoc"; } public Publisher newInstance(StaplerRequest req) { return new JavadocArchiver(req.getParameter("javadoc_dir")); } }; public static final class JavadocAction extends Actionable implements ProminentProjectAction { private final AbstractItem project; public JavadocAction(AbstractItem project) { this.project = project; } public String getUrlName() { return "javadoc"; } public String getDisplayName() { return "Javadoc"; } public String getIconFileName() { if(getJavadocDir(project).exists()) return "help.gif"; else // hide it since we don't have javadoc yet. return null; } public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { new DirectoryBrowserSupport(this).serveFile(req, rsp, new FilePath(getJavadocDir(project)), "help.gif", false); } } }
package org.eclipse.persistence.mappings; import java.util.*; import org.eclipse.persistence.descriptors.CMPPolicy; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.exceptions.*; import org.eclipse.persistence.expressions.*; import org.eclipse.persistence.indirection.ValueHolder; import org.eclipse.persistence.indirection.ValueHolderInterface; import org.eclipse.persistence.internal.descriptors.*; import org.eclipse.persistence.internal.helper.*; import org.eclipse.persistence.internal.identitymaps.CacheKey; import org.eclipse.persistence.internal.indirection.*; import org.eclipse.persistence.internal.sessions.*; import org.eclipse.persistence.queries.*; import org.eclipse.persistence.sessions.remote.*; import org.eclipse.persistence.sessions.CopyGroup; import org.eclipse.persistence.sessions.Project; /** * <p><b>Purpose</b>: Abstract class for 1:1, variable 1:1 and reference mappings */ public abstract class ObjectReferenceMapping extends ForeignReferenceMapping { /** Keeps track if any of the fields are foreign keys. */ protected boolean isForeignKeyRelationship; /** Keeps track of which fields are foreign keys on a per field basis (can have mixed foreign key relationships). */ protected Vector<DatabaseField> foreignKeyFields; protected ObjectReferenceMapping() { super(); this.setWeight(WEIGHT_TO_ONE); } /** * INTERNAL: * Used during building the backup shallow copy to copy the vector without re-registering the target objects. * For 1-1 or ref the reference is from the clone so it is already registered. */ @Override public Object buildBackupCloneForPartObject(Object attributeValue, Object clone, Object backup, UnitOfWorkImpl unitOfWork) { return attributeValue; } /** * INTERNAL: * Require for cloning, the part must be cloned. * Ignore the objects, use the attribute value. */ @Override public Object buildCloneForPartObject(Object attributeValue, Object original, CacheKey cacheKey, Object clone, AbstractSession cloningSession, boolean isExisting) { if (attributeValue == null) { return null; } if (cloningSession.isUnitOfWork()){ return buildUnitofWorkCloneForPartObject(attributeValue, original, clone, (UnitOfWorkImpl)cloningSession, isExisting); } // Not a unit Of Work clone so must have been a PROTECTED object if (this.referenceDescriptor.isProtectedIsolation()) { ClassDescriptor descriptor = this.referenceDescriptor; if (descriptor.hasInterfacePolicy()){ descriptor = cloningSession.getClassDescriptor(attributeValue.getClass()); } return cloningSession.createProtectedInstanceFromCachedData(attributeValue, descriptor); } return attributeValue; } /** * INTERNAL: * Require for cloning, the part must be cloned. * Ignore the objects, use the attribute value. */ public Object buildUnitofWorkCloneForPartObject(Object attributeValue, Object original, Object clone, UnitOfWorkImpl unitOfWork, boolean isExisting) { if (attributeValue == null) { return null; } // Optimize registration to knowledge of existence. Object registeredObject = null; if (isExisting) { registeredObject = unitOfWork.registerExistingObject(attributeValue); } else { // Not known whether existing or not. registeredObject = unitOfWork.registerObject(attributeValue); // if the mapping is privately owned, keep track of the privately owned reference in the UnitOfWork if (isCandidateForPrivateOwnedRemoval() && unitOfWork.shouldDiscoverNewObjects() && registeredObject != null && unitOfWork.isObjectNew(registeredObject)) { unitOfWork.addPrivateOwnedObject(this, registeredObject); } } return registeredObject; } /** * INTERNAL: * Copy of the attribute of the object. * This is NOT used for unit of work but for templatizing an object. */ @Override public void buildCopy(Object copy, Object original, CopyGroup group) { Object attributeValue = getRealAttributeValueFromObject(original, group.getSession()); if ((attributeValue != null) && (group.shouldCascadeAllParts() || (group.shouldCascadePrivateParts() && isPrivateOwned()) || group.shouldCascadeTree())) { attributeValue = group.getSession().copyInternal(attributeValue, group); } else if (attributeValue != null) { // Check for copy of part, i.e. back reference. Object copyValue = group.getCopies().get(attributeValue); if (copyValue != null) { attributeValue = copyValue; } } // if value holder is used, then the value holder shared with original substituted for a new ValueHolder. getIndirectionPolicy().reset(copy); setRealAttributeValueInObject(copy, attributeValue); } /** * INTERNAL: * In case Query By Example is used, this method generates an expression from a attribute value pair. Since * this is a ObjectReference mapping, a recursive call is made to the buildExpressionFromExample method of * ObjectBuilder. */ @Override public Expression buildExpression(Object queryObject, QueryByExamplePolicy policy, Expression expressionBuilder, Map processedObjects, AbstractSession session) { String attributeName = this.getAttributeName(); Object attributeValue = this.getRealAttributeValueFromObject(queryObject, session); if (!policy.shouldIncludeInQuery(queryObject.getClass(), attributeName, attributeValue)) { //the attribute name and value pair is not to be included in the query. return null; } if (attributeValue == null) { //even though it is null, it is to be always included in the query Expression expression = expressionBuilder.get(attributeName); return policy.completeExpressionForNull(expression); } ObjectBuilder objectBuilder = getReferenceDescriptor().getObjectBuilder(); return objectBuilder.buildExpressionFromExample(attributeValue, policy, expressionBuilder.get(attributeName), processedObjects, session); } /** * INTERNAL: * Return an ObjectReferenceChangeRecord describing the change, or null if no change. * Used to compute changes for deferred change tracking. */ @Override public ChangeRecord compareForChange(Object clone, Object backUp, ObjectChangeSet owner, AbstractSession session) { Object cloneAttribute = null; Object backUpAttribute = null; cloneAttribute = getAttributeValueFromObject(clone); if (!owner.isNew()) { backUpAttribute = getAttributeValueFromObject(backUp); if ((backUpAttribute == null) && (cloneAttribute == null)) { return null; } } if ((cloneAttribute != null) && (!this.indirectionPolicy.objectIsInstantiated(cloneAttribute))) { //the clone's valueholder was never triggered so there will be no change return null; } Object cloneAttributeValue = null; Object backUpAttributeValue = null; if (cloneAttribute != null) { cloneAttributeValue = getRealAttributeValueFromAttribute(cloneAttribute, clone, session); } if (backUpAttribute != null) { backUpAttributeValue = getRealAttributeValueFromAttribute(backUpAttribute, backUp, session); } if ((cloneAttributeValue == backUpAttributeValue) && (!owner.isNew())) {// if it is new record the value return null; } ObjectReferenceChangeRecord record = internalBuildChangeRecord(cloneAttributeValue, owner, session); if (!owner.isNew()) { record.setOldValue(backUpAttributeValue); } return record; } /** * INTERNAL: * Directly build a change record based on the newValue without comparison */ public ObjectReferenceChangeRecord internalBuildChangeRecord(Object newValue, ObjectChangeSet owner, AbstractSession session) { ObjectReferenceChangeRecord changeRecord = new ObjectReferenceChangeRecord(owner); changeRecord.setAttribute(getAttributeName()); changeRecord.setMapping(this); setNewValueInChangeRecord(newValue, changeRecord, owner, session); return changeRecord; } /** * INTERNAL: * Set the newValue in the change record */ public void setNewValueInChangeRecord(Object newValue, ObjectReferenceChangeRecord changeRecord, ObjectChangeSet owner, AbstractSession session) { if (newValue != null) { // Bug 2612571 - added more flexible manner of getting descriptor ObjectChangeSet newSet = getDescriptorForTarget(newValue, session).getObjectBuilder().createObjectChangeSet(newValue, (UnitOfWorkChangeSet)owner.getUOWChangeSet(), session); changeRecord.setNewValue(newSet); } else { changeRecord.setNewValue(null); } } /** * INTERNAL: * Compare the references of the two objects are the same, not the objects themselves. * Used for independent relationships. * This is used for testing and validation purposes. */ @Override protected boolean compareObjectsWithoutPrivateOwned(Object firstObject, Object secondObject, AbstractSession session) { Object firstReferencedObject = getRealAttributeValueFromObject(firstObject, session); Object secondReferencedObject = getRealAttributeValueFromObject(secondObject, session); if ((firstReferencedObject == null) && (secondReferencedObject == null)) { return true; } if ((firstReferencedObject == null) || (secondReferencedObject == null)) { return false; } Object firstKey = getReferenceDescriptor().getObjectBuilder().extractPrimaryKeyFromObject(firstReferencedObject, session); Object secondKey = getReferenceDescriptor().getObjectBuilder().extractPrimaryKeyFromObject(secondReferencedObject, session); if (firstKey == null) { if (secondKey == null) { return true; } return false; } return firstKey.equals(secondKey); } /** * INTERNAL: * Compare the references of the two objects are the same, and the objects themselves are the same. * Used for private relationships. * This is used for testing and validation purposes. */ @Override protected boolean compareObjectsWithPrivateOwned(Object firstObject, Object secondObject, AbstractSession session) { Object firstPrivateObject = getRealAttributeValueFromObject(firstObject, session); Object secondPrivateObject = getRealAttributeValueFromObject(secondObject, session); return session.compareObjects(firstPrivateObject, secondPrivateObject); } /** * INTERNAL: * We are not using a remote valueholder * so we need to replace the reference object(s) with * the corresponding object(s) from the remote session. * * ObjectReferenceMappings need to unwrap and wrap the * reference object. */ @Override public void fixRealObjectReferences(Object object, Map objectDescriptors, Map processedObjects, ObjectLevelReadQuery query, RemoteSession session) { //bug 4147755 getRealAttribute... / setReal... Object attributeValue = getRealAttributeValueFromObject(object, session); attributeValue = getReferenceDescriptor().getObjectBuilder().unwrapObject(attributeValue, session); ObjectLevelReadQuery tempQuery = query; if (!tempQuery.shouldMaintainCache()) { if ((!tempQuery.shouldCascadeParts()) || (tempQuery.shouldCascadePrivateParts() && (!isPrivateOwned()))) { tempQuery = null; } } Object remoteAttributeValue = session.getObjectCorrespondingTo(attributeValue, objectDescriptors, processedObjects, tempQuery); remoteAttributeValue = getReferenceDescriptor().getObjectBuilder().wrapObject(remoteAttributeValue, session); setRealAttributeValueInObject(object, remoteAttributeValue); } /** * INTERNAL: * Return a descriptor for the target of this mapping * @see org.eclipse.persistence.mappings.VariableOneToOneMapping * Bug 2612571 */ public ClassDescriptor getDescriptorForTarget(Object object, AbstractSession session) { return session.getDescriptor(object); } /** * INTERNAL: * Object reference must unwrap the reference object if required. */ @Override public Object getRealAttributeValueFromAttribute(Object attributeValue, Object object, AbstractSession session) { Object value = super.getRealAttributeValueFromAttribute(attributeValue, object, session); value = getReferenceDescriptor().getObjectBuilder().unwrapObject(value, session); return value; } /** * INTERNAL: * Related mapping should implement this method to return true. */ @Override public boolean isObjectReferenceMapping() { return true; } /** * INTERNAL: * Iterate on the attribute value. * The value holder has already been processed. */ @Override public void iterateOnRealAttributeValue(DescriptorIterator iterator, Object realAttributeValue) { // This may be wrapped as the caller in iterate on foreign reference does not unwrap as the type is generic. Object unwrappedAttributeValue = getReferenceDescriptor().getObjectBuilder().unwrapObject(realAttributeValue, iterator.getSession()); iterator.iterateReferenceObjectForMapping(unwrappedAttributeValue, this); } /** * INTERNAL: * Merge changes from the source to the target object. Which is the original from the parent UnitOfWork */ @Override public void mergeChangesIntoObject(Object target, ChangeRecord changeRecord, Object source, MergeManager mergeManager, AbstractSession targetSession) { if (this.descriptor.isProtectedIsolation()&& !this.isCacheable && !targetSession.isProtectedSession()){ setAttributeValueInObject(target, this.indirectionPolicy.buildIndirectObject(new ValueHolder(null))); return; } Object targetValueOfSource = null; // The target object must be completely merged before setting it otherwise // another thread can pick up the partial object. if (shouldMergeCascadeParts(mergeManager)) { ObjectChangeSet set = (ObjectChangeSet)((ObjectReferenceChangeRecord)changeRecord).getNewValue(); if (set != null) { if (mergeManager.shouldMergeChangesIntoDistributedCache()) { //Let's try and find it first. We may have merged it already. In which case merge //changes will stop the recursion targetValueOfSource = set.getTargetVersionOfSourceObject(mergeManager, targetSession, false); if ((targetValueOfSource == null) && (set.isNew() || set.isAggregate()) && set.containsChangesFromSynchronization()) { if (!mergeManager.isAlreadyMerged(set, targetSession)) { // if we haven't merged this object already then build a new object // otherwise leave it as null which will stop the recursion // CR 2855 // CR 3424 Need to build the right instance based on class type instead of refernceDescriptor Class objectClass = set.getClassType(mergeManager.getSession()); targetValueOfSource = mergeManager.getSession().getDescriptor(objectClass).getObjectBuilder().buildNewInstance(); //Store the changeset to prevent us from creating this new object again mergeManager.recordMerge(set, targetValueOfSource, targetSession); } else { //CR 4012 //we have all ready created the object, must be in a cyclic //merge on a new object so get it out of the already merged collection targetValueOfSource = mergeManager.getMergedObject(set, targetSession); } } else { // If We have not found it anywhere else load it from the database targetValueOfSource = set.getTargetVersionOfSourceObject(mergeManager, targetSession, true); } if (set.containsChangesFromSynchronization()) { mergeManager.mergeChanges(targetValueOfSource, set, targetSession); } //bug:3604593 - ensure reference not changed source is invalidated if target object not found if (targetValueOfSource == null) { mergeManager.getSession().getIdentityMapAccessorInstance().invalidateObject(target); return; } } else { mergeManager.mergeChanges(set.getUnitOfWorkClone(), set, targetSession); } } } if ((targetValueOfSource == null) && (((ObjectReferenceChangeRecord)changeRecord).getNewValue() != null)) { targetValueOfSource = ((ObjectChangeSet)((ObjectReferenceChangeRecord)changeRecord).getNewValue()).getTargetVersionOfSourceObject(mergeManager, targetSession); } // Register new object in nested units of work must not be registered into the parent, // so this records them in the merge to parent case. if (isPrivateOwned() && (source != null)) { mergeManager.registerRemovedNewObjectIfRequired(getRealAttributeValueFromObject(source, mergeManager.getSession())); } targetValueOfSource = getReferenceDescriptor().getObjectBuilder().wrapObject(targetValueOfSource, targetSession); // if value holder is used, then the value holder shared with original substituted for a new ValueHolder. getIndirectionPolicy().reset(target); setRealAttributeValueInObject(target, targetValueOfSource); } /** * INTERNAL: * Merge changes from the source to the target object. */ @Override public void mergeIntoObject(Object target, boolean isTargetUnInitialized, Object source, MergeManager mergeManager, AbstractSession targetSession) { if (this.descriptor.isProtectedIsolation()&& !this.isCacheable && !targetSession.isProtectedSession()){ setAttributeValueInObject(target, this.indirectionPolicy.buildIndirectObject(new ValueHolder(null))); return; } if (isTargetUnInitialized) { // This will happen if the target object was removed from the cache before the commit was attempted, // or for new objects. if (mergeManager.shouldMergeWorkingCopyIntoOriginal()) { if (!isAttributeValueInstantiated(source)) { setAttributeValueInObject(target, this.indirectionPolicy.getOriginalIndirectionObject(getAttributeValueFromObject(source), targetSession)); return; } else { // Must clear the old value holder to cause it to be reset. this.indirectionPolicy.reset(target); } } } if (!shouldMergeCascadeReference(mergeManager)) { // This is only going to happen on mergeClone, and we should not attempt to merge the reference return; } if (mergeManager.shouldRefreshRemoteObject() && usesIndirection()) { mergeRemoteValueHolder(target, source, mergeManager); return; } if (mergeManager.shouldMergeOriginalIntoWorkingCopy()) { if (!isAttributeValueInstantiated(target)) { // This will occur when the clone's value has not been instantiated yet and we do not need // the refresh that attribute return; } } else if (!isAttributeValueInstantiated(source)) { // I am merging from a clone into an original. No need to do merge if the attribute was never // modified return; } Object valueOfSource = getRealAttributeValueFromObject(source, mergeManager.getSession()); Object targetValueOfSource = null; // The target object must be completely merged before setting it otherwise // another thread can pick up the partial object. if (shouldMergeCascadeParts(mergeManager) && (valueOfSource != null)) { if ((mergeManager.getSession().isUnitOfWork()) && (((UnitOfWorkImpl)mergeManager.getSession()).getUnitOfWorkChangeSet() != null)) { // If it is a unit of work, we have to check if I have a change Set fot this object mergeManager.mergeChanges(mergeManager.getObjectToMerge(valueOfSource, referenceDescriptor, targetSession), (ObjectChangeSet)((UnitOfWorkChangeSet)((UnitOfWorkImpl)mergeManager.getSession()).getUnitOfWorkChangeSet()).getObjectChangeSetForClone(valueOfSource), targetSession); } else { mergeManager.mergeChanges(mergeManager.getObjectToMerge(valueOfSource, referenceDescriptor, targetSession), null, targetSession); } } if (valueOfSource != null) { // Need to do this after merge so that an object exists in the database targetValueOfSource = mergeManager.getTargetVersionOfSourceObject(valueOfSource, referenceDescriptor, targetSession); } // If merge into the unit of work, must only merge and raise the event is the value changed. if ((mergeManager.shouldMergeCloneIntoWorkingCopy() || mergeManager.shouldMergeCloneWithReferencesIntoWorkingCopy()) && this.descriptor.getObjectChangePolicy().isObjectChangeTrackingPolicy()) { // Object level or attribute level so lets see if we need to raise the event? Object valueOfTarget = getRealAttributeValueFromObject(target, mergeManager.getSession()); if (valueOfTarget != targetValueOfSource) { //equality comparison cause both are uow clones this.descriptor.getObjectChangePolicy().raiseInternalPropertyChangeEvent(target, getAttributeName(), valueOfTarget, targetValueOfSource); } else { // No change. return; } } targetValueOfSource = this.referenceDescriptor.getObjectBuilder().wrapObject(targetValueOfSource, mergeManager.getSession()); setRealAttributeValueInObject(target, targetValueOfSource); } /** * INTERNAL: * Return all the fields populated by this mapping, these are foreign keys only. */ @Override protected Vector<DatabaseField> collectFields() { return getForeignKeyFields(); } /** * INTERNAL: * Returns the foreign key names associated with the mapping. * These are the fields that will be populated by the 1-1 mapping when writing. */ public Vector<DatabaseField> getForeignKeyFields() { return foreignKeyFields; } /** * INTERNAL: * Set the foreign key fields associated with the mapping. * These are the fields that will be populated by the 1-1 mapping when writing. */ protected void setForeignKeyFields(Vector<DatabaseField> foreignKeyFields) { this.foreignKeyFields = foreignKeyFields; if (!foreignKeyFields.isEmpty()) { setIsForeignKeyRelationship(true); } } /** * INTERNAL: * Return if the 1-1 mapping has a foreign key dependency to its target. * This is true if any of the foreign key fields are true foreign keys, * i.e. populated on write from the targets primary key. */ public boolean isForeignKeyRelationship() { return isForeignKeyRelationship; } /** * INTERNAL: * Set if the 1-1 mapping has a foreign key dependency to its target. * This is true if any of the foreign key fields are true foreign keys, * i.e. populated on write from the targets primary key. */ public void setIsForeignKeyRelationship(boolean isForeignKeyRelationship) { this.isForeignKeyRelationship = isForeignKeyRelationship; } /** * INTERNAL: * Insert privately owned parts */ @Override public void preInsert(WriteObjectQuery query) throws DatabaseException, OptimisticLockException { if (isForeignKeyRelationship()) { insert(query); } } /** * INTERNAL: * Reads the private owned object. */ protected Object readPrivateOwnedForObject(ObjectLevelModifyQuery modifyQuery) throws DatabaseException { if (modifyQuery.getSession().isUnitOfWork()) { if (modifyQuery.getObjectChangeSet() != null) { ObjectReferenceChangeRecord record = (ObjectReferenceChangeRecord) modifyQuery.getObjectChangeSet().getChangesForAttributeNamed(getAttributeName()); if (record != null) { return record.getOldValue(); } } else { // Old commit. return getRealAttributeValueFromObject(modifyQuery.getBackupClone(), modifyQuery.getSession()); } } return null; } /** * INTERNAL: * Update privately owned parts */ @Override public void preUpdate(WriteObjectQuery query) throws DatabaseException, OptimisticLockException { if (!isAttributeValueInstantiated(query.getObject())) { return; } if (isPrivateOwned()) { Object objectInDatabase = readPrivateOwnedForObject(query); if (objectInDatabase != null) { query.setProperty(this, objectInDatabase); } } if (!isForeignKeyRelationship()) { return; } update(query); } /** * INTERNAL: * Overridden by mappings that require additional processing of the change record after the record has been calculated. */ @Override public void postCalculateChanges(org.eclipse.persistence.sessions.changesets.ChangeRecord changeRecord, UnitOfWorkImpl uow) { // no need for private owned check. This code is only registered for private owned mappings. // targets are added to and/or removed to/from the source. Object oldValue = ((ObjectReferenceChangeRecord)changeRecord).getOldValue(); if (oldValue != null) { uow.addDeletedPrivateOwnedObjects(this, oldValue); } } /** * INTERNAL: * Overridden by mappings that require additional processing of the change record after the record has been calculated. */ @Override public void recordPrivateOwnedRemovals(Object object, UnitOfWorkImpl uow) { Object target = getRealAttributeValueFromObject(object, uow); if (target != null){ this.referenceDescriptor.getObjectBuilder().recordPrivateOwnedRemovals(target, uow, false); } } /** * INTERNAL: * Delete privately owned parts */ @Override public void postDelete(DeleteObjectQuery query) throws DatabaseException, OptimisticLockException { // Deletion takes place only if it has privately owned parts and mapping is not read only. if (!shouldObjectModifyCascadeToParts(query)) { return; } Object object = query.getProperty(this); // The object is stored in the query by preDeleteForObjectUsing(...). if (isForeignKeyRelationship()) { if (object != null) { query.removeProperty(this); AbstractSession session = query.getSession(); //if the query is being passed from an aggregate collection descriptor then // The delete will have been cascaded at update time. This will cause sub objects // to be ignored, and real only classes to throw exceptions. // If it is an aggregate Collection then delay deletes until they should be deleted //CR 2811 if (query.isCascadeOfAggregateDelete()) { session.getCommitManager().addObjectToDelete(object); } else { // PERF: Avoid query execution if already deleted. if (session.getCommitManager().isCommitCompletedOrInPost(object)) { return; } if (this.isCascadeOnDeleteSetOnDatabase && !hasRelationTableMechanism() && session.isUnitOfWork()) { ((UnitOfWorkImpl)session).getCascadeDeleteObjects().add(object); } DeleteObjectQuery deleteQuery = new DeleteObjectQuery(); deleteQuery.setIsExecutionClone(true); deleteQuery.setObject(object); deleteQuery.setCascadePolicy(query.getCascadePolicy()); session.executeQuery(deleteQuery); } } } } /** * INTERNAL: * Insert privately owned parts */ @Override public void postInsert(WriteObjectQuery query) throws DatabaseException, OptimisticLockException { if (!isForeignKeyRelationship()) { insert(query); } } /** * INTERNAL: * Update privately owned parts */ @Override public void postUpdate(WriteObjectQuery query) throws DatabaseException, OptimisticLockException { if (!isAttributeValueInstantiated(query.getObject())) { return; } if (!isForeignKeyRelationship()) { update(query); } // If a private owned reference was changed the old value will be set on the query as a property. Object objectInDatabase = query.getProperty(this); if (objectInDatabase != null) { query.removeProperty(this); } else { return; } // If there is no change (old commit), it must be determined if the value changed. if (query.getObjectChangeSet() == null) { Object objectInMemory = getRealAttributeValueFromObject(query.getObject(), query.getSession()); // delete the object in the database if it is no more a referenced object. if (objectInDatabase != objectInMemory) { Object keyForObjectInDatabase = getPrimaryKeyForObject(objectInDatabase, query.getSession()); Object keyForObjectInMemory = null; if (objectInMemory != null) { keyForObjectInMemory = getPrimaryKeyForObject(objectInMemory, query.getSession()); } if ((keyForObjectInMemory != null) && keyForObjectInDatabase.equals(keyForObjectInMemory)) { return; } } else { return; } } if (!query.shouldCascadeOnlyDependentParts()) { query.getSession().deleteObject(objectInDatabase); } } /** * INTERNAL: * Delete privately owned parts */ @Override public void preDelete(DeleteObjectQuery query) throws DatabaseException, OptimisticLockException { // Deletion takes place according the the cascading policy if (!shouldObjectModifyCascadeToParts(query)) { return; } AbstractSession session = query.getSession(); // Get the privately owned parts. Object objectInMemory = getRealAttributeValueFromObject(query.getObject(), session); Object objectFromDatabase = null; // Because the value in memory may have been changed we check the previous value or database value. objectFromDatabase = readPrivateOwnedForObject(query); // If the value was changed, both values must be deleted (uow will have inserted the new one). if ((objectFromDatabase != null) && (objectFromDatabase != objectInMemory)) { // Also check pk as may not be maintaining identity. Object keyForObjectInMemory = null; Object keyForObjectInDatabase = getPrimaryKeyForObject(objectFromDatabase, session); if (objectInMemory != null) { keyForObjectInMemory = getPrimaryKeyForObject(objectInMemory, session); } if ((keyForObjectInMemory == null) || !keyForObjectInDatabase.equals(keyForObjectInMemory)) { if (objectFromDatabase != null) { if (this.isCascadeOnDeleteSetOnDatabase && !hasRelationTableMechanism() && session.isUnitOfWork()) { ((UnitOfWorkImpl)session).getCascadeDeleteObjects().add(objectFromDatabase); } DeleteObjectQuery deleteQuery = new DeleteObjectQuery(); deleteQuery.setIsExecutionClone(true); deleteQuery.setObject(objectFromDatabase); deleteQuery.setCascadePolicy(query.getCascadePolicy()); session.executeQuery(deleteQuery); } } } if (!isForeignKeyRelationship()) { if (objectInMemory != null) { if (this.isCascadeOnDeleteSetOnDatabase && !hasRelationTableMechanism() && session.isUnitOfWork()) { ((UnitOfWorkImpl)session).getCascadeDeleteObjects().add(objectInMemory); } // PERF: Avoid query execution if already deleted. if (session.getCommitManager().isCommitCompletedOrInPost(objectInMemory)) { return; } DeleteObjectQuery deleteQuery = new DeleteObjectQuery(); deleteQuery.setIsExecutionClone(true); deleteQuery.setObject(objectInMemory); deleteQuery.setCascadePolicy(query.getCascadePolicy()); session.executeQuery(deleteQuery); } } else { // The actual deletion of part takes place in postDeleteForObjectUsing(...). if (objectInMemory != null) { query.setProperty(this, objectInMemory); } } } /** * INTERNAL: * Record deletion dependencies for foreign key constraints. * This is used during deletion to resolve deletion cycles. */ @Override public void earlyPreDelete(DeleteObjectQuery query) { Object object = query.getObject(); AbstractSession session = query.getSession(); // Avoid instantiating objects. Object attributeValue = getAttributeValueFromObject(object); Object targetObject = null; if (!this.indirectionPolicy.objectIsInstantiated(attributeValue) && !this.indirectionPolicy.objectIsEasilyInstantiated(attributeValue)) { AbstractRecord referenceRow = this.indirectionPolicy.extractReferenceRow(attributeValue); targetObject = this.selectionQuery.checkEarlyReturn(session, referenceRow); } else { targetObject = getRealAttributeValueFromAttribute(attributeValue, object, session); } UnitOfWorkImpl unitOfWork = (UnitOfWorkImpl)session; if ((targetObject != null) && unitOfWork.getDeletedObjects().containsKey(targetObject)) { unitOfWork.addDeletionDependency(targetObject, object); } } /** * INTERNAL: * Cascade registerNew for Create through mappings that require the cascade */ @Override public void cascadePerformRemoveIfRequired(Object object, UnitOfWorkImpl uow, Map visitedObjects){ cascadePerformRemoveIfRequired(object, uow, visitedObjects, true); } /** * INTERNAL: * Cascade remove through mappings that require the cascade. * @param object is either the source object, or attribute value if getAttributeValueFromObject is true. */ public void cascadePerformRemoveIfRequired(Object object, UnitOfWorkImpl uow, Map visitedObjects, boolean getAttributeValueFromObject) { if (!this.cascadeRemove) { return; } Object attributeValue = null; if (getAttributeValueFromObject) { attributeValue = getAttributeValueFromObject(object); } else { attributeValue = object; } if (attributeValue != null) { if (getAttributeValueFromObject) { attributeValue = this.indirectionPolicy.getRealAttributeValueFromObject(object, attributeValue); } if (attributeValue != null && (! visitedObjects.containsKey(attributeValue)) ){ visitedObjects.put(attributeValue, attributeValue); if (this.isCascadeOnDeleteSetOnDatabase && !hasRelationTableMechanism()) { uow.getCascadeDeleteObjects().add(attributeValue); } uow.performRemove(attributeValue, visitedObjects); } } } /** * INTERNAL: * Cascade removal of orphaned private owned objects from the UnitOfWorkChangeSet */ @Override public void cascadePerformRemovePrivateOwnedObjectFromChangeSetIfRequired(Object object, UnitOfWorkImpl uow, Map visitedObjects) { // if the object is not instantiated, do not instantiate or cascade Object attributeValue = getAttributeValueFromObject(object); if (attributeValue != null && this.indirectionPolicy.objectIsInstantiated(attributeValue)) { Object realValue = getRealAttributeValueFromObject(object, uow); if (!visitedObjects.containsKey(realValue)){ visitedObjects.put(realValue, realValue); // remove private owned object from UnitOfWork ChangeSet uow.performRemovePrivateOwnedObjectFromChangeSet(realValue, visitedObjects); } } } /** * INTERNAL: * This method is used to store the FK fields that can be cached that correspond to noncacheable mappings * the FK field values will be used to re-issue the query when cloning the shared cache entity */ @Override public void collectQueryParameters(Set<DatabaseField> cacheFields){ for (DatabaseField field : foreignKeyFields) { cacheFields.add(field); } } /** * INTERNAL: * Cascade discover and persist new objects during commit. */ @Override public void cascadeDiscoverAndPersistUnregisteredNewObjects(Object object, Map newObjects, Map unregisteredExistingObjects, Map visitedObjects, UnitOfWorkImpl uow) { cascadeDiscoverAndPersistUnregisteredNewObjects(object, newObjects, unregisteredExistingObjects, visitedObjects, uow, true); } /** * INTERNAL: * Cascade discover and persist new objects during commit. */ public void cascadeDiscoverAndPersistUnregisteredNewObjects(Object object, Map newObjects, Map unregisteredExistingObjects, Map visitedObjects, UnitOfWorkImpl uow, boolean getAttributeValueFromObject) { Object attributeValue = null; if (getAttributeValueFromObject){ attributeValue = getAttributeValueFromObject(object); } else { attributeValue = object; } if (attributeValue != null && this.indirectionPolicy.objectIsInstantiated(attributeValue)) { if (getAttributeValueFromObject){ attributeValue = this.indirectionPolicy.getRealAttributeValueFromObject(object, attributeValue); } // remove private owned object from uow list if (isCandidateForPrivateOwnedRemoval()) { uow.removePrivateOwnedObject(this, attributeValue); } uow.discoverAndPersistUnregisteredNewObjects(attributeValue, isCascadePersist(), newObjects, unregisteredExistingObjects, visitedObjects); } } /** * INTERNAL: * Cascade registerNew for Create through mappings that require the cascade */ @Override public void cascadeRegisterNewIfRequired(Object object, UnitOfWorkImpl uow, Map visitedObjects){ cascadeRegisterNewIfRequired(object, uow, visitedObjects, true); } /** * INTERNAL: * Cascade registerNew for Create through mappings that require the cascade * @param object is either the source object, or attribute value if getAttributeValueFromObject is true. */ public void cascadeRegisterNewIfRequired(Object object, UnitOfWorkImpl uow, Map visitedObjects, boolean getAttributeValueFromObject) { if (!isCascadePersist()) { return; } Object attributeValue = null; if (getAttributeValueFromObject) { attributeValue = getAttributeValueFromObject(object); } else { attributeValue = object; } if ((attributeValue != null) && this.indirectionPolicy.objectIsInstantiated(attributeValue)){ if (getAttributeValueFromObject){ attributeValue = this.indirectionPolicy.getRealAttributeValueFromObject(object, attributeValue); } uow.registerNewObjectForPersist(attributeValue, visitedObjects); // add private owned object to uow list if mapping is a candidate and uow should discover new objects and the source object is new. if (isCandidateForPrivateOwnedRemoval() && uow.shouldDiscoverNewObjects() && attributeValue != null && uow.isObjectNew(object)) { uow.addPrivateOwnedObject(this, attributeValue); } } } /** * INTERNAL: */ protected Object getPrimaryKeyForObject(Object object, AbstractSession session) { return getReferenceDescriptor().getObjectBuilder().extractPrimaryKeyFromObject(object, session); } /** * INTERNAL: * The returns if the mapping has any constraint dependencies, such as foreign keys and join tables. */ @Override public boolean hasConstraintDependency() { return isForeignKeyRelationship(); } /** * INTERNAL: * Builder the unit of work value holder. * @param buildDirectlyFromRow indicates that we are building the clone directly * from a row as opposed to building the original from the row, putting it in * the shared cache, and then cloning the original. */ @Override public DatabaseValueHolder createCloneValueHolder(ValueHolderInterface attributeValue, Object original, Object clone, AbstractRecord row, AbstractSession cloningSession, boolean buildDirectlyFromRow) { DatabaseValueHolder valueHolder = null; if ((row == null) && (isPrimaryKeyMapping())) { // The row must be built if a primary key mapping for remote case. AbstractRecord rowFromTargetObject = extractPrimaryKeyRowForSourceObject(original, cloningSession); valueHolder = cloningSession.createCloneQueryValueHolder(attributeValue, clone, rowFromTargetObject, this); } else { valueHolder = cloningSession.createCloneQueryValueHolder(attributeValue, clone, row, this); } // In case of joined attributes it so happens that the attributeValue // contains a registered clone, as valueFromRow was called with a // UnitOfWork. So switch the values. // Note that this UOW valueholder starts off as instantiated but that // is fine, for the reality is that it is. if (buildDirectlyFromRow && attributeValue.isInstantiated()) { Object cloneAttributeValue = attributeValue.getValue(); valueHolder.privilegedSetValue(cloneAttributeValue); valueHolder.setInstantiated(); // PERF: Do not modify the original value-holder, it is never used. } return valueHolder; } /** * INTERNAL: * Extract the reference pk for rvh usage in remote model. */ public AbstractRecord extractPrimaryKeyRowForSourceObject(Object domainObject, AbstractSession session) { AbstractRecord databaseRow = getDescriptor().getObjectBuilder().createRecord(session); writeFromObjectIntoRow(domainObject, databaseRow, session, WriteType.UNDEFINED); return databaseRow; } /** * INTERNAL: * Extract the reference pk for rvh usage in remote model. */ public Object extractPrimaryKeysForReferenceObject(Object domainObject, AbstractSession session) { return this.indirectionPolicy.extractPrimaryKeyForReferenceObject(getAttributeValueFromObject(domainObject), session); } /** * INTERNAL: * Return the primary key for the reference object (i.e. the object * object referenced by domainObject and specified by mapping). * This key will be used by a RemoteValueHolder. */ public Object extractPrimaryKeysForReferenceObjectFromRow(AbstractRecord row) { return null; } /** * INTERNAL: * Extract the reference pk for rvh usage in remote model. */ public Object extractPrimaryKeysFromRealReferenceObject(Object object, AbstractSession session) { if (object == null) { return null; } else { Object implementation = getReferenceDescriptor().getObjectBuilder().unwrapObject(object, session); return getReferenceDescriptor().getObjectBuilder().extractPrimaryKeyFromObject(implementation, session); } } /** * INTERNAL: * Initialize the state of mapping. */ @Override public void preInitialize(AbstractSession session) throws DescriptorException { super.preInitialize(session); //Bug#4251902 Make Proxy Indirection writable and readable to deployment xml. If ProxyIndirectionPolicy does not //have any targetInterfaces, build a new set. if ((this.indirectionPolicy instanceof ProxyIndirectionPolicy) && !((ProxyIndirectionPolicy)this.indirectionPolicy).hasTargetInterfaces()) { useProxyIndirection(); } } /** * INTERNAL: * Insert privately owned parts */ protected void insert(WriteObjectQuery query) throws DatabaseException, OptimisticLockException { // Checks if privately owned parts should be inserted or not. if (!shouldObjectModifyCascadeToParts(query)) { return; } // Get the privately owned parts Object object = getRealAttributeValueFromObject(query.getObject(), query.getSession()); if (object == null) { return; } AbstractSession session = query.getSession(); // PERF: Avoid query execution if already written. if (session.getCommitManager().isCommitCompletedOrInPost(object)) { return; } ObjectChangeSet changeSet = null; // Get changeSet for referenced object. Change record may not exist for new objects, so always lookup. if (session.isUnitOfWork() && (((UnitOfWorkImpl)session).getUnitOfWorkChangeSet() != null)) { UnitOfWorkChangeSet uowChangeSet = (UnitOfWorkChangeSet)((UnitOfWorkImpl)session).getUnitOfWorkChangeSet(); changeSet = (ObjectChangeSet)uowChangeSet.getObjectChangeSetForClone(object); // PERF: If the changeSet is null it must be existing, if it is not new, then cascading is not required. if (changeSet == null || !changeSet.isNew()) { return; } } WriteObjectQuery writeQuery = null; // If private owned, the dependent objects should also be new. // However a bug was logged was put in to allow dependent objects to be existing in a unit of work, // so this allows existing dependent objects in the unit of work. if (this.isPrivateOwned && ((changeSet == null) || (changeSet.isNew()))) { // no identity check needed for private owned writeQuery = new InsertObjectQuery(); } else { writeQuery = new WriteObjectQuery(); } writeQuery.setIsExecutionClone(true); writeQuery.setObject(object); writeQuery.setObjectChangeSet(changeSet); writeQuery.setCascadePolicy(query.getCascadePolicy()); session.executeQuery(writeQuery); } /** * INTERNAL: * Update the private owned part. */ protected void update(WriteObjectQuery query) throws DatabaseException, OptimisticLockException { if (!shouldObjectModifyCascadeToParts(query)) { return; } Object sourceObject = query.getObject(); Object attributeValue = getAttributeValueFromObject(sourceObject); // If objects are not instantiated that means they are not changed. if (!this.indirectionPolicy.objectIsInstantiated(attributeValue)) { return; } // Get the privately owned parts in the memory AbstractSession session = query.getSession(); Object object = getRealAttributeValueFromAttribute(attributeValue, sourceObject, session); if (object != null) { ObjectChangeSet changeSet = query.getObjectChangeSet(); if (changeSet != null) { ObjectReferenceChangeRecord changeRecord = (ObjectReferenceChangeRecord)query.getObjectChangeSet().getChangesForAttributeNamed(getAttributeName()); if (changeRecord != null) { changeSet = (ObjectChangeSet)changeRecord.getNewValue(); // PERF: If it is not new, then cascading is not required. if (!changeSet.isNew()) { return; } } else { // no changeRecord no change to reference. return; } } else { UnitOfWorkChangeSet uowChangeSet = null; // Get changeSet for referenced object. if (session.isUnitOfWork() && (((UnitOfWorkImpl)session).getUnitOfWorkChangeSet() != null)) { uowChangeSet = (UnitOfWorkChangeSet)((UnitOfWorkImpl)session).getUnitOfWorkChangeSet(); changeSet = (ObjectChangeSet)uowChangeSet.getObjectChangeSetForClone(object); // PERF: If the changeSet is null it must be existing, if it is not new, then cascading is not required. if (changeSet == null || !changeSet.isNew()) { return; } } } // PERF: Only write dependent object if they are new. if ((!query.shouldCascadeOnlyDependentParts()) || (changeSet == null) || changeSet.isNew()) { // PERF: Avoid query execution if already written. if (session.getCommitManager().isCommitCompletedOrInPost(object)) { return; } WriteObjectQuery writeQuery = new WriteObjectQuery(); writeQuery.setIsExecutionClone(true); writeQuery.setObject(object); writeQuery.setObjectChangeSet(changeSet); writeQuery.setCascadePolicy(query.getCascadePolicy()); session.executeQuery(writeQuery); } } } /** * PUBLIC: * Indicates whether the mapping has RelationTableMechanism. */ public boolean hasRelationTableMechanism() { return false; } /** * PUBLIC: * Set this mapping to use Proxy Indirection. * * Proxy Indirection uses the <CODE>Proxy</CODE> and <CODE>InvocationHandler</CODE> features * of JDK 1.3 to provide "transparent indirection" for 1:1 relationships. In order to use Proxy * Indirection:<P> * * <UL> * <LI>The target class must implement at least one public interface * <LI>The attribute on the source class must be typed as that public interface * <LI>get() and set() methods for the attribute must use the interface * </UL> * * With this policy, proxy objects are returned during object creation. When a message other than * <CODE>toString</CODE> is called on the proxy the real object data is retrieved from the database. * * By default, use the target class' full list of interfaces for the proxy. * */ public void useProxyIndirection() { Class[] targetInterfaces = getReferenceClass().getInterfaces(); if (!getReferenceClass().isInterface() && getReferenceClass().getSuperclass() == null) { setIndirectionPolicy(new ProxyIndirectionPolicy(targetInterfaces)); } else { HashSet targetInterfacesCol = new HashSet(); //Bug#4432781 Include all the interfaces and the super interfaces of the target class if (getReferenceClass().getSuperclass() != null) { buildTargetInterfaces(getReferenceClass(), targetInterfacesCol); } //Bug#4251902 Make Proxy Indirection writable and readable to deployment xml. If //ReferenceClass is an interface, it needs to be included in the array. if (getReferenceClass().isInterface()) { targetInterfacesCol.add(getReferenceClass()); } targetInterfaces = (Class[])targetInterfacesCol.toArray(targetInterfaces); setIndirectionPolicy(new ProxyIndirectionPolicy(targetInterfaces)); } } /** * INTERNAL: This method will access the target relationship and create a * list of PKs of the target entities. This method is used in combination * with the CachedValueHolder to store references to PK's to be loaded from * a cache instead of a query. * @see ContainerPolicy.buildReferencesPKList() * @see MappedKeyMapContainerPolicy() */ @Override public Object[] buildReferencesPKList(Object entity, Object attribute, AbstractSession session) { ClassDescriptor referenceDescriptor = getReferenceDescriptor(); Object target = this.indirectionPolicy.getRealAttributeValueFromObject(entity, attribute); if (target != null){ Object[] result = new Object[1]; result[0] = referenceDescriptor.getObjectBuilder().extractPrimaryKeyFromObject(target, session); return result; } return new Object[]{}; } /** * INTERNAL: * Build a list of all the interfaces and super interfaces for a given class. */ public Collection buildTargetInterfaces(Class aClass, Collection targetInterfacesCol) { Class[] targetInterfaces = aClass.getInterfaces(); for (int index = 0; index < targetInterfaces.length; index++) { targetInterfacesCol.add(targetInterfaces[index]); } if (aClass.getSuperclass() == null) { return targetInterfacesCol; } else { return buildTargetInterfaces(aClass.getSuperclass(), targetInterfacesCol); } } /** * PUBLIC: * Set this mapping to use Proxy Indirection. * * Proxy Indirection uses the <CODE>Proxy</CODE> and <CODE>InvocationHandler</CODE> features * of JDK 1.3 to provide "transparent indirection" for 1:1 relationships. In order to use Proxy * Indirection:<P> * * <UL> * <LI>The target class must implement at least one public interface * <LI>The attribute on the source class must be typed as that public interface * <LI>get() and set() methods for the attribute must use the interface * </UL> * * With this policy, proxy objects are returned during object creation. When a message other than * <CODE>toString</CODE> is called on the proxy the real object data is retrieved from the database. * * @param proxyInterfaces The interfaces that the target class implements. The attribute must be typed * as one of these interfaces. */ public void useProxyIndirection(Class[] targetInterfaces) { setIndirectionPolicy(new ProxyIndirectionPolicy(targetInterfaces)); } /** * PUBLIC: * Set this mapping to use Proxy Indirection. * * Proxy Indirection uses the <CODE>Proxy</CODE> and <CODE>InvocationHandler</CODE> features * of JDK 1.3 to provide "transparent indirection" for 1:1 relationships. In order to use Proxy * Indirection:<P> * * <UL> * <LI>The target class must implement at least one public interface * <LI>The attribute on the source class must be typed as that public interface * <LI>get() and set() methods for the attribute must use the interface * </UL> * * With this policy, proxy objects are returned during object creation. When a message other than * <CODE>toString</CODE> is called on the proxy the real object data is retrieved from the database. * * @param proxyInterface The interface that the target class implements. The attribute must be typed * as this interface. */ public void useProxyIndirection(Class targetInterface) { Class[] targetInterfaces = new Class[] { targetInterface }; setIndirectionPolicy(new ProxyIndirectionPolicy(targetInterfaces)); } /** * INTERNAL: * This method is used to load a relationship from a list of PKs. * This list may be available if the relationship has been cached. */ @Override public Object valueFromPKList(Object[] pks, AbstractSession session) { if (pks[0] == null) return null; ReadObjectQuery query = new ReadObjectQuery(); query.setReferenceClass(getReferenceClass()); query.setSelectionId(pks[0]); query.setIsExecutionClone(true); query.setSession(session); return session.executeQuery(query); } /** * INTERNAL: * To verify if the specified object is deleted or not. */ @Override public boolean verifyDelete(Object object, AbstractSession session) throws DatabaseException { if (isPrivateOwned() || isCascadeRemove()) { Object attributeValue = getRealAttributeValueFromObject(object, session); if (attributeValue != null) { return session.verifyDelete(attributeValue); } } return true; } /** * INTERNAL: * Get a value from the object and set that in the respective field of the row. * But before that check if the reference object is instantiated or not. */ @Override public void writeFromObjectIntoRowForUpdate(WriteObjectQuery query, AbstractRecord databaseRow) { Object object = query.getObject(); AbstractSession session = query.getSession(); if (!isAttributeValueInstantiated(object)) { return; } if (session.isUnitOfWork()) { if (compareObjectsWithoutPrivateOwned(query.getBackupClone(), object, session)) { return; } } writeFromObjectIntoRow(object, databaseRow, session, WriteType.UPDATE); } /** * INTERNAL: * Get a value from the object and set that in the respective field of the row. */ @Override public void writeFromObjectIntoRowForWhereClause(ObjectLevelModifyQuery query, AbstractRecord databaseRow) { if (isReadOnly()) { return; } if (query.isDeleteObjectQuery()) { writeFromObjectIntoRow(query.getObject(), databaseRow, query.getSession(), WriteType.UNDEFINED); } else { // If the original was never instantiated the backup clone has a ValueHolder of null // so for this case we must extract from the original object. if (isAttributeValueInstantiated(query.getObject())) { writeFromObjectIntoRow(query.getBackupClone(), databaseRow, query.getSession(), WriteType.UNDEFINED); } else { writeFromObjectIntoRow(query.getObject(), databaseRow, query.getSession(), WriteType.UNDEFINED); } } } /** * INTERNAL: * Return if this mapping supports change tracking. */ @Override public boolean isChangeTrackingSupported(Project project) { return true; } /** * INTERNAL: * Either create a new change record or update the change record with the new value. * This is used by attribute change tracking. */ @Override public void updateChangeRecord(Object clone, Object newValue, Object oldValue, ObjectChangeSet objectChangeSet, UnitOfWorkImpl uow) { // Must ensure values are unwrapped. Object unwrappedNewValue = newValue; Object unwrappedOldValue = oldValue; if (newValue != null) { unwrappedNewValue = getReferenceDescriptor().getObjectBuilder().unwrapObject(newValue, uow); } if (oldValue != null) { unwrappedOldValue = getReferenceDescriptor().getObjectBuilder().unwrapObject(oldValue, uow); } ObjectReferenceChangeRecord changeRecord = (ObjectReferenceChangeRecord)objectChangeSet.getChangesForAttributeNamed(this.getAttributeName()); if (changeRecord == null) { changeRecord = internalBuildChangeRecord(unwrappedNewValue, objectChangeSet, uow); changeRecord.setOldValue(unwrappedOldValue); objectChangeSet.addChange(changeRecord); } else { setNewValueInChangeRecord(unwrappedNewValue, changeRecord, objectChangeSet, uow); } } /** * INTERNAL: * Directly build a change record without comparison */ @Override public ChangeRecord buildChangeRecord(Object clone, ObjectChangeSet owner, AbstractSession session) { return internalBuildChangeRecord(getRealAttributeValueFromObject(clone, session), owner, session); } }
package org.bouncycastle.util; import java.math.BigInteger; /** * General array utilities. */ public final class Arrays { private Arrays() { // static class, hide constructor } public static boolean areEqual( boolean[] a, boolean[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } public static boolean areEqual( char[] a, char[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } public static boolean areEqual( byte[] a, byte[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } /** * A constant time equals comparison - does not terminate early if * test will fail. * * @param a first array * @param b second array * @return true if arrays equal, false otherwise. */ public static boolean constantTimeAreEqual( byte[] a, byte[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } int nonEqual = 0; for (int i = 0; i != a.length; i++) { nonEqual |= (a[i] ^ b[i]); } return nonEqual == 0; } public static boolean areEqual( int[] a, int[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } public static boolean areEqual( long[] a, long[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } public static boolean areEqual(Object[] a, Object[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { Object objA = a[i], objB = b[i]; if (objA == null) { if (objB != null) { return false; } } else if (!objA.equals(objB)) { return false; } } return true; } public static void fill( byte[] array, byte value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } public static void fill( char[] array, char value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } public static void fill( long[] array, long value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } public static void fill( short[] array, short value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } public static void fill( int[] array, int value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } public static int hashCode(byte[] data) { if (data == null) { return 0; } int i = data.length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[i]; } return hc; } public static int hashCode(char[] data) { if (data == null) { return 0; } int i = data.length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[i]; } return hc; } public static int hashCode(int[][] ints) { int hc = 0; for (int i = 0; i != ints.length; i++) { hc = hc * 257 + hashCode(ints[i]); } return hc; } public static int hashCode(int[] data) { if (data == null) { return 0; } int i = data.length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[i]; } return hc; } public static int hashCode(short[][][] shorts) { int hc = 0; for (int i = 0; i != shorts.length; i++) { hc = hc * 257 + hashCode(shorts[i]); } return hc; } public static int hashCode(short[][] shorts) { int hc = 0; for (int i = 0; i != shorts.length; i++) { hc = hc * 257 + hashCode(shorts[i]); } return hc; } public static int hashCode(short[] data) { if (data == null) { return 0; } int i = data.length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= (data[i] & 0xff); } return hc; } public static int hashCode(BigInteger[] data) { if (data == null) { return 0; } int i = data.length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[i].hashCode(); } return hc; } public static byte[] clone(byte[] data) { if (data == null) { return null; } byte[] copy = new byte[data.length]; System.arraycopy(data, 0, copy, 0, data.length); return copy; } public static byte[] clone(byte[] data, byte[] existing) { if (data == null) { return null; } if ((existing == null) || (existing.length != data.length)) { return clone(data); } System.arraycopy(data, 0, existing, 0, existing.length); return existing; } public static byte[][] clone(byte[][] data) { if (data == null) { return null; } byte[][] copy = new byte[data.length][]; for (int i = 0; i != copy.length; i++) { copy[i] = clone(data[i]); } return copy; } public static byte[][][] clone(byte[][][] data) { if (data == null) { return null; } byte[][][] copy = new byte[data.length][][]; for (int i = 0; i != copy.length; i++) { copy[i] = clone(data[i]); } return copy; } public static int[] clone(int[] data) { if (data == null) { return null; } int[] copy = new int[data.length]; System.arraycopy(data, 0, copy, 0, data.length); return copy; } public static long[] clone(long[] data) { if (data == null) { return null; } long[] copy = new long[data.length]; System.arraycopy(data, 0, copy, 0, data.length); return copy; } public static long[] clone(long[] data, long[] existing) { if (data == null) { return null; } if ((existing == null) || (existing.length != data.length)) { return clone(data); } System.arraycopy(data, 0, existing, 0, existing.length); return existing; } public static short[] clone(short[] data) { if (data == null) { return null; } short[] copy = new short[data.length]; System.arraycopy(data, 0, copy, 0, data.length); return copy; } public static BigInteger[] clone(BigInteger[] data) { if (data == null) { return null; } BigInteger[] copy = new BigInteger[data.length]; System.arraycopy(data, 0, copy, 0, data.length); return copy; } public static byte[] copyOf(byte[] data, int newLength) { byte[] tmp = new byte[newLength]; if (newLength < data.length) { System.arraycopy(data, 0, tmp, 0, newLength); } else { System.arraycopy(data, 0, tmp, 0, data.length); } return tmp; } public static char[] copyOf(char[] data, int newLength) { char[] tmp = new char[newLength]; if (newLength < data.length) { System.arraycopy(data, 0, tmp, 0, newLength); } else { System.arraycopy(data, 0, tmp, 0, data.length); } return tmp; } public static int[] copyOf(int[] data, int newLength) { int[] tmp = new int[newLength]; if (newLength < data.length) { System.arraycopy(data, 0, tmp, 0, newLength); } else { System.arraycopy(data, 0, tmp, 0, data.length); } return tmp; } public static long[] copyOf(long[] data, int newLength) { long[] tmp = new long[newLength]; if (newLength < data.length) { System.arraycopy(data, 0, tmp, 0, newLength); } else { System.arraycopy(data, 0, tmp, 0, data.length); } return tmp; } public static BigInteger[] copyOf(BigInteger[] data, int newLength) { BigInteger[] tmp = new BigInteger[newLength]; if (newLength < data.length) { System.arraycopy(data, 0, tmp, 0, newLength); } else { System.arraycopy(data, 0, tmp, 0, data.length); } return tmp; } /** * Make a copy of a range of bytes from the passed in data array. The range can * extend beyond the end of the input array, in which case the return array will * be padded with zeroes. * * @param data the array from which the data is to be copied. * @param from the start index at which the copying should take place. * @param to the final index of the range (exclusive). * * @return a new byte array containing the range given. */ public static byte[] copyOfRange(byte[] data, int from, int to) { int newLength = getLength(from, to); byte[] tmp = new byte[newLength]; if (data.length - from < newLength) { System.arraycopy(data, from, tmp, 0, data.length - from); } else { System.arraycopy(data, from, tmp, 0, newLength); } return tmp; } public static int[] copyOfRange(int[] data, int from, int to) { int newLength = getLength(from, to); int[] tmp = new int[newLength]; if (data.length - from < newLength) { System.arraycopy(data, from, tmp, 0, data.length - from); } else { System.arraycopy(data, from, tmp, 0, newLength); } return tmp; } public static long[] copyOfRange(long[] data, int from, int to) { int newLength = getLength(from, to); long[] tmp = new long[newLength]; if (data.length - from < newLength) { System.arraycopy(data, from, tmp, 0, data.length - from); } else { System.arraycopy(data, from, tmp, 0, newLength); } return tmp; } public static BigInteger[] copyOfRange(BigInteger[] data, int from, int to) { int newLength = getLength(from, to); BigInteger[] tmp = new BigInteger[newLength]; if (data.length - from < newLength) { System.arraycopy(data, from, tmp, 0, data.length - from); } else { System.arraycopy(data, from, tmp, 0, newLength); } return tmp; } private static int getLength(int from, int to) { int newLength = to - from; if (newLength < 0) { StringBuffer sb = new StringBuffer(from); sb.append(" > ").append(to); throw new IllegalArgumentException(sb.toString()); } return newLength; } public static byte[] append(byte[] a, byte b) { if (a == null) { return new byte[]{ b }; } int length = a.length; byte[] result = new byte[length + 1]; System.arraycopy(a, 0, result, 0, length); result[length] = b; return result; } public static int[] append(int[] a, int b) { if (a == null) { return new int[]{ b }; } int length = a.length; int[] result = new int[length + 1]; System.arraycopy(a, 0, result, 0, length); result[length] = b; return result; } public static byte[] concatenate(byte[] a, byte[] b) { if (a != null && b != null) { byte[] rv = new byte[a.length + b.length]; System.arraycopy(a, 0, rv, 0, a.length); System.arraycopy(b, 0, rv, a.length, b.length); return rv; } else if (b != null) { return clone(b); } else { return clone(a); } } public static byte[] concatenate(byte[] a, byte[] b, byte[] c) { if (a != null && b != null && c != null) { byte[] rv = new byte[a.length + b.length + c.length]; System.arraycopy(a, 0, rv, 0, a.length); System.arraycopy(b, 0, rv, a.length, b.length); System.arraycopy(c, 0, rv, a.length + b.length, c.length); return rv; } else if (b == null) { return concatenate(a, c); } else { return concatenate(a, b); } } public static byte[] concatenate(byte[] a, byte[] b, byte[] c, byte[] d) { if (a != null && b != null && c != null && d != null) { byte[] rv = new byte[a.length + b.length + c.length + d.length]; System.arraycopy(a, 0, rv, 0, a.length); System.arraycopy(b, 0, rv, a.length, b.length); System.arraycopy(c, 0, rv, a.length + b.length, c.length); System.arraycopy(d, 0, rv, a.length + b.length + c.length, d.length); return rv; } else if (d == null) { return concatenate(a, b, c); } else if (c == null) { return concatenate(a, b, d); } else if (b == null) { return concatenate(a, c, d); } else { return concatenate(b, c, d); } } public static byte[] prepend(byte[] a, byte b) { if (a == null) { return new byte[]{ b }; } int length = a.length; byte[] result = new byte[length + 1]; System.arraycopy(a, 0, result, 1, length); result[0] = b; return result; } }
package org.eclipse.persistence.platform.database; import org.eclipse.persistence.internal.databaseaccess.DatabaseCall; import org.eclipse.persistence.internal.databaseaccess.FieldTypeDefinition; import org.eclipse.persistence.internal.expressions.ExpressionSQLPrinter; import org.eclipse.persistence.internal.expressions.SQLSelectStatement; import org.eclipse.persistence.internal.sessions.AbstractSession; import org.eclipse.persistence.internal.helper.DatabaseTable; import org.eclipse.persistence.exceptions.ValidationException; import org.eclipse.persistence.expressions.ExpressionOperator; import org.eclipse.persistence.queries.ValueReadQuery; import java.util.Vector; import java.io.Writer; import java.io.IOException; import java.sql.SQLException; import java.util.Hashtable; import java.util.Collection; import java.util.Iterator; import org.eclipse.persistence.internal.helper.DatabaseField; /** * <p><b>Purpose</b>: Provides Derby DBMS specific behavior. * * @since TOPLink Essentials 1.0 */ public class DerbyPlatform extends DB2Platform { public static final int MAX_CLOB = 2147483647; //The maximum clob/blob size is 2 gigs in Derby. public static final int MAX_BLOB = MAX_CLOB; /** * INTERNAL: * TODO: Need to find out how can byte arrays be inlined in Derby */ protected void appendByteArray(byte[] bytes, Writer writer) throws IOException { super.appendByteArray(bytes, writer); } /** * INTERNAL: * This method returns the query to select the timestamp from the server * for Derby. */ public ValueReadQuery getTimestampQuery() { if (timestampQuery == null) { timestampQuery = new ValueReadQuery(); timestampQuery.setSQLString("VALUES CURRENT_TIMESTAMP"); } return timestampQuery; } //TODO: check with reviewer. This method should be made private in DB2platform public Vector getNativeTableInfo(String table, String creator, AbstractSession session) { throw new RuntimeException("Should never reach here"); } /** * Used for stored procedure defs. */ public String getProcedureEndString() { return getBatchEndString(); } /** * Used for stored procedure defs. */ public String getProcedureBeginString() { return getBatchBeginString(); } /** * This method is used to print the output parameter token when stored * procedures are called */ public String getInOutputProcedureToken() { return "INOUT"; } /** * This is required in the construction of the stored procedures with * output parameters */ public boolean shouldPrintOutputTokenAtStart() { //TODO: Check with the reviewer where this is used return false; } /** * INTERNAL: * Answers whether platform is Derby */ public boolean isDerby() { return true; } public boolean isDB2() { //This class inhertits from DB2. But it is not DB2 return false; } public String getSelectForUpdateString() { return " FOR UPDATE WITH RS"; } /** * Allow for the platform to ignore exceptions. */ public boolean shouldIgnoreException(SQLException exception) { // Nothing is ignored. return false; } /** * INTERNAL: */ protected String getCreateTempTableSqlSuffix() { return " ON COMMIT DELETE ROWS NOT LOGGED"; } /** * INTERNAL: * Build the identity query for native sequencing. */ public ValueReadQuery buildSelectQueryForIdentity() { ValueReadQuery selectQuery = new ValueReadQuery(); selectQuery.setSQLString("values IDENTITY_VAL_LOCAL()"); return selectQuery; } /** * INTERNAL: * Indicates whether temporary table can specify primary keys (some platforms don't allow that). * Used by writeCreateTempTableSql method. */ protected boolean shouldTempTableSpecifyPrimaryKeys() { return false; } /** * INTERNAL: */ protected String getCreateTempTableSqlBodyForTable(DatabaseTable table) { // returning null includes fields of the table in body // see javadoc of DatabasePlatform#getCreateTempTableSqlBodyForTable(DataBaseTable) // for details return null; } /** * INTERNAL: * May need to override this method if the platform supports temporary tables * and the generated sql doesn't work. * Write an sql string for updating the original table from the temporary table. * Precondition: supportsTempTables() == true. * Precondition: pkFields and assignFields don't intersect. * @parameter Writer writer for writing the sql * @parameter DatabaseTable table is original table for which temp table is created. * @parameter Collection pkFields - primary key fields for the original table. * @parameter Collection assignedFields - fields to be assigned a new value. */ public void writeUpdateOriginalFromTempTableSql(Writer writer, DatabaseTable table, Collection pkFields, Collection assignedFields) throws IOException { writer.write("UPDATE "); String tableName = table.getQualifiedNameDelimited(this); writer.write(tableName); writer.write(" SET "); String tempTableName = getTempTableForTable(table).getQualifiedNameDelimited(this); boolean isFirst = true; Iterator itFields = assignedFields.iterator(); while(itFields.hasNext()) { if(isFirst) { isFirst = false; } else { writer.write(", "); } DatabaseField field = (DatabaseField)itFields.next(); String fieldName = field.getNameDelimited(this); writer.write(fieldName); writer.write(" = (SELECT "); writer.write(fieldName); writer.write(" FROM "); writer.write(tempTableName); writeAutoJoinWhereClause(writer, null, tableName, pkFields, this); writer.write(")"); } writer.write(" WHERE EXISTS(SELECT "); writer.write(((DatabaseField)pkFields.iterator().next()).getNameDelimited(this)); writer.write(" FROM "); writer.write(tempTableName); writeAutoJoinWhereClause(writer, null, tableName, pkFields, this); writer.write(")"); } /** * INTERNAL: * Append the receiver's field 'identity' constraint clause to a writer. */ public void printFieldIdentityClause(Writer writer) throws ValidationException { try { writer.write(" GENERATED ALWAYS AS IDENTITY"); } catch (IOException ioException) { throw ValidationException.fileError(ioException); } } protected Hashtable buildFieldTypes() { Hashtable fieldTypeMapping = new Hashtable(); fieldTypeMapping.put(Boolean.class, new FieldTypeDefinition("SMALLINT DEFAULT 0", false)); fieldTypeMapping.put(Integer.class, new FieldTypeDefinition("INTEGER", false)); fieldTypeMapping.put(Long.class, new FieldTypeDefinition("BIGINT", false)); fieldTypeMapping.put(Float.class, new FieldTypeDefinition("FLOAT", false)); fieldTypeMapping.put(Double.class, new FieldTypeDefinition("FLOAT", false)); fieldTypeMapping.put(Short.class, new FieldTypeDefinition("SMALLINT", false)); fieldTypeMapping.put(Byte.class, new FieldTypeDefinition("SMALLINT", false)); fieldTypeMapping.put(java.math.BigInteger.class, new FieldTypeDefinition("BIGINT", false)); fieldTypeMapping.put(java.math.BigDecimal.class, new FieldTypeDefinition("DECIMAL", 15)); fieldTypeMapping.put(Number.class, new FieldTypeDefinition("DECIMAL", 15)); fieldTypeMapping.put(String.class, new FieldTypeDefinition("VARCHAR", 255)); fieldTypeMapping.put(Character.class, new FieldTypeDefinition("CHAR", 1)); fieldTypeMapping.put(Byte[].class, new FieldTypeDefinition("BLOB", MAX_BLOB)); fieldTypeMapping.put(Character[].class, new FieldTypeDefinition("CLOB", MAX_CLOB)); fieldTypeMapping.put(byte[].class, new FieldTypeDefinition("BLOB", MAX_BLOB)); fieldTypeMapping.put(char[].class, new FieldTypeDefinition("CLOB", MAX_CLOB)); fieldTypeMapping.put(java.sql.Blob.class, new FieldTypeDefinition("BLOB", MAX_BLOB)); fieldTypeMapping.put(java.sql.Clob.class, new FieldTypeDefinition("CLOB", MAX_CLOB)); fieldTypeMapping.put(java.sql.Date.class, new FieldTypeDefinition("DATE", false)); fieldTypeMapping.put(java.sql.Time.class, new FieldTypeDefinition("TIME", false)); fieldTypeMapping.put(java.sql.Timestamp.class, new FieldTypeDefinition("TIMESTAMP", false)); return fieldTypeMapping; } /** * Initialize any platform-specific operators */ protected void initializePlatformOperators() { super.initializePlatformOperators(); // Derby does not support DECIMAL, but does have a DOUBLE function. addOperator(ExpressionOperator.simpleFunction(ExpressionOperator.ToNumber, "DOUBLE")); } /** * INTERNAL: * Derby does not support the DB2 syntax, so perform the default. */ @Override public void printSQLSelectStatement(DatabaseCall call, ExpressionSQLPrinter printer, SQLSelectStatement statement) { call.setFields(statement.printSQL(printer)); } /** * INTERNAL: Derby does not support sequence objects as DB2 does. */ @Override public boolean supportsSequenceObjects() { return false; } }
package com.evolveum.midpoint.web.component.assignment; import com.evolveum.midpoint.gui.api.util.WebComponentUtil; import com.evolveum.midpoint.prism.query.AndFilter; import com.evolveum.midpoint.prism.query.ObjectFilter; import com.evolveum.midpoint.prism.query.ObjectPaging; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.query.builder.QueryBuilder; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.component.form.Form; import com.evolveum.midpoint.web.component.prism.ContainerValueWrapper; import com.evolveum.midpoint.web.component.prism.ContainerWrapper; import com.evolveum.midpoint.web.component.prism.ValueStatus; import com.evolveum.midpoint.web.session.AssignmentsTabStorage; import com.evolveum.midpoint.web.session.UserProfileStorage; import com.evolveum.midpoint.web.util.ExpressionUtil; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.commons.lang.StringUtils; import org.apache.wicket.AttributeModifier; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import javax.jws.WebParam; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class InducedEntitlementsPanel extends InducementsPanel{ private static final long serialVersionUID = 1L; private static final Trace LOGGER = TraceManager.getTrace(InducedEntitlementsPanel.class); private static final String DOT_CLASS = InducedEntitlementsPanel.class.getName() + "."; private static final String OPERATION_LOAD_SHADOW_DISPLAY_NAME = DOT_CLASS + "loadShadowDisplayName"; public InducedEntitlementsPanel(String id, IModel<ContainerWrapper<AssignmentType>> inducementContainerWrapperModel){ super(id, inducementContainerWrapperModel); } @Override protected void initPaging() { getInducedEntitlementsTabStorage().setPaging(ObjectPaging.createPaging(0, getItemsPerPage())); } @Override protected UserProfileStorage.TableId getTableId() { return UserProfileStorage.TableId.INDUCED_ENTITLEMENTS_TAB_TABLE; } @Override protected int getItemsPerPage() { return (int) getParentPage().getItemsPerPage(UserProfileStorage.TableId.INDUCED_ENTITLEMENTS_TAB_TABLE); } private AssignmentsTabStorage getInducedEntitlementsTabStorage(){ return getParentPage().getSessionStorage().getInducedEntitlementsTabStorage(); } @Override protected List<IColumn<ContainerValueWrapper<AssignmentType>, String>> initColumns() { List<IColumn<ContainerValueWrapper<AssignmentType>, String>> columns = new ArrayList<>(); columns.add(new AbstractColumn<ContainerValueWrapper<AssignmentType>, String>(createStringResource("ConstructionType.kind")){ private static final long serialVersionUID = 1L; @Override public void populateItem(Item<ICellPopulator<ContainerValueWrapper<AssignmentType>>> item, String componentId, final IModel<ContainerValueWrapper<AssignmentType>> rowModel) { item.add(new Label(componentId, getKindLabelModel(rowModel.getObject()))); } }); columns.add(new AbstractColumn<ContainerValueWrapper<AssignmentType>, String>(createStringResource("ConstructionType.intent")){ private static final long serialVersionUID = 1L; @Override public void populateItem(Item<ICellPopulator<ContainerValueWrapper<AssignmentType>>> item, String componentId, final IModel<ContainerValueWrapper<AssignmentType>> rowModel) { item.add(new Label(componentId, getIntentLabelModel(rowModel.getObject()))); } }); columns.add(new AbstractColumn<ContainerValueWrapper<AssignmentType>, String>(createStringResource("ConstructionType.association")){ private static final long serialVersionUID = 1L; @Override public void populateItem(Item<ICellPopulator<ContainerValueWrapper<AssignmentType>>> item, String componentId, final IModel<ContainerValueWrapper<AssignmentType>> rowModel) { item.add(AttributeModifier.append("style", "white-space: pre-line")); item.add(new Label(componentId, getAssociationLabelModel(rowModel.getObject()))); } }); return columns; } @Override protected ObjectQuery createObjectQuery() { ObjectQuery query = super.createObjectQuery(); ObjectFilter filter = query.getFilter(); ObjectQuery entitlementsQuery = QueryBuilder.queryFor(AssignmentType.class, getParentPage().getPrismContext()) .exists(AssignmentType.F_CONSTRUCTION) .build(); if (filter != null){ query.setFilter(AndFilter.createAnd(filter, entitlementsQuery.getFilter())); } else { query.setFilter(entitlementsQuery.getFilter()); } return query; } @Override protected InducementDetailsPanel createDetailsPanel(String idAssignmentDetails, Form<?> form, IModel<ContainerValueWrapper<AssignmentType>> model) { return new InducedEntitlementDetailsPanel(ID_ASSIGNMENT_DETAILS, form, model); } @Override protected Class getDefaultNewAssignmentFocusType(){ return ResourceType.class; } @Override protected boolean isRelationVisible() { return false; } protected List<ObjectTypes> getObjectTypesList(){ return Arrays.asList(ObjectTypes.RESOURCE); } private IModel<String> getKindLabelModel(ContainerValueWrapper<AssignmentType> assignmentWrapper){ if (assignmentWrapper == null){ return Model.of(""); } AssignmentType assignment = assignmentWrapper.getContainerValue().asContainerable(); ConstructionType construction = assignment.getConstruction(); if (construction == null || construction.getKind() == null){ return Model.of(""); } return WebComponentUtil.createLocalizedModelForEnum(construction.getKind(), InducedEntitlementsPanel.this); } private IModel<String> getIntentLabelModel(ContainerValueWrapper<AssignmentType> assignmentWrapper){ if (assignmentWrapper == null){ return Model.of(""); } AssignmentType assignment = assignmentWrapper.getContainerValue().asContainerable(); ConstructionType construction = assignment.getConstruction(); if (construction == null || construction.getIntent() == null){ return Model.of(""); } return Model.of(construction.getIntent()); } private IModel<String> getAssociationLabelModel(ContainerValueWrapper<AssignmentType> assignmentWrapper){ if (assignmentWrapper == null){ return Model.of(""); } AssignmentType assignment = assignmentWrapper.getContainerValue().asContainerable(); ConstructionType construction = assignment.getConstruction(); if (construction == null || construction.getAssociation() == null){ return Model.of(""); } StringBuilder sb = new StringBuilder(); for (ResourceObjectAssociationType association : construction.getAssociation()){ if (association.getOutbound() == null || association.getOutbound().getExpression() == null){ continue; } ObjectReferenceType shadowRefValue = ExpressionUtil.getShadowRefValue(association.getOutbound().getExpression()); if (shadowRefValue == null || StringUtils.isEmpty(shadowRefValue.getOid())){ continue; } String shadowDisplayName = WebComponentUtil.getDisplayNameOrName(shadowRefValue, getPageBase(), OPERATION_LOAD_SHADOW_DISPLAY_NAME); if (sb.length() == 0){ sb.append(createStringResource("ExpressionValuePanel.shadowRefValueTitle").getString() + ":"); } if (StringUtils.isNotEmpty(shadowDisplayName)){ sb.append("\n"); sb.append(shadowDisplayName); } } return Model.of(sb.toString()); } @Override protected List<ContainerValueWrapper<AssignmentType>> postSearch(List<ContainerValueWrapper<AssignmentType>> assignments) { List<ContainerValueWrapper<AssignmentType>> filteredAssignments = new ArrayList<>(); if (assignments == null){ return filteredAssignments; } assignments.forEach(assignmentWrapper -> { AssignmentType assignment = assignmentWrapper.getContainerValue().asContainerable(); if (assignment.getConstruction() != null && assignment.getConstruction().getAssociation() != null) { List<ResourceObjectAssociationType> associations = assignment.getConstruction().getAssociation(); if (associations.size() == 0 && ValueStatus.ADDED.equals(assignmentWrapper.getStatus())){ filteredAssignments.add(assignmentWrapper); return; } associations.forEach(association -> { if (!filteredAssignments.contains(assignmentWrapper)) { if (association.getOutbound() == null && ValueStatus.ADDED.equals(assignmentWrapper.getStatus())) { filteredAssignments.add(assignmentWrapper); return; } if (association.getOutbound() != null && association.getOutbound().getExpression() != null) { ObjectReferenceType shadowRef = ExpressionUtil.getShadowRefValue(association.getOutbound().getExpression()); if ((shadowRef != null || ValueStatus.ADDED.equals(assignmentWrapper.getStatus()))) { filteredAssignments.add(assignmentWrapper); return; } } } }); } }); return filteredAssignments; } }
package jadx.cli; import jadx.api.JadxDecompiler; import jadx.core.utils.exceptions.JadxException; import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; //import jadx.core.xmlgen.BinaryXMLParser; public class JadxCLI { private static final Logger LOG = LoggerFactory.getLogger(JadxCLI.class); public static void main(String[] args) throws JadxException { //BinaryXMLParser bxp = new BinaryXMLParser(args[0],args[1]); //bxp.parse(); //System.exit(4); try { JadxCLIArgs jadxArgs = new JadxCLIArgs(); if (processArgs(jadxArgs, args)) { processAndSave(jadxArgs); } } catch (Throwable e) { LOG.error("jadx error: " + e.getMessage(), e); System.exit(1); } } static void processAndSave(JadxCLIArgs jadxArgs) throws JadxException { JadxDecompiler jadx = new JadxDecompiler(jadxArgs); jadx.setOutputDir(jadxArgs.getOutDir()); jadx.loadFiles(jadxArgs.getInput()); jadx.save(); if (jadx.getErrorsCount() != 0) { jadx.printErrorsReport(); LOG.error("finished with errors"); } else { LOG.info("done"); } } static boolean processArgs(JadxCLIArgs jadxArgs, String[] args) throws JadxException { if (!jadxArgs.processArgs(args)) { return false; } if (jadxArgs.getInput().isEmpty()) { LOG.error("Please specify input file"); jadxArgs.printUsage(); return false; } File outputDir = jadxArgs.getOutDir(); if (outputDir == null) { String outDirName; File file = jadxArgs.getInput().get(0); String name = file.getName(); int pos = name.lastIndexOf('.'); if (pos != -1) { outDirName = name.substring(0, pos); } else { outDirName = name + "-jadx-out"; } LOG.info("output directory: " + outDirName); outputDir = new File(outDirName); jadxArgs.setOutputDir(outputDir); } if (outputDir.exists() && !outputDir.isDirectory()) { throw new JadxException("Output directory exists as file " + outputDir); } return true; } }
package io.flutter.run.daemon; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; class ProgressHelper { final Project myProject; final List<String> myTasks = new ArrayList<>(); private Task.Backgroundable myTask; ProgressHelper(@NotNull Project project) { this.myProject = project; } /** * Start a progress task. * * @param log the title of the progress task */ public void start(String log) { synchronized (myTasks) { myTasks.add(log); myTasks.notifyAll(); if (myTask == null) { myTask = new Task.Backgroundable(myProject, log, false) { @Override public void run(@NotNull ProgressIndicator indicator) { indicator.setText(log); synchronized (myTasks) { while (!myTasks.isEmpty()) { indicator.setText(myTasks.get(myTasks.size() - 1)); try { myTasks.wait(); } catch (InterruptedException e) { // ignore } myTask = null; } } } }; ApplicationManager.getApplication().invokeLater(() -> { synchronized (myTasks) { if (myTask != null) { ProgressManager.getInstance().run(myTask); } } }); } } } /** * Notify that a progress task has finished. */ public void done() { synchronized (myTasks) { if (!myTasks.isEmpty()) { myTasks.remove(myTasks.size() - 1); myTasks.notifyAll(); } } } /** * Finish any outstanding progress tasks. */ public void cancel() { synchronized (myTasks) { myTasks.clear(); myTasks.notifyAll(); } } }
package jade.content.schema; import jade.content.onto.*; import jade.content.abs.*; import java.util.Hashtable; import java.util.Vector; import java.util.Enumeration; import jade.content.schema.facets.*; import jade.core.CaseInsensitiveString; /** * @author Giovanni Caire - TILAB */ class ObjectSchemaImpl extends ObjectSchema { private class SlotDescriptor { private String name = null; private ObjectSchema schema = null; private int optionality = 0; /** Construct a SlotDescriptor */ private SlotDescriptor(String name, ObjectSchema schema, int optionality) { this.name = name; this.schema = schema; this.optionality = optionality; } } /** Canstant value indicating that a slot in a schema is mandatory, i.e. its value must not be null */ //public static final int MANDATORY = 0; /** Canstant value indicating that a slot in a schema is optional, i.e. its value can be null */ //public static final int OPTIONAL = 1; /** Canstant value indicating that a slot in a schema has an infinite maximum cardinality */ //public static final int UNLIMITED = -1; private Hashtable slots = new Hashtable(); private Vector slotNames = new Vector(); private Vector superSchemas = new Vector(); private String typeName = null; private Hashtable facets = new Hashtable(); //public static final String BASE_NAME = "Object"; //private static ObjectSchema baseSchema = new ObjectSchemaImpl(); static { baseSchema = new ObjectSchemaImpl(); } /** * Construct a schema that vinculates an entity to be a generic * object (i.e. no constraints at all) */ private ObjectSchemaImpl() { this(BASE_NAME); } /** * Creates an <code>ObjectSchema</code> with a given type-name. * @param typeName The name of this <code>ObjectSchema</code>. */ protected ObjectSchemaImpl(String typeName) { this.typeName = typeName; } /** * Retrieve the generic base schema for all objects. * @return the generic base schema for all objects. */ //public static ObjectSchema getBaseSchema() { // return baseSchema; /** * Add a slot to the schema. * @param name The name of the slot. * @param slotSchema The schema defining the type of the slot. * @param optionality The optionality, i.e., <code>OPTIONAL</code> * or <code>MANDATORY</code> */ protected void add(String name, ObjectSchema slotSchema, int optionality) { CaseInsensitiveString ciName = new CaseInsensitiveString(name); if (slots.put(ciName, new SlotDescriptor(name, slotSchema, optionality)) == null) { slotNames.addElement(ciName); } } /** * Add a mandatory slot to the schema. * @param name name of the slot. * @param slotSchema schema of the slot. */ protected void add(String name, ObjectSchema slotSchema) { add(name, slotSchema, MANDATORY); } /** * Add a slot with cardinality between <code>cardMin</code> * and <code>cardMax</code> to this schema. * Adding such a slot is equivalent to add a slot * of type Aggregate and then to add proper facets (constraints) * to check that the type of the elements in the aggregate are * compatible with <code>elementsSchema</code> and that the * aggregate contains at least <code>cardMin</code> elements and * at most <code>cardMax</code> elements. * @param name The name of the slot. * @param elementsSchema The schema for the elements of this slot. * @param cardMin This slot must get at least <code>cardMin</code> * values * @param cardMax This slot can get at most <code>cardMax</code> * values */ protected void add(String name, ObjectSchema elementsSchema, int cardMin, int cardMax) { int optionality = (cardMin == 0 ? OPTIONAL : MANDATORY); try { add(name, BasicOntology.getInstance().getSchema(BasicOntology.SEQUENCE), optionality); // Add proper facets addFacet(name, new TypedAggregateFacet(elementsSchema)); addFacet(name, new CardinalityFacet(cardMin, cardMax)); } catch (OntologyException oe) { // Should never happen oe.printStackTrace(); } } /** * Add a super schema tho this schema, i.e. this schema will * inherit all characteristics from the super schema * @param superSchema the super schema. */ protected void addSuperSchema(ObjectSchema superSchema) { superSchemas.addElement(superSchema); } /** Add a <code>Facet</code> on a slot of this schema @param slotName the name of the slot the <code>Facet</code> must be added to. @param f the <code>Facet</code> to be added. @throws OntologyException if slotName does not identify a valid slot in this schema */ protected void addFacet(String slotName, Facet f) throws OntologyException { if (containsSlot(slotName)) { CaseInsensitiveString ciName = new CaseInsensitiveString(slotName); Vector v = (Vector) facets.get(ciName); if (v == null) { v = new Vector(); facets.put(ciName, v); //DEBUG //System.out.println("Added facet "+f+" to slot "+slotName); } v.addElement(f); } else { throw new OntologyException(slotName+" is not a valid slot in this schema"); } } /** * Retrieves the name of the type of this schema. * @return the name of the type of this schema. */ public String getTypeName() { return typeName; } /** * Returns the names of all the slots in this <code>Schema</code> * (including slots defined in super schemas). * * @return the names of all slots. */ public String[] getNames() { Vector allSlotNames = new Vector(); fillAllSlotNames(allSlotNames); String[] names = new String[allSlotNames.size()]; int counter = 0; for (Enumeration e = allSlotNames.elements(); e.hasMoreElements(); ) { names[counter++] = ((CaseInsensitiveString) e.nextElement()).toString(); } return names; } /** * Retrieves the schema of a slot of this <code>Schema</code>. * * @param name The name of the slot. * @return the <code>Schema</code> of slot <code>name</code> * @throws OntologyException If no slot with this name is present * in this schema. */ public ObjectSchema getSchema(String name) throws OntologyException { CaseInsensitiveString ciName = new CaseInsensitiveString(name); SlotDescriptor slot = (SlotDescriptor) slots.get(ciName); if (slot == null) { for (Enumeration e = superSchemas.elements(); e.hasMoreElements(); ) { try { ObjectSchema superSchema = (ObjectSchema) e.nextElement(); return superSchema.getSchema(name); } catch (OntologyException oe) { // Do nothing. Maybe the slot is defined in another super-schema } } throw new OntologyException("No slot named: " + name); } return slot.schema; } /** * Indicate whether a given <code>String</code> is the name of a * slot defined in this <code>Schema</code> * * @param name The <code>String</code> to test. * @return <code>true</code> if <code>name</code> is the name of a * slot defined in this <code>Schema</code>. */ public boolean containsSlot(String name) { CaseInsensitiveString ciName = new CaseInsensitiveString(name); SlotDescriptor slot = (SlotDescriptor) slots.get(ciName); if (slot != null) { return true; } for (Enumeration e = superSchemas.elements(); e.hasMoreElements(); ) { ObjectSchema superSchema = (ObjectSchema) e.nextElement(); if (superSchema.containsSlot(name)) { return true; } } return false; } /** * Creates an Abstract descriptor to hold an object compliant to * this <code>Schema</code>. */ public AbsObject newInstance() throws OntologyException { throw new OntologyException("AbsObject cannot be instantiated"); } private void fillAllSlotNames(Vector v) { // Get slot names of super schemas first for (Enumeration e = superSchemas.elements(); e.hasMoreElements(); ) { ObjectSchemaImpl superSchema = (ObjectSchemaImpl) e.nextElement(); superSchema.fillAllSlotNames(v); } // Then add slot names of this schema for (Enumeration e = slotNames.elements(); e.hasMoreElements(); ) { v.addElement(e.nextElement()); } } /** Check whether a given abstract descriptor complies with this schema. @param abs The abstract descriptor to be checked @throws OntologyException If the abstract descriptor does not complies with this schema */ public void validate(AbsObject abs, Ontology onto) throws OntologyException { validateSlots(abs, onto); } /** For each slot - get the corresponding attribute value from the abstract descriptor abs - Check that it is not null if the slot is mandatory - Check that its schema is compatible with the schema of the slot - Check that it is a correct abstract descriptor by validating it against its schema. */ protected void validateSlots(AbsObject abs, Ontology onto) throws OntologyException { // Validate all the attributes in the abstract descriptor String[] slotNames = getNames(); for (int i = 0; i < slotNames.length; ++i) { AbsObject slotValue = abs.getAbsObject(slotNames[i]); CaseInsensitiveString ciName = new CaseInsensitiveString(slotNames[i]); validate(ciName, slotValue, onto); } } /** Validate a given abstract descriptor as a value for a slot defined in this schema @param slotName The name of the slot @param value The abstract descriptor to be validated @throws OntologyException If the abstract descriptor is not a valid value @return true if the slot is defined in this schema (or in one of its super schemas). false otherwise */ private boolean validate(CaseInsensitiveString slotName, AbsObject value, Ontology onto) throws OntologyException { // DEBUG //System.out.println("Validating "+value+" as a value for slot "+slotName); // NOTE: for performance reasons we don't want to scan the schema // to check if slotValue is a valid slot and THEN to scan again // the schema to validate value. This is the reason for the // boolean return value of this method boolean slotFound = false; // If the slot is defined in this schema --> check the value // against the schema of the slot. Otherwise let the super-schema // where the slot is defined validate the value SlotDescriptor dsc = (SlotDescriptor) slots.get(slotName); if (dsc != null) { // DEBUG //System.out.println("Slot "+slotName+" is defined in schema "+this); if (value == null) { // Check optionality if (dsc.optionality == MANDATORY) { throw new OntologyException("Missing value for mandatory slot "+slotName+". Schema is "+this); } // Don't need to check facets on a null value for an optional slot return true; } else { // - Get from the ontology the schema s that defines the type // of the abstract descriptor value. // - Check if this schema is compatible with the schema for // slot slotName // - Finally check value against s ObjectSchema s = onto.getSchema(value.getTypeName()); //DEBUG //System.out.println("Actual schema for "+value+" is "+s); if (s == null) { throw new OntologyException("No schema found for type "+value.getTypeName()); } if (!s.isCompatibleWith(dsc.schema)) { throw new OntologyException("Schema "+s+" for element "+value+" is not compatible with schema "+dsc.schema+" for slot "+slotName); } //DEBUG //System.out.println("Schema "+s+" for type "+value+" is compatible with schema "+dsc.schema+" for slot "+slotName); s.validate(value, onto); } slotFound = true; } else { Enumeration e = superSchemas.elements(); while (e.hasMoreElements()) { ObjectSchemaImpl s = (ObjectSchemaImpl) e.nextElement(); if (s.validate(slotName, value, onto)) { slotFound = true; // Don't need to check other super-schemas break; } } } if (slotFound) { // Check value against the facets (if any) defined for the // slot in this schema Vector ff = (Vector) facets.get(slotName); if (ff != null) { Enumeration e = ff.elements(); while (e.hasMoreElements()) { Facet f = (Facet) e.nextElement(); //DEBUG //System.out.println("Checking facet "+f+" defined on slot "+slotName); f.validate(value, onto); } } else { //DEBUG //System.out.println("No facets for slot "+slotName); } } return slotFound; } /** Check if this schema is compatible with a given schema s. This is the case if 1) This schema is equals to s 2) s is one of the super-schemas of this schema 3) This schema descends from s i.e. - s is the base schema for the XXXSchema class this schema is an instance of (e.g. s is ConceptSchema.getBaseSchema() and this schema is an instance of ConceptSchema) - s is the base schema for a super-class of the XXXSchema class this schema is an instance of (e.g. s is TermSchema.getBaseSchema() and this schema is an instance of ConceptSchema) */ public boolean isCompatibleWith(ObjectSchema s) { if (equals(s)) { return true; } if (isSubSchemaOf(s)) { return true; } if (descendsFrom(s)) { return true; } return false; } /** Return true if - s is the base schema for the XXXSchema class this schema is an instance of (e.g. s is ConceptSchema.getBaseSchema() and this schema is an instance of ConceptSchema) - s is the base schema for a super-class of the XXXSchema class this schema is an instance of (e.g. s is TermSchema.getBaseSchema() and this schema is an instance of ConceptSchema) */ protected boolean descendsFrom(ObjectSchema s) { // The base schema for the ObjectSchema class descends only // from itself if (s!= null) { return s.equals(getBaseSchema()); } else { return false; } } /** Return true if s is a super-schema (directly or indirectly) of this schema */ private boolean isSubSchemaOf(ObjectSchema s) { Enumeration e = superSchemas.elements(); while (e.hasMoreElements()) { ObjectSchemaImpl s1 = (ObjectSchemaImpl) e.nextElement(); if (s1.equals(s)) { return true; } if (s1.isSubSchemaOf(s)) { return true; } } return false; } public String toString() { return getClass().getName()+"-"+getTypeName(); } public boolean equals(Object o) { if (o != null) { return toString().equals(o.toString()); } else { return false; } } }
package javaslang; import javaslang.collection.*; import javaslang.control.Either; import javaslang.control.Option; import javaslang.control.Try; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.Objects; import java.util.Optional; import java.util.function.*; import java.util.stream.Collector; import java.util.stream.StreamSupport; public interface Value<T> extends Iterable<T> { /** * Narrows a widened {@code Value<? extends T>} to {@code Value<T>} * by performing a type safe-cast. This is eligible because immutable/read-only * collections are covariant. * * @param value A {@code Value}. * @param <T> Component type of the {@code Value}. * @return the given {@code value} instance as narrowed type {@code Value<T>}. */ @SuppressWarnings("unchecked") static <T> Value<T> narrow(Value<? extends T> value) { return (Value<T>) value; } /** * Collects the underlying value(s) (if present) using the provided {@code collector}. * * @param collector Collector performing reduction * @return R reduction result */ default <R, A> R collect(Collector<? super T, A, R> collector) { return StreamSupport.stream(spliterator(), false).collect(collector); } /** * Collects the underlying value(s) (if present) using the given {@code supplier}, {@code accumulator} and * {@code combiner}. * * @param supplier provide unit value for reduction * @param accumulator perform reduction with unit value * @param combiner function for combining two values, which must be * compatible with the accumulator. * @return R reduction result */ default <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner) { return StreamSupport.stream(spliterator(), false).collect(supplier, accumulator, combiner); } /** * Shortcut for {@code exists(e -> Objects.equals(e, element))}, tests if the given {@code element} is contained. * * @param element An Object of type A, may be null. * @return true, if element is contained, false otherwise. */ default boolean contains(T element) { return exists(e -> Objects.equals(e, element)); } /** * Tests whether every element of this iterable relates to the corresponding element of another iterable by * satisfying a test predicate. * * @param <U> Component type of that iterable * @param that the other iterable * @param predicate the test predicate, which relates elements from both iterables * @return {@code true} if both iterables have the same length and {@code predicate(x, y)} * is {@code true} for all corresponding elements {@code x} of this iterable and {@code y} of {@code that}, * otherwise {@code false}. */ default <U> boolean corresponds(Iterable<U> that, BiPredicate<? super T, ? super U> predicate) { final java.util.Iterator<T> it1 = iterator(); final java.util.Iterator<U> it2 = that.iterator(); while (it1.hasNext() && it2.hasNext()) { if (!predicate.test(it1.next(), it2.next())) { return false; } } return !it1.hasNext() && !it2.hasNext(); } /** * A <em>smoothing</em> replacement for {@code equals}. It is similar to Scala's {@code ==} but better in the way * that it is not limited to collection types, e.g. {@code Some(1) eq List(1)}, {@code None eq Failure(x)} etc. * <p> * In a nutshell: eq checks <strong>congruence of structures</strong> and <strong>equality of contained values</strong>. * <p> * Example: * <p> * <pre><code> * // ((1, 2), ((3))) =&gt; structure: (()(())) values: 1, 2, 3 * final Value&lt;?&gt; i1 = List.of(List.of(1, 2), Arrays.asList(List.of(3))); * final Value&lt;?&gt; i2 = Queue.of(Stream.of(1, 2), List.of(Lazy.of(() -&gt; 3))); * assertThat(i1.eq(i2)).isTrue(); * </code></pre> * <p> * Semantics: * <p> * <pre><code> * o == this : true * o instanceof Value : iterable elements are eq, non-iterable elements equals, for all (o1, o2) in (this, o) * o instanceof Iterable : this eq Iterator.of((Iterable&lt;?&gt;) o); * otherwise : false * </code></pre> * * @param o An object * @return true, if this equals o according to the rules defined above, otherwise false. */ default boolean eq(Object o) { if (o == this) { return true; } else if (o instanceof Value) { final Value<?> that = (Value<?>) o; return this.iterator().corresponds(that.iterator(), (o1, o2) -> { if (o1 instanceof Value) { return ((Value<?>) o1).eq(o2); } else if (o2 instanceof Value) { return ((Value<?>) o2).eq(o1); } else { return Objects.equals(o1, o2); } }); } else if (o instanceof Iterable) { final Value<?> that = Iterator.ofAll((Iterable<?>) o); return this.eq(that); } else { return false; } } /** * Checks, if an element exists such that the predicate holds. * * @param predicate A Predicate * @return true, if predicate holds for one or more elements, false otherwise * @throws NullPointerException if {@code predicate} is null */ default boolean exists(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (T t : this) { if (predicate.test(t)) { return true; } } return false; } /** * Checks, if the given predicate holds for all elements. * * @param predicate A Predicate * @return true, if the predicate holds for all elements, false otherwise * @throws NullPointerException if {@code predicate} is null */ default boolean forAll(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return !exists(predicate.negate()); } /** * Performs an action on each element. * * @param action A {@code Consumer} * @throws NullPointerException if {@code action} is null */ @Override default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action, "action is null"); for (T t : this) { action.accept(t); } } /** * Gets the underlying value or throws if no value is present. * * @return the underlying value * @throws java.util.NoSuchElementException if no value is defined */ T get(); /** * Gets the underlying value as Option. * * @return Some(value) if a value is present, None otherwise */ default Option<T> getOption() { return isEmpty() ? Option.none() : Option.some(get()); } /** * Returns the underlying value if present, otherwise {@code other}. * * @param other An alternative value. * @return A value of type {@code T} */ default T getOrElse(T other) { return isEmpty() ? other : get(); } /** * Returns the underlying value if present, otherwise {@code other}. * * @param supplier An alternative value supplier. * @return A value of type {@code T} * @throws NullPointerException if supplier is null */ default T getOrElse(Supplier<? extends T> supplier) { Objects.requireNonNull(supplier, "supplier is null"); return isEmpty() ? supplier.get() : get(); } /** * Returns the underlying value if present, otherwise throws {@code supplier.get()}. * * @param <X> a Throwable type * @param supplier An exception supplier. * @return A value of type {@code T}. * @throws NullPointerException if supplier is null * @throws X if no value is present */ default <X extends Throwable> T getOrElseThrow(Supplier<X> supplier) throws X { Objects.requireNonNull(supplier, "supplier is null"); if (isEmpty()) { throw supplier.get(); } else { return get(); } } /** * Returns the underlying value if present, otherwise returns the result of {@code Try.of(supplier).get()}. * * @param supplier An alternative value supplier. * @return A value of type {@code T}. * @throws NullPointerException if supplier is null * @throws Try.NonFatalException containing the original exception if this Value was empty and the Try failed. */ default T getOrElseTry(Try.CheckedSupplier<? extends T> supplier) { Objects.requireNonNull(supplier, "supplier is null"); return isEmpty() ? Try.of(supplier).get() : get(); } /** * Checks, this {@code Value} is empty, i.e. if the underlying value is absent. * * @return false, if no underlying value is present, true otherwise. */ boolean isEmpty(); /** * States whether this is a single-valued type. * * @return {@code true} if this is single-valued, {@code false} otherwise. */ boolean isSingleValued(); /** * Maps the underlying value to a different component type. * * @param mapper A mapper * @param <U> The new component type * @return A new value */ <U> Value<U> map(Function<? super T, ? extends U> mapper); /** * Performs the given {@code action} on the first element if this is an <em>eager</em> implementation. * Performs the given {@code action} on all elements (the first immediately, successive deferred), * if this is a <em>lazy</em> implementation. * * @param action The action that will be performed on the element(s). * @return this instance */ Value<T> peek(Consumer<? super T> action); /** * Returns the name of this Value type, which is used by toString(). * * @return This type name. */ String stringPrefix(); // -- output @GwtIncompatible("java.io.PrintStream is not implemented") default void out(PrintStream out) { for (T t : this) { out.println(String.valueOf(t)); if (out.checkError()) { throw new IllegalStateException("Error writing to PrintStream"); } } } @GwtIncompatible("java.io.PrintWriter is not implemented") default void out(PrintWriter writer) { for (T t : this) { writer.println(String.valueOf(t)); if (writer.checkError()) { throw new IllegalStateException("Error writing to PrintWriter"); } } } @GwtIncompatible("java.io.PrintStream is not implemented") default void stderr() { out(System.err); } @GwtIncompatible("java.io.PrintStream is not implemented") default void stdout() { out(System.out); } // -- Adjusted return types of Iterable /** * Returns a rich {@code javaslang.collection.Iterator}. * * @return A new Iterator */ @Override Iterator<T> iterator(); // -- conversion methods /** * Converts this to a {@link Array}. * * @return A new {@link Array}. */ default Array<T> toArray() { return ValueModule.toTraversable(this, Array.empty(), Array::of, Array::ofAll); } /** * Converts this to a {@link CharSeq}. * * @return A new {@link CharSeq}. */ default CharSeq toCharSeq() { return CharSeq.of(toString()); } /** * Converts this to a specific {@link java.util.Collection}. * * @param factory A {@code java.util.Collection} factory * that returns empty collection with the specified initial capacity * @param <C> a sub-type of {@code java.util.Collection} * @return a new {@code java.util.Collection} of type {@code C} */ default <C extends java.util.Collection<T>> C toJavaCollection(Function<Integer, C> factory) { return ValueModule.toJavaCollection(this, factory); } /** * Converts this to an untyped Java array. * * @return A new Java array. */ default Object[] toJavaArray() { return toJavaList().toArray(); } /** * Converts this to a typed Java array. * * @param componentType Component type of the array * @return A new Java array. * @throws NullPointerException if componentType is null */ @SuppressWarnings("unchecked") @GwtIncompatible("reflection is not supported") default T[] toJavaArray(Class<T> componentType) { Objects.requireNonNull(componentType, "componentType is null"); final java.util.List<T> list = toJavaList(); return list.toArray((T[]) java.lang.reflect.Array.newInstance(componentType, list.size())); } /** * Converts this to an {@link java.util.List}. * * @return A new {@link java.util.ArrayList}. */ default java.util.List<T> toJavaList() { return ValueModule.toJavaCollection(this, ArrayList::new); } /** * Converts this to a specific {@link java.util.List}. * * @param factory A {@code java.util.List} factory * @param <LIST> a sub-type of {@code java.util.List} * @return a new {@code java.util.List} of type {@code LIST} */ default <LIST extends java.util.List<T>> LIST toJavaList(Function<Integer, LIST> factory) { return ValueModule.toJavaCollection(this, factory); } /** * Converts this to a {@link java.util.Map}. * * @param f A function that maps an element to a key/value pair represented by Tuple2 * @param <K> The key type * @param <V> The value type * @return A new {@link java.util.HashMap}. */ default <K, V> java.util.Map<K, V> toJavaMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f) { return toJavaMap(java.util.HashMap::new, f); } /** * Converts this to a specific {@link java.util.Map}. * * @param factory A {@code java.util.Map} factory * @param keyMapper A function that maps an element to a key * @param valueMapper A function that maps an element to a value * @param <K> The key type * @param <V> The value type * @param <MAP> a sub-type of {@code java.util.Map} * @return a new {@code java.util.Map} of type {@code MAP} */ default <K, V, MAP extends java.util.Map<K, V>> MAP toJavaMap(Supplier<MAP> factory, Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) { Objects.requireNonNull(keyMapper, "keyMapper is null"); Objects.requireNonNull(valueMapper, "valueMapper is null"); return toJavaMap(factory, t -> Tuple.of(keyMapper.apply(t), valueMapper.apply(t))); } /** * Converts this to a specific {@link java.util.Map}. * * @param factory A {@code java.util.Map} factory * @param f A function that maps an element to a key/value pair represented by Tuple2 * @param <K> The key type * @param <V> The value type * @param <MAP> a sub-type of {@code java.util.Map} * @return a new {@code java.util.Map} of type {@code MAP} */ default <K, V, MAP extends java.util.Map<K, V>> MAP toJavaMap(Supplier<MAP> factory, Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f) { Objects.requireNonNull(f, "f is null"); final MAP map = factory.get(); if (!isEmpty()) { if (isSingleValued()) { final Tuple2<? extends K, ? extends V> entry = f.apply(get()); map.put(entry._1, entry._2); } else { for (T a : this) { final Tuple2<? extends K, ? extends V> entry = f.apply(a); map.put(entry._1, entry._2); } } } return map; } /** * Converts this to an {@link java.util.Optional}. * * @return A new {@link java.util.Optional}. */ default Optional<T> toJavaOptional() { return isEmpty() ? Optional.empty() : Optional.ofNullable(get()); } /** * Converts this to a {@link java.util.Set}. * * @return A new {@link java.util.HashSet}. */ default java.util.Set<T> toJavaSet() { return ValueModule.toJavaCollection(this, java.util.HashSet::new); } /** * Converts this to a specific {@link java.util.Set}. * * @param factory A {@code java.util.Set} factory * that returns empty set with the specified initial capacity * @param <SET> a sub-type of {@code java.util.Set} * @return a new {@code java.util.Set} of type {@code SET} */ default <SET extends java.util.Set<T>> SET toJavaSet(Function<Integer, SET> factory) { return ValueModule.toJavaCollection(this, factory); } /** * Converts this to a {@link java.util.stream.Stream}. * * @return A new {@link java.util.stream.Stream}. */ default java.util.stream.Stream<T> toJavaStream() { return StreamSupport.stream(spliterator(), false); } /** * Converts this to a {@link Either}. * * @param <R> right type * @param right A supplier of a right value * @return A new {@link Either.Right} containing the result of {@code right} if this is empty, otherwise * a new {@link Either.Left} containing this value. * @throws NullPointerException if {@code right} is null */ default <R> Either<T, R> toLeft(Supplier<? extends R> right) { Objects.requireNonNull(right, "right is null"); return isEmpty() ? Either.right(right.get()) : Either.left(get()); } /** * Converts this to a {@link Either}. * * @param <R> right type * @param right An instance of a right value * @return A new {@link Either.Right} containing the value of {@code right} if this is empty, otherwise * a new {@link Either.Left} containing this value. * @throws NullPointerException if {@code right} is null */ default <R> Either<T, R> toLeft(R right) { return isEmpty() ? Either.right(right) : Either.left(get()); } /** * Converts this to a {@link List}. * * @return A new {@link List}. */ default List<T> toList() { return ValueModule.toTraversable(this, List.empty(), List::of, List::ofAll); } /** * Converts this to a {@link Map}. * * @param keyMapper A function that maps an element to a key * @param valueMapper A function that maps an element to a value * @param <K> The key type * @param <V> The value type * @return A new {@link HashMap}. */ default <K, V> Map<K, V> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) { Objects.requireNonNull(keyMapper, "keyMapper is null"); Objects.requireNonNull(valueMapper, "valueMapper is null"); return toMap(t -> Tuple.of(keyMapper.apply(t), valueMapper.apply(t))); } /** * Converts this to a {@link Map}. * * @param f A function that maps an element to a key/value pair represented by Tuple2 * @param <K> The key type * @param <V> The value type * @return A new {@link HashMap}. */ default <K, V> Map<K, V> toMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f) { Objects.requireNonNull(f, "f is null"); final Function<Tuple2<? extends K, ? extends V>, Map<K, V>> ofElement = HashMap::of; final Function<Iterable<Tuple2<? extends K, ? extends V>>, Map<K, V>> ofAll = HashMap::ofEntries; return ValueModule.toMap(this, HashMap.empty(), ofElement, ofAll, f); } /** * Converts this to a {@link Map}. * * @param keyMapper A function that maps an element to a key * @param valueMapper A function that maps an element to a value * @param <K> The key type * @param <V> The value type * @return A new {@link LinkedHashMap}. */ default <K, V> Map<K, V> toLinkedMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) { Objects.requireNonNull(keyMapper, "keyMapper is null"); Objects.requireNonNull(valueMapper, "valueMapper is null"); return toLinkedMap(t -> Tuple.of(keyMapper.apply(t), valueMapper.apply(t))); } /** * Converts this to a {@link Map}. * * @param f A function that maps an element to a key/value pair represented by Tuple2 * @param <K> The key type * @param <V> The value type * @return A new {@link LinkedHashMap}. */ default <K, V> Map<K, V> toLinkedMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f) { Objects.requireNonNull(f, "f is null"); final Function<Tuple2<? extends K, ? extends V>, Map<K, V>> ofElement = LinkedHashMap::of; final Function<Iterable<Tuple2<? extends K, ? extends V>>, Map<K, V>> ofAll = LinkedHashMap::ofEntries; return ValueModule.toMap(this, LinkedHashMap.empty(), ofElement, ofAll, f); } /** * Converts this to a {@link Map}. * * @param keyMapper A function that maps an element to a key * @param valueMapper A function that maps an element to a value * @param <K> The key type * @param <V> The value type * @return A new {@link TreeMap}. */ default <K extends Comparable<? super K>, V> SortedMap<K, V> toSortedMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) { Objects.requireNonNull(keyMapper, "keyMapper is null"); Objects.requireNonNull(valueMapper, "valueMapper is null"); return toSortedMap(t -> Tuple.of(keyMapper.apply(t), valueMapper.apply(t))); } /** * Converts this to a {@link Map}. * * @param f A function that maps an element to a key/value pair represented by Tuple2 * @param <K> The key type * @param <V> The value type * @return A new {@link TreeMap}. */ default <K extends Comparable<? super K>, V> SortedMap<K, V> toSortedMap(Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f) { Objects.requireNonNull(f, "f is null"); return toSortedMap((Comparator<? super K> & Serializable) K::compareTo, f); } /** * Converts this to a {@link Map}. * * @param comparator A comparator that induces an order of the Map keys. * @param keyMapper A function that maps an element to a key * @param valueMapper A function that maps an element to a value * @param <K> The key type * @param <V> The value type * @return A new {@link TreeMap}. */ default <K, V> SortedMap<K, V> toSortedMap(Comparator<? super K> comparator, Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) { Objects.requireNonNull(comparator, "comparator is null"); Objects.requireNonNull(keyMapper, "keyMapper is null"); Objects.requireNonNull(valueMapper, "valueMapper is null"); return toSortedMap(comparator, t -> Tuple.of(keyMapper.apply(t), valueMapper.apply(t))); } /** * Converts this to a {@link Map}. * * @param comparator A comparator that induces an order of the Map keys. * @param f A function that maps an element to a key/value pair represented by Tuple2 * @param <K> The key type * @param <V> The value type * @return A new {@link TreeMap}. */ default <K, V> SortedMap<K, V> toSortedMap(Comparator<? super K> comparator, Function<? super T, ? extends Tuple2<? extends K, ? extends V>> f) { Objects.requireNonNull(comparator, "comparator is null"); Objects.requireNonNull(f, "f is null"); final Function<Tuple2<? extends K, ? extends V>, SortedMap<K, V>> ofElement = t -> TreeMap.of(comparator, t); final Function<Iterable<Tuple2<? extends K, ? extends V>>, SortedMap<K, V>> ofAll = t -> TreeMap.ofEntries(comparator, t); return ValueModule.toMap(this, TreeMap.empty(comparator), ofElement, ofAll, f); } /** * Converts this to an {@link Option}. * * @return A new {@link Option}. */ default Option<T> toOption() { if (this instanceof Option) { return (Option<T>) this; } else { return getOption(); } } /** * Converts this to a {@link Queue}. * * @return A new {@link Queue}. */ default Queue<T> toQueue() { return ValueModule.toTraversable(this, Queue.empty(), Queue::of, Queue::ofAll); } /** * Converts this to a {@link PriorityQueue}. * * @return A new {@link PriorityQueue}. */ @SuppressWarnings("unchecked") default PriorityQueue<T> toPriorityQueue() { if (this instanceof PriorityQueue<?>) { return (PriorityQueue<T>) this; } else { final Comparator<T> comparator = (Comparator<T> & Serializable) (o1, o2) -> ((Comparable<T>) o1).compareTo(o2); return toPriorityQueue(comparator); } } /** * Converts this to a {@link PriorityQueue}. * * @param comparator A comparator that induces an order of the PriorityQueue elements. * @return A new {@link PriorityQueue}. */ default PriorityQueue<T> toPriorityQueue(Comparator<? super T> comparator) { Objects.requireNonNull(comparator, "comparator is null"); final PriorityQueue<T> empty = PriorityQueue.empty(comparator); final Function<T, PriorityQueue<T>> of = value -> PriorityQueue.of(comparator, value); final Function<Iterable<T>, PriorityQueue<T>> ofAll = values -> PriorityQueue.ofAll(comparator, values); return ValueModule.toTraversable(this, empty, of, ofAll); } /** * Converts this to a {@link Either}. * * @param <L> left type * @param left A supplier of a left value * @return A new {@link Either.Left} containing the result of {@code left} if this is empty, otherwise * a new {@link Either.Right} containing this value. * @throws NullPointerException if {@code left} is null */ default <L> Either<L, T> toRight(Supplier<? extends L> left) { Objects.requireNonNull(left, "left is null"); return isEmpty() ? Either.left(left.get()) : Either.right(get()); } /** * Converts this to a {@link Either}. * * @param <L> left type * @param left An instance of a left value * @return A new {@link Either.Left} containing the value of {@code left} if this is empty, otherwise * a new {@link Either.Right} containing this value. * @throws NullPointerException if {@code left} is null */ default <L> Either<L, T> toRight(L left) { return isEmpty() ? Either.left(left) : Either.right(get()); } /** * Converts this to a {@link Set}. * * @return A new {@link HashSet}. */ default Set<T> toSet() { return ValueModule.toTraversable(this, HashSet.empty(), HashSet::of, HashSet::ofAll); } /** * Converts this to a {@link Set}. * * @return A new {@link LinkedHashSet}. */ default Set<T> toLinkedSet() { return ValueModule.toTraversable(this, LinkedHashSet.empty(), LinkedHashSet::of, LinkedHashSet::ofAll); } /** * Converts this to a {@link SortedSet}. * Current items must be comparable * * @return A new {@link TreeSet}. * @throws ClassCastException if items are not comparable */ @SuppressWarnings("unchecked") default SortedSet<T> toSortedSet() throws ClassCastException { final Comparator<T> comparator; if (this instanceof TreeSet<?>) { return (TreeSet<T>) this; } else if (this instanceof SortedSet<?>) { comparator = ((SortedSet<T>) this).comparator(); } else { comparator = (Comparator<T> & Serializable) (o1, o2) -> ((Comparable<T>) o1).compareTo(o2); } return toSortedSet(comparator); } /** * Converts this to a {@link SortedSet}. * * @param comparator A comparator that induces an order of the SortedSet elements. * @return A new {@link TreeSet}. */ default SortedSet<T> toSortedSet(Comparator<? super T> comparator) { Objects.requireNonNull(comparator, "comparator is null"); return ValueModule.toTraversable(this, TreeSet.empty(comparator), value -> TreeSet.of(comparator, value), values -> TreeSet.ofAll(comparator, values)); } /** * Converts this to a {@link Stack}. * * @return A new {@link List}, which is a {@link Stack}. */ default Stack<T> toStack() { return toList(); } /** * Converts this to a {@link Stream}. * * @return A new {@link Stream}. */ default Stream<T> toStream() { return ValueModule.toTraversable(this, Stream.empty(), Stream::of, Stream::ofAll); } /** * Converts this to a {@link Try}. * <p> * If this value is undefined, i.e. empty, then a new {@code Failure(NoSuchElementException)} is returned, * otherwise a new {@code Success(value)} is returned. * * @return A new {@link Try}. */ default Try<T> toTry() { if (this instanceof Try) { return (Try<T>) this; } else { return Try.of(this::get); } } /** * Converts this to a {@link Try}. * <p> * If this value is undefined, i.e. empty, then a new {@code Failure(ifEmpty.get())} is returned, * otherwise a new {@code Success(value)} is returned. * * @param ifEmpty an exception supplier * @return A new {@link Try}. */ default Try<T> toTry(Supplier<? extends Throwable> ifEmpty) { Objects.requireNonNull(ifEmpty, "ifEmpty is null"); return isEmpty() ? Try.failure(ifEmpty.get()) : toTry(); } /** * Converts this to a {@link Tree}. * * @return A new {@link Tree}. */ default Tree<T> toTree() { return ValueModule.toTraversable(this, Tree.empty(), Tree::of, Tree::ofAll); } /** * Converts this to a {@link Vector}. * * @return A new {@link Vector}. */ default Vector<T> toVector() { return ValueModule.toTraversable(this, Vector.empty(), Vector::of, Vector::ofAll); } // -- Object @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } interface ValueModule { @SuppressWarnings("unchecked") static <T extends Traversable<V>, V> T toTraversable(Value<V> value, T empty, Function<V, T> ofElement, Function<Iterable<V>, T> ofAll) { if (value.isEmpty()) { return empty; } else if (value.isSingleValued()) { return ofElement.apply(value.get()); } else { return ofAll.apply(value); } } static <T, K, V, M extends Map<K, V>, TT extends Tuple2<? extends K, ? extends V>> M toMap( Value<T> value, M empty, Function<TT, M> ofElement, Function<Iterable<TT>, M> ofAll, Function<? super T, ? extends TT> f ) { if (value.isEmpty()) { return empty; } else if (value.isSingleValued()) { return ofElement.apply(f.apply(value.get())); } else { return ofAll.apply(Iterator.ofAll(value).map(f)); } } static <T extends java.util.Collection<V>, V> T toJavaCollection(Value<V> value, Function<Integer, T> containerSupplier) { final T container; if (value.isEmpty()) { container = containerSupplier.apply(0); } else { if (value.isSingleValued()) { container = containerSupplier.apply(1); container.add(value.get()); } else { final int size = value instanceof Traversable && ((Traversable) value).isTraversableAgain() ? ((Traversable<V>) value).size() : 0; container = containerSupplier.apply(size); value.forEach(container::add); } } return container; } }
// $Id: Controller.java,v 1.18 2004/05/21 20:53:08 ray Exp $ // samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.swing; import java.awt.Component; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.Method; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JComponent; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import com.samskivert.Log; import com.samskivert.swing.event.CommandEvent; /** * The controller class provides a basis for the separation of user interface * code into display code and control code. The display code lives in a panel * class (<code>javax.swing.JPanel</code> or something conceptually similar) * and the control code lives in an associated controller class. * * <p> The controller philosophy is thus: The panel class (and its UI * components) convert basic user interface actions into higher level actions * that more cleanly encapsulate the action desired by the user and they pass * those actions on to their controller. The controller then performs abstract * processing based on the users desires and the changing state of the * application and calls back to the panel to affect changes to the display. * * <p> Controllers also support the notion of scope. When a panel wishes to * post an action, it doesn't do it directly to the controller. Instead it does * it using a controller utility function called {@link #postAction}, which * searches up the user interface hierarchy looking for a component that * implements {@link ControllerProvider} which it will use to obtain the * controller "in scope" for that component. That controller is requested to * handle the action, but if it cannot handle the action, the next controller * up the chain is located and requested to process the action. * * <p> In this manner, a hierarchy of controllers (often just two: one * application wide and one for whatever particular mode the application is in * at the moment) can provide a set of services that are available to all user * interface elements in the entire application and in a way that doesn't * require tight connectedness between the UI elements and the controllers. */ public abstract class Controller implements ActionListener { /** * This action listener can be wired up to any action event generator * and it will take care of forwarding that event on to the controller * in scope for the component that generated the action event. * * <p> For example, wiring a button up to a dispatcher would look like * so: * * <pre> * JButton button = new JButton("Do thing"); * button.setActionCommand("dothing"); * button.addActionListener(Controller.DISPATCHER); * </pre> * * or, use the provided convenience function: * * <pre> * JButton button = * Controller.createActionButton("Do thing", "dothing"); * </pre> * * The controllers in scope would then be requested (in order) to * process the <code>dothing</code> action whenever the button was * clicked. */ public static final ActionListener DISPATCHER = new ActionListener() { public void actionPerformed (ActionEvent event) { Controller.postAction(event); } }; /** * Posts the specified action to the nearest controller in scope. The * controller search begins with the source component of the action and * traverses up the component tree looking for a controller to handle the * action. The controller location and action event processing is * guaranteed to take place on the AWT thread regardless of what thread * calls <code>postAction</code> and that processing will not occur * immediately but is instead appended to the AWT event dispatch queue for * processing. */ public static void postAction (ActionEvent action) { // slip things onto the event queue for later EventQueue.invokeLater(new ActionInvoker(action)); } /** * Like {@link #postAction(ActionEvent)} except that it constructs the * action event for you with the supplied source component and string * command. The <code>id</code> of the event will always be set to * zero. */ public static void postAction (Component source, String command) { // slip things onto the event queue for later ActionEvent event = new ActionEvent(source, 0, command); EventQueue.invokeLater(new ActionInvoker(event)); } /** * Like {@link #postAction(ActionEvent)} except that it constructs a * {@link CommandEvent} with the supplied source component, string * command and argument. */ public static void postAction ( Component source, String command, Object argument) { // slip things onto the event queue for later CommandEvent event = new CommandEvent(source, command, argument); EventQueue.invokeLater(new ActionInvoker(event)); } /** * Creates a button and configures it with the specified label and action * command and adds {@link #DISPATCHER} as an action listener. */ public static JButton createActionButton (String label, String command) { JButton button = new JButton(label); configureAction(button, command); return button; } /** * Configures the supplied button with the {@link #DISPATCHER} action * listener and the specified action command (which, if it is a method name * will be looked up dynamically on the matching controller). */ public static void configureAction (AbstractButton button, String action) { button.setActionCommand(action); button.addActionListener(DISPATCHER); } /** * Lets this controller know about the panel that it is controlling. */ public void setControlledPanel (final JComponent panel) { panel.addHierarchyListener(new HierarchyListener() { public void hierarchyChanged (HierarchyEvent e) { boolean nowShowing = panel.isDisplayable(); //System.err.println("Controller." + Controller.this + // " nowShowing=" + nowShowing + // ", wasShowing=" + _showing); if (_showing != nowShowing) { _showing = nowShowing; if (_showing) { wasAdded(); } else { wasRemoved(); } } } boolean _showing = false; }); } /** * Called when the panel controlled by this controller was added to * the user interface hierarchy. This assumes that the controlled * panel made itself known to the controller via {@link * #setControlledPanel} (which is done automatically by {@link * ControlledPanel} and derived classes). */ public void wasAdded () { } /** * Called when the panel controlled by this controller was removed * from the user interface hierarchy. This assumes that the controlled * panel made itself known to the controller via {@link * #setControlledPanel} (which is done automatically by {@link * ControlledPanel} and derived classes). */ public void wasRemoved () { } /** * Instructs this controller to process this action event. When an action * is posted by a user interface element, it will be posted to the * controller in closest scope for that element. If that controller handles * the event, it should return true from this method to indicate that * processing should stop. If it cannot handle the event, it can return * false to indicate that the event should be propagated to the next * controller up the chain. * * <p> This method will be called on the AWT thread, so the controller can * safely manipulate user interface components while handling an action. * However, this means that action handling cannot block and should not * take an undue amount of time. If the controller needs to perform * complicated, lengthy processing it should do so with a separate thread, * for example via {@link com.samskivert.swing.util.TaskMaster}. * * <p> The default implementation of this method will reflect on the * controller class, looking for a method that matches the name of the * action event. For example, if the action was "exit" a method named * "exit" would be sought. A handler method must provide one of three * signatures: one accepting no arguments, one including only a reference * to the source object, or one including the source object and an extra * argument (which can be used only if the action event is an instance of * {@link CommandEvent}). For example: * * <pre> * public void cancelClicked (Object source); * public void textEntered (Object source, String text); * </pre> * * The arguments to the method can be as specific or as generic as desired * and reflection will perform the appropriate conversions at runtime. For * example, a method could be declared like so: * * <pre> * public void cancelClicked (JButton source); * </pre> * * One would have to ensure that the only action events generated with the * action command string "cancelClicked" were generated by JButton * instances if such a signature were used. * * @param action the action to be processed. * * @return true if the action was processed, false if it should be * propagated up to the next controller in scope. */ public boolean handleAction (ActionEvent action) { Object arg = null; if (action instanceof CommandEvent) { arg = ((CommandEvent)action).getArgument(); } return handleAction(action.getSource(), action.getActionCommand(), arg); } /** * A version of {@link #handleAction(ActionEvent)} with the parameters * broken out so that it can be used by non-Swing interface toolkits. */ public boolean handleAction (Object source, String action, Object arg) { Method method = null; Object[] args = null; try { // look for the appropriate method Method[] methods = getClass().getMethods(); int mcount = methods.length; for (int i = 0; i < mcount; i++) { if (methods[i].getName().equals(action) || // handle our old style of prepending "handle" methods[i].getName().equals("handle" + action)) { // see if we can generate the appropriate arguments args = generateArguments(methods[i], source, arg); // if we were able to, go ahead and use this method if (args != null) { method = methods[i]; break; } } } } catch (Exception e) { Log.warning("Error searching for action handler method " + "[controller=" + this + ", action=" + action + "]."); return false; } try { if (method != null) { method.invoke(this, args); return true; } else { return false; } } catch (Exception e) { Log.warning("Error invoking action handler [controller=" + this + ", action=" + action + "]."); Log.logStackTrace(e); // even though we choked, we still "handled" the action return true; } } /** * A convenience method for constructing and immediately handling an * event on this controller (via {@link #handleAction(ActionEvent)}). * * @return true if the controller knew how to handle the action, false * otherwise. */ public boolean handleAction (Component source, String command) { return handleAction(new ActionEvent(source, 0, command)); } /** * A convenience method for constructing and immediately handling an * event on this controller (via {@link #handleAction(ActionEvent)}). * * @return true if the controller knew how to handle the action, false * otherwise. */ public boolean handleAction (Component source, String command, Object arg) { return handleAction(new CommandEvent(source, command, arg)); } // documentation inherited from interface ActionListener public void actionPerformed (ActionEvent event) { handleAction(event); } /** * Used by {@link #handleAction} to generate arguments to the action * handler method. */ protected Object[] generateArguments ( Method method, Object source, Object argument) { // figure out what sort of arguments are required by the method Class[] atypes = method.getParameterTypes(); if (atypes == null || atypes.length == 0) { return new Object[0]; } else if (atypes.length == 1) { return new Object[] { source }; } else if (atypes.length == 2) { if (argument != null) { return new Object[] { source, argument }; } Log.warning("Unable to map argumentless event to handler method " + "that requires an argument [controller=" + this + ", method=" + method + ", source=" + source + "]."); } // we would have handled it, but we couldn't return null; } /** * This class is used to dispatch action events to controllers within * the context of the AWT event dispatch mechanism. */ protected static class ActionInvoker implements Runnable { public ActionInvoker (ActionEvent action) { _action = action; } public void run () { // do some sanity checking on the source Object src = _action.getSource(); if (src == null || !(src instanceof Component)) { Log.warning("Requested to dispatch action on " + "non-component source [source=" + src + ", action=" + _action + "]."); return; } // scan up the component hierarchy looking for a controller on // which to dispatch this action for (Component source = (Component)src; source != null; source = source.getParent()) { if (!(source instanceof ControllerProvider)) { continue; } Controller ctrl = ((ControllerProvider)source).getController(); if (ctrl == null) { Log.warning("Provider returned null controller " + "[provider=" + source + "]."); continue; } try { // if the controller returns true, it handled the // action and we can call this business done if (ctrl.handleAction(_action)) { return; } } catch (Exception e) { Log.warning("Controller choked on action " + "[ctrl=" + ctrl + ", action=" + _action + "]."); Log.logStackTrace(e); } } // if we got here, we didn't find a controller Log.warning("Unable to find a controller to process action " + "[action=" + _action + "]."); } protected ActionEvent _action; } }
// $Id: Comparators.java,v 1.3 2002/02/19 03:38:06 mdb Exp $ // samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.util; import java.util.Comparator; /** * A repository for standard comparators. */ public class Comparators { /** * A comparator that compares the toString() value of all objects case insensitively. */ public static final Comparator<Object> LEXICAL_CASE_INSENSITIVE = new Comparator<Object>() { public int compare (Object o1, Object o2) { if (o1 == o2) { // catches null == null return 0; } else if (o1 == null) { return 1; } else if (o2 == null) { return -1; } // now that we've filtered all nulls, compare the toString()s return String.CASE_INSENSITIVE_ORDER.compare( o1.toString(), o2.toString()); } }; /** * A comparator that compares {@link Comparable} instances. */ public static final Comparator<Object> COMPARABLE = new Comparator<Object>() { @SuppressWarnings("unchecked") public int compare (Object o1, Object o2) { if (o1 == o2) { // catches null == null return 0; } else if (o1 == null) { return 1; } else if (o2 == null) { return -1; } return ((Comparable<Object>)o1).compareTo(o2); // null-free } }; /** * Compares two integers in an overflow safe manner. */ public static int compareTo (int value1, int value2) { return (value1 < value2 ? -1 : (value1 == value2 ? 0 : 1)); } }
package org.innovateuk.ifs.competition.domain; import org.innovateuk.ifs.application.domain.Application; import org.innovateuk.ifs.application.domain.Question; import org.innovateuk.ifs.application.domain.Section; import org.innovateuk.ifs.competition.mapper.CompetitionMapper; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import java.math.BigDecimal; import java.math.BigInteger; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; import static java.time.temporal.ChronoUnit.SECONDS; import static junit.framework.TestCase.assertFalse; import static org.innovateuk.ifs.competition.resource.CompetitionStatus.*; import static org.junit.Assert.*; public class CompetitionTest { private Competition competition; @Mock CompetitionMapper competitionMapper; private Long id; private List<Application> applications; private List<Question> questions; private List<Section> sections; private String name; private ZonedDateTime startDate; private ZonedDateTime endDate; private ZonedDateTime registrationDate; private Integer maxResearchRatio; private Integer academicGrantPercentage; private String budgetCode; private String activityCode; private String funder; private BigDecimal funderBudget; @Before public void setUp() throws Exception { id = 0L; name = "testCompetitionName"; startDate = ZonedDateTime.now().minusDays(5); registrationDate = startDate.plusDays(4); endDate = startDate.plusDays(15); maxResearchRatio = 10; academicGrantPercentage = 30; budgetCode = "BudgetCode"; activityCode = "ActivityCode"; funder = "Funder"; funderBudget = new BigDecimal(0); sections = new ArrayList<>(); sections.add(new Section()); sections.add(new Section()); sections.add(new Section()); competition = new Competition(id, applications, questions, sections, name, startDate, endDate, registrationDate); competition.setMaxResearchRatio(maxResearchRatio); competition.setAcademicGrantPercentage(academicGrantPercentage); competition.setBudgetCode(budgetCode); competition.setActivityCode(activityCode); competition.setFunders(getTestFunders(competition)); } private List<CompetitionFunder> getTestFunders(Competition competition) { List<CompetitionFunder> returnList = new ArrayList<>(); CompetitionFunder Funder1 = new CompetitionFunder(); Funder1.setId(1L); Funder1.setCompetition(competition); Funder1.setFunder("Funder1"); Funder1.setFunderBudget(BigInteger.valueOf(1)); Funder1.setCoFunder(false); returnList.add(Funder1); CompetitionFunder coFunder1 = new CompetitionFunder(); coFunder1.setId(1L); coFunder1.setCompetition(competition); coFunder1.setFunder("CoFunder1"); coFunder1.setFunderBudget(BigInteger.valueOf(1)); coFunder1.setCoFunder(true); returnList.add(coFunder1); CompetitionFunder coFunder2 = new CompetitionFunder(); coFunder2.setId(2L); coFunder2.setCompetition(competition); coFunder2.setFunder("CoFunder2"); coFunder2.setFunderBudget(BigInteger.valueOf(2)); coFunder1.setCoFunder(true); returnList.add(coFunder2); return returnList; } @Test public void competitionShouldReturnCorrectAttributeValues() throws Exception { assertEquals(competition.getId(), id); assertEquals(competition.getName(), name); assertEquals(competition.getSections(), sections); assertEquals(competition.getMaxResearchRatio(), maxResearchRatio); assertEquals(competition.getAcademicGrantPercentage(), academicGrantPercentage); assertEquals(competition.getRegistrationDate(), registrationDate.truncatedTo(SECONDS)); assertEquals(competition.getBudgetCode(), budgetCode); assertEquals(competition.getActivityCode(), activityCode); assertEquals(competition.getFunders().size(), getTestFunders(competition).size()); } @Test public void competitionStatusOpen() { assertEquals(OPEN, competition.getCompetitionStatus()); } @Test public void competitionStatusReadyToOpen() { competition.setStartDate(ZonedDateTime.now().plusDays(1)); assertEquals(READY_TO_OPEN, competition.getCompetitionStatus()); } @Test public void competitionClosingSoon() { CompetitionResource competitionResource = new CompetitionResource(); competitionResource.setCompetitionStatus(OPEN); competitionResource.setStartDate(ZonedDateTime.now().minusDays(4)); competitionResource.setEndDate(ZonedDateTime.now().plusHours(1)); assertTrue(competitionResource.isClosingSoon()); } @Test public void competitionNotClosingSoon() { CompetitionResource competitionResource = new CompetitionResource(); competitionResource.setCompetitionStatus(OPEN); competitionResource.setStartDate(ZonedDateTime.now().minusDays(4)); competitionResource.setEndDate(ZonedDateTime.now().plusHours(3).plusMinutes(1)); assertFalse(competitionResource.isClosingSoon()); } @Test public void competitionStatusInAssessment() { competition.setEndDate(ZonedDateTime.now().minusDays(1)); competition.notifyAssessors(ZonedDateTime.now().minusDays(1)); competition.setFundersPanelDate(ZonedDateTime.now().plusDays(1)); assertEquals(IN_ASSESSMENT, competition.getCompetitionStatus()); } @Test public void competitionStatusInAssessment_notCompetitionClosed() throws Exception { competition.setEndDate(ZonedDateTime.now().minusDays(3)); competition.notifyAssessors(ZonedDateTime.now().minusDays(2)); competition.closeAssessment(ZonedDateTime.now().minusDays(1)); try { competition.notifyAssessors(ZonedDateTime.now()); } catch (IllegalStateException e) { assertEquals("Tried to notify assessors when in competitionStatus=FUNDERS_PANEL. " + "Applications can only be distributed when competitionStatus=CLOSED", e.getMessage()); } } @Test public void competitionStatusInAssessment_alreadyInAssessment() throws Exception { competition.setEndDate(ZonedDateTime.now().minusDays(3)); competition.notifyAssessors(ZonedDateTime.now().minusDays(2)); competition.notifyAssessors(ZonedDateTime.now().minusDays(1)); assertEquals(IN_ASSESSMENT, competition.getCompetitionStatus()); } @Test public void competitionStatusFundersPanelAsFundersPanelEndDateAbsent() { competition.setEndDate(ZonedDateTime.now().minusDays(5)); competition.notifyAssessors(ZonedDateTime.now().minusDays(4)); competition.closeAssessment(ZonedDateTime.now().minusDays(3)); competition.setFundersPanelDate(ZonedDateTime.now().minusDays(2)); assertEquals(FUNDERS_PANEL, competition.getCompetitionStatus()); } @Test public void competitionStatusFundersPanelAsFundersPanelEndDatePresentButInFuture() { competition.setEndDate(ZonedDateTime.now().minusDays(6)); competition.setAssessorAcceptsDate(ZonedDateTime.now().minusDays(5)); competition.notifyAssessors(ZonedDateTime.now().minusDays(4)); competition.closeAssessment(ZonedDateTime.now().minusDays(3)); competition.setFundersPanelDate(ZonedDateTime.now().minusDays(2)); competition.setFundersPanelEndDate(ZonedDateTime.now().plusDays(1)); assertEquals(FUNDERS_PANEL, competition.getCompetitionStatus()); } @Test public void competitionStatusAssessorFeedback() { competition.setEndDate(ZonedDateTime.now().minusDays(6)); competition.setAssessorAcceptsDate(ZonedDateTime.now().minusDays(5)); competition.notifyAssessors(ZonedDateTime.now().minusDays(4)); competition.closeAssessment(ZonedDateTime.now().minusDays(3)); competition.setFundersPanelDate(ZonedDateTime.now().minusDays(2)); competition.setFundersPanelEndDate(ZonedDateTime.now().minusDays(1)); assertEquals(ASSESSOR_FEEDBACK, competition.getCompetitionStatus()); } @Test public void competitionStatusFeedbackReleased() { competition.setEndDate(ZonedDateTime.now().minusDays(7)); competition.setAssessorAcceptsDate(ZonedDateTime.now().minusDays(6)); competition.notifyAssessors(ZonedDateTime.now().minusDays(5)); competition.closeAssessment(ZonedDateTime.now().minusDays(4)); competition.setFundersPanelDate(ZonedDateTime.now().minusDays(3)); competition.setFundersPanelEndDate(ZonedDateTime.now().minusDays(2)); competition.setReleaseFeedbackDate(ZonedDateTime.now().minusDays(1)); competition.releaseFeedback(ZonedDateTime.now().minusDays(1)); assertEquals(PROJECT_SETUP, competition.getCompetitionStatus()); } }
package com.sun.facelets; import java.io.IOException; import java.net.URL; import javax.el.ELContext; import javax.el.ELException; import javax.el.ExpressionFactory; import javax.el.FunctionMapper; import javax.el.VariableMapper; import javax.faces.FacesException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; /** * Context representative of a single request from a Facelet * * @author Jacob Hookom * @version $Id: FaceletContext.java,v 1.3 2005-07-20 05:00:28 jhook Exp $ */ public abstract class FaceletContext extends ELContext { /** * The current FacesContext bound to this "request" * * @return cannot be null */ public abstract FacesContext getFacesContext(); /** * Generate a unique ID for the passed String * * @param base * @return a unique ID given the passed base */ public abstract String generateUniqueId(String base); /** * The ExpressionFactory to use within the Facelet this context is executing * upon. * * @return cannot be null */ public abstract ExpressionFactory getExpressionFactory(); /** * Set the VariableMapper to use in EL evaluation/creation * * @param varMapper */ public abstract void setVariableMapper(VariableMapper varMapper); /** * Set the FunctionMapper to use in EL evaluation/creation * * @param fnMapper */ public abstract void setFunctionMapper(FunctionMapper fnMapper); /** * Support method which is backed by the current VariableMapper * * @param name * @param value */ public abstract void setAttribute(String name, Object value); /** * Support method which is backed by the current VariableMapper * * @param name * @return an Object specified for that name */ public abstract Object getAttribute(String name); /** * Include another Facelet defined at some path, relative to the executing * context, not the current Facelet (same as include directive in JSP) * * @param parent * @param relativePath * @throws IOException * @throws FaceletException * @throws FacesException * @throws ELException */ public abstract void includeFacelet(UIComponent parent, String relativePath) throws IOException, FaceletException, FacesException, ELException; /** * Include another Facelet defined at some path, absolute to this * ClassLoader/OS * * @param parent * @param absolutePath * @throws IOException * @throws FaceletException * @throws FacesException * @throws ELException */ public abstract void includeFacelet(UIComponent parent, URL absolutePath) throws IOException, FaceletException, FacesException, ELException; }
// $Id: MediaPanel.java,v 1.4 2002/04/27 04:57:05 mdb Exp $ package com.threerings.media; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Shape; import javax.swing.JComponent; import javax.swing.RepaintManager; import javax.swing.SwingUtilities; import javax.swing.event.AncestorEvent; import java.util.ArrayList; import java.util.List; import com.samskivert.swing.event.AncestorAdapter; import com.samskivert.util.StringUtil; import com.threerings.media.FrameManager; import com.threerings.media.Log; import com.threerings.media.animation.Animation; import com.threerings.media.animation.AnimationManager; import com.threerings.media.sprite.Sprite; import com.threerings.media.sprite.SpriteManager; public class MediaPanel extends JComponent implements FrameParticipant, MediaConstants { /** * Constructs an animated panel. */ public MediaPanel (FrameManager framemgr) { // keep this for later _framemgr = framemgr; // create our region manager _remgr = new RegionManager(); // create our animation and sprite managers _animmgr = new AnimationManager(_remgr); _spritemgr = new SpriteManager(_remgr); // we don't want to hear about repaints setIgnoreRepaint(true); // participate in the frame when we're visible addAncestorListener(new AncestorAdapter() { public void ancestorAdded (AncestorEvent event) { _framemgr.registerFrameParticipant(MediaPanel.this); } public void ancestorRemoved (AncestorEvent event) { _framemgr.removeFrameParticipant(MediaPanel.this); } }); } /** * Instructs the view to scroll by the specified number of pixels * (which can be negative if it should scroll in the negative x or y * direction) in the specified number of milliseconds. While the view * is scrolling, derived classes can hear about the scrolled * increments by overriding {@link #viewWillScroll} and they can find * out when scrolling is complete by overriding {@link * #viewFinishedScrolling}. * * @param dx the number of pixels in the x direction to scroll. * @param dy the number of pixels in the y direction to scroll. * @param millis the number of milliseconds in which to do it. The * scrolling is calculated such that we will "drop frames" in order to * scroll the necessary distance by the requested time. */ public void setScrolling (int dx, int dy, long millis) { // if dx and dy are zero, we've got nothing to do if (dx == 0 && dy == 0) { return; } // set our scrolling parameters _scrollx = dx; _scrolly = dy; _last = System.currentTimeMillis(); _ttime = _last + millis; // Log.info("Scrolling [dx=" + dx + ", dy=" + dy + // ", millis=" + millis + "ms."); } /** * Pauses the sprites and animations that are currently active on this * media panel. Also stops listening to the frame tick while paused. */ public void setPaused (boolean paused) { // sanity check if ((paused && (_pauseTime != 0)) || (!paused && (_pauseTime == 0))) { Log.warning("Requested to pause when paused or vice-versa " + "[paused=" + paused + "]."); return; } if (paused) { // stop listening to the frame tick _framemgr.removeFrameParticipant(this); // make a note of our pause time _pauseTime = System.currentTimeMillis(); } else { // start listening to the frame tick once again _framemgr.registerFrameParticipant(this); // let the animation and sprite managers know that we just // warped into the future long delta = System.currentTimeMillis() - _pauseTime; _animmgr.fastForward(delta); _spritemgr.fastForward(delta); // clear out our pause time _pauseTime = 0; } } /** * Returns a reference to the region manager that is used to * accumulate dirty regions each frame. */ public RegionManager getRegionManager () { return _remgr; } /** * Adds a sprite to this panel. */ public void addSprite (Sprite sprite) { _spritemgr.addSprite(sprite); } /** * Removes a sprite from this panel. */ public void removeSprite (Sprite sprite) { _spritemgr.removeSprite(sprite); } /** * Adds an animation to this panel. */ public void addAnimation (Animation anim) { _animmgr.registerAnimation(anim); } /** * Removes an animation from this panel. */ public void removeAnimation (Animation anim) { _animmgr.unregisterAnimation(anim); } // documentation inherited public void doLayout () { super.doLayout(); // figure out our viewport offsets Dimension size = getSize(), vsize = getViewSize(); _tx = (vsize.width - size.width)/2; _ty = (vsize.height - size.height)/2; // Log.info("Size: " + size + ", vsize: " + vsize + // ", tx: " + _tx + ", ty: " + _ty + "."); } // documentation inherited public void invalidate () { super.invalidate(); // invalidate our bounds with the region manager _remgr.invalidateRegion(_tx, _ty, getWidth(), getHeight()); } // documentation inherited from interface public void tick (long tickStamp) { int width = getWidth(), height = getHeight(); // if scrolling is enabled, determine the scrolling delta to be // used and do the business _dx = 0; _dy = 0; if (_ttime != 0) { // if we've blown past our allotted time, we want to scroll // the rest of the way if (tickStamp > _ttime) { _dx = _scrollx; _dy = _scrolly; // Log.info("Scrolling rest [dx=" + _dx + ", dy=" + _dy + "]."); } else { // otherwise figure out how many milliseconds have gone by // since we last scrolled and scroll the requisite amount float dt = (float)(tickStamp - _last); float rt = (float)(_ttime - _last); // our delta is the remaining distance multiplied by the // time delta divided by the remaining time _dx = Math.round((float)(_scrollx * dt) / rt); _dy = Math.round((float)(_scrolly * dt) / rt); // Log.info("Scrolling delta [dt=" + dt + ", rt=" + rt + // ", dx=" + _dx + ", dy=" + _dy + "]."); } // and add invalid rectangles for the exposed areas if (_dx > 0) { _remgr.invalidateRegion(width - _dx + _tx, _ty, _dx, height); } else if (_dx < 0) { _remgr.invalidateRegion(_tx, _ty, -_dx, height); } if (_dy > 0) { _remgr.invalidateRegion(_tx, height - _dy + _ty, width, _dy); } else if (_dy < 0) { _remgr.invalidateRegion(_tx, _ty, width, -_dy); } // make sure we're actually scrolling before telling people // about it if (_dx != 0 || _dy != 0) { // if we are working with a sprite manager, let it know // that we're about to scroll out from under its sprites // and allow it to provide us with more dirty rects if (_spritemgr != null) { _spritemgr.viewWillScroll(_dx, _dy); } // let our derived classes do whatever they need to do to // prepare to be scrolled viewWillScroll(_dx, _dy, tickStamp); // keep track of the last time we scrolled _last = tickStamp; // subtract our scrolled deltas from the distance remaining _scrollx -= _dx; _scrolly -= _dy; // if we've reached our desired position, finish the job if (_scrollx == 0 && _scrolly == 0) { _ttime = 0; viewFinishedScrolling(); } } } // now tick our animations and sprites _animmgr.tick(tickStamp); _spritemgr.tick(tickStamp); // make a note that the next paint will correspond to a call to // tick() _tickPaintPending = true; } /** * We want to be painted every tick. */ public Component getComponent () { return this; } // documentation inherited public void repaint (long tm, int x, int y, int width, int height) { _remgr.invalidateRegion(_tx + x, _ty + y, width, height); } // documentation inherited public void paint (Graphics g) { Graphics2D gfx = (Graphics2D)g; int width = getWidth(), height = getHeight(); // no use in painting if we're not showing or if we've not yet // been validated if (!isValid() || !isShowing()) { return; } // if this isn't a tick paint, then we need to grab the clipping // rectangle and mark it as dirty if (!_tickPaintPending) { Shape clip = g.getClip(); Rectangle dirty = (clip == null) ? getBounds() : clip.getBounds(); dirty.translate(_tx, _ty); _remgr.invalidateRegion(dirty); } else { _tickPaintPending = false; } // if we didn't scroll and have no invalid rects, there's no need // to repaint anything if (!_remgr.haveDirtyRegions() && _dx == 0 && _dy == 0) { return; } // we may need to do some scrolling if (_dx != 0 || _dy != 0) { gfx.copyArea(0, 0, getWidth(), getHeight(), -_dx, -_dy); } // get our dirty rectangles Rectangle[] dirty = _remgr.getDirtyRegions(); int dcount = dirty.length; // clip the dirty regions to the viewport for (int ii = 0; ii < dcount; ii++) { SwingUtilities.computeIntersection( _tx, _ty, width, height, dirty[ii]); } // translate into happy space gfx.translate(-_tx, -_ty); // paint the behind the scenes stuff paintBehind(gfx, dirty); // paint back sprites and animations for (int ii = 0; ii < dcount; ii++) { paintBits(gfx, AnimationManager.BACK, dirty[ii]); } // paint the between the scenes stuff paintBetween(gfx, dirty); // paint front sprites and animations for (int ii = 0; ii < dcount; ii++) { paintBits(gfx, AnimationManager.FRONT, dirty[ii]); } // paint anything in front paintInFront(gfx, dirty); // translate back out of happy space gfx.translate(_tx, _ty); } /** * Paints behind all sprites and animations. The supplied list of * invalid rectangles should be redrawn in the supplied graphics * context. The rectangles will be in the view coordinate system * (which may differ from screen coordinates, see {@link * #getViewSize}. Sub-classes should override this method to do the * actual rendering for their display. */ protected void paintBehind (Graphics2D gfx, Rectangle[] dirtyRects) { } /** * Paints between the front and back layer of sprites and animations. * The supplied list of invalid rectangles should be redrawn in the * supplied graphics context. The rectangles will be in the view * coordinate system (which may differ from screen coordinates, see * {@link #getViewSize}. Sub-classes should override this method to do * the actual rendering for their display. */ protected void paintBetween (Graphics2D gfx, Rectangle[] dirtyRects) { } /** * Paints in front of all sprites and animations. The supplied list of * invalid rectangles should be redrawn in the supplied graphics * context. The rectangles will be in the view coordinate system * (which may differ from screen coordinates, see {@link * #getViewSize}. Sub-classes should override this method to do the * actual rendering for their display. */ protected void paintInFront (Graphics2D gfx, Rectangle[] dirtyRects) { } /** * Renders the sprites and animations that intersect the supplied * clipping region in the specified layer. Derived classes can * override this method if they need to do custom sprite or animation * rendering (if they need to do special sprite z-order handling, for * example). This method also takes care of setting the clipping * region in the graphics object which an overridden method should * also do to preserve performance. */ protected void paintBits (Graphics2D gfx, int layer, Rectangle clip) { Shape oclip = gfx.getClip(); gfx.clipRect(clip.x, clip.y, clip.width, clip.height); _animmgr.renderAnimations(gfx, layer, clip); _spritemgr.renderSprites(gfx, layer, clip); gfx.setClip(oclip); } /** * This is called, when the view is scrolling, during the tick * processing phase. The animated panel will take care of scrolling * the contents of the offscreen buffer when the time comes to render, * but the derived class will need to do whatever is necessary to * prepare to repaint the exposed regions as well as update its own * internal state accordingly. * * @param dx the distance (in pixels) that the view will scroll in the * x direction. * @param dy the distance (in pixels) that the view will scroll in the * y direction. * @param now the current time, provided because we have it and * scrolling views are likely to want to use it in calculating stuff. */ protected void viewWillScroll (int dx, int dy, long tickStamp) { // nothing to do here } /** * Called during the same frame that we scrolled into the final * desired position. This method is called after {@link * #viewWillScroll} is called with the final scrolling deltas. */ protected void viewFinishedScrolling () { // Log.info("viewFinishedScrolling"); } /** * Derived classes that wish to operate in a coordinate system based * on a view size that is larger or smaller than the viewport size * (the actual dimensions of the animated panel) can override this * method and return the desired size of the view. The animated panel * will take this size into account and translate into the view * coordinate system before calling {@link #render}. */ protected Dimension getViewSize () { return getSize(); } /** The frame manager with whom we register. */ protected FrameManager _framemgr; /** The animation manager in use by this panel. */ protected AnimationManager _animmgr; /** The sprite manager in use by this panel. */ protected SpriteManager _spritemgr; /** Used to accumulate and merge dirty regions on each tick. */ protected RegionManager _remgr; /** Our viewport offsets. */ protected int _tx, _ty; /** How many pixels we have left to scroll. */ protected int _scrollx, _scrolly; /** Our scroll offsets for this frame tick. */ protected int _dx, _dy; /** The time at which we expect to stop scrolling. */ protected long _ttime; /** The last time we were scrolled. */ protected long _last; /** Used to correlate tick()s with paint()s. */ protected boolean _tickPaintPending = false; /** Used to track the clock time at which we were paused. */ protected long _pauseTime; }
package org.jaxen.expr; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jaxen.Context; import org.jaxen.ContextSupport; import org.jaxen.JaxenException; import org.jaxen.UnsupportedAxisException; import org.jaxen.expr.iter.IterableAxis; import org.jaxen.saxpath.Axis; public abstract class DefaultStep implements Step { private IterableAxis axis; private PredicateSet predicates; public DefaultStep(IterableAxis axis, PredicateSet predicates) { this.axis = axis; this.predicates = predicates; } public void addPredicate(Predicate predicate) { this.predicates.addPredicate(predicate); } public List getPredicates() { return this.predicates.getPredicates(); } public PredicateSet getPredicateSet() { return this.predicates; } public int getAxis() { return this.axis.value(); } public IterableAxis getIterableAxis() { return this.axis; } public String getAxisName() { return Axis.lookup(getAxis()); } public String getText() { return this.predicates.getText(); } public String toString() { return getIterableAxis() + " " + super.toString(); } public void simplify() { this.predicates.simplify(); } public Iterator axisIterator(Object contextNode, ContextSupport support) throws UnsupportedAxisException { return getIterableAxis().iterator(contextNode, support); } public List evaluate(final Context context) throws JaxenException { final List contextNodeSet = context.getNodeSet(); final IdentitySet unique = new IdentitySet(); final int contextSize = contextNodeSet.size(); // ???? try linked lists instead? // ???? initial size for these? final ArrayList interimSet = new ArrayList(); final ArrayList newNodeSet = new ArrayList(); final ContextSupport support = context.getContextSupport(); // ???? use iterator instead???? for ( int i = 0 ; i < contextSize ; ++i ) { Object eachContextNode = contextNodeSet.get( i ); Iterator axisNodeIter = axis.iterator(eachContextNode, support); while ( axisNodeIter.hasNext() ) { Object eachAxisNode = axisNodeIter.next(); if ( matches( eachAxisNode, support ) ) { if ( ! unique.contains( eachAxisNode ) ) { unique.add( eachAxisNode ); interimSet.add( eachAxisNode ); } } } newNodeSet.addAll(getPredicateSet().evaluatePredicates( interimSet, support )); interimSet.clear(); } return newNodeSet; } }
package com.microsoft.azure.eventhubs.exceptioncontracts; import java.util.concurrent.ExecutionException; import org.junit.Assume; import org.junit.Test; import com.microsoft.azure.eventhubs.*; import com.microsoft.azure.eventhubs.lib.*; import com.microsoft.azure.servicebus.*; public class ReceiverEpoch extends TestBase { @Test (expected = ReceiverDisconnectedException.class) public void testEpochReceiver() throws Throwable { Assume.assumeTrue(TestBase.isServiceRun()); TestEventHubInfo eventHubInfo = TestBase.checkoutTestEventHub(); try { ConnectionStringBuilder connectionString = TestBase.getConnectionString(eventHubInfo); EventHubClient ehClient = EventHubClient.createFromConnectionString(connectionString.toString()).get(); try { String cgName = eventHubInfo.getRandomConsumerGroup(); String partitionId = "0"; long epoch = 345632; PartitionReceiver receiver = ehClient.createEpochReceiver(cgName, partitionId, PartitionReceiver.StartOfStream, false, epoch).get(); receiver.setReceiveHandler(new EventCounter()); try { ehClient.createEpochReceiver(cgName, partitionId, epoch - 10).get(); } catch(ExecutionException exp) { throw exp.getCause(); } } finally { ehClient.close(); } } finally { TestBase.checkinTestEventHub(eventHubInfo.getName()); } } public static final class EventCounter extends PartitionReceiveHandler { private long count; public EventCounter() { count = 0; } @Override public void onReceive(Iterable<EventData> events) { for(EventData event: events) { System.out.println(String.format("Counter: %s, Offset: %s, SeqNo: %s, EnqueueTime: %s, PKey: %s", this.count, event.getSystemProperties().getOffset(), event.getSystemProperties().getSequenceNumber(), event.getSystemProperties().getEnqueuedTime(), event.getSystemProperties().getPartitionKey())); } count++; } @Override public void onError(Exception exception) { } } }
package de.uni_tuebingen.ub.ixTheo.bibleRangeSearch; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.Weight; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; class BibleRangeQuery extends Query { private static Logger logger = LoggerFactory.getLogger(BibleRangeQuery.class); private Query query; private BibleRange[] ranges; BibleRangeQuery(final Query query, final BibleRange[] ranges) { this.query = query; this.ranges = ranges; } @Override public Weight createWeight(final IndexSearcher searcher, final boolean needsScores, final float boost) throws IOException { // query rewriting is necessary before createWeight delivers any usable result. // rewrite needs to be called multiple times, until derived Query class no longer changes. Query rewrite_query = BibleRangeQuery.this.query; Query rewritten_query = rewrite_query; do { rewrite_query = rewritten_query; rewritten_query = rewrite_query.rewrite(searcher.getIndexReader()); } while(rewrite_query.getClass() != rewritten_query.getClass()); final Weight weight = rewritten_query.createWeight(searcher, needsScores, boost); return new BibleRangeWeight(this, ranges, weight); } @Override public String toString(String default_field) { return query.toString(default_field); } // The standard toString() in the parent class is final so we needed to give this a different name. public String asString() { return "BibleRangeQuery(Query:" + query.toString() + ", Ranges:" + Range.toString(ranges) + ")"; } @Override public boolean equals(final Object obj) { if (!(obj instanceof BibleRangeQuery)) return false; final BibleRangeQuery otherQuery = (BibleRangeQuery)obj; if (otherQuery.ranges.length != ranges.length) return false; for (int i = 0; i < ranges.length; ++i) { if (!ranges[i].equals(otherQuery.ranges[i])) return false; } return true; } @Override public int hashCode() { int combinedHashCode = 0; for (final BibleRange range : ranges) combinedHashCode ^= range.hashCode(); return combinedHashCode; } }
package jp.ac.kyushu.iarch.sequencediagram.features; import java.util.List; import java.util.TreeMap; import jp.ac.kyushu.iarch.archdsl.archDSL.Model; import jp.ac.kyushu.iarch.basefunction.model.ConnectorTypeCheckModel; import jp.ac.kyushu.iarch.basefunction.model.ConnectorTypeCheckModel.BehaviorModel; import jp.ac.kyushu.iarch.basefunction.model.ConnectorTypeCheckModel.CallModel; import jp.ac.kyushu.iarch.basefunction.reader.ArchModel; import jp.ac.kyushu.iarch.basefunction.reader.XMLreader; import jp.ac.kyushu.iarch.basefunction.utils.PlatformUtils; import jp.ac.kyushu.iarch.basefunction.utils.ProblemViewManager; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.emf.ecore.EObject; import org.eclipse.graphiti.features.IFeatureProvider; import org.eclipse.graphiti.features.context.ICustomContext; import org.eclipse.graphiti.features.custom.AbstractCustomFeature; import org.eclipse.graphiti.mm.pictograms.Diagram; import behavior.AlternativeMessage; import behavior.BehavioredClassifier; import behavior.Lifeline; import behavior.Message; import behavior.MessageEnd; import behavior.MessageOccurrenceSpecification; import behavior.OptionalMessage; public class TypeCheckFeature extends AbstractCustomFeature { public TypeCheckFeature(IFeatureProvider fp) { super(fp); } @Override public String getName() { return "Type Check"; } @Override public String getDescription() { return "Performs type check."; } @Override public boolean canExecute(ICustomContext context) { return true; } @Override public void execute(ICustomContext context) { // Get file of class diagram. IFile diagramFile = PlatformUtils.getActiveFile(); // Get Archface model within the project. IProject project = diagramFile != null ? diagramFile.getProject() : null; if (project == null) { System.out.println("TypeCheckFeature: failed to get active project."); return; } IResource archfile = new XMLreader(project).getArchfileResource(); ArchModel archModel = new ArchModel(archfile); Model model = archModel.getModel(); doTypeCheck(diagramFile, model, getDiagram()); } private static behavior.Object getBehaviorObject(Message message) { MessageEnd recvEvent = message.getReceiveEvent(); if (recvEvent instanceof MessageOccurrenceSpecification) { Lifeline lifeline = ((MessageOccurrenceSpecification) recvEvent).getCovered().get(0); if (lifeline != null) { BehavioredClassifier actor = lifeline.getActor(); if (actor instanceof behavior.Object) { return (behavior.Object) actor; } } } return null; } private static class MessageCallModel extends CallModel { private boolean certain; private boolean optional; private boolean alternative; private MessageCallModel(Message message) { this.certain = false; this.optional = false; this.alternative = false; if (message instanceof AlternativeMessage) { this.alternative = true; boolean first = true; for (Message m : ((AlternativeMessage) message).getMessages()) { setMessage(m, first); first = false; } } else { if (message instanceof OptionalMessage) { this.optional = true; } else { this.certain = true; } setMessage(message, true); } } private boolean setMessage(Message message, boolean setClassName) { behavior.Object bObj = getBehaviorObject(message); if (bObj != null) { methodNames.add(message.getName()); if (setClassName) { className = bObj.getName(); } return true; } else { return false; } } @Override public boolean isCertain() { return certain; } @Override public boolean isOptional() { return optional; } @Override public boolean isAlternative() { return alternative; } } private void doTypeCheck(IFile diagramFile, Model model, Diagram diagram) { // TODO: Change marker type to unique one so as not to remove by other checkers. ProblemViewManager problemViewManager = ProblemViewManager.getInstance(); // Remove previously added markers. problemViewManager.removeProblems(diagramFile, false); // Collect Messages from diagram. // Note that Messages are assumed to: // 1. be direct children of the root // 2. have their order numbers based upon Y coordinates (if not AlternativeMessage) TreeMap<Integer, Message> messageMap = new TreeMap<Integer, Message>(); for (EObject obj : diagram.eResource().getContents()) { if (obj instanceof Message && !(obj instanceof AlternativeMessage)) { Message message = (Message) obj; messageMap.put(message.getMessageOrder(), message); } } // Remove Messages which AlternativeMessage possesses. for (EObject obj : diagram.eResource().getContents()) { if (obj instanceof AlternativeMessage) { AlternativeMessage altMessage = (AlternativeMessage) obj; int altOrder = 0; boolean first = true; for (Message message : altMessage.getMessages()) { int order = message.getMessageOrder(); altOrder = first ? order : Math.min(altOrder, order); first = false; messageMap.remove(order); } messageMap.put(altOrder, altMessage); } } // Create behavior model from Messages BehaviorModel diagramBm = new BehaviorModel(); for (Message message : messageMap.values()) { // Check if message is not received by Actor. if (checkMessage(message)) { MessageCallModel mcm = new MessageCallModel(message); diagramBm.add(mcm); // System.out.println(mcm); } else { System.out.println("WARNING: Message is ignored since it is received by Actor: " + message.getName()); } } // Compare with behavior model on Archmodel. List<ConnectorTypeCheckModel> ctcModels = ConnectorTypeCheckModel.getTypeCheckModel(model, false); boolean foundBehavior = false; for (ConnectorTypeCheckModel ctcModel : ctcModels) { for (BehaviorModel bm : ctcModel.getBehaviorModels()) { if (bm.sameBehavior(diagramBm)) { System.out.println("INFO: Sequence is defined: " + ctcModel.getConnectorName()); foundBehavior = true; } } } if (!foundBehavior) { String msg = "Sequence is not defined in Archcode."; System.out.println("ERROR: " + msg); problemViewManager.createErrorMarker(diagramFile, msg, null); } } private boolean checkMessage(Message message) { if (message instanceof AlternativeMessage) { return checkMessage(((AlternativeMessage) message).getMessages().get(0)); } return getBehaviorObject(message) != null; } @Override public boolean hasDoneChanges() { // If results of type check modify objects, it should return true. return false; } }
package org.neo4j.api.core; import java.io.Serializable; import java.rmi.RemoteException; import java.util.Map; /** * Can start and stop a shell server via reflection if the shell should happen * to be on the classpath, else it will gracefully say that it isn't there. */ class ShellService { private final NeoService neo; private final Object shellServer; ShellService( NeoService neo, Map<String, Serializable> config ) throws ShellNotAvailableException, RemoteException { this.neo = neo; if ( !shellDependencyAvailable() ) { throw new ShellNotAvailableException(); } this.shellServer = startShellServer( config ); } private boolean shellDependencyAvailable() { try { Class.forName( "org.neo4j.shell.ShellServer" ); return true; } catch ( Throwable t ) { return false; } } private Object startShellServer( Map<String, Serializable> config ) throws RemoteException { Integer port = ( Integer ) getConfig( config, "port", "DEFAULT_PORT" ); String name = ( String ) getConfig( config, "name", "DEFAULT_NAME" ); try { Class<?> shellServerClass = Class.forName( "org.neo4j.shell.neo.NeoShellServer" ); Object shellServer = shellServerClass.getConstructor( NeoService.class ).newInstance( neo ); shellServer.getClass().getMethod( "makeRemotelyAvailable", Integer.TYPE, String.class ).invoke( shellServer, port, name ); return shellServer; } catch ( Exception e ) { throw new RemoteException( "Couldn't start shell '" + name + "' at port " + port, e ); } } private Serializable getConfig( Map<String, Serializable> config, String key, String defaultVariableName ) throws RemoteException { Serializable result = config.get( key ); if ( result == null ) { try { result = ( Serializable ) Class.forName( "org.neo4j.shell.AbstractServer" ). getDeclaredField( defaultVariableName ).get( null ); } catch ( Exception e ) { throw new RemoteException( "Default variable not found", e ); } } return result; } public boolean shutdown() throws ShellNotAvailableException { try { shellServer.getClass().getMethod( "shutdown" ).invoke( shellServer ); return true; } catch ( Exception e ) { // TODO Really swallow this? Why not, who cares? return false; } } static class ShellNotAvailableException extends Exception { public ShellNotAvailableException() { super(); } } }
package org.slf4j.impl; public class MessageFormatter { static final char DELIM_START = '{'; static final char DELIM_STOP = '}'; /** * Performs single argument substitution for the 'messagePattern' passed as * parameter. * <p> * For example, <code>MessageFormatter.format("Hi {}.", "there");</code> will * return the string "Hi there.". * <p> * The {} pair is called the formatting element. It serves to designate the * location where the argument needs to be inserted within the pattern. * * @param messagePattern The message pattern which will be parsed and formatted * @param argument The argument to be inserted instead of the formatting element * @return The formatted message */ public static String format(String messagePattern, Object arg) { return arrayFormat(messagePattern, new Object[] {arg}); } /** * * Performs a two argument substitution for the 'messagePattern' passed as * parameter. * <p> * For example, <code>MessageFormatter.format("Hi {}. My name is {}.", * "there", "David");</code> will return the string "Hi there. My name is David.". * <p> * The '{}' pair is called a formatting element. It serves to designate the * location where the arguments need to be inserted within the message pattern. * * @param messagePattern The message pattern which will be parsed and formatted * @param arg1 The first argument to replace the first formatting element * @param arg2 The second argument to replace the second formatting element * @return The formatted message */ public static String format(String messagePattern, Object arg1, Object arg2) { return arrayFormat(messagePattern, new Object[] {arg1, arg2}); } public static String arrayFormat(String messagePattern, Object[] argArray) { if(messagePattern == null) { return null; } int i = 0; int len = messagePattern.length(); int j = messagePattern.indexOf(DELIM_START); char escape = 'x'; StringBuffer sbuf = new StringBuffer(messagePattern.length() + 50); for (int L = 0; L < argArray.length; L++) { j = messagePattern.indexOf(DELIM_START, i); if (j == -1 || (j+1 == len)) { // no more variables if (i == 0) { // this is a simple string return messagePattern; } else { // add the tail string which contains no variables and return the result. sbuf.append(messagePattern.substring(i, messagePattern.length())); return sbuf.toString(); } } else { char delimStop = messagePattern.charAt(j + 1); if (j > 0) { escape = messagePattern.charAt(j - 1); } if(escape == '\\') { sbuf.append(messagePattern.substring(i, j)); sbuf.append(DELIM_START); i = j + 1; } else if ((delimStop != DELIM_STOP)) { // invalid DELIM_START/DELIM_STOP pair sbuf.append(messagePattern.substring(i, messagePattern.length())); return sbuf.toString(); } else { // normal case sbuf.append(messagePattern.substring(i, j)); sbuf.append(argArray[L]); i = j + 2; } } } // append the characters following the second {} pair. sbuf.append(messagePattern.substring(i, messagePattern.length())); return sbuf.toString(); } }
package vektah.rust; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.testFramework.LightVirtualFile; import com.intellij.testFramework.ParsingTestCase; import org.junit.Ignore; import java.io.File; import java.io.IOException; /** * Tests that cover parts of the rust compiler source tree. Will be expanded for complete coverage over time. * * There doesn't appear to be an easy way to do parametrized tests with junit 3 and the intellij test suites all * seem to extend TestCase. Woe is me. */ @Ignore public class RustSourceTest extends ParsingTestCase { public RustSourceTest() { super("", "rs", new RustParserDefinition()); } @Override protected String getTestDataPath() { return System.getProperty("rust.source"); } public void testCompileTest() { doAllTests("compiletest"); } public void testLibArena() { doAllTests("libarena"); } public void testLibCollections() { doAllTests("libcollections"); } public void testLibCore() { doAllTests("libcore"); } public void testLibFlate() { doAllTests("libflate"); } public void testLibFourcc() { doAllTests("libfourcc"); } public void testLibGetOpts() { doAllTests("libgetopts"); } public void testLibGlob() { doAllTests("libglob"); } public void testLibGraphviz() { doAllTests("libgraphviz"); } public void testLibGreen() { doAllTests("libgreen"); } public void testLibHexFloat() { doAllTests("libhexfloat"); } public void testLibC() { doAllTests("liblibc"); } public void testLibLog() { doAllTests("liblog"); } public void testLibNative() { doAllTests("libnative"); } public void testLibNum() { doAllTests("libnum"); } public void testLibRand() { doAllTests("librand"); } public void testLibRegex() { doAllTests("libregex"); } public void testLibRegexMacros() { doAllTests("libregex_macros"); } public void testLibRustDoc() { doAllTests("librustdoc"); } public void testLibRustUV() { doAllTests("librustuv"); } public void testLibsemver() { doAllTests("libsemver"); } public void testLibSerialize() { doAllTests("libserialize"); } public void testLibSync() { doAllTests("libsync"); } public void testLibSyntax() { doAllTests("libsyntax"); } public void testLibTerm() { doAllTests("libterm"); } public void testLibTest() { doAllTests("libtest"); } public void testLibTime() { doAllTests("libtime"); } public void testLibUrl() { doAllTests("liburl"); } public void testLibUuid() { doAllTests("libuuid"); } public void testLibUV() { doAllTests("libuv"); } public void testLibWorkCache() { doAllTests("libworkcache"); } public void testLibRustC() { doAllTests("librustc", new String[] { "middle/typeck/infer/test.rs", // Not valid rust as of 574cbe5b07042c448c198af371803f977977b74f }); } public void testLibStd() { doAllTests("libstd", new String[] { "vec.rs" // TODO: Unusual syntax 'let mut count_x @ mut count_y = 0;' }); } protected void doAllTests(String dir) { doAllTests(dir, new String[] {}); } protected void doAllTests(String dir, String[] ignore) { doAllTests(new File(getTestDataPath() + dir), ignore); } protected void doAllTests(File dir_or_filename, String[] ignore) { if (dir_or_filename.isFile() && !dir_or_filename.getName().endsWith(".rs")) { return; } for (String ignore_file: ignore) { if (dir_or_filename.getAbsolutePath().endsWith(ignore_file)) { return; } } if (!dir_or_filename.isDirectory()) { doTest(dir_or_filename); } File[] files = dir_or_filename.listFiles(); if (files != null) { for (File file : files) { doAllTests(file, ignore); } } } public void doTest(File file) { try { String text = FileUtil.loadFile(file, CharsetToolkit.UTF8, true).trim(); myFile = createFile(file.getName(), text); ensureParsed(myFile); assertEquals("light virtual file text mismatch", text, ((LightVirtualFile)myFile.getVirtualFile()).getContent().toString()); assertEquals("virtual file text mismatch", text, LoadTextUtil.loadText(myFile.getVirtualFile())); assertEquals("doc text mismatch", text, myFile.getViewProvider().getDocument().getText()); assertEquals("psi text mismatch", text, myFile.getText()); String parseTree = toParseTreeText(myFile, skipSpaces(), includeRanges()); assertFalse("rust source tree file " + file.getName() + " contains errors!", parseTree.contains("PsiErrorElement")); assertFalse("rust source tree file " + file.getName() + " contains dummyblocks!", parseTree.contains("DummyBlock")); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected boolean skipSpaces() { return true; } @Override protected boolean includeRanges() { return false; } }
package org.languagetool.rules.en; import org.jetbrains.annotations.Nullable; import org.languagetool.*; import org.languagetool.language.English; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.Example; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.SuggestedReplacement; import org.languagetool.rules.spelling.morfologik.MorfologikSpellerRule; import org.languagetool.synthesis.en.EnglishSynthesizer; import java.io.IOException; import java.util.*; public abstract class AbstractEnglishSpellerRule extends MorfologikSpellerRule { private static final EnglishSynthesizer synthesizer = new EnglishSynthesizer(new English()); public AbstractEnglishSpellerRule(ResourceBundle messages, Language language) throws IOException { this(messages, language, null, Collections.emptyList()); } /** * @since 4.4 */ public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages) throws IOException { this(messages, language, userConfig, altLanguages, null); } protected static Map<String,String> loadWordlist(String path, int column) { if (column != 0 && column != 1) { throw new IllegalArgumentException("Only column 0 and 1 are supported: " + column); } Map<String,String> words = new HashMap<>(); List<String> lines = JLanguageTool.getDataBroker().getFromResourceDirAsLines(path); for (String line : lines) { line = line.trim(); if (line.isEmpty() || line.startsWith(" continue; } String[] parts = line.split(";"); if (parts.length != 2) { throw new RuntimeException("Unexpected format in " + path + ": " + line + " - expected two parts delimited by ';'"); } words.put(parts[column], parts[column == 1 ? 0 : 1]); } return words; } /** * @since 4.5 * optional: language model for better suggestions */ @Experimental public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages, LanguageModel languageModel) throws IOException { super(messages, language, userConfig, altLanguages, languageModel); super.ignoreWordsWithLength = 1; setCheckCompound(true); addExamplePair(Example.wrong("This <marker>sentenc</marker> contains a spelling mistake."), Example.fixed("This <marker>sentence</marker> contains a spelling mistake.")); String languageSpecificIgnoreFile = getSpellingFileName().replace(".txt", "_"+language.getShortCodeWithCountryAndVariant()+".txt"); for (String ignoreWord : wordListLoader.loadWords(languageSpecificIgnoreFile)) { addIgnoreWords(ignoreWord); } } @Override protected List<RuleMatch> getRuleMatches(String word, int startPos, AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar, int idx, AnalyzedTokenReadings[] tokens) throws IOException { List<RuleMatch> ruleMatches = super.getRuleMatches(word, startPos, sentence, ruleMatchesSoFar, idx, tokens); if (ruleMatches.size() > 0) { // so 'word' is misspelled: IrregularForms forms = getIrregularFormsOrNull(word); if (forms != null) { String message = "Possible spelling mistake. Did you mean <suggestion>" + forms.forms.get(0) + "</suggestion>, the " + forms.formName + " form of the " + forms.posName + " '" + forms.baseform + "'?"; addFormsToFirstMatch(message, sentence, ruleMatches, forms.forms); } else { VariantInfo variantInfo = isValidInOtherVariant(word); if (variantInfo != null) { String message = "Possible spelling mistake. '" + word + "' is " + variantInfo.getVariantName() + "."; replaceFormsOfFirstMatch(message, sentence, ruleMatches, variantInfo.otherVariant()); } } } return ruleMatches; } /** * @since 4.5 */ @Nullable protected VariantInfo isValidInOtherVariant(String word) { return null; } private void addFormsToFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, List<String> forms) { // recreating match, might overwrite information by SuggestionsRanker; // this has precedence RuleMatch oldMatch = ruleMatches.get(0); RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message); List<String> allSuggestions = new ArrayList<>(forms); for (String repl : oldMatch.getSuggestedReplacements()) { if (!allSuggestions.contains(repl)) { allSuggestions.add(repl); } } newMatch.setSuggestedReplacements(allSuggestions); ruleMatches.set(0, newMatch); } private void replaceFormsOfFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, String suggestion) { // recreating match, might overwrite information by SuggestionsRanker; // this has precedence RuleMatch oldMatch = ruleMatches.get(0); RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message); SuggestedReplacement sugg = new SuggestedReplacement(suggestion); sugg.setShortDescription(language.getName()); newMatch.setSuggestedReplacementObjects(Collections.singletonList(sugg)); ruleMatches.set(0, newMatch); } @SuppressWarnings({"ReuseOfLocalVariable", "ControlFlowStatementWithoutBraces"}) @Nullable private IrregularForms getIrregularFormsOrNull(String word) { IrregularForms irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("ed"), "VBD", "verb", "past tense"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("d" /* e.g. awaked */), "VBD", "verb", "past tense"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "s", Arrays.asList("s"), "NNS", "noun", "plural"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "es", Arrays.asList("es"/* e.g. 'analysises' */), "NNS", "noun", "plural"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "er", Arrays.asList("er"/* e.g. 'farer' */), "JJR", "adjective", "comparative"); if (irregularFormsOrNull != null) return irregularFormsOrNull; irregularFormsOrNull = getIrregularFormsOrNull(word, "est", Arrays.asList("est"/* e.g. 'farest' */), "JJS", "adjective", "superlative"); return irregularFormsOrNull; } @Nullable private IrregularForms getIrregularFormsOrNull(String word, String wordSuffix, List<String> suffixes, String posTag, String posName, String formName) { try { for (String suffix : suffixes) { if (word.endsWith(wordSuffix)) { String baseForm = word.substring(0, word.length() - suffix.length()); String[] forms = synthesizer.synthesize(new AnalyzedToken(word, null, baseForm), posTag); List<String> result = new ArrayList<>(); for (String form : forms) { if (!speller1.isMisspelled(form)) { // only accept suggestions that the spellchecker will accept result.add(form); } } // the internal dict might contain forms that the spell checker doesn't accept (e.g. 'criterions'), // but we trust the spell checker in this case: result.remove(word); result.remove("badder"); // non-standard usage result.remove("baddest"); // non-standard usage result.remove("spake"); // can be removed after dict update if (result.size() > 0) { return new IrregularForms(baseForm, posName, formName, result); } } } return null; } catch (IOException e) { throw new RuntimeException(e); } } /** * @since 2.7 */ @Override protected List<String> getAdditionalTopSuggestions(List<String> suggestions, String word) throws IOException { if ("Alot".equals(word)) { return Arrays.asList("A lot"); } else if ("alot".equals(word)) { return Arrays.asList("a lot"); } else if ("ad-on".equals(word)) { return Arrays.asList("add-on"); } else if ("acc".equals(word)) { return Arrays.asList("account", "accusative"); } else if ("Acc".equals(word)) { return Arrays.asList("Account", "Accusative"); } else if ("Addon".equals(word)) { return Arrays.asList("Add-on"); } else if ("Addons".equals(word)) { return Arrays.asList("Add-ons"); } else if ("Adhoc".equals(word)) { return Arrays.asList("Ad hoc"); } else if ("adhoc".equals(word)) { return Arrays.asList("ad hoc"); } else if ("ios".equals(word)) { return Arrays.asList("iOS"); } else if ("yrs".equals(word)) { return Arrays.asList("years"); } else if ("standup".equals(word)) { return Arrays.asList("stand-up"); } else if ("standups".equals(word)) { return Arrays.asList("stand-ups"); } else if ("Standup".equals(word)) { return Arrays.asList("Stand-up"); } else if ("Standups".equals(word)) { return Arrays.asList("Stand-ups"); } else if ("Playdough".equals(word)) { return Arrays.asList("Play-Doh"); } else if ("playdough".equals(word)) { return Arrays.asList("Play-Doh"); } else if ("biggy".equals(word)) { return Arrays.asList("biggie"); } else if ("lieing".equals(word)) { return Arrays.asList("lying"); } else if ("preffered".equals(word)) { return Arrays.asList("preferred"); } else if ("preffering".equals(word)) { return Arrays.asList("preferring"); } else if ("reffered".equals(word)) { return Arrays.asList("referred"); } else if ("reffering".equals(word)) { return Arrays.asList("referring"); } else if ("passthrough".equals(word)) { return Arrays.asList("pass-through"); } else if ("&&".equals(word)) { return Arrays.asList("&"); } else if ("cmon".equals(word)) { return Arrays.asList("c'mon"); } else if ("Cmon".equals(word)) { return Arrays.asList("C'mon"); } else if ("da".equals(word)) { return Arrays.asList("the"); } else if ("Da".equals(word)) { return Arrays.asList("The"); } else if ("Vue".equals(word)) { return Arrays.asList("Vue.JS"); } else if ("errornous".equals(word)) { return Arrays.asList("erroneous"); } else if ("brang".equals(word) || "brung".equals(word)) { return Arrays.asList("brought"); } else if ("thru".equals(word)) { return Arrays.asList("through"); } else if ("pitty".equals(word)) { return Arrays.asList("pity"); } else if ("speach".equals(word)) { // the replacement pairs would prefer "speak" return Arrays.asList("speech"); } else if ("icecreem".equals(word)) { return Arrays.asList("ice cream"); } else if ("math".equals(word)) { // in en-gb it's 'maths' return Arrays.asList("maths"); } else if ("fora".equals(word)) { return Arrays.asList("for a"); } else if ("lotsa".equals(word)) { return Arrays.asList("lots of"); } else if ("tryna".equals(word)) { return Arrays.asList("trying to"); } else if ("coulda".equals(word)) { return Arrays.asList("could have"); } else if ("shoulda".equals(word)) { return Arrays.asList("should have"); } else if ("woulda".equals(word)) { return Arrays.asList("would have"); } else if ("tellem".equals(word)) { return Arrays.asList("tell them"); } else if ("Tellem".equals(word)) { return Arrays.asList("Tell them"); } else if ("afro-american".equalsIgnoreCase(word)) { return Arrays.asList("Afro-American"); } else if ("Webex".equals(word)) { return Arrays.asList("WebEx"); } else if ("didint".equals(word)) { return Arrays.asList("didn't"); } else if ("Didint".equals(word)) { return Arrays.asList("Didn't"); } else if ("wasint".equals(word)) { return Arrays.asList("wasn't"); } else if ("hasint".equals(word)) { return Arrays.asList("hasn't"); } else if ("doesint".equals(word)) { return Arrays.asList("doesn't"); } else if ("ist".equals(word)) { return Arrays.asList("is"); } else if ("Boing".equals(word)) { return Arrays.asList("Boeing"); } else if ("te".equals(word)) { return Arrays.asList("the"); } else if ("todays".equals(word)) { return Arrays.asList("today's"); } else if ("Todays".equals(word)) { return Arrays.asList("Today's"); } else if ("todo".equals(word)) { return Arrays.asList("to-do", "to do"); } else if ("todos".equals(word)) { return Arrays.asList("to-dos", "to do"); } else if ("Todo".equalsIgnoreCase(word)) { return Arrays.asList("To-do", "To do"); } else if ("Todos".equalsIgnoreCase(word)) { return Arrays.asList("To-dos"); } else if ("heres".equals(word)) { return Arrays.asList("here's"); } else if ("Heres".equals(word)) { return Arrays.asList("Here's"); } else if ("McDonalds".equals(word)) { return Arrays.asList("McDonald's"); } else if ("ux".equals(word)) { return Arrays.asList("UX"); } else if ("ive".equals(word)) { return Arrays.asList("I've"); } else if ("infos".equals(word)) { return Arrays.asList("informations"); } else if ("Infos".equals(word)) { return Arrays.asList("Informations"); } else if ("prios".equals(word)) { return Arrays.asList("priorities"); } else if ("Prio".equals(word)) { return Arrays.asList("Priority"); } else if ("prio".equals(word)) { return Arrays.asList("Priority"); } else if ("esport".equals(word)) { return Arrays.asList("e-sport"); } else if ("Esport".equals(word)) { return Arrays.asList("E-Sport"); } else if ("eSport".equals(word)) { return Arrays.asList("e-sport"); } else if ("esports".equals(word)) { return Arrays.asList("e-sports"); } else if ("Esports".equals(word)) { return Arrays.asList("E-Sports"); } else if ("eSports".equals(word)) { return Arrays.asList("e-sports"); } else if ("ecommerce".equals(word)) { return Arrays.asList("e-commerce"); } else if ("Ecommerce".equals(word)) { return Arrays.asList("E-Commerce"); } else if ("eCommerce".equals(word)) { return Arrays.asList("e-commerce"); } else if ("elearning".equals(word)) { return Arrays.asList("e-learning"); } else if ("eLearning".equals(word)) { return Arrays.asList("e-learning"); } else if ("ebook".equals(word)) { return Arrays.asList("e-book"); } else if ("ebooks".equals(word)) { return Arrays.asList("e-books"); } else if ("eBook".equals(word)) { return Arrays.asList("e-book"); } else if ("eBooks".equals(word)) { return Arrays.asList("e-books"); } else if ("Ebook".equals(word)) { return Arrays.asList("E-Book"); } else if ("Ebooks".equals(word)) { return Arrays.asList("E-Books"); } else if ("R&B".equals(word)) { return Arrays.asList("R & B", "R 'n' B"); } else if ("ie".equals(word)) { return Arrays.asList("i.e."); } else if ("eg".equals(word)) { return Arrays.asList("e.g."); } else if ("Thx".equals(word)) { return Arrays.asList("Thanks"); } else if ("thx".equals(word)) { return Arrays.asList("thanks"); } else if ("ty".equals(word)) { return Arrays.asList("thank you", "thanks"); } else if ("Sry".equals(word)) { return Arrays.asList("Sorry"); } else if ("sry".equals(word)) { return Arrays.asList("sorry"); } else if ("im".equals(word)) { return Arrays.asList("I'm"); } else if ("spoilt".equals(word)) { return Arrays.asList("spoiled"); } else if ("Lil".equals(word)) { return Arrays.asList("Little"); } else if ("lil".equals(word)) { return Arrays.asList("little"); } else if ("Sucka".equals(word)) { return Arrays.asList("Sucker"); } else if ("sucka".equals(word)) { return Arrays.asList("sucker"); } else if ("whaddya".equals(word)) { return Arrays.asList("what are you", "what do you"); } else if ("Whaddya".equals(word)) { return Arrays.asList("What are you", "What do you"); } else if ("sinc".equals(word)) { return Arrays.asList("sync"); } else if ("Hongkong".equals(word)) { return Arrays.asList("Hong Kong"); } else if ("center".equals(word)) { // For non-US English return Arrays.asList("centre"); } else if ("ur".equals(word)) { return Arrays.asList("your", "you are"); } else if ("Ur".equals(word)) { return Arrays.asList("Your", "You are"); } else if ("ure".equals(word)) { return Arrays.asList("your", "you are"); } else if ("Ure".equals(word)) { return Arrays.asList("Your", "You are"); } else if ("mins".equals(word)) { return Arrays.asList("minutes", "min"); } else if ("addon".equals(word)) { return Arrays.asList("add-on"); } else if ("addons".equals(word)) { return Arrays.asList("add-ons"); } else if ("afterparty".equals(word)) { return Arrays.asList("after-party"); } else if ("Afterparty".equals(word)) { return Arrays.asList("After-party"); } else if ("wellbeing".equals(word)) { return Arrays.asList("well-being"); } else if ("cuz".equals(word) || "coz".equals(word)) { return Arrays.asList("because"); } else if ("pls".equals(word)) { return Arrays.asList("please"); } else if ("Pls".equals(word)) { return Arrays.asList("Please"); } else if ("plz".equals(word)) { return Arrays.asList("please"); } else if ("Plz".equals(word)) { return Arrays.asList("Please"); } else if ("gmail".equals(word)) { return Arrays.asList("Gmail"); // AtD irregular plurals - START } else if ("addendums".equals(word)) { return Arrays.asList("addenda"); } else if ("algas".equals(word)) { return Arrays.asList("algae"); } else if ("alumnas".equals(word)) { return Arrays.asList("alumnae"); } else if ("alumnuses".equals(word)) { return Arrays.asList("alumni"); } else if ("analysises".equals(word)) { return Arrays.asList("analyses"); } else if ("appendixs".equals(word)) { return Arrays.asList("appendices"); } else if ("axises".equals(word)) { return Arrays.asList("axes"); } else if ("bacilluses".equals(word)) { return Arrays.asList("bacilli"); } else if ("bacteriums".equals(word)) { return Arrays.asList("bacteria"); } else if ("basises".equals(word)) { return Arrays.asList("bases"); } else if ("beaus".equals(word)) { return Arrays.asList("beaux"); } else if ("bisons".equals(word)) { return Arrays.asList("bison"); } else if ("buffalos".equals(word)) { return Arrays.asList("buffaloes"); } else if ("calfs".equals(word)) { return Arrays.asList("calves"); } else if ("childs".equals(word)) { return Arrays.asList("children"); } else if ("crisises".equals(word)) { return Arrays.asList("crises"); } else if ("criterions".equals(word)) { return Arrays.asList("criteria"); } else if ("curriculums".equals(word)) { return Arrays.asList("curricula"); } else if ("datums".equals(word)) { return Arrays.asList("data"); } else if ("deers".equals(word)) { return Arrays.asList("deer"); } else if ("diagnosises".equals(word)) { return Arrays.asList("diagnoses"); } else if ("echos".equals(word)) { return Arrays.asList("echoes"); } else if ("elfs".equals(word)) { return Arrays.asList("elves"); } else if ("ellipsises".equals(word)) { return Arrays.asList("ellipses"); } else if ("embargos".equals(word)) { return Arrays.asList("embargoes"); } else if ("erratums".equals(word)) { return Arrays.asList("errata"); } else if ("firemans".equals(word)) { return Arrays.asList("firemen"); } else if ("fishs".equals(word)) { return Arrays.asList("fishes", "fish"); } else if ("genuses".equals(word)) { return Arrays.asList("genera"); } else if ("gooses".equals(word)) { return Arrays.asList("geese"); } else if ("halfs".equals(word)) { return Arrays.asList("halves"); } else if ("heros".equals(word)) { return Arrays.asList("heroes"); } else if ("indexs".equals(word)) { return Arrays.asList("indices", "indexes"); } else if ("lifes".equals(word)) { return Arrays.asList("lives"); } else if ("mans".equals(word)) { return Arrays.asList("men"); } else if ("matrixs".equals(word)) { return Arrays.asList("matrices"); } else if ("meanses".equals(word)) { return Arrays.asList("means"); } else if ("mediums".equals(word)) { return Arrays.asList("media"); } else if ("memorandums".equals(word)) { return Arrays.asList("memoranda"); } else if ("mooses".equals(word)) { return Arrays.asList("moose"); } else if ("mosquitos".equals(word)) { return Arrays.asList("mosquitoes"); } else if ("neurosises".equals(word)) { return Arrays.asList("neuroses"); } else if ("nucleuses".equals(word)) { return Arrays.asList("nuclei"); } else if ("oasises".equals(word)) { return Arrays.asList("oases"); } else if ("ovums".equals(word)) { return Arrays.asList("ova"); } else if ("oxs".equals(word)) { return Arrays.asList("oxen"); } else if ("oxes".equals(word)) { return Arrays.asList("oxen"); } else if ("paralysises".equals(word)) { return Arrays.asList("paralyses"); } else if ("potatos".equals(word)) { return Arrays.asList("potatoes"); } else if ("radiuses".equals(word)) { return Arrays.asList("radii"); } else if ("selfs".equals(word)) { return Arrays.asList("selves"); } else if ("serieses".equals(word)) { return Arrays.asList("series"); } else if ("sheeps".equals(word)) { return Arrays.asList("sheep"); } else if ("shelfs".equals(word)) { return Arrays.asList("shelves"); } else if ("scissorses".equals(word)) { return Arrays.asList("scissors"); } else if ("specieses".equals(word)) { return Arrays.asList("species"); } else if ("stimuluses".equals(word)) { return Arrays.asList("stimuli"); } else if ("stratums".equals(word)) { return Arrays.asList("strata"); } else if ("tableaus".equals(word)) { return Arrays.asList("tableaux"); } else if ("thats".equals(word)) { return Arrays.asList("those"); } else if ("thesises".equals(word)) { return Arrays.asList("theses"); } else if ("thiefs".equals(word)) { return Arrays.asList("thieves"); } else if ("thises".equals(word)) { return Arrays.asList("these"); } else if ("tomatos".equals(word)) { return Arrays.asList("tomatoes"); } else if ("tooths".equals(word)) { return Arrays.asList("teeth"); } else if ("torpedos".equals(word)) { return Arrays.asList("torpedoes"); } else if ("vertebras".equals(word)) { return Arrays.asList("vertebrae"); } else if ("vetos".equals(word)) { return Arrays.asList("vetoes"); } else if ("vitas".equals(word)) { return Arrays.asList("vitae"); } else if ("watchs".equals(word)) { return Arrays.asList("watches"); } else if ("wifes".equals(word)) { return Arrays.asList("wives"); } else if ("womans".equals(word)) { return Arrays.asList("women"); // AtD irregular plurals - END } else if ("tippy-top".equals(word) || "tippytop".equals(word)) { // "tippy-top" is an often used word by Donald Trump return Arrays.asList("tip-top", "top most"); } else if ("imma".equals(word)) { return Arrays.asList("I'm going to", "I'm a"); } else if ("Imma".equals(word)) { return Arrays.asList("I'm going to", "I'm a"); } else if ("dontcha".equals(word)) { return Arrays.asList("don't you"); } else if ("Dontcha".equals(word)) { return Arrays.asList("don't you"); } else if ("greatfruit".equals(word)) { return Arrays.asList("grapefruit", "great fruit"); } else if (word.endsWith("ys")) { String suggestion = word.replaceFirst("ys$", "ies"); if (!speller1.isMisspelled(suggestion)) { return Arrays.asList(suggestion); } } return super.getAdditionalTopSuggestions(suggestions, word); } private static class IrregularForms { final String baseform; final String posName; final String formName; final List<String> forms; private IrregularForms(String baseform, String posName, String formName, List<String> forms) { this.baseform = baseform; this.posName = posName; this.formName = formName; this.forms = forms; } } }
package org.safehaus.subutai.ui.tracker; import com.google.common.base.Strings; import com.vaadin.data.Item; import com.vaadin.data.Property; import com.vaadin.data.util.IndexedContainer; import com.vaadin.server.ThemeResource; import com.vaadin.shared.ui.datefield.Resolution; import com.vaadin.ui.*; import org.safehaus.subutai.shared.operation.ProductOperationState; import org.safehaus.subutai.shared.operation.ProductOperationView; import java.text.SimpleDateFormat; import java.util.*; import java.util.Calendar; import java.util.logging.Level; import java.util.logging.Logger; /** * Tracker Vaadin UI */ public class TrackerForm extends CustomComponent { private static final Logger LOG = Logger.getLogger(TrackerForm.class.getName()); private GridLayout content; private Table operationsTable; private TextArea outputTxtArea; private String okIconSource = "img/ok.png"; private String errorIconSource = "img/cancel.png"; private String loadIconSource = "img/spinner.gif"; private PopupDateField fromDate, toDate; private ComboBox sourcesCombo, limitCombo; private Date fromDateValue, toDateValue; private volatile UUID trackID; private volatile boolean track = false; private List<ProductOperationView> currentOperations = new ArrayList<>(); private String source; private int limit = 10; public TrackerForm() { content = new GridLayout(); content.setSpacing(true); content.setSizeFull(); content.setMargin(true); content.setRows(7); content.setColumns(1); HorizontalLayout filterLayout = fillFilterLayout(); operationsTable = createTableTemplate("Operations"); getOutputTextArea(); content.addComponent(filterLayout, 0, 0); content.addComponent(operationsTable, 0, 1, 0, 3); content.addComponent(outputTxtArea, 0, 4, 0, 6); setCompositionRoot(content); } private HorizontalLayout fillFilterLayout() { HorizontalLayout filterLayout = new HorizontalLayout(); filterLayout.setSpacing(true); getSourcesCombo(); generateDateFormat(); getFromDateField(); getToDateField(); getLimitCombo(); filterLayout.addComponent(sourcesCombo); filterLayout.addComponent(fromDate); filterLayout.addComponent(toDate); filterLayout.addComponent(limitCombo); return filterLayout; } private Table createTableTemplate(String caption) { Table table = new Table(caption); table.setContainerDataSource(new IndexedContainer()); table.addContainerProperty("Date", Date.class, null); table.addContainerProperty("Operation", String.class, null); table.addContainerProperty("Check", Button.class, null); table.addContainerProperty("Status", Embedded.class, null); table.setSizeFull(); table.setPageLength(10); table.setSelectable(false); table.setImmediate(true); return table; } private void getOutputTextArea() { outputTxtArea = new TextArea("Operation output"); outputTxtArea.setSizeFull(); // outputTxtArea.setRows(20); outputTxtArea.setImmediate(true); outputTxtArea.setWordwrap(true); } private void getSourcesCombo() { sourcesCombo = new ComboBox("Source"); sourcesCombo.setImmediate(true); sourcesCombo.setTextInputAllowed(false); sourcesCombo.setNullSelectionAllowed(false); sourcesCombo.addValueChangeListener(new Property.ValueChangeListener() { @Override public void valueChange(final Property.ValueChangeEvent event) { source = (String) event.getProperty().getValue(); trackID = null; outputTxtArea.setValue(""); } }); } private void generateDateFormat() { SimpleDateFormat df = new SimpleDateFormat("ddMMyyyy HH:mm:ss"); Calendar cal = Calendar.getInstance(); try { fromDateValue = df.parse(String.format("%02d", cal.get(Calendar.DAY_OF_MONTH)) + String .format("%02d", (cal.get(Calendar.MONTH) + 1)) + cal.get(Calendar.YEAR) + " 00:00:00"); toDateValue = df.parse(String.format("%02d", cal.get(Calendar.DAY_OF_MONTH)) + String .format("%02d", (cal.get(Calendar.MONTH) + 1)) + cal.get(Calendar.YEAR) + " 23:59:59"); } catch (java.text.ParseException ex) { Logger.getLogger(TrackerForm.class.getName()).log(Level.SEVERE, null, ex); } } private void getFromDateField() { fromDate = new PopupDateField(); fromDate.setCaption("From"); fromDate.setValue(fromDateValue); fromDate.setImmediate(true); fromDate.setDateFormat("yyyy-MM-dd HH:mm:ss"); fromDate.addValueChangeListener(new Property.ValueChangeListener() { public void valueChange(Property.ValueChangeEvent event) { if (event.getProperty().getValue() instanceof Date) { fromDateValue = (Date) event.getProperty().getValue(); } } }); } private void getToDateField() { toDate = new PopupDateField("To", toDateValue); toDate.setImmediate(true); toDate.setDateFormat("yyyy-MM-dd HH:mm:ss"); fromDate.setResolution(Resolution.SECOND); toDate.setResolution(Resolution.SECOND); toDate.addValueChangeListener(new Property.ValueChangeListener() { public void valueChange(Property.ValueChangeEvent event) { if (event.getProperty().getValue() instanceof Date) { toDateValue = (Date) event.getProperty().getValue(); } } }); } private void getLimitCombo() { limitCombo = new ComboBox("Show last", Arrays.asList(10, 50, 100)); limitCombo.setImmediate(true); limitCombo.setTextInputAllowed(false); limitCombo.setNullSelectionAllowed(false); limitCombo.setValue(limit); limitCombo.addValueChangeListener(new Property.ValueChangeListener() { public void valueChange(Property.ValueChangeEvent event) { limit = (Integer) event.getProperty().getValue(); } }); } public void startTracking() { if (!track) { track = true; TrackerUI.getExecutor().execute(new Runnable() { public void run() { while (track) { try { populateOperations(); populateLogs(); } catch (Exception e) { LOG.log(Level.SEVERE, "Error in tracker", e); } try { Thread.sleep(1000); } catch (InterruptedException ex) { break; } } } }); } } private void populateOperations() { if (!Strings.isNullOrEmpty(source)) { List<ProductOperationView> operations = TrackerUI.getTracker().getProductOperations(source, fromDateValue, toDateValue, limit); if (operations.isEmpty()) { trackID = null; outputTxtArea.setValue(""); } IndexedContainer container = (IndexedContainer) operationsTable.getContainerDataSource(); currentOperations.removeAll(operations); for (ProductOperationView po : currentOperations) { container.removeItem(po.getId()); } boolean sortNeeded = false; for (final ProductOperationView po : operations) { Embedded progressIcon; if (po.getState() == ProductOperationState.RUNNING) { progressIcon = new Embedded("", new ThemeResource(loadIconSource)); } else if (po.getState() == ProductOperationState.FAILED) { progressIcon = new Embedded("", new ThemeResource(errorIconSource)); } else { progressIcon = new Embedded("", new ThemeResource(okIconSource)); } Item item = container.getItem(po.getId()); if (item == null) { final Button trackLogsBtn = new Button("View logs"); trackLogsBtn.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent clickEvent) { trackID = po.getId(); } }); item = container.addItem(po.getId()); item.getItemProperty("Date").setValue(po.getCreateDate()); item.getItemProperty("Operation").setValue(po.getDescription()); item.getItemProperty("Check").setValue(trackLogsBtn); item.getItemProperty("Status").setValue(progressIcon); sortNeeded = true; } else { if (!((Embedded) item.getItemProperty("Status").getValue()).getSource().equals( progressIcon.getSource())) { item.getItemProperty("Status").setValue(progressIcon); } } } if (sortNeeded) { Object[] properties = {"Date"}; boolean[] ordering = {false}; operationsTable.sort(properties, ordering); } currentOperations = operations; } } private void populateLogs() { if (trackID != null && !Strings.isNullOrEmpty(source)) { ProductOperationView po = TrackerUI.getTracker().getProductOperation(source, trackID); if (po != null) { setOutput(po.getDescription() + "\nState: " + po.getState() + "\nLogs:\n" + po.getLog()); if (po.getState() != ProductOperationState.RUNNING) { trackID = null; } } else { setOutput("Product operation not found. Check logs"); } } } private void setOutput(String output) { if (!Strings.isNullOrEmpty(output)) { outputTxtArea.setValue(output); outputTxtArea.setCursorPosition(outputTxtArea.getValue().toString().length() - 1); } } void refreshSources() { String oldSource = source; sourcesCombo.removeAllItems(); List<String> sources = TrackerUI.getTracker().getProductOperationSources(); for (String src : sources) { sourcesCombo.addItem(src); } if (!Strings.isNullOrEmpty(oldSource)) { sourcesCombo.setValue(oldSource); } else if (!sources.isEmpty()) { sourcesCombo.setValue(sources.iterator().next()); } } @Override public void detach() { super.detach(); stopTracking(); } private void stopTracking() { track = false; } }
package com.elmakers.mine.bukkit.block.magic; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import com.elmakers.mine.bukkit.api.block.UndoList; import com.elmakers.mine.bukkit.api.effect.EffectPlayer; import com.elmakers.mine.bukkit.api.item.ItemData; import com.elmakers.mine.bukkit.api.magic.MaterialSet; import com.elmakers.mine.bukkit.block.BlockData; import com.elmakers.mine.bukkit.effect.EffectContext; import com.elmakers.mine.bukkit.magic.Mage; import com.elmakers.mine.bukkit.magic.MagicController; import com.elmakers.mine.bukkit.magic.MagicMetaKeys; import com.elmakers.mine.bukkit.utility.CompatibilityLib; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import com.elmakers.mine.bukkit.warp.MagicWarpDescription; public class MagicBlock implements com.elmakers.mine.bukkit.api.automata.Automaton, com.elmakers.mine.bukkit.api.block.magic.MagicBlock { @Nonnull private final MagicController controller; @Nullable private MagicBlockTemplate template; @Nullable private ConfigurationSection parameters; private String templateKey; @Nonnull private Location location; private String worldName; private long createdAt; private String creatorId; private String creatorName; private String name; private long nextTick; private List<WeakReference<Entity>> spawned; private long lastSpawn; private EffectContext effectContext; private boolean pendingWorldLoad; private boolean isActive; private boolean enabled = true; private Mage mage; public MagicBlock(@Nonnull MagicController controller, @Nonnull ConfigurationSection node) { this.controller = controller; enabled = node.getBoolean("enabled", true); templateKey = node.getString("template"); parameters = ConfigurationUtils.getConfigurationSection(node, "parameters"); if (templateKey != null) { setTemplate(controller.getMagicBlockTemplate(templateKey)); } createdAt = node.getLong("created", 0); creatorId = node.getString("creator"); creatorName = node.getString("creator_name"); name = node.getString("name"); double x = node.getDouble("x"); double y = node.getDouble("y"); double z = node.getDouble("z"); float yaw = (float)node.getDouble("yaw"); float pitch = (float)node.getDouble("pitch"); worldName = node.getString("world"); if (template == null) { controller.getLogger().warning("Automaton missing template: " + templateKey + " at " + x + "," + y + "," + z + " in world " + worldName); } if (worldName == null || worldName.isEmpty()) { worldName = "world"; controller.getLogger().warning("Automaton missing world name, defaulting to 'world'"); } World world = Bukkit.getWorld(worldName); if (world == null) { pendingWorldLoad = true; // Fill in a world for now so we have a non-null valid Location, but // nothing should use it if we're marked as pending load. world = Bukkit.getWorlds().iterator().next(); } location = new Location(world, x, y, z, yaw, pitch); } public MagicBlock(@Nonnull MagicController controller, @Nonnull Location location, @Nonnull String templateKey, String creatorId, String creatorName, @Nullable ConfigurationSection parameters) { this.controller = controller; this.templateKey = templateKey; this.parameters = parameters; this.location = location; World world = this.location.getWorld(); worldName = world == null ? null : world.getName(); setTemplate(controller.getMagicBlockTemplate(templateKey)); createdAt = System.currentTimeMillis(); this.creatorId = creatorId; this.creatorName = creatorName; } private void setTemplate(MagicBlockTemplate template) { this.template = template; if (template != null) { if (parameters != null) { this.template = template.getVariant(parameters); } nextTick = 0; lastSpawn = 0; } } public void reload() { if (template != null) { setTemplate(controller.getMagicBlockTemplate(template.getKey())); } } public void save(ConfigurationSection node) { node.set("enabled", enabled); node.set("created", createdAt); node.set("creator", creatorId); node.set("creator_name", creatorName); node.set("template", templateKey); node.set("world", worldName); node.set("x", location.getX()); node.set("y", location.getY()); node.set("z", location.getZ()); node.set("yaw", location.getYaw()); node.set("pitch", location.getPitch()); node.set("parameters", parameters); node.set("name", name); } public long getCreatedTime() { return createdAt; } @Override public void pause() { deactivate(); } @Override public void resume() { if (template == null) return; // Always tick at least once tick(); } public void activate() { isActive = true; if (template != null) { Collection<EffectPlayer> effects = template.getEffects(); if (effects != null) { for (EffectPlayer player : effects) { player.start(getEffectContext()); } } } } public void deactivate() { isActive = false; if (spawned != null) { for (WeakReference<Entity> mobReference : spawned) { Entity mob = mobReference.get(); if (mob != null && mob.isValid()) { mob.remove(); } } spawned.clear(); } lastSpawn = 0; if (effectContext != null) { effectContext.cancelEffects(); effectContext = null; } if (template != null) { Collection<EffectPlayer> effects = template.getEffects(); if (effects != null) { for (EffectPlayer player : effects) { player.cancel(); } } } if (mage != null) { Mage mage = this.mage; mage.deactivate(); mage.undoScheduled(); if (template != null && template.isUndoAll()) { UndoList undone = mage.undo(); while (undone != null) { undone = mage.undo(); } } controller.forgetMage(mage); this.mage = null; } } @Override public boolean isActive() { return isActive; } @Override public boolean isEnabled() { return enabled; } @Override public void enable() { if (enabled) return; this.enabled = true; if (shouldBeActive()) { resume(); } } @Override public void disable() { this.enabled = false; pause(); } public boolean shouldBeActive() { return isAlwaysActive() || inActiveChunk(); } public boolean inActiveChunk() { return CompatibilityLib.getCompatibilityUtils().isChunkLoaded(getLocation()); } @Override @Nonnull public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; World world = this.location.getWorld(); worldName = world == null ? null : world.getName(); } public void track(List<Entity> entities) { if (template == null) return; Spawner spawner = template.getSpawner(); if (spawner == null || !spawner.isTracked()) return; if (spawned == null) { spawned = new ArrayList<>(); } for (Entity entity : entities) { CompatibilityLib.getEntityMetadataUtils().setLong(entity, MagicMetaKeys.AUTOMATION, getId()); spawned.add(new WeakReference<>(entity)); } } public void checkEntities() { if (spawned == null || template == null) return; Spawner spawner = template.getSpawner(); if (spawner.isLeashed()) { MaterialSet leashBlocks = spawner.getLeashBlocks(); double leashRangeSquared = spawner.getLimitRange(); if (leashRangeSquared > 0) { leashRangeSquared = leashRangeSquared * leashRangeSquared; } Iterator<WeakReference<Entity>> iterator = spawned.iterator(); while (iterator.hasNext()) { WeakReference<Entity> mobReference = iterator.next(); Entity mob = mobReference.get(); boolean handled = false; if (mob == null || !mob.isValid()) { iterator.remove(); handled = true; } if (!handled && leashRangeSquared > 0) { if (mob.getLocation().distanceSquared(location) > leashRangeSquared) { mob.teleport(spawner.getSpawnLocation(location)); } } if (!handled && leashBlocks != null) { Block block = mob.getLocation().getBlock(); Block down = block.getRelative(BlockFace.DOWN); if (leashBlocks.testBlock(block) || leashBlocks.testBlock(down)) { mob.teleport(spawner.getSpawnLocation(location)); } } } } } public void onSpawnDeath() { lastSpawn = System.currentTimeMillis(); } public void spawn() { if (template == null) return; Spawner spawner = template.getSpawner(); if (spawner == null) return; List<Entity> entities = spawner.spawn(this); if (entities != null && !entities.isEmpty()) { lastSpawn = System.currentTimeMillis(); track(entities); } } public void tick() { if (template == null || !enabled) return; long now = System.currentTimeMillis(); if (now < nextTick) return; template.tick(this); nextTick = now + template.getInterval(); } public boolean hasSpawner() { return template != null && template.getSpawner() != null; } public long getTimeToNextSpawn() { if (template == null) return 0; Spawner spawner = template.getSpawner(); if (spawner == null) return 0; int spawnInterval = spawner.getInterval(); if (spawnInterval == 0) return 0; return Math.max(0, lastSpawn + spawnInterval - System.currentTimeMillis()); } public int getSpawnLimit() { if (template == null) return 0; Spawner spawner = template.getSpawner(); return spawner == null ? 0 : spawner.getLimit(); } public int getSpawnMinPlayers() { if (template == null) return 0; Spawner spawner = template.getSpawner(); return spawner == null ? 0 : spawner.getMinPlayers(); } public long getId() { return BlockData.getBlockId(getLocation()); } public boolean isPendingWorldLoad() { return pendingWorldLoad; } @Override @Nonnull public String getTemplateKey() { return templateKey == null ? "" : templateKey; } @Nullable public MagicBlockTemplate getTemplate() { return template; } public boolean isAlwaysActive() { return template != null && template.isAlwaysActive(); } public boolean removeWhenBroken() { return template != null && template.removeWhenBroken(); } @Nonnull private EffectContext getEffectContext() { if (effectContext == null) { effectContext = new EffectContext(controller, location); } return effectContext; } @Nullable public ConfigurationSection getParameters() { return parameters; } public void setParameters(@Nullable ConfigurationSection parameters) { this.parameters = parameters; } @Nullable public String getCreatorName() { return creatorName; } @Nonnull @Override public Mage getMage() { if (mage == null) { String automatonId = UUID.randomUUID().toString(); mage = controller.getBlockMage(automatonId, template == null ? "?" : template.getName()); mage.setLocation(location); } return mage; } public int getSpawnedCount() { return spawned == null ? 0 : spawned.size(); } @Nullable public Nearby getNearby() { if (template == null) return null; Spawner spawner = template.getSpawner(); Nearby nearby = null; if (spawner != null) { nearby = spawner.getNearby(this); if (nearby != null && spawner.isTracked()) { nearby.mobs = spawned == null ? 0 : spawned.size(); } } return nearby; } @Nullable public Collection<WeakReference<Entity>> getSpawned() { return spawned; } @Override @Nonnull public String getName() { if (name != null) return name; if (template != null) return template.getName(); if (templateKey != null) return templateKey; return "(Unknown)"; } @Nullable public String getDescription() { return template == null ? null : template.getDescription(); } public void setName(String name) { this.name = name; } public void removed() { if (template == null) return; if (template.removeWhenBroken()) { location.getBlock().setType(Material.AIR); } String dropWhenRemoved = template.getDropWhenRemoved(); if (dropWhenRemoved != null && !dropWhenRemoved.isEmpty()) { ItemData item = controller.getOrCreateItem(dropWhenRemoved); ItemStack stack = item == null ? null : item.getItemStack(); if (CompatibilityLib.getItemUtils().isEmpty(stack)) { controller.getLogger().warning("Invalid item dropped in automaton " + template.getKey() + ": " + dropWhenRemoved); } else { location.getWorld().dropItemNaturally(location, stack); } } } public boolean onInteract(Player player) { if (template == null) { return false; } return template.interact(this, player); } public MagicWarpDescription getPortalWarp() { return template == null ? null : template.getPortalWarp(); } public String getPortalSpell() { return template == null ? null : template.getPortalSpell(); } }
package org.gridgain.grid.kernal.visor.dto.node; import org.gridgain.grid.kernal.visor.dto.cache.*; import org.gridgain.grid.kernal.visor.dto.event.*; import org.gridgain.grid.kernal.visor.dto.ggfs.*; import org.gridgain.grid.kernal.visor.dto.streamer.*; import java.io.*; import java.util.*; /** * Data collector task result. */ public class VisorNodeDataCollectorTaskResult implements Serializable { private static final long serialVersionUID = 0L; /** Unhandled exceptions from nodes. */ private final Map<UUID, Throwable> unhandledEx = new HashMap<>(); /** Nodes grid names. */ private final Map<UUID, String> gridNames = new HashMap<>(); /** Nodes topology versions. */ private final Map<UUID, Long> topologyVersions = new HashMap<>(); /** All task monitoring state collected from nodes. */ private final Map<UUID, Boolean> taskMonitoringEnabled = new HashMap<>(); /** All events collected from nodes. */ private final List<VisorGridEvent> events = new ArrayList<>(); /** Exceptions caught during collecting events from nodes. */ private final Map<UUID, Throwable> eventsEx = new HashMap<>(); /** All caches collected from nodes. */ private final Map<UUID, Collection<VisorCache>> caches = new HashMap<>(); /** Exceptions caught during collecting caches from nodes. */ private final Map<UUID, Throwable> cachesEx = new HashMap<>(); /** All GGFS collected from nodes. */ private final Map<UUID, Collection<VisorGgfs>> ggfss = new HashMap<>(); /** All GGFS endpoints collected from nodes. */ private final Map<UUID, Collection<VisorGgfsEndpoint>> ggfsEndpoints = new HashMap<>(); /** Exceptions caught during collecting GGFS from nodes. */ private final Map<UUID, Throwable> ggfssEx = new HashMap<>(); /** All streamers collected from nodes. */ private final Map<UUID, Collection<VisorStreamer>> streamers = new HashMap<>(); /** Exceptions caught during collecting streamers from nodes. */ private final Map<UUID, Throwable> streamersEx = new HashMap<>(); /** * @return {@code true} If no data was collected. */ public boolean isEmpty() { return gridNames.isEmpty() && topologyVersions.isEmpty() && unhandledEx.isEmpty() && taskMonitoringEnabled.isEmpty() && events.isEmpty() && eventsEx.isEmpty() && caches.isEmpty() && cachesEx.isEmpty() && ggfss.isEmpty() && ggfsEndpoints.isEmpty() && ggfssEx.isEmpty() && streamers.isEmpty() && streamersEx.isEmpty(); } /** * @return Unhandled exceptions from nodes. */ public Map<UUID, Throwable> unhandledEx() { return unhandledEx; } /** * @return Nodes grid names. */ public Map<UUID, String> gridNames() { return gridNames; } /** * @return Nodes topology versions. */ public Map<UUID, Long> topologyVersions() { return topologyVersions; } /** * @return All task monitoring state collected from nodes. */ public Map<UUID, Boolean> taskMonitoringEnabled() { return taskMonitoringEnabled; } /** * @return All events collected from nodes. */ public List<VisorGridEvent> events() { return events; } /** * @return Exceptions caught during collecting events from nodes. */ public Map<UUID, Throwable> eventsEx() { return eventsEx; } /** * @return All caches collected from nodes. */ public Map<UUID, Collection<VisorCache>> caches() { return caches; } /** * @return Exceptions caught during collecting caches from nodes. */ public Map<UUID, Throwable> cachesEx() { return cachesEx; } /** * @return All GGFS collected from nodes. */ public Map<UUID, Collection<VisorGgfs>> ggfss() { return ggfss; } /** * @return All GGFS endpoints collected from nodes. */ public Map<UUID, Collection<VisorGgfsEndpoint>> ggfsEndpoints() { return ggfsEndpoints; } /** * @return Exceptions caught during collecting GGFS from nodes. */ public Map<UUID, Throwable> ggfssEx() { return ggfssEx; } /** * @return All streamers collected from nodes. */ public Map<UUID, Collection<VisorStreamer>> streamers() { return streamers; } /** * @return Exceptions caught during collecting streamers from nodes. */ public Map<UUID, Throwable> streamersEx() { return streamersEx; } }
package org.navalplanner.business.materials.bootstrap; import org.navalplanner.business.IDataBootstrap; import org.navalplanner.business.common.exceptions.InstanceNotFoundException; import org.navalplanner.business.materials.daos.IUnitTypeDAO; import org.navalplanner.business.materials.entities.UnitType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; /** * Creates the bootstrap of the predefined {@link UnitType}. * @author Susana Montes Pedreira <[email protected]> */ @Component @Scope("singleton") public class UnitTypeBootstrap implements IDataBootstrap { @Autowired private IUnitTypeDAO unitTypeDAO; private static UnitType defaultUnitType; @Transactional @Override public void loadRequiredData() { for (PredefinedUnitTypes predefinedUnitType : PredefinedUnitTypes .values()) { UnitType type = null; try { type = unitTypeDAO .findUniqueByNameInAnotherTransaction(predefinedUnitType .getMeasure()); } catch (InstanceNotFoundException e) { type = predefinedUnitType.createUnitType(); unitTypeDAO.save(type); } if (predefinedUnitType .equals(PredefinedUnitTypes.defaultUnitType())) { defaultUnitType = type; } } } public static UnitType getDefaultUnitType() { if (defaultUnitType.isNewObject()) { defaultUnitType.dontPoseAsTransientObjectAnymore(); } return defaultUnitType; } }
package org.nd4j.linalg.jcublas.blas; import org.bytedeco.javacpp.Pointer; import org.nd4j.jita.allocator.impl.AllocationPoint; import org.nd4j.jita.allocator.pointers.CudaPointer; import org.nd4j.linalg.api.blas.impl.BaseLapack; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.linalg.api.ops.executioner.GridExecutioner; import org.nd4j.nativeblas.NativeOps; import org.nd4j.nativeblas.NativeOpsHolder; import org.nd4j.linalg.jcublas.context.CudaContext; import org.nd4j.jita.allocator.impl.AtomicAllocator; import org.nd4j.jita.allocator.Allocator; import org.nd4j.linalg.jcublas.CublasPointer; import org.nd4j.jita.allocator.pointers.cuda.cusolverDnHandle_t; import org.nd4j.jita.allocator.impl.AtomicAllocator ; import org.nd4j.linalg.api.buffer.DataBuffer; import org.nd4j.linalg.api.buffer.IntBuffer; import org.nd4j.linalg.jcublas.buffer.BaseCudaDataBuffer; import org.nd4j.linalg.jcublas.buffer.CudaIntDataBuffer; import org.nd4j.linalg.jcublas.buffer.CudaFloatDataBuffer; import org.bytedeco.javacpp.FloatPointer; import org.bytedeco.javacpp.IntPointer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import static org.bytedeco.javacpp.cusolver.*; /** * JCublas lapack * * @author Adam Gibson */ public class JcublasLapack extends BaseLapack { private NativeOps nativeOps = NativeOpsHolder.getInstance().getDeviceNativeOps(); private Allocator allocator = AtomicAllocator.getInstance(); private static Logger logger = LoggerFactory.getLogger(JcublasLapack.class); /** * LU decomposiiton of a matrix * * @param M * @param N * @param A * @param lda * @param IPIV * @param INFO */ @Override public void getrf(int M, int N, INDArray A, int lda, INDArray IPIV, INDArray INFO) { if (Nd4j.dataType() != DataBuffer.Type.FLOAT) logger.warn("FLOAT getrf called"); if (Nd4j.getExecutioner() instanceof GridExecutioner) ((GridExecutioner) Nd4j.getExecutioner()).flushQueue(); // Get context for current thread CudaContext ctx = (CudaContext) AtomicAllocator.getInstance().getDeviceContext().getContext() ; // setup the solver handles for cuSolver calls cusolverDnHandle_t handle = ctx.getSolverHandle(); cusolverDnContext solverDn = new cusolverDnContext( handle ) ; // synchronized on the solver synchronized (handle) { long result = nativeOps.setSolverStream(handle, ctx.getOldStream()); if (result == 0) throw new IllegalStateException("solverSetStream failed"); // transfer the INDArray into GPU memory CublasPointer xAPointer = new CublasPointer(A, ctx); // this output - indicates how much memory we'll need for the real operation DataBuffer worksize = Nd4j.getDataBufferFactory().createInt(1) ; int stat = cusolverDnSgetrf_bufferSize( solverDn, M, N, (FloatPointer)xAPointer.getDevicePointer(), lda, (IntPointer) worksize.addressPointer() // we intentionally use host pointer here ) ; if( stat != CUSOLVER_STATUS_SUCCESS ) { throw new IllegalStateException("cusolverDnSgetrf_bufferSize failed with code: " + stat ) ; } logger.info("Worksize returned: {}", worksize.getInt(0)); // Now allocate memory for the workspace, the permutation matrix and a return code DataBuffer work = Nd4j.getDataBufferFactory().createFloat(worksize.getInt(0)) ; //DataBuffer ipiv = Nd4j.getDataBufferFactory().createInt( IPIV.length() ) ; //DataBuffer info = Nd4j.getDataBufferFactory().createInt(1) ; AllocationPoint pointIPIV = AtomicAllocator.getInstance().getAllocationPoint(IPIV); //IntPointer ip1 = (IntPointer) AtomicAllocator.getInstance().getPointer(ipiv, ctx) ; //IntPointer ip2 = (IntPointer) ipiv.addressPointer() ; IntPointer ptr = new CudaPointer(AtomicAllocator.getInstance().getHostPointer(IPIV)).asIntPointer(); ptr.put(0, 1); ptr.put(1, 1); ptr.put(2, 1); logger.info("IPIV data before: {}", Arrays.toString(IPIV.data().asInt())); AtomicAllocator.getInstance().getAllocationPoint(IPIV).tickHostWrite(); logger.info("ipiv HS: {}", pointIPIV.isActualOnHostSide()); // DO the actual LU decomp stat = cusolverDnSgetrf( solverDn, M, N, (FloatPointer)xAPointer.getDevicePointer(), lda, new CudaPointer(AtomicAllocator.getInstance().getHostPointer(work)).asFloatPointer(), ptr , new CudaPointer(AtomicAllocator.getInstance().getHostPointer(INFO)).asIntPointer() ) ; // we do sync to make sure getr is finished ctx.syncOldStream(); logger.info("ipiv HS: {}", pointIPIV.isActualOnHostSide()); //AtomicAllocator.getInstance().getAllocationPoint(ipiv).tickHostWrite(); //ogger.info("ipiv: {}", Arrays.toString(ipiv.asInt())); logger.info("ip2[0]: {}; ip2[1]: {}; ip2[2]: {};", ptr.get(0), ptr.get(1), ptr.get(2)); AtomicAllocator.getInstance().getAllocationPoint(IPIV).tickHostWrite(); AtomicAllocator.getInstance().getAllocationPoint(IPIV).tickHostRead(); AtomicAllocator.getInstance().getAllocationPoint(INFO).tickHostWrite(); AtomicAllocator.getInstance().getAllocationPoint(A).tickHostWrite(); logger.info("IPIV data after 2: {}", Arrays.toString(IPIV.data().asInt())); if( stat != CUSOLVER_STATUS_SUCCESS ) { throw new IllegalStateException("cusolverDnSgetrf failed with code: " + stat ) ; } // Copy the results back to the input vectors// // INFO.putScalar(0,info.asInt()[0] ) ; // int xxx[] = ipiv.asInt() ; // obtain pointers // Pointer dst = AtomicAllocator.getInstance().getPointer(IPIV, ctx); // Pointer src = AtomicAllocator.getInstance().getPointer(ipiv, ctx); // device to device copy // nativeOps.memcpyAsync(dst, src, IPIV.length() * 4, 3, ctx.getSpecialStream()); // ctx.syncSpecialStream(); AtomicAllocator.getInstance().getAllocationPoint(IPIV).tickDeviceWrite(); AtomicAllocator.getInstance().getAllocationPoint(INFO).tickDeviceWrite(); AtomicAllocator.getInstance().getAllocationPoint(A).tickDeviceWrite(); //IPIV.setData( ipiv ); // now when you'll call getInt(), data will travel back to host // if( IPIV.getInt(2) != 4 ) { // System.out.println( "WTF" + xxx[2] ) ; // After we get an inplace result we should // transpose the array - because of differenes in // column- and row-major ordering between ND4J & CUDA //A.setStride( A.stride()[1], A.stride()[0] ); } // this op call is synchronous, so we don't need register action here //allocator.registerAction(ctx, A ); } /** * Generate inverse ggiven LU decomp * * @param N * @param A * @param lda * @param IPIV * @param WORK * @param lwork * @param INFO */ @Override public void getri(int N, INDArray A, int lda, int[] IPIV, INDArray WORK, int lwork, int INFO) { } }
package org.opendaylight.ovsdb.openstack.netvirt.impl; import org.opendaylight.neutron.spi.INeutronPortCRUD; import org.opendaylight.neutron.spi.NeutronPort; import org.opendaylight.neutron.spi.NeutronSecurityGroup; import org.opendaylight.ovsdb.openstack.netvirt.api.Constants; import org.opendaylight.ovsdb.openstack.netvirt.api.SecurityServicesManager; import org.opendaylight.ovsdb.schema.openvswitch.Interface; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; public class SecurityServicesImpl implements SecurityServicesManager { static final Logger logger = LoggerFactory.getLogger(TenantNetworkManagerImpl.class); private volatile INeutronPortCRUD neutronPortService; public SecurityServicesImpl() { } /** * Is security group ready. * * @param intf the intf * @return the boolean */ public boolean isPortSecurityReady(Interface intf) { logger.trace("getTenantNetworkForInterface for {}", intf); if (intf == null) return false; Map<String, String> externalIds = intf.getExternalIdsColumn().getData(); logger.trace("externalIds {}", externalIds); if (externalIds == null) return false; String neutronPortId = externalIds.get(Constants.EXTERNAL_ID_INTERFACE_ID); if (neutronPortId == null) return false; NeutronPort neutronPort = neutronPortService.getPort(neutronPortId); String deviceOwner = neutronPort.getDeviceOwner(); if (!deviceOwner.contains("compute")) { logger.debug("Port {} is not a compute host, it is a: {}", neutronPortId, deviceOwner); } logger.debug("isPortSecurityReady() is a {} ", deviceOwner); List<NeutronSecurityGroup> securityGroups = neutronPort.getSecurityGroups(); if (securityGroups.isEmpty()) { logger.debug("Check for device: {} does not contain a Security Group for port: {}", deviceOwner, neutronPortId); return false; } try { String vmPort = externalIds.get("attached-mac"); } catch(Exception e) { logger.debug("Error VMID did *NOT* work"); } logger.debug("Security Group Check {} DOES contain a Neutron Security Group", neutronPortId); return true; } /** * Gets security group in port. * * @param intf the intf * @return the security group in port */ public NeutronSecurityGroup getSecurityGroupInPort(Interface intf) { logger.trace("getTenantNetworkForInterface for {}", intf); if (intf == null) return null; Map<String, String> externalIds = intf.getExternalIdsColumn().getData(); logger.trace("externalIds {}", externalIds); if (externalIds == null) return null; String neutronPortId = externalIds.get(Constants.EXTERNAL_ID_INTERFACE_ID); if (neutronPortId == null) return null; NeutronPort neutronPort = neutronPortService.getPort(neutronPortId); List<NeutronSecurityGroup> neutronSecurityGroups = neutronPort.getSecurityGroups(); NeutronSecurityGroup neutronSecurityGroup = (NeutronSecurityGroup) neutronSecurityGroups.toArray()[0]; return neutronSecurityGroup; } }
package org.eclipse.egit.gitflow.ui.internal.dialogs; import static org.eclipse.egit.ui.internal.CommonUtils.STRING_ASCENDING_COMPARATOR; import java.util.List; import org.eclipse.egit.ui.internal.repository.tree.RepositoryTreeNodeType; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jgit.lib.Ref; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.dialogs.FilteredTree; import org.eclipse.ui.dialogs.PatternFilter; /** * Widget for viewing a filtered list of Gitflow branches. */ public class FilteredBranchesWidget { private TreeViewer branchesViewer; private final List<Ref> refs; private String prefix; FilteredBranchesWidget(List<Ref> refs, String prefix) { this.refs = refs; this.prefix = prefix; } Control create(Composite parent) { Composite area = new Composite(parent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).span(2, 1).applyTo(area); area.setLayout(new GridLayout(1, false)); PatternFilter filter = new PatternFilter() { @Override protected boolean isLeafMatch(Viewer viewer, Object element) { TreeViewer treeViewer = (TreeViewer) viewer; int numberOfColumns = treeViewer.getTree().getColumnCount(); boolean isMatch = false; for (int columnIndex = 0; columnIndex < numberOfColumns; columnIndex++) { ColumnLabelProvider labelProvider = (ColumnLabelProvider) treeViewer .getLabelProvider(columnIndex); String labelText = labelProvider.getText(element); isMatch |= wordMatches(labelText); } return isMatch; } }; filter.setIncludeLeadingWildcard(true); final FilteredTree tree = new FilteredTree(area, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION, filter, true); tree.setQuickSelectionMode(true); branchesViewer = tree.getViewer(); TreeColumn nameColumn = new TreeColumn(branchesViewer.getTree(), SWT.LEFT); branchesViewer.getTree().setLinesVisible(false); nameColumn.setAlignment(SWT.LEFT); GridDataFactory.fillDefaults().grab(true, true).applyTo(branchesViewer.getControl()); branchesViewer.setContentProvider(new BranchListContentProvider()); branchesViewer.setLabelProvider(createLabelProvider()); branchesViewer.setComparator(new ViewerComparator(STRING_ASCENDING_COMPARATOR)); branchesViewer.setInput(refs); nameColumn.pack(); branchesViewer.addFilter(createFilter()); return area; } private ViewerFilter createFilter() { return new ViewerFilter() { @Override public boolean select(Viewer viewer, Object parentElement, Object element) { return true; } }; } private ColumnLabelProvider createLabelProvider() { return new ColumnLabelProvider() { @Override public String getText(Object element) { if (element instanceof Ref) { String name = ((Ref) element).getName(); return name.substring(prefix.length()); } return super.getText(element); } @Override public Image getImage(Object element) { return RepositoryTreeNodeType.REF.getIcon(); } }; } @SuppressWarnings("unchecked") // conversion to conform to List<Ref> List<Ref> getSelection() { return ((IStructuredSelection) branchesViewer.getSelection()).toList(); } TreeViewer getBranchesList() { return branchesViewer; } }
package org.nasdanika.codegen.java.impl; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.pde.core.target.ITargetDefinition; import org.eclipse.pde.core.target.ITargetLocation; import org.eclipse.pde.core.target.ITargetPlatformService; import org.eclipse.pde.internal.core.PDECore; import org.eclipse.pde.internal.core.target.IUBundleContainer; import org.nasdanika.codegen.GeneratorController; import org.nasdanika.codegen.GenericFile; import org.nasdanika.config.Context; /** * Creates target definition using result IFile handler passed by the generic file generator. * @author Pavel Vlasov * */ public abstract class AbstractTargetPlatformGeneratorController implements GeneratorController<IFile, GenericFile> { @Override public IFile configure(GenericFile generator, Context context, IFile targetFile, SubMonitor monitor) throws Exception { ITargetPlatformService service = (ITargetPlatformService) PDECore.getDefault().acquireService(ITargetPlatformService.class); ITargetDefinition targetDefinition = service.getTarget(targetFile).getTargetDefinition(); targetDefinition.setName(getTargetName(targetFile)); configureTargetDefinition(service, targetDefinition); service.saveTargetDefinition(targetDefinition); targetDefinition.resolve(monitor.split(1)); return targetFile; } /** * Configures target definition. This implementation sets target locations. * @param service * @param targetDefinition * @throws Exception */ protected void configureTargetDefinition(ITargetPlatformService service, ITargetDefinition targetDefinition) throws Exception { TargetLocation[] targetLocations = getTargetLocations(); ITargetLocation[] iTargetLocations = new ITargetLocation[targetLocations.length]; for (int i=0; i < targetLocations.length; ++i) { iTargetLocations[i] = targetLocations[i].getITargetLocation(service); } targetDefinition.setTargetLocations(iTargetLocations); } protected String getTargetName(IFile targetFile) { return targetFile.getName(); } protected static abstract class TargetLocation { protected abstract java.net.URI[] getRepositories() throws Exception; protected class InstallableUnit { private String id; private String version; public InstallableUnit() { } public InstallableUnit(String id, String version) { this.id = id; this.version = version; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } } protected abstract InstallableUnit[] getInstallableUnits(); protected ITargetLocation getITargetLocation(ITargetPlatformService targetPlatformService) throws Exception { InstallableUnit[] installableUnits = getInstallableUnits(); String[] unitIds = new String[installableUnits.length]; String[] versions = new String[installableUnits.length]; for (int i=0; i < installableUnits.length; ++i) { unitIds[i] = installableUnits[i].getId(); versions[i] = installableUnits[i].getVersion(); } return targetPlatformService.newIULocation(unitIds, versions, getRepositories(), getResolutionFlags()); } protected int getResolutionFlags() { return IUBundleContainer.INCLUDE_SOURCE; // | IUBundleContainer.INCLUDE_REQUIRED; } } protected abstract TargetLocation[] getTargetLocations(); }
package org.jetbrains.jps.appengine.build; import com.intellij.appengine.rt.EnhancerRunner; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.execution.ParametersListUtil; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.ModuleChunk; import org.jetbrains.jps.appengine.model.JpsAppEngineExtensionService; import org.jetbrains.jps.appengine.model.JpsAppEngineModuleExtension; import org.jetbrains.jps.appengine.model.PersistenceApi; import org.jetbrains.jps.builders.ChunkBuildOutputConsumer; import org.jetbrains.jps.builders.DirtyFilesHolder; import org.jetbrains.jps.builders.FileProcessor; import org.jetbrains.jps.builders.java.JavaBuilderUtil; import org.jetbrains.jps.builders.java.JavaSourceRootDescriptor; import org.jetbrains.jps.builders.logging.ProjectBuilderLogger; import org.jetbrains.jps.incremental.*; import org.jetbrains.jps.incremental.messages.BuildMessage; import org.jetbrains.jps.incremental.messages.CompilerMessage; import org.jetbrains.jps.incremental.messages.ProgressMessage; import org.jetbrains.jps.model.JpsDummyElement; import org.jetbrains.jps.model.java.JpsJavaExtensionService; import org.jetbrains.jps.model.java.JpsJavaSdkType; import org.jetbrains.jps.model.library.sdk.JpsSdk; import org.jetbrains.jps.model.module.JpsModule; import org.jetbrains.jps.util.JpsPathUtil; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.*; /** * @author nik */ public class AppEngineEnhancerBuilder extends ModuleLevelBuilder { public static final String NAME = "Google AppEngine Enhancer"; public AppEngineEnhancerBuilder() { super(BuilderCategory.CLASS_POST_PROCESSOR); } @Override public ExitCode build(final CompileContext context, ModuleChunk chunk, DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder, ChunkBuildOutputConsumer outputConsumer) throws ProjectBuildException, IOException { boolean doneSomething = false; for (final JpsModule module : chunk.getModules()) { JpsAppEngineModuleExtension extension = JpsAppEngineExtensionService.getInstance().getExtension(module); if (extension != null && extension.isRunEnhancerOnMake()) { doneSomething |= processModule(context, dirtyFilesHolder, extension); } } return doneSomething ? ExitCode.OK : ExitCode.NOTHING_DONE; } private static boolean processModule(final CompileContext context, DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder, JpsAppEngineModuleExtension extension) throws IOException, ProjectBuildException { final Set<File> roots = new THashSet<File>(FileUtil.FILE_HASHING_STRATEGY); for (String path : extension.getFilesToEnhance()) { roots.add(new File(FileUtil.toSystemDependentName(path))); } final List<String> pathsToProcess = new ArrayList<String>(); dirtyFilesHolder.processDirtyFiles(new FileProcessor<JavaSourceRootDescriptor, ModuleBuildTarget>() { @Override public boolean apply(ModuleBuildTarget target, File file, JavaSourceRootDescriptor root) throws IOException { if (JpsPathUtil.isUnder(roots, file)) { Collection<String> outputs = context.getProjectDescriptor().dataManager.getSourceToOutputMap(target).getOutputs(file.getAbsolutePath()); if (outputs != null) { pathsToProcess.addAll(outputs); } } return true; } }); if (pathsToProcess.isEmpty()) { return false; } JpsModule module = extension.getModule(); JpsSdk<JpsDummyElement> sdk = JavaBuilderUtil.ensureModuleHasJdk(module, context, NAME); context.processMessage(new ProgressMessage("Enhancing classes in module '" + module.getName() + "'...")); List<String> vmParams = Collections.singletonList("-Xmx256m"); List<String> classpath = new ArrayList<String>(); classpath.add(extension.getToolsApiJarPath()); classpath.add(PathManager.getJarPathForClass(EnhancerRunner.class)); for (File file : JpsJavaExtensionService.dependencies(module).recursively().compileOnly().productionOnly().classes().getRoots()) { classpath.add(file.getAbsolutePath()); } List<String> programParams = new ArrayList<String>(); final File argsFile = FileUtil.createTempFile("appEngineEnhanceFiles", ".txt"); PrintWriter writer = new PrintWriter(argsFile); try { for (String path : pathsToProcess) { writer.println(FileUtil.toSystemDependentName(path)); } } finally { writer.close(); } programParams.add(argsFile.getAbsolutePath()); programParams.add("com.google.appengine.tools.enhancer.Enhance"); programParams.add("-api"); PersistenceApi api = extension.getPersistenceApi(); programParams.add(api.getEnhancerApiName()); if (api.getEnhancerVersion() == 2) { programParams.add("-enhancerVersion"); programParams.add("v2"); } programParams.add("-v"); List<String> commandLine = ExternalProcessUtil.buildJavaCommandLine(JpsJavaSdkType.getJavaExecutable(sdk), EnhancerRunner.class.getName(), Collections.<String>emptyList(), classpath, vmParams, programParams); Process process = new ProcessBuilder(commandLine).start(); ExternalEnhancerProcessHandler handler = new ExternalEnhancerProcessHandler(process, commandLine, context); handler.startNotify(); handler.waitFor(); ProjectBuilderLogger logger = context.getLoggingManager().getProjectBuilderLogger(); if (logger.isEnabled()) { logger.logCompiledPaths(pathsToProcess, NAME, "Enhancing classes:"); } return true; } @NotNull @Override public String getPresentableName() { return NAME; } private static class ExternalEnhancerProcessHandler extends EnhancerProcessHandlerBase { private final CompileContext myContext; public ExternalEnhancerProcessHandler(Process process, List<String> commandLine, CompileContext context) { super(process, ParametersListUtil.join(commandLine), null); myContext = context; } @Override protected void reportInfo(String message) { myContext.processMessage(new CompilerMessage(NAME, BuildMessage.Kind.INFO, message)); } @Override protected void reportError(String message) { myContext.processMessage(new CompilerMessage(NAME, BuildMessage.Kind.ERROR, message)); } } }
package org.eclipse.cmf.occi.core.gen.emf; import static java.util.Comparator.comparingInt; import static java.util.stream.Collectors.toMap; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.eclipse.cmf.occi.core.Action; import org.eclipse.cmf.occi.core.ArrayType; import org.eclipse.cmf.occi.core.Attribute; import org.eclipse.cmf.occi.core.BasicType; import org.eclipse.cmf.occi.core.BooleanType; import org.eclipse.cmf.occi.core.Category; import org.eclipse.cmf.occi.core.Constraint; import org.eclipse.cmf.occi.core.DataType; import org.eclipse.cmf.occi.core.EObjectType; import org.eclipse.cmf.occi.core.EnumerationLiteral; import org.eclipse.cmf.occi.core.EnumerationType; import org.eclipse.cmf.occi.core.Extension; import org.eclipse.cmf.occi.core.Kind; import org.eclipse.cmf.occi.core.Mixin; import org.eclipse.cmf.occi.core.NumericType; import org.eclipse.cmf.occi.core.RecordField; import org.eclipse.cmf.occi.core.RecordType; import org.eclipse.cmf.occi.core.StringType; import org.eclipse.cmf.occi.core.Type; import org.eclipse.cmf.occi.core.util.Occi2Ecore; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EAnnotation; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EEnumLiteral; import org.eclipse.emf.ecore.EModelElement; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EOperation; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EParameter; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.EcoreFactory; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import com.google.common.collect.Lists; /** * Convert an OCCI Extension to Ecore. */ public class OCCIExtension2Ecore { /** * Store mapping from OCCI Kind to Ecore EClass. */ private Map<Type, EClass> occiKind2emfEclass = new HashMap<Type, EClass>(); /** * Get the EClass associated to an OCCI Kind. * * @param kind the given OCCI kind. * @return the EClass. */ private EClass getMappedEClass(Type type) { EClass res = null; if (type != null) { // retrieve from currently converted kinds res = occiKind2emfEclass.get(type); if (res == null) { // retrieve from installed extensions. EPackage p = ConverterUtils.getEPackage(type); res = (EClass) p.getEClassifier(ConverterUtils.toU1Case(ConverterUtils.formatName(type.getTerm()))); // Cache it for optimizing next searches. occiKind2emfEclass.put(type, res); } } return res; } /** * Store mapping from OCCI EDataType to Ecore EClassifier. */ private Map<DataType, EClassifier> occiType2emfType = new HashMap<DataType, EClassifier>(); /** * Get the EMF data type associated to an OCCI data type. * * @param type the given OCCI data type. * @return the EMF data type. */ private EClassifier getMappedType(DataType type) { EClassifier res = null; if (type == null) { res = EcorePackage.eINSTANCE.getEString(); } else { // retrieve from currently converted data types res = occiType2emfType.get(type); if (res == null) { if (((Extension) type.eContainer()).getScheme().equals("http://schemas.ogf.org/occi/core if(type.getName().equals("String")) res = EcorePackage.eINSTANCE.getEString(); if(type.getName().equals("Boolean")) res = EcorePackage.eINSTANCE.getEBoolean(); if(type.getName().equals("Integer")) res = EcorePackage.eINSTANCE.getEBigInteger(); } else { // retrieve from installed extensions. EPackage p = ConverterUtils.getEPackage(type); res = p.getEClassifier(type.getName()); // Cache it for optimizing next searches. } occiType2emfType.put(type, res); } } //System.out.println("occiType2emfType "+occiType2emfType); return res; } /** * Convert an OCCI extension to an Ecore package. * * @param extension the OCCI extension to convert. * @return the resulting Ecore package. */ public EPackage convertExtension(Extension extension) { // Create the Ecore package. EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage(); // Set the name of the Ecore package. String formattedName = formatExtensionName(extension); ePackage.setName(formattedName); // Set the name space prefix of the Ecore package. ePackage.setNsPrefix(formattedName); // Set the URI of the Ecore package. ePackage.setNsURI(Occi2Ecore.convertOcciScheme2EcoreNamespace(extension.getScheme())); // fetch occi package // but won't solve issue if user wants to use types from installed // models // EClass root = EcoreFactory.eINSTANCE.createEClass(); // ePackage.getEClassifiers().add(root); // root.setName(ConverterUtils.toU1Case(extension.getName()+"Configuration")); // root.getESuperTypes().add(OCCIPackage.eINSTANCE.getConfiguration()); // Convert all data types of the OCCI extension to data types of the // Ecore package. for (DataType type : extension.getTypes()) { // // Create the EMF type from the OCCI data type. EClassifier createdEMFType = null; if (type instanceof StringType) { createdEMFType = createStringType((StringType) type); } if (type instanceof NumericType) { createdEMFType = createNumericType((NumericType) type); } if (type instanceof BooleanType) { createdEMFType = createBooleanType((BooleanType) type); } if (type instanceof EnumerationType) { createdEMFType = createEnumerationType((EnumerationType) type); } if (type instanceof EObjectType) { createdEMFType = createEObjectType((EObjectType) type); } if (type instanceof ArrayType) { createdEMFType = createArrayType((ArrayType) type); } if (type instanceof RecordType) { createdEMFType = createRecordType((RecordType) type); } // Cache the copied data type to search it later. occiType2emfType.put(type, createdEMFType); // Add the data type to the Ecore package. ePackage.getEClassifiers().add(createdEMFType); } // Resolve types of arrays attributes and record attributes // Why here: pattern matching for (DataType type : extension.getTypes()) { if (type instanceof ArrayType) { completeArrayTypeFeatures((ArrayType) type, (EClass) occiType2emfType.get(type), ePackage); } if (type instanceof RecordType) { completeRecordTypeFeatures((RecordType) type, (EClass) occiType2emfType.get(type)); } } // Convert all OCCI kinds. for (Kind kind : extension.getKinds()) { // Convert each OCCI kind to an Ecore class. EClass convertKind = convertKind(kind); // Add the Ecore class to the Ecore package. if (convertKind != null) { ePackage.getEClassifiers().add(convertKind); } } // Convert all OCCI mixins. for (Mixin mixin : extension.getMixins()) { EClass convertMixin = convertMixin(mixin); if (convertMixin != null) { ePackage.getEClassifiers().add(convertMixin); } } // Resolve inheritance between OCCI kinds. for (Kind kind : extension.getKinds()) { // System.out.println("kind "+kind); // Get the Ecore class of this OCCI kind. EClass mappedEClass = getMappedEClass(kind); // System.out.println("getMappedEClass(kind) "+getMappedEClass(kind)); // If kind has a parent kind then if (kind.getParent() != null) { // Get the Ecore class of the OCCI kind's parent. EClass mappedParentEClass = getMappedEClass(kind.getParent()); // System.out.println("kind.getParent() "+kind.getParent()); // System.out.println("getMappedEClass(kind.getParent()) // "+getMappedEClass(kind.getParent())); if (mappedParentEClass != null) { // The Ecore class of the kind's parent is a super type of // the Ecore class of the OCCI kind. // System.out.println("mappedParentEClass " + mappedParentEClass + // mappedEClass.getEPackage()); mappedEClass.getESuperTypes().add(mappedParentEClass); } else { // Should never happen! throw new IllegalArgumentException("Not found: " + kind.getParent()); } } } // Resolve inheritance between OCCI mixins. for (Mixin mixin : extension.getMixins()) { // System.out.println("mixin "+mixin); // Get the Ecore class of this OCCI kind. // System.out.println("mappedParentEClass " + mixin); EClass mappedEClass = getMappedEClass(mixin); // System.out.println("getMappedEClass(mixin) "+getMappedEClass(mixin)); // System.out.println("mappedParentEClass " + mappedEClass); // If kind has a parent kind then if (mixin.getDepends() != null) { // Get the Ecore class of the OCCI kind's parent. for (Mixin superMixin : mixin.getDepends()) { EClass mappedParentEClass = getMappedEClass(superMixin); // System.out.println("superMixin "+superMixin); // System.out.println("mappedParentEClass "+mappedParentEClass); if (mappedParentEClass != null) { // The Ecore class of the kind's parent is a super type of // the Ecore class of the OCCI kind. // System.out.println("mappedParentEClass " + mappedParentEClass + // mappedEClass.getEPackage()); mappedEClass.getESuperTypes().add(mappedParentEClass); } else { // Should never happen! throw new IllegalArgumentException("Not found: " + superMixin); } } } addSuperTypeFromOCCI(mappedEClass, "MixinBase"); } // System.out.println(occiKind2emfEclass); return ePackage; } // add inheritance to depends // for (Mixin superMixin : mixin.getDepends()) { // EClass mappedParentEClass = getMappedEClass(superMixin); // if (mappedParentEClass != null) { // // The Ecore class of the depend is a super type of // // the Ecore class of the OCCI mixin. // eClass.getESuperTypes().add(mappedParentEClass); // } else { // // Should never happen! public static String formatExtensionName(Extension extension) { return ConverterUtils .formatName(extension.getName().replaceFirst("OCCI ", "").replaceFirst("OCCIware ", "").toLowerCase()) .replaceAll("-", "_"); } protected EClass convertMixin(Mixin mixin) { EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName(ConverterUtils.toU1Case(ConverterUtils.formatName(mixin.getTerm()))); occiKind2emfEclass.put(mixin, eClass); for (Attribute attribute : mixin.getAttributes()) { EStructuralFeature convertAttribute = convertAttribute(attribute); if (convertAttribute != null) { eClass.getEStructuralFeatures().add(convertAttribute); } } for (Action action : mixin.getActions()) { EOperation convertAction = convertAction(action); if (convertAction != null) { eClass.getEOperations().add(convertAction); } } // Add OCL constraints convertConstraints(eClass, mixin); if (mixin.getApplies().size() > 0) { if (mixin.getConstraints().size() > 0) { // So, it exists emf and ocl annotations EAnnotation annotation_emf = eClass.getEAnnotation("http: annotation_emf.getDetails().put("constraints", annotation_emf.getDetails().get("constraints") + " appliesConstraint"); EAnnotation annotation_ocl = eClass.getEAnnotation("http: annotation_ocl.getDetails().put("appliesConstraint", createAppliesContraintBody(mixin)); } else { // EMF Annotation EAnnotation annotation_emf = EcoreFactory.eINSTANCE.createEAnnotation(); annotation_emf.setSource("http: // OCL Annotation EAnnotation annotation_ocl = EcoreFactory.eINSTANCE.createEAnnotation(); annotation_ocl.setSource("http: annotation_ocl.getDetails().put("appliesConstraint", createAppliesContraintBody(mixin)); annotation_emf.getDetails().put("constraints", "appliesConstraint"); eClass.getEAnnotations().add(annotation_emf); eClass.getEAnnotations().add(annotation_ocl); } } return eClass; } private String createAppliesContraintBody(Mixin mixin) { String appliesBody = ""; for (Kind kind : mixin.getApplies()) { if (!(mixin.getApplies().get(0) == kind)) appliesBody += " or "; appliesBody += "self.entity.oclIsKindOf("; if (((Extension) kind.eContainer()).getScheme().equals("http://schemas.ogf.org/occi/core appliesBody += "occi"; else appliesBody += formatExtensionName((Extension) kind.eContainer()); appliesBody += "::"; appliesBody += ConverterUtils.toU1Case(ConverterUtils.formatName(kind.getTerm())); appliesBody += ")"; } return appliesBody; } private Resource createAndLoadOCCIEcoreResource(String pathToDDLEcore) { // creating a proper URI is vitally important since this is how // referenced objects in the is ecore file will be found from the ecore // file that we produce. ResourceSet resSet = new ResourceSetImpl(); final URI uri = URI.createPlatformPluginURI(pathToDDLEcore, true); Resource res = resSet.createResource(uri); try { res.load(Collections.emptyMap()); } catch (IOException e) { e.printStackTrace(); } return res; } private void addSuperTypeFromOCCI(EClass subClass, String esuperClassName) { Resource oCCIEcoreResource = createAndLoadOCCIEcoreResource("org.eclipse.cmf.occi.core/model/OCCI.ecore"); // of course, in production code we would fail here if there were no // contents or they weren't of type EPackage. final EPackage oCCIEPackage = (EPackage) oCCIEcoreResource.getContents().get(0); final EClass eSuperClass = (EClass) oCCIEPackage.getEClassifier(esuperClassName); subClass.getESuperTypes().add(eSuperClass); } private EEnum createEnumerationType(EnumerationType type) { EEnum eenum = EcoreFactory.eINSTANCE.createEEnum(); eenum.setName(type.getName()); int value = 0; for (EnumerationLiteral literal : type.getLiterals()) { EEnumLiteral eenumliteral = EcoreFactory.eINSTANCE.createEEnumLiteral(); eenum.getELiterals().add(eenumliteral); eenumliteral.setName(literal.getName()); eenumliteral.setLiteral(literal.getName()); eenumliteral.setValue(value); value++; if (literal.getDocumentation() != null) { attachInfo(eenumliteral, literal.getDocumentation()); } } if (type.getDocumentation() != null) { attachInfo(eenum, type.getDocumentation()); } return eenum; } private EDataType createEObjectType(EObjectType type) { EDataType edatatype = EcoreFactory.eINSTANCE.createEDataType(); edatatype.setName(type.getName()); edatatype.setInstanceTypeName(type.getInstanceClassName()); if (type.getDocumentation() != null) { attachInfo(edatatype, type.getDocumentation()); } return edatatype; } private EDataType createBooleanType(BooleanType type) { EDataType edatatype = EcoreFactory.eINSTANCE.createEDataType(); edatatype.setName(type.getName()); edatatype.setInstanceTypeName("java.lang.Boolean"); if (type.getDocumentation() != null) { attachInfo(edatatype, type.getDocumentation()); } return edatatype; } private EDataType createNumericType(NumericType type) { EDataType edatatype = EcoreFactory.eINSTANCE.createEDataType(); edatatype.setName(type.getName()); switch (type.getType()) { case BYTE: edatatype.setInstanceTypeName("java.lang.Byte"); break; case DOUBLE: edatatype.setInstanceTypeName("java.lang.Double"); break; case FLOAT: edatatype.setInstanceTypeName("java.lang.Float"); break; case INTEGER: edatatype.setInstanceTypeName("java.lang.Integer"); break; case LONG: edatatype.setInstanceTypeName("java.lang.Long"); break; case SHORT: edatatype.setInstanceTypeName("java.lang.Short"); break; case BIG_DECIMAL: edatatype.setInstanceTypeName("java.math.BigDecimal"); break; default: break; } if (type.isSetTotalDigits() || type.isSetMinInclusive() || type.isSetMinExclusive() || type.isSetMaxInclusive() || type.isSetMaxExclusive()) { EAnnotation eannotation = EcoreFactory.eINSTANCE.createEAnnotation(); edatatype.getEAnnotations().add(eannotation); eannotation.setSource("http:///org/eclipse/emf/ecore/util/ExtendedMetaData"); if (type.isSetTotalDigits()) eannotation.getDetails().put("totalDigits", Integer.toString(type.getTotalDigits())); if (type.isSetMinInclusive()) eannotation.getDetails().put("minInclusive", type.getMinInclusive()); if (type.isSetMinExclusive()) eannotation.getDetails().put("minExclusive", type.getMinExclusive()); if (type.isSetMaxInclusive()) eannotation.getDetails().put("maxInclusive", type.getMaxInclusive()); if (type.isSetMaxExclusive()) eannotation.getDetails().put("maxExclusive", type.getMaxExclusive()); } if (type.getDocumentation() != null) { attachInfo(edatatype, type.getDocumentation()); } return edatatype; } private EDataType createStringType(StringType type) { EDataType edatatype = EcoreFactory.eINSTANCE.createEDataType(); edatatype.setName(type.getName()); edatatype.setInstanceTypeName("java.lang.String"); if (type.getDocumentation() != null) { attachInfo(edatatype, type.getDocumentation()); } if (type.isSetLength() || type.isSetMaxLength() || type.isSetMinLength() || type.getPattern() != null) { EAnnotation eannotation = EcoreFactory.eINSTANCE.createEAnnotation(); edatatype.getEAnnotations().add(eannotation); eannotation.setSource("http:///org/eclipse/emf/ecore/util/ExtendedMetaData"); if (type.isSetLength()) eannotation.getDetails().put("length", Integer.toString(type.getLength())); if (type.isSetMaxLength()) eannotation.getDetails().put("maxLength", Integer.toString(type.getMaxLength())); if (type.isSetMinLength()) eannotation.getDetails().put("minLength", Integer.toString(type.getMinLength())); if (type.getPattern() != null) { if (type.getPattern() != "") eannotation.getDetails().put("pattern", type.getPattern()); } } return edatatype; } private EClass createArrayType(ArrayType arrayType) { // System.out.println("maaaaap " + occiType2emfType); EClass type = EcoreFactory.eINSTANCE.createEClass(); type.setName(arrayType.getName()); if (arrayType.getDocumentation() != null) { attachInfo(type, arrayType.getDocumentation()); } return type; } private void completeArrayTypeFeatures(ArrayType arrayType, EClass type, EPackage ePackage) { if (!(arrayType.getType() instanceof RecordType || arrayType.getType() instanceof ArrayType)) { // if the type of ArrayType is a primitive type then we create an // attribute EAttribute values = EcoreFactory.eINSTANCE.createEAttribute(); type.getEStructuralFeatures().add(values); values.setName("values"); values.setUpperBound(-1); // Set the unique of the Ecore reference to false. values.setUnique(false); values.setEType(getMappedType(arrayType.getType())); } else { // otherwise, we create a reference to the generated EClass EReference values = EcoreFactory.eINSTANCE.createEReference(); type.getEStructuralFeatures().add(values); values.setName(arrayType.getName().toLowerCase() + "Values"); values.setUpperBound(-1); values.setEType(getMappedType(arrayType.getType())); values.setContainment(true); } } private EClass createRecordType(RecordType recordType) { // System.out.println("maaaaap " + occiType2emfType); EClass type = EcoreFactory.eINSTANCE.createEClass(); type.setName(recordType.getName()); if (recordType.getDocumentation() != null) { attachInfo(type, recordType.getDocumentation()); } return type; } private void completeRecordTypeFeatures(RecordType recordType, EClass type) { for (RecordField rf : recordType.getRecordFields()) { // if the type of the recordField is different to arraytype or a recordtype // it will be translated into a EMF attribute if (!(rf.getType() instanceof RecordType || rf.getType() instanceof ArrayType)) { EAttribute attribute = EcoreFactory.eINSTANCE.createEAttribute(); type.getEStructuralFeatures().add(attribute); attribute.setName(rf.getName()); attribute.setLowerBound(1); attribute.setEType(getMappedType(rf.getType())); // Set the default value of the Ecore attribute. String defaultValue = rf.getDefault(); if (defaultValue != null && !defaultValue.isEmpty()) { attribute.setDefaultValue(defaultValue); } // The Ecore attribute is required when the OCCI attribute is required. if (attribute.isRequired()) { attribute.setLowerBound(1); } attachInfo(attribute, rf.getDescription()); } else { // otherwise, il will be translated into an EMF reference EReference reference = EcoreFactory.eINSTANCE.createEReference(); type.getEStructuralFeatures().add(reference); reference.setName(rf.getName()); // The Ecore attribute is required when the OCCI attribute is required. if (rf.isRequired()) { reference.setLowerBound(1); } reference.setUpperBound(1); reference.setEType(getMappedType(rf.getType())); reference.setContainment(true); // Set the default value of the Ecore attribute. // Default values for EMF EReference is not supported // see // https://www.eclipse.org/forums/index.php?t=msg&th=131049&goto=406266&#msg_406266 // String defaultValue = rf.getDefault(); // if (defaultValue != null && !defaultValue.isEmpty()) { // reference.setDefaultValue(defaultValue); attachInfo(reference, rf.getDescription()); } } } /** * Convert an OCCI kind to an Ecore class. * * @param kind the OCCI kind to convert. * @return the resulting Ecore class. */ protected EClass convertKind(Kind kind) { // Create the Ecore class. EClass eClass = EcoreFactory.eINSTANCE.createEClass(); // Set the name of the Ecore class. eClass.setName(ConverterUtils.toU1Case(ConverterUtils.formatName(kind.getTerm()))); // Convert all attributes of the OCCI kind. for (Attribute attribute : kind.getAttributes()) { // Convert each OCCI attribute to an Ecore attribute. EStructuralFeature convertAttribute = convertAttribute(attribute); if (convertAttribute != null) { // Add the Ecore attribute as a structural feature of the Ecore // class. eClass.getEStructuralFeatures().add(convertAttribute); } } // Convert all actions of the OCCI kind. for (Action action : kind.getActions()) { // Convert each OCCI action to an Ecore operation. EOperation convertAction = convertAction(action); if (convertAction != null) { // Add the Ecore action as an operation of the Ecore class. eClass.getEOperations().add(convertAction); } } attachInfo(eClass, kind.getTitle()); // Keep the Ecore class into a cache to search it later. occiKind2emfEclass.put(kind, eClass); // Convert all constraints of the OCCI kind. convertConstraints(eClass, kind); if (kind.getSource().size() > 0) { addSourceConstraint(kind, eClass); } if (kind.getTarget().size() > 0) { addTargetConstraint(kind, eClass); } return eClass; } private void addTargetConstraint(Kind kind, EClass eClass) { if (eClass.getEAnnotation("http: // So, it exists emf and ocl annotations EAnnotation annotation_emf = eClass.getEAnnotation("http: annotation_emf.getDetails().put("constraints", annotation_emf.getDetails().get("constraints") + " targetConstraint"); EAnnotation annotation_ocl = eClass.getEAnnotation("http: annotation_ocl.getDetails().put("targetConstraint", createTargetConstraintBody(kind)); } else { // EMF Annotation EAnnotation annotation_emf = EcoreFactory.eINSTANCE.createEAnnotation(); annotation_emf.setSource("http: // OCL Annotation EAnnotation annotation_ocl = EcoreFactory.eINSTANCE.createEAnnotation(); annotation_ocl.setSource("http: annotation_ocl.getDetails().put("targetConstraint", createTargetConstraintBody(kind)); annotation_emf.getDetails().put("constraints", "targetConstraint"); eClass.getEAnnotations().add(annotation_emf); eClass.getEAnnotations().add(annotation_ocl); } } private String createTargetConstraintBody(Kind kind) { StringBuilder constraint = new StringBuilder(); for (Kind targetKind : kind.getTarget()) { String epackage_name = formatExtensionName((Extension) targetKind.eContainer()); if (kind.getTarget().get(0) == targetKind) { constraint.append("self.target.oclIsKindOf(" + epackage_name + "::" + ConverterUtils.toU1Case(ConverterUtils.formatName(targetKind.getTerm())) + ")"); } else { constraint.append(" or self.target.oclIsKindOf(" + epackage_name + "::" + ConverterUtils.toU1Case(ConverterUtils.formatName(targetKind.getTerm())) + ")"); } } return constraint.toString(); } private void addSourceConstraint(Kind kind, EClass eClass) { if (eClass.getEAnnotation("http: // So, it exists emf and ocl annotations EAnnotation annotation_emf = eClass.getEAnnotation("http: annotation_emf.getDetails().put("constraints", annotation_emf.getDetails().get("constraints") + " sourceConstraint"); EAnnotation annotation_ocl = eClass.getEAnnotation("http: annotation_ocl.getDetails().put("sourceConstraint", createSourceConstraintBody(kind)); } else { // EMF Annotation EAnnotation annotation_emf = EcoreFactory.eINSTANCE.createEAnnotation(); annotation_emf.setSource("http: // OCL Annotation EAnnotation annotation_ocl = EcoreFactory.eINSTANCE.createEAnnotation(); annotation_ocl.setSource("http: annotation_ocl.getDetails().put("sourceConstraint", createSourceConstraintBody(kind)); annotation_emf.getDetails().put("constraints", "sourceConstraint"); eClass.getEAnnotations().add(annotation_emf); eClass.getEAnnotations().add(annotation_ocl); } } private String createSourceConstraintBody(Kind kind) { StringBuilder constraint = new StringBuilder(); for (Kind sourceKind : kind.getSource()) { String epackage_name = formatExtensionName((Extension) sourceKind.eContainer()); if (kind.getSource().get(0) == sourceKind) { constraint.append("self.source.oclIsKindOf(" + epackage_name + "::" + ConverterUtils.toU1Case(ConverterUtils.formatName(sourceKind.getTerm())) + ")"); } else { constraint.append(" or self.source.oclIsKindOf(" + epackage_name + "::" + ConverterUtils.toU1Case(ConverterUtils.formatName(sourceKind.getTerm())) + ")"); } } return constraint.toString(); } protected void convertConstraints(EClass eClass, Type type) { if (type.getConstraints().size() > 0) { // EMF Annotation EAnnotation annotation_emf = EcoreFactory.eINSTANCE.createEAnnotation(); annotation_emf.setSource("http: String value = ""; // OCL Annotation EAnnotation annotation_ocl = EcoreFactory.eINSTANCE.createEAnnotation(); annotation_ocl.setSource("http: for (Constraint constraint : type.getConstraints()) { annotation_ocl.getDetails().put(constraint.getName(), convertbody(constraint.getBody(), (Extension) type.eContainer())); if (value.equals("")) { value += constraint.getName(); } else { value += " "; value += constraint.getName(); } // convertbody(constraint.getBody(), (Extension) // type.eContainer()); } annotation_emf.getDetails().put("constraints", value); eClass.getEAnnotations().add(annotation_emf); eClass.getEAnnotations().add(annotation_ocl); } } public String convertbody(String body, Extension extension) { // System.out.println(body); List<EObject> attributesList = Lists.newArrayList(extension.eAllContents()).stream() .filter(eobject -> eobject instanceof Attribute).collect(Collectors.toList()); HashMap<String, String> attributesMap = new HashMap<String, String>(); for (EObject attribute : attributesList) { attributesMap.put(((Attribute) attribute).getName(), Occi2Ecore.convertOcciAttributeName2EcoreAttributeName(((Attribute) attribute).getName())); } Map<String, String> attributesSorted = attributesMap.entrySet().stream() .sorted(comparingInt(e -> e.getKey().length())) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> { throw new AssertionError(); }, LinkedHashMap::new)); ArrayList<String> attributesKeys = new ArrayList<String>(attributesSorted.keySet()); for (int i = attributesKeys.size() - 1; i >= 0; i // System.out.println("bottom "+attributesSorted.get(attributesKeys.get(i))); body = body.replace(attributesKeys.get(i), attributesSorted.get(attributesKeys.get(i))); } // System.out.println(body); /* * This part convert the Category OCCI ids of Ecore ids for example from * IpNetworkInterface to Ipnetworkinterface */ List<EObject> categoriesList = Lists.newArrayList(extension.eAllContents()).stream() .filter(eobject -> eobject instanceof Category).collect(Collectors.toList()); HashMap<String, String> categoriesMap = new HashMap<String, String>(); for (EObject category : categoriesList) { categoriesMap.put(((Category) category).getName(), ConverterUtils.toU1Case(ConverterUtils.formatName(((Category) category).getTerm()))); // System.out.println(((Category) category).getName()); // System.out.println(ConverterUtils.toU1Case(ConverterUtils.formatName(((Category) // category).getTerm()))); } Map<String, String> categoriesSorted = categoriesMap.entrySet().stream() .sorted(comparingInt(e -> e.getKey().length())) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> { throw new AssertionError(); }, LinkedHashMap::new)); // System.out.println("sorted "+categoriesSorted); ArrayList<String> keys = new ArrayList<String>(categoriesSorted.keySet()); for (int i = keys.size() - 1; i >= 0; i // System.out.println("bottom "+categoriesSorted.get(keys.get(i))); body = body.replace(keys.get(i), categoriesSorted.get(keys.get(i))); } // System.out.println(body); return body; } /** * Convert an OCCI action to an Ecore operation. * * @param action the OCCI action to convert. * @return the resulting Ecore operation. */ protected EOperation convertAction(Action action) { // Create the Ecore operation. EOperation eOperation = EcoreFactory.eINSTANCE.createEOperation(); // Set the name of the Ecore operation. eOperation.setName(ConverterUtils.formatName(action.getTerm())); // Convert all attributes of the OCCI action. for (Attribute attribute : action.getAttributes()) { // Each OCCI attribute of the OCCI action is converted to an Ecore // parameter of the Ecore operation. EParameter convertParameter = convertParameter(attribute); if (convertParameter != null) { // Add the Ecore parameter to the Ecore operation. eOperation.getEParameters().add(convertParameter); } } attachInfo(eOperation, action.getTitle()); return eOperation; } /** * Convert an OCCI action's attribute to an Ecore operation parameter. * * @param attribute the OCCI attribute to convert. * @return the resulting Ecore operation parameter. */ protected EParameter convertParameter(Attribute attribute) { // Create an Ecore parameter. EParameter eParam = EcoreFactory.eINSTANCE.createEParameter(); // Set the name of the Ecore parameter. eParam.setName(Occi2Ecore.convertOcciAttributeName2EcoreAttributeName(attribute.getName())); // Set the type of the Ecore parameter. eParam.setEType(getMappedType(attribute.getType())); // If the OCCI attribute is required then the Ecore parameter is also // required. if (attribute.isRequired()) { eParam.setLowerBound(1); } attachInfo(eParam, attribute.getDescription()); return eParam; } /** * Convert an OCCI attribute to an Ecore attribute. * * @param attribute the OCCI attribute to convert. * @return the resulting Ecore attribute. */ protected EStructuralFeature convertAttribute(Attribute attribute) { if (attribute.getType() instanceof BasicType || attribute.getType() instanceof EnumerationType) { // Create an Ecore attribute. EAttribute eAttr = EcoreFactory.eINSTANCE.createEAttribute(); // Set the name of the Ecore attribute. eAttr.setName(Occi2Ecore.convertOcciAttributeName2EcoreAttributeName(attribute.getName())); // Set the type of the Ecore attribute. eAttr.setEType(getMappedType(attribute.getType())); // Set the default value of the Ecore attribute. String defaultValue = attribute.getDefault(); if (defaultValue != null && !defaultValue.isEmpty()) { eAttr.setDefaultValue(defaultValue); } // The Ecore attribute is required when the OCCI attribute is required. if (attribute.isRequired()) { eAttr.setLowerBound(1); } attachInfo(eAttr, attribute.getDescription()); return eAttr; } else { // Create an Ecore reference. EReference eRef = EcoreFactory.eINSTANCE.createEReference(); // Set the name of the Ecore reference. eRef.setName(Occi2Ecore.convertOcciAttributeName2EcoreAttributeName(attribute.getName())); // Set the type of the Ecore reference. eRef.setEType(getMappedType(attribute.getType())); // Set the containment of the Ecore reference to true. eRef.setContainment(true); // The Ecore reference is required when the OCCI attribute is required. if (attribute.isRequired()) { eRef.setLowerBound(1); } attachInfo(eRef, attribute.getDescription()); return eRef; } } private void attachInfo(EModelElement element, String value) { EAnnotation annotation = EcoreFactory.eINSTANCE.createEAnnotation(); annotation.setSource("http: element.getEAnnotations().add(annotation); if (value != null) annotation.getDetails().put("documentation", value); else annotation.getDetails().put("documentation", ""); } }
package org.jkiss.dbeaver.ext.postgresql.model; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.ext.postgresql.PostgreUtils; import org.jkiss.dbeaver.model.DBPDataKind; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.exec.DBCException; import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement; import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet; import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession; import org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCObjectCache; import org.jkiss.dbeaver.model.impl.jdbc.struct.JDBCDataType; import org.jkiss.dbeaver.model.meta.Property; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSDataType; import org.jkiss.dbeaver.model.struct.DBSEntityAssociation; import org.jkiss.dbeaver.model.struct.DBSEntityConstraint; import org.jkiss.dbeaver.model.struct.DBSEntityType; import org.jkiss.utils.ArrayUtils; import org.jkiss.utils.CommonUtils; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; /** * PostgreTypeType */ public class PostgreDataType extends JDBCDataType<PostgreSchema> implements PostgreClass { static final Log log = Log.getLog(PostgreDataType.class); private static final String CAT_MAIN = "Main"; private static final String CAT_MISC = "Miscellaneous"; private static final String CAT_MODIFIERS = "Modifiers"; private static final String CAT_FUNCTIONS = "Functions"; private static final String CAT_ARRAY = "Array"; private static String[] OID_TYPES = new String[] { "regproc", "regprocedure", "regoper", "regoperator", "regclass", "regtype", "regconfig", "regdictionary", }; private int typeId; private PostgreTypeType typeType; private PostgreTypeCategory typeCategory; private final int ownerId; private boolean isByValue; private boolean isPreferred; private String arrayDelimiter; private int classId; private int elementTypeId; private int arrayItemTypeId; private String inputFunc; private String outputFunc; private String receiveFunc; private String sendFunc; private String modInFunc; private String modOutFunc; private String analyzeFunc; private PostgreTypeAlign align = PostgreTypeAlign.c; private PostgreTypeStorage storage = PostgreTypeStorage.p; private boolean isNotNull; private int baseTypeId; private int typeMod; private int arrayDim; private int collationId; private String defaultValue; private final AttributeCache attributeCache; private Object[] enumValues; public PostgreDataType(@NotNull JDBCSession monitor, @NotNull PostgreSchema owner, int typeId, int valueType, String name, int length, JDBCResultSet dbResult) throws DBException { super(owner, valueType, name, null, false, true, length, -1, -1); this.typeId = typeId; this.typeType = PostgreTypeType.b; try { String typTypeStr = JDBCUtils.safeGetString(dbResult, "typtype"); if (typTypeStr != null && !typTypeStr.isEmpty()) { this.typeType = PostgreTypeType.valueOf(typTypeStr.toLowerCase(Locale.ENGLISH)); } } catch (Exception e) { log.debug(e); } this.typeCategory = PostgreTypeCategory.X; try { String typCategoryStr = JDBCUtils.safeGetString(dbResult, "typcategory"); if (typCategoryStr != null && !typCategoryStr.isEmpty()) { this.typeCategory = PostgreTypeCategory.valueOf(typCategoryStr.toUpperCase(Locale.ENGLISH)); } } catch (Exception e) { log.debug(e); } this.ownerId = JDBCUtils.safeGetInt(dbResult, "typowner"); this.isByValue = JDBCUtils.safeGetBoolean(dbResult, "typbyval"); this.isPreferred = JDBCUtils.safeGetBoolean(dbResult, "typispreferred"); this.arrayDelimiter = JDBCUtils.safeGetString(dbResult, "typdelim"); this.classId = JDBCUtils.safeGetInt(dbResult, "typrelid"); this.elementTypeId = JDBCUtils.safeGetInt(dbResult, "typelem"); this.arrayItemTypeId = JDBCUtils.safeGetInt(dbResult, "typarray"); this.inputFunc = JDBCUtils.safeGetString(dbResult, "typinput"); this.outputFunc = JDBCUtils.safeGetString(dbResult, "typoutput"); this.receiveFunc = JDBCUtils.safeGetString(dbResult, "typreceive"); this.sendFunc = JDBCUtils.safeGetString(dbResult, "typsend"); this.modInFunc = JDBCUtils.safeGetString(dbResult, "typmodin"); this.modOutFunc = JDBCUtils.safeGetString(dbResult, "typmodout"); this.analyzeFunc = JDBCUtils.safeGetString(dbResult, "typanalyze"); try { this.align = PostgreTypeAlign.valueOf(JDBCUtils.safeGetString(dbResult, "typalign")); } catch (Exception e) { log.debug(e); } try { this.storage = PostgreTypeStorage.valueOf(JDBCUtils.safeGetString(dbResult, "typstorage")); } catch (Exception e) { log.debug(e); } this.isNotNull = JDBCUtils.safeGetBoolean(dbResult, "typnotnull"); this.baseTypeId = JDBCUtils.safeGetInt(dbResult, "typbasetype"); this.typeMod = JDBCUtils.safeGetInt(dbResult, "typtypmod"); this.arrayDim = JDBCUtils.safeGetInt(dbResult, "typndims"); this.collationId = JDBCUtils.safeGetInt(dbResult, "typcollation"); this.defaultValue = JDBCUtils.safeGetString(dbResult, "typdefault"); this.attributeCache = hasAttributes() ? new AttributeCache() : null; if (typeCategory == PostgreTypeCategory.E) { readEnumValues(monitor); } } private void readEnumValues(JDBCSession session) throws DBException { try (JDBCPreparedStatement dbStat = session.prepareStatement( "SELECT e.enumlabel \n" + "FROM pg_catalog.pg_enum e\n" + "WHERE e.enumtypid=?")) { dbStat.setInt(1, getObjectId()); try (JDBCResultSet rs = dbStat.executeQuery()) { List<String> values = new ArrayList<>(); while (rs.nextRow()) { values.add(JDBCUtils.safeGetString(rs, 1)); } enumValues = values.toArray(); } } catch (SQLException e) { throw new DBException("Error reading enum values", e, getDataSource()); } } @NotNull @Override public PostgreDataSource getDataSource() { return (PostgreDataSource) super.getDataSource(); } @NotNull @Override public PostgreDatabase getDatabase() { return getParentObject().getDatabase(); } @Override public DBPDataKind getDataKind() { switch (typeCategory) { case A: return DBPDataKind.ARRAY; case B: return DBPDataKind.BOOLEAN; case C: return DBPDataKind.STRUCT; case D: return DBPDataKind.DATETIME; case E: return DBPDataKind.OBJECT; case N: return DBPDataKind.NUMERIC; case S: return DBPDataKind.STRING; } return super.getDataKind(); } @Nullable @Override public DBSDataType getComponentType(@NotNull DBRProgressMonitor monitor) throws DBCException { return getElementType(); } @Nullable @Override public Object geTypeExtension() { return typeCategory; } @Override public int getObjectId() { return typeId; } @Property(category = CAT_MAIN, viewable = true, order = 10) public PostgreTypeType getTypeType() { return typeType; } @Property(category = CAT_MAIN, viewable = true, order = 11) public PostgreTypeCategory getTypeCategory() { return typeCategory; } @Property(category = CAT_MAIN, viewable = true, order = 12) public PostgreDataType getBaseType() { return resolveType(baseTypeId); } @Property(category = CAT_MAIN, viewable = true, order = 13) public PostgreDataType getElementType() { return elementTypeId == 0 ? null : resolveType(elementTypeId); } @Property(category = CAT_MAIN, order = 15) public PostgreAuthId getOwner(DBRProgressMonitor monitor) throws DBException { return PostgreUtils.getObjectById(monitor, getDatabase().authIdCache, getDatabase(), ownerId); } @Property(category = CAT_MISC) public boolean isByValue() { return isByValue; } @Property(category = CAT_MISC) public boolean isPreferred() { return isPreferred; } @Property(category = CAT_MISC) public String getDefaultValue() { return defaultValue; } @Property(category = CAT_FUNCTIONS) public String getInputFunc() { return inputFunc; } @Property(category = CAT_FUNCTIONS) public String getOutputFunc() { return outputFunc; } @Property(category = CAT_FUNCTIONS) public String getReceiveFunc() { return receiveFunc; } @Property(category = CAT_FUNCTIONS) public String getSendFunc() { return sendFunc; } @Property(category = CAT_FUNCTIONS) public String getModInFunc() { return modInFunc; } @Property(category = CAT_FUNCTIONS) public String getModOutFunc() { return modOutFunc; } @Property(category = CAT_FUNCTIONS) public String getAnalyzeFunc() { return analyzeFunc; } @Property(category = CAT_MODIFIERS) public PostgreTypeAlign getAlign() { return align; } @Property(category = CAT_MODIFIERS) public PostgreTypeStorage getStorage() { return storage; } @Property(category = CAT_MODIFIERS) public boolean isNotNull() { return isNotNull; } @Property(category = CAT_MODIFIERS) public int getTypeMod() { return typeMod; } @Property(category = CAT_MODIFIERS) public int getCollationId() { return collationId; } @Property(category = CAT_ARRAY) public String getArrayDelimiter() { return arrayDelimiter; } @Property(category = CAT_ARRAY) public PostgreDataType getArrayItemType() { return arrayItemTypeId == 0 ? null : resolveType(arrayItemTypeId); } // Plain type public boolean isPlainType() { return arrayItemTypeId != 0; } @Property(category = CAT_ARRAY) public int getArrayDim() { return arrayDim; } public boolean hasAttributes() { return typeType == PostgreTypeType.c && classId >= 0; } private PostgreDataType resolveType(int typeId) { if (typeId <= 0) { return null; } final PostgreDataType dataType = getDatabase().dataTypeCache.getDataType(typeId); if (dataType == null) { log.debug("Data type '" + typeId + "' not found"); } return dataType; } public static PostgreDataType readDataType(@NotNull JDBCSession session, @NotNull PostgreDatabase owner, @NotNull JDBCResultSet dbResult) throws SQLException, DBException { int schemaId = JDBCUtils.safeGetInt(dbResult, "typnamespace"); final PostgreSchema schema = owner.getSchema(dbResult.getSourceStatement().getConnection().getProgressMonitor(), schemaId); int typeId = JDBCUtils.safeGetInt(dbResult, "oid"); String name = JDBCUtils.safeGetString(dbResult, "typname"); if (CommonUtils.isEmpty(name)) { return null; } int typeLength = JDBCUtils.safeGetInt(dbResult, "typlen"); PostgreTypeCategory typeCategory; final String catString = JDBCUtils.safeGetString(dbResult, "typcategory"); if (catString == null) { typeCategory = null; } else { try { typeCategory = PostgreTypeCategory.valueOf(catString.toUpperCase()); } catch (IllegalArgumentException e) { log.debug(e); typeCategory = null; } } int valueType; if (ArrayUtils.contains(OID_TYPES, name) || name.equals("hstore")) { valueType = Types.VARCHAR; } else { if (typeCategory == null) { final int typElem = JDBCUtils.safeGetInt(dbResult, "typelem"); // In old PostgreSQL versions switch (typeId) { case PostgreOid.BIT: valueType = Types.BIT; break; case PostgreOid.BOOL: valueType = Types.BOOLEAN; break; case PostgreOid.INT2: valueType = Types.SMALLINT; break; case PostgreOid.INT4: valueType = Types.INTEGER; break; case PostgreOid.INT8: valueType = Types.BIGINT; break; case PostgreOid.FLOAT4: valueType = Types.FLOAT; break; case PostgreOid.FLOAT8: valueType = Types.DOUBLE; break; case PostgreOid.NUMERIC: valueType = Types.NUMERIC; break; case PostgreOid.CHAR: valueType = Types.CHAR; break; case PostgreOid.VARCHAR: valueType = Types.VARCHAR; break; case PostgreOid.DATE: valueType = Types.DATE; break; case PostgreOid.TIME: case PostgreOid.TIMETZ: valueType = Types.TIME; break; case PostgreOid.TIMESTAMP: case PostgreOid.TIMESTAMPTZ: valueType = Types.TIMESTAMP; break; case PostgreOid.BYTEA: valueType = Types.BINARY; break; case PostgreOid.CHAR_ARRAY: valueType = Types.CHAR; break; case PostgreOid.BPCHAR: valueType = Types.CHAR; break; case PostgreOid.XML: valueType = Types.SQLXML; break; default: if (typElem > 0) { valueType = Types.ARRAY; } else { valueType = Types.OTHER; } break; } } else { switch (typeCategory) { case A: valueType = Types.ARRAY; break; case P: valueType = Types.OTHER; break; case B: valueType = Types.BOOLEAN; break; case C: valueType = Types.STRUCT; break; case D: if (name.startsWith("timestamp")) { valueType = Types.TIMESTAMP; } else if (name.startsWith("date")) { valueType = Types.DATE; } else { valueType = Types.TIME; } break; case N: valueType = Types.NUMERIC; if (name.equals("numeric")) { valueType = Types.NUMERIC; } else if (name.startsWith("float")) { switch (typeLength) { case 4: valueType = Types.FLOAT; break; case 8: valueType = Types.DOUBLE; break; } } else { switch (typeLength) { case 2: valueType = Types.SMALLINT; break; case 4: valueType = Types.INTEGER; break; case 8: valueType = Types.BIGINT; break; } } break; case S: // if (name.equals("text")) { // valueType = Types.CLOB; // } else { valueType = Types.VARCHAR; break; case U: switch (name) { case "bytea": valueType = Types.BINARY; break; case "xml": valueType = Types.SQLXML; break; default: valueType = Types.OTHER; break; } break; default: valueType = Types.OTHER; break; } } } return new PostgreDataType( session, schema, typeId, valueType, name, typeLength, dbResult); } @NotNull @Override public DBSEntityType getEntityType() { return DBSEntityType.TYPE; } @Override public Collection<PostgreDataTypeAttribute> getAttributes(@NotNull DBRProgressMonitor monitor) throws DBException { return attributeCache == null ? null : attributeCache.getAllObjects(monitor, this); } @Override public PostgreDataTypeAttribute getAttribute(@NotNull DBRProgressMonitor monitor, @NotNull String attributeName) throws DBException { return attributeCache == null ? null : attributeCache.getObject(monitor, this, attributeName); } @Override public Collection<? extends DBSEntityConstraint> getConstraints(@NotNull DBRProgressMonitor monitor) throws DBException { return null; } @Override public Collection<? extends DBSEntityAssociation> getAssociations(@NotNull DBRProgressMonitor monitor) throws DBException { return null; } @Override public Collection<? extends DBSEntityAssociation> getReferences(@NotNull DBRProgressMonitor monitor) throws DBException { return null; } @Override public boolean refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException { if (attributeCache != null) { attributeCache.clearCache(); } if (typeCategory == PostgreTypeCategory.E) { try (JDBCSession session = DBUtils.openMetaSession(monitor, getDataSource(), "Refresh enum values")) { readEnumValues(session); } } return true; } public Object[] getEnumValues() { return enumValues; } class AttributeCache extends JDBCObjectCache<PostgreDataType, PostgreDataTypeAttribute> { @Override protected JDBCStatement prepareObjectsStatement(@NotNull JDBCSession session, @NotNull PostgreDataType postgreDataType) throws SQLException { JDBCPreparedStatement dbStat = session.prepareStatement( "SELECT c.relname,a.*,pg_catalog.pg_get_expr(ad.adbin, ad.adrelid) as def_value,dsc.description" + "\nFROM pg_catalog.pg_attribute a" + "\nINNER JOIN pg_catalog.pg_class c ON (a.attrelid=c.oid)" + "\nLEFT OUTER JOIN pg_catalog.pg_attrdef ad ON (a.attrelid=ad.adrelid AND a.attnum = ad.adnum)" + "\nLEFT OUTER JOIN pg_catalog.pg_description dsc ON (c.oid=dsc.objoid AND a.attnum = dsc.objsubid)" + "\nWHERE a.attnum > 0 AND NOT a.attisdropped AND c.oid=?" + "\nORDER BY a.attnum"); dbStat.setInt(1, postgreDataType.classId); return dbStat; } @Override protected PostgreDataTypeAttribute fetchObject(@NotNull JDBCSession session, @NotNull PostgreDataType postgreDataType, @NotNull JDBCResultSet resultSet) throws SQLException, DBException { return new PostgreDataTypeAttribute(postgreDataType, resultSet); } } }
package com.intellij.structuralsearch.impl.matcher.compiler; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.lang.Language; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiErrorElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.tree.LeafElement; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.util.PsiUtilBase; import com.intellij.structuralsearch.*; import com.intellij.structuralsearch.impl.matcher.CompiledPattern; import com.intellij.structuralsearch.impl.matcher.MatcherImplUtil; import com.intellij.structuralsearch.impl.matcher.PatternTreeContext; import com.intellij.structuralsearch.impl.matcher.filters.LexicalNodesFilter; import com.intellij.structuralsearch.impl.matcher.filters.NodeFilter; import com.intellij.structuralsearch.impl.matcher.handlers.MatchPredicate; import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler; import com.intellij.structuralsearch.impl.matcher.iterators.ArrayBackedNodeIterator; import com.intellij.structuralsearch.impl.matcher.predicates.*; import com.intellij.structuralsearch.plugin.ui.Configuration; import com.intellij.util.IncorrectOperationException; import gnu.trove.TIntArrayList; import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.regex.*; import java.util.regex.Matcher; /** * Compiles the handlers for usability */ public class PatternCompiler { private static CompileContext lastTestingContext; public static final Key<List<PsiElement>> ALTERNATIVE_PATTERN_ROOTS = new Key<List<PsiElement>>("ALTERNATIVE_PATTERN_ROOTS"); public static void transformOldPattern(MatchOptions options) { StringToConstraintsTransformer.transformOldPattern(options); } public static CompiledPattern compilePattern(final Project project, final MatchOptions options) throws MalformedPatternException, UnsupportedOperationException { return new WriteAction<CompiledPattern>() { protected void run(Result<CompiledPattern> result) throws Throwable { result.setResult(compilePatternImpl(project, options)); } }.execute().getResultObject(); } public static String getLastFindPlan() { return ((TestModeOptimizingSearchHelper)lastTestingContext.getSearchHelper()).getSearchPlan(); } private static CompiledPattern compilePatternImpl(Project project,MatchOptions options) { FileType fileType = options.getFileType(); assert fileType instanceof LanguageFileType; Language language = ((LanguageFileType)fileType).getLanguage(); StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(language); assert profile != null; CompiledPattern result = profile.createCompiledPattern(); final String[] prefixes = result.getTypedVarPrefixes(); assert prefixes.length > 0; final CompileContext context = new CompileContext(); if (ApplicationManager.getApplication().isUnitTestMode()) lastTestingContext = context; /*CompiledPattern result = options.getFileType() == StdFileTypes.JAVA ? new JavaCompiledPattern() : new XmlCompiledPattern();*/ try { context.init(result, options, project, options.getScope() instanceof GlobalSearchScope); List<PsiElement> elements = compileByAllPrefixes(project, options, result, context, prefixes); context.getPattern().setNodes( new ArrayBackedNodeIterator(PsiUtilBase.toPsiElementArray(elements)) ); if (context.getSearchHelper().doOptimizing() && context.getSearchHelper().isScannedSomething()) { final Set<PsiFile> set = context.getSearchHelper().getFilesSetToScan(); final List<PsiFile> filesToScan = new ArrayList<PsiFile>(set.size()); final GlobalSearchScope scope = (GlobalSearchScope)options.getScope(); for (final PsiFile file : set) { if (!scope.contains(file.getVirtualFile())) { continue; } if (file instanceof PsiFileImpl) { ((PsiFileImpl)file).clearCaches(); } filesToScan.add(file); } if (filesToScan.size() == 0) { throw new MalformedPatternException(SSRBundle.message("ssr.will.not.find.anything")); } result.setScope( new LocalSearchScope(PsiUtilBase.toPsiElementArray(filesToScan)) ); } } finally { context.clear(); } return result; } @NotNull private static List<PsiElement> compileByAllPrefixes(Project project, MatchOptions options, CompiledPattern pattern, CompileContext context, String[] applicablePrefixes) { if (applicablePrefixes.length == 0) { return Collections.emptyList(); } LinkedList<PsiElement> elements = doCompile(project, options, pattern, new ConstantPrefixProvider(applicablePrefixes[0]), context); if (elements.size() == 0) { return elements; } final PsiFile file = elements.getFirst().getContainingFile(); if (file == null) { return elements; } final PsiElement last = elements.getLast(); final Pattern[] patterns = new Pattern[applicablePrefixes.length]; for (int i = 0; i < applicablePrefixes.length; i++) { String s = StructuralSearchUtil.shieldSpecialChars(applicablePrefixes[i]); patterns[i] = Pattern.compile(s + "\\w+\\b"); } final int[] varEndOffsets = findAllTypedVarOffsets(file, patterns); final int patternEndOffset = last.getTextRange().getEndOffset(); if (elements.size() == 0 || checkErrorElements(file, patternEndOffset, patternEndOffset, varEndOffsets, true) != Boolean.TRUE) { return elements; } final int varCount = varEndOffsets.length; final String[] prefixSequence = new String[varCount]; for (int i = 0; i < varCount; i++) { prefixSequence[i] = applicablePrefixes[0]; } final List<PsiElement> finalElements = compileByPrefixes(project, options, pattern, context, applicablePrefixes, patterns, prefixSequence, 0); return finalElements != null ? finalElements : doCompile(project, options, pattern, new ConstantPrefixProvider(applicablePrefixes[0]), context); } @Nullable private static List<PsiElement> compileByPrefixes(Project project, MatchOptions options, CompiledPattern pattern, CompileContext context, String[] applicablePrefixes, Pattern[] substitutionPatterns, String[] prefixSequence, int index) { if (index >= prefixSequence.length) { final LinkedList<PsiElement> elements = doCompile(project, options, pattern, new ArrayPrefixProvider(prefixSequence), context); if (elements.size() == 0) { return elements; } final PsiElement parent = elements.getFirst().getParent(); final PsiElement last = elements.getLast(); final int[] varEndOffsets = findAllTypedVarOffsets(parent.getContainingFile(), substitutionPatterns); final int patternEndOffset = last.getTextRange().getEndOffset(); return checkErrorElements(parent, patternEndOffset, patternEndOffset, varEndOffsets, false) != Boolean.TRUE ? elements : null; } String[] alternativeVariant = null; for (String applicablePrefix : applicablePrefixes) { prefixSequence[index] = applicablePrefix; LinkedList<PsiElement> elements = doCompile(project, options, pattern, new ArrayPrefixProvider(prefixSequence), context); if (elements.size() == 0) { return elements; } final PsiFile file = elements.getFirst().getContainingFile(); if (file == null) { return elements; } final int[] varEndOffsets = findAllTypedVarOffsets(file, substitutionPatterns); final int offset = varEndOffsets[index]; final int patternEndOffset = elements.getLast().getTextRange().getEndOffset(); final Boolean result = checkErrorElements(file, offset, patternEndOffset, varEndOffsets, false); if (result == Boolean.TRUE) { continue; } if (result == Boolean.FALSE || (result == null && alternativeVariant == null)) { final List<PsiElement> finalElements = compileByPrefixes(project, options, pattern, context, applicablePrefixes, substitutionPatterns, prefixSequence, index + 1); if (finalElements != null) { if (result == Boolean.FALSE) { return finalElements; } alternativeVariant = new String[prefixSequence.length]; System.arraycopy(prefixSequence, 0, alternativeVariant, 0, prefixSequence.length); } } } return alternativeVariant != null ? compileByPrefixes(project, options, pattern, context, applicablePrefixes, substitutionPatterns, alternativeVariant, index + 1) : null; } @NotNull private static int[] findAllTypedVarOffsets(final PsiFile file, final Pattern[] substitutionPatterns) { final TIntHashSet result = new TIntHashSet(); file.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { super.visitElement(element); if (element instanceof LeafElement) { final String text = element.getText(); for (Pattern pattern : substitutionPatterns) { final Matcher matcher = pattern.matcher(text); while (matcher.find()) { result.add(element.getTextRange().getStartOffset() + matcher.end()); } } } } }); final int[] resultArray = result.toArray(); Arrays.sort(resultArray); return resultArray; } /** * False: there are no error elements before offset, except patternEndOffset * Null: there are only error elements located exactly after template variables or at the end of the pattern * True: otherwise */ private static Boolean checkErrorElements(PsiElement element, final int offset, final int patternEndOffset, final int[] varEndOffsets, final boolean strict) { final TIntArrayList errorOffsets = new TIntArrayList(); final boolean[] containsErrorTail = {false}; final TIntHashSet varEndOffsetsSet = new TIntHashSet(varEndOffsets); element.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { super.visitElement(element); if (!(element instanceof PsiErrorElement)) { return; } final int startOffset = element.getTextRange().getStartOffset(); if ((strict || !varEndOffsetsSet.contains(startOffset)) && startOffset != patternEndOffset) { errorOffsets.add(startOffset); } if (startOffset == offset) { containsErrorTail[0] = true; } } }); for (int i = 0; i < errorOffsets.size(); i++) { final int errorOffset = errorOffsets.get(i); if (errorOffset <= offset) { return true; } } return containsErrorTail[0] ? null : false; } private interface PrefixProvider { String getPrefix(int varIndex); } private static class ConstantPrefixProvider implements PrefixProvider { private final String myPrefix; private ConstantPrefixProvider(String prefix) { myPrefix = prefix; } @Override public String getPrefix(int varIndex) { return myPrefix; } } private static class ArrayPrefixProvider implements PrefixProvider { private final String[] myPrefixes; private ArrayPrefixProvider(String[] prefixes) { myPrefixes = prefixes; } @Override public String getPrefix(int varIndex) { return myPrefixes[varIndex]; } } private static LinkedList<PsiElement> doCompile(Project project, MatchOptions options, CompiledPattern result, PrefixProvider prefixProvider, CompileContext context) { result.clearHandlers(); context.init(result, options, project, options.getScope() instanceof GlobalSearchScope); final StringBuilder buf = new StringBuilder(); Template template = TemplateManager.getInstance(project).createTemplate("","",options.getSearchPattern()); int segmentsCount = template.getSegmentsCount(); String text = template.getTemplateText(); buf.setLength(0); int prevOffset = 0; for(int i=0;i<segmentsCount;++i) { final int offset = template.getSegmentOffset(i); final String name = template.getSegmentName(i); final String prefix = prefixProvider.getPrefix(i); buf.append(text.substring(prevOffset,offset)); buf.append(prefix); buf.append(name); MatchVariableConstraint constraint = options.getVariableConstraint(name); if (constraint==null) { // we do not edited the constraints constraint = new MatchVariableConstraint(); constraint.setName( name ); options.addVariableConstraint(constraint); } SubstitutionHandler handler = result.createSubstitutionHandler( name, prefix + name, constraint.isPartOfSearchResults(), constraint.getMinCount(), constraint.getMaxCount(), constraint.isGreedy() ); if(constraint.isWithinHierarchy()) { handler.setSubtype(true); } if(constraint.isStrictlyWithinHierarchy()) { handler.setStrictSubtype(true); } MatchPredicate predicate; if (constraint.getRegExp()!=null && constraint.getRegExp().length() > 0) { predicate = new RegExpPredicate( constraint.getRegExp(), options.isCaseSensitiveMatch(), name, constraint.isWholeWordsOnly(), constraint.isPartOfSearchResults() ); if (constraint.isInvertRegExp()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.isReadAccess()) { predicate = new ReadPredicate(); if (constraint.isInvertReadAccess()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.isWriteAccess()) { predicate = new WritePredicate(); if (constraint.isInvertWriteAccess()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.isReference()) { predicate = new ReferencePredicate( constraint.getNameOfReferenceVar() ); if (constraint.isInvertReference()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.getNameOfExprType()!=null && constraint.getNameOfExprType().length() > 0 ) { predicate = new ExprTypePredicate( constraint.getNameOfExprType(), name, constraint.isExprTypeWithinHierarchy(), options.isCaseSensitiveMatch(), constraint.isPartOfSearchResults() ); if (constraint.isInvertExprType()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.getNameOfFormalArgType()!=null && constraint.getNameOfFormalArgType().length() > 0) { predicate = new FormalArgTypePredicate( constraint.getNameOfFormalArgType(), name, constraint.isFormalArgTypeWithinHierarchy(), options.isCaseSensitiveMatch(), constraint.isPartOfSearchResults() ); if (constraint.isInvertFormalType()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } addScriptConstraint(name, constraint, handler); if (constraint.getContainsConstraint() != null && constraint.getContainsConstraint().length() > 0) { predicate = new ContainsPredicate(name, constraint.getContainsConstraint()); if (constraint.isInvertContainsConstraint()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.getWithinConstraint() != null && constraint.getWithinConstraint().length() > 0) { assert false; } prevOffset = offset; } MatchVariableConstraint constraint = options.getVariableConstraint(Configuration.CONTEXT_VAR_NAME); if (constraint != null) { SubstitutionHandler handler = result.createSubstitutionHandler( Configuration.CONTEXT_VAR_NAME, Configuration.CONTEXT_VAR_NAME, constraint.isPartOfSearchResults(), constraint.getMinCount(), constraint.getMaxCount(), constraint.isGreedy() ); if (constraint.getWithinConstraint() != null && constraint.getWithinConstraint().length() > 0) { MatchPredicate predicate = new WithinPredicate(Configuration.CONTEXT_VAR_NAME, constraint.getWithinConstraint(), project); if (constraint.isInvertWithinConstraint()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } addScriptConstraint(Configuration.CONTEXT_VAR_NAME, constraint, handler); } buf.append(text.substring(prevOffset,text.length())); PsiElement[] matchStatements; try { matchStatements = MatcherImplUtil.createTreeFromText(buf.toString(), PatternTreeContext.Block, options.getFileType(), options.getDialect(), options.getPatternContext(), project, false); if (matchStatements.length==0) throw new MalformedPatternException(); } catch (IncorrectOperationException e) { throw new MalformedPatternException(e.getMessage()); } NodeFilter filter = LexicalNodesFilter.getInstance(); GlobalCompilingVisitor compilingVisitor = new GlobalCompilingVisitor(); compilingVisitor.compile(matchStatements,context); LinkedList<PsiElement> elements = new LinkedList<PsiElement>(); for (PsiElement matchStatement : matchStatements) { if (!filter.accepts(matchStatement)) { elements.add(matchStatement); } } // delete last brace ApplicationManager.getApplication().runWriteAction( new DeleteNodesAction(compilingVisitor.getLexicalNodes()) ); return elements; } private static void addScriptConstraint(String name, MatchVariableConstraint constraint, SubstitutionHandler handler) { MatchPredicate predicate; if (constraint.getScriptCodeConstraint()!= null && constraint.getScriptCodeConstraint().length() > 2) { final String script = StringUtil.stripQuotesAroundValue(constraint.getScriptCodeConstraint()); final String s = ScriptSupport.checkValidScript(script); if (s != null) throw new MalformedPatternException("Script constraint for " + constraint.getName() + " has problem "+s); predicate = new ScriptPredicate(name, script); addPredicate(handler,predicate); } } static void addPredicate(SubstitutionHandler handler, MatchPredicate predicate) { if (handler.getPredicate()==null) { handler.setPredicate(predicate); } else { handler.setPredicate( new BinaryPredicate( handler.getPredicate(), predicate, false ) ); } } }
package com.facebook.react.uimanager; import android.content.Context; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.config.ReactFeatureFlags; import com.facebook.react.touch.JSResponderHandler; import com.facebook.react.touch.ReactInterceptingViewGroup; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.annotations.ReactPropGroup; import com.facebook.react.uimanager.annotations.ReactPropertyHolder; import com.facebook.yoga.YogaMeasureMode; import java.util.Map; /** * Class responsible for knowing how to create and update catalyst Views of a given type. It is also * responsible for creating and updating CSSNodeDEPRECATED subclasses used for calculating position * and size for the corresponding native view. */ @ReactPropertyHolder public abstract class ViewManager<T extends View, C extends ReactShadowNode> extends BaseJavaModule { /** * For the vast majority of ViewManagers, you will not need to override this. Only override this * if you really know what you're doing and have a very unique use-case. * * @param viewToUpdate * @param props * @param stateWrapper */ public void updateProperties(@NonNull T viewToUpdate, ReactStylesDiffMap props) { final ViewManagerDelegate<T> delegate; if (ReactFeatureFlags.useViewManagerDelegates && (delegate = getDelegate()) != null) { ViewManagerPropertyUpdater.updateProps(delegate, viewToUpdate, props); } else { ViewManagerPropertyUpdater.updateProps(this, viewToUpdate, props); } onAfterUpdateTransaction(viewToUpdate); } /** * Override this method and return an instance of {@link ViewManagerDelegate} if the props of the * view managed by this view manager should be set via this delegate. The provided instance will * then get calls to {@link ViewManagerDelegate#setProperty(View, String, Object)} for every prop * that must be updated and it's the delegate's responsibility to apply these values to the view. * * <p>By default this method returns {@code null}, which means that the view manager doesn't have * a delegate and the view props should be set internally by the view manager itself. * * @return an instance of {@link ViewManagerDelegate} if the props of the view managed by this * view manager should be set via this delegate */ @Nullable protected ViewManagerDelegate<T> getDelegate() { return null; } /** Creates a view and installs event emitters on it. */ private final @NonNull T createView( @NonNull ThemedReactContext reactContext, JSResponderHandler jsResponderHandler) { return createView(reactContext, null, null, jsResponderHandler); } /** Creates a view with knowledge of props and state. */ public @NonNull T createView( @NonNull ThemedReactContext reactContext, @Nullable ReactStylesDiffMap props, @Nullable StateWrapper stateWrapper, JSResponderHandler jsResponderHandler) { T view = createViewInstance(reactContext, props, stateWrapper); if (view instanceof ReactInterceptingViewGroup) { ((ReactInterceptingViewGroup) view).setOnInterceptTouchEventListener(jsResponderHandler); } return view; } /** * @return the name of this view manager. This will be the name used to reference this view * manager from JavaScript in createReactNativeComponentClass. */ public abstract @NonNull String getName(); /** * This method should return a subclass of {@link ReactShadowNode} which will be then used for * measuring position and size of the view. In most of the cases this should just return an * instance of {@link ReactShadowNode} */ public C createShadowNodeInstance() { throw new RuntimeException("ViewManager subclasses must implement createShadowNodeInstance()"); } public @NonNull C createShadowNodeInstance(@NonNull ReactApplicationContext context) { return createShadowNodeInstance(); } /** * This method should return {@link Class} instance that represent type of shadow node that this * manager will return from {@link #createShadowNodeInstance}. * * <p>This method will be used in the bridge initialization phase to collect properties exposed * using {@link ReactProp} (or {@link ReactPropGroup}) annotation from the {@link ReactShadowNode} * subclass specific for native view this manager provides. * * @return {@link Class} object that represents type of shadow node used by this view manager. */ public abstract Class<? extends C> getShadowNodeClass(); /** * Subclasses should return a new View instance of the proper type. * * @param reactContext */ protected abstract @NonNull T createViewInstance(@NonNull ThemedReactContext reactContext); /** * Subclasses should return a new View instance of the proper type. This is an optional method * that will call createViewInstance for you. Override it if you need props upon creation of the * view. * * @param reactContext */ protected @NonNull T createViewInstance( @NonNull ThemedReactContext reactContext, @Nullable ReactStylesDiffMap initialProps, @Nullable StateWrapper stateWrapper) { T view = createViewInstance(reactContext); addEventEmitters(reactContext, view); if (initialProps != null) { updateProperties(view, initialProps); } if (stateWrapper != null) { Object extraData = updateState(view, initialProps, stateWrapper); if (extraData != null) { updateExtraData(view, extraData); } } return view; } /** * Called when view is detached from view hierarchy and allows for some additional cleanup by the * {@link ViewManager} subclass. */ public void onDropViewInstance(@NonNull T view) {} /** * Subclasses can override this method to install custom event emitters on the given View. You * might want to override this method if your view needs to emit events besides basic touch events * to JS (e.g. scroll events). */ protected void addEventEmitters(@NonNull ThemedReactContext reactContext, @NonNull T view) {} /** * Callback that will be triggered after all properties are updated in current update transaction * (all @ReactProp handlers for properties updated in current transaction have been called). If * you want to override this method you should call super.onAfterUpdateTransaction from it as the * parent class of the ViewManager may rely on callback being executed. */ protected void onAfterUpdateTransaction(@NonNull T view) {} /** * Subclasses can implement this method to receive an optional extra data enqueued from the * corresponding instance of {@link ReactShadowNode} in {@link * ReactShadowNode#onCollectExtraUpdates}. * * <p>Since css layout step and ui updates can be executed in separate thread apart of setting * x/y/width/height this is the recommended and thread-safe way of passing extra data from css * node to the native view counterpart. * * <p>TODO T7247021: Replace updateExtraData with generic update props mechanism after D2086999 */ public abstract void updateExtraData(@NonNull T root, Object extraData); /** * Subclasses may use this method to receive events/commands directly from JS through the {@link * UIManager}. Good example of such a command would be {@code scrollTo} request with coordinates * for a {@link ScrollView} instance. * * <p>This method is deprecated use {@link #receiveCommand(View, String, ReadableArray)} instead. * * @param root View instance that should receive the command * @param commandId code of the command * @param args optional arguments for the command */ @Deprecated public void receiveCommand(@NonNull T root, int commandId, @Nullable ReadableArray args) {} /** * Subclasses may use this method to receive events/commands directly from JS through the {@link * UIManager}. Good example of such a command would be {@code scrollTo} request with coordinates * for a {@link ReactScrollView} instance. * * @param root View instance that should receive the command * @param commandId code of the command * @param args optional arguments for the command */ public void receiveCommand(@NonNull T root, String commandId, @Nullable ReadableArray args) {} /** * Subclasses of {@link ViewManager} that expect to receive commands through {@link * UIManagerModule#dispatchViewManagerCommand} should override this method returning the map * between names of the commands and IDs that are then used in {@link #receiveCommand} method * whenever the command is dispatched for this particular {@link ViewManager}. * * @return map of string to int mapping of the expected commands */ public @Nullable Map<String, Integer> getCommandsMap() { return null; } /** * Returns a map of config data passed to JS that defines eligible events that can be placed on * native views. This should return bubbling directly-dispatched event types and specify what * names should be used to subscribe to either form (bubbling/capturing). * * <p>Returned map should be of the form: * * <pre> * { * "onTwirl": { * "phasedRegistrationNames": { * "bubbled": "onTwirl", * "captured": "onTwirlCaptured" * } * } * } * </pre> */ public @Nullable Map<String, Object> getExportedCustomBubblingEventTypeConstants() { return null; } /** * Returns a map of config data passed to JS that defines eligible events that can be placed on * native views. This should return non-bubbling directly-dispatched event types. * * <p>Returned map should be of the form: * * <pre> * { * "onTwirl": { * "registrationName": "onTwirl" * } * } * </pre> */ public @Nullable Map<String, Object> getExportedCustomDirectEventTypeConstants() { return null; } /** * Returns a map of view-specific constants that are injected to JavaScript. These constants are * made accessible via UIManager.<ViewName>.Constants. */ public @Nullable Map<String, Object> getExportedViewConstants() { return null; } /** * Returns a {@link Map<String, String>} representing the native props of the view manager. The * Map contains the names (key) and types (value) of the ViewManager's props. */ public Map<String, String> getNativeProps() { return ViewManagerPropertyUpdater.getNativeProps(getClass(), getShadowNodeClass()); } /** * Subclasses can implement this method to receive state updates shared between all instances of * this component type. */ public @Nullable Object updateState( @NonNull T view, ReactStylesDiffMap props, @Nullable StateWrapper stateWrapper) { return null; } /** * Subclasses can override this method to implement custom measure functions for the ViewManager * * @param context {@link com.facebook.react.bridge.ReactContext} used for the view. * @param localData {@link ReadableMap} containing "local data" defined in C++ * @param props {@link ReadableMap} containing JS props * @param state {@link ReadableMap} containing state defined in C++ * @param width width of the view (usually zero) * @param widthMode widthMode used during calculation of layout * @param height height of the view (usually zero) * @param heightMode widthMode used during calculation of layout * @param attachmentsPositions {@link int[]} array containing 2x times the amount of attachments * of the view. An attachment represents the position of an inline view that needs to be * rendered inside a component and it requires the content of the parent view in order to be * positioned. This array is meant to be used by the platform to RETURN the position of each * attachment, as a result of the calculation of layout. (e.g. this array is used to measure * inlineViews that are rendered inside Text components). On most of the components this array * will be contain a null value. * <p>Even values will represent the TOP of each attachment, Odd values represent the LEFT of * each attachment. * @return result of calculation of layout for the arguments received as a parameter. */ public long measure( Context context, ReadableMap localData, ReadableMap props, ReadableMap state, float width, YogaMeasureMode widthMode, float height, YogaMeasureMode heightMode, @Nullable float[] attachmentsPositions) { return 0; } /** * Subclasses can override this method to set padding for the given View in Fabric. Since not all * components support setting padding, the default implementation of this method does nothing. */ public void setPadding(T view, int left, int top, int right, int bottom) {} }
package org.protempa.bp.commons.dsb.relationaldb; import org.protempa.bp.commons.dsb.relationaldb.ColumnSpec.Constraint; abstract class WhereConstraintProcessor { private final ColumnSpec columnSpec; private final Constraint constraint; private final WhereClause whereClause; private final Object[] sqlCodes; private final TableAliaser referenceIndices; protected WhereConstraintProcessor(ColumnSpec columnSpec, Constraint constraint, WhereClause whereClause, Object[] sqlCodes, TableAliaser referenceIndices) { this.columnSpec = columnSpec; this.constraint = constraint; this.whereClause = whereClause; this.sqlCodes = sqlCodes; this.referenceIndices = referenceIndices; } static WhereConstraintProcessor getInstance(ColumnSpec columnSpec, Constraint constraint, WhereClause whereClause, Object[] sqlCodes, TableAliaser referenceIndices) { switch (constraint) { case EQUAL_TO: return new EqualToWhereConstraintProcessor(columnSpec, constraint, whereClause, sqlCodes, referenceIndices); case NOT_EQUAL_TO: return new NotEqualToWhereConstraintProcessor(columnSpec, constraint, whereClause, sqlCodes, referenceIndices); case LESS_THAN: case LESS_THAN_OR_EQUAL_TO: case GREATER_THAN: case GREATER_THAN_OR_EQUAL_TO: return new InequalityWhereConstraintProcessor(columnSpec, constraint, whereClause, sqlCodes, referenceIndices); case LIKE: return new LikeWhereConstraintProcessor(columnSpec, constraint, whereClause, sqlCodes, referenceIndices); default: throw new AssertionError("Invalid constraint: " + constraint); } } protected ColumnSpec getColumnSpec() { return columnSpec; } protected Constraint getConstraint() { return constraint; } protected WhereClause getWhereClause() { return whereClause; } protected Object[] getSqlCodes() { return sqlCodes; } protected TableAliaser getReferenceIndices() { return referenceIndices; } protected abstract String processConstraint(); }
package io.github.benas.randombeans.randomizers; import com.github.javafaker.Faker; import io.github.benas.randombeans.api.Randomizer; import java.util.Locale; public abstract class FakerBasedRandomizer<T> extends AbstractRandomizer<T> { protected Faker faker; protected FakerBasedRandomizer() { faker = new Faker(Locale.ENGLISH); } protected FakerBasedRandomizer(final long seed) { this(seed, Locale.ENGLISH); } protected FakerBasedRandomizer(final long seed, final Locale locale) { super(seed); faker = new Faker(locale, random); } @Override public abstract T getRandomValue(); }
package net.runelite.client.plugins.cluescrolls.clues.hotcold; import java.awt.Rectangle; import lombok.AllArgsConstructor; import lombok.Getter; import net.runelite.api.coords.WorldPoint; import static net.runelite.client.plugins.cluescrolls.clues.hotcold.HotColdArea.ASGARNIA; import static net.runelite.client.plugins.cluescrolls.clues.hotcold.HotColdArea.DESERT; import static net.runelite.client.plugins.cluescrolls.clues.hotcold.HotColdArea.FELDIP_HILLS; import static net.runelite.client.plugins.cluescrolls.clues.hotcold.HotColdArea.FREMENNIK_PROVINCE; import static net.runelite.client.plugins.cluescrolls.clues.hotcold.HotColdArea.KANDARIN; import static net.runelite.client.plugins.cluescrolls.clues.hotcold.HotColdArea.KARAMJA; import static net.runelite.client.plugins.cluescrolls.clues.hotcold.HotColdArea.MISTHALIN; import static net.runelite.client.plugins.cluescrolls.clues.hotcold.HotColdArea.MORYTANIA; import static net.runelite.client.plugins.cluescrolls.clues.hotcold.HotColdArea.WESTERN_PROVINCE; import static net.runelite.client.plugins.cluescrolls.clues.hotcold.HotColdArea.WILDERNESS; import static net.runelite.client.plugins.cluescrolls.clues.hotcold.HotColdArea.ZEAH; // The locations contains all hot/cold points and their descriptions according to the wiki // these central points were obtained by checking wiki location pictures against a coordinate map // some central points points may be slightly off-center // calculations are done considering the 9x9 grid around the central point where the strange device shakes // because the calculations consider the 9x9 grid, slightly off-center points should still be found by the calculations @AllArgsConstructor @Getter public enum HotColdLocation { ASGARNIA_WARRIORS(new WorldPoint(2860, 3562, 0), ASGARNIA, "North of the Warriors' Guild in Burthorpe."), ASGARNIA_JATIX(new WorldPoint(2914, 3429, 0), ASGARNIA, "East of Jatix's Herblore Shop in Taverley."), ASGARNIA_BARB(new WorldPoint(3036, 3439, 0), ASGARNIA, "West of Barbarian Village."), ASGARNIA_MIAZRQA(new WorldPoint(2973, 3489, 0), ASGARNIA, "North of Miazrqa's tower, outside Goblin Village."), ASGARNIA_COW(new WorldPoint(3033, 3308, 0), ASGARNIA, "In the cow pen north of Sarah's Farming Shop."), ASGARNIA_PARTY_ROOM(new WorldPoint(3026, 3363, 0), ASGARNIA, "Outside the Falador Party Room."), ASGARNIA_CRAFT_GUILD(new WorldPoint(2917, 3295, 0), ASGARNIA, "Outside the Crafting Guild cow pen."), ASGARNIA_RIMMINGTON(new WorldPoint(2978, 3241, 0), ASGARNIA, "In the centre of the Rimmington mine."), ASGARNIA_MUDSKIPPER(new WorldPoint(2984, 3109, 0), ASGARNIA, "Mudskipper Point, on the starfish in the south-west corner."), ASGARNIA_TROLL(new WorldPoint(2910, 3616, 0), ASGARNIA, "The Troll arena, where the player fights Dad during the Troll Stronghold quest. Bring climbing boots if travelling from Burthorpe."), DESERT_GENIE(new WorldPoint(3364, 2910, 0), DESERT, "West of Nardah genie cave."), DESERT_ALKHARID_MINE(new WorldPoint(3282, 3270, 0), DESERT, "West of Al Kharid mine."), DESERT_MENAPHOS_GATE(new WorldPoint(3224, 2816, 0), DESERT, "North of Menaphos gate."), DESERT_BEDABIN_CAMP(new WorldPoint(3164, 3050, 0), DESERT, "Bedabin Camp, dig around the north tent."), DESERT_UZER(new WorldPoint(3431, 3106, 0), DESERT, "West of Uzer."), DESERT_POLLNIVNEACH(new WorldPoint(3287, 2975, 0), DESERT, "West of Pollnivneach."), DESERT_MTA(new WorldPoint(3350, 3293, 0), DESERT, "Next to Mage Training Arena."), DESERT_SHANTY(new WorldPoint(3294, 3106, 0), DESERT, "South-west of Shantay Pass."), DRAYNOR_MANOR_MUSHROOMS(true, new WorldPoint(3096, 3379, 0), MISTHALIN, "Patch of mushrooms just northwest of Draynor Manor"), DRAYNOR_WHEAT_FIELD(true, new WorldPoint(3120, 3282, 0), MISTHALIN, "Inside the wheat field next to Draynor Village"), FELDIP_HILLS_JIGGIG(new WorldPoint(2413, 3055, 0), FELDIP_HILLS, "West of Jiggig, east of the fairy ring bkp."), FELDIP_HILLS_SW(new WorldPoint(2582, 2895, 0), FELDIP_HILLS, "West of the southeasternmost lake in Feldip Hills."), FELDIP_HILLS_GNOME_GLITER(new WorldPoint(2553, 2972, 0), FELDIP_HILLS, "East of the gnome glider (Lemantolly Undri)."), FELDIP_HILLS_RANTZ(new WorldPoint(2611, 2946, 0), FELDIP_HILLS, "South of Rantz, six steps west of the empty glass bottles."), FELDIP_HILLS_SOUTH(new WorldPoint(2487, 3005, 0), FELDIP_HILLS, "South of Jiggig."), FELDIP_HILLS_RED_CHIN(new WorldPoint(2532, 2900, 0), FELDIP_HILLS, "Outside the red chinchompa hunting ground entrance, south of the Hunting expert's hut."), FELDIP_HILLS_SE(new WorldPoint(2567, 2916, 0), FELDIP_HILLS, "South-east of the ∩-shaped lake, near the icon."), FELDIP_HILLS_CW_BALLOON(new WorldPoint(2452, 3108, 0), FELDIP_HILLS, "Directly west of the Castle Wars balloon."), FREMENNIK_PROVINCE_MTN_CAMP(new WorldPoint(2804, 3672, 0), FREMENNIK_PROVINCE, "At the Mountain Camp."), FREMENNIK_PROVINCE_RELLEKKA_HUNTER(new WorldPoint(2724, 3783, 0), FREMENNIK_PROVINCE, "At the Rellekka Hunter area, near the icon."), FREMENNIK_PROVINCE_KELGADRIM_ENTRANCE(new WorldPoint(2715, 3689, 0), FREMENNIK_PROVINCE, "West of the Keldagrim entrance mine."), FREMENNIK_PROVINCE_SW(new WorldPoint(2605, 3648, 0), FREMENNIK_PROVINCE, "Outside the fence in the south-western corner of Rellekka."), FREMENNIK_PROVINCE_LIGHTHOUSE(new WorldPoint(2589, 3598, 0), FREMENNIK_PROVINCE, "South-east of the Lighthouse."), FREMENNIK_PROVINCE_ETCETERIA_CASTLE(new WorldPoint(2614, 3867, 0), FREMENNIK_PROVINCE, "Inside Etceteria's castle, in the southern staircase."), FREMENNIK_PROVINCE_MISC_COURTYARD(new WorldPoint(2529, 3867, 0), FREMENNIK_PROVINCE, "Outside Miscellania's courtyard."), FREMENNIK_PROVINCE_FREMMY_ISLES_MINE(new WorldPoint(2378, 3849, 0), FREMENNIK_PROVINCE, "Central Fremennik Isles mine."), FREMENNIK_PROVINCE_WEST_ISLES_MINE(new WorldPoint(2313, 3854, 0), FREMENNIK_PROVINCE, "West Fremennik Isles mine."), FREMENNIK_PROVINCE_WEST_JATIZSO_ENTRANCE(new WorldPoint(2391, 3813, 0), FREMENNIK_PROVINCE, "West of the Jatizso mine entrance."), FREMENNIK_PROVINCE_PIRATES_COVE(new WorldPoint(2210, 3814, 0), FREMENNIK_PROVINCE, "Pirates' Cove"), FREMENNIK_PROVINCE_ASTRAL_ALTER(new WorldPoint(2147, 3862, 0), FREMENNIK_PROVINCE, "Astral altar"), FREMENNIK_PROVINCE_LUNAR_VILLAGE(new WorldPoint(2087, 3915, 0), FREMENNIK_PROVINCE, "Lunar Isle, inside the village."), FREMENNIK_PROVINCE_LUNAR_NORTH(new WorldPoint(2106, 3949, 0), FREMENNIK_PROVINCE, "Lunar Isle, north of the village."), ICE_MOUNTAIN(true, new WorldPoint(3007, 3475, 0), MISTHALIN, "Atop Ice Mountain"), KANDARIN_SINCLAR_MANSION(new WorldPoint(2726, 3588, 0), KANDARIN, "North-west of the Sinclair Mansion, near the log balance shortcut."), KANDARIN_CATHERBY(new WorldPoint(2774, 3433, 0), KANDARIN, "Catherby, between the bank and the beehives, near small rock formation."), KANDARIN_GRAND_TREE(new WorldPoint(2444, 3503, 0), KANDARIN, "Grand Tree, just east of the terrorchick gnome enclosure."), KANDARIN_SEERS(new WorldPoint(2735, 3486, 0), KANDARIN, "Between the Seers' Village bank and Camelot."), KANDARIN_MCGRUBORS_WOOD(new WorldPoint(2653, 3485, 0), KANDARIN, "McGrubor's Wood"), KANDARIN_FISHING_BUILD(new WorldPoint(2586, 3372, 0), KANDARIN, "South of Fishing Guild"), KANDARIN_WITCHHAVEN(new WorldPoint(2708, 3304, 0), KANDARIN, "Outside Witchaven, west of Jeb, Holgart, and Caroline."), KANDARIN_NECRO_TOWER(new WorldPoint(2669, 3242, 0), KANDARIN, "Ground floor inside the Necromancer Tower. Easily accessed by using fairy ring code djp."), KANDARIN_FIGHT_ARENA(new WorldPoint(2587, 3134, 0), KANDARIN, "South of the Fight Arena, north-west of the Nightmare Zone."), KANDARIN_TREE_GNOME_VILLAGE(new WorldPoint(2526, 3160, 0), KANDARIN, "Tree Gnome Village, near the general store icon."), KANDARIN_GRAVE_OF_SCORPIUS(new WorldPoint(2464, 3228, 0), KANDARIN, "Grave of Scorpius"), KANDARIN_KHAZARD_BATTLEFIELD(new WorldPoint(2518, 3249, 0), KANDARIN, "Khazard Battlefield, in the small ruins south of tracker gnome 2."), KANDARIN_WEST_ARDY(new WorldPoint(2533, 3320, 0), KANDARIN, "West Ardougne, near the staircase outside the Civic Office."), KANDARIN_SW_TREE_GNOME_STRONGHOLD(new WorldPoint(2411, 3431, 0), KANDARIN, "South-west Tree Gnome Stronghold"), KANDARIN_OUTPOST(new WorldPoint(2457, 3362, 0), KANDARIN, "South of the Tree Gnome Stronghold, north-east of the Outpost."), KANDARIN_BAXTORIAN_FALLS(new WorldPoint(2534, 3479, 0), KANDARIN, "South-east of Almera's house on Baxtorian Falls."), KANDARIN_BA_AGILITY_COURSE(new WorldPoint(2536, 3546, 0), KANDARIN, "Inside the Barbarian Agility Course. Completion of Alfred Grimhand's Barcrawl is required."), KARAMJA_MUSA_POINT(new WorldPoint(2914, 3168, 0), KARAMJA, "Musa Point, banana plantation."), KARAMJA_BRIMHAVEN_FRUIT_TREE(new WorldPoint(2783, 3214, 0), KARAMJA, "Brimhaven, east of the fruit tree patch."), KARAMJA_WEST_BRIMHAVEN(new WorldPoint(2721, 3169, 0), KARAMJA, "West of Brimhaven."), KARAMJA_GLIDER(new WorldPoint(2966, 2975, 0), KARAMJA, "West of the gnome glider."), KARAMJA_KHARAZI_NE(new WorldPoint(2904, 2925, 0), KARAMJA, "North-eastern part of Kharazi Jungle."), KARAMJA_KHARAZI_SW(new WorldPoint(2783, 2898, 0), KARAMJA, "South-western part of Kharazi Jungle."), KARAMJA_CRASH_ISLAND(new WorldPoint(2910, 2737, 0), KARAMJA, "Northern part of Crash Island."), LUMBRIDGE_COW_FIELD(true, new WorldPoint(3174, 3336, 0), MISTHALIN, "Cow field north of Lumbridge"), MISTHALIN_VARROCK_STONE_CIRCLE(new WorldPoint(3225, 3355, 0), MISTHALIN, "South of the stone circle near Varrock's entrance."), MISTHALIN_LUMBRIDGE(new WorldPoint(3238, 3169, 0), MISTHALIN, "Just north-west of the Lumbridge Fishing tutor."), MISTHALIN_LUMBRIDGE_2(new WorldPoint(3170, 3278, 0), MISTHALIN, "North of the pond between Lumbridge and Draynor Village."), MISTHALIN_GERTUDES(new WorldPoint(3158, 3421, 0), MISTHALIN, "North-east of Gertrude's house west of Varrock."), MISTHALIN_DRAYNOR_BANK(new WorldPoint(3096, 3235, 0), MISTHALIN, "South of Draynor Village bank."), MISTHALIN_LUMBER_YARD(new WorldPoint(3303, 3483, 0), MISTHALIN, "South of Lumber Yard, east of Assistant Serf."), MORYTANIA_BURGH_DE_ROTT(new WorldPoint(3545, 3253, 0), MORYTANIA, "In the north-east area of Burgh de Rott, by the reverse-L-shaped ruins."), MORYTANIA_PORT_PHASMATYS(new WorldPoint(3613, 3485, 0), MORYTANIA, "West of Port Phasmatys, south-east of fairy ring."), MORYTANIA_HOLLOWS(new WorldPoint(3500, 3423, 0), MORYTANIA, "Inside The Hollows, south of the bridge which was repaired in a quest."), MORYTANIA_SWAMP(new WorldPoint(3422, 3374, 0), MORYTANIA, "Inside the Mort Myre Swamp, north-west of the Nature Grotto."), MORYTANIA_HAUNTED_MINE(new WorldPoint(3441, 3259, 0), MORYTANIA, "At Haunted Mine quest start."), MORYTANIA_MAUSOLEUM(new WorldPoint(3499, 3539, 0), MORYTANIA, "South of the Mausoleum."), MORYTANIA_MOS_LES_HARMLESS(new WorldPoint(3744, 3041, 0), MORYTANIA, "Northern area of Mos Le'Harmless, between the lakes."), MORYTANIA_MOS_LES_HARMLESS_BAR(new WorldPoint(3670, 2974, 0), MORYTANIA, "Near Mos Le'Harmless southern bar."), MORYTANIA_DRAGONTOOTH_NORTH(new WorldPoint(3813, 3567, 0), MORYTANIA, "Northern part of Dragontooth Island."), MORYTANIA_DRAGONTOOTH_SOUTH(new WorldPoint(3803, 3532, 0), MORYTANIA, "Southern part of Dragontooth Island."), NORTHEAST_OF_AL_KHARID_MINE(true, new WorldPoint(3332, 3313, 0), MISTHALIN, "Northeast of Al Kharid Mine"), WESTERN_PROVINCE_EAGLES_PEAK(new WorldPoint(2297, 3530, 0), WESTERN_PROVINCE, "North-west of Eagles' Peak."), WESTERN_PROVINCE_PISCATORIS(new WorldPoint(2337, 3689, 0), WESTERN_PROVINCE, "Piscatoris Fishing Colony"), WESTERN_PROVINCE_PISCATORIS_HUNTER_AREA(new WorldPoint(2361, 3566, 0), WESTERN_PROVINCE, "Eastern part of Piscatoris Hunter area, south-west of the Falconry."), WESTERN_PROVINCE_ARANDAR(new WorldPoint(2366, 3318, 0), WESTERN_PROVINCE, "South-west of the crystal gate to Arandar."), WESTERN_PROVINCE_ELF_CAMP_EAST(new WorldPoint(2270, 3244, 0), WESTERN_PROVINCE, "East of Elf Camp."), WESTERN_PROVINCE_ELF_CAMP_NW(new WorldPoint(2174, 3280, 0), WESTERN_PROVINCE, "North-west of Elf Camp."), WESTERN_PROVINCE_LLETYA(new WorldPoint(2335, 3166, 0), WESTERN_PROVINCE, "In Lletya."), WESTERN_PROVINCE_TYRAS(new WorldPoint(2204, 3157, 0), WESTERN_PROVINCE, "Near Tyras Camp."), WESTERN_PROVINCE_ZULANDRA(new WorldPoint(2196, 3057, 0), WESTERN_PROVINCE, "The northern house at Zul-Andra."), WILDERNESS_5(new WorldPoint(3169, 3558, 0), WILDERNESS, "North of the Grand Exchange, level 5 Wilderness."), WILDERNESS_12(new WorldPoint(3038, 3612, 0), WILDERNESS, "South-east of the Dark Warriors' Fortress, level 12 Wilderness."), WILDERNESS_20(new WorldPoint(3225, 3676, 0), WILDERNESS, "East of the Corporeal Beast's lair, level 20 Wilderness."), WILDERNESS_27(new WorldPoint(3174, 3735, 0), WILDERNESS, "Inside the Ruins north of the Graveyard of Shadows, level 27 Wilderness."), WILDERNESS_28(new WorldPoint(3374, 3734, 0), WILDERNESS, "East of Venenatis' nest, level 28 Wilderness."), WILDERNESS_32(new WorldPoint(3311, 3773, 0), WILDERNESS, "North of Venenatis' nest, level 32 Wilderness."), WILDERNESS_35(new WorldPoint(3153, 3795, 0), WILDERNESS, "East of the Wilderness canoe exit, level 35 Wilderness."), WILDERNESS_37(new WorldPoint(2975, 3811, 0), WILDERNESS, "South-east of the Chaos Temple, level 37 Wilderness."), WILDERNESS_38(new WorldPoint(3293, 3813, 0), WILDERNESS, "South of Callisto, level 38 Wilderness."), WILDERNESS_49(new WorldPoint(3140, 3910, 0), WILDERNESS, "South-west of the Deserted Keep, level 49 Wilderness."), WILDERNESS_54(new WorldPoint(2983, 3946, 0), WILDERNESS, "West of the Wilderness Agility Course, level 54 Wilderness."), ZEAH_BLASTMINE_BANK(new WorldPoint(1507, 3856, 0), ZEAH, "Next to the bank in the Lovakengj blast mine."), ZEAH_BLASTMINE_NORTH(new WorldPoint(1490, 3883, 0), ZEAH, "Northern part of the Lovakengj blast mine."), ZEAH_LOVAKITE_FURNACE(new WorldPoint(1507, 3819, 0), ZEAH, "Next to the lovakite furnace in Lovakengj."), ZEAH_LOVAKENGJ_MINE(new WorldPoint(1477, 3779, 0), ZEAH, "Next to mithril rock in the Lovakengj mine."), ZEAH_SULPHR_MINE(new WorldPoint(1428, 3866, 0), ZEAH, "Western entrance in the Lovakengj sulphur mine."), ZEAH_SHAYZIEN_BANK(new WorldPoint(1517, 3603, 0), ZEAH, "South-east of the bank in Shayzien."), ZEAH_OVERPASS(new WorldPoint(1467, 3714, 0), ZEAH, "Overpass between Lovakengj and Shayzien."), ZEAH_LIZARDMAN(new WorldPoint(1493, 3694, 0), ZEAH, "Within Lizardman Canyon, east of the ladder. Requires 5% favour with Shayzien."), ZEAH_COMBAT_RING(new WorldPoint(1557, 3580, 0), ZEAH, "Shayzien, south-east of the Combat Ring."), ZEAH_SHAYZIEN_BANK_2(new WorldPoint(1494, 3622, 0), ZEAH, "North-west of the bank in Shayzien."), ZEAH_LIBRARY(new WorldPoint(1601, 3842, 0), ZEAH, "North-west of the Arceuus Library."), ZEAH_HOUSECHURCH(new WorldPoint(1682, 3792, 0), ZEAH, "By the entrance to the Arceuus church."), ZEAH_DARK_ALTAR(new WorldPoint(1699, 3879, 0), ZEAH, "West of the Dark Altar."), ZEAH_ARCEUUS_HOUSE(new WorldPoint(1708, 3701, 0), ZEAH, "By the southern entrance to Arceuus."), ZEAH_ESSENCE_MINE(new WorldPoint(1762, 3852, 0), ZEAH, "By the Arceuus essence mine."), ZEAH_ESSENCE_MINE_NE(new WorldPoint(1772, 3866, 0), ZEAH, "North-east of the Arceuus essence mine."), ZEAH_PISCARILUS_MINE(new WorldPoint(1768, 3705, 0), ZEAH, "South of the Piscarilius mine."), ZEAH_GOLDEN_FIELD_TAVERN(new WorldPoint(1718, 3647, 0), ZEAH, "South of The Golden Field tavern in the northern area of Hosidius."), ZEAH_MESS_HALL(new WorldPoint(1658, 3621, 0), ZEAH, "East of the Mess hall."), ZEAH_WATSONS_HOUSE(new WorldPoint(1653, 3573, 0), ZEAH, "East of Watson's house."), ZEAH_VANNAHS_FARM_STORE(new WorldPoint(1806, 3521, 0), ZEAH, "North of Vannah's Farm Store, between the chicken coop and willow trees."), ZEAH_FARMING_GUILD_W(new WorldPoint(1209, 3737, 0), ZEAH, "West of the Farming Guild."), ZEAH_DAIRY_COW(new WorldPoint(1320, 3718, 0), ZEAH, "North-east of the Kebos Lowlands, east of the dairy cow."), ZEAH_CRIMSON_SWIFTS(new WorldPoint(1186, 3583, 0), ZEAH, "South-west of the Kebos Swamp, below the crimson swifts."); private final boolean beginnerClue; private final WorldPoint worldPoint; private final HotColdArea hotColdArea; private final String area; HotColdLocation(WorldPoint worldPoint, HotColdArea hotColdArea, String areaDescription) { this(false, worldPoint, hotColdArea, areaDescription); } public Rectangle getRect() { final int digRadius = beginnerClue ? HotColdTemperature.BEGINNER_VISIBLY_SHAKING.getMaxDistance() : HotColdTemperature.MASTER_VISIBLY_SHAKING.getMaxDistance(); return new Rectangle(worldPoint.getX() - digRadius, worldPoint.getY() - digRadius, digRadius * 2 + 1, digRadius * 2 + 1); } }
package io.branch.referral; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StyleRes; import android.text.TextUtils; import android.util.Log; import android.view.View; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import io.branch.indexing.BranchUniversalObject; import io.branch.indexing.ContentDiscoverer; import io.branch.referral.network.BranchRemoteInterface; import io.branch.referral.util.CommerceEvent; import io.branch.referral.util.LinkProperties; /** * <p> * The core object required when using Branch SDK. You should declare an object of this type at * the class-level of each Activity or Fragment that you wish to use Branch functionality within. * </p> * <p> * Normal instantiation of this object would look like this: * </p> * <!-- * <pre style="background:#fff;padding:10px;border:2px solid silver;"> * Branch.getInstance(this.getApplicationContext()) // from an Activity * Branch.getInstance(getActivity().getApplicationContext()) // from a Fragment * </pre> * --> */ public class Branch implements BranchViewHandler.IBranchViewEvents, SystemObserver.GAdsParamsFetchEvents, InstallListener.IInstallReferrerEvents { private static final String TAG = "BranchSDK"; /** * Hard-coded {@link String} that denotes a {@link BranchLinkData#tags}; applies to links that * are shared with others directly as a user action, via social media for instance. */ public static final String FEATURE_TAG_SHARE = "share"; /** * Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are associated * with a referral program, incentivized or not. */ public static final String FEATURE_TAG_REFERRAL = "referral"; /** * Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are sent as * referral actions by users of an app using an 'invite contacts' feature for instance. */ public static final String FEATURE_TAG_INVITE = "invite"; /** * Hard-coded {@link String} that denotes a link that is part of a commercial 'deal' or offer. */ public static final String FEATURE_TAG_DEAL = "deal"; /** * Hard-coded {@link String} that denotes a link tagged as a gift action within a service or * product. */ public static final String FEATURE_TAG_GIFT = "gift"; /** * The code to be passed as part of a deal or gift; retrieved from the Branch object as a * tag upon initialisation. Of {@link String} format. */ public static final String REDEEM_CODE = "$redeem_code"; /** * <p>Default value of referral bucket; referral buckets contain credits that are used when users * are referred to your apps. These can be viewed in the Branch dashboard under Referrals.</p> */ public static final String REFERRAL_BUCKET_DEFAULT = "default"; /** * <p>Hard-coded value for referral code type. Referral codes will always result on "credit" actions. * Even if they are of 0 value.</p> */ public static final String REFERRAL_CODE_TYPE = "credit"; /** * Branch SDK version for the current release of the Branch SDK. */ public static final int REFERRAL_CREATION_SOURCE_SDK = 2; /** * Key value for referral code as a parameter. */ public static final String REFERRAL_CODE = "referral_code"; /** * The redirect URL provided when the link is handled by a desktop client. */ public static final String REDIRECT_DESKTOP_URL = "$desktop_url"; /** * The redirect URL provided when the link is handled by an Android device. */ public static final String REDIRECT_ANDROID_URL = "$android_url"; /** * The redirect URL provided when the link is handled by an iOS device. */ public static final String REDIRECT_IOS_URL = "$ios_url"; /** * The redirect URL provided when the link is handled by a large form-factor iOS device such as * an iPad. */ public static final String REDIRECT_IPAD_URL = "$ipad_url"; /** * The redirect URL provided when the link is handled by an Amazon Fire device. */ public static final String REDIRECT_FIRE_URL = "$fire_url"; /** * The redirect URL provided when the link is handled by a Blackberry device. */ public static final String REDIRECT_BLACKBERRY_URL = "$blackberry_url"; /** * The redirect URL provided when the link is handled by a Windows Phone device. */ public static final String REDIRECT_WINDOWS_PHONE_URL = "$windows_phone_url"; public static final String OG_TITLE = "$og_title"; public static final String OG_DESC = "$og_description"; public static final String OG_IMAGE_URL = "$og_image_url"; public static final String OG_VIDEO = "$og_video"; public static final String OG_URL = "$og_url"; /** * Unique identifier for the app in use. */ public static final String OG_APP_ID = "$og_app_id"; /** * {@link String} value denoting the deep link path to override Branch's default one. By * default, Branch will use yourapp://open?link_click_id=12345. If you specify this key/value, * Branch will use yourapp://'$deeplink_path'?link_click_id=12345 */ public static final String DEEPLINK_PATH = "$deeplink_path"; /** * {@link String} value indicating whether the link should always initiate a deep link action. * By default, unless overridden on the dashboard, Branch will only open the app if they are * 100% sure the app is installed. This setting will cause the link to always open the app. * Possible values are "true" or "false" */ public static final String ALWAYS_DEEPLINK = "$always_deeplink"; /** * An {@link Integer} value indicating the user to reward for applying a referral code. In this * case, the user applying the referral code receives credit. */ public static final int REFERRAL_CODE_LOCATION_REFERREE = 0; /** * An {@link Integer} value indicating the user to reward for applying a referral code. In this * case, the user who created the referral code receives credit. */ public static final int REFERRAL_CODE_LOCATION_REFERRING_USER = 2; /** * An {@link Integer} value indicating the user to reward for applying a referral code. In this * case, both the creator and applicant receive credit */ public static final int REFERRAL_CODE_LOCATION_BOTH = 3; /** * An {@link Integer} value indicating the calculation type of the referral code. In this case, * the referral code can be applied continually. */ public static final int REFERRAL_CODE_AWARD_UNLIMITED = 1; /** * An {@link Integer} value indicating the calculation type of the referral code. In this case, * a user can only apply a specific referral code once. */ public static final int REFERRAL_CODE_AWARD_UNIQUE = 0; /** * An {@link Integer} value indicating the link type. In this case, the link can be used an * unlimited number of times. */ public static final int LINK_TYPE_UNLIMITED_USE = 0; /** * An {@link Integer} value indicating the link type. In this case, the link can be used only * once. After initial use, subsequent attempts will not validate. */ public static final int LINK_TYPE_ONE_TIME_USE = 1; private static final int SESSION_KEEPALIVE = 2000; /** * <p>An {@link Integer} value defining the timeout period in milliseconds to wait during a * looping task before triggering an actual connection close during a session close action.</p> */ private static final int PREVENT_CLOSE_TIMEOUT = 500; /* Json object containing key-value pairs for debugging deep linking */ private JSONObject deeplinkDebugParams_; private static boolean disableDeviceIDFetch_; private boolean enableFacebookAppLinkCheck_ = false; private static boolean isSimulatingInstalls_; private static boolean isLogging_ = false; static boolean checkInstallReferrer_ = true; private static long playStoreReferrerFetchTime = 1500; public static final long NO_PLAY_STORE_REFERRER_WAIT = 0; /** * <p>A {@link Branch} object that is instantiated on init and holds the singleton instance of * the class during application runtime.</p> */ private static Branch branchReferral_; private BranchRemoteInterface branchRemoteInterface_; private PrefHelper prefHelper_; private final SystemObserver systemObserver_; private Context context_; final Object lock; private Semaphore serverSema_; private ServerRequestQueue requestQueue_; private int networkCount_; private boolean hasNetwork_; private Map<BranchLinkData, String> linkCache_; private ScheduledFuture<?> appListingSchedule_; /* Set to true when application is instantiating {@BranchApp} by extending or adding manifest entry. */ private static boolean isAutoSessionMode_ = false; /* Set to true when {@link Activity} life cycle callbacks are registered. */ private static boolean isActivityLifeCycleCallbackRegistered_ = false; /* Enumeration for defining session initialisation state. */ private enum SESSION_STATE { INITIALISED, INITIALISING, UNINITIALISED } private enum INTENT_STATE { PENDING, READY } private INTENT_STATE intentState_ = INTENT_STATE.PENDING; private boolean handleDelayedNewIntents_ = false; /* Holds the current Session state. Default is set to UNINITIALISED. */ private SESSION_STATE initState_ = SESSION_STATE.UNINITIALISED; /* Instance of share link manager to share links automatically with third party applications. */ private ShareLinkManager shareLinkManager_; /* The current activity instance for the application.*/ WeakReference<Activity> currentActivityReference_; /* Specifies the choice of user for isReferrable setting. used to determine the link click is referrable or not. See getAutoSession for usage */ private enum CUSTOM_REFERRABLE_SETTINGS { USE_DEFAULT, REFERRABLE, NON_REFERRABLE } /* By default assume user want to use the default settings. Update this option when user specify custom referrable settings */ private static CUSTOM_REFERRABLE_SETTINGS customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT; /* Key to indicate whether the Activity was launched by Branch or not. */ private static final String AUTO_DEEP_LINKED = "io.branch.sdk.auto_linked"; /* Key for Auto Deep link param. The activities which need to automatically deep linked should define in this in the activity metadata. */ private static final String AUTO_DEEP_LINK_KEY = "io.branch.sdk.auto_link_keys"; /* Path for $deeplink_path or $android_deeplink_path to auto deep link. The activities which need to automatically deep linked should define in this in the activity metadata. */ private static final String AUTO_DEEP_LINK_PATH = "io.branch.sdk.auto_link_path"; /* Key for disabling auto deep link feature. Setting this to true in manifest will disable auto deep linking feature. */ private static final String AUTO_DEEP_LINK_DISABLE = "io.branch.sdk.auto_link_disable"; /*Key for defining a request code for an activity. should be added as a metadata for an activity. This is used as a request code for launching a an activity on auto deep link. */ private static final String AUTO_DEEP_LINK_REQ_CODE = "io.branch.sdk.auto_link_request_code"; /* Request code used to launch and activity on auto deep linking unless DEF_AUTO_DEEP_LINK_REQ_CODE is not specified for teh activity in manifest.*/ private static final int DEF_AUTO_DEEP_LINK_REQ_CODE = 1501; /* Sets to true when the init session params are reported to the app though call back.*/ private boolean isInitReportedThroughCallBack = false; private final ConcurrentHashMap<String, String> instrumentationExtraData_; /* Name of the key for getting Fabric Branch API key from string resource */ private static final String FABRIC_BRANCH_API_KEY = "io.branch.apiKey"; private boolean isGAParamsFetchInProgress_ = false; private List<String> externalUriWhiteList_; private List<String> skipExternalUriHosts_; String sessionReferredLink_; // Link which opened this application session if opened by a link click. private static String cookieBasedMatchDomain_ = "app.link"; // Domain name used for cookie based matching. private static int LATCH_WAIT_UNTIL = 2500; //used for getLatestReferringParamsSync and getFirstReferringParamsSync, fail after this many milliseconds /* List of keys whose values are collected from the Intent Extra.*/ private static final String[] EXTERNAL_INTENT_EXTRA_KEY_WHITE_LIST = new String[]{ "extra_launch_uri" // Key for embedded uri in FB ads triggered intents }; private CountDownLatch getFirstReferringParamsLatch = null; private CountDownLatch getLatestReferringParamsLatch = null; /* Flag for checking of Strong matching is waiting on GAID fetch */ private boolean performCookieBasedStrongMatchingOnGAIDAvailable = false; /** * <p>The main constructor of the Branch class is private because the class uses the Singleton * pattern.</p> * * <p>Use {@link #getInstance(Context) getInstance} method when instantiating.</p> * * @param context A {@link Context} from which this call was made. */ private Branch(@NonNull Context context) { prefHelper_ = PrefHelper.getInstance(context); branchRemoteInterface_ = BranchRemoteInterface.getDefaultBranchRemoteInterface(context); systemObserver_ = new SystemObserver(context); requestQueue_ = ServerRequestQueue.getInstance(context); serverSema_ = new Semaphore(1); lock = new Object(); networkCount_ = 0; hasNetwork_ = true; linkCache_ = new HashMap<>(); instrumentationExtraData_ = new ConcurrentHashMap<>(); isGAParamsFetchInProgress_ = systemObserver_.prefetchGAdsParams(this); InstallListener.setListener(this); // newIntent() delayed issue is only with Android M+ devices. So need to handle android M and above // PRS: Since this seem more reliable and not causing any integration issues adding this to all supported SDK versions if (android.os.Build.VERSION.SDK_INT >= 15) { handleDelayedNewIntents_ = true; intentState_ = INTENT_STATE.PENDING; } else { handleDelayedNewIntents_ = false; intentState_ = INTENT_STATE.READY; } externalUriWhiteList_ = new ArrayList<>(); skipExternalUriHosts_ = new ArrayList<>(); } /** * Sets a custom Branch Remote interface for handling RESTful requests. Call this for implementing a custom network layer for handling communication between * Branch SDK and remote Branch server * * @param remoteInterface A instance of class extending {@link BranchRemoteInterface} with implementation for abstract RESTful GET or POST methods */ public void setBranchRemoteInterface(BranchRemoteInterface remoteInterface) { branchRemoteInterface_ = remoteInterface; } /** * <p> * Enables/Disables the test mode for the SDK. This will use the Branch Test Keys. * This will also enable debug logs. * Note: This is same as setting "io.branch.sdk.TestMode" to "True" in Manifest file * </p> */ public static void enableTestMode() { BranchUtil.isCustomDebugEnabled_ = true; } public static void disableTestMode() { BranchUtil.isCustomDebugEnabled_ = false; } public void setDebug() { enableTestMode(); } /** * @deprecated This method is deprecated since play store referrer is enabled by default from v2.9.1. * Please use {@link #setPlayStoreReferrerCheckTimeout(long)} instead. */ public static void enablePlayStoreReferrer(long delay) { setPlayStoreReferrerCheckTimeout(delay); } /** * Since play store referrer broadcast from google play is few millisecond delayed Branch will delay the collecting deep link data on app install by {@link #playStoreReferrerFetchTime} millisecond * This will allow branch to provide for more accurate tracking and attribution. This will delay branch init only the first time user open the app. * This method allows to override the maximum wait time for play store referrer to arrive. Set it to {@link Branch#NO_PLAY_STORE_REFERRER_WAIT} if you don't want to wait for play store referrer * * Note: as of our testing 4/2017 a 1500 milli sec wait time is enough to capture more than 90% of the install referrer case * * @param delay {@link Long} Maximum wait time for install referrer broadcast in milli seconds. Set to {@link Branch#NO_PLAY_STORE_REFERRER_WAIT} if you don't want to wait for play store referrer */ public static void setPlayStoreReferrerCheckTimeout(long delay) { checkInstallReferrer_ = delay > 0; playStoreReferrerFetchTime = delay; } /** * <p>Singleton method to return the pre-initialised object of the type {@link Branch}. * Make sure your app is instantiating {@link BranchApp} before calling this method * or you have created an instance of Branch already by calling getInstance(Context ctx).</p> * * @return An initialised singleton {@link Branch} object */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static Branch getInstance() { /* Check if BranchApp is instantiated. */ if (branchReferral_ == null) { Log.e("BranchSDK", "Branch instance is not created yet. Make sure you have initialised Branch. [Consider Calling getInstance(Context ctx) if you still have issue.]"); } else if (isAutoSessionMode_) { /* Check if Activity life cycle callbacks are set if in auto session mode. */ if (!isActivityLifeCycleCallbackRegistered_) { Log.e("BranchSDK", "Branch instance is not properly initialised. Make sure your Application class is extending BranchApp class. " + "If you are not extending BranchApp class make sure you are initialising Branch in your Applications onCreate()"); } } return branchReferral_; } public static Branch getInstance(@NonNull Context context, @NonNull String branchKey) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); } branchReferral_.context_ = context.getApplicationContext(); if (branchKey.startsWith("key_")) { boolean isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey); //on setting a new key clear link cache and pending requests if (isNewBranchKeySet) { branchReferral_.linkCache_.clear(); branchReferral_.requestQueue_.clear(); } } else { Log.e("BranchSDK", "Branch Key is invalid.Please check your BranchKey"); } return branchReferral_; } private static Branch getBranchInstance(@NonNull Context context, boolean isLive) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); String branchKey = branchReferral_.prefHelper_.readBranchKey(isLive); boolean isNewBranchKeySet; if (branchKey == null || branchKey.equalsIgnoreCase(PrefHelper.NO_STRING_VALUE)) { // If Branch key is not available check for Fabric provided Branch key String fabricBranchApiKey = null; try { Resources resources = context.getResources(); fabricBranchApiKey = resources.getString(resources.getIdentifier(FABRIC_BRANCH_API_KEY, "string", context.getPackageName())); } catch (Exception ignore) { } if (!TextUtils.isEmpty(fabricBranchApiKey)) { isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(fabricBranchApiKey); } else { Log.i("BranchSDK", "Branch Warning: Please enter your branch_key in your project's Manifest file!"); isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(PrefHelper.NO_STRING_VALUE); } } else { isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey); } //on setting a new key clear link cache and pending requests if (isNewBranchKeySet) { branchReferral_.linkCache_.clear(); branchReferral_.requestQueue_.clear(); } branchReferral_.context_ = context.getApplicationContext(); /* If {@link Application} is instantiated register for activity life cycle events. */ if (context instanceof Application) { isAutoSessionMode_ = true; branchReferral_.setActivityLifeCycleObserver((Application) context); } } return branchReferral_; } /** * <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton * object of the type {@link Branch}.</p> * <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object, either fetched from a pre-initialised * instance within the singleton class, or a newly instantiated object where * one was not already requested during the current app lifecycle. */ public static Branch getInstance(@NonNull Context context) { return getBranchInstance(context, true); } /** * <p>If you configured the your Strings file according to the guide, you'll be able to use * the test version of your app by just calling this static method before calling initSession.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object. */ public static Branch getTestInstance(@NonNull Context context) { return getBranchInstance(context, false); } /** * <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton * object of the type {@link Branch}.</p> * <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object, either fetched from a pre-initialised * instance within the singleton class, or a newly instantiated object where * one was not already requested during the current app lifecycle. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static Branch getAutoInstance(@NonNull Context context) { isAutoSessionMode_ = true; customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT; boolean isLive = !BranchUtil.isTestModeEnabled(context); getBranchInstance(context, isLive); return branchReferral_; } /** * <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton * object of the type {@link Branch}.</p> * <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p> * * @param context A {@link Context} from which this call was made. * @param isReferrable A {@link Boolean} value indicating whether initialising a session on this Branch instance * should be considered as potentially referrable or not. By default, a user is only referrable * if initSession results in a fresh install. Overriding this gives you control of who is referrable. * @return An initialised {@link Branch} object, either fetched from a pre-initialised * instance within the singleton class, or a newly instantiated object where * one was not already requested during the current app lifecycle. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static Branch getAutoInstance(@NonNull Context context, boolean isReferrable) { isAutoSessionMode_ = true; customReferrableSettings_ = isReferrable ? CUSTOM_REFERRABLE_SETTINGS.REFERRABLE : CUSTOM_REFERRABLE_SETTINGS.NON_REFERRABLE; boolean isDebug = BranchUtil.isTestModeEnabled(context); getBranchInstance(context, !isDebug); return branchReferral_; } /** * <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton * object of the type {@link Branch}.</p> * <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p> * * @param context A {@link Context} from which this call was made. * @param branchKey A {@link String} value used to initialize Branch. * @return An initialised {@link Branch} object, either fetched from a pre-initialised * instance within the singleton class, or a newly instantiated object where * one was not already requested during the current app lifecycle. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static Branch getAutoInstance(@NonNull Context context, @NonNull String branchKey) { isAutoSessionMode_ = true; customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT; boolean isLive = !BranchUtil.isTestModeEnabled(context); getBranchInstance(context, isLive); if (branchKey.startsWith("key_")) { boolean isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey); //on setting a new key clear link cache and pending requests if (isNewBranchKeySet) { branchReferral_.linkCache_.clear(); branchReferral_.requestQueue_.clear(); } } else { Log.e("BranchSDK", "Branch Key is invalid.Please check your BranchKey"); } return branchReferral_; } /** * <p>If you configured the your Strings file according to the guide, you'll be able to use * the test version of your app by just calling this static method before calling initSession.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static Branch getAutoTestInstance(@NonNull Context context) { isAutoSessionMode_ = true; customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT; getBranchInstance(context, false); return branchReferral_; } /** * <p>If you configured the your Strings file according to the guide, you'll be able to use * the test version of your app by just calling this static method before calling initSession.</p> * * @param context A {@link Context} from which this call was made. * @param isReferrable A {@link Boolean} value indicating whether initialising a session on this Branch instance * should be considered as potentially referrable or not. By default, a user is only referrable * if initSession results in a fresh install. Overriding this gives you control of who is referrable. * @return An initialised {@link Branch} object. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static Branch getAutoTestInstance(@NonNull Context context, boolean isReferrable) { isAutoSessionMode_ = true; customReferrableSettings_ = isReferrable ? CUSTOM_REFERRABLE_SETTINGS.REFERRABLE : CUSTOM_REFERRABLE_SETTINGS.NON_REFERRABLE; getBranchInstance(context, false); return branchReferral_; } /** * <p>Initialises an instance of the Branch object.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object. */ private static Branch initInstance(@NonNull Context context) { return new Branch(context.getApplicationContext()); } /** * <p>Manually sets the {@link Boolean} value, that indicates that the Branch API connection has * been initialised, to false - forcing re-initialisation.</p> */ public void resetUserSession() { initState_ = SESSION_STATE.UNINITIALISED; } /** * <p>Sets the number of times to re-attempt a timed-out request to the Branch API, before * considering the request to have failed entirely. Default 5.</p> * * @param retryCount An {@link Integer} specifying the number of times to retry before giving * up and declaring defeat. */ public void setRetryCount(int retryCount) { if (prefHelper_ != null && retryCount >= 0) { prefHelper_.setRetryCount(retryCount); } } /** * <p>Sets the amount of time in milliseconds to wait before re-attempting a timed-out request * to the Branch API. Default 3000 ms.</p> * * @param retryInterval An {@link Integer} value specifying the number of milliseconds to * wait before re-attempting a timed-out request. */ public void setRetryInterval(int retryInterval) { if (prefHelper_ != null && retryInterval > 0) { prefHelper_.setRetryInterval(retryInterval); } } /** * <p>Sets the duration in milliseconds that the system should wait for a response before considering * any Branch API call to have timed out. Default 3000 ms.</p> * <p>Increase this to perform better in low network speed situations, but at the expense of * responsiveness to error situation.</p> * * @param timeout An {@link Integer} value specifying the number of milliseconds to wait before * considering the request to have timed out. */ public void setNetworkTimeout(int timeout) { if (prefHelper_ != null && timeout > 0) { prefHelper_.setTimeout(timeout); } } /** * Method to control reading Android ID from device. Set this to true to disable reading the device id. * This method should be called from your {@link Application#onCreate()} method before creating Branch auto instance by calling {@link Branch#getAutoInstance(Context)} * * @param deviceIdFetch {@link Boolean with value true to disable reading the Android id from device} */ public static void disableDeviceIDFetch(Boolean deviceIdFetch) { disableDeviceIDFetch_ = deviceIdFetch; } /** * Returns true if reading device id is disabled * * @return {@link Boolean} with value true to disable reading Andoid ID */ public static boolean isDeviceIDFetchDisabled() { return disableDeviceIDFetch_; } /** * Sets the key-value pairs for debugging the deep link. The key-value set in debug mode is given back with other deep link data on branch init session. * This method should be called from onCreate() of activity which listens to Branch Init Session callbacks * * @param debugParams A {@link JSONObject} containing key-value pairs for debugging branch deep linking */ public void setDeepLinkDebugMode(JSONObject debugParams) { deeplinkDebugParams_ = debugParams; } /** * <p>Calls the {@link PrefHelper#disableExternAppListing()} on the local instance to prevent * a list of installed apps from being returned to the Branch API.</p> */ public void disableAppList() { prefHelper_.disableExternAppListing(); } /** * <p> * Enable Facebook app link check operation during Branch initialisation. * </p> */ public void enableFacebookAppLinkCheck() { enableFacebookAppLinkCheck_ = true; } /** * <p>Add key value pairs to all requests</p> */ public void setRequestMetadata(@NonNull String key, @NonNull String value) { prefHelper_.setRequestMetadata(key, value); } /** * <p>Initialises a session with the Branch API, assigning a {@link BranchUniversalReferralInitListener} * to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called following * successful (or unsuccessful) initialisation of the session with the Branch API. * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback) { return initSession(callback, (Activity) null); } /** * <p>Initialises a session with the Branch API, assigning a {@link BranchReferralInitListener} * to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called following * successful (or unsuccessful) initialisation of the session with the Branch API. * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchReferralInitListener callback) { return initSession(callback, (Activity) null); } /** * <p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a * {@link BranchUniversalReferralInitListener} to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, Activity activity) { if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) { initUserSessionInternal(callback, activity, true); } else { boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE; initUserSessionInternal(callback, activity, isReferrable); } return true; } /** * <p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a * {@link BranchReferralInitListener} to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, Activity activity) { if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) { initUserSessionInternal(callback, activity, true); } else { boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE; initUserSessionInternal(callback, activity, isReferrable); } return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchUniversalReferralInitListener callback, @NonNull Uri data) { return initSession(callback, data, null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchReferralInitListener callback, @NonNull Uri data) { return initSession(callback, data, null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchUniversalReferralInitListener callback, @NonNull Uri data, Activity activity) { readAndStripParam(data, activity); initSession(callback, activity); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchReferralInitListener callback, @NonNull Uri data, Activity activity) { readAndStripParam(data, activity); return initSession(callback, activity); } /** * <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p> * * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession() { return initSession((Activity) null); } /** * <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p> * * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(Activity activity) { return initSession((BranchReferralInitListener) null, activity); } /** * <p>Initialises a session with the Branch API, with associated data from the supplied * {@link Uri}.</p> * * @param data A {@link Uri} variable containing the details of the source link that * led to this * initialisation action. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSessionWithData(@NonNull Uri data) { return initSessionWithData(data, null); } /** * <p>Initialises a session with the Branch API, with associated data from the supplied * {@link Uri}.</p> * * @param data A {@link Uri} variable containing the details of the source link that led to this * initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSessionWithData(Uri data, Activity activity) { readAndStripParam(data, activity); return initSession((BranchReferralInitListener) null, activity); } /** * <p>Initialises a session with the Branch API, specifying whether the initialisation can count * as a referrable action.</p> * * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(boolean isReferrable) { return initSession((BranchReferralInitListener) null, isReferrable, (Activity) null); } /** * <p>Initialises a session with the Branch API, specifying whether the initialisation can count * as a referrable action, and supplying the calling {@link Activity} for context.</p> * * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(boolean isReferrable, @NonNull Activity activity) { return initSession((BranchReferralInitListener) null, isReferrable, activity); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, Uri data) { return initSession(callback, isReferrable, data, null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, @NonNull Uri data) { return initSession(callback, isReferrable, data, null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, @NonNull Uri data, Activity activity) { readAndStripParam(data, activity); return initSession(callback, isReferrable, activity); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, @NonNull Uri data, Activity activity) { readAndStripParam(data, activity); return initSession(callback, isReferrable, activity); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable) { return initSession(callback, isReferrable, (Activity) null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable) { return initSession(callback, isReferrable, (Activity) null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, Activity activity) { initUserSessionInternal(callback, activity, isReferrable); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Activity activity) { initUserSessionInternal(callback, activity, isReferrable); return true; } private void initUserSessionInternal(BranchUniversalReferralInitListener callback, Activity activity, boolean isReferrable) { BranchUniversalReferralInitWrapper branchUniversalReferralInitWrapper = new BranchUniversalReferralInitWrapper(callback); initUserSessionInternal(branchUniversalReferralInitWrapper, activity, isReferrable); } private void initUserSessionInternal(BranchReferralInitListener callback, Activity activity, boolean isReferrable) { if (activity != null) { currentActivityReference_ = new WeakReference<>(activity); } //If already initialised if (hasUser() && hasSession() && initState_ == SESSION_STATE.INITIALISED) { if (callback != null) { if (isAutoSessionMode_) { // Since Auto session mode initialise the session by itself on starting the first activity, we need to provide user // the referring params if they call init session after init is completed. Note that user wont do InitSession per activity in auto session mode. if (!isInitReportedThroughCallBack) { //Check if session params are reported already in case user call initsession form a different activity(not a noraml case) callback.onInitFinished(getLatestReferringParams(), null); isInitReportedThroughCallBack = true; } else { callback.onInitFinished(new JSONObject(), null); } } else { // Since user will do init session per activity in non auto session mode , we don't want to repeat the referring params with each initSession()call. callback.onInitFinished(new JSONObject(), null); } } } //If uninitialised or initialising else { // In case of Auto session init will be called from Branch before user. So initialising // State also need to look for isReferrable value if (isReferrable) { this.prefHelper_.setIsReferrable(); } else { this.prefHelper_.clearIsReferrable(); } //If initialising ,then set new callbacks. if (initState_ == SESSION_STATE.INITIALISING) { if (callback != null) { requestQueue_.setInstallOrOpenCallback(callback); } } //if Uninitialised move request to the front if there is an existing request or create a new request. else { initState_ = SESSION_STATE.INITIALISING; initializeSession(callback); } } } /** * <p>Closes the current session, dependent on the state of the * PrefHelper#getSmartSession() {@link Boolean} value. If <i>true</i>, take no action. * If false, close the session via the {@link #executeClose()} method.</p> * <p>Note that if smartSession is enabled, closeSession cannot be called within * a 2 second time span of another Branch action. This has to do with the method that * Branch uses to keep a session alive during Activity transitions</p> * * @deprecated This method is deprecated from SDK v1.14.6. Session Start and close are automatically handled by Branch. * In case you need to handle sessions manually inorder to support minimum sdk version less than 14 please consider using * SDK version 1.14.5 */ public void closeSession() { Log.w("BranchSDK", "closeSession() method is deprecated from SDK v1.14.6.Session is automatically handled by Branch." + "In case you need to handle sessions manually inorder to support minimum sdk version less than 14 please consider using " + " SDK version 1.14.5"); } /* * <p>Closes the current session. Should be called by on getting the last actvity onStop() event. * </p> */ private void closeSessionInternal() { executeClose(); sessionReferredLink_ = null; if (prefHelper_.getExternAppListing()) { if (appListingSchedule_ == null) { scheduleListOfApps(); } } } /** * <p> * Enabled Strong matching check using chrome cookies. This method should be called before * Branch#getAutoInstance(Context).</p> * * @param cookieMatchDomain The domain for the url used to match the cookie (eg. example.app.link) */ public static void enableCookieBasedMatching(String cookieMatchDomain) { cookieBasedMatchDomain_ = cookieMatchDomain; } /** * <p> * Enabled Strong matching check using chrome cookies. This method should be called before * Branch#getAutoInstance(Context).</p> * * @param cookieMatchDomain The domain for the url used to match the cookie (eg. example.app.link) * @param delay Time in millisecond to wait for the strong match to check to finish before Branch init session is called. * Default time is 750 msec. */ public static void enableCookieBasedMatching(String cookieMatchDomain, int delay) { cookieBasedMatchDomain_ = cookieMatchDomain; BranchStrongMatchHelper.getInstance().setStrongMatchUrlHitDelay(delay); } /** * <p>Perform the state-safe actions required to terminate any open session, and report the * closed application event to the Branch API.</p> */ private void executeClose() { if (initState_ != SESSION_STATE.UNINITIALISED) { if (!hasNetwork_) { // if there's no network connectivity, purge the old install/open ServerRequest req = requestQueue_.peek(); if (req != null && (req instanceof ServerRequestRegisterInstall) || (req instanceof ServerRequestRegisterOpen)) { requestQueue_.dequeue(); } } else { if (!requestQueue_.containsClose()) { ServerRequest req = new ServerRequestRegisterClose(context_); handleNewRequest(req); } } initState_ = SESSION_STATE.UNINITIALISED; } } private boolean readAndStripParam(Uri data, Activity activity) { if (intentState_ == INTENT_STATE.READY) { // Capture the intent URI and extra for analytics in case started by external intents such as google app search try { if (data != null) { boolean foundSchemeMatch; boolean skipThisHost = false; if (externalUriWhiteList_.size() > 0) { foundSchemeMatch = externalUriWhiteList_.contains(data.getScheme()); } else { foundSchemeMatch = true; } if (skipExternalUriHosts_.size() > 0) { for (String host : skipExternalUriHosts_) { String externalHost = data.getHost(); if (externalHost != null && externalHost.equals(host)) { skipThisHost = true; break; } } } if (foundSchemeMatch && !skipThisHost) { sessionReferredLink_ = data.toString(); prefHelper_.setExternalIntentUri(data.toString()); if (activity != null && activity.getIntent() != null && activity.getIntent().getExtras() != null) { Bundle bundle = activity.getIntent().getExtras(); Set<String> extraKeys = bundle.keySet(); if (extraKeys.size() > 0) { JSONObject extrasJson = new JSONObject(); for (String key : EXTERNAL_INTENT_EXTRA_KEY_WHITE_LIST) { if (extraKeys.contains(key)) { extrasJson.put(key, bundle.get(key)); } } if (extrasJson.length() > 0) { prefHelper_.setExternalIntentExtra(extrasJson.toString()); } } } } } } catch (Exception ignore) { } //Check for any push identifier in case app is launched by a push notification try { if (activity != null && activity.getIntent() != null && activity.getIntent().getExtras() != null) { if (activity.getIntent().getExtras().getBoolean(Defines.Jsonkey.BranchLinkUsed.getKey()) == false) { String pushIdentifier = activity.getIntent().getExtras().getString(Defines.Jsonkey.AndroidPushNotificationKey.getKey()); // This seems producing unmarshalling errors in some corner cases if (pushIdentifier != null && pushIdentifier.length() > 0) { prefHelper_.setPushIdentifier(pushIdentifier); Intent thisIntent = activity.getIntent(); thisIntent.putExtra(Defines.Jsonkey.BranchLinkUsed.getKey(), true); activity.setIntent(thisIntent); return false; } } } } catch (Exception ignore) { } //Check for link click id or app link if (data != null && data.isHierarchical() && activity != null) { try { if (data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()) != null) { prefHelper_.setLinkClickIdentifier(data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey())); String paramString = "link_click_id=" + data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()); String uriString = null; if (activity.getIntent() != null) { uriString = activity.getIntent().getDataString(); } if (data.getQuery().length() == paramString.length()) { paramString = "\\?" + paramString; } else if (uriString != null && (uriString.length() - paramString.length()) == uriString.indexOf(paramString)) { paramString = "&" + paramString; } else { paramString = paramString + "&"; } if (uriString != null) { Uri newData = Uri.parse(uriString.replaceFirst(paramString, "")); activity.getIntent().setData(newData); } else { Log.w(TAG, "Branch Warning. URI for the launcher activity is null. Please make sure that intent data is not set to null before calling Branch#InitSession "); } return true; } else { // Check if the clicked url is an app link pointing to this app String scheme = data.getScheme(); Intent intent = activity.getIntent(); if (scheme != null && intent != null) { // On Launching app from the recent apps, Android Start the app with the original intent data. So up in opening app from recent list // Intent will have App link in data and lead to issue of getting wrong parameters. (In case of link click id since we are looking for actual link click on back end this case will never happen) if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) { if ((scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")) && data.getHost() != null && data.getHost().length() > 0 && !intent.getBooleanExtra(Defines.Jsonkey.BranchLinkUsed.getKey(), false)) { prefHelper_.setAppLink(data.toString()); intent.putExtra(Defines.Jsonkey.BranchLinkUsed.getKey(), true); activity.setIntent(intent); return false; } } } } } catch (Exception ignore) { } } } return false; } @Override public void onGAdsFetchFinished() { isGAParamsFetchInProgress_ = false; requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.GAID_FETCH_WAIT_LOCK); if (performCookieBasedStrongMatchingOnGAIDAvailable) { performCookieBasedStrongMatch(); performCookieBasedStrongMatchingOnGAIDAvailable = false; } else { processNextQueueItem(); } } @Override public void onInstallReferrerEventsFinished() { requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.INSTALL_REFERRER_FETCH_WAIT_LOCK); processNextQueueItem(); } /** * Add the given URI Scheme to the external Uri white list. Branch will collect * external intent uri only if white list matches with the app opened URL properties * If no URI is added to the white list branch will collect all external intent uris. * White list schemes should be added immediately after calling {@link Branch#getAutoInstance(Context)} * * @param uriScheme {@link String} Case sensitive Uri scheme to be added to the external intent uri white list.(eg. "my_scheme://") * @return {@link Branch} instance for successive method calls */ public Branch addWhiteListedScheme(String uriScheme) { if (uriScheme == null) { return this; } uriScheme = uriScheme.replace(": externalUriWhiteList_.add(uriScheme); return this; } /** * <p>Set the given list of URI Scheme as the external Uri white list. Branch will collect * external intent uri only for Uris in white list. * </p> * If no URI is added to the white list branch will collect all external intent uris * White list should be set immediately after calling {@link Branch#getAutoInstance(Context)} * <!-- @param uriSchemes {@link List<String>} List of case sensitive Uri schemes to set as the white list --> * * @return {@link Branch} instance for successive method calls */ public Branch setWhiteListedSchemes(List<String> uriSchemes) { externalUriWhiteList_ = uriSchemes; return this; } * @param hostName {@link String} Case sensitive Uri path to be added to the external Intent uri skip list. (e.g. "product" to skip my-scheme://product/*) * @return {@link Branch} instance for successive method calls */ public Branch addUriHostsToSkip(String hostName) { if ((hostName != null) && (!hostName.equals(""))) skipExternalUriHosts_.add(hostName); return this; } /** * <p>Identifies the current user to the Branch API by supplying a unique identifier as a * {@link String} value. No callback.</p> * * @param userId A {@link String} value containing the unique identifier of the user. */ public void setIdentity(@NonNull String userId) { setIdentity(userId, null); } /** * <p>Identifies the current user to the Branch API by supplying a unique identifier as a * {@link String} value, with a callback specified to perform a defined action upon successful * response to request.</p> * * @param userId A {@link String} value containing the unique identifier of the user. * @param callback A {@link BranchReferralInitListener} callback instance that will return * the data associated with the user id being assigned, if available. */ public void setIdentity(@NonNull String userId, @Nullable BranchReferralInitListener callback) { ServerRequest req = new ServerRequestIdentifyUserRequest(context_, callback, userId); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } else { if (((ServerRequestIdentifyUserRequest) req).isExistingID()) { ((ServerRequestIdentifyUserRequest) req).handleUserExist(branchReferral_); } } } /** * Indicates whether or not this user has a custom identity specified for them. Note that this is independent of installs. * If you call setIdentity, this device will have that identity associated with this user until logout is called. * This includes persisting through uninstalls, as we track device id. * * @return A {@link Boolean} value that will return <i>true</i> only if user already has an identity. */ public boolean isUserIdentified() { return !prefHelper_.getIdentity().equals(PrefHelper.NO_STRING_VALUE); } /** * <p>This method should be called if you know that a different person is about to use the app. For example, * if you allow users to log out and let their friend use the app, you should call this to notify Branch * to create a new user for this device. This will clear the first and latest params, as a new session is created.</p> */ public void logout() { logout(null); } /** * <p>This method should be called if you know that a different person is about to use the app. For example, * if you allow users to log out and let their friend use the app, you should call this to notify Branch * to create a new user for this device. This will clear the first and latest params, as a new session is created.</p> * * @param callback An instance of {@link io.branch.referral.Branch.LogoutStatusListener} to callback with the logout operation status. */ public void logout(LogoutStatusListener callback) { ServerRequest req = new ServerRequestLogout(context_, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Fire-and-forget retrieval of rewards for the current session. Without a callback.</p> */ public void loadRewards() { loadRewards(null); } /** * <p>Retrieves rewards for the current session, with a callback to perform a predefined * action following successful report of state change. You'll then need to call getCredits * in the callback to update the credit totals in your UX.</p> * * @param callback A {@link BranchReferralStateChangedListener} callback instance that will * trigger actions defined therein upon a referral state change. */ public void loadRewards(BranchReferralStateChangedListener callback) { ServerRequest req = new ServerRequestGetRewards(context_, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Retrieve the number of credits available for the "default" bucket.</p> * * @return An {@link Integer} value of the number credits available in the "default" bucket. */ public int getCredits() { return prefHelper_.getCreditCount(); } /** * Returns an {@link Integer} of the number of credits available for use within the supplied * bucket name. * * @param bucket A {@link String} value indicating the name of the bucket to get credits for. * @return An {@link Integer} value of the number credits available in the specified * bucket. */ public int getCreditsForBucket(String bucket) { return prefHelper_.getCreditCount(bucket); } /** * <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the bucket. */ public void redeemRewards(int count) { redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, null); } /** * <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the bucket. * @param callback A {@link BranchReferralStateChangedListener} callback instance that will * trigger actions defined therein upon a executing redeem rewards. */ public void redeemRewards(int count, BranchReferralStateChangedListener callback) { redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, callback); } /** * <p>Redeems the specified number of credits from the named bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param bucket A {@link String} value containing the name of the referral bucket to attempt * to redeem credits from. * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the specified bucket. */ public void redeemRewards(@NonNull final String bucket, final int count) { redeemRewards(bucket, count, null); } /** * <p>Redeems the specified number of credits from the named bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param bucket A {@link String} value containing the name of the referral bucket to attempt * to redeem credits from. * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the specified bucket. * @param callback A {@link BranchReferralStateChangedListener} callback instance that will * trigger actions defined therein upon a executing redeem rewards. */ public void redeemRewards(@NonNull final String bucket, final int count, BranchReferralStateChangedListener callback) { ServerRequestRedeemRewards req = new ServerRequestRedeemRewards(context_, bucket, count, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(BranchListResponseListener callback) { getCreditHistory(null, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param bucket A {@link String} value containing the name of the referral bucket that the * code will belong to. * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(@NonNull final String bucket, BranchListResponseListener callback) { getCreditHistory(bucket, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param afterId A {@link String} value containing the ID of the history record to begin after. * This allows for a partial history to be retrieved, rather than the entire * credit history of the bucket. * @param length A {@link Integer} value containing the number of credit history records to * return. * @param order A {@link CreditHistoryOrder} object indicating which order the results should * be returned in. * <p>Valid choices:</p> * <ul> * <li>{@link CreditHistoryOrder#kMostRecentFirst}</li> * <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li> * </ul> * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(@NonNull final String afterId, final int length, @NonNull final CreditHistoryOrder order, BranchListResponseListener callback) { getCreditHistory(null, afterId, length, order, callback); } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param bucket A {@link String} value containing the name of the referral bucket that the * code will belong to. * @param afterId A {@link String} value containing the ID of the history record to begin after. * This allows for a partial history to be retrieved, rather than the entire * credit history of the bucket. * @param length A {@link Integer} value containing the number of credit history records to * return. * @param order A {@link CreditHistoryOrder} object indicating which order the results should * be returned in. * <p>Valid choices:</p> * <ul> * <li>{@link CreditHistoryOrder#kMostRecentFirst}</li> * <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li> * </ul> * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(final String bucket, final String afterId, final int length, @NonNull final CreditHistoryOrder order, BranchListResponseListener callback) { ServerRequest req = new ServerRequestGetRewardHistory(context_, bucket, afterId, length, order, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API, with additional app-defined meta data to go along with that action.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". * @param metadata A {@link JSONObject} containing app-defined meta-data to be attached to a * user action that has just been completed. */ public void userCompletedAction(@NonNull final String action, JSONObject metadata) { userCompletedAction(action, metadata, null); } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". */ public void userCompletedAction(final String action) { userCompletedAction(action, null, null); } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". * @param callback instance of {@link BranchViewHandler.IBranchViewEvents} to listen Branch view events */ public void userCompletedAction(final String action, BranchViewHandler. IBranchViewEvents callback) { userCompletedAction(action, null, callback); } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API, with additional app-defined meta data to go along with that action.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". * @param metadata A {@link JSONObject} containing app-defined meta-data to be attached to a * user action that has just been completed. * @param callback instance of {@link BranchViewHandler.IBranchViewEvents} to listen Branch view events */ public void userCompletedAction(@NonNull final String action, JSONObject metadata, BranchViewHandler.IBranchViewEvents callback) { if (metadata != null) { metadata = BranchUtil.filterOutBadCharacters(metadata); } ServerRequest req = new ServerRequestActionCompleted(context_, action, metadata, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } public void sendCommerceEvent(@NonNull CommerceEvent commerceEvent, JSONObject metadata, BranchViewHandler.IBranchViewEvents callback) { if (metadata != null) { metadata = BranchUtil.filterOutBadCharacters(metadata); } ServerRequest req = new ServerRequestRActionCompleted(context_, commerceEvent, metadata, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } public void sendCommerceEvent(@NonNull CommerceEvent commerceEvent) { sendCommerceEvent(commerceEvent, null, null); } /** * <p>Returns the parameters associated with the link that referred the user. This is only set once, * the first time the user is referred by a link. Think of this as the user referral parameters. * It is also only set if isReferrable is equal to true, which by default is only true * on a fresh install (not upgrade or reinstall). This will change on setIdentity (if the * user already exists from a previous device) and logout.</p> * * @return A {@link JSONObject} containing the install-time parameters as configured * locally. */ public JSONObject getFirstReferringParams() { String storedParam = prefHelper_.getInstallParams(); JSONObject firstReferringParams = convertParamsStringToDictionary(storedParam); firstReferringParams = appendDebugParams(firstReferringParams); return firstReferringParams; } /** * <p>This function must be called from a non-UI thread! If Branch has no install link data, * and this func is called, it will return data upon initializing, or until LATCH_WAIT_UNTIL. * Returns the parameters associated with the link that referred the user. This is only set once, * the first time the user is referred by a link. Think of this as the user referral parameters. * It is also only set if isReferrable is equal to true, which by default is only true * on a fresh install (not upgrade or reinstall). This will change on setIdentity (if the * user already exists from a previous device) and logout.</p> * * @return A {@link JSONObject} containing the install-time parameters as configured * locally. */ public JSONObject getFirstReferringParamsSync() { getFirstReferringParamsLatch = new CountDownLatch(1); if (prefHelper_.getInstallParams().equals(PrefHelper.NO_STRING_VALUE)) { try { getFirstReferringParamsLatch.await(LATCH_WAIT_UNTIL, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } } String storedParam = prefHelper_.getInstallParams(); JSONObject firstReferringParams = convertParamsStringToDictionary(storedParam); firstReferringParams = appendDebugParams(firstReferringParams); getFirstReferringParamsLatch = null; return firstReferringParams; } /** * <p>Returns the parameters associated with the link that referred the session. If a user * clicks a link, and then opens the app, initSession will return the parameters of the link * and then set them in as the latest parameters to be retrieved by this method. By default, * sessions persist for the duration of time that the app is in focus. For example, if you * minimize the app, these parameters will be cleared when closeSession is called.</p> * * @return A {@link JSONObject} containing the latest referring parameters as * configured locally. */ public JSONObject getLatestReferringParams() { String storedParam = prefHelper_.getSessionParams(); JSONObject latestParams = convertParamsStringToDictionary(storedParam); latestParams = appendDebugParams(latestParams); return latestParams; } /** * <p>This function must be called from a non-UI thread! If Branch has not been initialized * and this func is called, it will return data upon initialization, or until LATCH_WAIT_UNTIL. * Returns the parameters associated with the link that referred the session. If a user * clicks a link, and then opens the app, initSession will return the parameters of the link * and then set them in as the latest parameters to be retrieved by this method. By default, * sessions persist for the duration of time that the app is in focus. For example, if you * minimize the app, these parameters will be cleared when closeSession is called.</p> * * @return A {@link JSONObject} containing the latest referring parameters as * configured locally. */ public JSONObject getLatestReferringParamsSync() { getLatestReferringParamsLatch = new CountDownLatch(1); try { if (initState_ != SESSION_STATE.INITIALISED) { getLatestReferringParamsLatch.await(LATCH_WAIT_UNTIL, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { } String storedParam = prefHelper_.getSessionParams(); JSONObject latestParams = convertParamsStringToDictionary(storedParam); latestParams = appendDebugParams(latestParams); getLatestReferringParamsLatch = null; return latestParams; } /** * Append the deep link debug params to the original params * * @param originalParams A {@link JSONObject} original referrer parameters * @return A new {@link JSONObject} with debug params appended. */ private JSONObject appendDebugParams(JSONObject originalParams) { try { if (originalParams != null && deeplinkDebugParams_ != null) { if (deeplinkDebugParams_.length() > 0) { Log.w(TAG, "You're currently in deep link debug mode. Please comment out 'setDeepLinkDebugMode' to receive the deep link parameters from a real Branch link"); } Iterator<String> keys = deeplinkDebugParams_.keys(); while (keys.hasNext()) { String key = keys.next(); originalParams.put(key, deeplinkDebugParams_.get(key)); } } } catch (Exception ignore) { } return originalParams; } public JSONObject getDeeplinkDebugParams() { if (deeplinkDebugParams_ != null && deeplinkDebugParams_.length() > 0) { Log.w(TAG, "You're currently in deep link debug mode. Please comment out 'setDeepLinkDebugMode' to receive the deep link parameters from a real Branch link"); } return deeplinkDebugParams_; } /** * <p> Generates a shorl url for the given {@link ServerRequestCreateUrl} object </p> * * @param req An instance of {@link ServerRequestCreateUrl} with parameters create the short link. * @return A url created with the given request if the request is synchronous else null. * Note : This method can be used only internally. Use {@link BranchUrlBuilder} for creating short urls. */ String generateShortLinkInternal(ServerRequestCreateUrl req) { if (!req.constructError_ && !req.handleErrors(context_)) { if (linkCache_.containsKey(req.getLinkPost())) { String url = linkCache_.get(req.getLinkPost()); req.onUrlAvailable(url); return url; } else { if (req.isAsync()) { generateShortLinkAsync(req); } else { return generateShortLinkSync(req); } } } return null; } /** * <p>Creates options for sharing a link with other Applications. Creates a link with given attributes and shares with the * user selected clients.</p> * * @param builder A {@link io.branch.referral.Branch.ShareLinkBuilder} instance to build share link. */ private void shareLink(ShareLinkBuilder builder) { //Cancel any existing sharing in progress. if (shareLinkManager_ != null) { shareLinkManager_.cancelShareLinkDialog(true); } shareLinkManager_ = new ShareLinkManager(); shareLinkManager_.shareLink(builder); } /** * <p>Cancel current share link operation and Application selector dialog. If your app is not using auto session management, make sure you are * calling this method before your activity finishes inorder to prevent any window leak. </p> * * @param animateClose A {@link Boolean} to specify whether to close the dialog with an animation. * A value of true will close the dialog with an animation. Setting this value * to false will close the Dialog immediately. */ public void cancelShareLinkDialog(boolean animateClose) { if (shareLinkManager_ != null) { shareLinkManager_.cancelShareLinkDialog(animateClose); } } // PRIVATE FUNCTIONS private String convertDate(Date date) { return android.text.format.DateFormat.format("yyyy-MM-dd", date).toString(); } private String generateShortLinkSync(ServerRequestCreateUrl req) { if (initState_ == SESSION_STATE.INITIALISED) { ServerResponse response = null; try { int timeOut = prefHelper_.getTimeout() + 2000; // Time out is set to slightly more than link creation time to prevent any edge case response = new getShortLinkTask().execute(req).get(timeOut, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException ignore) { } String url = null; if (req.isDefaultToLongUrl()) { url = req.getLongUrl(); } if (response != null && response.getStatusCode() == HttpURLConnection.HTTP_OK) { try { url = response.getObject().getString("url"); if (req.getLinkPost() != null) { linkCache_.put(req.getLinkPost(), url); } } catch (JSONException e) { e.printStackTrace(); } } return url; } else { Log.i("BranchSDK", "Branch Warning: User session has not been initialized"); } return null; } private void generateShortLinkAsync(final ServerRequest req) { handleNewRequest(req); } private JSONObject convertParamsStringToDictionary(String paramString) { if (paramString.equals(PrefHelper.NO_STRING_VALUE)) { return new JSONObject(); } else { try { return new JSONObject(paramString); } catch (JSONException e) { byte[] encodedArray = Base64.decode(paramString.getBytes(), Base64.NO_WRAP); try { return new JSONObject(new String(encodedArray)); } catch (JSONException ex) { ex.printStackTrace(); return new JSONObject(); } } } } /** * <p>Schedules a repeating threaded task to get the following details and report them to the * Branch API <b>once a week</b>:</p> * <pre style="background:#fff;padding:10px;border:2px solid silver;"> * int interval = 7 * 24 * 60 * 60; * appListingSchedule_ = scheduler.scheduleAtFixedRate( * periodicTask, (days * 24 + hours) * 60 * 60, interval, TimeUnit.SECONDS);</pre> * <ul> * <li>{@link SystemObserver#getOS()}</li> * <li>{@link SystemObserver#getListOfApps()}</li> * </ul> * * @see {@link SystemObserver} * @see {@link PrefHelper} */ private void scheduleListOfApps() { ScheduledThreadPoolExecutor scheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1); Runnable periodicTask = new Runnable() { @Override public void run() { ServerRequest req = new ServerRequestSendAppList(context_); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } }; Date date = new Date(); Calendar calendar = GregorianCalendar.getInstance(); calendar.setTime(date); int days = Calendar.SATURDAY - calendar.get(Calendar.DAY_OF_WEEK); // days to Saturday int hours = 2 - calendar.get(Calendar.HOUR_OF_DAY); // hours to 2am, can be negative if (days == 0 && hours < 0) { days = 7; } int interval = 7 * 24 * 60 * 60; appListingSchedule_ = scheduler.scheduleAtFixedRate(periodicTask, (days * 24 + hours) * 60 * 60, interval, TimeUnit.SECONDS); } private void processNextQueueItem() { try { serverSema_.acquire(); if (networkCount_ == 0 && requestQueue_.getSize() > 0) { networkCount_ = 1; ServerRequest req = requestQueue_.peek(); serverSema_.release(); if (req != null) { if (!req.isWaitingOnProcessToFinish()) { // All request except Install request need a valid IdentityID if (!(req instanceof ServerRequestRegisterInstall) && !hasUser()) { Log.i("BranchSDK", "Branch Error: User session has not been initialized!"); networkCount_ = 0; handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION); } //All request except open and install need a session to execute else if (!(req instanceof ServerRequestInitSession) && (!hasSession() || !hasDeviceFingerPrint())) { networkCount_ = 0; handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION); } else { BranchPostTask postTask = new BranchPostTask(req); postTask.executeTask(); } } else { networkCount_ = 0; } } else { requestQueue_.remove(null); //In case there is any request nullified remove it. } } else { serverSema_.release(); } } catch (Exception e) { e.printStackTrace(); } } private void handleFailure(int index, int statusCode) { ServerRequest req; if (index >= requestQueue_.getSize()) { req = requestQueue_.peekAt(requestQueue_.getSize() - 1); } else { req = requestQueue_.peekAt(index); } handleFailure(req, statusCode); } private void handleFailure(final ServerRequest req, int statusCode) { if (req == null) return; req.handleFailure(statusCode, ""); } private void updateAllRequestsInQueue() { try { for (int i = 0; i < requestQueue_.getSize(); i++) { ServerRequest req = requestQueue_.peekAt(i); if (req != null) { JSONObject reqJson = req.getPost(); if (reqJson != null) { if (reqJson.has(Defines.Jsonkey.SessionID.getKey())) { req.getPost().put(Defines.Jsonkey.SessionID.getKey(), prefHelper_.getSessionID()); } if (reqJson.has(Defines.Jsonkey.IdentityID.getKey())) { req.getPost().put(Defines.Jsonkey.IdentityID.getKey(), prefHelper_.getIdentityID()); } if (reqJson.has(Defines.Jsonkey.DeviceFingerprintID.getKey())) { req.getPost().put(Defines.Jsonkey.DeviceFingerprintID.getKey(), prefHelper_.getDeviceFingerPrintID()); } } } } } catch (JSONException e) { e.printStackTrace(); } } private boolean hasSession() { return !prefHelper_.getSessionID().equals(PrefHelper.NO_STRING_VALUE); } private boolean hasDeviceFingerPrint() { return !prefHelper_.getDeviceFingerPrintID().equals(PrefHelper.NO_STRING_VALUE); } private boolean hasUser() { return !prefHelper_.getIdentityID().equals(PrefHelper.NO_STRING_VALUE); } private void insertRequestAtFront(ServerRequest req) { if (networkCount_ == 0) { requestQueue_.insert(req, 0); } else { requestQueue_.insert(req, 1); } } private void registerInstallOrOpen(ServerRequest req, BranchReferralInitListener callback) { // If there isn't already an Open / Install request, add one to the queue if (!requestQueue_.containsInstallOrOpen()) { insertRequestAtFront(req); } // If there is already one in the queue, make sure it's in the front. // Make sure a callback is associated with this request. This callback can // be cleared if the app is terminated while an Open/Install is pending. else { // Update the callback to the latest one in init session call if (callback != null) { requestQueue_.setInstallOrOpenCallback(callback); } requestQueue_.moveInstallOrOpenToFront(req, networkCount_, callback); } processNextQueueItem(); } private void initializeSession(final BranchReferralInitListener callback) { if ((prefHelper_.getBranchKey() == null || prefHelper_.getBranchKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE))) { initState_ = SESSION_STATE.UNINITIALISED; //Report Key error on callback if (callback != null) { callback.onInitFinished(null, new BranchError("Trouble initializing Branch.", BranchError.ERR_BRANCH_KEY_INVALID)); } Log.i("BranchSDK", "Branch Warning: Please enter your branch_key in your project's res/values/strings.xml!"); return; } else if (prefHelper_.getBranchKey() != null && prefHelper_.getBranchKey().startsWith("key_test_")) { Log.i("BranchSDK", "Branch Warning: You are using your test app's Branch Key. Remember to change it to live Branch Key during deployment."); } if (!prefHelper_.getExternalIntentUri().equals(PrefHelper.NO_STRING_VALUE) || !enableFacebookAppLinkCheck_) { registerAppInit(callback, null); } else { // Check if opened by facebook with deferred install data boolean appLinkRqSucceeded; appLinkRqSucceeded = DeferredAppLinkDataHandler.fetchDeferredAppLinkData(context_, new DeferredAppLinkDataHandler.AppLinkFetchEvents() { @Override public void onAppLinkFetchFinished(String nativeAppLinkUrl) { prefHelper_.setIsAppLinkTriggeredInit(true); // callback returns when app link fetch finishes with success or failure. Report app link checked in both cases if (nativeAppLinkUrl != null) { Uri appLinkUri = Uri.parse(nativeAppLinkUrl); String bncLinkClickId = appLinkUri.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()); if (!TextUtils.isEmpty(bncLinkClickId)) { prefHelper_.setLinkClickIdentifier(bncLinkClickId); } } requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.FB_APP_LINK_WAIT_LOCK); processNextQueueItem(); } }); if (appLinkRqSucceeded) { registerAppInit(callback, ServerRequest.PROCESS_WAIT_LOCK.FB_APP_LINK_WAIT_LOCK); } else { registerAppInit(callback, null); } } } private void registerAppInit(BranchReferralInitListener callback, ServerRequest.PROCESS_WAIT_LOCK lock) { ServerRequest request; if (hasUser()) { // If there is user this is open request = new ServerRequestRegisterOpen(context_, callback, systemObserver_); } else { // If no user this is an Install request = new ServerRequestRegisterInstall(context_, callback, systemObserver_, InstallListener.getInstallationID()); } request.addProcessWaitLock(lock); if (isGAParamsFetchInProgress_) { request.addProcessWaitLock(ServerRequest.PROCESS_WAIT_LOCK.GAID_FETCH_WAIT_LOCK); } if (intentState_ != INTENT_STATE.READY) { request.addProcessWaitLock(ServerRequest.PROCESS_WAIT_LOCK.INTENT_PENDING_WAIT_LOCK); } if (checkInstallReferrer_ && request instanceof ServerRequestRegisterInstall) { request.addProcessWaitLock(ServerRequest.PROCESS_WAIT_LOCK.INSTALL_REFERRER_FETCH_WAIT_LOCK); InstallListener.captureInstallReferrer(playStoreReferrerFetchTime); } registerInstallOrOpen(request, callback); } private void onIntentReady(Activity activity) { requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.INTENT_PENDING_WAIT_LOCK); if (activity.getIntent() != null) { Uri intentData = activity.getIntent().getData(); readAndStripParam(intentData, activity); if (cookieBasedMatchDomain_ != null && prefHelper_.getBranchKey() != null && !prefHelper_.getBranchKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE)) { if (isGAParamsFetchInProgress_) { // Wait for GAID to Available performCookieBasedStrongMatchingOnGAIDAvailable = true; } else { performCookieBasedStrongMatch(); } } else { processNextQueueItem(); } } else { processNextQueueItem(); } } private void performCookieBasedStrongMatch() { boolean simulateInstall = (prefHelper_.getExternDebug() || isSimulatingInstalls()); DeviceInfo deviceInfo = DeviceInfo.getInstance(simulateInstall, systemObserver_, disableDeviceIDFetch_); Activity currentActivity = null; if (currentActivityReference_ != null) { currentActivity = currentActivityReference_.get(); } Context context = (currentActivity != null) ? currentActivity.getApplicationContext() : null; if (context != null) { requestQueue_.setStrongMatchWaitLock(); BranchStrongMatchHelper.getInstance().checkForStrongMatch(context, cookieBasedMatchDomain_, deviceInfo, prefHelper_, systemObserver_, new BranchStrongMatchHelper.StrongMatchCheckEvents() { @Override public void onStrongMatchCheckFinished() { requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.STRONG_MATCH_PENDING_WAIT_LOCK); processNextQueueItem(); } }); } } /** * Handles execution of a new request other than open or install. * Checks for the session initialisation and adds a install/Open request in front of this request * if the request need session to execute. * * @param req The {@link ServerRequest} to execute */ public void handleNewRequest(ServerRequest req) { //If not initialised put an open or install request in front of this request(only if this needs session) if (initState_ != SESSION_STATE.INITIALISED && !(req instanceof ServerRequestInitSession)) { if ((req instanceof ServerRequestLogout)) { req.handleFailure(BranchError.ERR_NO_SESSION, ""); Log.i(TAG, "Branch is not initialized, cannot logout"); return; } if ((req instanceof ServerRequestRegisterClose)) { Log.i(TAG, "Branch is not initialized, cannot close session"); return; } else { Activity currentActivity = null; if (currentActivityReference_ != null) { currentActivity = currentActivityReference_.get(); } if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) { initUserSessionInternal((BranchReferralInitListener) null, currentActivity, true); } else { boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE; initUserSessionInternal((BranchReferralInitListener) null, currentActivity, isReferrable); } } } requestQueue_.enqueue(req); req.onRequestQueued(); processNextQueueItem(); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void setActivityLifeCycleObserver(Application application) { try { BranchActivityLifeCycleObserver activityLifeCycleObserver = new BranchActivityLifeCycleObserver(); /* Set an observer for activity life cycle events. */ application.unregisterActivityLifecycleCallbacks(activityLifeCycleObserver); application.registerActivityLifecycleCallbacks(activityLifeCycleObserver); isActivityLifeCycleCallbackRegistered_ = true; } catch (NoSuchMethodError | NoClassDefFoundError Ex) { isActivityLifeCycleCallbackRegistered_ = false; isAutoSessionMode_ = false; /* LifeCycleEvents are available only from API level 14. */ Log.w(TAG, new BranchError("", BranchError.ERR_API_LVL_14_NEEDED).getMessage()); } } /** * <p>Class that observes activity life cycle events and determines when to start and stop * session.</p> */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private class BranchActivityLifeCycleObserver implements Application.ActivityLifecycleCallbacks { private int activityCnt_ = 0; //Keep the count of live activities. @Override public void onActivityCreated(Activity activity, Bundle bundle) { intentState_ = handleDelayedNewIntents_ ? INTENT_STATE.PENDING : INTENT_STATE.READY; if (BranchViewHandler.getInstance().isInstallOrOpenBranchViewPending(activity.getApplicationContext())) { BranchViewHandler.getInstance().showPendingBranchView(activity); } } @Override public void onActivityStarted(Activity activity) { intentState_ = handleDelayedNewIntents_ ? INTENT_STATE.PENDING : INTENT_STATE.READY; // If configured on dashboard, trigger content discovery runnable if (initState_ == SESSION_STATE.INITIALISED) { try { ContentDiscoverer.getInstance().discoverContent(activity, sessionReferredLink_); } catch (Exception ignore) { } } if (activityCnt_ < 1) { // Check if this is the first Activity.If so start a session. if (initState_ == SESSION_STATE.INITIALISED) { // Handling case : init session completed previously when app was in background. initState_ = SESSION_STATE.UNINITIALISED; } // Check if debug mode is set in manifest. If so enable debug. if (BranchUtil.isTestModeEnabled(context_)) { prefHelper_.setExternDebug(); } prefHelper_.setLogging(getIsLogging()); startSession(activity); } else if (checkIntentForSessionRestart(activity.getIntent())) { // Case of opening the app by clicking a push notification while app is in foreground initState_ = SESSION_STATE.UNINITIALISED; // no need call close here since it is session forced restart. Don't want to wait till close finish startSession(activity); } activityCnt_++; } @Override public void onActivityResumed(Activity activity) { // Need to check here again for session restart request in case the intent is created while the activity is already running if (checkIntentForSessionRestart(activity.getIntent())) { initState_ = SESSION_STATE.UNINITIALISED; startSession(activity); } currentActivityReference_ = new WeakReference<>(activity); if (handleDelayedNewIntents_) { intentState_ = INTENT_STATE.READY; onIntentReady(activity); } } @Override public void onActivityPaused(Activity activity) { /* Close any opened sharing dialog.*/ if (shareLinkManager_ != null) { shareLinkManager_.cancelShareLinkDialog(true); } } @Override public void onActivityStopped(Activity activity) { ContentDiscoverer.getInstance().onActivityStopped(activity); activityCnt_--; // Check if this is the last activity. If so, stop the session. if (activityCnt_ < 1) { closeSessionInternal(); } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle bundle) { } @Override public void onActivityDestroyed(Activity activity) { if (currentActivityReference_ != null && currentActivityReference_.get() == activity) { currentActivityReference_.clear(); } BranchViewHandler.getInstance().onCurrentActivityDestroyed(activity); } } private void startSession(Activity activity) { Uri intentData = null; if (activity.getIntent() != null) { intentData = activity.getIntent().getData(); } initSessionWithData(intentData, activity); // indicate starting of session. } /* * Check for forced session restart. The Branch session is restarted if the incoming intent has branch_force_new_session set to true. * This is for supporting opening a deep link path while app is already running in the foreground. Such as clicking push notification while app in foreground. * */ private boolean checkIntentForSessionRestart(Intent intent) { boolean isRestartSessionRequested = false; if (intent != null) { isRestartSessionRequested = intent.getBooleanExtra(Defines.Jsonkey.ForceNewBranchSession.getKey(), false); if (isRestartSessionRequested) { intent.putExtra(Defines.Jsonkey.ForceNewBranchSession.getKey(), false); } } return isRestartSessionRequested; } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchReferralInitListener}, defining a single method that takes a list of params in * {@link JSONObject} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see JSONObject * @see BranchError */ public interface BranchReferralInitListener { void onInitFinished(JSONObject referringParams, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchUniversalReferralInitListener}, defining a single method that provides * {@link BranchUniversalObject}, {@link LinkProperties} and an error message of {@link BranchError} format that will be * returned on failure of the request response. * In case of an error the value for {@link BranchUniversalObject} and {@link LinkProperties} are set to null.</p> * * @see BranchUniversalObject * @see LinkProperties * @see BranchError */ public interface BranchUniversalReferralInitListener { void onInitFinished(BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchReferralStateChangedListener}, defining a single method that takes a value of * {@link Boolean} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see Boolean * @see BranchError */ public interface BranchReferralStateChangedListener { void onStateChanged(boolean changed, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchLinkCreateListener}, defining a single method that takes a URL * {@link String} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see String * @see BranchError */ public interface BranchLinkCreateListener { void onLinkCreate(String url, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchLinkShareListener}, defining methods to listen for link sharing status.</p> */ public interface BranchLinkShareListener { /** * <p> Callback method to update when share link dialog is launched.</p> */ void onShareLinkDialogLaunched(); /** * <p> Callback method to update when sharing dialog is dismissed.</p> */ void onShareLinkDialogDismissed(); /** * <p> Callback method to update the sharing status. Called on sharing completed or on error.</p> * * @param sharedLink The link shared to the channel. * @param sharedChannel Channel selected for sharing. * @param error A {@link BranchError} to update errors, if there is any. */ void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError error); /** * <p>Called when user select a channel for sharing a deep link. * Branch will create a deep link for the selected channel and share with it after calling this * method. On sharing complete, status is updated by onLinkShareResponse() callback. Consider * having a sharing in progress UI if you wish to prevent user activity in the window between selecting a channel * and sharing complete.</p> * * @param channelName Name of the selected application to share the link. An empty string is returned if unable to resolve selected client name. */ void onChannelSelected(String channelName); } /** * <p>An interface class for customizing sharing properties with selected channel.</p> */ public interface IChannelProperties { /** * @param channel The name of the channel selected for sharing. * @return {@link String} with value for the message title for sharing the link with the selected channel */ String getSharingTitleForChannel(String channel); /** * @param channel The name of the channel selected for sharing. * @return {@link String} with value for the message body for sharing the link with the selected channel */ String getSharingMessageForChannel(String channel); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchListResponseListener}, defining a single method that takes a list of * {@link JSONArray} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see JSONArray * @see BranchError */ public interface BranchListResponseListener { void onReceivingResponse(JSONArray list, BranchError error); } /** * <p> * Callback interface for listening logout status * </p> */ public interface LogoutStatusListener { /** * Called on finishing the the logout process * * @param loggedOut A {@link Boolean} which is set to true if logout succeeded * @param error An instance of {@link BranchError} to notify any error occurred during logout. * A null value is set if logout succeeded. */ void onLogoutFinished(boolean loggedOut, BranchError error); } /** * <p>enum containing the sort options for return of credit history.</p> */ public enum CreditHistoryOrder { kMostRecentFirst, kLeastRecentFirst } /** * Async Task to create a shorlink for synchronous methods */ private class getShortLinkTask extends AsyncTask<ServerRequest, Void, ServerResponse> { @Override protected ServerResponse doInBackground(ServerRequest... serverRequests) { String urlExtend = "v1/url"; return branchRemoteInterface_.make_restful_post(serverRequests[0].getPost(), prefHelper_.getAPIBaseUrl() + urlExtend, Defines.RequestPath.GetURL.getPath(), prefHelper_.getBranchKey()); } } /** * Asynchronous task handling execution of server requests. Execute the network task on background * thread and request are executed in sequential manner. Handles the request execution in * Synchronous-Asynchronous pattern. Should be invoked only form main thread and the results are * published in the main thread. */ private class BranchPostTask extends BranchAsyncTask<Void, Void, ServerResponse> { ServerRequest thisReq_; public BranchPostTask(ServerRequest request) { thisReq_ = request; } @Override protected void onPreExecute() { super.onPreExecute(); thisReq_.onPreExecute(); } @Override protected ServerResponse doInBackground(Void... voids) { if (thisReq_ instanceof ServerRequestInitSession) { ((ServerRequestInitSession) thisReq_).updateLinkReferrerParams(); } //Update queue wait time addExtraInstrumentationData(thisReq_.getRequestPath() + "-" + Defines.Jsonkey.Queue_Wait_Time.getKey(), String.valueOf(thisReq_.getQueueWaitTime())); //Google ADs ID and LAT value are updated using reflection. These method need background thread //So updating them for install and open on background thread. if (thisReq_.isGAdsParamsRequired() && !BranchUtil.isTestModeEnabled(context_)) { thisReq_.updateGAdsParams(systemObserver_); } if (thisReq_.isGetRequest()) { return branchRemoteInterface_.make_restful_get(thisReq_.getRequestUrl(), thisReq_.getGetParams(), thisReq_.getRequestPath(), prefHelper_.getBranchKey()); } else { return branchRemoteInterface_.make_restful_post(thisReq_.getPostWithInstrumentationValues(instrumentationExtraData_), thisReq_.getRequestUrl(), thisReq_.getRequestPath(), prefHelper_.getBranchKey()); } } @Override protected void onPostExecute(ServerResponse serverResponse) { super.onPostExecute(serverResponse); if (serverResponse != null) { try { int status = serverResponse.getStatusCode(); hasNetwork_ = true; //If the request is not succeeded if (status != 200) { //If failed request is an initialisation request then mark session not initialised if (thisReq_ instanceof ServerRequestInitSession) { initState_ = SESSION_STATE.UNINITIALISED; } // On a bad request notify with call back and remove the request. if (status == 409) { requestQueue_.remove(thisReq_); if (thisReq_ instanceof ServerRequestCreateUrl) { ((ServerRequestCreateUrl) thisReq_).handleDuplicateURLError(); } else { Log.i("BranchSDK", "Branch API Error: Conflicting resource error code from API"); handleFailure(0, status); } } //On Network error or Branch is down fail all the pending requests in the queue except //for request which need to be replayed on failure. else { hasNetwork_ = false; //Collect all request from the queue which need to be failed. ArrayList<ServerRequest> requestToFail = new ArrayList<>(); for (int i = 0; i < requestQueue_.getSize(); i++) { requestToFail.add(requestQueue_.peekAt(i)); } //Remove the requests from the request queue first for (ServerRequest req : requestToFail) { if (req == null || !req.shouldRetryOnFail()) { // Should remove any nullified request object also from queque requestQueue_.remove(req); } } // Then, set the network count to zero, indicating that requests can be started again. networkCount_ = 0; //Finally call the request callback with the error. for (ServerRequest req : requestToFail) { if (req != null) { req.handleFailure(status, serverResponse.getFailReason()); //If request need to be replayed, no need for the callbacks if (req.shouldRetryOnFail()) req.clearCallbacks(); } } } } //If the request succeeded else { hasNetwork_ = true; //On create new url cache the url. if (thisReq_ instanceof ServerRequestCreateUrl) { if (serverResponse.getObject() != null) { final String url = serverResponse.getObject().getString("url"); // cache the link linkCache_.put(((ServerRequestCreateUrl) thisReq_).getLinkPost(), url); } } //On Logout clear the link cache and all pending requests else if (thisReq_ instanceof ServerRequestLogout) { linkCache_.clear(); requestQueue_.clear(); } requestQueue_.dequeue(); // If this request changes a session update the session-id to queued requests. if (thisReq_ instanceof ServerRequestInitSession || thisReq_ instanceof ServerRequestIdentifyUserRequest) { // Immediately set session and Identity and update the pending request with the params JSONObject respJson = serverResponse.getObject(); if (respJson != null) { boolean updateRequestsInQueue = false; if (respJson.has(Defines.Jsonkey.SessionID.getKey())) { prefHelper_.setSessionID(respJson.getString(Defines.Jsonkey.SessionID.getKey())); updateRequestsInQueue = true; } if (respJson.has(Defines.Jsonkey.IdentityID.getKey())) { String new_Identity_Id = respJson.getString(Defines.Jsonkey.IdentityID.getKey()); if (!prefHelper_.getIdentityID().equals(new_Identity_Id)) { //On setting a new identity Id clear the link cache linkCache_.clear(); prefHelper_.setIdentityID(respJson.getString(Defines.Jsonkey.IdentityID.getKey())); updateRequestsInQueue = true; } } if (respJson.has(Defines.Jsonkey.DeviceFingerprintID.getKey())) { prefHelper_.setDeviceFingerPrintID(respJson.getString(Defines.Jsonkey.DeviceFingerprintID.getKey())); updateRequestsInQueue = true; } if (updateRequestsInQueue) { updateAllRequestsInQueue(); } if (thisReq_ instanceof ServerRequestInitSession) { initState_ = SESSION_STATE.INITIALISED; thisReq_.onRequestSucceeded(serverResponse, branchReferral_); // Publish success to listeners isInitReportedThroughCallBack = ((ServerRequestInitSession) thisReq_).hasCallBack(); if (!((ServerRequestInitSession) thisReq_).handleBranchViewIfAvailable((serverResponse))) { checkForAutoDeepLinkConfiguration(); } // Count down the latch holding getLatestReferringParamsSync if (getLatestReferringParamsLatch != null) { getLatestReferringParamsLatch.countDown(); } // Count down the latch holding getFirstReferringParamsSync if (getFirstReferringParamsLatch != null) { getFirstReferringParamsLatch.countDown(); } } else { // For setting identity just call only request succeeded thisReq_.onRequestSucceeded(serverResponse, branchReferral_); } } } else { //Publish success to listeners thisReq_.onRequestSucceeded(serverResponse, branchReferral_); } } networkCount_ = 0; if (hasNetwork_ && initState_ != SESSION_STATE.UNINITIALISED) { processNextQueueItem(); } } catch (JSONException ex) { ex.printStackTrace(); } } } } /** * <p>Checks if an activity is launched by Branch auto deep link feature. Branch launches activitie configured for auto deep link on seeing matching keys. * Keys for auto deep linking should be specified to each activity as a meta data in manifest.</p> * Configure your activity in your manifest to enable auto deep linking as follows * <!-- * <activity android:name=".YourActivity"> * <meta-data android:name="io.branch.sdk.auto_link" android:value="DeepLinkKey1","DeepLinkKey2" /> * </activity> * --> * * @param activity Instance of activity to check if launched on auto deep link. * @return A {Boolean} value whose value is true if this activity is launched by Branch auto deeplink feature. */ public static boolean isAutoDeepLinkLaunch(Activity activity) { return (activity.getIntent().getStringExtra(AUTO_DEEP_LINKED) != null); } private void checkForAutoDeepLinkConfiguration() { JSONObject latestParams = getLatestReferringParams(); String deepLinkActivity = null; try { //Check if the application is launched by clicking a Branch link. if (!latestParams.has(Defines.Jsonkey.Clicked_Branch_Link.getKey()) || !latestParams.getBoolean(Defines.Jsonkey.Clicked_Branch_Link.getKey())) { return; } if (latestParams.length() > 0) { // Check if auto deep link is disabled. ApplicationInfo appInfo = context_.getPackageManager().getApplicationInfo(context_.getPackageName(), PackageManager.GET_META_DATA); if (appInfo.metaData != null && appInfo.metaData.getBoolean(AUTO_DEEP_LINK_DISABLE, false)) { return; } PackageInfo info = context_.getPackageManager().getPackageInfo(context_.getPackageName(), PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA); ActivityInfo[] activityInfos = info.activities; int deepLinkActivityReqCode = DEF_AUTO_DEEP_LINK_REQ_CODE; if (activityInfos != null) { for (ActivityInfo activityInfo : activityInfos) { if (activityInfo != null && activityInfo.metaData != null && (activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY) != null || activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH) != null)) { if (checkForAutoDeepLinkKeys(latestParams, activityInfo) || checkForAutoDeepLinkPath(latestParams, activityInfo)) { deepLinkActivity = activityInfo.name; deepLinkActivityReqCode = activityInfo.metaData.getInt(AUTO_DEEP_LINK_REQ_CODE, DEF_AUTO_DEEP_LINK_REQ_CODE); break; } } } } if (deepLinkActivity != null && currentActivityReference_ != null) { Activity currentActivity = currentActivityReference_.get(); if (currentActivity != null) { Intent intent = new Intent(currentActivity, Class.forName(deepLinkActivity)); intent.putExtra(AUTO_DEEP_LINKED, "true"); // Put the raw JSON params as extra in case need to get the deep link params as JSON String intent.putExtra(Defines.Jsonkey.ReferringData.getKey(), latestParams.toString()); // Add individual parameters in the data Iterator<?> keys = latestParams.keys(); while (keys.hasNext()) { String key = (String) keys.next(); intent.putExtra(key, latestParams.getString(key)); } currentActivity.startActivityForResult(intent, deepLinkActivityReqCode); } else { // This case should not happen. Adding a safe handling for any corner case Log.w(TAG, "No activity reference to launch deep linked activity"); } } } } catch (final PackageManager.NameNotFoundException e) { Log.i("BranchSDK", "Branch Warning: Please make sure Activity names set for auto deep link are correct!"); } catch (ClassNotFoundException e) { Log.i("BranchSDK", "Branch Warning: Please make sure Activity names set for auto deep link are correct! Error while looking for activity " + deepLinkActivity); } catch (Exception ignore) { // Can get TransactionTooLarge Exception here if the Application info exceeds 1mb binder data limit. Usually results with manifest merge from SDKs } } private boolean checkForAutoDeepLinkKeys(JSONObject params, ActivityInfo activityInfo) { if (activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY) != null) { String[] activityLinkKeys = activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY).split(","); for (String activityLinkKey : activityLinkKeys) { if (params.has(activityLinkKey)) { return true; } } } return false; } private boolean checkForAutoDeepLinkPath(JSONObject params, ActivityInfo activityInfo) { String deepLinkPath = null; try { if (params.has(Defines.Jsonkey.AndroidDeepLinkPath.getKey())) { deepLinkPath = params.getString(Defines.Jsonkey.AndroidDeepLinkPath.getKey()); } else if (params.has(Defines.Jsonkey.DeepLinkPath.getKey())) { deepLinkPath = params.getString(Defines.Jsonkey.DeepLinkPath.getKey()); } } catch (JSONException ignored) { } if (activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH) != null && deepLinkPath != null) { String[] activityLinkPaths = activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH).split(","); for (String activityLinkPath : activityLinkPaths) { if (pathMatch(activityLinkPath.trim(), deepLinkPath)) { return true; } } } return false; } private boolean pathMatch(String templatePath, String path) { boolean matched = true; String[] pathSegmentsTemplate = templatePath.split("\\?")[0].split("/"); String[] pathSegmentsTarget = path.split("\\?")[0].split("/"); if (pathSegmentsTemplate.length != pathSegmentsTarget.length) { return false; } for (int i = 0; i < pathSegmentsTemplate.length && i < pathSegmentsTarget.length; i++) { String pathSegmentTemplate = pathSegmentsTemplate[i]; String pathSegmentTarget = pathSegmentsTarget[i]; if (!pathSegmentTemplate.equals(pathSegmentTarget) && !pathSegmentTemplate.contains("*")) { matched = false; break; } } return matched; } public static void enableSimulateInstalls() { isSimulatingInstalls_ = true; } public static void disableSimulateInstalls() { isSimulatingInstalls_ = false; } public static boolean isSimulatingInstalls() { return isSimulatingInstalls_; } public static void enableLogging() { isLogging_ = true; } public static void disableLogging() { isLogging_ = false; } public static boolean getIsLogging() { return isLogging_; } /** * <p> Class for building a share link dialog.This creates a chooser for selecting application for * sharing a link created with given parameters. </p> */ public static class ShareLinkBuilder { private final Activity activity_; private final Branch branch_; private String shareMsg_; private String shareSub_; private Branch.BranchLinkShareListener callback_ = null; private Branch.IChannelProperties channelPropertiesCallback_ = null; private ArrayList<SharingHelper.SHARE_WITH> preferredOptions_; private String defaultURL_; //Customise more and copy url option private Drawable moreOptionIcon_; private String moreOptionText_; private Drawable copyUrlIcon_; private String copyURlText_; private String urlCopiedMessage_; private int styleResourceID_; private boolean setFullWidthStyle_; private int dividerHeight = -1; private String sharingTitle = null; private View sharingTitleView = null; BranchShortLinkBuilder shortLinkBuilder_; private List<String> includeInShareSheet = new ArrayList<>(); private List<String> excludeFromShareSheet = new ArrayList<>(); /** * <p>Creates options for sharing a link with other Applications. Creates a builder for sharing the link with * user selected clients</p> * * @param activity The {@link Activity} to show the dialog for choosing sharing application. * @param parameters A {@link JSONObject} value containing the deep link params. */ public ShareLinkBuilder(Activity activity, JSONObject parameters) { this.activity_ = activity; this.branch_ = branchReferral_; shortLinkBuilder_ = new BranchShortLinkBuilder(activity); try { Iterator<String> keys = parameters.keys(); while (keys.hasNext()) { String key = keys.next(); shortLinkBuilder_.addParameters(key, (String) parameters.get(key)); } } catch (Exception ignore) { } shareMsg_ = ""; callback_ = null; channelPropertiesCallback_ = null; preferredOptions_ = new ArrayList<>(); defaultURL_ = null; moreOptionIcon_ = BranchUtil.getDrawable(activity.getApplicationContext(), android.R.drawable.ic_menu_more); moreOptionText_ = "More..."; copyUrlIcon_ = BranchUtil.getDrawable(activity.getApplicationContext(), android.R.drawable.ic_menu_save); copyURlText_ = "Copy link"; urlCopiedMessage_ = "Copied link to clipboard!"; } /** * *<p>Creates options for sharing a link with other Applications. Creates a builder for sharing the link with * user selected clients</p> * * @param activity The {@link Activity} to show the dialog for choosing sharing application. * @param shortLinkBuilder An instance of {@link BranchShortLinkBuilder} to create link to be shared */ public ShareLinkBuilder(Activity activity, BranchShortLinkBuilder shortLinkBuilder) { this(activity, new JSONObject()); shortLinkBuilder_ = shortLinkBuilder; } /** * <p>Sets the message to be shared with the link.</p> * * @param message A {@link String} to be shared with the link * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setMessage(String message) { this.shareMsg_ = message; return this; } /** * <p>Sets the subject of this message. This will be added to Email and SMS Application capable of handling subject in the message.</p> * * @param subject A {@link String} subject of this message. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setSubject(String subject) { this.shareSub_ = subject; return this; } /** * <p>Adds the given tag an iterable {@link Collection} of {@link String} tags associated with a deep * link.</p> * * @param tag A {@link String} to be added to the iterable {@link Collection} of {@link String} tags associated with a deep * link. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder addTag(String tag) { this.shortLinkBuilder_.addTag(tag); return this; } /** * <p>Adds the given tag an iterable {@link Collection} of {@link String} tags associated with a deep * link.</p> * * @param tags A {@link java.util.List} of tags to be added to the iterable {@link Collection} of {@link String} tags associated with a deep * link. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder addTags(ArrayList<String> tags) { this.shortLinkBuilder_.addTags(tags); return this; } /** * <p>Adds a feature that make use of the link.</p> * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setFeature(String feature) { this.shortLinkBuilder_.setFeature(feature); return this; } /** * <p>Adds a stage application or user flow associated with this link.</p> * * @param stage A {@link String} value identifying the stage in an application or user flow * process. Should not exceed 128 characters. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setStage(String stage) { this.shortLinkBuilder_.setStage(stage); return this; } /** * <p>Adds a callback to get the sharing status.</p> * * @param callback A {@link BranchLinkShareListener} instance for getting sharing status. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setCallback(BranchLinkShareListener callback) { this.callback_ = callback; return this; } /** * @param channelPropertiesCallback A {@link io.branch.referral.Branch.IChannelProperties} instance for customizing sharing properties for channels. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setChannelProperties(IChannelProperties channelPropertiesCallback) { this.channelPropertiesCallback_ = channelPropertiesCallback; return this; } /** * <p>Adds application to the preferred list of applications which are shown on share dialog. * Only these options will be visible when the application selector dialog launches. Other options can be * accessed by clicking "More"</p> * * @param preferredOption A list of applications to be added as preferred options on the app chooser. * Preferred applications are defined in {@link io.branch.referral.SharingHelper.SHARE_WITH}. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder addPreferredSharingOption(SharingHelper.SHARE_WITH preferredOption) { this.preferredOptions_.add(preferredOption); return this; } /** * <p>Adds application to the preferred list of applications which are shown on share dialog. * Only these options will be visible when the application selector dialog launches. Other options can be * accessed by clicking "More"</p> * * @param preferredOptions A list of applications to be added as preferred options on the app chooser. * Preferred applications are defined in {@link io.branch.referral.SharingHelper.SHARE_WITH}. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder addPreferredSharingOptions(ArrayList<SharingHelper.SHARE_WITH> preferredOptions) { this.preferredOptions_.addAll(preferredOptions); return this; } /** * Add the given key value to the deep link parameters * * @param key A {@link String} with value for the key for the deep link params * @param value A {@link String} with deep link parameters value * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder addParam(String key, String value) { try { this.shortLinkBuilder_.addParameters(key, value); } catch (Exception ignore) { } return this; } /** * <p> Set a default url to share in case there is any error creating the deep link </p> * * @param url A {@link String} with value of default url to be shared with the selected application in case deep link creation fails. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setDefaultURL(String url) { defaultURL_ = url; return this; } /** * <p> Set the icon and label for the option to expand the application list to see more options. * Default label is set to "More" </p> * * @param icon Drawable to set as the icon for more option. Default icon is system menu_more icon. * @param label A {@link String} with value for the more option label. Default label is "More" * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setMoreOptionStyle(Drawable icon, String label) { moreOptionIcon_ = icon; moreOptionText_ = label; return this; } /** * <p> Set the icon and label for the option to expand the application list to see more options. * Default label is set to "More" </p> * * @param drawableIconID Resource ID for the drawable to set as the icon for more option. Default icon is system menu_more icon. * @param stringLabelID Resource ID for String label for the more option. Default label is "More" * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setMoreOptionStyle(int drawableIconID, int stringLabelID) { moreOptionIcon_ = BranchUtil.getDrawable(activity_.getApplicationContext(), drawableIconID); moreOptionText_ = activity_.getResources().getString(stringLabelID); return this; } /** * <p> Set the icon, label and success message for copy url option. Default label is "Copy link".</p> * * @param icon Drawable to set as the icon for copy url option. Default icon is system menu_save icon * @param label A {@link String} with value for the copy url option label. Default label is "Copy link" * @param message A {@link String} with value for a toast message displayed on copying a url. * Default message is "Copied link to clipboard!" * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setCopyUrlStyle(Drawable icon, String label, String message) { copyUrlIcon_ = icon; copyURlText_ = label; urlCopiedMessage_ = message; return this; } /** * <p> Set the icon, label and success message for copy url option. Default label is "Copy link".</p> * * @param drawableIconID Resource ID for the drawable to set as the icon for copy url option. Default icon is system menu_save icon * @param stringLabelID Resource ID for the string label the copy url option. Default label is "Copy link" * @param stringMessageID Resource ID for the string message to show toast message displayed on copying a url * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setCopyUrlStyle(int drawableIconID, int stringLabelID, int stringMessageID) { copyUrlIcon_ = BranchUtil.getDrawable(activity_.getApplicationContext(), drawableIconID); copyURlText_ = activity_.getResources().getString(stringLabelID); urlCopiedMessage_ = activity_.getResources().getString(stringMessageID); return this; } public ShareLinkBuilder setAlias(String alias) { this.shortLinkBuilder_.setAlias(alias); return this; } /** * <p> Sets the amount of time that Branch allows a click to remain outstanding.</p> * * @param matchDuration A {@link Integer} value specifying the time that Branch allows a click to * remain outstanding and be eligible to be matched with a new app session. * @return This Builder object to allow for chaining of calls to set methods. */ public ShareLinkBuilder setMatchDuration(int matchDuration) { this.shortLinkBuilder_.setDuration(matchDuration); return this; } /** * <p> * Sets the share dialog to full width mode. Full width mode will show a non modal sheet with entire screen width. * </p> * * @param setFullWidthStyle {@link Boolean} With value true if a full width style share sheet is desired. * @return This Builder object to allow for chaining of calls to set methods. */ public ShareLinkBuilder setAsFullWidthStyle(boolean setFullWidthStyle) { this.setFullWidthStyle_ = setFullWidthStyle; return this; } /** * Set the height for the divider for the sharing channels in the list. Set this to zero to remove the dividers * * @param height The new height of the divider in pixels. * @return this Builder object to allow for chaining of calls to set methods. */ public ShareLinkBuilder setDividerHeight(int height) { this.dividerHeight = height; return this; } /** * Set the title for the sharing dialog * * @param title {@link String} containing the value for the title text. * @return this Builder object to allow for chaining of calls to set methods. */ public ShareLinkBuilder setSharingTitle(String title) { this.sharingTitle = title; return this; } /** * Set the title for the sharing dialog * * @param titleView {@link View} for setting the title. * @return this Builder object to allow for chaining of calls to set methods. */ public ShareLinkBuilder setSharingTitle(View titleView) { this.sharingTitleView = titleView; return this; } /** * Exclude items from the ShareSheet by package name String. * * @param packageName {@link String} package name to be excluded. * @return this Builder object to allow for chaining of calls to set methods. */ public ShareLinkBuilder excludeFromShareSheet(@NonNull String packageName) { this.excludeFromShareSheet.add(packageName); return this; } /** * Exclude items from the ShareSheet by package name array. * * @param packageName {@link String[]} package name to be excluded. * @return this Builder object to allow for chaining of calls to set methods. */ public ShareLinkBuilder excludeFromShareSheet(@NonNull String[] packageName) { this.excludeFromShareSheet.addAll(Arrays.asList(packageName)); return this; } /** * Exclude items from the ShareSheet by package name List. * * @param packageNames {@link List} package name to be excluded. * @return this Builder object to allow for chaining of calls to set methods. */ public ShareLinkBuilder excludeFromShareSheet(@NonNull List<String> packageNames) { this.excludeFromShareSheet.addAll(packageNames); return this; } /** * Include items from the ShareSheet by package name String. If only "com.Slack" * is included, then only preferred sharing options + Slack * will be displayed, for example. * * @param packageName {@link String} package name to be included. * @return this Builder object to allow for chaining of calls to set methods. */ public ShareLinkBuilder includeInShareSheet(@NonNull String packageName) { this.includeInShareSheet.add(packageName); return this; } /** * Include items from the ShareSheet by package name Array. If only "com.Slack" * is included, then only preferred sharing options + Slack * will be displayed, for example. * * @param packageName {@link String[]} package name to be included. * @return this Builder object to allow for chaining of calls to set methods. */ public ShareLinkBuilder includeInShareSheet(@NonNull String[] packageName) { this.includeInShareSheet.addAll(Arrays.asList(packageName)); return this; } /** * Include items from the ShareSheet by package name List. If only "com.Slack" * is included, then only preferred sharing options + Slack * will be displayed, for example. * * @param packageNames {@link List} package name to be included. * @return this Builder object to allow for chaining of calls to set methods. */ public ShareLinkBuilder includeInShareSheet(@NonNull List<String> packageNames) { this.includeInShareSheet.addAll(packageNames); return this; } /** * <p> Set the given style to the List View showing the share sheet</p> * * @param resourceID A Styleable resource to be applied to the share sheet list view */ public void setStyleResourceID(@StyleRes int resourceID) { styleResourceID_ = resourceID; } public void setShortLinkBuilderInternal(BranchShortLinkBuilder shortLinkBuilder) { this.shortLinkBuilder_ = shortLinkBuilder; } /** * <p>Creates an application selector dialog and share a link with user selected sharing option. * The link is created with the parameters provided to the builder. </p> */ public void shareLink() { branchReferral_.shareLink(this); } public Activity getActivity() { return activity_; } public ArrayList<SharingHelper.SHARE_WITH> getPreferredOptions() { return preferredOptions_; } List<String> getExcludedFromShareSheet() { return excludeFromShareSheet; } List<String> getIncludedInShareSheet() { return includeInShareSheet; } public Branch getBranch() { return branch_; } public String getShareMsg() { return shareMsg_; } public String getShareSub() { return shareSub_; } public BranchLinkShareListener getCallback() { return callback_; } public IChannelProperties getChannelPropertiesCallback() { return channelPropertiesCallback_; } public String getDefaultURL() { return defaultURL_; } public Drawable getMoreOptionIcon() { return moreOptionIcon_; } public String getMoreOptionText() { return moreOptionText_; } public Drawable getCopyUrlIcon() { return copyUrlIcon_; } public String getCopyURlText() { return copyURlText_; } public String getUrlCopiedMessage() { return urlCopiedMessage_; } public BranchShortLinkBuilder getShortLinkBuilder() { return shortLinkBuilder_; } public boolean getIsFullWidthStyle() { return setFullWidthStyle_; } public int getDividerHeight() { return dividerHeight; } public String getSharingTitle() { return sharingTitle; } public View getSharingTitleView() { return sharingTitleView; } public int getStyleResourceID() { return styleResourceID_; } } public void registerView(BranchUniversalObject branchUniversalObject, BranchUniversalObject.RegisterViewStatusListener callback) { if (context_ != null) { ServerRequest req; req = new ServerRequestRegisterView(context_, branchUniversalObject, systemObserver_, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } } /** * Update the extra instrumentation data provided to Branch * * @param instrumentationData A {@link HashMap} with key value pairs for instrumentation data. */ public void addExtraInstrumentationData(HashMap<String, String> instrumentationData) { instrumentationExtraData_.putAll(instrumentationData); } /** * Update the extra instrumentation data provided to Branch * * @param key A {@link String} Value for instrumentation data key * @param value A {@link String} Value for instrumentation data value */ public void addExtraInstrumentationData(String key, String value) { instrumentationExtraData_.put(key, value); } @Override public void onBranchViewVisible(String action, String branchViewID) { //No Implementation on purpose } @Override public void onBranchViewAccepted(String action, String branchViewID) { if (ServerRequestInitSession.isInitSessionAction(action)) { checkForAutoDeepLinkConfiguration(); } } @Override public void onBranchViewCancelled(String action, String branchViewID) { if (ServerRequestInitSession.isInitSessionAction(action)) { checkForAutoDeepLinkConfiguration(); } } @Override public void onBranchViewError(int errorCode, String errorMsg, String action) { if (ServerRequestInitSession.isInitSessionAction(action)) { checkForAutoDeepLinkConfiguration(); } } /** * Interface for defining optional Branch view behaviour for Activities */ public interface IBranchViewControl { /** * Defines if an activity is interested to show Branch views or not. * By default activities are considered as Branch view enabled. In case of activities which are not interested to show a Branch view (Splash screen for example) * should implement this and return false. The pending Branch view will be shown with the very next Branch view enabled activity * * @return A {@link Boolean} whose value is true if the activity don't want to show any Branch view. */ boolean skipBranchViewsOnThisActivity(); } private static Context lastApplicationContext = null; private static Boolean isInstantApp = null; /** * Checks if this is an Instant app instance * * @param context Current {@link Context} * @return {@code true} if current application is an instance of instant app */ public static boolean isInstantApp(@NonNull Context context) { try { Context applicationContext = context.getApplicationContext(); if (isInstantApp != null && applicationContext.equals(lastApplicationContext)) { return isInstantApp.booleanValue(); } else { isInstantApp = null; lastApplicationContext = applicationContext; applicationContext.getClassLoader().loadClass("com.google.android.instantapps.supervisor.InstantAppsRuntime"); isInstantApp = Boolean.valueOf(true); } } catch (Exception ex) { isInstantApp = Boolean.valueOf(false); } return isInstantApp.booleanValue(); } /** * Method shows play store install prompt for the full app. Thi passes the referrer to the installed application. The same deep link params as the instant app are provided to the * full app up on Branch#initSession() * * @param activity Current activity * @param requestCode Request code for the activity to receive the result * @return {@code true} if install prompt is shown to user */ public static boolean showInstallPrompt(@NonNull Activity activity, int requestCode) { String installReferrerString = ""; if (Branch.getInstance() != null) { JSONObject latestReferringParams = Branch.getInstance().getLatestReferringParams(); String referringLinkKey = "~" + Defines.Jsonkey.ReferringLink.getKey(); if (latestReferringParams != null && latestReferringParams.has(referringLinkKey)) { String referringLink = ""; try { referringLink = latestReferringParams.getString(referringLinkKey); // Considering the case that url may contain query params with `=` and `&` with it and may cause issue when parsing play store referrer referringLink = URLEncoder.encode(referringLink, "UTF-8"); } catch (JSONException | UnsupportedEncodingException e) { e.printStackTrace(); } if (!TextUtils.isEmpty(referringLink)) { installReferrerString = Defines.Jsonkey.IsFullAppConv.getKey() + "=true&" + Defines.Jsonkey.ReferringLink.getKey() + "=" + referringLink; } } } return doShowInstallPrompt(activity, requestCode, installReferrerString); } /** * Method shows play store install prompt for the full app. Use this method only if you have custom parameters to pass to the full app using referrer else use * {@link #showInstallPrompt(Activity, int)} * * @param activity Current activity * @param requestCode Request code for the activity to receive the result * @param referrer Any custom referrer string to pass to full app (must be of format "referrer_key1=referrer_value1%26referrer_key2=referrer_value2") * @return {@code true} if install prompt is shown to user */ public static boolean showInstallPrompt(@NonNull Activity activity, int requestCode, @Nullable String referrer) { String installReferrerString = Defines.Jsonkey.IsFullAppConv.getKey() + "=true&" + referrer; return doShowInstallPrompt(activity, requestCode, installReferrerString); } /** * Method shows play store install prompt for the full app. Use this method only if you want the full app to receive a custom {@link BranchUniversalObject} to do deferred deep link. * Please see {@link #showInstallPrompt(Activity, int)} * NOTE : * This method will do a synchronous generation of Branch short link for the BUO. So please consider calling this method on non UI thread * Please make sure your instant app and full ap are using same Branch key in order for the deferred deep link working * * @param activity Current activity * @param requestCode Request code for the activity to receive the result * @param buo {@link BranchUniversalObject} to pass to the full app up on install * @return {@code true} if install prompt is shown to user */ public static boolean showInstallPrompt(@NonNull Activity activity, int requestCode, @NonNull BranchUniversalObject buo) { if (buo != null) { String shortUrl = buo.getShortUrl(activity, new LinkProperties()); String installReferrerString = Defines.Jsonkey.ReferringLink.getKey() + "=" + shortUrl; if (!TextUtils.isEmpty(installReferrerString)) { return showInstallPrompt(activity, requestCode, installReferrerString); } else { return showInstallPrompt(activity, requestCode, ""); } } return false; } private static boolean doShowInstallPrompt(@NonNull Activity activity, int requestCode, @Nullable String referrer) { if (activity == null) { Log.e("BranchSDK", "Unable to show install prompt. Activity is null"); return false; } else if (!isInstantApp(activity)) { Log.e("BranchSDK", "Unable to show install prompt. Application is not an instant app"); return false; } else { Intent intent = (new Intent("android.intent.action.VIEW")).setPackage("com.android.vending").addCategory("android.intent.category.DEFAULT") .putExtra("callerId", activity.getPackageName()) .putExtra("overlay", true); Uri.Builder uriBuilder = (new Uri.Builder()).scheme("market").authority("details").appendQueryParameter("id", activity.getPackageName()); if (!TextUtils.isEmpty(referrer)) { uriBuilder.appendQueryParameter("referrer", referrer); } intent.setData(uriBuilder.build()); activity.startActivityForResult(intent, requestCode); return true; } } }
package org.globus.cog.abstraction.coaster.service.job.manager; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.globus.cog.abstraction.impl.common.IdentityImpl; import org.globus.cog.abstraction.impl.common.StatusEvent; import org.globus.cog.abstraction.impl.execution.coaster.NotificationManager; import org.globus.cog.abstraction.interfaces.ExecutionService; import org.globus.cog.abstraction.interfaces.Identity; import org.globus.cog.abstraction.interfaces.JobSpecification; import org.globus.cog.abstraction.interfaces.Status; import org.globus.cog.abstraction.interfaces.StatusListener; import org.globus.cog.abstraction.interfaces.Task; import org.globus.cog.util.ProcessKiller; import org.globus.cog.util.ProcessListener; import org.globus.cog.util.ProcessMonitor; import org.globus.cog.util.StreamProcessor; import org.globus.cog.util.Streamer; import org.globus.cog.util.StringUtil; /** * Construct MPICH/Hydra proxies and submit them back to sleeping Cpu * There is one Mpiexec instance for each Job that requires MPI * @author wozniak */ public class Mpiexec implements ProcessListener, StatusListener { public static final Logger logger = Logger.getLogger(Mpiexec.class); /** The path to mpiexec */ public static String MPIEXEC = "mpiexec"; private List<Job> proxies = null; /** The original user job */ private final Job job; /** Map from Status code to count of those codes received */ private final Map<Integer,Integer> statusCount = new HashMap<Integer,Integer>(); /** The Block containing the Cpus that will run this Job TODO: Use this to ensure all Cpus are in this Block */ private final Block block; /** The Cpus that will run this Job */ private final List<Cpu> cpus; /** The output from mpiexec */ private String output; /** The error from mpiexec */ private String error; /** The provider on which this task will be run Essentially, there is the local SMP mode and the remote host/TCP mode (currently, only local SMP works) */ private String provider; Mpiexec(List<Cpu> cpus, Job job) { this.cpus = cpus; this.job = job; assert(cpus.size() > 0); this.block = cpus.get(0).getBlock(); proxies = new ArrayList<Job>(job.cpus); // Get the provider String p = job.getTask().getService(0).getProvider(); provider = p.toLowerCase(); logger.debug("start: " + job + " provider: " + provider); } boolean launch() { try { boolean result = runMpiexec(); logger.debug("Output from Hydra: \n" + output); if (error.length() > 0) logger.error("Errors from Hydra:\n" + error); if (!result) return result; } catch (IOException e) { e.printStackTrace(); return false; } List<String[]> lines = getProxyLines(); for (int i = 0; i < job.cpus; i++) { Job proxy = getProxyJob(lines.get(i), i); proxies.add(proxy); } launchProxies(); return true; } private boolean runMpiexec() throws IOException { Task task = job.getTask(); String[] cmd = commandLine(task); Process process = Runtime.getRuntime().exec(cmd); InputStream istream = process.getInputStream(); InputStream estream = process.getErrorStream(); ByteArrayOutputStream ibytes = new ByteArrayOutputStream(); ByteArrayOutputStream ebytes = new ByteArrayOutputStream(); Streamer streamer = new Streamer(estream, ebytes); streamer.start(); Object object = new Object(); StreamProcessor sprocessor = new StreamProcessor(istream, ibytes, object, "HYDRA_LAUNCH_END"); monitor(process); boolean result = waitForHydra(sprocessor, object); output = ibytes.toString(); error = ebytes.toString(); return result; } private String[] commandLine(Task task) { JobSpecification spec = (JobSpecification) task.getSpecification(); List<String> cmdl = new ArrayList<String>(); logger.debug(spec.toString()); String hosts = getHydraHostList(task); cmdl.add(MPIEXEC); cmdl.add("-bootstrap"); cmdl.add("none"); cmdl.add("-disable-hostname-propagation"); cmdl.add("-n"); cmdl.add(Integer.toString(job.cpus)); cmdl.add("-hosts"); cmdl.add(hosts); cmdl.add(spec.getExecutable()); cmdl.addAll(spec.getArgumentsAsList()); String[] result = new String[cmdl.size()]; cmdl.toArray(result); if (logger.isDebugEnabled()) { String logline = StringUtil.concat(result); logger.debug(logline); } return result; } private String getHydraHostList(Task task) { String result = null; ExecutionService service = (ExecutionService) task.getService(0); String jobManager = service.getJobManager(); // logger.debug("jobmanager: " + jobManager); if (jobManager.equals("local:local")) result = getHydraHostListLocal(); else result = getHydraHostListHostnames(); return result; } private String getHydraHostListLocal() { int count = cpus.size(); StringBuilder sb = new StringBuilder(count*4); for (int i = 0; i < count; i++) { sb.append(i); if (i < count-1) sb.append(','); } String result = sb.toString(); // logger.trace("getHydraHostListLocal: " + result); return result; } private String getHydraHostListHostnames() { StringBuilder sb = new StringBuilder(cpus.size()*16); for (int i = 0; i < cpus.size(); i++) { Cpu cpu = cpus.get(i); Node node = cpu.getNode(); sb.append(node.getHostname()); if (i < cpus.size()-1) sb.append(','); } return sb.toString(); } /** Time to wait for MPICH output; seconds */ private static final int MPICH_TIMEOUT = 3; /** Wait until Hydra has reported the proxy command lines The process does not exit until the proxies exit */ private boolean waitForHydra(StreamProcessor sprocessor, Object object) { int tries = 0; boolean result = false; synchronized (object) { try { sprocessor.start(); while (!sprocessor.matched() && tries++ < MPICH_TIMEOUT) object.wait(1000); } catch (InterruptedException e) { logger.error(e.getStackTrace()); } } result = sprocessor.matched(); logger.debug("waitForHydra complete: " + result); return result; } /** Break output into lines and then into words, returning only the significant words */ private List<String[]> getProxyLines() { List<String[]> result = new ArrayList<String[]>(); String[] lines = output.split("\\n"); for (String line : lines) if (line.startsWith("HYDRA_LAUNCH:")) { String[] tokens = line.split("\\s"); String[] args = StringUtil.subset(tokens, 1); result.add(args); } return result; } /** Replace the user job with a Hydra proxy job New Job.Task.Identity is appended with unique integer */ private Job getProxyJob(String[] line, int i) { // Set clone to notify this Mpiexec Task clone = (Task) job.getTask().clone(); clone.addStatusListener(this); // Update Task Identity and set Notification Identity cloneID = new IdentityImpl(clone.getIdentity()); String value = cloneID.getValue() + ":" + i; cloneID.setValue(value); clone.setIdentity(cloneID); NotificationManager.getDefault().registerTask(value, clone); // Update Task Specification JobSpecification spec = (JobSpecification) clone.getSpecification(); spec.setExecutable(line[0]); spec.setArguments(StringUtil.concat(line, 1)); if (logger.isDebugEnabled()) logger.debug("Proxy job: " + spec.getExecutable() + " " + spec.getArguments()); Job result = new Job(clone, 1); return result; } /** * Set up threads to watch the external process * @param process */ private void monitor(Process process) { ProcessMonitor monitor = new ProcessMonitor(process, this); monitor.start(); ProcessKiller killer = new ProcessKiller(process, 10000); killer.start(); } public void callback(ProcessMonitor monitor) { logger.debug("mpiexec exitcode: " + monitor.getExitCode()); } /** Launch proxies on this Cpu and several others (The LinkedList sleeping should already have enough Cpus) */ private void launchProxies() { for (int i = 0; i < proxies.size(); i++) submitToCpu(cpus.get(i), proxies.get(i), i); } private void submitToCpu(Cpu sleeper, Job proxy, int i) { assert(sleeper != null); JobSpecification spec = (JobSpecification) proxy.getTask().getSpecification(); spec.addEnvironmentVariable("MPI_RANK", i); sleeper.launch(proxy); } /** Multiplex Hydra proxy StatusEvents into the StatusEvents for the original job */ public void statusChanged(StatusEvent event) { logger.debug(event); synchronized (statusCount) { int code = event.getStatus().getStatusCode(); Integer count = statusCount.get(code); if (count == null) count = 1; else count++; statusCount.put(code, count); if (count == proxies.size()) propagate(event); } } private void propagate(StatusEvent event) { Status s = event.getStatus(); logger.debug("propagating: to: " + job + " " + s); job.getTask().setStatus(s); } }
package org.rstudio.studio.client.workbench.views.source.editors.text.r; import org.rstudio.core.client.Debug; import org.rstudio.core.client.HandlerRegistrations; import org.rstudio.core.client.Rectangle; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.events.MouseDragHandler.MouseCoordinates; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.common.codetools.CodeToolsServerOperations; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor; import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay; import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay.AnchoredSelection; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceEditorNative; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Token; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.TokenCursor; import org.rstudio.studio.client.workbench.views.source.editors.text.events.CursorChangedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.events.CursorChangedHandler; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.logical.shared.AttachEvent; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Event.NativePreviewEvent; import com.google.gwt.user.client.Event.NativePreviewHandler; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.PopupPanel.PositionCallback; import com.google.inject.Inject; public class SignatureToolTipManager { public SignatureToolTipManager(DocDisplay docDisplay) { RStudioGinjector.INSTANCE.injectMembers(this); toolTip_ = new RCompletionToolTip(docDisplay); docDisplay_ = docDisplay; handlers_ = new HandlerRegistrations(); timer_ = new Timer() { @Override public void run() { // Bail if we don't ever show tooltips if (!uiPrefs_.showSignatureTooltips().getGlobalValue()) return; // Bail if this is a cursor-activated timer and we // don't want idle tooltips if (coordinates_ == null && !uiPrefs_.showFunctionTooltipOnIdle().getGlobalValue()) return; resolveActiveFunctionAndDisplayToolTip(); } }; monitor_ = new Timer() { @Override public void run() { if (ready_) { timer_.schedule(TIMER_DELAY_MS); ready_ = false; } } }; handlers_.add(docDisplay_.addFocusHandler(new FocusHandler() { @Override public void onFocus(FocusEvent event) { beginMonitoring(); } })); handlers_.add(docDisplay_.addBlurHandler(new BlurHandler() { @Override public void onBlur(BlurEvent event) { timer_.cancel(); toolTip_.hide(); endMonitoring(); } })); handlers_.add(docDisplay_.addCursorChangedHandler(new CursorChangedHandler() { @Override public void onCursorChanged(final CursorChangedEvent event) { // Ensure that we're running when we receive a // cursor changed event. if (!isMonitoring()) beginMonitoring(); // Defer so that anchors can update Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { // Check to see if the cursor has moved outside of the anchored region. if (anchor_ != null && toolTip_.isShowing() && !anchor_.getRange().contains(event.getPosition())) { anchor_ = null; toolTip_.hide(); } } }); } })); handlers_.add(toolTip_.addAttachHandler(new AttachEvent.Handler() { @Override public void onAttachOrDetach(AttachEvent event) { if (!event.isAttached()) { coordinates_ = null; position_ = null; anchor_ = null; } } })); } @Inject public void initialize(UIPrefs uiPrefs, CodeToolsServerOperations server) { uiPrefs_ = uiPrefs; server_ = server; } private void attachPreviewHandler() { detachPreviewHandler(); preview_ = Event.addNativePreviewHandler(new NativePreviewHandler() { @Override public void onPreviewNativeEvent(NativePreviewEvent preview) { if (preview.getTypeInt() == Event.ONMOUSEMOVE) { NativeEvent event = preview.getNativeEvent(); coordinates_ = new MouseCoordinates( event.getClientX(), event.getClientY()); ready_ = true; } else if (preview.getTypeInt() == Event.ONKEYDOWN) { coordinates_ = null; ready_ = true; if (preview.getNativeEvent().getKeyCode() == KeyCodes.KEY_ESCAPE) suppressed_ = true; } } }); } private void detachPreviewHandler() { if (preview_ != null) { preview_.removeHandler(); preview_ = null; } } private boolean isMonitoring() { return monitoring_; } private void beginMonitoring() { if (monitoring_) return; attachPreviewHandler(); monitor_.scheduleRepeating(MONITOR_DELAY_MS); monitoring_ = true; } private void endMonitoring() { detachPreviewHandler(); monitor_.cancel(); monitoring_ = false; } public void detach() { endMonitoring(); timer_.cancel(); handlers_.removeHandler(); } public RCompletionToolTip getToolTip() { return toolTip_; } public boolean previewKeyDown(NativeEvent event) { return toolTip_.previewKeyDown(event); } public void displayToolTip(final String name, final String source) { if (isBoringFunction(name)) return; server_.getArgs(name, source, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String response) { if (StringUtil.isNullOrEmpty(response)) return; toolTip_.resolvePositionAndShow(name + response); } @Override public void onError(ServerError error) { Debug.logError(error); } }); } boolean isMouseDrivenEvent() { return coordinates_ != null; } Position getLookupPosition() { if (coordinates_ == null) { Position position = docDisplay_.getCursorPosition(); // Nudge the cursor column if the cursor currently lies // upon a closing paren. if (docDisplay_.getCharacterAtCursor() == ')' && position.getColumn() != 0) { position = Position.create( position.getRow(), position.getColumn() - 1); } return position; } return docDisplay_.screenCoordinatesToDocumentPosition( coordinates_.getMouseX(), coordinates_.getMouseY()); } // Sets an anchored range for a cursor currently lying // on an identifier before a '(' (a function call). private void setAnchor(TokenCursor cursor) { if (anchor_ != null) { anchor_.detach(); anchor_ = null; } TokenCursor endCursor = cursor.cloneCursor(); if (!endCursor.moveToNextToken()) return; if (!endCursor.valueEquals("(")) return; // TODO: How to anchor if there is no matching ')' for // this function? if (!endCursor.fwdToMatchingToken()) return; Position endPos = endCursor.currentPosition(); TokenCursor startCursor = cursor.cloneCursor(); Token lookbehind = startCursor.peekBwd(1); if (lookbehind.valueEquals("::") || lookbehind.valueEquals(":::")) { if (!startCursor.moveToPreviousToken()) return; if (!startCursor.moveToPreviousToken()) return; } Position startPos = startCursor.currentPosition(); anchor_ = docDisplay_.createAnchoredSelection(startPos, endPos); } public void resolveActiveFunctionAndDisplayToolTip() { if (suppressed_) { suppressed_ = false; return; } if (docDisplay_.isPopupVisible()) return; AceEditor editor = (AceEditor) docDisplay_; if (editor == null) return; final Position position = getLookupPosition(); final boolean isMouseEvent = isMouseDrivenEvent(); // Ensure that the mouse target is actually the active editor if (isMouseEvent) { Element el = DomUtils.elementFromPoint( coordinates_.getMouseX(), coordinates_.getMouseY()); AceEditorNative nativeEditor = AceEditorNative.getEditor(el); if (nativeEditor != null && nativeEditor != editor.getWidget().getEditor()) return; } // Hide an older tooltip if this was a mouse move (this allows // the popup to hide if the user hovers over a function name, // and then later moves the mouse away) if (isMouseEvent) toolTip_.hide(); TokenCursor cursor = editor.getSession().getMode().getRCodeModel().getTokenCursor(); if (!cursor.moveToPosition(position, true)) return; // If this is a cursor-idle event and the user has opted into // cursor-idle tooltips, then do some extra work to resolve // the location of that function. It's okay if this fails // (implies that perhaps the cursor is already on a function name, // rather than within a function). Note that on failure the cursor // position is not changed. if (!isMouseEvent && uiPrefs_.showFunctionTooltipOnIdle().getGlobalValue() && !cursor.valueEquals("(")) { cursor.findOpeningBracket("(", false); } Token lookahead = cursor.peekFwd(1); if (lookahead.valueEquals("::") || lookahead.valueEquals(":::")) if (!cursor.moveToNextToken()) return; if (cursor.valueEquals("::") || cursor.valueEquals(":::")) if (!cursor.moveToNextToken()) return; if (cursor.valueEquals("(")) if (!cursor.moveToPreviousToken()) return; // Cache the cursor position -- this should be the first // token prior to a '(', forming the active call. // If we already have an active tooltip for the current position, // then bail. if (toolTip_.isShowing() && cursor.currentPosition().isEqualTo(position_)) { return; } position_ = cursor.currentPosition(); // Double check that we're in the correct spot for a function call. // The cursor should lie upon an identifier, and the next token should // be an opening paren. if (!cursor.hasType("identifier")) return; if (!cursor.nextValue().equals("(")) return; String callString = cursor.currentValue(); if (isBoringFunction(callString)) return; // If this is a namespaced function call, then append that context. Token lookbehind = cursor.peekBwd(1); if (lookbehind.valueEquals("::") || lookbehind.valueEquals(":::")) { // Do-while loop just to allow 'break' for control flow do { TokenCursor clone = cursor.cloneCursor(); if (!clone.moveToPreviousToken()) break; if (!clone.moveToPreviousToken()) break; if (!clone.hasType("identifier")) break; callString = clone.currentValue() + "::" + callString; } while (false); } // Set anchor (so we can dismiss popup when cursor moves outside // of anchored region) setAnchor(cursor.cloneCursor()); final String fnString = callString; server_.getArgs(fnString, "", new ServerRequestCallback<String>() { @Override public void onResponseReceived(String arguments) { final String signature = fnString + arguments; if (StringUtil.isNullOrEmpty(arguments)) return; resolvePositionAndShow(signature, position); } @Override public void onError(ServerError error) { Debug.logError(error); } }); } private void resolvePositionAndShow(String signature, Position position) { // Default to displaying before cursor; however, display above // if doing so would place the tooltip too close (or off) of // the window. final Rectangle bounds = docDisplay_.getPositionBounds(position); toolTip_.setText(signature); toolTip_.setPopupPositionAndShow(new PositionCallback() { @Override public void setPosition(int offsetWidth, int offsetHeight) { int left = bounds.getLeft(); boolean verticalOverflow = bounds.getBottom() + offsetHeight >= Window.getClientHeight() - 20; int top = verticalOverflow ? bounds.getTop() - offsetHeight - 10 : bounds.getBottom() + 10; toolTip_.setPopupPosition(left, top); } }); } private final RCompletionToolTip toolTip_; private final DocDisplay docDisplay_; private final HandlerRegistrations handlers_; private final Timer timer_; private final Timer monitor_; private boolean monitoring_; private boolean suppressed_; private HandlerRegistration preview_; private MouseCoordinates coordinates_; private Position position_; private AnchoredSelection anchor_; private boolean ready_; private UIPrefs uiPrefs_; private CodeToolsServerOperations server_; private static final int MONITOR_DELAY_MS = 200; private static final int TIMER_DELAY_MS = 900; }
package com.magshimim.torch.recording; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.PixelFormat; import android.graphics.Point; import android.hardware.display.VirtualDisplay; import android.media.Image; import android.media.ImageReader; import android.media.projection.MediaProjection; import android.os.Handler; import android.os.HandlerThread; import android.os.Process; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.Display; import com.magshimim.torch.BuildConfig; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.nio.Buffer; import java.nio.ByteBuffer; public class FrameRecorder implements IFrameRecorder { private final static String TAG = "FrameRecorder"; private final static boolean DEBUG = BuildConfig.DEBUG; // Used in order to save reconstruction of Bitmap object private Bitmap latest; // Handler for callbacks of media projection and image reader private Handler handler; // Thread for the handler private HandlerThread handlerThread; // An object for acquiring captured bitmap private ImageReader imageReader; // A callback that is called with a captured bitmap, supplied by the user private IFrameCallback callback; // MediaProjection for recording the screen private MediaProjection mediaProjection; // An external exception handler private Thread.UncaughtExceptionHandler exceptionHandler; // VirtualDisplay for contain the recorded data private VirtualDisplay virtualDisplay; // Display metrics private int height, width, dpi; // Used to prevent re-calls of start/stop methods private boolean recording; /** * Construct new frame recorder. * @param mediaProjection A MediaProjection object for recording the screen * @param display The display to be recorder * @param dpi The display dpi * @param callback The callback after capturing a frame * @param exceptionHandler The exception handler for uncaught exceptions */ public FrameRecorder(@NonNull MediaProjection mediaProjection, @NonNull Display display, int dpi, @NonNull IFrameCallback callback, @NonNull Thread.UncaughtExceptionHandler exceptionHandler) { if(DEBUG) Log.d(TAG, "Constructor"); this.mediaProjection = mediaProjection; this.callback = callback; this.dpi = dpi; this.exceptionHandler = exceptionHandler; latest = null; recording = false; // Get display size Point size = new Point(); display.getSize(size); height = size.y; width = size.x; if(DEBUG) Log.d(TAG, "Height: " + height + ", Width: " + width); // Create running objects handlerThread = new HandlerThread(getClass().getSimpleName(), Process.THREAD_PRIORITY_BACKGROUND); if(DEBUG) Log.d(TAG, "HandlerThread is created"); handlerThread.setUncaughtExceptionHandler(this.exceptionHandler); if(DEBUG) Log.d(TAG, "UncaughtExceptionHandler is set"); handler = new Handler(handlerThread.getLooper()); if(DEBUG) Log.d(TAG, "Handler is created"); imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2); if(DEBUG) Log.d(TAG, "ImageReader is created"); imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() { @Override public void onImageAvailable(ImageReader reader) { FrameRecorder.this.callback.onFrameCaptured(getBitmap(reader)); } }, handler); if(DEBUG) Log.d(TAG, "ImageReader listener is registered"); } /** * Starts recording. * Nothing is done if the recording has already started. * The function starts a handler thread for recording. * */ public synchronized void startRecording() { if(DEBUG) Log.d(TAG, "startRecording"); // If already recording then return if(recording) { if(DEBUG) Log.d(TAG, "already recording"); return; } // Start relevant tasks handlerThread.start(); if(DEBUG) Log.d(TAG, "HandlerThread started"); virtualDisplay = mediaProjection.createVirtualDisplay("CurrentFrame", width, height, dpi, 0, imageReader.getSurface(), null, handler); if(DEBUG) Log.d(TAG, "VirtualDisplay created"); MediaProjection.Callback cb=new MediaProjection.Callback() { @Override public void onStop() { virtualDisplay.release(); } }; mediaProjection.registerCallback(cb, handler); if(DEBUG) Log.d(TAG, "Registered MediaProjection callback"); if(!objectsInitialized()) { if(DEBUG) Log.d(TAG, "startRecording failed"); stopRecording(); if(DEBUG) Log.d(TAG, "Stopped recording"); exceptionHandler.uncaughtException(Thread.currentThread(), new IllegalStateException("Objects initialization went wrong")); return; } // Set recording to true recording = true; } /** * Stops recording. * Nothing is done if recording has not started. * This function stops running objects and cleans up any necessary objects. */ public synchronized void stopRecording() { if(DEBUG) Log.d(TAG, "stopRecording"); // Return if not recording if(!recording) { if(DEBUG) Log.d(TAG, "not recording"); return; } if(mediaProjection != null) { mediaProjection.stop(); mediaProjection = null; if(DEBUG) Log.d(TAG, "cleaned mediaProjection"); } else Log.w(TAG, "mediaProjection was null"); if(imageReader != null) { imageReader.close(); imageReader = null; if(DEBUG) Log.d(TAG, "cleaned imageReader"); } else Log.w(TAG, "imageReader was null"); if(virtualDisplay != null) { virtualDisplay.release(); virtualDisplay = null; if(DEBUG) Log.d(TAG, "cleaned virtualDisplay"); } else Log.w(TAG, "virtualDisplay was null"); if(handlerThread != null) { handlerThread.quit(); handlerThread = null; if(DEBUG) Log.d(TAG, "cleaned handlerThread"); } else Log.w(TAG, "handlerThread was null"); if(handler != null) { handler.getLooper().quit(); handler = null; if(DEBUG) Log.d(TAG, "cleaned handler"); } else Log.w(TAG, "handler is null"); if(latest != null) { latest.recycle(); latest = null; if(DEBUG) Log.d(TAG, "cleaned latest"); } else Log.w(TAG, "latest was null"); recording = false; } /** * A function for extracting Bitmap from ImageReader. * @param reader An ImageReader * @return PNG compressed bitmap */ @Nullable private Bitmap getBitmap(@NonNull ImageReader reader) { if(DEBUG) Log.d(TAG, "getBitmap"); // Get latest bitmap final Image image = reader.acquireLatestImage(); // Return latest bitmap in case of null result if(image == null) { if(DEBUG) Log.d(TAG, "No new image, return latest one"); return latest; } // Convert new Image object to bitmap Image.Plane[] planes = image.getPlanes(); ByteBuffer buffer = planes[0].getBuffer(); int pixelStride = planes[0].getPixelStride(); int rowStride = planes[0].getRowStride(); int rowPadding = rowStride - pixelStride * width; int bitmapWidth = width + rowPadding / pixelStride; // Create new bitmap object if the current has no matching dimensions if(latest == null || latest.getWidth() != bitmapWidth || latest.getHeight() != height) { if (latest != null) { if(DEBUG) Log.d(TAG, "Recycling latest bitmap"); latest.recycle(); } if(DEBUG) Log.d(TAG, "Creating new bitmap"); latest = Bitmap.createBitmap(bitmapWidth, height, Bitmap.Config.ARGB_8888); } // Load the frame data ro the bitmap object latest.copyPixelsFromBuffer(buffer); if(DEBUG) Log.d(TAG, "Loaded data to bitmap"); image.close(); if(DEBUG) Log.d(TAG, "Closed Image object"); // Compress to PNG ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Bitmap cropped = Bitmap.createBitmap(latest, 0, 0, width, height); cropped.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] compressedBytes = byteArrayOutputStream.toByteArray(); latest.recycle(); latest = BitmapFactory.decodeByteArray(compressedBytes, 0, compressedBytes.length); if(DEBUG) Log.d(TAG, "Compressed frame"); return latest; } private boolean objectsInitialized() { if(DEBUG) Log.d(TAG, "objectsInitialized"); boolean retVal = true; if(handlerThread == null) { Log.w(TAG, "handlerThread is null"); retVal = false; } if(handler == null) { Log.w(TAG, "handler is null"); retVal = false; } if(imageReader == null) { Log.w(TAG, "imageReader is null"); retVal = false; } if(mediaProjection == null) { Log.w(TAG, "mediaProjection is null"); retVal = false; } if(virtualDisplay == null) { Log.w(TAG, "virtualDisplay is null"); retVal = false; } return retVal; } }
import org.apache.commons.lang.StringUtils; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class CommandParser { public CommandParser(){ } public Command parseCommand(String command){ MainCommand mainCommand; switch (getMainCommand(command)) { case HEAD: // Alles in lijn per lijn opsplitsen: String[] commandLines = LineString(command); // De eerste lijn bevat de core info String[] param = commandLines[0].split(" "); String path = param[1]; boolean http1 = http1(param[2]); Map<String, String> info = getInfo(commandLines, 1, commandLines.length); return new CommandHead(path, http1,info); case POST: break; case GET: System.out.println(); case PUT: break; } return null; } /** * Returns false if its a GET or HEAD request, is used to see if we need to continue read the input stream. * @param command * @return */ public boolean continueReading(String command){ if (getMainCommand(command).equals(MainCommand.GET) || getMainCommand(command).equals(MainCommand.HEAD)){ return false; } else { return true; } } private enum MainCommand { HEAD, POST, GET, PUT } /** * Geeft het hoofdcommando terug * @param command in stringvorm * @return */ private MainCommand getMainCommand(String command){ String mainCommand = command.substring(0, command.indexOf(" ")); switch (mainCommand){ case "HEAD": command = command.substring(4, command.length() - 1); //Removes mainCommand System.out.println(command); return MainCommand.HEAD; case "GET": command = command.substring(3, command.length() - 1); //Removes mainCommand return MainCommand.GET; case "POST": command = command.substring(4, command.length() - 1); //Removes mainCommand return MainCommand.POST; case "PUT": command = command.substring(3, command.length() - 1); //Removes mainCommand return MainCommand.PUT; } return null; } /** * * @param command * @return */ private String[] LineString(String command) { String[] lines = command.split("\\r?\\n"); return lines; } private boolean http1(String http1){ if (http1.equalsIgnoreCase("HTTP/1.1")){ return true; } else { return false; } } private String getData(String[] data) { List<String> strList = Arrays.asList(data); return StringUtils.join(strList, "\r\n"); } private Map<String, String> getInfo(String[] info, int startIndex, int endIndex) { info = Arrays.copyOfRange(info, startIndex, endIndex); HashMap<String, String> infoMap = new HashMap<>(); if (info.length > 1) { for (String item : info) { String key = item.substring(0, item.indexOf(": ")).toLowerCase(); String value = item.substring(item.indexOf(": ") + 2); infoMap.put(key, value); } } return infoMap; } }
package com.creativemd.littletiles.common.structure.type.premade.signal; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import com.creativemd.creativecore.common.utils.math.RotationUtils; import com.creativemd.creativecore.common.utils.math.VectorUtils; import com.creativemd.creativecore.common.utils.math.box.AlignedBox; import com.creativemd.creativecore.common.utils.mc.ColorUtils; import com.creativemd.creativecore.common.utils.type.HashMapList; import com.creativemd.creativecore.common.utils.type.Pair; import com.creativemd.littletiles.LittleTiles; import com.creativemd.littletiles.client.render.tile.LittleRenderBox; import com.creativemd.littletiles.common.structure.LittleStructure; import com.creativemd.littletiles.common.structure.attribute.LittleStructureAttribute; import com.creativemd.littletiles.common.structure.exception.CorruptedConnectionException; import com.creativemd.littletiles.common.structure.exception.NotYetConnectedException; import com.creativemd.littletiles.common.structure.registry.LittleStructureType; import com.creativemd.littletiles.common.structure.signal.component.ISignalComponent; import com.creativemd.littletiles.common.structure.signal.component.ISignalStructureBase; import com.creativemd.littletiles.common.structure.signal.component.SignalComponentType; import com.creativemd.littletiles.common.structure.signal.network.SignalNetwork; import com.creativemd.littletiles.common.structure.type.premade.LittleStructurePremade; import com.creativemd.littletiles.common.tile.LittleTile; import com.creativemd.littletiles.common.tile.math.box.LittleAbsoluteBox; import com.creativemd.littletiles.common.tile.math.box.LittleBox; import com.creativemd.littletiles.common.tile.math.vec.LittleVec; import com.creativemd.littletiles.common.tile.parent.IParentTileList; import com.creativemd.littletiles.common.tile.parent.IStructureTileList; import com.creativemd.littletiles.common.tile.preview.LittlePreviews; import com.creativemd.littletiles.common.tileentity.TileEntityLittleTiles; import com.creativemd.littletiles.common.util.grid.LittleGridContext; import com.creativemd.littletiles.common.util.vec.SurroundingBox; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing.Axis; import net.minecraft.util.EnumFacing.AxisDirection; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public abstract class LittleSignalCableBase extends LittleStructurePremade implements ISignalStructureBase { public static final int DEFAULT_CABLE_COLOR = -13619152; private SignalNetwork network; public int color; protected LittleConnectionFace[] faces; public LittleSignalCableBase(LittleStructureType type, IStructureTileList mainBlock) { super(type, mainBlock); this.faces = new LittleConnectionFace[getNumberOfConnections()]; } @Override public boolean compatible(ISignalStructureBase other) { if (ISignalStructureBase.super.compatible(other)) { if (other.getType() == SignalComponentType.TRANSMITTER && this.getType() == SignalComponentType.TRANSMITTER) return other.getColor() == DEFAULT_CABLE_COLOR || this.getColor() == DEFAULT_CABLE_COLOR || getColor() == other.getColor(); return true; } return false; } @Override public boolean hasStructureColor() { return true; } @Override public int getStructureColor() { return color; } @Override public int getDefaultColor() { return DEFAULT_CABLE_COLOR; } @Override public void paint(int color) { this.color = color; } @Override public int getColor() { return color; } @Override public SignalNetwork getNetwork() { return network; } @Override public void setNetwork(SignalNetwork network) { this.network = network; } @Override public World getStructureWorld() { return getWorld(); } @Override protected void loadFromNBTExtra(NBTTagCompound nbt) { int[] result = nbt.getIntArray("faces"); if (result != null && result.length == getNumberOfConnections() * 3) { for (int i = 0; i < faces.length; i++) { int distance = result[i * 3]; if (distance < 0) faces[i] = null; else { faces[i] = new LittleConnectionFace(); faces[i].distance = distance; faces[i].context = LittleGridContext.get(result[i * 3 + 1]); faces[i].oneSidedRenderer = result[i * 3 + 2] == 1; } } } else if (result != null && result.length == getNumberOfConnections() * 2) for (int i = 0; i < faces.length; i++) { int distance = result[i * 2]; if (distance < 0) faces[i] = null; else { faces[i] = new LittleConnectionFace(); faces[i].distance = distance; faces[i].context = LittleGridContext.get(result[i * 2 + 1]); } } if (nbt.hasKey("color")) color = nbt.getInteger("color"); else color = DEFAULT_CABLE_COLOR; } @Override protected void writeToNBTExtraInternal(NBTTagCompound nbt, boolean preview) { super.writeToNBTExtraInternal(nbt, preview); if (!preview && faces != null) { int[] result = new int[getNumberOfConnections() * 3]; for (int i = 0; i < faces.length; i++) { if (faces[i] != null) { result[i * 3] = faces[i].distance; result[i * 3 + 1] = faces[i].context.size; result[i * 3 + 2] = faces[i].oneSidedRenderer ? 1 : 0; } else { result[i * 3] = -1; result[i * 3 + 1] = 0; result[i * 3 + 2] = 0; } } nbt.setIntArray("faces", result); } if (color != -1) nbt.setInteger("color", color); } @Override protected void writeToNBTExtra(NBTTagCompound nbt) {} public abstract EnumFacing getFacing(int index); public abstract int getIndex(EnumFacing facing); @Override public int getBandwidth() { return ((LittleStructureTypeNetwork) type).bandwidth; } public int getNumberOfConnections() { return ((LittleStructureTypeNetwork) type).numberOfConnections; } @Override public boolean connect(EnumFacing facing, ISignalStructureBase base, LittleGridContext context, int distance, boolean oneSidedRenderer) { int index = getIndex(facing); if (faces[index] != null) { if (faces[index].getConnection() == base) return false; faces[index].disconnect(facing); } else faces[index] = new LittleConnectionFace(); faces[index].connect(base, context, distance, oneSidedRenderer); return true; } @Override public void disconnect(EnumFacing facing, ISignalStructureBase base) { int index = getIndex(facing); if (faces[index] != null) { faces[index] = null; updateStructure(); } } @Override public void neighbourChanged() { try { load(); if (getWorld().isRemote) return; LittleAbsoluteBox box = getSurroundingBox().getAbsoluteBox(); boolean changed = false; for (int i = 0; i < faces.length; i++) { EnumFacing facing = getFacing(i); LittleConnectResult result = checkConnection(facing, box); if (result != null) { changed |= this.connect(facing, result.base, result.context, result.distance, result.oneSidedRenderer); changed |= result.base.connect(facing.getOpposite(), this, result.context, result.distance, result.oneSidedRenderer); } else { if (faces[i] != null) { faces[i].disconnect(facing); changed = true; } faces[i] = null; } } if (changed) findNetwork(); } catch (CorruptedConnectionException | NotYetConnectedException e) {} } @Override public Iterator<ISignalStructureBase> connections() { try { load(); return new Iterator<ISignalStructureBase>() { LittleAbsoluteBox box = getSurroundingBox().getAbsoluteBox(); int index = searchForNextIndex(0); int searchForNextIndex(int index) { while (index < faces.length && (faces[index] == null || !faces[index].verifyConnect(getFacing(index), box))) { faces[index] = null; index++; } return index; } @Override public boolean hasNext() { return index < faces.length && faces[index] != null; } @Override public ISignalStructureBase next() { ISignalStructureBase next = faces[index].getConnection(); this.index = searchForNextIndex(index + 1); return next; } }; } catch (CorruptedConnectionException | NotYetConnectedException e) {} return new Iterator<ISignalStructureBase>() { @Override public boolean hasNext() { return false; } @Override public ISignalStructureBase next() { return null; } }; } protected LittleConnectResult checkConnection(World world, LittleAbsoluteBox box, EnumFacing facing, BlockPos pos) throws ConnectionException { try { TileEntity tileEntity = world.getTileEntity(pos); if (tileEntity instanceof TileEntityLittleTiles) { TileEntityLittleTiles te = (TileEntityLittleTiles) tileEntity; LittleTile closest = null; IParentTileList parent = null; int minDistance = 0; for (Pair<IParentTileList, LittleTile> pair : te.allTiles()) { LittleTile tile = pair.value; if (!pair.key.isStructureChild(this)) { int distance = box.getDistanceIfEqualFromOneSide(facing, tile.getBox(), pair.key.getPos(), pair.key.getContext()); if (distance < 0) continue; if (closest == null || minDistance > distance) { closest = tile; parent = pair.key; minDistance = distance; } } } if (closest != null && parent.isStructure()) { LittleStructure structure = parent.getStructure(); if (structure instanceof ISignalStructureBase && ((ISignalStructureBase) structure).compatible(this)) { box = box.createBoxFromFace(facing, minDistance); HashMapList<BlockPos, LittleBox> boxes = box.splitted(); for (Entry<BlockPos, ArrayList<LittleBox>> entry : boxes.entrySet()) { TileEntity toSearchIn = world.getTileEntity(entry.getKey()); if (toSearchIn instanceof TileEntityLittleTiles) { TileEntityLittleTiles parsedSearch = (TileEntityLittleTiles) toSearchIn; LittleBox toCheck = entry.getValue().get(0); try { parsedSearch.convertToAtMinimum(box.getContext()); if (parsedSearch.getContext().size > box.getContext().size) toCheck.convertTo(box.getContext(), parsedSearch.getContext()); if (!parsedSearch.isSpaceForLittleTile(toCheck)) throw new ConnectionException("No space"); } finally { parsedSearch.convertToSmallest(); } } else if (!world.getBlockState(entry.getKey()).getMaterial().isReplaceable()) throw new ConnectionException("Block in the way"); } ISignalStructureBase base = (ISignalStructureBase) structure; if (base.canConnect(facing.getOpposite())) return new LittleConnectResult(base, box.getContext(), minDistance, false); throw new ConnectionException("Side is invalid"); } else if (closest != null) throw new ConnectionException("Tile in the way"); } } else if (tileEntity instanceof ISignalStructureBase && ((ISignalStructureBase) tileEntity).compatible(this)) { Axis axis = facing.getAxis(); boolean positive = facing.getAxisDirection() == AxisDirection.POSITIVE; LittleGridContext context = box.context; int minDistance = positive ? 0 - context.toGrid(VectorUtils.get(axis, box.pos) - VectorUtils.get(axis, pos)) - box.box.getMax(axis) : box.box .getMin(axis) - (context.size - context.toGrid(VectorUtils.get(axis, box.pos) - VectorUtils.get(axis, pos))); box = box.createBoxFromFace(facing, minDistance); HashMapList<BlockPos, LittleBox> boxes = box.splitted(); for (Entry<BlockPos, ArrayList<LittleBox>> entry : boxes.entrySet()) { TileEntity toSearchIn = world.getTileEntity(entry.getKey()); if (toSearchIn instanceof TileEntityLittleTiles) { TileEntityLittleTiles parsedSearch = (TileEntityLittleTiles) toSearchIn; LittleBox toCheck = entry.getValue().get(0); try { parsedSearch.convertToAtMinimum(box.getContext()); if (parsedSearch.getContext().size > box.getContext().size) toCheck.convertTo(box.getContext(), parsedSearch.getContext()); if (!parsedSearch.isSpaceForLittleTile(toCheck)) throw new ConnectionException("No space"); } finally { parsedSearch.convertToSmallest(); } } else if (!world.getBlockState(entry.getKey()).getMaterial().isReplaceable()) throw new ConnectionException("Block in the way"); } ISignalStructureBase base = (ISignalStructureBase) tileEntity; if (base.canConnect(facing.getOpposite())) return new LittleConnectResult(base, box.getContext(), minDistance, true); throw new ConnectionException("Side is invalid"); } } catch (CorruptedConnectionException | NotYetConnectedException e) {} return null; } public LittleConnectResult checkConnection(EnumFacing facing, LittleAbsoluteBox box) { if (!canConnect(facing)) return null; BlockPos pos = box.getMinPos(); Axis axis = facing.getAxis(); boolean positive = facing.getAxisDirection() == AxisDirection.POSITIVE; if (positive) pos = VectorUtils.set(pos, box.getMaxPos(axis), axis); World world = getWorld(); try { if (positive ? box.getMaxGridFrom(axis, pos) < box.getContext().size : box.getMinGridFrom(axis, pos) > 0) { LittleConnectResult result = checkConnection(world, box, facing, pos); if (result != null) return result; } return checkConnection(world, box, facing, pos.offset(facing)); } catch (ConnectionException e) { return null; } } @Override @SideOnly(Side.CLIENT) public void getRenderingCubes(BlockPos pos, BlockRenderLayer layer, List<LittleRenderBox> cubes) { if (layer != (ColorUtils.isTransparent(color) ? BlockRenderLayer.TRANSLUCENT : BlockRenderLayer.SOLID)) return; try { SurroundingBox box = getSurroundingBox(); LittleVec min = box.getMinPosOffset(); LittleVec max = box.getSize(); max.add(min); LittleBox overallBox = new LittleBox(min, max); BlockPos difference = pos.subtract(box.getMinPos()); overallBox.sub(box.getContext().toGrid(difference.getX()), box.getContext().toGrid(difference.getY()), box.getContext().toGrid(difference.getZ())); render(box, overallBox, cubes); } catch (CorruptedConnectionException | NotYetConnectedException e) {} } @SideOnly(Side.CLIENT) public void renderFace(EnumFacing facing, LittleGridContext context, LittleBox renderBox, int distance, Axis axis, Axis one, Axis two, boolean positive, boolean oneSidedRenderer, List<LittleRenderBox> cubes) { if (positive) { renderBox.setMin(axis, renderBox.getMax(axis)); renderBox.setMax(axis, renderBox.getMax(axis) + distance); } else { renderBox.setMax(axis, renderBox.getMin(axis)); renderBox.setMin(axis, renderBox.getMin(axis) - distance); } LittleRenderBox cube = renderBox.getRenderingCube(context, LittleTiles.singleCable, axis.ordinal()); if (!oneSidedRenderer) { if (positive) cube.setMax(axis, cube.getMin(axis) + cube.getSize(axis) / 2); else cube.setMin(axis, cube.getMax(axis) - cube.getSize(axis) / 2); } cube.color = color; cube.keepVU = true; cube.allowOverlap = true; float shrink = 0.18F; float shrinkOne = cube.getSize(one) * shrink; float shrinkTwo = cube.getSize(two) * shrink; cube.setMin(one, cube.getMin(one) + shrinkOne); cube.setMax(one, cube.getMax(one) - shrinkOne); cube.setMin(two, cube.getMin(two) + shrinkTwo); cube.setMax(two, cube.getMax(two) - shrinkTwo); cubes.add(cube); } @SideOnly(Side.CLIENT) public void render(SurroundingBox box, LittleBox overallBox, List<LittleRenderBox> cubes) { for (int i = 0; i < faces.length; i++) { if (faces[i] == null) continue; int distance = faces[i].distance; EnumFacing facing = getFacing(i); Axis axis = facing.getAxis(); Axis one = RotationUtils.getOne(axis); Axis two = RotationUtils.getTwo(axis); boolean positive = facing.getAxisDirection() == AxisDirection.POSITIVE; LittleGridContext context = faces[i].context; LittleBox renderBox = overallBox.copy(); if (box.getContext().size > context.size) { distance *= box.getContext().size / context.size; context = box.getContext(); } else if (context.size > box.getContext().size) renderBox.convertTo(box.getContext(), context); renderFace(facing, context, renderBox, distance, axis, one, two, positive, faces[i].oneSidedRenderer, cubes); } } @Override public void onStructureDestroyed() { if (network != null) if (network.remove(this)) { for (int i = 0; i < faces.length; i++) { if (faces[i] != null) { ISignalStructureBase connection = faces[i].connection; faces[i].disconnect(getFacing(i)); connection.findNetwork(); } } } } @Override public void unload() { super.unload(); if (network != null) network.unload(this); } public class LittleConnectionFace { public ISignalStructureBase connection; public int distance; public LittleGridContext context; public boolean oneSidedRenderer; public LittleConnectionFace() { } public void disconnect(EnumFacing facing) { if (connection != null) connection.disconnect(facing.getOpposite(), LittleSignalCableBase.this); if (hasNetwork()) getNetwork().remove(connection); connection = null; updateStructure(); } public void connect(ISignalStructureBase connection, LittleGridContext context, int distance, boolean oneSidedRenderer) { if (this.connection != null) throw new RuntimeException("Cannot connect until old connection is closed"); this.oneSidedRenderer = oneSidedRenderer; if (hasNetwork()) getNetwork().add(connection); this.connection = connection; this.context = context; this.distance = distance; updateStructure(); } public boolean verifyConnect(EnumFacing facing, LittleAbsoluteBox box) { if (connection != null) return true; LittleConnectResult result = checkConnection(facing, box); if (result != null) { this.connection = result.base; this.context = result.context; this.distance = result.distance; return true; } return false; } public ISignalStructureBase getConnection() { return connection; } } public static class LittleConnectResult { public final ISignalStructureBase base; public final LittleGridContext context; public final int distance; public final boolean oneSidedRenderer; public LittleConnectResult(ISignalStructureBase base, LittleGridContext context, int distance, boolean oneSidedRenderer) { this.base = base; this.context = context; this.distance = distance; this.oneSidedRenderer = oneSidedRenderer; } } public static class ConnectionException extends Exception { public ConnectionException(String msg) { super(msg); } } public static abstract class LittleStructureTypeNetwork extends LittleStructureTypePremade implements ISignalComponent { public final int bandwidth; public final int numberOfConnections; public LittleStructureTypeNetwork(String id, String category, Class<? extends LittleStructure> structureClass, int attribute, String modid, int bandwidth, int numberOfConnections) { super(id, category, structureClass, attribute | LittleStructureAttribute.NEIGHBOR_LISTENER, modid); this.bandwidth = bandwidth; this.numberOfConnections = numberOfConnections; } public int getColor(LittlePreviews previews) { if (previews.structureNBT.hasKey("color")) return previews.structureNBT.getInteger("color"); return DEFAULT_CABLE_COLOR; } @Override @SideOnly(Side.CLIENT) public List<LittleRenderBox> getPositingCubes(World world, BlockPos pos, ItemStack stack) { try { List<LittleRenderBox> cubes = new ArrayList<>(); for (int i = 0; i < 6; i++) { EnumFacing facing = EnumFacing.VALUES[i]; Axis axis = facing.getAxis(); TileEntity tileEntity = world.getTileEntity(pos.offset(facing)); if (tileEntity instanceof TileEntityLittleTiles) { for (LittleStructure structure : ((TileEntityLittleTiles) tileEntity).loadedStructures()) { if (structure instanceof ISignalStructureBase && ((ISignalStructureBase) structure).getBandwidth() == bandwidth && ((ISignalStructureBase) structure) .canConnect(facing.getOpposite())) { LittleRenderBox cube = new LittleRenderBox(new AlignedBox(structure.getSurroundingBox().getAABB() .offset(-tileEntity.getPos().getX(), -tileEntity.getPos().getY(), -tileEntity.getPos().getZ())), null, Blocks.AIR, 0); cube.setMin(axis, 0); cube.setMax(axis, 1); cubes.add(cube); } } } } TileEntity tileEntity = world.getTileEntity(pos); if (tileEntity instanceof TileEntityLittleTiles) { for (LittleStructure structure : ((TileEntityLittleTiles) tileEntity).loadedStructures()) { if (structure instanceof ISignalStructureBase && ((ISignalStructureBase) structure).getBandwidth() == bandwidth) { AxisAlignedBB box = structure.getSurroundingBox().getAABB() .offset(-tileEntity.getPos().getX(), -tileEntity.getPos().getY(), -tileEntity.getPos().getZ()); LittleRenderBox cube; if (((ISignalStructureBase) structure).canConnect(EnumFacing.WEST) || ((ISignalStructureBase) structure).canConnect(EnumFacing.EAST)) { cube = new LittleRenderBox(new AlignedBox(box), null, Blocks.AIR, 0); if (((ISignalStructureBase) structure).canConnect(EnumFacing.WEST)) cube.setMin(Axis.X, 0); if (((ISignalStructureBase) structure).canConnect(EnumFacing.EAST)) cube.setMax(Axis.X, 1); cubes.add(cube); } if (((ISignalStructureBase) structure).canConnect(EnumFacing.DOWN) || ((ISignalStructureBase) structure).canConnect(EnumFacing.UP)) { cube = new LittleRenderBox(new AlignedBox(box), null, Blocks.AIR, 0); if (((ISignalStructureBase) structure).canConnect(EnumFacing.DOWN)) cube.setMin(Axis.Y, 0); if (((ISignalStructureBase) structure).canConnect(EnumFacing.UP)) cube.setMax(Axis.Y, 1); cubes.add(cube); } if (((ISignalStructureBase) structure).canConnect(EnumFacing.NORTH) || ((ISignalStructureBase) structure).canConnect(EnumFacing.SOUTH)) { cube = new LittleRenderBox(new AlignedBox(box), null, Blocks.AIR, 0); if (((ISignalStructureBase) structure).canConnect(EnumFacing.NORTH)) cube.setMin(Axis.Z, 0); if (((ISignalStructureBase) structure).canConnect(EnumFacing.SOUTH)) cube.setMax(Axis.Z, 1); cubes.add(cube); } } } } if (cubes.isEmpty()) return null; for (LittleRenderBox cube : cubes) cube.color = ColorUtils.RGBAToInt(255, 255, 255, 90); return cubes; } catch (CorruptedConnectionException | NotYetConnectedException e) {} return null; } @Override public World getStructureWorld() { return null; } @Override public LittleStructure getStructure() { return null; } } }
package net.unicon.cas.addons.web.support.view.saml; import org.jasig.cas.authentication.principal.SamlService; import org.jasig.cas.authentication.principal.WebApplicationService; import org.jasig.cas.util.CasHTTPSOAP11Encoder; import org.jasig.cas.web.support.SamlArgumentExtractor; import org.jasig.cas.web.view.AbstractCasView; import org.joda.time.DateTime; import org.opensaml.Configuration; import org.opensaml.DefaultBootstrap; import org.opensaml.common.SAMLObject; import org.opensaml.common.SAMLObjectBuilder; import org.opensaml.common.SAMLVersion; import org.opensaml.common.binding.BasicSAMLMessageContext; import org.opensaml.common.impl.SecureRandomIdentifierGenerator; import org.opensaml.saml1.binding.encoding.HTTPSOAP11Encoder; import org.opensaml.saml1.core.Response; import org.opensaml.saml1.core.Status; import org.opensaml.saml1.core.StatusCode; import org.opensaml.saml1.core.StatusMessage; import org.opensaml.ws.transport.http.HttpServletResponseAdapter; import org.opensaml.xml.ConfigurationException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.constraints.NotNull; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import java.lang.reflect.Field; import java.security.NoSuchAlgorithmException; import java.util.Map; /** * This is an extension of the {@link AbstractCasView} that disables SAML namespaces * from the ultimate assertion. The SAML assertion syntax is compliant with CAS server 3.4.x behavior * in response to <code>/samlValidate</code> requests, presumably * for compatibility with CAS-using applications that depended upon details of * the CAS 3.4-style <code>/samlValidate</code> formatting such that they can't cope with the CAS 3.5-style * <code>/samlValidate</code> responses. The namespace parameter is set to {@link XMLConstants#DEFAULT_NS_PREFIX}. * * <p>The implementation closely mimics that of {@link org.jasig.cas.web.view.AbstractSaml10ResponseView} with * small changes to the {@link #newSamlObject(Class)} method. Given the way {@link org.jasig.cas.web.view.AbstractSaml10ResponseView} * is implemented and the finality of {@link org.jasig.cas.web.view.AbstractSaml10ResponseView#newSamlObject(Class)}, * the entire class structure was ported over and tweaks made to SAML object creation.</p> * @see #newSamlObject(Class) * @see Saml10SuccessResponseView * @author Misagh Moayyed * @since 1.7 */ public abstract class NoSamlNamespaceAbstractSaml10ResponseView extends AbstractCasView { private static final String DEFAULT_ELEMENT_NAME_FIELD = "DEFAULT_ELEMENT_NAME"; private static final String DEFAULT_ENCODING = "UTF-8"; private final SamlArgumentExtractor samlArgumentExtractor = new SamlArgumentExtractor(); private final HTTPSOAP11Encoder encoder = new CasHTTPSOAP11Encoder(); private final SecureRandomIdentifierGenerator idGenerator; @NotNull private String encoding = DEFAULT_ENCODING; /** * Sets the character encoding in the HTTP response. * * @param encoding Response character encoding. */ public void setEncoding(final String encoding) { this.encoding = encoding; } static { try { // Initialize OpenSAML default configuration // (only needed once per classloader) DefaultBootstrap.bootstrap(); } catch (final ConfigurationException e) { throw new IllegalStateException("Error initializing OpenSAML library.", e); } } protected NoSamlNamespaceAbstractSaml10ResponseView() { try { this.idGenerator = new SecureRandomIdentifierGenerator(); } catch (final NoSuchAlgorithmException e) { throw new IllegalStateException("Cannot create secure random ID generator for SAML message IDs."); } } protected void renderMergedOutputModel( final Map<String, Object> model, final HttpServletRequest request, final HttpServletResponse response) throws Exception { response.setCharacterEncoding(this.encoding); final WebApplicationService service = this.samlArgumentExtractor.extractService(request); final String serviceId = service != null ? service.getId() : "UNKNOWN"; try { final Response samlResponse = newSamlObject(Response.class); samlResponse.setID(generateId()); samlResponse.setIssueInstant(new DateTime()); samlResponse.setVersion(SAMLVersion.VERSION_11); samlResponse.setRecipient(serviceId); if (service instanceof SamlService) { final SamlService samlService = (SamlService) service; if (samlService.getRequestID() != null) { samlResponse.setInResponseTo(samlService.getRequestID()); } } prepareResponse(samlResponse, model); final BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext(); messageContext.setOutboundMessageTransport(new HttpServletResponseAdapter(response, request.isSecure())); messageContext.setOutboundSAMLMessage(samlResponse); this.encoder.encode(messageContext); } catch (final Exception e) { this.log.error("Error generating SAML response for service {}.", serviceId); throw e; } } /** * Subclasses must implement this method by adding child elements (status, assertion, etc) to * the given empty SAML 1 response message. Impelmenters need not be concerned with error handling. * * @param response SAML 1 response message to be filled. * @param model Spring MVC model map containing data needed to prepare response. */ protected abstract void prepareResponse(Response response, Map<String, Object> model); protected final String generateId() { return this.idGenerator.generateIdentifier(); } protected final <T extends SAMLObject> T newSamlObject(final Class<T> objectType) { final QName qName; try { final Field f = objectType.getField(DEFAULT_ELEMENT_NAME_FIELD); final QName tempQName = (QName) f.get(null); qName = new QName(tempQName.getNamespaceURI(), tempQName.getLocalPart(), XMLConstants.DEFAULT_NS_PREFIX); } catch (final NoSuchFieldException e) { throw new IllegalStateException("Cannot find field " + objectType.getName() + "." + DEFAULT_ELEMENT_NAME_FIELD); } catch (final IllegalAccessException e) { throw new IllegalStateException("Cannot access field " + objectType.getName() + "." + DEFAULT_ELEMENT_NAME_FIELD); } final SAMLObjectBuilder<T> builder = (SAMLObjectBuilder<T>) Configuration.getBuilderFactory().getBuilder(qName); if (builder == null) { throw new IllegalStateException("No SAMLObjectBuilder registered for class " + objectType.getName()); } return objectType.cast(builder.buildObject(qName)); } protected final Status newStatus(final QName codeValue, final String statusMessage) { final Status status = newSamlObject(Status.class); final StatusCode code = newSamlObject(StatusCode.class); code.setValue(codeValue); status.setStatusCode(code); if (statusMessage != null) { final StatusMessage message = newSamlObject(StatusMessage.class); message.setMessage(statusMessage); status.setStatusMessage(message); } return status; } }
package org.wyona.yanel.resources.registration; import org.wyona.yanel.core.util.MailUtil; import org.wyona.yanel.impl.resources.BasicXMLResource; import org.wyona.commons.xml.XMLHelper; import org.wyona.yarep.core.Node; import org.wyona.yarep.core.NodeType; import org.wyona.yarep.util.YarepUtil; import org.wyona.security.core.api.User; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.net.URL; import java.util.Date; import java.util.regex.Pattern; import java.util.regex.Matcher; import javax.mail.internet.InternetAddress; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; /** * A resource to register new users */ public class UserRegistrationResource extends BasicXMLResource { private static Logger log = LogManager.getLogger(UserRegistrationResource.class); static String NAMESPACE = "http: private static String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ"; private static final long DEFAULT_TOTAL_VALID_HRS = 24L; private static final String FROM_ADDRESS_PROP_NAME = "fromEmail"; private static final String ONE_OR_MORE_INPUTS_NOT_VALID = "one-or-more-inputs-not-valid"; private static final String ADMIN_CONFIRMATION_KEY = "admin-confirmation-key"; private static final String ADMINISTRATOR_CONFIRMED = "administrator-confirmed"; protected static final String EMAIL = "email"; protected static final String FIRSTNAME = "firstname"; protected static final String LASTNAME = "lastname"; protected static final String STREET = "street"; protected static final String CITY = "location"; protected static final String ZIP = "zip"; protected static final String GENDER = "gender"; protected static final String SALUTATION = "salutation"; protected static final String PHONE = "phone"; protected static final String COMPANY = "company"; protected static final String PASSWORD = "password"; protected static final String PASSWORD_CONFIRMED = "password2"; /** * @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String) */ @Override protected InputStream getContentXML(String viewId) throws Exception { if (log.isDebugEnabled()) { log.debug("requested viewId: " + viewId); } java.io.ByteArrayOutputStream baout = new java.io.ByteArrayOutputStream(); org.wyona.commons.xml.XMLHelper.writeDocument(generateResponseDocument(), baout); return new java.io.ByteArrayInputStream(baout.toByteArray()); } /** * Check whether email address is valid */ private boolean isEmailValid(String email) { if (email != null && email.length() > 0 && email.indexOf("@") > 0) { return true; } return false; } /** * Check whether password is valid */ private boolean isPasswordValid(String password) { if (password != null && password.length() > 0) { return true; } return false; } /** * Check whether first name is valid * @param firstname First name * @return true when first name is valid and false otherwise */ private boolean isFirstnameValid(String firstname) { if (firstname != null && firstname.length() > 0) { return true; } return false; } /** * Check whether lastname is valid */ private boolean isLastnameValid(String lastname) { if (lastname != null && lastname.length() > 0) { return true; } return false; } /** * Check whether street is valid */ private boolean isStreetValid(String street) { if (street != null && street.length() > 0) { return true; } return false; } /** * Check whether zip code is neither null nor has zero length */ private boolean isZipNotEmpty(String zipCode) { if (zipCode != null && zipCode.length() > 0) { return true; } return false; } /** * Check whether format of zip code is valid * @param zipCode ZIP code * @return valid zip code or null if not valid */ protected String isZipValid(String zipCode) { Pattern pzip = Pattern.compile("[1-9][0-9]{3}"); // INFO: Example of valid ZIP: 1234, Example of not-valid ZIP: 01234 Matcher mzip = pzip.matcher(zipCode); if(mzip.find()) { return mzip.group(0); } else { log.warn("Format of ZIP '" + zipCode + "' is not valid!"); return null; } } /** * Check whether city is valid */ private boolean isCityValid(String city) { if (city != null && city.length() > 0) { return true; } return false; } /** * Check whether phone number is valid */ private boolean isPhoneValid(String phone) { if (phone != null && phone.length() > 0) { return true; } return false; } /** * Check whether gender is valid * @return Either 'm' or 'f' and otherwise null */ private String isGenderValid(String gender) { if (gender != null && gender.length() > 0) { if (gender.equals("male")) { return "m"; } else if (gender.equals("female")) { return "f"; } } log.error("No such gender: " + gender); return null; } /** * Check whether company is valid * @return Either company name or null */ private String isCompanyValid(String company) { if (company != null && company.length() > 0) { return company; } return null; } /** * Check whether fax number is valid * @return Either fax number or null */ private String isFaxValid(String fax) { if (fax != null && fax.length() > 0) { return fax; } return null; } /** * Exists? */ public boolean exists() { return true; } /** * Send email containing a confirmation link * @param userRegBean Bean containing all information about user registration */ private void sendConfirmationLinkEmail(Document doc, UserRegistrationBean userRegBean) { log.info("Do not register user right away, but send an email to '" + userRegBean.getEmail() + "' containing a confirmation link..."); Element rootElement = doc.getDocumentElement(); try { Element element = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "confirmation-link-email")); element.setAttribute("sent-by-yanel", "false"); if (sendNotificationsEnabled()) { if (administratorConfirmationRequired()) { String adminConfirmationKey = java.util.UUID.randomUUID().toString(); setAdminConfirmationKey(userRegBean.getUUID(), adminConfirmationKey); StringBuilder body = new StringBuilder(); body.append("A user with email address '" + userRegBean.getEmail() + "' has sent a registration request."); body.append("\n\nPlease confirm the request by clicking on the following link:"); body.append("\n\n" + getActivationURL(userRegBean) + "&" + ADMIN_CONFIRMATION_KEY + "=" + adminConfirmationKey); body.append("\n\nNote that this confirmation link is valid only for the next " + getHoursValid() + " hours."); MailUtil.send(getResourceConfigProperty(FROM_ADDRESS_PROP_NAME), getResourceConfigProperty("administrator-email"), "[" + getRealm().getName() + "] Confirm User Registration Request", body.toString()); Element adminConfirmationRequiredEl = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "admin-confirmation-required")); } MailUtil.send(getResourceConfigProperty(FROM_ADDRESS_PROP_NAME), userRegBean.getEmail(), getSubject(), getConfirmationEmailBody(getActivationURL(userRegBean))); element.setAttribute("sent-by-yanel", "true"); } element.setAttribute("hours-valid", "" + getHoursValid()); if (getResourceConfigProperty("include-activation-link") != null && getResourceConfigProperty("include-activation-link").equals("true")) { log.warn("Activation link will be part of response! Because of security reasons this should only be done for development or testing environments."); element.setAttribute("activation-link", getActivationURL(userRegBean)); } } catch(Exception e) { log.error(e, e); Element element = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "confirmation-link-email-not-sent")); element.setAttribute(EMAIL, userRegBean.getEmail()); element.setAttribute("exception-message", e.getMessage()); } } /** * Get subject of confirmation email */ private String getSubject() throws Exception { String subject = "Activate User Registration (sent by Yanel)"; if (getResourceConfigProperty("subject") != null) { subject = getResourceConfigProperty("subject"); } return subject; } /** * Get body of confirmation email * @param url Email confirmation link * @return body of confirmation email */ private String getConfirmationEmailBody(String url) throws Exception { String body = null; if (getResourceConfigProperty("email-body-template-path") != null) { Node templateNode = getRealm().getRepository().getNode(getResourceConfigProperty("email-body-template-path")); InputStream in = templateNode.getInputStream(); body = org.apache.commons.io.IOUtils.toString(in); in.close(); } else { String htdocsPath = "rthtdocs:/registration-confirmation-email-template.txt"; org.wyona.yanel.core.source.SourceResolver resolver = new org.wyona.yanel.core.source.SourceResolver(this); javax.xml.transform.Source source = resolver.resolve(htdocsPath, null); InputStream in = ((javax.xml.transform.stream.StreamSource) source).getInputStream(); body = org.apache.commons.io.IOUtils.toString(in); in.close(); } body = body.replace("@CONFIRMATION_LINK@", url); body= body.replace("@VALID_HRS@", "" + getHoursValid()); return body; } /** * Get hours valid */ private long getHoursValid() throws Exception { if (getResourceConfigProperty("hours-valid") != null) { return new Long(getResourceConfigProperty("hours-valid")).longValue(); } return DEFAULT_TOTAL_VALID_HRS; } /** * Register user * @param userRegBean User registration bean containing gender, firstname, etc. */ private void registerUser(Document doc, UserRegistrationBean userRegBean) throws Exception { Element rootElement = doc.getDocumentElement(); try { // INFO: Yanel registration if (getRealm().getIdentityManager().getUserManager().existsAlias(userRegBean.getEmail())) { throw new Exception("Alias '" + userRegBean.getEmail() + "' already exists, hence do not create user: " + userRegBean.getFirstname() + " " + userRegBean.getLastname()); } User user = activateUser(userRegBean); addUserToGroups(user); // TODO: getUserManager().existsAlias(userRegBean.getEmail()) getRealm().getIdentityManager().getUserManager().createAlias(userRegBean.getEmail(), user.getID()); Element ncE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "new-customer-registered")); ncE.setAttributeNS(NAMESPACE, "id", user.getID()); } catch(Exception e) { log.error(e, e); Element fnE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "registration-failed")); fnE.appendChild(doc.createTextNode("" + e.getMessage())); } } /** * Create user profile access policy * @param id User ID */ private void createUserProfileAccessPolicy(String id) throws Exception { // TODO: Also see src/resources/user-mgmt/src/java/org/wyona/yanel/impl/resources/CreateUserResource.java org.wyona.security.core.api.PolicyManager policyManager = getRealm().getPolicyManager(); org.wyona.security.core.api.Policy policy = policyManager.createEmptyPolicy(); org.wyona.security.core.UsecasePolicy usecasePolicy = new org.wyona.security.core.UsecasePolicy("view"); usecasePolicy.addIdentity(new org.wyona.security.core.api.Identity(id, id), true); policy.addUsecasePolicy(usecasePolicy); // TODO: Replace "/users" by org.wyona.yanel.servlet.YanelGlobalResourceTypeMatcher#usersPathPrefix policyManager.setPolicy("/" + getYanel().getReservedPrefix() + "/users/" + id + ".html", policy); } /** * Activate user * @param userRegBean User registration bean containing gender, firstname, etc. * @return activated user */ protected User activateUser(UserRegistrationBean userRegBean) throws Exception { long customerID = new java.util.Date().getTime(); createUserProfileAccessPolicy("" + customerID); // TODO: Use encrypted password User user = getRealm().getIdentityManager().getUserManager().createUser("" + customerID, getName(userRegBean.getFirstname(), userRegBean.getLastname()), userRegBean.getEmail(), userRegBean.getPassword()); // TODO: user.setProperty(GENDER, gender); user.setLanguage(getContentLanguage()); user.save(); // INFO: User needs to be saved persistently before adding an alias, because otherwise one can add an alias though, but the 'link' from the user to the alias will not be created! return user; } /** * Get name of user */ private String getName(String firstname, String lastname) { if (firstname == null && lastname == null) { return null; } else { return firstname + " " + lastname; } } /** * Save registration request persistently * @param urb User registration bean containing E-Mail address of user, etc. * @throws ValidationException if during saving the registration request more validation errors occur, which might be the case if third-party system is involved * @throws Exception if some generic error occurs */ protected void saveRegistrationRequest(UserRegistrationBean urb) throws ValidationException, Exception { Document doc = getRegistrationRequestAsXML(urb); Node node = null; try { String path = getActivationNodePath(urb.getUUID()); if (!getRealm().getRepository().existsNode(path)) { node = YarepUtil.addNodes(getRealm().getRepository(), path, NodeType.RESOURCE); } else { log.error("Node already exists: " + "TODO"); return; } XMLHelper.writeDocument(doc, node.getOutputStream()); } catch(Exception e) { log.error(e, e); } } /** * Generate registration request as XML * @param urb User registration bean containing E-Mail address of user, etc. */ private Document getRegistrationRequestAsXML(UserRegistrationBean urb) { // TODO: What about custom fields?! Document doc = XMLHelper.createDocument(NAMESPACE, "registration-request"); Element rootElem = doc.getDocumentElement(); rootElem.setAttribute("uuid", urb.getUUID()); DateFormat df = new SimpleDateFormat(DATE_FORMAT); rootElem.setAttribute("request-time", df.format(new Date().getTime())); // IMPORTANT TODO: Password needs to be encrypted! Element passwordElem = doc.createElementNS(NAMESPACE, "password"); passwordElem.setAttribute("algorithm", "plaintext"); passwordElem.setTextContent(urb.getPassword()); /* passwordElem.setAttribute("algorithm", "SHA-256"); passwordElem.setTextContent(encrypt(urb.getPassword())); // TODO: What about salt?! */ rootElem.appendChild(passwordElem); Element genderElem = doc.createElementNS(NAMESPACE, GENDER); genderElem.setTextContent(urb.getGender()); rootElem.appendChild(genderElem); Element lastnameElem = doc.createElementNS(NAMESPACE, LASTNAME); lastnameElem.setTextContent(urb.getLastname()); rootElem.appendChild(lastnameElem); Element firstnameElem = doc.createElementNS(NAMESPACE, FIRSTNAME); firstnameElem.setTextContent(urb.getFirstname()); rootElem.appendChild(firstnameElem); Element emailElem = doc.createElementNS(NAMESPACE, EMAIL); emailElem.setTextContent(urb.getEmail()); rootElem.appendChild(emailElem); return doc; } /** * Get activation URL which will be sent via E-Mail (also see YanelServlet#getRequestURLQS(HttpServletRequest, String, boolean)) * @param userRegBean User registration bean containing 'all' information about registration request */ public String getActivationURL(UserRegistrationBean userRegBean) throws Exception { URL url = new URL(request.getRequestURL().toString()); org.wyona.yanel.core.map.Realm realm = getRealm(); if (realm.isProxySet()) { // TODO: Finish proxy settings replacement String proxyHostName = realm.getProxyHostName(); log.debug("Proxy host name: " + proxyHostName); if (proxyHostName != null) { url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile()); } int proxyPort = realm.getProxyPort(); if (proxyPort >= 0) { url = new URL(url.getProtocol(), url.getHost(), proxyPort, url.getFile()); } else { url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile()); } String proxyPrefix = realm.getProxyPrefix(); if (proxyPrefix != null) { url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length())); } } else { log.warn("No proxy set."); } String uuid = userRegBean.getUUID(); return url.toString() + "?uuid=" + uuid; } /** * Get homepage URL which will be sent via E-Mail (also see YanelServlet#getRequestURLQS(HttpServletRequest, String, boolean)) */ public String getHomepageURL() throws Exception { URL url = new URL(request.getRequestURL().toString()); if (realm.isProxySet()) { org.wyona.yanel.core.map.Realm realm = getRealm(); // TODO: Finish proxy settings replacement String proxyHostName = realm.getProxyHostName(); log.debug("Proxy host name: " + proxyHostName); if (proxyHostName != null) { url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile()); } int proxyPort = realm.getProxyPort(); if (proxyPort >= 0) { url = new URL(url.getProtocol(), url.getHost(), proxyPort, url.getFile()); } else { url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile()); } String proxyPrefix = realm.getProxyPrefix(); if (proxyPrefix != null) { url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length())); } } else { log.warn("No proxy set."); } return url.toString().replace("registration", "index"); // TODO: Replace hardcoded registration... } /** * @param doc XML document containing response to client * @param email E-Mail of user which will be used as username/alias */ private void processRegistrationRequest(Document doc, String email) throws Exception { Element rootElement = doc.getDocumentElement(); addSubmittedValuesToResponse(doc); UserRegistrationBean userRegBean = areSubmittedValuesValid(doc, email); if (userRegBean != null) { boolean emailConfigurationRequired = true; if (getResourceConfigProperty("email-confirmation") != null) { emailConfigurationRequired = new Boolean(getResourceConfigProperty("email-confirmation")).booleanValue(); } if (!emailConfigurationRequired) { log.warn("User will be registered without email configuration! Because of security reasons this should only be done for development or testing environments."); registerUser(doc, userRegBean); } else { String uuid = java.util.UUID.randomUUID().toString(); userRegBean.setUUID(uuid); try { saveRegistrationRequest(userRegBean); // TODO: Already create user, because of password encryption, but disable via expire?! sendConfirmationLinkEmail(doc, userRegBean); } catch(ValidationException e) { log.error(e, e); Element invalidE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, ONE_OR_MORE_INPUTS_NOT_VALID)); invalidE.appendChild(doc.createTextNode("Validation errors: " + e.getMessage())); ValidationError[] ves = e.getValidationErrors(); if (ves != null) { for (int i = 0; i < ves.length; i++) { Element validationErrorEl = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "validation-error")); validationErrorEl.setAttributeNS(NAMESPACE, "key", ves[i].getKey()); validationErrorEl.setAttributeNS(NAMESPACE, "value", ves[i].getValue()); validationErrorEl.setAttributeNS(NAMESPACE, "code", ves[i].getErrorCode()); log.warn("Validation error: '" + ves[i].getKey() + "', '" + ves[i].getValue()+ "', '" + ves[i].getErrorCode() + "')"); } } return; } catch(Exception e) { log.error(e, e); Element invalidE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, ONE_OR_MORE_INPUTS_NOT_VALID)); invalidE.appendChild(doc.createTextNode(e.getMessage())); return; } } rootElement.appendChild(doc.createElementNS(NAMESPACE, "all-inputs-valid")); } else { log.warn("One or more inputs are not valid...see returned XML for more details!"); rootElement.appendChild(doc.createElementNS(NAMESPACE, ONE_OR_MORE_INPUTS_NOT_VALID)); } } /** * Check whether administrator needs to confirm registration request */ private boolean administratorConfirmationRequired() throws Exception { if (getResourceConfigProperty("administrator-confirmation-required") != null && getResourceConfigProperty("administrator-confirmation-required").equals("true")) { return true; } return false; } /** * Check whether administrator key matches * @param adminConfirmationKey Confirmation key as UUID * @param uuid UUID of user registration activation request * @param doc Document containing response to administrator trying to confirm registration request * @return true if administrator key matches, otherwise return false */ private boolean adminKeyMatches(String adminConfirmationKey, String uuid, Document doc) throws Exception { String path = getActivationNodePath(uuid); if (getRealm().getRepository().existsNode(path)) { Node registrationRequestNode = getRealm().getRepository().getNode(path); UserRegistrationBean urBean = readRegistrationRequest(registrationRequestNode); if (adminConfirmationKey.equals(urBean.getAdministratorConfirmationKey())) { return true; } else { log.warn("Keys did not match!"); } } else { log.error("No such activation request node: " + path); } return false; } /** * Try to activate user registration * @param uuid UUID of user registration activation request * @param doc Document containing response to user trying to activate account * @return true if user registration activation was successful, otherwise return false if actication failed */ protected boolean activateRegistration(String uuid, Document doc) { try { String path = getActivationNodePath(uuid); if (getRealm().getRepository().existsNode(path)) { Node registrationRequestNode = getRealm().getRepository().getNode(path); UserRegistrationBean urBean = readRegistrationRequest(registrationRequestNode); Element rootElement = doc.getDocumentElement(); if (administratorConfirmationRequired() && !urBean.hasAdministratorConfirmedRegistration()) { log.warn("Administrator has not confirmed registration request yet!"); rootElement.appendChild(doc.createElement("administrator-not-confirmed-yet")); setConfirmedByUser(registrationRequestNode); return false; } else { registerUser(doc, urBean); getRealm().getRepository().getNode(path).delete(); if (doNotifyAdministrator()) { StringBuilder body = new StringBuilder(); body.append("The following user account has been activated:"); body.append("\n\n" + urBean.getEmail()); body.append("\n\nvia " + getHomepageURL()); MailUtil.send(getResourceConfigProperty(FROM_ADDRESS_PROP_NAME), getResourceConfigProperty("administrator-email"), "[" + getRealm().getName() + "] User account has been created", body.toString()); } if (sendNotificationsEnabled() && sendActivationSuccessfulEmail()) { StringBuilder body = new StringBuilder(); body.append("Thank you for your registration."); body.append("\n\nYou have successfully activated your account."); body.append("\n\n" + getHomepageURL()); MailUtil.send(getResourceConfigProperty(FROM_ADDRESS_PROP_NAME), urBean.getEmail(), "[" + getRealm().getName() + "] User Registration Successful", body.toString()); } // TODO: Add gender/salutation Element emailE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, EMAIL)); emailE.appendChild(doc.createTextNode(urBean.getEmail())); Element firstnameE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, FIRSTNAME)); firstnameE.appendChild(doc.createTextNode(urBean.getFirstname())); Element lastnameE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, LASTNAME)); lastnameE.appendChild(doc.createTextNode(urBean.getLastname())); return true; } } else { log.error("No such activation request node: " + path); return false; } } catch(Exception e) { log.error(e, e); return false; } } private String getActivationNodePath(String uuid) { return "/user-registration-requests/" + uuid + ".xml"; } /** * Set attribute that administrator has confirmed registration request * @param requestUUID UUID of registration request */ private void setAdminConfirmed(String requestUUID) throws Exception { String path = getActivationNodePath(requestUUID); if (getRealm().getRepository().existsNode(path)) { Node node = getRealm().getRepository().getNode(path); Document doc = XMLHelper.readDocument(node.getInputStream()); doc.getDocumentElement().setAttribute(ADMINISTRATOR_CONFIRMED, "true"); java.io.OutputStream out = node.getOutputStream(); XMLHelper.writeDocument(doc, out); out.close(); } else { log.warn("No such reqgistration request '" + path + "'!"); } } /** * Add administrator confirmation key to registration request * @param requestUUID UUID of registration request * @param adminKey Administrator confirmation key */ private void setAdminConfirmationKey(String requestUUID, String adminKey) throws Exception { String path = getActivationNodePath(requestUUID); if (getRealm().getRepository().existsNode(path)) { Node node = getRealm().getRepository().getNode(path); Document doc = XMLHelper.readDocument(node.getInputStream()); doc.getDocumentElement().setAttribute(ADMIN_CONFIRMATION_KEY, adminKey); java.io.OutputStream out = node.getOutputStream(); XMLHelper.writeDocument(doc, out); out.close(); } else { log.warn("No such reqgistration request '" + path + "'!"); } } /** * Set flag that user confirmed email address * @param node Repository node containing registration request (firstname, lastname, etc.) */ private void setConfirmedByUser(Node node) throws Exception { Document doc = XMLHelper.readDocument(node.getInputStream()); DateFormat df = new SimpleDateFormat(DATE_FORMAT); doc.getDocumentElement().setAttribute("date-confirmed-by-user", df.format(new Date().getTime())); java.io.OutputStream out = node.getOutputStream(); XMLHelper.writeDocument(doc, out); out.close(); } /** * Read user registration request from repository node * @param node Repository node containing firstname, lastname, etc. */ private UserRegistrationBean readRegistrationRequest(Node node) throws Exception { Document doc = XMLHelper.readDocument(node.getInputStream()); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new UserRegistrationNamespaceContext()); // TODO: Get creation date to determine expire date! String uuid = (String) xpath.evaluate("/ur:registration-request/@uuid", doc, XPathConstants.STRING); String gender = (String) xpath.evaluate("/ur:registration-request/ur:" + GENDER, doc, XPathConstants.STRING); String firstname = (String) xpath.evaluate("/ur:registration-request/ur:" + FIRSTNAME, doc, XPathConstants.STRING); String lastname = (String) xpath.evaluate("/ur:registration-request/ur:" + LASTNAME, doc, XPathConstants.STRING); String email = (String) xpath.evaluate("/ur:registration-request/ur:" + EMAIL, doc, XPathConstants.STRING); String password = (String) xpath.evaluate("/ur:registration-request/ur:password", doc, XPathConstants.STRING); UserRegistrationBean urBean = new UserRegistrationBean(gender, firstname, lastname, email, password, "TODO", "TODO"); urBean.setUUID(uuid); if (doc.getDocumentElement().hasAttribute(ADMINISTRATOR_CONFIRMED)) { if (doc.getDocumentElement().getAttribute(ADMINISTRATOR_CONFIRMED).equals("true")) { urBean.setAdministratorConfirmed(true); } } else { urBean.setAdministratorConfirmed(false); } if (doc.getDocumentElement().hasAttribute(ADMIN_CONFIRMATION_KEY)) { urBean.setAdministratorConfirmationKey(doc.getDocumentElement().getAttribute(ADMIN_CONFIRMATION_KEY)); } return urBean; } /** * Check whether notification emails should be sent (In the case of a "continuous integration" environment one might not want to send emails) */ private boolean sendNotificationsEnabled() { try { String value = getResourceConfigProperty("send-notification-emails"); if (value != null && value.equals("false")) { return false; } } catch(Exception e) { log.error(e, e); } return true; } /** * Check whether an email should be sent when activation was successful */ private boolean sendActivationSuccessfulEmail() { try { String value = getResourceConfigProperty("send-activation-successful-email"); if (value != null && value.equals("false")) { return false; } } catch(Exception e) { log.error(e, e); } return true; } /** * Check whether notification email should be sent to administrator */ private boolean doNotifyAdministrator() { try { String value = getResourceConfigProperty("notify-administrator"); if (value != null && value.equals("true")) { return true; } } catch(Exception e) { log.error(e, e); } return false; } /** * Add registered user to particular groups by default * @param user User to be added to groups */ private void addUserToGroups(User user) throws Exception { String groupsCSV = getResourceConfigProperty("groups"); if (groupsCSV != null) { String[] groupIDs = null; if (groupsCSV.indexOf(",") >= 0) { groupIDs = groupsCSV.split(","); } else { groupIDs = new String[1]; groupIDs[0] = groupsCSV; } for (int i = 0; i < groupIDs.length; i++) { if (getRealm().getIdentityManager().getGroupManager().existsGroup(groupIDs[i])) { log.debug("Add user '" + user.getEmail() + "' to group: " + groupIDs[i]); getRealm().getIdentityManager().getGroupManager().getGroup(groupIDs[i]).addMember(user); } else { log.warn("No such group: " + groupIDs[i]); } } } } /** * Generate document which is used for response * @return XML document containing response */ protected Document generateResponseDocument() throws Exception { Document doc = getEmptyDocument(); Element rootElement = doc.getDocumentElement(); String email = null; if (getEnvironment().getRequest().getParameter(EMAIL) != null) { try { email = new InternetAddress(getEnvironment().getRequest().getParameter(EMAIL)).getAddress(); } catch(Exception e) { Element exceptionEl = (Element) rootElement.appendChild(doc.createElement("invalid-email-address")); exceptionEl.appendChild(doc.createTextNode(e.getMessage())); log.error(e, e); } } String uuid = getEnvironment().getRequest().getParameter("uuid"); String adminConfirmationKey = getEnvironment().getRequest().getParameter(ADMIN_CONFIRMATION_KEY); if (email != null) { // INFO: Somebody tries to register (Please note that the email can also be empty in case somebody forgets to enter an email, but the query string parameter 'email' will exist anyway) processRegistrationRequest(doc, email); } else if (uuid != null) { // INFO: Somebody (user or administrator) tries to activate registration if (adminConfirmationKey != null) { log.warn("DEBUG: Administrator confirms registration request."); if (adminKeyMatches(adminConfirmationKey, uuid, doc)) { setAdminConfirmed(uuid); String path = getActivationNodePath(uuid); if (getRealm().getRepository().existsNode(path)) { Node registrationRequestNode = getRealm().getRepository().getNode(path); UserRegistrationBean urBean = readRegistrationRequest(registrationRequestNode); Element adminConfirmedEl = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "administrator-confirmed")); adminConfirmedEl.setAttribute("user-email", urBean.getEmail()); StringBuilder body = new StringBuilder("Administrator has confirmed your registration request."); body.append("\n\nTo activate your account, you need to click on the following link:"); body.append("\n\n" + getActivationURL(urBean)); // TODO: Calculate remaining time //body.append("\n\nNote that this confirmation link is valid only for the next " + getHoursValid() + " hours."); MailUtil.send(getResourceConfigProperty(FROM_ADDRESS_PROP_NAME), urBean.getEmail(), "[" + getRealm().getName() + "] Administrator has confirmed your registration request", body.toString()); } } else { log.warn("Administrator key did not match!"); } } else { if(activateRegistration(uuid, doc)) { rootElement.appendChild(doc.createElementNS(NAMESPACE, "activation-successful")); } else { rootElement.appendChild(doc.createElementNS(NAMESPACE, "activation-failed")); } } } else { rootElement.appendChild(doc.createElementNS(NAMESPACE, "no-input-yet")); } return doc; } /** * Get empty document to start with */ private Document getEmptyDocument() throws Exception { Document doc = null; try { doc = org.wyona.commons.xml.XMLHelper.createDocument(NAMESPACE, "registration"); } catch (Exception e) { throw new Exception(e.getMessage(), e); } return doc; } /** * Check whether submitted fields are valid * @param doc XML document containing response to client * @param email E-Mail of user which will be used as username/alias * @return user registration information if all fields are valid, otherwise return null (and add errors to DOM document) */ protected UserRegistrationBean areSubmittedValuesValid(Document doc, String email) throws Exception { boolean inputsValid = true; Element rootElement = doc.getDocumentElement(); // INFO: Check email if (!isEmailValid(email)) { Element exception = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "email-not-valid")); inputsValid = false; } else { // TODO: if (getRealm().getIdentityManager().getUserManager().existsUser(email)) { if (getRealm().getIdentityManager().getUserManager().existsAlias(email)) { log.warn("E-Mail '" + email + "' is already used as alias!"); Element exception = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "email-in-use")); inputsValid = false; } Element emailE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, EMAIL)); emailE.appendChild(doc.createTextNode("" + email)); } // INFO: Check password String password = getEnvironment().getRequest().getParameter(PASSWORD); int minPwdLength = getMinPwdLength(); int maxPwdLength = getMaxPwdLength(); if (!isPasswordValid(password) || password.length() < minPwdLength || password.length() > maxPwdLength) { Element exception = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "password-not-valid")); log.error("Password not valid"); inputsValid = false; } // INFO: Check password confirmed String confirmedPassword = getEnvironment().getRequest().getParameter(PASSWORD_CONFIRMED); if (password != null && confirmedPassword != null && !password.equals(confirmedPassword)) { log.warn("Passwords do not match!"); Element exception = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "passwords-do-not-match")); inputsValid = false; } // INFO: Check firstname String firstname = getEnvironment().getRequest().getParameter(FIRSTNAME); if (!isFirstnameValid(firstname)) { Element exception = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "firstname-not-valid")); inputsValid = false; } else { Element fnE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, FIRSTNAME)); fnE.appendChild(doc.createTextNode("" + firstname)); } // INFO: Check lastname String lastname = getEnvironment().getRequest().getParameter(LASTNAME); if (!isLastnameValid(lastname)) { Element exception = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "lastname-not-valid")); inputsValid = false; } else { Element fnE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, LASTNAME)); fnE.appendChild(doc.createTextNode("" + lastname)); } // INFO: Check gender (mandatory) String gender = isGenderValid(getEnvironment().getRequest().getParameter(SALUTATION)); // INFO: Please note that the gender is determined based on the salutation parameter if (gender == null) { Element exception = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "gender-not-valid")); inputsValid = false; } else { Element fnE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, GENDER)); fnE.appendChild(doc.createTextNode("" + gender)); } // INFO: Check company (optional) String company = isCompanyValid(getEnvironment().getRequest().getParameter(COMPANY)); if (company != null && company.length() > 0) { Element fnE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, COMPANY)); fnE.appendChild(doc.createTextNode("" + company)); } // INFO: Check fax (optional) String fax = isFaxValid(getEnvironment().getRequest().getParameter("fax")); if (fax != null && fax.length() > 0) { Element fnE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "fax")); fnE.appendChild(doc.createTextNode("" + fax)); } // INFO: Check street String street = getEnvironment().getRequest().getParameter(STREET); if (!isStreetValid(street)) { Element exception = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "street-not-valid")); log.warn("'" + STREET + "' not valid!"); inputsValid = false; } else { Element fnE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, STREET)); fnE.appendChild(doc.createTextNode("" + street)); } // INFO: Check zip String zip = getEnvironment().getRequest().getParameter(ZIP); if (!isZipNotEmpty(zip)) { log.warn("ZIP '" + zip + "' is not valid!"); Element exception = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "zip-not-valid")); inputsValid = false; } else { log.debug("Submitted ZIP: " + zip); String formattedZip = isZipValid(zip); if (formattedZip != null) { log.debug("Formatted ZIP: " + formattedZip); if (!zip.equals(formattedZip)) { log.warn("Submitted zip code '" + zip + "' has been modified: " + formattedZip); } Element fnE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, ZIP)); fnE.appendChild(doc.createTextNode(formattedZip)); } else { log.warn("Format of ZIP '" + zip + "' is not valid!"); Element exception = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "zip-not-valid")); inputsValid = false; } } // INFO: Check city String city = getEnvironment().getRequest().getParameter(CITY); if (!isCityValid(city)) { Element exception = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "city-not-valid")); log.warn("'" + CITY + "' not valid!"); inputsValid = false; } else { Element fnE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "city")); fnE.appendChild(doc.createTextNode("" + city)); } // INFO: Check phone String phone = getEnvironment().getRequest().getParameter(PHONE); if (!isPhoneValid(phone)) { Element exception = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "phone-not-valid")); log.warn("'" + PHONE + "' not valid!"); inputsValid = false; } else { Element fnE = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, PHONE)); fnE.appendChild(doc.createTextNode("" + phone)); } if (inputsValid) { UserRegistrationBean userRegBean = new UserRegistrationBean(gender, firstname, lastname, email, password, city, phone); userRegBean.setStreetName(street); userRegBean.setZipCode(zip); return userRegBean; } else { return null; } } /** * Get minimum password length */ private int getMinPwdLength() throws Exception { String minPwdLengthSt = getResourceConfigProperty("min-password-length"); if (minPwdLengthSt != null) { return new Integer(minPwdLengthSt).intValue(); } int DEFAULT_MIN_PWD_LENGTH = 5; log.warn("No minimal password length configured, hence use default value: " + DEFAULT_MIN_PWD_LENGTH); return DEFAULT_MIN_PWD_LENGTH; } /** * Get maximum password length */ private int getMaxPwdLength() throws Exception { String maxPwdLengthSt = getResourceConfigProperty("max-password-length"); if (maxPwdLengthSt != null) { return new Integer(maxPwdLengthSt).intValue(); } int DEFAULT_MAX_PWD_LENGTH = 15; log.warn("No maximum password length configured, hence use default value: " + DEFAULT_MAX_PWD_LENGTH); return DEFAULT_MAX_PWD_LENGTH; } /** * Add all submitted input parameters to response document such that they can be used for further processing (if necessary) * @param doc XML document containing response to client * @return DOM element containing submitted inputs */ protected Element addSubmittedValuesToResponse(Document doc) throws Exception { Element submittedElem = (Element) doc.getDocumentElement().appendChild(doc.createElement("submitted-inputs")); Element emailElem = doc.createElementNS(NAMESPACE, EMAIL); emailElem.setTextContent(new InternetAddress(getEnvironment().getRequest().getParameter(EMAIL)).getAddress()); submittedElem.appendChild(emailElem); Element lastnameElem = doc.createElementNS(NAMESPACE, LASTNAME); lastnameElem.setTextContent(getEnvironment().getRequest().getParameter(LASTNAME)); submittedElem.appendChild(lastnameElem); Element firstnameElem = doc.createElementNS(NAMESPACE, FIRSTNAME); firstnameElem.setTextContent(getEnvironment().getRequest().getParameter(FIRSTNAME)); submittedElem.appendChild(firstnameElem); Element streetElem = doc.createElementNS(NAMESPACE, STREET); streetElem.setTextContent(getEnvironment().getRequest().getParameter(STREET)); submittedElem.appendChild(streetElem); Element cityElem = doc.createElementNS(NAMESPACE, CITY); cityElem.setTextContent(getEnvironment().getRequest().getParameter(CITY)); submittedElem.appendChild(cityElem); Element zipElem = doc.createElementNS(NAMESPACE, ZIP); zipElem.setTextContent(getEnvironment().getRequest().getParameter(ZIP)); submittedElem.appendChild(zipElem); Element companyElem = doc.createElementNS(NAMESPACE, COMPANY); companyElem.setTextContent(getEnvironment().getRequest().getParameter(COMPANY)); submittedElem.appendChild(companyElem); Element phoneElem = doc.createElementNS(NAMESPACE, PHONE); phoneElem.setTextContent(getEnvironment().getRequest().getParameter(PHONE)); submittedElem.appendChild(phoneElem); Element genderElem = doc.createElementNS(NAMESPACE, GENDER); genderElem.setTextContent(getEnvironment().getRequest().getParameter(SALUTATION)); submittedElem.appendChild(genderElem); return submittedElem; } } class UserRegistrationNamespaceContext implements javax.xml.namespace.NamespaceContext { public String getNamespaceURI(String prefix) { if (prefix == null) { throw new IllegalArgumentException("No prefix provided!"); } else if (prefix.equals("ur")) { return UserRegistrationResource.NAMESPACE; } else if (prefix.equals("xhtml")) { return "http: } else if (prefix.equals("dc")) { return "http://purl.org/dc/elements/1.1/"; } else if (prefix.equals("dcterms")) { return "http://purl.org/dc/terms/"; } else { return javax.xml.XMLConstants.NULL_NS_URI; } } public String getPrefix(String namespaceURI) { // Not needed in this context. throw new UnsupportedOperationException(); } public java.util.Iterator getPrefixes(String namespaceURI) { // Not needed in this context. throw new UnsupportedOperationException(); } }
package com.grayben.riskExtractor.htmlScorer.partScorers.tagScorers; import org.jsoup.parser.Tag; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.lang.Object; import java.util.HashMap; import java.util.Map; import static com.grayben.riskExtractor.htmlScorer.partScorers.elementScorers.TestHelper.*; import static org.junit.Assert.*; @RunWith(MockitoJUnitRunner.class) public class TagSegmentationScorerTest extends MapScorerTest<Tag> { TagSegmentationScorer tagSegmentationScorerSUT; public Tag tagToBeScoredMock; @Before public void setUp() throws Exception { this.tagSegmentationScorerSUT = new TagSegmentationScorer( TagSegmentationScorer.defaultMap() ); this.tagToBeScoredMock = stubTag("some-name-to-use"); super.setArgumentToBeScoredMock(this.tagToBeScoredMock); super.setMapScorerSUT(this.tagSegmentationScorerSUT); super.setUp(); } @After public void tearDown() throws Exception { super.tearDown(); } @Override @Test public void test_ScoreReturnsInteger_WhenArgumentIsNotEmpty() throws Exception { Object returned = tagSegmentationScorerSUT.score(tagToBeScoredMock); assertEquals(Integer.class, returned.getClass()); } @Override @Test public void test_ScoreGivesExpectedResult_WhenSimpleInput() throws Exception { Map<Tag, Integer> tagScoresMap = new HashMap<>(); tagScoresMap.put(Tag.valueOf("table"), 1); tagScoresMap.put(Tag.valueOf("li"), 1); tagScoresMap.put(Tag.valueOf("tr"), 2); tagScoresMap.put(Tag.valueOf("th"), 1); tagSegmentationScorerSUT = new TagSegmentationScorer(tagScoresMap); Map<Tag, Integer> expectedResults = new HashMap<>(tagScoresMap); assert expectedResults.put(Tag.valueOf("foo"), 0) == null; assert expectedResults.put(Tag.valueOf("bar"), 0) == null; assert expectedResults.put(Tag.valueOf("baz"), 0) == null; super.testHelper_ScoreGivesExpectedResult_WhenSimpleInput( tagSegmentationScorerSUT, expectedResults); } @Override @Test public void test_InitThrowsNullPointerException_WhenMapParamIsNull() throws Exception { thrown.expect(NullPointerException.class); new TagSegmentationScorer(null); } @Test public void test_ScoreThrowsIllegalArgumentException_WhenEmptyInput() throws Exception { Mockito.when(tagToBeScoredMock.isEmpty()) .thenReturn(true); thrown.expect(IllegalArgumentException.class); tagSegmentationScorerSUT.score(tagToBeScoredMock); } @Test public void test_ScoreThrowsIllegalArgumentException_WhenTagHasNoName() throws Exception { Mockito.when(tagToBeScoredMock.isEmpty()) .thenReturn(false); Mockito.when(tagToBeScoredMock.getName()) .thenReturn(""); thrown.expect(IllegalArgumentException.class); tagSegmentationScorerSUT.score(tagToBeScoredMock); } }