answer
stringlengths
17
10.2M
package io.grpc.netty; import static io.grpc.netty.GrpcSslContexts.HTTP2_VERSIONS; import com.google.common.base.Preconditions; import io.grpc.Status; import io.grpc.internal.GrpcUtil; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpClientUpgradeHandler; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http2.Http2ClientUpgradeCodec; import io.netty.handler.codec.http2.Http2ConnectionHandler; import io.netty.handler.ssl.OpenSsl; import io.netty.handler.ssl.OpenSslEngine; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; import io.netty.util.ByteString; import java.net.URI; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLParameters; /** * Common {@link ProtocolNegotiator}s used by gRPC. */ public final class ProtocolNegotiators { private static final Logger log = Logger.getLogger(ProtocolNegotiators.class.getName()); private ProtocolNegotiators() { } /** * Create a TLS handler for HTTP/2 capable of using ALPN/NPN. */ public static ChannelHandler serverTls(SSLEngine sslEngine, final ChannelHandler grpcHandler) { Preconditions.checkNotNull(sslEngine, "sslEngine"); final SslHandler sslHandler = new SslHandler(sslEngine, false); return new ChannelInboundHandlerAdapter() { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { super.handlerAdded(ctx); ctx.pipeline().addFirst(sslHandler); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { fail(ctx, cause); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; if (handshakeEvent.isSuccess()) { if (HTTP2_VERSIONS.contains(sslHandler(ctx).applicationProtocol())) { // Successfully negotiated the protocol. Replace this handler with // the GRPC handler. ctx.pipeline().replace(this, null, grpcHandler); } else { fail(ctx, new Exception( "Failed protocol negotiation: Unable to find compatible protocol.")); } } else { fail(ctx, handshakeEvent.cause()); } } super.userEventTriggered(ctx, evt); } private void fail(ChannelHandlerContext ctx, Throwable exception) { logSslEngineDetails(Level.FINE, ctx, "TLS negotiation failed for new client.", exception); ctx.close(); } private SslHandler sslHandler(ChannelHandlerContext ctx) { return ctx.pipeline().get(SslHandler.class); } }; } /** * Returns a {@link ProtocolNegotiator} that ensures the pipeline is set up so that TLS will * be negotiated, the {@code handler} is added and writes to the {@link io.netty.channel.Channel} * may happen immediately, even before the TLS Handshake is complete. */ public static ProtocolNegotiator tls(final SslContext sslContext, String authority) { Preconditions.checkNotNull(sslContext, "sslContext"); final URI uri = GrpcUtil.authorityToUri(Preconditions.checkNotNull(authority, "authority")); return new ProtocolNegotiator() { @Override public Handler newHandler(Http2ConnectionHandler handler) { ChannelHandler sslBootstrap = new ChannelHandlerAdapter() { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { SSLEngine sslEngine = sslContext.newEngine(ctx.alloc(), uri.getHost(), uri.getPort()); SSLParameters sslParams = new SSLParameters(); sslParams.setEndpointIdentificationAlgorithm("HTTPS"); sslEngine.setSSLParameters(sslParams); ctx.pipeline().replace(this, null, new SslHandler(sslEngine, false)); } }; return new BufferUntilTlsNegotiatedHandler(sslBootstrap, handler); } }; } /** * Returns a {@link ProtocolNegotiator} used for upgrading to HTTP/2 from HTTP/1.x. */ public static ProtocolNegotiator plaintextUpgrade() { return new ProtocolNegotiator() { @Override public Handler newHandler(Http2ConnectionHandler handler) { // Register the plaintext upgrader Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(handler); HttpClientCodec httpClientCodec = new HttpClientCodec(); final HttpClientUpgradeHandler upgrader = new HttpClientUpgradeHandler(httpClientCodec, upgradeCodec, 1000); return new BufferingHttp2UpgradeHandler(upgrader); } }; } /** * Returns a {@link ChannelHandler} that ensures that the {@code handler} is added to the * pipeline writes to the {@link io.netty.channel.Channel} may happen immediately, even before it * is active. */ public static ProtocolNegotiator plaintext() { return new ProtocolNegotiator() { @Override public Handler newHandler(Http2ConnectionHandler handler) { return new BufferUntilChannelActiveHandler(handler); } }; } private static RuntimeException unavailableException(String msg) { return Status.UNAVAILABLE.withDescription(msg).asRuntimeException(); } private static void logSslEngineDetails(Level level, ChannelHandlerContext ctx, String msg, @Nullable Throwable t) { if (!log.isLoggable(level)) { return; } SslHandler sslHandler = ctx.pipeline().get(SslHandler.class); SSLEngine engine = sslHandler.engine(); StringBuilder builder = new StringBuilder(msg); builder.append("\nSSLEngine Details: [\n"); if (engine instanceof OpenSslEngine) { builder.append(" OpenSSL, "); builder.append("Version: 0x").append(Integer.toHexString(OpenSsl.version())); builder.append(" (").append(OpenSsl.versionString()).append("), "); builder.append("ALPN supported: ").append(OpenSsl.isAlpnSupported()); } else if (JettyTlsUtil.isJettyAlpnConfigured()) { builder.append(" Jetty ALPN"); } else if (JettyTlsUtil.isJettyNpnConfigured()) { builder.append(" Jetty NPN"); } builder.append("\n TLS Protocol: "); builder.append(engine.getSession().getProtocol()); builder.append("\n Application Protocol: "); builder.append(sslHandler.applicationProtocol()); builder.append("\n Need Client Auth: " ); builder.append(engine.getNeedClientAuth()); builder.append("\n Want Client Auth: "); builder.append(engine.getWantClientAuth()); builder.append("\n Supported protocols="); builder.append(Arrays.toString(engine.getSupportedProtocols())); builder.append("\n Enabled protocols="); builder.append(Arrays.toString(engine.getEnabledProtocols())); builder.append("\n Supported ciphers="); builder.append(Arrays.toString(engine.getSupportedCipherSuites())); builder.append("\n Enabled ciphers="); builder.append(Arrays.toString(engine.getEnabledCipherSuites())); builder.append("\n]"); log.log(level, builder.toString(), t); } /** * Buffers all writes until either {@link #writeBufferedAndRemove(ChannelHandlerContext)} or * {@link #fail(ChannelHandlerContext, Throwable)} is called. This handler allows us to * write to a {@link io.netty.channel.Channel} before we are allowed to write to it officially * i.e. before it's active or the TLS Handshake is complete. */ public abstract static class AbstractBufferingHandler extends ChannelDuplexHandler { private ChannelHandler[] handlers; private Queue<ChannelWrite> bufferedWrites = new ArrayDeque<ChannelWrite>(); private boolean writing; private boolean flushRequested; private Throwable failCause; /** * @param handlers the ChannelHandlers are added to the pipeline on channelRegistered and * before this handler. */ AbstractBufferingHandler(ChannelHandler... handlers) { this.handlers = handlers; } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { /** * This check is necessary as a channel may be registered with different event loops during it * lifetime and we only want to configure it once. */ if (handlers != null) { ctx.pipeline().addFirst(handlers); handlers = null; } super.channelRegistered(ctx); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { fail(ctx, cause); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { fail(ctx, unavailableException("Connection broken while performing protocol negotiation")); super.channelInactive(ctx); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { /** * This check handles a race condition between Channel.write (in the calling thread) and the * removal of this handler (in the event loop thread). * The problem occurs in e.g. this sequence: * 1) [caller thread] The write method identifies the context for this handler * 2) [event loop] This handler removes itself from the pipeline * 3) [caller thread] The write method delegates to the invoker to call the write method in * the event loop thread. When this happens, we identify that this handler has been * removed with "bufferedWrites == null". */ if (failCause != null) { promise.setFailure(failCause); } else if (bufferedWrites == null) { super.write(ctx, msg, promise); } else { bufferedWrites.add(new ChannelWrite(msg, promise)); } } @Override public void flush(ChannelHandlerContext ctx) { /** * Swallowing any flushes is not only an optimization but also required * for the SslHandler to work correctly. If the SslHandler receives multiple * flushes while the handshake is still ongoing, then the handshake "randomly" * times out. Not sure at this point why this is happening. Doing a single flush * seems to work but multiple flushes don't ... */ if (bufferedWrites == null) { ctx.flush(); } else { flushRequested = true; } } @Override public void close(ChannelHandlerContext ctx, ChannelPromise future) throws Exception { fail(ctx, unavailableException("Channel closed while performing protocol negotiation")); } protected final void fail(ChannelHandlerContext ctx, Throwable cause) { if (failCause == null) { failCause = cause; } if (bufferedWrites != null) { while (!bufferedWrites.isEmpty()) { ChannelWrite write = bufferedWrites.poll(); write.promise.setFailure(cause); } bufferedWrites = null; } /** * In case something goes wrong ensure that the channel gets closed as the * NettyClientTransport relies on the channel's close future to get completed. */ ctx.close(); } protected final void writeBufferedAndRemove(ChannelHandlerContext ctx) { if (!ctx.channel().isActive() || writing) { return; } // Make sure that method can't be reentered, so that the ordering // in the queue can't be messed up. writing = true; while (!bufferedWrites.isEmpty()) { ChannelWrite write = bufferedWrites.poll(); ctx.write(write.msg, write.promise); } assert bufferedWrites.isEmpty(); bufferedWrites = null; if (flushRequested) { ctx.flush(); } // Removal has to happen last as the above writes will likely trigger // new writes that have to be added to the end of queue in order to not // mess up the ordering. ctx.pipeline().remove(this); } private static class ChannelWrite { Object msg; ChannelPromise promise; ChannelWrite(Object msg, ChannelPromise promise) { this.msg = msg; this.promise = promise; } } } /** * Buffers all writes until the TLS Handshake is complete. */ private static class BufferUntilTlsNegotiatedHandler extends AbstractBufferingHandler implements ProtocolNegotiator.Handler { BufferUntilTlsNegotiatedHandler(ChannelHandler... handlers) { super(handlers); } @Override public ByteString scheme() { return Utils.HTTPS; } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; if (handshakeEvent.isSuccess()) { SslHandler handler = ctx.pipeline().get(SslHandler.class); if (HTTP2_VERSIONS.contains(handler.applicationProtocol())) { // Successfully negotiated the protocol. logSslEngineDetails(Level.FINER, ctx, "TLS negotiation succeeded.", null); writeBufferedAndRemove(ctx); } else { Exception ex = new Exception( "Failed ALPN negotiation: Unable to find compatible protocol."); logSslEngineDetails(Level.FINE, ctx, "TLS negotiation failed.", ex); fail(ctx, ex); } } else { fail(ctx, handshakeEvent.cause()); } } super.userEventTriggered(ctx, evt); } } /** * Buffers all writes until the {@link io.netty.channel.Channel} is active. */ private static class BufferUntilChannelActiveHandler extends AbstractBufferingHandler implements ProtocolNegotiator.Handler { BufferUntilChannelActiveHandler(ChannelHandler... handlers) { super(handlers); } @Override public ByteString scheme() { return Utils.HTTP; } @Override public void handlerAdded(ChannelHandlerContext ctx) { writeBufferedAndRemove(ctx); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { writeBufferedAndRemove(ctx); super.channelActive(ctx); } } /** * Buffers all writes until the HTTP to HTTP/2 upgrade is complete. */ private static class BufferingHttp2UpgradeHandler extends AbstractBufferingHandler implements ProtocolNegotiator.Handler { BufferingHttp2UpgradeHandler(ChannelHandler... handlers) { super(handlers); } @Override public ByteString scheme() { return Utils.HTTP; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // Trigger the HTTP/1.1 plaintext upgrade protocol by issuing an HTTP request // which causes the upgrade headers to be added DefaultHttpRequest upgradeTrigger = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); ctx.writeAndFlush(upgradeTrigger); super.channelActive(ctx); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt == HttpClientUpgradeHandler.UpgradeEvent.UPGRADE_SUCCESSFUL) { writeBufferedAndRemove(ctx); } else if (evt == HttpClientUpgradeHandler.UpgradeEvent.UPGRADE_REJECTED) { fail(ctx, unavailableException("HTTP/2 upgrade rejected")); } super.userEventTriggered(ctx, evt); } } }
package org.jboss.modules; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.SecureClassLoader; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; /** * @author <a href="mailto:jbailey@redhat.com">John Bailey</a> * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class ModuleClassLoader extends SecureClassLoader { private static final boolean debugDefines; static { try { final Method method = ClassLoader.class.getMethod("registerAsParallelCapable"); method.invoke(null); } catch (Exception e) { // ignore } debugDefines = AccessController.doPrivileged(new PrivilegedAction<Boolean>() { public Boolean run() { return Boolean.valueOf(System.getProperty("jboss.modules.debug.defineClass", "false")); } }).booleanValue(); } private final Module module; private final Set<Module.Flag> flags; private final Map<String, Class<?>> cache = new HashMap<String, Class<?>>(256); ModuleClassLoader(final Module module, final Set<Module.Flag> flags, final AssertionSetting setting) { this.module = module; this.flags = flags; if (setting != AssertionSetting.INHERIT) { setDefaultAssertionStatus(setting == AssertionSetting.ENABLED); } } @Override public Class<?> loadClass(final String name) throws ClassNotFoundException { return loadClass(name, false); } @Override protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException { Class<?> loadedClass = loadClassInternal(className); if (resolve) resolveClass(loadedClass); return loadedClass; } protected Class<?> loadClassInternal(String className) throws ClassNotFoundException { return performLoadClass(className, false); } protected Class<?> loadClassExternal(String className) throws ClassNotFoundException { return performLoadClass(className, true); } private Class<?> performLoadClass(String className, boolean exportsOnly) throws ClassNotFoundException { if (className == null) { throw new IllegalArgumentException("name is null"); } if (className.startsWith("java.")) { // always delegate to system return findSystemClass(className); } if (Thread.holdsLock(this) && Thread.currentThread() != LoaderThreadHolder.LOADER_THREAD) { // Only the classloader thread may take this lock; use a condition to relinquish it final LoadRequest req = new LoadRequest(className, exportsOnly, this); final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; synchronized (LoaderThreadHolder.REQUEST_QUEUE) { queue.add(req); queue.notify(); } boolean intr = false; try { while (!req.done) try { wait(); } catch (InterruptedException e) { intr = true; } } finally { if (intr) Thread.currentThread().interrupt(); } return req.result; } else { // no deadlock risk! Either the lock isn't held, or we're inside the class loader thread. // Check if we have already loaded it.. Class<?> loadedClass; final Map<String, Class<?>> cache = this.cache; synchronized (this) { loadedClass = cache.get(className); } if (loadedClass != null) { return loadedClass; } final Set<Module.Flag> flags = this.flags; if (flags.contains(Module.Flag.CHILD_FIRST)) { loadedClass = loadClassLocal(className); if (loadedClass == null) { loadedClass = module.getImportedClass(className, exportsOnly); } if (loadedClass == null) { loadedClass = findSystemClass(className); } } else { loadedClass = module.getImportedClass(className, exportsOnly); if (loadedClass == null) try { loadedClass = findSystemClass(className); } catch (ClassNotFoundException e) { } if (loadedClass == null) { loadedClass = loadClassLocal(className); } if (loadedClass == null) { throw new ClassNotFoundException(className); } } synchronized (this) { cache.put(className, loadedClass); } return loadedClass; } } private Class<?> loadClassLocal(String name) throws ClassNotFoundException { // Check to see if we can load it ClassSpec classSpec = null; try { classSpec = module.getLocalClassSpec(name); } catch (IOException e) { throw new ClassNotFoundException(name, e); } catch (RuntimeException e) { System.err.print("Unexpected runtime exception in module loader: "); e.printStackTrace(System.err); throw new ClassNotFoundException(name, e); } catch (Error e) { System.err.print("Unexpected error in module loader: "); e.printStackTrace(System.err); throw new ClassNotFoundException(name, e); } if (classSpec == null) return null; return defineClass(name, classSpec); } private Class<?> defineClass(final String name, final ClassSpec classSpec) { // Ensure that the package is loaded final int lastIdx = name.lastIndexOf('.'); if (lastIdx != -1) { // there's a package name; get the Package for it final String packageName = name.substring(0, lastIdx); final Package pkg = getPackage(packageName); if (pkg != null) { // Package is defined already if (pkg.isSealed() && ! pkg.isSealed(classSpec.getCodeSource().getLocation())) { // use the same message as the JDK throw new SecurityException("sealing violation: package " + packageName + " is sealed"); } } else { final PackageSpec spec; try { spec = getModule().getLocalPackageSpec(name); definePackage(packageName, spec); } catch (IOException e) { definePackage(packageName, null); } } } final Class<?> newClass; try { final byte[] bytes = classSpec.getBytes(); newClass = defineClass(name, bytes, 0, bytes.length, classSpec.getCodeSource()); } catch (Error e) { if (debugDefines) System.err.println("Failed to define class '" + name + "': " + e); throw e; } catch (RuntimeException e) { if (debugDefines) System.err.println("Failed to define class '" + name + "': " + e); throw e; } final AssertionSetting setting = classSpec.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setClassAssertionStatus(name, setting == AssertionSetting.ENABLED); } return newClass; } private Package definePackage(final String name, final PackageSpec spec) { if (spec == null) { return definePackage(name, null, null, null, null, null, null, null); } else { final Package pkg = definePackage(name, spec.getSpecTitle(), spec.getSpecVersion(), spec.getSpecVendor(), spec.getImplTitle(), spec.getImplVersion(), spec.getImplVendor(), spec.getSealBase()); final AssertionSetting setting = spec.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setPackageAssertionStatus(name, setting == AssertionSetting.ENABLED); } return pkg; } } @Override protected Package getPackage(String name) { return super.getPackage(name); } @Override protected String findLibrary(final String libname) { return module.getLocalLibrary(libname); } @Override public URL getResource(String name) { final Resource resource = module.getExportedResource(name); return resource == null ? null : resource.getURL(); } @Override public Enumeration<URL> getResources(String name) throws IOException { final Iterable<Resource> resources = module.getExportedResources(name); final Iterator<Resource> iterator = resources.iterator(); return new Enumeration<URL>() { @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public URL nextElement() { return iterator.next().getURL(); } }; } @Override public InputStream getResourceAsStream(final String name) { try { final Resource resource = module.getExportedResource(name); return resource == null ? null : resource.openStream(); } catch (IOException e) { return null; } } /** * Get the module for this class loader. * * @return the module */ public Module getModule() { return module; } public String toString() { return "ClassLoader for " + module; } public static ModuleClassLoader forModule(ModuleIdentifier identifier) throws ModuleLoadException { return Module.getModule(identifier).getClassLoader(); } public static ModuleClassLoader forModuleName(String identifier) throws ModuleLoadException { return forModule(ModuleIdentifier.fromString(identifier)); } public static ModuleClassLoader createAggregate(String identifier, List<String> dependencies) throws ModuleLoadException { List<ModuleIdentifier> depModuleIdentifiers = new ArrayList<ModuleIdentifier>(dependencies.size()); for(String dependencySpec : dependencies) { depModuleIdentifiers.add(ModuleIdentifier.fromString(dependencySpec)); } return InitialModuleLoader.INSTANCE.createAggregate(ModuleIdentifier.fromString(identifier), depModuleIdentifiers).getClassLoader(); } private static final class LoaderThreadHolder { private static final Thread LOADER_THREAD; private static final Queue<LoadRequest> REQUEST_QUEUE = new ArrayDeque<LoadRequest>(); static { Thread thr = new LoaderThread(); thr.setName("ModuleClassLoader Thread"); // This thread will always run as long as the VM is alive. thr.setDaemon(true); thr.start(); LOADER_THREAD = thr; } private LoaderThreadHolder() { } } static class LoadRequest { private final String className; private final ModuleClassLoader requester; private Class<?> result; private boolean exportsOnly; private boolean done; public LoadRequest(final String className, final boolean exportsOnly, final ModuleClassLoader requester) { this.className = className; this.exportsOnly = exportsOnly; this.requester = requester; } } static class LoaderThread extends Thread { @Override public void interrupt() { // no interruption } @Override public void run() { /* This resolves a know deadlock that can occur if one thread is in the process of defining a package as part of defining a class, and another thread is defining the system package that can result in loading a class. One holds the Package.pkgs lock and one holds the Classloader lock. */ Package.getPackages(); final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; for (; ;) { try { LoadRequest request; synchronized (queue) { while ((request = queue.poll()) == null) { queue.wait(); } } final ModuleClassLoader loader = request.requester; Class<?> result = null; synchronized (loader) { try { result = loader.performLoadClass(request.className, request.exportsOnly); } finally { // no matter what, the requester MUST be notified request.result = result; request.done = true; loader.notifyAll(); } } } catch (Throwable t) { // ignore } } } } }
package imj2.tools; import static java.lang.Math.max; import static java.lang.Math.min; import static net.sourceforge.aprog.swing.SwingTools.horizontalBox; import static net.sourceforge.aprog.tools.Tools.cast; import static net.sourceforge.aprog.tools.Tools.debugPrint; import static net.sourceforge.aprog.tools.Tools.unchecked; import imj2.core.Image2D; import imj2.core.Image2D.MonopatchProcess; import java.awt.Adjustable; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import javax.swing.Box; import javax.swing.JComponent; import javax.swing.JScrollBar; import javax.swing.SwingUtilities; import net.sourceforge.aprog.swing.SwingTools; import net.sourceforge.aprog.tools.Tools; /** * @author codistmonk (creation 2013-08-05) */ public final class Image2DComponent extends JComponent { private ScaledImage2D scaledImage; private BufferedImage backBuffer; private Graphics2D backBufferGraphics; private BufferedImage frontBuffer; private Graphics2D frontBufferGraphics; private final Rectangle scaledImageVisibleRectangle; private final JScrollBar horizontalScrollBar; private final JScrollBar verticalScrollBar; private boolean multiThread; public Image2DComponent() { this.scaledImageVisibleRectangle = new Rectangle(); this.horizontalScrollBar = new JScrollBar(Adjustable.HORIZONTAL); this.verticalScrollBar = new JScrollBar(Adjustable.VERTICAL); this.multiThread = false; this.setDoubleBuffered(false); this.setLayout(new BorderLayout()); this.add(horizontalBox(this.horizontalScrollBar, Box.createHorizontalStrut(this.verticalScrollBar.getPreferredSize().width)), BorderLayout.SOUTH); this.add(this.verticalScrollBar, BorderLayout.EAST); this.addComponentListener(new ComponentAdapter() { @Override public final void componentResized(final ComponentEvent event) { Image2DComponent.this.setScrollBarsVisibleAmounts(); } }); final AdjustmentListener bufferPositionAdjuster = new AdjustmentListener() { @Override public final void adjustmentValueChanged(final AdjustmentEvent event) { Image2DComponent.this.updateBufferAccordingToScrollBars(false); Image2DComponent.this.repaint(); } }; this.horizontalScrollBar.addAdjustmentListener(bufferPositionAdjuster); this.verticalScrollBar.addAdjustmentListener(bufferPositionAdjuster); this.setBackground(Color.BLACK); this.setFocusable(true); this.addKeyListener(new KeyAdapter() { @Override public final void keyTyped(final KeyEvent event) { final Image2D image = Image2DComponent.this.getImage(); final int zoom = Image2DComponent.this.getZoom(); switch (event.getKeyChar()) { case '*': Image2DComponent.this.setZoom(zoom * 2); break; case '/': Image2DComponent.this.setZoom(zoom / 2); break; case '+': final SubsampledImage2D subsampledImage = cast(SubsampledImage2D.class, image); if (subsampledImage != null) { Image2DComponent.this.setImage(subsampledImage.getSource()); Image2DComponent.this.setZoom(zoom / 2); } break; case '-': if (1 < image.getWidth() && 1 < image.getHeight()) { Image2DComponent.this.setImage(new SubsampledImage2D(image)); Image2DComponent.this.setZoom(zoom * 2); } break; default: return; } final JScrollBar horizontalScrollBar = Image2DComponent.this.getHorizontalScrollBar(); final JScrollBar verticalScrollBar = Image2DComponent.this.getVerticalScrollBar(); final int oldHV = horizontalScrollBar.getValue(); final int oldHA = horizontalScrollBar.getVisibleAmount(); final int oldHM = horizontalScrollBar.getMaximum(); final int oldVV = verticalScrollBar.getValue(); final int oldVA = verticalScrollBar.getVisibleAmount(); final int oldVM = verticalScrollBar.getMaximum(); Image2DComponent.this.setScrollBarsVisibleAmounts(); Image2DComponent.this.updateBufferAccordingToScrollBars(true); final int newHA = horizontalScrollBar.getVisibleAmount(); final int newHM = horizontalScrollBar.getMaximum(); final int newVA = verticalScrollBar.getVisibleAmount(); final int newVM = verticalScrollBar.getMaximum(); // oldC / oldM = newC / newM // -> newC = oldC * newM / oldM // -> newV + newA / 2 = (oldV + oldA / 2) * newM / oldM // -> newV = (oldV + oldA / 2) * newM / oldM - newA / 2 // -> newV = ((2 * oldV + oldA) * newM - newA * oldM) / (2 * oldM) horizontalScrollBar.setValue((int) (((2L * oldHV + oldHA) * newHM - (long) newHA * oldHM) / (2L * oldHM))); verticalScrollBar.setValue((int) (((2L * oldVV + oldVA) * newVM - (long) newVA * oldVM) / (2L * oldVM))); } }); final MouseAdapter mouseHandler = new MouseAdapter() { private int horizontalScrollBarValue; private int verticalScrollBarValue; private int x; private int y; @Override public final void mousePressed(final MouseEvent event) { this.horizontalScrollBarValue = Image2DComponent.this.getHorizontalScrollBar().getValue(); this.verticalScrollBarValue = Image2DComponent.this.getVerticalScrollBar().getValue(); this.x = event.getX(); this.y = event.getY(); } @Override public final void mouseDragged(final MouseEvent event) { Image2DComponent.this.getHorizontalScrollBar().setValue(this.horizontalScrollBarValue - (event.getX() - this.x)); Image2DComponent.this.getVerticalScrollBar().setValue(this.verticalScrollBarValue - (event.getY() - this.y)); } }; this.addMouseListener(mouseHandler); this.addMouseMotionListener(mouseHandler); this.addMouseMotionListener(mouseHandler); } public Image2DComponent(final Image2D image) { this(); this.scaledImage = new ScaledImage2D(image); this.horizontalScrollBar.setMaximum(image.getWidth()); this.verticalScrollBar.setMaximum(image.getHeight()); final Dimension preferredSize = new Dimension(Toolkit.getDefaultToolkit().getScreenSize()); preferredSize.width = min(preferredSize.width / 2, image.getWidth() + this.verticalScrollBar.getPreferredSize().width); preferredSize.height = min(preferredSize.height / 2, image.getHeight() + this.horizontalScrollBar.getPreferredSize().height); this.setPreferredSize(preferredSize); } public final int getZoom() { return this.getScaledImage().getZoom(); } public final void setZoom(final int zoom) { if (0 < zoom && zoom != this.getZoom()) { this.getScaledImage().setZoom(zoom); this.repaint(); } } public final Image2D getImage() { return this.getScaledImage() == null ? null : this.getScaledImage().getSource(); } public final void setImage(final Image2D image) { this.scaledImage = new ScaledImage2D(image); } public final boolean isMultiThread() { return this.multiThread; } public final void setMultiThread(final boolean multiThread) { this.multiThread = multiThread; } public final void setBuffer() { final int width = min(this.getScaledImageWidth(), max(1, this.getUsableWidth())); final int height = min(this.getScaledImageHeight(), max(1, this.getUsableHeight())); final boolean createBuffer; if (this.frontBuffer == null) { createBuffer = true; } else if (this.frontBuffer.getWidth() != width || this.frontBuffer.getHeight() != height) { this.frontBufferGraphics.dispose(); this.frontBufferGraphics = null; this.backBufferGraphics.dispose(); this.backBufferGraphics = null; createBuffer = true; } else { createBuffer = false; } if (createBuffer) { final BufferedImage oldBuffer = this.frontBuffer; this.frontBuffer = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); this.frontBufferGraphics = this.frontBuffer.createGraphics(); this.backBuffer = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); this.backBufferGraphics = this.backBuffer.createGraphics(); this.setScaledImageVisibleRectangle(new Rectangle( min(this.scaledImageVisibleRectangle.x, this.getScaledImageWidth() - width), min(this.scaledImageVisibleRectangle.y, this.getScaledImageHeight() - height), width, height), oldBuffer); } } public final void updateBuffer(final int left, final int top, final int width, final int height) { if (this.getScaledImage() != null && 0 < width && 0 < height) { this.copyImagePixelsToBuffer(left, top, width, height); } } @Override protected final void paintComponent(final Graphics g) { this.setBuffer(); final int centeringOffsetX = max(0, (this.getUsableWidth() - this.frontBuffer.getWidth()) / 2); final int centeringOffsetY = max(0, (this.getUsableHeight() - this.frontBuffer.getHeight()) / 2); g.drawImage(this.frontBuffer, centeringOffsetX, centeringOffsetY, null); } final JScrollBar getHorizontalScrollBar() { return this.horizontalScrollBar; } final JScrollBar getVerticalScrollBar() { return this.verticalScrollBar; } final void updateBufferAccordingToScrollBars(final boolean forceRepaint) { if (this.frontBuffer == null) { return; } final int width = min(this.getScaledImageWidth(), this.frontBuffer.getWidth()); final int height = min(this.getScaledImageHeight(), this.frontBuffer.getHeight()); final int left = width < this.getScaledImageWidth() ? min(this.getScaledImageWidth() - width, this.horizontalScrollBar.getValue()) : 0; final int top = height < this.getScaledImageHeight() ? min(this.getScaledImageHeight() - height, this.verticalScrollBar.getValue()) : 0; this.setScaledImageVisibleRectangle(new Rectangle(left, top, width, height), forceRepaint ? null : this.frontBuffer); } final void setScrollBarsVisibleAmounts() { this.horizontalScrollBar.setMaximum(this.getScaledImageWidth()); this.verticalScrollBar.setMaximum(this.getScaledImageHeight()); final int usableWidth = max(0, this.getUsableWidth()); final int usableHeight = max(0, this.getUsableHeight()); if (this.horizontalScrollBar.getMaximum() <= this.horizontalScrollBar.getValue() + usableWidth) { this.horizontalScrollBar.setValue(max(0, this.horizontalScrollBar.getMaximum() - usableWidth)); } this.horizontalScrollBar.setVisibleAmount(usableWidth); if (this.verticalScrollBar.getMaximum() <= this.verticalScrollBar.getValue() + usableHeight) { this.verticalScrollBar.setValue(max(0, this.verticalScrollBar.getMaximum() - usableHeight)); } this.verticalScrollBar.setVisibleAmount(usableHeight); } final void copyImagePixelsToBuffer(final int left, final int top, final int width, final int height) { if (this.isMultiThread()) { new ParallelProcess2D(this.getScaledImage(), left, top, width, height) { @Override public final void pixel(final int x, final int y) { Image2DComponent.this.copyImagePixelToBuffer(x, y); } /** * {@value}. */ private static final long serialVersionUID = 7757156523330629112L; }; } else { this.getScaledImage().forEachPixelInBox(left, top, width, height, new MonopatchProcess() { @Override public final void pixel(final int x, final int y) { Image2DComponent.this.copyImagePixelToBuffer(x, y); } /** * {@value}. */ private static final long serialVersionUID = 1810623847473680066L; }); } } final void copyImagePixelToBuffer(final int xInScaledImage, final int yInScaledImage) { try { this.frontBuffer.setRGB(xInScaledImage - this.scaledImageVisibleRectangle.x, yInScaledImage - this.scaledImageVisibleRectangle.y, this.getScaledImage().getPixelValue(xInScaledImage, yInScaledImage)); } catch (final Exception exception) { exception.printStackTrace(); debugPrint(xInScaledImage, yInScaledImage, xInScaledImage - this.scaledImageVisibleRectangle.x, yInScaledImage - this.scaledImageVisibleRectangle.y); System.exit(-1); } } final ScaledImage2D getScaledImage() { return this.scaledImage; } public final void setScaledImage(ScaledImage2D scaledImage) { this.scaledImage = scaledImage; } private final int getUsableHeight() { return this.getHeight() - this.horizontalScrollBar.getHeight(); } private final int getUsableWidth() { return this.getWidth() - this.verticalScrollBar.getWidth(); } private final void setScaledImageVisibleRectangle(final Rectangle rectangle, final BufferedImage oldBuffer) { if (this.getScaledImageWidth() < rectangle.x + rectangle.width || this.getScaledImageHeight() < rectangle.y + rectangle.height || this.frontBuffer.getWidth() < rectangle.width || this.frontBuffer.getHeight() < rectangle.height) { throw new IllegalArgumentException(rectangle + " " + new Rectangle(this.getScaledImageWidth(), this.getScaledImageHeight()) + " " + new Rectangle(this.frontBuffer.getWidth(), this.frontBuffer.getHeight())); } if (oldBuffer == null) { this.scaledImageVisibleRectangle.setBounds(rectangle); this.updateBuffer(rectangle.x, rectangle.y, rectangle.width, rectangle.height); } else { final Rectangle intersection = this.scaledImageVisibleRectangle.intersection(rectangle); if (intersection.isEmpty()) { this.scaledImageVisibleRectangle.setBounds(rectangle); this.updateBuffer(rectangle.x, rectangle.y, rectangle.width, rectangle.height); } else { final int intersectionRight = intersection.x + intersection.width; final int intersectionBottom = intersection.y + intersection.height; this.backBufferGraphics.drawImage(oldBuffer, intersection.x - rectangle.x, intersection.y - rectangle.y, intersectionRight - rectangle.x, intersectionBottom - rectangle.y, intersection.x - this.scaledImageVisibleRectangle.x, intersection.y - this.scaledImageVisibleRectangle.y, intersectionRight - this.scaledImageVisibleRectangle.x, intersectionBottom - this.scaledImageVisibleRectangle.y , null); this.swapBuffers(); this.scaledImageVisibleRectangle.setBounds(rectangle); final boolean multiThread = this.isMultiThread(); this.setMultiThread(false); // Update top this.updateBuffer(rectangle.x, rectangle.y, rectangle.width, intersection.y - rectangle.y); // Update left this.updateBuffer(rectangle.x, intersection.y, intersection.x - rectangle.x, intersection.height); // Update right this.updateBuffer(intersectionRight, intersection.y, rectangle.x + rectangle.width - intersectionRight, intersection.height); // Update bottom this.updateBuffer(rectangle.x, intersectionBottom, rectangle.width, rectangle.y + rectangle.height - intersectionBottom); this.setMultiThread(multiThread); } } if (this.frontBuffer.getWidth() < this.scaledImageVisibleRectangle.width || this.frontBuffer.getHeight() < this.scaledImageVisibleRectangle.getHeight()) { throw new IllegalStateException(); } } private final void swapBuffers() { final BufferedImage tmpBuffer = this.frontBuffer; final Graphics2D tmpGraphics = this.frontBufferGraphics; this.frontBuffer = this.backBuffer; this.frontBufferGraphics = this.backBufferGraphics; this.backBuffer = tmpBuffer; this.backBufferGraphics = tmpGraphics; } private final int getScaledImageWidth() { return this.getScaledImage().getWidth(); } private final int getScaledImageHeight() { return this.getScaledImage().getHeight(); } /** * {@value}. */ private static final long serialVersionUID = 4189273248039238064L; public static final void show(final Image2D image) { final Component[] component = { null }; try { SwingUtilities.invokeAndWait(new Runnable() { @Override public final void run() { component[0] = new Image2DComponent(image); } }); } catch (final Exception exception) { throw unchecked(exception); } SwingTools.show(component[0], image.getId(), true); } /** * @author codistmonk (creation 2013-08-12) */ public static final class ScaledImage2D extends TiledImage2D { private final Image2D source; private int zoom; public ScaledImage2D(final Image2D source) { super(source.getId()); this.source = source; this.setZoom(1); } public final int getZoom() { return this.zoom; } public final void setZoom(final int zoom) { if (0 < zoom) { this.zoom = zoom; if (this.getSource() instanceof TiledImage2D) { this.setOptimalTileWidth(((TiledImage2D) this.getSource()).getOptimalTileWidth() * zoom); this.setOptimalTileHeight(((TiledImage2D) this.getSource()).getOptimalTileHeight() * zoom); } else { this.setOptimalTileWidth(this.getSource().getWidth() * zoom); this.setOptimalTileHeight(this.getSource().getHeight() * zoom); } } } public final Image2D getSource() { return this.source; } @Override public final int getWidth() { return this.getSource().getWidth() * this.getZoom(); } @Override public final int getHeight() { return this.getSource().getHeight() * this.getZoom(); } @Override public final Channels getChannels() { return this.getSource().getChannels(); } @Override public final ScaledImage2D[] newParallelViews(final int n) { final ScaledImage2D[] result = new ScaledImage2D[n]; result[0] = this; if (1 < n) { final Image2D[] sources = this.getSource().newParallelViews(n); for (int i = 1; i < n; ++i) { result[i] = new ScaledImage2D(sources[i]); } } return result; } @Override protected final int getPixelValueFromTile(final int x, final int y, final int xInTile, final int yInTile) { return this.getSource().getPixelValue(x / this.getZoom(), y / this.getZoom()); } @Override protected final boolean makeNewTile() { return false; } @Override protected final void updateTile() { // NOP } /** * {@value}. */ private static final long serialVersionUID = -7082323074031564968L; } }
package org.jenetics; import static org.jenetics.util.object.eq; import static org.jenetics.util.object.hashCodeOf; import static org.jenetics.util.object.nonNull; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.RandomAccess; import javolution.context.ConcurrentContext; import javolution.xml.XMLFormat; import javolution.xml.XMLSerializable; import javolution.xml.stream.XMLStreamException; import org.jenetics.util.Concurrency; import org.jenetics.util.Copyable; import org.jenetics.util.Factory; import org.jenetics.util.arrays; public class Population<G extends Gene<?, G>, C extends Comparable<? super C>> implements List<Phenotype<G, C>>, Copyable<Population<G, C>>, RandomAccess, XMLSerializable { private static final long serialVersionUID = 1L; private final List<Phenotype<G, C>> _population; /** * @PrimaryConstructor */ private Population(final List<Phenotype<G, C>> population) { _population = population; } /** * Constructs a population containing the elements of the specified collection, * in the order they are returned by the collection's iterator. * * @param population the collection whose elements are to be placed into * this list. * @throws NullPointerException if the specified population is {@code null}. */ public Population(final Collection<? extends Phenotype<G, C>> population) { this(new ArrayList<>(population)); } public Population(final int size) { this(new ArrayList<Phenotype<G, C>>(size + 1)); } /** * Creating a new <code>Population</code>. */ public Population() { this(new ArrayList<Phenotype<G, C>>()); } public Population<G, C> fill( final Factory<? extends Phenotype<G, C>> factory, final int count ) { // Serial version. if (ConcurrentContext.getConcurrency() == 0) { for (int i = 0; i < count; ++i) { _population.add(factory.newInstance()); } // Parallel version. } else { final PhenotypeArray<G, C> array = new PhenotypeArray<>(count); fill(factory, array._array); _population.addAll(array); } return this; } private static < G extends Gene<?, G>, C extends Comparable<? super C> > void fill( final Factory<? extends Phenotype<G, C>> factory, final Object[] array ) { try (final Concurrency c = Concurrency.start()) { final int threads = ConcurrentContext.getConcurrency() + 1; final int[] parts = arrays.partition(array.length, threads); for (int i = 0; i < parts.length - 1; ++i) { final int part = i; c.execute(new Runnable() { @Override public void run() { for (int j = parts[part + 1]; --j >= parts[part];) { array[j] = factory.newInstance(); } }}); } } } /** * Add <code>Phenotype</code> to the <code>Population</code>. * * @param phenotype <code>Phenotype</code> to be add. * @throws NullPointerException if the given {@code phenotype} is {@code null}. */ @Override public boolean add(final Phenotype<G, C> phenotype) { nonNull(phenotype, "Phenotype"); return _population.add(phenotype); } /** * Add <code>Phenotype</code> to the <code>Population</code>. * * @param index Index of the * @param phenotype <code>Phenotype</code> to be add. * @throws NullPointerException if the given {@code phenotype} is {@code null}. */ @Override public void add(final int index, final Phenotype<G, C> phenotype) { nonNull(phenotype, "Phenotype"); _population.add(index, phenotype); } @Override public boolean addAll(final Collection<? extends Phenotype<G, C>> c) { return _population.addAll(c); } @Override public boolean addAll(int index, Collection<? extends Phenotype<G, C>> c) { return _population.addAll(index, c); } @Override public Phenotype<G, C> get(final int index) { return _population.get(index); } @Override public Phenotype<G, C> set(final int index, final Phenotype<G, C> phenotype) { nonNull(phenotype, "Phenotype"); return _population.set(index, phenotype); } public void remove(final Phenotype<G, C> phenotype) { nonNull(phenotype, "Phenotype"); _population.remove(phenotype); } @Override public boolean remove(final Object o) { return _population.remove(o); } @Override public boolean removeAll(final Collection<?> c) { return _population.removeAll(c); } @Override public Phenotype<G, C> remove(final int index) { return _population.remove(index); } @Override public void clear() { _population.clear(); } /** * Sorting the phenotypes in this population according to its fitness * value in descending order. */ public void sort() { sort(Optimize.MAXIMUM.<C>descending()); } public void sort(final Comparator<? super C> comparator) { quicksort(0, size() - 1, comparator); } private void quicksort( final int left, final int right, final Comparator<? super C> comparator ) { if (right > left) { final int j = partition(left, right, comparator); quicksort(left, j - 1, comparator); quicksort(j + 1, right, comparator); } } private int partition( final int left, final int right, final Comparator<? super C> comparator ) { final C pivot = _population.get(left).getFitness(); int i = left; int j = right + 1; while (true) { do { ++i; } while ( i < right && comparator.compare(_population.get(i).getFitness(), pivot) < 0 ); do { --j; } while ( j > left && comparator.compare(_population.get(j).getFitness(), pivot) > 0 ); if (j <= i) { break; } swap(i, j); } swap(left, j); return j; } private void swap(final int i, final int j) { _population.set(i, _population.set(j, _population.get(i))); } /** * Reverse the order of the population. */ public void reverse() { Collections.reverse(_population); } @Override public Iterator<Phenotype<G, C>> iterator() { return _population.iterator(); } @Override public ListIterator<Phenotype<G, C>> listIterator() { return _population.listIterator(); } @Override public ListIterator<Phenotype<G, C>> listIterator(final int index) { return _population.listIterator(index); } @Override public int size() { return _population.size(); } @Override public boolean isEmpty() { return _population.isEmpty(); } @Override public boolean contains(final Object o) { return _population.contains(o); } @Override public boolean containsAll(final Collection<?> c) { return _population.containsAll(c); } @Override public int indexOf(final Object o) { return _population.indexOf(o); } @Override public int lastIndexOf(final Object o) { return _population.lastIndexOf(o); } @Override public boolean retainAll(final Collection<?> c) { return _population.retainAll(c); } @Override public List<Phenotype<G, C>> subList(final int fromIndex, final int toIndex) { return _population.subList(fromIndex, toIndex); } @Override public Object[] toArray() { return _population.toArray(); } @Override public <A> A[] toArray(final A[] a) { return _population.toArray(a); } public List<Genotype<G>> getGenotypes() { final List<Genotype<G>> genotypes = new ArrayList<>(_population.size()); for (Phenotype<G, C> phenotype : _population) { genotypes.add(phenotype.getGenotype()); } return genotypes; } @Override public Population<G, C> copy() { return new Population<>(_population); } @Override public int hashCode() { return hashCodeOf(getClass()).and(_population).value(); } @Override public boolean equals(final Object object) { if (object == this) { return true; } if (!(object instanceof Population<?, ?>)) { return false; } final Population<?, ?> population = (Population<?, ?>)object; return eq(_population, population._population); } @Override public String toString() { StringBuilder out = new StringBuilder(); for (Phenotype<?, ?> pt : this) { out.append(pt.toString()).append("\n"); } return out.toString(); } @SuppressWarnings({ "unchecked", "rawtypes" }) static final XMLFormat<Population> XML = new XMLFormat<Population>(Population.class) { private static final String SIZE = "size"; @Override public Population newInstance( final Class<Population> cls, final InputElement xml ) throws XMLStreamException { final int size = xml.getAttribute(SIZE, 10); final Population p = new Population(size); for (int i = 0; i < size; ++i) { p.add(xml.<Phenotype>getNext()); } return p; } @Override public void write(final Population p, final OutputElement xml) throws XMLStreamException { xml.setAttribute(SIZE, p.size()); for (Object phenotype : p) { xml.add(phenotype); } } @Override public void read(final InputElement xml, final Population p) { } }; private static final class PhenotypeArray< G extends Gene<?, G>, C extends Comparable<? super C> > extends AbstractCollection<Phenotype<G, C>> { final Object[] _array; PhenotypeArray(final int size) { _array = new Object[size]; } @SuppressWarnings("unchecked") @Override public Iterator<Phenotype<G, C>> iterator() { return Arrays.asList((Phenotype<G, C>[])_array).iterator(); } @Override public int size() { return _array.length; } @Override public Object[] toArray() { return _array; } } }
package org.ocelotds.test; import org.ocelotds.objects.Result; import org.ocelotds.test.dataservices.EJBDataService; import org.ocelotds.test.dataservices.CDIDataService; import org.ocelotds.test.dataservices.SingletonCDIDataService; import org.ocelotds.test.dataservices.PojoDataService; import com.fasterxml.jackson.databind.ObjectMapper; import org.ocelotds.Constants; import org.ocelotds.OcelotServices; import org.ocelotds.messaging.Fault; import org.ocelotds.messaging.MessageFromClient; import org.ocelotds.messaging.MessageToClient; import org.ocelotds.messaging.MessageEvent; import org.ocelotds.messaging.MessageType; import org.ocelotds.resolvers.CdiResolver; import org.ocelotds.spi.DataServiceException; import org.ocelotds.spi.IDataServiceResolver; import org.ocelotds.resolvers.DataServiceResolverIdLitteral; import org.ocelotds.resolvers.EJBResolver; import org.ocelotds.resolvers.PojoResolver; import org.ocelotds.test.dataservices.GetValue; import org.ocelotds.test.dataservices.SessionCDIDataService; import org.ocelotds.test.dataservices.SessionEJBDataService; import org.ocelotds.test.dataservices.SingletonEJBDataService; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.enterprise.event.Event; import javax.enterprise.inject.Any; import javax.enterprise.inject.Instance; import javax.inject.Inject; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.MessageHandler; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import static org.assertj.core.api.Assertions.*; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.FileAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.jboss.weld.exceptions.UnsatisfiedResolutionException; import org.junit.AfterClass; import org.junit.Assert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.ocelotds.ArquillianTestCase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author hhfrancois */ //@RunWith(Arquillian.class) public class OcelotTest extends ArquillianTestCase { private final static Logger logger = LoggerFactory.getLogger(OcelotTest.class); private final static long TIMEOUT = 1000; private final static String PORT = "8282"; private final static String ctxpath = "ocelot-test"; @Inject @MessageEvent Event<MessageToClient> wsEvent; @Inject @Any private Instance<IDataServiceResolver> resolvers; @Inject TestTopicAccessControler accessControl; private IDataServiceResolver getResolver(String type) { return resolvers.select(new DataServiceResolverIdLitteral(type)).get(); } private final PojoDataService destination = new PojoDataService(); @Deployment public static WebArchive createWarGlassfishArchive() { return createWarArchive(); } public static WebArchive createWarArchive() { File[] core = Maven.resolver().resolve("org.ocelotds:ocelot-core:2.2.1-SNAPSHOT").withTransitivity().asFile(); File logback = new File("src/test/resources/logback.xml"); File localeFr = new File("src/test/resources/test_fr_FR.properties"); File localeUs = new File("src/test/resources/test_en_US.properties"); WebArchive webArchive = ShrinkWrap.create(WebArchive.class, ctxpath + ".war") .addAsLibraries(core) .addAsLibraries(createOcelotWebJar()) .addPackages(true, OcelotTest.class.getPackage()) .addAsResource(new FileAsset(logback), "logback.xml") .addAsResource(new FileAsset(localeUs), "test_en_US.properties") .addAsResource(new FileAsset(localeFr), "test_fr_FR.properties") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); addJSAndProvider("target/test-classes", webArchive, webArchive); return webArchive; } @BeforeClass public static void setUpClass() { System.out.println("==============================================================================================================="); } @AfterClass public static void tearDownClass() { System.out.println("==============================================================================================================="); } public static Session createAndGetSession() { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); try { StringBuilder sb = new StringBuilder("ws://localhost:"); sb.append(PORT).append(Constants.SLASH).append(ctxpath).append(Constants.SLASH).append("ocelot-endpoint"); URI uri = new URI(sb.toString()); return container.connectToServer(OcelotClientEnpoint.class, uri); } catch (URISyntaxException | DeploymentException | IOException ex) { fail("CONNEXION FAILED " + ex.getMessage()); } return null; } private MessageFromClient getMessageFromClient(String classname, String operation, String... params) { MessageFromClient messageFromClient = new MessageFromClient(); messageFromClient.setId(UUID.randomUUID().toString()); messageFromClient.setDataService(classname); messageFromClient.setOperation(operation); if (params != null) { messageFromClient.getParameters().addAll(Arrays.asList(params)); } return messageFromClient; } private MessageFromClient getMessageFromClient(Class cls, String operation, String paramNames, String... params) { MessageFromClient messageFromClient = getMessageFromClient(cls.getName(), operation, params); messageFromClient.setParameterNames(Arrays.asList(paramNames.split(","))); return messageFromClient; } /** * Transforme un objet en json, attention aux string * * @param obj * @return */ private String getJson(Object obj) { try { if (String.class.isInstance(obj)) { return "\"" + obj + "\""; } ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(obj); } catch (IOException ex) { return null; } } private static class CountDownMessageHandler implements MessageHandler.Whole<String> { private final CountDownLatch lock; private MessageToClient messageToClient = null; private String id = null; CountDownMessageHandler(String id, CountDownLatch lock) { this.lock = lock; this.id = id; } CountDownMessageHandler(CountDownLatch lock) { this.lock = lock; } @Override public void onMessage(String message) { logger.debug("RECEIVE RESPONSE FROM SERVER = {}", message); MessageToClient messageToClientIn = MessageToClient.createFromJson(message); if (id == null || id.equals(messageToClientIn.getId())) { messageToClient = messageToClientIn; lock.countDown(); } } public MessageToClient getMessageToClient() { return messageToClient; } } private Object getResultAfterSendInSession(Session wsSession, Class clazz, String operation, String... params) { return getMessageToClientAfterSendInSession(wsSession, clazz.getName(), operation, params).getResponse(); } private void checkMessageAfterSendInSession(Session session, String className, String operation, String... params) { // contruction de l'objet command MessageFromClient messageFromClient = getMessageFromClient(className, operation, params); // send session.getAsyncRemote().sendText(messageFromClient.toJson()); } private MessageToClient getMessageToClientAfterSendInSession(Session session, String classname, String operation, String... params) { MessageToClient result = null; try { long t0 = System.currentTimeMillis(); // construction de la commande MessageFromClient messageFromClient = getMessageFromClient(classname, operation, params); // on pose un locker CountDownLatch lock = new CountDownLatch(1); CountDownMessageHandler messageHandler = new CountDownMessageHandler(messageFromClient.getId(), lock); session.addMessageHandler(messageHandler); // send session.getAsyncRemote().sendText(messageFromClient.toJson()); // wait le delock ou timeout boolean await = lock.await(TIMEOUT, TimeUnit.MILLISECONDS); long t1 = System.currentTimeMillis(); assertTrue("Timeout. waiting " + (t1 - t0) + " ms. Remain " + lock.getCount() + "/1 msgs", await); // lecture du resultat dans le handler result = messageHandler.getMessageToClient(); assertNotNull(result); session.removeMessageHandler(messageHandler); } catch (InterruptedException ex) { fail("Bean not reached"); } return result; } private void testDifferentInstancesInDifferentThreads(final Class<? extends GetValue> clazz, String resolverId) { final IDataServiceResolver resolver = getResolver(resolverId); try { ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new CallRunnable(clazz, resolver)); executorService.shutdown(); GetValue bean2 = resolver.resolveDataService(clazz); assertNotNull(bean2); Assert.assertNotEquals("two instances of session bean should be differents", bean2.getValue(), 500); } catch (DataServiceException ex) { fail(resolverId + " bean not reached"); } } private static class CallRunnable implements Runnable { private final Class<? extends GetValue> clazz; private final IDataServiceResolver resolver; public CallRunnable(Class<? extends GetValue> clazz, IDataServiceResolver resolver) { this.clazz = clazz; this.resolver = resolver; } @Override public void run() { try { GetValue bean1 = resolver.resolveDataService(clazz); bean1.setValue(500); Thread.sleep(1000); assertNotNull(bean1); assertTrue(clazz.isInstance(bean1)); } catch (DataServiceException | InterruptedException ex) { } } } private void testInstanceRequestScope(Class clazz, String resolverId) { IDataServiceResolver resolver = getResolver(resolverId); try { Object bean1 = resolver.resolveDataService(clazz); assertNotNull(bean1); assertTrue(clazz.isInstance(bean1)); Object bean2 = resolver.resolveDataService(clazz); assertNotNull(bean2); assertFalse("two instances of request bean should be differents", bean1.equals(bean2)); } catch (DataServiceException ex) { fail(resolverId + " bean not reached"); } } public void testResultRequestScope(Class clazz) { // premiere requete Object firstResult = null; try (Session wssession = createAndGetSession()) { firstResult = getResultAfterSendInSession(wssession, clazz, "getValue"); } catch (IOException exception) { } // deuxieme requetesur une autre session Object secondResult = null; try (Session wssession = createAndGetSession()) { secondResult = getResultAfterSendInSession(wssession, clazz, "getValue"); } catch (IOException exception) { } // controle Assert.assertNotEquals("two instances of request bean should be differents", firstResult, secondResult); // doit etre different } private void testInstanceSingletonScope(Class clazz, String resolverId) { IDataServiceResolver resolver = getResolver(resolverId); try { Object singleton1 = resolver.resolveDataService(clazz); assertNotNull(singleton1); Object singleton2 = resolver.resolveDataService(clazz); assertNotNull(singleton2); assertEquals(singleton1, singleton2); } catch (DataServiceException ex) { fail(resolverId + " bean not reached"); } } public void testResultSingletonScope(Class clazz) { // premiere requete Object firstResult = null; try (Session wssession = createAndGetSession()) { firstResult = getResultAfterSendInSession(wssession, clazz, "getValue"); } catch (IOException exception) { } // deuxieme requete sur autre session Object secondResult = null; try (Session wssession = createAndGetSession()) { secondResult = getResultAfterSendInSession(wssession, clazz, "getValue"); } catch (IOException exception) { } // controle, doit etre identique assertEquals(firstResult, secondResult); } private void testInstanceSessionScope(Class clazz, String resolverId) { IDataServiceResolver resolver = getResolver(resolverId); try { Object bean1 = resolver.resolveDataService(clazz); assertNotNull(bean1); assertTrue(clazz.isInstance(bean1)); Object bean2 = resolver.resolveDataService(clazz); assertNotNull(bean2); assertFalse("two instances of session bean should be differents", bean1.equals(bean2)); } catch (DataServiceException ex) { fail(resolverId + " bean not reached"); } } private void testResultSessionScope(Class clazz) { // premiere requete Object firstResult = null; Object secondResult = null; try (Session wssession = createAndGetSession()) { firstResult = getResultAfterSendInSession(wssession, clazz, "getValue"); // deuxieme requete secondResult = getResultAfterSendInSession(wssession, clazz, "getValue"); } catch (IOException exception) { } // controle : sur la meme session cela doit se comporter comme un singleton, donc meme resultat assertEquals(secondResult, firstResult); // troisiement appel sur une session differente Object thirdResult = null; try (Session wssession = createAndGetSession()) { thirdResult = getResultAfterSendInSession(wssession, clazz, "getValue"); } catch (IOException exception) { } // controle : sur != session cela doit etre different Assert.assertNotEquals(secondResult, thirdResult); } public HttpURLConnection getConnectionForResource(String resource, boolean min) throws MalformedURLException, IOException { StringBuilder sb = new StringBuilder("http://localhost:"); sb.append(PORT).append(Constants.SLASH).append(ctxpath).append(Constants.SLASH).append(resource); if (!min) { sb.append("?").append(Constants.MINIFY_PARAMETER).append("=false"); } URL url = new URL(sb.toString()); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); System.out.println("Content-type: " + uc.getContentType()); System.out.println("Content-encoding: " + uc.getContentEncoding()); System.out.println("Date: " + new Date(uc.getDate())); System.out.println("Last modified: " + new Date(uc.getLastModified())); System.out.println("Expiration date: " + new Date(uc.getExpiration())); System.out.println("Content-length: " + uc.getContentLength()); // connection.setRequestMethod("GET"); // connection.connect(); assertEquals("'" + sb.toString() + "' is unreachable", 200, uc.getResponseCode()); return uc; } ////@Test public void testJavascriptCoreMinification() { System.out.println("testJavascriptCoreMinification"); String resource = Constants.OCELOT + Constants.JS; HttpURLConnection connection1 = null; HttpURLConnection connection2 = null; try { connection1 = getConnectionForResource(resource, true); int minlength = connection1.getInputStream().available(); // traceFile(connection1.getInputStream()); connection2 = getConnectionForResource(resource, false); int length = connection2.getInputStream().available(); // traceFile(connection2.getInputStream()); assertTrue("Minification of " + resource + " didn't work, same size of file magnifier : " + length + " / minifer : " + minlength, minlength < length); } catch (Exception e) { fail(e.getMessage()); } finally { if (connection1 != null) { connection1.disconnect(); } if (connection2 != null) { connection2.disconnect(); } } } private void traceFile(InputStream input) { try (BufferedReader in = new BufferedReader(new InputStreamReader(input, Constants.UTF_8))) { String inputLine; while ((inputLine = in.readLine()) != null) { System.out.write(inputLine.getBytes(Constants.UTF_8)); System.out.write(Constants.BACKSLASH_N.getBytes(Constants.UTF_8)); } } catch (IOException e) { } } //@Test public void testJavascriptGeneration() { System.out.println("testJavascriptCoreGeneration"); try { HttpURLConnection connection = getConnectionForResource(Constants.OCELOT + Constants.JS, false); boolean replaced; try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), Constants.UTF_8))) { String inputLine; replaced = false; while ((inputLine = in.readLine()) != null) { assertFalse("Dynamic replacement of " + Constants.CTXPATH + " doen't work", inputLine.contains(Constants.CTXPATH)); replaced |= inputLine.contains(ctxpath); } } assertTrue("Dynamic replacement of context doen't work", replaced); } catch (Exception e) { fail(e.getMessage()); } } //@Test(expected = UnsatisfiedResolutionException.class) public void testDataServiceExceptionOnUnknownResolver() { System.out.println("failResolveDataService"); getResolver("foo"); } //@Test public void testGetResolverEjb() { System.out.println("getResolverEjb"); IDataServiceResolver resolver = getResolver(Constants.Resolver.EJB); assertNotNull(resolver); assertTrue(EJBResolver.class.isInstance(resolver)); } //@Test public void testGetEjbs() { System.out.println("getEjbs"); String resolverId = Constants.Resolver.EJB; testDifferentInstancesInDifferentThreads(EJBDataService.class, resolverId); } //@Test public void testGetEJBStatefull() { System.out.println("getEJBSession"); String resolverId = Constants.Resolver.EJB; // testDifferentInstancesInDifferentThreads(SessionEJBDataService.class, resolverId); testInstanceSessionScope(SessionEJBDataService.class, Constants.Resolver.EJB); } //@Test public void testGetResultEJBSession() { System.out.println("getResultEJBSession"); testResultSessionScope(SessionEJBDataService.class); } //@Test public void testGetEJBSingleton() { System.out.println("getEJBSingleton"); testInstanceSingletonScope(SingletonEJBDataService.class, Constants.Resolver.EJB); } //@Test public void testGetResultEjbSingleton() { System.out.println("getResultEjbSingleton"); testResultSingletonScope(SingletonEJBDataService.class); } //@Test public void testGetResolverPojo() { System.out.println("getResolverPojo"); IDataServiceResolver resolver = getResolver(Constants.Resolver.POJO); assertNotNull(resolver); assertTrue(PojoResolver.class.isInstance(resolver)); } //@Test public void testGetPojo() { System.out.println("getPojo"); IDataServiceResolver resolver = getResolver(Constants.Resolver.POJO); try { PojoDataService resolveDataService = resolver.resolveDataService(PojoDataService.class); assertNotNull(resolveDataService); assertEquals(PojoDataService.class, resolveDataService.getClass()); } catch (DataServiceException ex) { fail("Pojo not reached"); } } //@Test public void testGetResolverCdi() { System.out.println("getResolverCdi"); IDataServiceResolver resolver = getResolver(Constants.Resolver.CDI); assertNotNull(resolver); assertTrue(CdiResolver.class.isInstance(resolver)); } //@Test public void testGetCdiBeans() { System.out.println("getCdiBeans"); testInstanceRequestScope(CDIDataService.class, Constants.Resolver.CDI); } //@Test public void testGetResultCdiBeans() { System.out.println("getResultCdiBeans"); testResultRequestScope(CDIDataService.class); } //@Test public void testGetCdiBeanIsManaged() { System.out.println("getCdiBeanIsManaged"); IDataServiceResolver resolver = getResolver(Constants.Resolver.CDI); try { CDIDataService cdids = resolver.resolveDataService(CDIDataService.class); assertNotNull(cdids); assertEquals(CDIDataService.class, cdids.getClass()); assertNotNull(cdids.getBeanManager()); } catch (DataServiceException ex) { fail("Cdi bean not reached"); } } //@Test public void testGetCdiBeanSession() { System.out.println("getCdiBeanSession"); testInstanceSessionScope(SessionCDIDataService.class, Constants.Resolver.CDI); } //@Test public void testGetResultCdiBeanSession() { System.out.println("getResultCdiBeanSession"); testResultSessionScope(SessionCDIDataService.class); } //@Test public void testGetCdiBeanSingleton() { System.out.println("getCdiBeanSingleton"); testInstanceSingletonScope(SingletonCDIDataService.class, Constants.Resolver.CDI); } //@Test public void testGetResultCdiBeanSingleton() { System.out.println("getResultCdiBeanSingleton"); testResultSingletonScope(SingletonCDIDataService.class); } //@Test public void testResolvePojoDataService() { System.out.println("resolveDataService"); try { IDataServiceResolver resolver = getResolver(Constants.Resolver.POJO); Object dest = resolver.resolveDataService(PojoDataService.class); assertNotNull(dest); assertEquals(PojoDataService.class, dest.getClass()); } catch (DataServiceException ex) { fail(ex.getMessage()); } } //@Test public void testMessageIntResultToClientCreator() { System.out.println("MessageToClient.createFromJson"); String uuid = UUID.randomUUID().toString(); Object expectedResult = 1; String json = String.format("{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":%s,\"%s\":%s}", Constants.Message.TYPE, MessageType.RESULT, Constants.Message.ID, uuid, Constants.Message.DEADLINE, 5, Constants.Message.RESPONSE, expectedResult); MessageToClient result = MessageToClient.createFromJson(json); assertEquals(MessageType.RESULT, result.getType()); assertEquals(uuid, result.getId()); assertEquals(5, result.getDeadline()); assertEquals(MessageType.RESULT, result.getType()); assertEquals("" + expectedResult, result.getResponse()); } //@Test public void testMessageToTopicCreator() { System.out.println("MessageToTopic.createFromJson"); String uuid = UUID.randomUUID().toString(); Object expectedResult = 1; String json = String.format("{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":%s,\"%s\":%s}", Constants.Message.TYPE, MessageType.MESSAGE, Constants.Message.ID, uuid, Constants.Message.DEADLINE, 5, Constants.Message.RESPONSE, expectedResult); MessageToClient result = MessageToClient.createFromJson(json); assertEquals(MessageType.MESSAGE, result.getType()); assertEquals(uuid, result.getId()); assertEquals(5, result.getDeadline()); assertEquals("" + expectedResult, result.getResponse()); } //@Test public void testMessageStringResultToClientCreator() { System.out.println("MessageToClient.createFromJson"); String uuid = UUID.randomUUID().toString(); String expectedResultJS = "\"foo\""; String json = String.format("{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":%s,\"%s\":%s}", Constants.Message.TYPE, MessageType.RESULT, Constants.Message.ID, uuid, Constants.Message.DEADLINE, 10, Constants.Message.RESPONSE, expectedResultJS); MessageToClient result = MessageToClient.createFromJson(json); assertEquals(MessageType.RESULT, result.getType()); assertEquals(uuid, result.getId()); assertEquals(10, result.getDeadline()); assertEquals(MessageType.RESULT, result.getType()); assertEquals(expectedResultJS, result.getResponse()); } //@Test public void testMessageObjectResultToClientCreator() { System.out.println("MessageToClient.createFromJson"); String uuid = UUID.randomUUID().toString(); Object expectedResult = "{\"integer\":5,\"foo\":\"foo\"}"; String json = String.format("{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":%s,\"%s\":%s}", Constants.Message.TYPE, MessageType.RESULT, Constants.Message.ID, uuid, Constants.Message.DEADLINE, 20, Constants.Message.RESPONSE, expectedResult); MessageToClient result = MessageToClient.createFromJson(json); assertEquals(MessageType.RESULT, result.getType()); assertEquals(uuid, result.getId()); assertEquals(20, result.getDeadline()); assertEquals(MessageType.RESULT, result.getType()); assertEquals(expectedResult, result.getResponse()); } //@Test public void testMessageFaultToClientCreator() { System.out.println("MessageToClient.createFromJson"); String uuid = UUID.randomUUID().toString(); Fault f = new Fault(new NullPointerException("Message d'erreur"), 0); String json = String.format("{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":%s,\"%s\":%s}", Constants.Message.TYPE, MessageType.FAULT, Constants.Message.ID, uuid, Constants.Message.DEADLINE, 0, Constants.Message.RESPONSE, f.toJson()); MessageToClient result = MessageToClient.createFromJson(json); assertEquals(MessageType.FAULT, result.getType()); assertEquals(uuid, result.getId()); assertEquals(0, result.getDeadline()); assertEquals(MessageType.FAULT, result.getType()); assertEquals(f.getClassname(), ((Fault) result.getResponse()).getClassname()); } //@Test public void testMessageFromClientCreator() { System.out.println("MessageFromClient.createFromJson"); String uuid = UUID.randomUUID().toString(); String resultJS = getJson(new Result(6)); String mapResultJS = getJson(destination.getMapResult()); String operation = "methodWithResult"; String json = String.format("{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":[\"%s\",\"%s\"],\"%s\":[%s,%s]}", Constants.Message.ID, uuid, Constants.Message.DATASERVICE, PojoDataService.class.getName(), Constants.Message.OPERATION, operation, Constants.Message.ARGUMENTNAMES, "r", "m", Constants.Message.ARGUMENTS, resultJS, mapResultJS); MessageFromClient result = MessageFromClient.createFromJson(json); assertEquals(uuid, result.getId()); assertEquals(PojoDataService.class.getName(), result.getDataService()); assertEquals(operation, result.getOperation()); List<String> parameters = result.getParameters(); assertEquals(resultJS, parameters.get(0)); assertEquals(mapResultJS, parameters.get(1)); } //@Test public void testLocale() { Class clazz = OcelotServices.class; try (Session wssession = createAndGetSession()) { // Par default la locale est US String methodName = "getLocale"; System.out.println(methodName); MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertThat(messageToClient.getType()).isEqualTo(MessageType.RESULT); Object result = messageToClient.getResponse(); assertThat(result).isEqualTo("{\"country\":\"US\",\"language\":\"en\"}"); methodName = "getLocaleHello"; System.out.println(methodName); messageToClient = getMessageToClientAfterSendInSession(wssession, EJBDataService.class.getName(), methodName, getJson("hhfrancois")); assertThat(messageToClient.getType()).isEqualTo(MessageType.RESULT); result = messageToClient.getResponse(); assertThat(result).isEqualTo("\"Hello hhfrancois\""); // On change pour le francais methodName = "setLocale"; System.out.println(methodName); messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, "{\"country\":\"FR\",\"language\":\"fr\"}"); assertThat(messageToClient.getType()).isEqualTo(MessageType.RESULT); methodName = "getLocale"; System.out.println(methodName); messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertThat(messageToClient.getType()).isEqualTo(MessageType.RESULT); result = messageToClient.getResponse(); assertThat(result).isEqualTo("{\"country\":\"FR\",\"language\":\"fr\"}"); methodName = "getLocaleHello"; System.out.println(methodName); messageToClient = getMessageToClientAfterSendInSession(wssession, EJBDataService.class.getName(), methodName, getJson("hhfrancois")); assertThat(messageToClient.getType()).isEqualTo(MessageType.RESULT); result = messageToClient.getResponse(); assertThat(result).isEqualTo("\"Bonjour hhfrancois\""); } catch (IOException exception) { } try (Session wssession = createAndGetSession()) { String methodName = "getLocale"; System.out.println(methodName); MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertThat(messageToClient.getType()).isEqualTo(MessageType.RESULT); Object result = messageToClient.getResponse(); assertThat(result).isEqualTo("{\"country\":\"US\",\"language\":\"en\"}"); } catch (IOException exception) { } } //@Test public void testMethodUnknow() { Class clazz = PojoDataService.class; String methodName = "getUnknownMethod"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.FAULT, messageToClient.getType()); Object fault = messageToClient.getResponse(); assertNotNull(fault); } catch (IOException exception) { } } //@Test public void testMethodNoResult() { Class clazz = PojoDataService.class; String methodName = "getVoid"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); assertEquals("null", messageToClient.getResponse()); } catch (IOException exception) { } } //@Test public void testGetString() { Class clazz = PojoDataService.class; String methodName = "getString"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getString()), result); } catch (IOException exception) { } } //@Test public void testGetNum() { Class clazz = PojoDataService.class; String methodName = "getNum"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getNum()), result); } catch (IOException exception) { } } //@Test public void testGetNumber() { Class clazz = PojoDataService.class; String methodName = "getNumber"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getNumber()), result); } catch (IOException exception) { } } //@Test public void testGetBool() { Class clazz = PojoDataService.class; String methodName = "getBool"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getBool()), result); } catch (IOException exception) { } } //@Test public void testGetBoolean() { Class clazz = PojoDataService.class; String methodName = "getBoolean"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getBoolean()), result); } catch (IOException exception) { } } //@Test public void testGetDate() { System.out.println("getDate"); final Date before = new Date(); System.out.println("BEFORE = " + before.getTime()); try (Session wssession = createAndGetSession()) { Thread.sleep(1000); MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, PojoDataService.class.getName(), "getDate"); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertNotNull(result); Date res = new Date(Long.parseLong(result.toString())); System.out.println("RES = " + res.getTime()); assertTrue(before.before(res)); Thread.sleep(1000); Date after = new Date(); System.out.println("AFTER = " + after.getTime()); assertTrue(after.after(res)); } catch (IOException exception) { } catch (InterruptedException ex) { fail(ex.getMessage()); } } //@Test public void testGetResult() { Class clazz = PojoDataService.class; String methodName = "getResult"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getResult()), result); } catch (IOException exception) { } } //@Test public void testGetCollectionInteger() { Class clazz = PojoDataService.class; String methodName = "getCollectionInteger"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getCollectionInteger()), result); } catch (IOException exception) { } } //@Test public void testGetCollectionResult() { Class clazz = PojoDataService.class; String methodName = "getCollectionResult"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getCollectionResult()), result); } catch (IOException exception) { } } //@Test public void testGetCollectionOfCollectionResult() { Class clazz = PojoDataService.class; String methodName = "getCollectionOfCollectionResult"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getCollectionOfCollectionResult()), result); } catch (IOException exception) { } } //@Test public void testGetMapResult() { Class clazz = PojoDataService.class; String methodName = "getMapResult"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getMapResult()), result); } catch (IOException exception) { } } //@Test public void testMethodWithNum() { Class clazz = PojoDataService.class; String methodName = "methodWithNum"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(1)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithNum(1)), result); } catch (IOException exception) { } } //@Test public void testMethodWithNumber() { Class clazz = PojoDataService.class; String methodName = "methodWithNumber"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(2)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithNumber(2)), result); } catch (IOException exception) { } } //@Test public void testMethodWithBool() { Class clazz = PojoDataService.class; String methodName = "methodWithBool"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(true)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithBool(true)), result); } catch (IOException exception) { } } //@Test public void testMethodWithBoolean() { Class clazz = PojoDataService.class; String methodName = "methodWithBoolean"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(false)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithBoolean(false)), result); } catch (IOException exception) { } } //@Test public void testMethodWithDate() { Class clazz = PojoDataService.class; String methodName = "methodWithDate"; System.out.println(methodName); Object arg = new Date(); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithDate((Date) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithResult() { Class clazz = PojoDataService.class; String methodName = "methodWithResult"; System.out.println(methodName); Object arg = new Result(6); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithResult((Result) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithArrayInteger() { Class clazz = PojoDataService.class; String methodName = "methodWithArrayInteger"; System.out.println(methodName); Object arg = new Integer[]{1, 2}; try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithArrayInteger((Integer[]) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithCollectionInteger() { Class clazz = PojoDataService.class; String methodName = "methodWithCollectionInteger"; System.out.println(methodName); Object arg = destination.getCollectionInteger(); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithCollectionInteger((Collection<Integer>) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithArrayResult() { Class clazz = PojoDataService.class; String methodName = "methodWithArrayResult"; System.out.println(methodName); Object arg = new Result[]{new Result(1), new Result(2)}; try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithArrayResult((Result[]) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithCollectionResult() { Class clazz = PojoDataService.class; String methodName = "methodWithCollectionResult"; System.out.println(methodName); Object arg = destination.getCollectionResult(); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithCollectionResult((Collection<Result>) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithMapResult() { Class clazz = PojoDataService.class; String methodName = "methodWithMapResult"; System.out.println(methodName); Object arg = destination.getMapResult(); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithMapResult((Map<String, Result>) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithCollectionOfCollectionResult() { Class clazz = PojoDataService.class; String methodName = "methodWithCollectionOfCollectionResult"; System.out.println(methodName); Object arg = destination.getCollectionOfCollectionResult(); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithCollectionOfCollectionResult((Collection<Collection<Result>>) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithManyParameters() { Class clazz = PojoDataService.class; String methodName = "methodWithManyParameters"; System.out.println(methodName); Collection<String> cl = new ArrayList<>(); cl.add("foo"); cl.add("foo"); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson("foo"), getJson(5), getJson(new Result(3)), getJson(cl)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithManyParameters("foo", 5, new Result(3), cl)), result); } catch (IOException exception) { } } //@Test public void testMethodThatThrowException() { Class clazz = PojoDataService.class; String methodName = "methodThatThrowException"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.FAULT, messageToClient.getType()); Fault fault = (Fault) messageToClient.getResponse(); assertEquals(MethodException.class.getName(), fault.getClassname()); } catch (IOException exception) { } } //@Test public void testMethodWithAlmostSameSignature1() { Class clazz = PojoDataService.class; String methodName = "methodWithAlmostSameSignature"; System.out.println(methodName + "(int)"); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(5)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithAlmostSameSignature(5)), result); } catch (IOException exception) { } } //@Test public void testMethodWithAlmostSameSignature2() { Class clazz = PojoDataService.class; String methodName = "methodWithAlmostSameSignature"; System.out.println(methodName + "(string)"); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson("foo")); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithAlmostSameSignature("foo")), result); } catch (IOException exception) { } } final int NB_SIMUL_METHODS = 500; //@Test public void testCallMultiMethodsMultiSessions() { int nb = NB_SIMUL_METHODS; System.out.println("call" + nb + "MethodsMultiSession"); ExecutorService executorService = Executors.newFixedThreadPool(nb); final List<Session> sessions = new ArrayList<>(); try { final Class clazz = EJBDataService.class; final String methodName = "getValue"; long t0 = System.currentTimeMillis(); final CountDownLatch lock = new CountDownLatch(nb); for (int i = 0; i < nb; i++) { Session session = OcelotTest.createAndGetSession(); sessions.add(session); session.addMessageHandler(new CountDownMessageHandler(lock)); executorService.execute(new TestThread(clazz, methodName, session)); } boolean await = lock.await(30L * nb, TimeUnit.MILLISECONDS); long t1 = System.currentTimeMillis(); assertTrue("Timeout. waiting " + (t1 - t0) + " ms. Remain " + lock.getCount() + "/" + nb + " msgs", await); } catch (InterruptedException ex) { fail(ex.getMessage()); } finally { for (Session session : sessions) { try { session.close(); } catch (IOException ex) { } } executorService.shutdown(); } } //@Test public void testCallMultiMethodsMonoSessions() { int nb = NB_SIMUL_METHODS; System.out.println("call" + nb + "MethodsMonoSession"); ExecutorService executorService = Executors.newFixedThreadPool(nb); try (Session session = OcelotTest.createAndGetSession()) { final CountDownLatch lock = new CountDownLatch(nb); CountDownMessageHandler messageHandler = new CountDownMessageHandler(lock); session.addMessageHandler(messageHandler); final Class clazz = EJBDataService.class; final String methodName = "getValue"; long t0 = System.currentTimeMillis(); for (int i = 0; i < nb; i++) { executorService.execute(new TestThread(clazz, methodName, session)); } boolean await = lock.await(10L * nb, TimeUnit.MILLISECONDS); long t1 = System.currentTimeMillis(); assertTrue("Timeout. waiting " + (t1 - t0) + " ms. Remain " + lock.getCount() + " msgs", await); } catch (IOException | InterruptedException ex) { fail(ex.getMessage()); } finally { executorService.shutdown(); } } private class TestThread implements Runnable { private final Class clazz; private final String methodName; private final Session wsSession; public TestThread(Class clazz, String methodName, Session wsSession) { this.clazz = clazz; this.methodName = methodName; this.wsSession = wsSession; } @Override public void run() { checkMessageAfterSendInSession(wsSession, clazz.getName(), methodName); } } /** * Test d'envoi d'un message generant un message de suppression de cache */ //@Test public void testSendRemoveCacheMessage() { System.out.println("sendRemoveCacheMessage"); final String topic = "ocelot-cleancache"; System.out.println("Enregistrement au Topic '" + topic + "'"); Class clazz = OcelotServices.class; String methodName = "subscribe"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(topic)); assertEquals(MessageType.RESULT, messageToClient.getType()); long t0 = System.currentTimeMillis(); MessageFromClient messageFromClient = getMessageFromClient(EJBDataService.class, "generateCleanCacheMessage", "\"a\",\"r\"", getJson(""), getJson(new Result(5))); CountDownLatch lock = new CountDownLatch(2); CountDownMessageHandler messageHandler = new CountDownMessageHandler(lock); wssession.addMessageHandler(messageHandler); // send wssession.getAsyncRemote().sendText(messageFromClient.toJson()); // wait le delock ou timeout boolean await = lock.await(TIMEOUT, TimeUnit.MILLISECONDS); long t1 = System.currentTimeMillis(); assertTrue("Timeout. waiting " + (t1 - t0) + " ms. Remain " + lock.getCount() + "/2 msgs", await); wssession.removeMessageHandler(messageHandler); } catch (InterruptedException | IOException ex) { fail(ex.getMessage()); } } //@Test public void testSendMessageToTopic() { System.out.println("sendMessageToTopic"); final String topic = "mytopic"; System.out.println("Enregistrement au Topic '" + topic + "'"); Class clazz = OcelotServices.class; String methodName = "subscribe"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(topic)); assertEquals(MessageType.RESULT, messageToClient.getType()); long t0 = System.currentTimeMillis(); // Thread.sleep(TIMEOUT); int nbMsg = 10; CountDownLatch lock = new CountDownLatch(nbMsg); CountDownMessageHandler messageHandler = new CountDownMessageHandler(topic, lock); wssession.addMessageHandler(messageHandler); MessageToClient toTopic = new MessageToClient(); toTopic.setId(topic); for (int i = 0; i < nbMsg; i++) { System.out.println("Envois d'un message au Topic '" + topic + "'"); toTopic.setResponse(new Result(i)); wsEvent.fire(toTopic); } boolean await = lock.await(TIMEOUT, TimeUnit.MILLISECONDS); long t1 = System.currentTimeMillis(); assertTrue("Timeout. waiting " + (t1 - t0) + " ms. Remain " + lock.getCount() + "/" + nbMsg + " msgs", await); wssession.removeMessageHandler(messageHandler); } catch (InterruptedException | IOException ex) { fail(ex.getMessage()); } } }
package bisq.core.trade; import bisq.core.btc.wallet.BtcWalletService; import bisq.core.dao.DaoFacade; import bisq.core.offer.Offer; import bisq.core.support.SupportType; import bisq.core.support.dispute.Dispute; import bisq.core.util.validation.RegexValidatorFactory; import bisq.network.p2p.NodeAddress; import bisq.common.config.Config; import bisq.common.util.Tuple3; import org.bitcoinj.core.Address; import org.bitcoinj.core.Coin; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.core.TransactionOutput; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; @Slf4j public class TradeDataValidation { public static void validateDonationAddress(String addressAsString, DaoFacade daoFacade) throws AddressException { validateDonationAddress(null, addressAsString, daoFacade); } public static void validateNodeAddress(Dispute dispute, NodeAddress nodeAddress, Config config) throws NodeAddressException { if (!config.useLocalhostForP2P && !RegexValidatorFactory.onionAddressRegexValidator().validate(nodeAddress.getFullAddress()).isValid) { String msg = "Node address " + nodeAddress.getFullAddress() + " at dispute with trade ID " + dispute.getShortTradeId() + " is not a valid address"; log.error(msg); throw new NodeAddressException(dispute, msg); } } public static void validateDonationAddress(@Nullable Dispute dispute, String addressAsString, DaoFacade daoFacade) throws AddressException { if (addressAsString == null) { log.debug("address is null at validateDonationAddress. This is expected in case of an not updated trader."); return; } Set<String> allPastParamValues = daoFacade.getAllDonationAddresses(); if (!allPastParamValues.contains(addressAsString)) { String errorMsg = "Donation address is not a valid DAO donation address." + "\nAddress used in the dispute: " + addressAsString + "\nAll DAO param donation addresses:" + allPastParamValues; log.error(errorMsg); throw new AddressException(dispute, errorMsg); } } public static void testIfAnyDisputeTriedReplay(List<Dispute> disputeList, Consumer<DisputeReplayException> exceptionHandler) { var tuple = getTestReplayHashMaps(disputeList); Map<String, Set<String>> disputesPerTradeId = tuple.first; Map<String, Set<String>> disputesPerDelayedPayoutTxId = tuple.second; Map<String, Set<String>> disputesPerDepositTxId = tuple.third; disputeList.forEach(disputeToTest -> { try { testIfDisputeTriesReplay(disputeToTest, disputesPerTradeId, disputesPerDelayedPayoutTxId, disputesPerDepositTxId); } catch (DisputeReplayException e) { exceptionHandler.accept(e); } }); } public static void testIfDisputeTriesReplay(Dispute dispute, List<Dispute> disputeList) throws DisputeReplayException { var tuple = TradeDataValidation.getTestReplayHashMaps(disputeList); Map<String, Set<String>> disputesPerTradeId = tuple.first; Map<String, Set<String>> disputesPerDelayedPayoutTxId = tuple.second; Map<String, Set<String>> disputesPerDepositTxId = tuple.third; testIfDisputeTriesReplay(dispute, disputesPerTradeId, disputesPerDelayedPayoutTxId, disputesPerDepositTxId); } private static Tuple3<Map<String, Set<String>>, Map<String, Set<String>>, Map<String, Set<String>>> getTestReplayHashMaps( List<Dispute> disputeList) { Map<String, Set<String>> disputesPerTradeId = new HashMap<>(); Map<String, Set<String>> disputesPerDelayedPayoutTxId = new HashMap<>(); Map<String, Set<String>> disputesPerDepositTxId = new HashMap<>(); disputeList.forEach(dispute -> { String uid = dispute.getUid(); String tradeId = dispute.getTradeId(); disputesPerTradeId.putIfAbsent(tradeId, new HashSet<>()); Set<String> set = disputesPerTradeId.get(tradeId); set.add(uid); String delayedPayoutTxId = dispute.getDelayedPayoutTxId(); if (delayedPayoutTxId != null) { disputesPerDelayedPayoutTxId.putIfAbsent(delayedPayoutTxId, new HashSet<>()); set = disputesPerDelayedPayoutTxId.get(delayedPayoutTxId); set.add(uid); } String depositTxId = dispute.getDepositTxId(); if (depositTxId != null) { disputesPerDepositTxId.putIfAbsent(depositTxId, new HashSet<>()); set = disputesPerDepositTxId.get(depositTxId); set.add(uid); } }); return new Tuple3<>(disputesPerTradeId, disputesPerDelayedPayoutTxId, disputesPerDepositTxId); } private static void testIfDisputeTriesReplay(Dispute disputeToTest, Map<String, Set<String>> disputesPerTradeId, Map<String, Set<String>> disputesPerDelayedPayoutTxId, Map<String, Set<String>> disputesPerDepositTxId) throws DisputeReplayException { try { String disputeToTestTradeId = disputeToTest.getTradeId(); String disputeToTestDelayedPayoutTxId = disputeToTest.getDelayedPayoutTxId(); String disputeToTestDepositTxId = disputeToTest.getDepositTxId(); String disputeToTestUid = disputeToTest.getUid(); // For pre v1.4.0 we do not get the delayed payout tx sent in mediation cases but in refund agent case we do. // So until all users have updated to 1.4.0 we only check in refund agent case. With 1.4.0 we send the // delayed payout tx also in mediation cases and that if check can be removed. if (disputeToTest.getSupportType() == SupportType.REFUND) { checkNotNull(disputeToTestDelayedPayoutTxId, "Delayed payout transaction ID is null. " + "Trade ID: " + disputeToTestTradeId); } checkNotNull(disputeToTestDepositTxId, "depositTxId must not be null. Trade ID: " + disputeToTestTradeId); checkNotNull(disputeToTestUid, "agentsUid must not be null. Trade ID: " + disputeToTestTradeId); checkArgument(disputesPerTradeId.get(disputeToTestTradeId).size() <= 2, "We found more then 2 disputes with the same trade ID. " + "Trade ID: " + disputeToTestTradeId); if (!disputesPerDelayedPayoutTxId.isEmpty()) { checkArgument(disputesPerDelayedPayoutTxId.get(disputeToTestDelayedPayoutTxId).size() <= 2, "We found more then 2 disputes with the same delayedPayoutTxId. " + "Trade ID: " + disputeToTestTradeId); } if (!disputesPerDepositTxId.isEmpty()) { checkArgument(disputesPerDepositTxId.get(disputeToTestDepositTxId).size() <= 2, "We found more then 2 disputes with the same depositTxId. " + "Trade ID: " + disputeToTestTradeId); } } catch (IllegalArgumentException e) { throw new DisputeReplayException(disputeToTest, e.getMessage()); } catch (NullPointerException e) { throw new DisputeReplayException(disputeToTest, e.toString()); } } public static void validateDelayedPayoutTx(Trade trade, Transaction delayedPayoutTx, DaoFacade daoFacade, BtcWalletService btcWalletService) throws AddressException, MissingTxException, InvalidTxException, InvalidLockTimeException, InvalidAmountException { validateDelayedPayoutTx(trade, delayedPayoutTx, null, daoFacade, btcWalletService, null); } public static void validateDelayedPayoutTx(Trade trade, Transaction delayedPayoutTx, @Nullable Dispute dispute, DaoFacade daoFacade, BtcWalletService btcWalletService) throws AddressException, MissingTxException, InvalidTxException, InvalidLockTimeException, InvalidAmountException { validateDelayedPayoutTx(trade, delayedPayoutTx, dispute, daoFacade, btcWalletService, null); } public static void validateDelayedPayoutTx(Trade trade, Transaction delayedPayoutTx, DaoFacade daoFacade, BtcWalletService btcWalletService, @Nullable Consumer<String> addressConsumer) throws AddressException, MissingTxException, InvalidTxException, InvalidLockTimeException, InvalidAmountException { validateDelayedPayoutTx(trade, delayedPayoutTx, null, daoFacade, btcWalletService, addressConsumer); } public static void validateDelayedPayoutTx(Trade trade, Transaction delayedPayoutTx, @Nullable Dispute dispute, DaoFacade daoFacade, BtcWalletService btcWalletService, @Nullable Consumer<String> addressConsumer) throws AddressException, MissingTxException, InvalidTxException, InvalidLockTimeException, InvalidAmountException { String errorMsg; if (delayedPayoutTx == null) { errorMsg = "DelayedPayoutTx must not be null"; log.error(errorMsg); throw new MissingTxException("DelayedPayoutTx must not be null"); } // Validate tx structure if (delayedPayoutTx.getInputs().size() != 1) { errorMsg = "Number of delayedPayoutTx inputs must be 1"; log.error(errorMsg); log.error(delayedPayoutTx.toString()); throw new InvalidTxException(errorMsg); } if (delayedPayoutTx.getOutputs().size() != 1) { errorMsg = "Number of delayedPayoutTx outputs must be 1"; log.error(errorMsg); log.error(delayedPayoutTx.toString()); throw new InvalidTxException(errorMsg); } // connectedOutput is null and input.getValue() is null at that point as the tx is not committed to the wallet // yet. So we cannot check that the input matches but we did the amount check earlier in the trade protocol. // Validate lock time if (delayedPayoutTx.getLockTime() != trade.getLockTime()) { errorMsg = "delayedPayoutTx.getLockTime() must match trade.getLockTime()"; log.error(errorMsg); log.error(delayedPayoutTx.toString()); throw new InvalidLockTimeException(errorMsg); } // Validate seq num if (delayedPayoutTx.getInput(0).getSequenceNumber() != TransactionInput.NO_SEQUENCE - 1) { errorMsg = "Sequence number must be 0xFFFFFFFE"; log.error(errorMsg); log.error(delayedPayoutTx.toString()); throw new InvalidLockTimeException(errorMsg); } // Check amount TransactionOutput output = delayedPayoutTx.getOutput(0); Offer offer = checkNotNull(trade.getOffer()); Coin msOutputAmount = offer.getBuyerSecurityDeposit() .add(offer.getSellerSecurityDeposit()) .add(checkNotNull(trade.getTradeAmount())); if (!output.getValue().equals(msOutputAmount)) { errorMsg = "Output value of deposit tx and delayed payout tx is not matching. Output: " + output + " / msOutputAmount: " + msOutputAmount; log.error(errorMsg); log.error(delayedPayoutTx.toString()); throw new InvalidAmountException(errorMsg); } NetworkParameters params = btcWalletService.getParams(); Address address = output.getScriptPubKey().getToAddress(params); if (address == null) { errorMsg = "Donation address cannot be resolved (not of type P2PK nor P2SH nor P2WH). Output: " + output; log.error(errorMsg); log.error(delayedPayoutTx.toString()); throw new AddressException(dispute, errorMsg); } String addressAsString = address.toString(); if (addressConsumer != null) { addressConsumer.accept(addressAsString); } validateDonationAddress(addressAsString, daoFacade); if (dispute != null) { // Verify that address in the dispute matches the one in the trade. String donationAddressOfDelayedPayoutTx = dispute.getDonationAddressOfDelayedPayoutTx(); // Old clients don't have it set yet. Can be removed after a forced update if (donationAddressOfDelayedPayoutTx != null) { checkArgument(addressAsString.equals(donationAddressOfDelayedPayoutTx), "donationAddressOfDelayedPayoutTx from dispute does not match address from delayed payout tx"); } } } public static void validatePayoutTxInput(Transaction depositTx, Transaction delayedPayoutTx) throws InvalidInputException { TransactionInput input = delayedPayoutTx.getInput(0); checkNotNull(input, "delayedPayoutTx.getInput(0) must not be null"); // input.getConnectedOutput() is null as the tx is not committed at that point TransactionOutPoint outpoint = input.getOutpoint(); if (!outpoint.getHash().toString().equals(depositTx.getTxId().toString()) || outpoint.getIndex() != 0) { throw new InvalidInputException("Input of delayed payout transaction does not point to output of deposit tx.\n" + "Delayed payout tx=" + delayedPayoutTx + "\n" + "Deposit tx=" + depositTx); } } // Exceptions public static class ValidationException extends Exception { @Nullable @Getter private final Dispute dispute; ValidationException(String msg) { this(null, msg); } ValidationException(@Nullable Dispute dispute, String msg) { super(msg); this.dispute = dispute; } } public static class AddressException extends ValidationException { AddressException(@Nullable Dispute dispute, String msg) { super(dispute, msg); } } public static class MissingTxException extends ValidationException { MissingTxException(String msg) { super(msg); } } public static class InvalidTxException extends ValidationException { InvalidTxException(String msg) { super(msg); } } public static class InvalidAmountException extends ValidationException { InvalidAmountException(String msg) { super(msg); } } public static class InvalidLockTimeException extends ValidationException { InvalidLockTimeException(String msg) { super(msg); } } public static class InvalidInputException extends ValidationException { InvalidInputException(String msg) { super(msg); } } public static class DisputeReplayException extends ValidationException { DisputeReplayException(Dispute dispute, String msg) { super(dispute, msg); } } public static class NodeAddressException extends ValidationException { NodeAddressException(Dispute dispute, String msg) { super(dispute, msg); } } }
package mp400; /** * * @author akeegazooka */ public class PPMConvolve { PixMask mask; PixMask normalMask; PPMFile imageData; public PPMFile convolve(PixMask inMask, PPMFile inImage, String operation) { return imageData; } public PixMask normalizeMask(PixMask inMask) { PixMask normalMask = new PixMask(inMask.kernel); double runningTotal = 0; for(int mX = 0;mX<inMask.dimensions.getX();mX++) { for(int mY = 0;mY<inMask.dimensions.getY();mY++) { runningTotal+=inMask.kernel[mX][mY]; } } for(int nX=0;nX<inMask.dimensions.getX();nX++) { for(int nY=0;nY<inMask.dimensions.getY();nY++) { normalMask.kernel[nX][nY] = inMask.kernel[nX][nY] / runningTotal; } } return normalMask; } }
package timeseries.model.arima; import com.google.common.collect.EvictingQueue; import math.operations.DoubleFunctions; import math.stats.distributions.Distribution; import math.stats.distributions.Normal; import timeseries.TimePeriod; import timeseries.TimeSeries; import timeseries.operators.LagPolynomial; import java.util.PrimitiveIterator; import java.util.Queue; import java.util.function.DoubleSupplier; /** * Represents an indefinite, observation generating ARIMA process. * * @author Jacob Rachiele * Oct. 06, 2017 */ public class ArimaProcess implements DoubleSupplier, PrimitiveIterator.OfDouble { private final ArimaCoefficients coefficients; private final Distribution distribution; private final TimePeriod period; private final TimePeriod seasonalCycle; private final LagPolynomial maPoly; private final LagPolynomial arPoly; private final LagPolynomial diffPoly; private final Queue<Double> diffSeries; private final Queue<Double> series; private final Queue<Double> errors; private ArimaProcess(Builder builder) { this.coefficients = builder.coefficients; this.distribution = builder.distribution; this.period = builder.period; this.seasonalCycle = builder.seasonalCycle; int seasonalFrequency = (int) builder.period.frequencyPer(builder.seasonalCycle); double[] arSarCoeffs = ArimaCoefficients.expandArCoefficients(coefficients.arCoeffs(), coefficients.seasonalARCoeffs(), seasonalFrequency); double[] maSmaCoeffs = ArimaCoefficients.expandMaCoefficients(coefficients.maCoeffs(), coefficients.seasonalMACoeffs(), seasonalFrequency); this.errors = EvictingQueue.create(maSmaCoeffs.length); this.diffSeries = EvictingQueue.create(arSarCoeffs.length); this.series = EvictingQueue.create(coefficients.d() + coefficients.D() * seasonalFrequency); this.maPoly = LagPolynomial.movingAverage(maSmaCoeffs); this.arPoly = LagPolynomial.autoRegressive(arSarCoeffs); this.diffPoly = LagPolynomial.differences(coefficients.d()) .times(LagPolynomial.seasonalDifferences(seasonalFrequency, coefficients.D())); } @Override public boolean hasNext() { return true; } @Override public double nextDouble() { return getAsDouble(); } /** * Generate the next observation from this ARIMA process. * @return the next observation from this ARIMA process. */ @Override public synchronized double getAsDouble() { double error = distribution.rand(); double newValue = error; double[] series = getSeries(); double[] errors = getErrors(); double[] diffSeries = getDiffSeries(); int p = diffSeries.length; int q = errors.length; int d = series.length; newValue += (d == 0)? coefficients.intercept() : coefficients.drift(); newValue += arPoly.solve(diffSeries, p); newValue += maPoly.solve(errors, q); this.diffSeries.add(newValue); newValue += diffPoly.solve(series, d); this.series.add(newValue); this.errors.add(error); return newValue; } /** * Generate and return the next n values of this process. * @param n the number of values to generate. * @return the next n values of this process. */ public double[] getNext(int n) { double[] next = new double[n]; for (int i = 0; i < n; i++) { next[i] = getAsDouble(); } return next; } public TimeSeries toSeries(int size) { return TimeSeries.from(this.period, getNext(size)); } double[] getErrors() { return DoubleFunctions.arrayFrom(this.errors); } double[] getSeries() { return DoubleFunctions.arrayFrom(this.series); } double[] getDiffSeries() { return DoubleFunctions.arrayFrom(this.diffSeries); } public ArimaProcess startOver() { return builder() .setCoefficients(this.coefficients) .setDistribution(this.distribution) .setPeriod(this.period) .setSeasonalCycle(this.seasonalCycle) .build(); } public static Builder builder() { return new Builder(); } /** * An ARIMA simulation builder. */ public static class Builder { private ArimaCoefficients coefficients = ArimaCoefficients.builder().build(); private Distribution distribution = new Normal(); private TimePeriod period = (coefficients.isSeasonal()) ? TimePeriod.oneMonth() : TimePeriod.oneYear(); private TimePeriod seasonalCycle = TimePeriod.oneYear(); private boolean periodSet = false; /** * Set the model coefficients to be used in simulating the ARIMA model. * * @param coefficients the model coefficients for the simulation. * @return this builder. */ public Builder setCoefficients(ArimaCoefficients coefficients) { if (coefficients == null) { throw new NullPointerException("The model coefficients cannot be null."); } this.coefficients = coefficients; if (!periodSet) { this.period = (coefficients.isSeasonal()) ? TimePeriod.oneMonth() : TimePeriod.oneYear(); } return this; } /** * Set the probability distribution to draw the ARIMA process random errors from. * * @param distribution the probability distribution to draw the random errors from. * @return this builder. */ public Builder setDistribution(Distribution distribution) { if (distribution == null) { throw new NullPointerException("The distribution cannot be null."); } this.distribution = distribution; return this; } /** * Set the time period between simulated observations. The default is one year for * non-seasonal model coefficients and one month for seasonal model coefficients. * * @param period the time period between simulated observations. * @return this builder. */ public Builder setPeriod(TimePeriod period) { if (period == null) { throw new NullPointerException("The time period cannot be null."); } this.periodSet = true; this.period = period; return this; } /** * Set the time cycle at which the seasonal pattern of the simulated time series repeats. This defaults * to one year. * * @param seasonalCycle the time cycle at which the seasonal pattern of the simulated time series repeats. * @return this builder. */ public Builder setSeasonalCycle(TimePeriod seasonalCycle) { if (seasonalCycle == null) { throw new NullPointerException("The seasonal cycle cannot be null."); } this.seasonalCycle = seasonalCycle; return this; } /** * Construct and return a new fully built and immutable ArimaSimulation object. * * @return a new fully built and immutable ArimaSimulation object. */ public ArimaProcess build() { return new ArimaProcess(this); } } }
package de.lmu.ifi.dbs.elki.visualization.visualizers.visunproj; import java.util.Collection; import java.util.List; import org.apache.batik.util.SVGConstants; import org.w3c.dom.Element; import org.w3c.dom.events.Event; import org.w3c.dom.events.EventListener; import org.w3c.dom.events.EventTarget; import de.lmu.ifi.dbs.elki.data.Cluster; import de.lmu.ifi.dbs.elki.data.Clustering; import de.lmu.ifi.dbs.elki.data.model.Model; import de.lmu.ifi.dbs.elki.result.HierarchicalResult; import de.lmu.ifi.dbs.elki.result.Result; import de.lmu.ifi.dbs.elki.result.ResultUtil; import de.lmu.ifi.dbs.elki.visualization.VisualizationTask; import de.lmu.ifi.dbs.elki.visualization.style.ClusterStylingPolicy; import de.lmu.ifi.dbs.elki.visualization.style.StyleLibrary; import de.lmu.ifi.dbs.elki.visualization.style.StylingPolicy; import de.lmu.ifi.dbs.elki.visualization.style.marker.MarkerLibrary; import de.lmu.ifi.dbs.elki.visualization.svg.SVGButton; import de.lmu.ifi.dbs.elki.visualization.svg.SVGPlot; import de.lmu.ifi.dbs.elki.visualization.svg.SVGUtil; import de.lmu.ifi.dbs.elki.visualization.visualizers.AbstractVisFactory; import de.lmu.ifi.dbs.elki.visualization.visualizers.AbstractVisualization; import de.lmu.ifi.dbs.elki.visualization.visualizers.Visualization; /** * Visualizer, displaying the key for a clustering. * * @author Erich Schubert * * @apiviz.has Clustering oneway - - visualizes */ public class KeyVisualization extends AbstractVisualization { /** * Name for this visualizer. */ private static final String NAME = "Cluster Key"; /** * Clustering to display */ private Clustering<Model> clustering; /** * Constructor. * * @param task Visualization task */ public KeyVisualization(VisualizationTask task) { super(task); this.clustering = task.getResult(); context.addResultListener(this); } @Override public void destroy() { context.removeResultListener(this); super.destroy(); } @Override public void resultChanged(Result current) { super.resultChanged(current); if(current == context.getStyleResult()) { incrementalRedraw(); } } @Override protected void redraw() { SVGPlot svgp = task.getPlot(); final List<Cluster<Model>> allcs = clustering.getAllClusters(); StyleLibrary style = context.getStyleLibrary(); MarkerLibrary ml = style.markers(); layer = svgp.svgElement(SVGConstants.SVG_G_TAG); // Add a label for the clustering. { Element label = svgp.svgText(0.1, 0.7, clustering.getLongName()); label.setAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE, "font-size: 0.4; fill: "+style.getTextColor(StyleLibrary.DEFAULT)); layer.appendChild(label); } // TODO: multi-column layout! int i = 0; for(Cluster<Model> c : allcs) { ml.useMarker(svgp, layer, 0.3, i + 1.5, i, 0.3); Element label = svgp.svgText(0.7, i + 1.7, c.getNameAutomatic()); label.setAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE, "font-size: 0.6; fill: "+style.getTextColor(StyleLibrary.DEFAULT)); layer.appendChild(label); i++; } // Add a button to set style policy { StylingPolicy sp = context.getStyleResult().getStylingPolicy(); if(sp instanceof ClusterStylingPolicy && ((ClusterStylingPolicy) sp).getClustering() == clustering) { // Don't show the button when active. May confuse people more than the disappearing button // SVGButton button = new SVGButton(.1, i + 1.1, 3.8, .7, .2); // button.setTitle("Active style", "darkgray"); // layer.appendChild(button.render(svgp)); } else { SVGButton button = new SVGButton(.1, i + 1.1, 3.8, .7, .2); button.setTitle("Set style", "black"); Element elem = button.render(svgp); // Attach listener EventTarget etr = (EventTarget) elem; etr.addEventListener(SVGConstants.SVG_CLICK_EVENT_TYPE, new EventListener() { @Override public void handleEvent(Event evt) { setStylePolicy(); } }, false); layer.appendChild(elem); } } int rows = i + 2; int cols = Math.max(6, (int) (rows * task.getHeight() / task.getWidth())); final double margin = style.getSize(StyleLibrary.MARGIN); final String transform = SVGUtil.makeMarginTransform(task.getWidth(), task.getHeight(), cols, rows, margin / StyleLibrary.SCALE); SVGUtil.setAtt(layer, SVGConstants.SVG_TRANSFORM_ATTRIBUTE, transform); } /** * Trigger a style change. */ protected void setStylePolicy() { context.getStyleResult().setStylingPolicy(new ClusterStylingPolicy(clustering, context.getStyleLibrary())); context.getHierarchy().resultChanged(context.getStyleResult()); } public static class Factory extends AbstractVisFactory { @Override public void processNewResult(HierarchicalResult baseResult, Result newResult) { // Find clusterings we can visualize: Collection<Clustering<?>> clusterings = ResultUtil.filterResults(newResult, Clustering.class); for (Clustering<?> c : clusterings) { if(c.getAllClusters().size() > 0) { final VisualizationTask task = new VisualizationTask(NAME, c, null, this); task.width = 1.0; task.height = 1.0; task.put(VisualizationTask.META_LEVEL, VisualizationTask.LEVEL_STATIC); task.put(VisualizationTask.META_NODETAIL, true); baseResult.getHierarchy().add(c, task); } } } @Override public Visualization makeVisualization(VisualizationTask task) { return new KeyVisualization(task); } @Override public boolean allowThumbnails(VisualizationTask task) { return false; } } }
package com.zyeeda.framework.ws; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; 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.Context; import com.zyeeda.framework.entities.User; import com.zyeeda.framework.ldap.LdapService; import com.zyeeda.framework.managers.UserPersistException; import com.zyeeda.framework.managers.internal.LdapUserManager; import com.zyeeda.framework.sync.UserSyncService; import com.zyeeda.framework.utils.LdapEncryptUtils; import com.zyeeda.framework.viewmodels.UserVo; import com.zyeeda.framework.ws.base.ResourceService; @Path("/users") public class UserService extends ResourceService { public UserService(@Context ServletContext ctx) { super(ctx); } private static String createUserDn(String parent, String id) { return "uid=" + id + "," + parent; } @POST @Path("/{parent:.*}") @Produces("application/json") public User persist(@FormParam("") User user, @PathParam("parent") String parent) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); UserSyncService userSyncService = this.getUserSynchService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); List<User> userList = userMgr.findByName(user.getId()); if (userList != null && userList.size() > 0) { throw new RuntimeException(""); } else { user.setDepartmentName(parent); user.setDeptFullPath(createUserDn(parent, user.getId())); userMgr.persist(user); user = userMgr.findById(user.getDeptFullPath()); userSyncService.persist(user); return user; } } @DELETE @Path("/{id}") public void remove(@PathParam("id") String id) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); userMgr.remove(id); } @PUT @Path("/{id}") @Produces("application/json") public User update(@FormParam("") User user, @PathParam("id") String id) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); UserSyncService userSyncService = this.getUserSynchService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); String uid = id.substring(id.indexOf("=") + 1, id.indexOf(",")); if (!uid.equals(user.getId())) { throw new RuntimeException(""); } else { user.setDeptFullPath(id); userMgr.update(user); user = userMgr.findById(id); userSyncService.update(user); return user; } } @GET @Path("/{id}") @Produces("application/json") public User findById(@PathParam("id") String id) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); return userMgr.findById(id); } @GET @Path("/search/{name}") @Produces("application/json") public List<UserVo> getUserListByName(@PathParam("name") String name) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); return UserService.fillUserListPropertiesToVo(userMgr.findByName(name)); } @GET @Path("/userList/{deptId}") @Produces("application/json") public List<UserVo> getUserListByDepartmentId(@PathParam("deptId") String deptId) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); return UserService.fillUserListPropertiesToVo(userMgr.findByDepartmentId(deptId)); } @PUT @Path("/{id}/update_password") @Produces("application/json") public User updatePassword(@PathParam("id") String id, @FormParam("oldPassword") String oldPassword, @FormParam("newPassword") String newPassword) throws UserPersistException, UnsupportedEncodingException { LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); User u = userMgr.findById(id); System.out.println(" System.out.println(" if (LdapEncryptUtils.md5Encode(oldPassword).equals(u.getPassword())) { if (!LdapEncryptUtils.md5Encode(newPassword).equals(u.getPassword())) { userMgr.updatePassword(id, LdapEncryptUtils.md5Encode(newPassword)); } } else { throw new RuntimeException(""); } return userMgr.findById(id); } @PUT @Path("/{id}/enable") @Produces("application/json") public User enable(@PathParam("id") String id, @FormParam("status") Boolean visible) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); UserSyncService userSyncService = this.getUserSynchService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); userMgr.enable(id); userSyncService.enable(id); return userMgr.findById(id); } @PUT @Path("/{id}/unenable") @Produces("application/json") public User disable(@PathParam("id") String id, @FormParam("status") Boolean visible) throws UserPersistException { LdapService ldapSvc = this.getLdapService(); UserSyncService userSyncService = this.getUserSynchService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); userMgr.disable(id); userSyncService.disable(id); return userMgr.findById(id); } @POST @Path("/{id}") @Produces("application/json") public void uploadPhoto(@Context HttpServletRequest request, @PathParam("id") String id) throws Throwable { InputStream in = request.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int len = 0; while ((len = in.read(b, 0, 1024)) != -1) { baos.write(b, 0, len); } baos.flush(); // byte[] bytes = baos.toByteArray(); LdapService ldapSvc = this.getLdapService(); LdapUserManager userMgr = new LdapUserManager(ldapSvc); User user = new User(); user.setId("china"); // user.setPhoto(bytes); userMgr.update(user); } // private User setVisible(String id, Boolean visible) throws UserPersistException { // LdapService ldapSvc = this.getLdapService(); // UserSyncService userSyncService = this.getUserSynchService(); // LdapUserManager userMgr = new LdapUserManager(ldapSvc); // userMgr.setVisible(visible, id); // userSyncService.enable(id); // return userMgr.findById(id.substring(id.indexOf("=") + 1, id.indexOf(","))); public static UserVo fillUserPropertiesToVo(User user) { UserVo userVo = new UserVo(); userVo.setId(user.getId()); userVo.setType("io"); userVo.setLabel("<a>" + user.getId() + "<a>"); userVo.setCheckName(user.getId()); userVo.setLeaf(true); userVo.setUid(user.getId()); userVo.setDeptFullPath(user.getDeptFullPath()); userVo.setKind("user"); return userVo; } public static UserVo fillUserPropertiesToVo(User user, String type) { UserVo userVo = new UserVo(); userVo.setId(user.getId()); userVo.setType(type); userVo.setLabel("<a>" + user.getId() + "<a>"); userVo.setCheckName(user.getId()); userVo.setLeaf(true); userVo.setUid(user.getId()); userVo.setDeptFullPath(user.getDeptFullPath()); userVo.setKind("user"); return userVo; } public static List<UserVo> fillUserListPropertiesToVo(List<User> userList) { List<UserVo> userVoList = new ArrayList<UserVo>(userList.size()); UserVo userVo = null; for (User user : userList) { userVo = UserService.fillUserPropertiesToVo(user); userVoList.add(userVo); } return userVoList; } public static List<UserVo> fillUserListPropertiesToVo(List<User> userList, String type) { List<UserVo> userVoList = new ArrayList<UserVo>(userList.size()); UserVo userVo = null; for (User user : userList) { userVo = UserService.fillUserPropertiesToVo(user, type); userVoList.add(userVo); } return userVoList; } public static void updateAccount(@QueryParam("username") String username,@QueryParam("password") String password){ } }
package edu.psu.compbio.seqcode.projects.naomi.multiscalesignal; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.distribution.NormalDistribution; import edu.psu.compbio.seqcode.deepseq.experiments.ExptConfig; import edu.psu.compbio.seqcode.genome.GenomeConfig; import edu.psu.compbio.seqcode.genome.location.Region; import edu.psu.compbio.seqcode.projects.naomi.utilities.MapUtility; import edu.psu.compbio.seqcode.projects.seed.SEEDConfig; /** * Segmentation Tree * * Methods for MultiScaleSignalRepresentation * Probabilistic Multiscale Image Segmentation, Vincken et al. IEEE (1997) * * @author naomi yamada * **/ public class SegmentationTree { protected GenomeConfig gconfig; protected ExptConfig econfig; protected SEEDConfig sconfig; protected int numScale; /********************* * Gaussian scale space and window parameters */ final static double DELTA_TAU = 0.5*Math.log(2); final static double MINIMUM_VALUE = Math.pow(10, -100); //arbitrary minimum value; I cannot use Double.MIN_VALUE because it can become zero // I have to determine P_MIN value carefully because P_MIN will substantially affect Gaussian window size final static double P_MIN = Math.pow(10,-3); final static double K_MIN = 1/Math.sqrt(1-Math.exp(-2*DELTA_TAU)); final static double K_N = Math.ceil(K_MIN); /********************* * Linkage parameters */ final static double WEIGHT_I = 1.00; final static double WEIGHT_G = 0.0000001; final static double WEIGHT_M = 1000; public SegmentationTree(GenomeConfig gcon, ExptConfig econ, SEEDConfig scon, int scale){ gconfig = gcon; econfig = econ; sconfig = scon; numScale = scale; } protected Map <Integer, Set<Integer>> buildTree (int currchromBinSize, float[][] gaussianBlur, Map <Integer, Integer> linkageMap, float DImax, int trailingZero, int zeroEnd){ Map<Integer,Set<Integer>> segmentationTree =new HashMap<Integer,Set<Integer>>(); segmentationTree.put(0, linkageMap.keySet()); System.out.println("curr Scale 0 size, printing from segmentationTree "+segmentationTree.get(0).size()); Set<Integer> startingNodes = new TreeSet<Integer>(segmentationTree.get(0)); // Map<Region, HashMap<Integer,Set<Integer>>> segmentationTree = new HashMap<Region, HashMap<Integer, Set<Integer>>>(); /********************* * Matrices parameters */ double[] sigma = new double[numScale]; double[] radius = new double[numScale]; for (int i = 0; i<numScale;i++){ sigma[i] = 1; radius[i] = 1; } for (int n = 1; n<numScale; n++){ double polyCoeffi[] = new double [currchromBinSize]; //first copy from column[1] to column[0];this procedure need to be repeated for each iteration of scale //also copy from column[1] to array to store polynomial coefficient for (int i = 0 ; i<currchromBinSize; i++){ gaussianBlur[i][0]=gaussianBlur[i][1]; if (gaussianBlur[i][1] != 0){ polyCoeffi[i]=gaussianBlur[i][1]; }else{ polyCoeffi[i]=MINIMUM_VALUE; } } //sigma calculation sigma[n] = Math.exp(n*DELTA_TAU); // create normal distribution with mean zero and sigma[n] NormalDistribution normDistribution = new NormalDistribution(0.00,sigma[n]); //take inverse CDF based on the normal distribution using probability double inverseCDF = normDistribution.inverseCumulativeProbability(P_MIN); int windowSize = (int) (-Math.round(inverseCDF)*2+1); //window calculation based on Gaussian(normal) distribution with sigma, mean=zero,x=X[i] double window[] = new double[windowSize]; double windowSum = 0; for (int i = 0;i<windowSize;i++){ window[i] = normDistribution.density(Math.round(inverseCDF)+i); windowSum = windowSum+window[i]; } double normalizedWindow[]=new double[windowSize]; for (int i = 0;i<windowSize;i++) normalizedWindow[i] = window[i]/windowSum; PolynomialFunction poly1 = new PolynomialFunction(polyCoeffi); PolynomialFunction poly2 = new PolynomialFunction(normalizedWindow); PolynomialFunction polyMultiplication=poly1.multiply(poly2); double coefficients[]= polyMultiplication.getCoefficients(); //taking mid point of polynomial coefficients int polyMid = (int) Math.floor(coefficients.length/2); System.out.println("currchromBin Size is : "+currchromBinSize+"\t"+ "windowSize is: "+windowSize+"\t"+"coefficients length is: "+coefficients.length); //copy Gaussian blur results to the column[1] // I should check to make sure that it's not off by 1 for (int i = 0; i<currchromBinSize;i++){ if (currchromBinSize % 2 ==0 && coefficients.length/2 == 1) gaussianBlur[i][1]=(float) coefficients[polyMid-currchromBinSize/2+i+1]; else gaussianBlur[i][1]=(float) coefficients[polyMid-currchromBinSize/2+i]; } //testing; I can identify the region that I want to print using peak calling // if (currchromBinSize < 200000 && currchromBinSize >15000){ // for (int i = 0; i< 200;i++) // System.out.println(gaussianBlur[9650+i][0]+" : "+gaussianBlur[9650+i][1]); /*************** * Search Volume */ double tempRadius; if (n==1){ tempRadius = sigma[n]; }else{ tempRadius = Math.sqrt(Math.pow(sigma[n],2)-Math.pow(sigma[n-1], 2)); } radius[n] = Math.ceil(K_MIN*tempRadius); int DCPsize = (int) (Math.round(radius[n])*2+1); int dcp[] = new int[DCPsize]; double distanceFactor[] = new double[DCPsize]; double affectionDistance; double denom = -2*(Math.pow(sigma[n], 2)-Math.pow(sigma[n-1],2)); for (int i = 0; i<DCPsize;i++){ dcp[i] = (int) -Math.round(radius[n])+i; // applying equation 7 in Vincken(1997) affectionDistance=Math.exp(Math.pow(dcp[i], 2)/denom)/Math.exp(Math.pow(0.5*sigma[n],2)/denom); //applying equation 8 in Vincken (1997) if (Math.abs(dcp[i]) > 0.5*sigma[n]){distanceFactor[i]= affectionDistance;} else{distanceFactor[i] = 1.0000;} } /*************** * Linkage Loop */ TreeMap<Integer, Integer> GvParents = new TreeMap<Integer,Integer>(); //First iteration only consider intensity differences between parent and kid and connect to the ones with the least difference. //From the second iteration, we consider ground volume = number of nodes that parents are linked to the kids //From third iteration, we increase the weight of the ground volume by 1e-7. //Vincken paper said after 3-4 iteration, there would be no significant difference. double groundVC = 0; double groundVPmax = 0; double tempScore = 0; //updating ground volume and iterating to encourage convergence for (int counter = 0; counter<5; counter++){ if (counter != 0){ for (Integer parent : GvParents.keySet()){ if ( GvParents.get(parent) > groundVPmax) groundVPmax = GvParents.get(parent); } } for (Integer kid : linkageMap.keySet()){ double intensityDiffScore = 0; for (int i = 0; i<DCPsize; i++){ if ((kid + dcp[i]) >=0 && (kid + dcp[i]) <currchromBinSize){ if (counter ==0 || groundVPmax == 0){groundVC = 0.00;} else{ groundVC = (WEIGHT_I+WEIGHT_G*counter)*GvParents.get(linkageMap.get(kid))/groundVPmax;} tempScore = distanceFactor[i]*((1- Math.abs(gaussianBlur[kid][0] - gaussianBlur[kid+dcp[i]][1])/DImax)+groundVC); if (tempScore > intensityDiffScore){ intensityDiffScore = tempScore; //test if (counter ==0){linkageMap.put(kid,(kid+dcp[i]));} //test else{ // if(GvParents.containsKey(kid+dcp[i])){linkageMap.put(kid,(kid+dcp[i]));} if(linkageMap.containsValue(kid+dcp[i])){linkageMap.put(kid,(kid+dcp[i]));} //test } } } } } //test // if (currchromBinSize > 20000000){ // System.out.println("current Chrom is: "+currChrom.getChrom()); // System.out.println("printing linkangeMap content"); // for (Map.Entry<Integer, Integer> entry : linkageMap.entrySet()){ // System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue()); GvParents.clear(); Integer lastParent = 0; Map<Integer, Integer> sortedLinkageMap = new HashMap<Integer,Integer> (MapUtility.sortByValue(linkageMap)); for (Integer parent : sortedLinkageMap.values()){ GvParents.put(parent, (parent-lastParent)); lastParent = parent; } GvParents.put(0, trailingZero); GvParents.put(gaussianBlur.length-1,gaussianBlur.length-zeroEnd-1); } Map<Integer, Integer> sortedLinkageMap = new HashMap<Integer,Integer> (MapUtility.sortByValue(linkageMap)); linkageMap.clear(); for (Integer parent : sortedLinkageMap.values()){ linkageMap.put(parent, parent); } //for each scaleNum, add the parents to the segmentationTree segmentationTree.put(n, GvParents.keySet()); }//end of scale space iteration // scale zero is getting overwriting with the parents of the last scale; I'm overwriting the scale zero with initial nodesest for quick fix segmentationTree.put(0, startingNodes); for (Integer scale : segmentationTree.keySet()){ System.out.println("current scale is: "+scale); Set<Integer> sortedNodeSet = new TreeSet<Integer>(segmentationTree.get(scale)); System.out.println("current nodeset size is: "+sortedNodeSet.size()); for (Integer node : sortedNodeSet) System.out.println(node); } return segmentationTree; } }
// ReportsController.java // MacPAFTest import java.io.File; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import com.apple.cocoa.application.*; import com.apple.cocoa.foundation.NSArray; import com.apple.cocoa.foundation.NSSelector; import com.redbugz.macpaf.Individual; import com.redbugz.macpaf.jdom.GedcomLoaderJDOM; import com.redbugz.macpaf.util.CocoaUtils; public class ImportController { private static final Logger log = Logger.getLogger(ImportController.class); public NSWindow importWindow; /* IBOutlet */ public NSMatrix importRadio; /* IBOutlet */ public NSTextField filePathField; /* IBOutlet */ public NSProgressIndicator progress; /* IBOutlet */ private NSOpenPanel openPanel; public void cancel(Object sender) { /* IBAction */ // NSApplication.sharedApplication().stopModal(); NSApplication.sharedApplication().endSheet(importWindow); importWindow.orderOut(this); } public void browse(Object sender) { /* IBAction */ NDC.push(((MyDocument) NSDocumentController.sharedDocumentController().currentDocument()).displayName()+" import browse"); try { openPanel = NSOpenPanel.openPanel(); //panther only? panel.setMessage("Please select a GEDCOM file to import into this MacPAF file."); // NSWindow mainWindow = ((MyDocument) NSDocumentController.sharedDocumentController().currentDocument()).mainWindow; // log.debug("mainwindow:"+mainWindow.title()); openPanel.beginSheetForDirectory(null, null, new NSArray(new Object[] {"GED"}), null, this, new NSSelector("openPanelDidEnd", new Class[] {NSOpenPanel.class, int.class, Object.class}), null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } NDC.pop(); } public void openPanelDidEnd(NSOpenPanel sheet, int returnCode, Object contextInfo) { NDC.push(((MyDocument) NSDocumentController.sharedDocumentController().currentDocument()).displayName()+" import"); if (returnCode == NSPanel.OKButton) { log.debug("import filename:" + sheet.filename()); filePathField.setStringValue(sheet.filename()); } NDC.pop(); } public void importFile(Object sender) { /* IBAction */ NDC.push(((MyDocument) NSDocumentController.sharedDocumentController().currentDocument()).displayName()+" import"); log.debug("save sender=" + sender + " selectedTag=" + importRadio.selectedTag()); try { MyDocument doc = (MyDocument) NSDocumentController.sharedDocumentController().currentDocument(); if (importRadio.selectedTag() == 0) { // import into existing file doc.startSuppressUpdates(); try { new GedcomLoaderJDOM(doc.doc, progress).loadXMLFile(new File(filePathField.stringValue())); } catch (RuntimeException e) { throw e; } finally { doc.endSuppressUpdates(); } } NSApplication.sharedApplication().endSheet(importWindow); } catch (RuntimeException e) { e.printStackTrace(); MyDocument.showUserErrorMessage("There was an unexpected error during import.", "An unexpected error occurred while attempting to import the file. The data may not have been imported. Please try again or report this to the MacPAF developers"); } finally { NDC.pop(); } importWindow.orderOut(this); resetWindow(); } private void resetWindow() { // prepare window for next use, reset default values filePathField.setStringValue(""); progress.setIndeterminate(true); progress.stopAnimation(this); } // public void setDocument(NSDocument nsDocument) { // super.setDocument(nsDocument); // log.debug("setdocument:" + nsDocument); //// log.debug("surname:"+surname); // Individual individual = ( (MyDocument) nsDocument).getPrimaryIndividual(); //// setIndividual(individual); // doc = (MyDocument) nsDocument; // public void openImportSheet(Object sender) { /* IBAction */ // NSApplication nsapp = NSApplication.sharedApplication(); // nsapp.beginSheet(importWindow, ((MyDocument)this.document()).mainWindow, null, null, null); //// nsapp.runModalForWindow(this.window()); //// nsapp.endSheet(this.window()); //// this.window().orderOut(this); }
package network.thunder.core.mesh; import io.netty.channel.ChannelHandlerContext; import network.thunder.core.communication.nio.P2PContext; import network.thunder.core.communication.objects.subobjects.AuthenticationObject; import network.thunder.core.etc.crypto.CryptoTools; import org.bitcoinj.core.ECKey; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; public class Node { private String host; private int port; private boolean connected = false; private ChannelHandlerContext nettyContext; private byte[] pubkey; private ECKey pubKeyTempClient; private ECKey pubKeyTempServer; private boolean isAuth; private boolean sentAuth; private boolean authFinished; private boolean isReady; private boolean hasOpenChannel; //From the gossip handler upwards nodes have their own connection object public Connection conn; public boolean justFetchNewIpAddresses = false; public P2PContext context; public Node (String host, int port) { this.host = host; this.port = port; } public Node (ResultSet set) throws SQLException { this.host = set.getString("host"); this.port = set.getInt("port"); } public Node (byte[] pubkey) { this.pubkey = pubkey; } public Node () { } public boolean processAuthentication (AuthenticationObject authentication, ECKey pubkeyClient, ECKey pubkeyServerTemp) throws NoSuchProviderException, NoSuchAlgorithmException { byte[] data = new byte[pubkeyClient.getPubKey().length + pubkeyServerTemp.getPubKey().length]; System.arraycopy(pubkeyClient.getPubKey(), 0, data, 0, pubkeyClient.getPubKey().length); System.arraycopy(pubkeyServerTemp.getPubKey(), 0, data, pubkeyClient.getPubKey().length, pubkeyServerTemp.getPubKey().length); CryptoTools.verifySignature(pubkeyClient, data, authentication.signature); isAuth = true; if (sentAuth) { authFinished = true; } return true; } public AuthenticationObject getAuthenticationObject (ECKey keyServer, ECKey keyClientTemp) throws NoSuchProviderException, NoSuchAlgorithmException { byte[] data = new byte[keyServer.getPubKey().length + keyClientTemp.getPubKey().length]; System.arraycopy(keyServer.getPubKey(), 0, data, 0, keyServer.getPubKey().length); System.arraycopy(keyClientTemp.getPubKey(), 0, data, keyServer.getPubKey().length, keyClientTemp.getPubKey().length); AuthenticationObject obj = new AuthenticationObject(); obj.pubkeyServer = keyServer.getPubKey(); obj.signature = CryptoTools.createSignature(keyServer, data); sentAuth = true; if (this.isAuth) { this.authFinished = true; } return obj; } public ChannelHandlerContext getNettyContext () { return nettyContext; } public void setNettyContext (ChannelHandlerContext nettyContext) { this.nettyContext = nettyContext; } public int getPort () { return port; } public void setPort (int port) { this.port = port; } public String getHost () { return host; } public void setHost (String host) { this.host = host; } public boolean isConnected () { return connected; } public void setConnected (boolean connected) { this.connected = connected; } public boolean hasSentAuth () { return sentAuth; } public boolean isAuth () { return isAuth; } public boolean allowsAuth () { return !isAuth; } public void finishAuth () { authFinished = true; } public boolean isAuthFinished () { return authFinished; } public ECKey getPubKeyTempClient () { return pubKeyTempClient; } public void setPubKeyTempClient (ECKey pubKeyTempClient) { this.pubKeyTempClient = pubKeyTempClient; } public ECKey getPubKeyTempServer () { return pubKeyTempServer; } public void setPubKeyTempServer (ECKey pubKeyTempServer) { this.pubKeyTempServer = pubKeyTempServer; } private OnConnectionCloseListener onConnectionCloseListener; public void setOnConnectionCloseListener (OnConnectionCloseListener onConnectionCloseListener) { this.onConnectionCloseListener = onConnectionCloseListener; } public void closeConnection () { if (onConnectionCloseListener != null) { onConnectionCloseListener.onClose(); } try { this.nettyContext.close(); } catch (Exception e) { } } public interface OnConnectionCloseListener { public void onClose (); } @Override public boolean equals (Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Node node = (Node) o; return Arrays.equals(pubkey, node.pubkey); } @Override public int hashCode () { return pubkey != null ? Arrays.hashCode(pubkey) : 0; } }
package lucee.runtime.extension; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.jar.Attributes; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import lucee.Info; import lucee.commons.digest.HashUtil; import lucee.commons.io.IOUtil; import lucee.commons.io.SystemUtil; import lucee.commons.io.log.Log; import lucee.commons.io.res.Resource; import lucee.commons.io.res.util.ResourceUtil; import lucee.commons.lang.StringUtil; import lucee.loader.util.Util; import lucee.runtime.config.Config; import lucee.runtime.config.ConfigImpl; import lucee.runtime.config.ConfigWeb; import lucee.runtime.config.ConfigWebUtil; import lucee.runtime.config.Constants; import lucee.runtime.config.XMLConfigAdmin; import lucee.runtime.db.ClassDefinition; import lucee.runtime.engine.ThreadLocalConfig; import lucee.runtime.engine.ThreadLocalPageContext; import lucee.runtime.exp.ApplicationException; import lucee.runtime.exp.DatabaseException; import lucee.runtime.exp.PageException; import lucee.runtime.exp.PageRuntimeException; import lucee.runtime.functions.conversion.DeserializeJSON; import lucee.runtime.op.Caster; import lucee.runtime.op.Decision; import lucee.runtime.osgi.BundleFile; import lucee.runtime.osgi.OSGiUtil; import lucee.runtime.osgi.OSGiUtil.BundleDefinition; import lucee.runtime.type.Collection.Key; import lucee.runtime.type.KeyImpl; import lucee.runtime.type.Query; import lucee.runtime.type.QueryImpl; import lucee.runtime.type.util.ArrayUtil; import lucee.runtime.type.util.KeyConstants; import lucee.runtime.type.util.ListUtil; import org.osgi.framework.BundleException; import org.osgi.framework.Version; import org.w3c.dom.Element; /** * Extension completely handled by the engine and not by the Install/config.xml */ public class RHExtension implements Serializable { private static final long serialVersionUID = 2904020095330689714L; //public static final Key JARS = KeyImpl.init("jars"); private static final Key BUNDLES = KeyImpl.init("bundles"); private static final Key TLDS = KeyImpl.init("tlds"); private static final Key FLDS = KeyImpl.init("flds"); private static final Key EVENT_GATEWAYS = KeyImpl.init("eventGateways"); private static final Key TAGS = KeyImpl.init("tags"); private static final Key FUNCTIONS = KeyConstants._functions; private static final Key ARCHIVES = KeyImpl.init("archives"); private static final Key CONTEXTS = KeyImpl.init("contexts"); private static final Key WEBCONTEXTS = KeyImpl.init("webcontexts"); private static final Key APPLICATIONS = KeyImpl.init("applications"); private static final Key CATEGORIES = KeyImpl.init("categories"); private static final Key PLUGINS = KeyImpl.init("plugins"); private static final Key START_BUNDLES = KeyImpl.init("startBundles"); private static final Key TRIAL = KeyImpl.init("trial"); private static final String[] EMPTY = new String[0]; private static final BundleDefinition[] EMPTY_BD = new BundleDefinition[0]; private final String id; private final String version; private final String name; private final String description; private final boolean trial; private final String image; private final boolean startBundles; private final BundleFile[] bundlesfiles; private final String[] flds; private final String[] tlds; private final String[] tags; private final String[] functions; private final String[] archives; private final String[] applications; private final String[] plugins; private final String[] contexts; private final String[] webContexts; private final String[] categories; private final String[] gateways; private final List<Map<String, String>> cacheHandlers; private final List<Map<String, String>> orms; private final List<Map<String, String>> monitors; private final List<Map<String, String>> searchs; private final List<Map<String, String>> resources; private final List<Map<String, String>> amfs; private final List<Map<String, String>> jdbcs; private final List<Map<String, String>> mappings; private final Resource extensionFile; public RHExtension(Config config, Resource ext, boolean moveIfNecessary) throws PageException, IOException, BundleException { // make sure the config is registerd with the thread if(ThreadLocalPageContext.getConfig()==null) ThreadLocalConfig.register(config); // is it a web or server context? boolean isWeb=config instanceof ConfigWeb; String type=isWeb?"web":"server"; Log logger = ((ConfigImpl)config).getLog("deploy"); // get info necessary for checking Info info = ConfigWebUtil.getEngine(config).getInfo(); // get the Manifest Manifest manifest = null; ZipInputStream zis=null; String _img=null; try { zis = new ZipInputStream( IOUtil.toBufferedInputStream(ext.getInputStream()) ) ; ZipEntry entry; String name; while ( ( entry = zis.getNextEntry()) != null ) { name=entry.getName(); if(!entry.isDirectory() && name.equalsIgnoreCase("META-INF/MANIFEST.MF")) { manifest = toManifest(config,zis,null); } else if(!entry.isDirectory() && name.equalsIgnoreCase("META-INF/logo.png")) { _img = toBase64(zis,null); } zis.closeEntry() ; } } catch(Throwable t){ throw Caster.toPageException(t); } finally { IOUtil.closeEL(zis); } if(manifest==null) throw new ApplicationException("The Extension ["+ext+"] is invalid,no Manifest file was found at [META-INF/MANIFEST.MF]."); // read the manifest List<Map<String,String>> cacheHandlers=null; List<Map<String,String>> orms=null; List<Map<String,String>> monitors=null; List<Map<String,String>> searchs=null; List<Map<String,String>> resources=null; List<Map<String,String>> amfs=null; List<Map<String,String>> jdbcs=null; List<Map<String,String>> eventGateways=null; List<Map<String,String>> mappings=null; Attributes attr = manifest.getMainAttributes(); // version version=unwrap(attr.getValue("version")); if(StringUtil.isEmpty(version)) { throw new ApplicationException("cannot deploy extension ["+ext+"], this Extension has no version information."); } id=unwrap(attr.getValue("id")); if(!Decision.isUUId(id)) { throw new ApplicationException("The Extension ["+ext+"] has no valid id defined ("+id+"),id must be a valid UUID."); } // name String str=unwrap(attr.getValue("name")); if(StringUtil.isEmpty(str,true)) { throw new ApplicationException("The Extension ["+ext+"] has no name defined, a name is necesary."); } name=str.trim(); // description description=unwrap(attr.getValue("description")); trial=Caster.toBooleanValue(unwrap(attr.getValue("trial")),false); // image if(_img==null)_img=unwrap(attr.getValue("image")); image=_img; // categories str=unwrap(attr.getValue("category")); if(StringUtil.isEmpty(str,true))str=unwrap(attr.getValue("categories")); if(!StringUtil.isEmpty(str,true)) { categories=ListUtil.trimItems(ListUtil.listToStringArray(str, ",")); } else categories=null; // core version str=unwrap(attr.getValue("lucee-core-version")); //int minCoreVersion=InfoImpl.toIntVersion(str,0); Version minCoreVersion = OSGiUtil.toVersion(str, null); if(minCoreVersion!=null && Util.isNewerThan(minCoreVersion,info.getVersion())) { throw new ApplicationException("The Extension ["+ext+"] cannot be loaded, "+Constants.NAME+" Version must be at least ["+minCoreVersion.toString()+"], version is ["+info.getVersion().toString()+"]."); } // loader version str=unwrap(attr.getValue("lucee-loader-version")); double minLoaderVersion = Caster.toDoubleValue(str,0); if(minLoaderVersion>SystemUtil.getLoaderVersion()) { throw new ApplicationException("The Extension ["+ext+"] cannot be loaded, "+Constants.NAME+" Loader Version must be at least ["+str+"], update the Lucee.jar first."); } // start bundles str = unwrap(attr.getValue("start-bundles")); startBundles=Caster.toBooleanValue(str,true); // amf str=unwrap(attr.getValue("amf")); if(!StringUtil.isEmpty(str,true)) { amfs = toSettings(logger,str); } // resource str=unwrap(attr.getValue("resource")); if(!StringUtil.isEmpty(str,true)) { resources = toSettings(logger,str); } // search str=unwrap(attr.getValue("search")); if(!StringUtil.isEmpty(str,true)) { searchs = toSettings(logger,str); } // orm str=unwrap(attr.getValue("orm")); if(!StringUtil.isEmpty(str,true)) { orms = toSettings(logger,str); } // monitor str=unwrap(attr.getValue("monitor")); if(!StringUtil.isEmpty(str,true)) { monitors = toSettings(logger,str); } // cache-handlers str=unwrap(attr.getValue("cache-handler")); if(!StringUtil.isEmpty(str,true)) { cacheHandlers = toSettings(logger,str); } // jdbcs str=unwrap(attr.getValue("jdbc")); if(!StringUtil.isEmpty(str,true)) { jdbcs = toSettings(logger,str); } // event-handler str=unwrap(attr.getValue("event-handler")); if(!StringUtil.isEmpty(str,true)) { eventGateways = toSettings(logger,str); } // mappings str=unwrap(attr.getValue("mapping")); if(!StringUtil.isEmpty(str,true)) { mappings = toSettings(logger,str); } // no we read the content of the zip zis = new ZipInputStream( IOUtil.toBufferedInputStream(ext.getInputStream()) ) ; ZipEntry entry; String path; String fileName,sub; BundleFile bf; List<BundleFile> bundles=new ArrayList<BundleFile>(); List<String> flds=new ArrayList<String>(); List<String> tlds=new ArrayList<String>(); List<String> tags=new ArrayList<String>(); List<String> functions=new ArrayList<String>(); List<String> contexts=new ArrayList<String>(); List<String> webContexts=new ArrayList<String>(); List<String> applications=new ArrayList<String>(); List<String> plugins=new ArrayList<String>(); List<String> gateways=new ArrayList<String>(); List<String> archives=new ArrayList<String>(); try { while ( ( entry = zis.getNextEntry()) != null ) { path=entry.getName(); fileName=fileName(entry); sub=subFolder(entry); // jars if(!entry.isDirectory() && (startsWith(path,type,"jars") || startsWith(path,type,"jar") || startsWith(path,type,"bundles") || startsWith(path,type,"bundle") || startsWith(path,type,"lib") || startsWith(path,type,"libs")) && StringUtil.endsWithIgnoreCase(path, ".jar")) { bf = XMLConfigAdmin.installBundle(config,zis,fileName,version,false); bundles.add(bf); } // flds if(!entry.isDirectory() && startsWith(path,type,"flds") && StringUtil.endsWithIgnoreCase(path, ".fld")) flds.add(fileName); // tlds if(!entry.isDirectory() && startsWith(path,type,"tlds") && StringUtil.endsWithIgnoreCase(path, ".tld")) tlds.add(fileName); // archives if(!entry.isDirectory() && (startsWith(path,type,"archives") || startsWith(path,type,"mappings")) && StringUtil.endsWithIgnoreCase(path, ".lar")) archives.add(fileName); // event-gateway if(!entry.isDirectory() && (startsWith(path,type,"event-gateway") || startsWith(path,type,"eventGateway")) && ( StringUtil.endsWithIgnoreCase(path, "."+Constants.getCFMLComponentExtension()) || StringUtil.endsWithIgnoreCase(path, "."+Constants.getLuceeComponentExtension()) ) ) gateways.add(sub); // tags if(!entry.isDirectory() && startsWith(path,type,"tags")) tags.add(sub); // functions if(!entry.isDirectory() && startsWith(path,type,"functions")) functions.add(sub); // context if(!entry.isDirectory() && startsWith(path,type,"context") && !StringUtil.startsWith(fileName(entry), '.')) contexts.add(sub); // web contextS if(!entry.isDirectory() && startsWith(path,type,"webcontexts") && !StringUtil.startsWith(fileName(entry), '.')) webContexts.add(sub); // applications if(!entry.isDirectory() && (startsWith(path,type,"applications")) && !StringUtil.startsWith(fileName(entry), '.')) applications.add(sub); // plugins if(!entry.isDirectory() && (startsWith(path,type,"plugins")) && !StringUtil.startsWith(fileName(entry), '.')) plugins.add(sub); zis.closeEntry() ; } } finally { IOUtil.closeEL(zis); } this.flds=flds.toArray(new String[flds.size()]); this.tlds=tlds.toArray(new String[tlds.size()]); this.tags=tags.toArray(new String[tags.size()]); this.gateways=gateways.toArray(new String[gateways.size()]); this.functions=functions.toArray(new String[functions.size()]); this.archives=archives.toArray(new String[archives.size()]); this.contexts=contexts.toArray(new String[contexts.size()]); this.webContexts=webContexts.toArray(new String[webContexts.size()]); this.applications=applications.toArray(new String[applications.size()]); this.plugins=plugins.toArray(new String[plugins.size()]); this.bundlesfiles=bundles.toArray(new BundleFile[bundles.size()]); this.cacheHandlers=cacheHandlers==null?new ArrayList<Map<String, String>>():cacheHandlers; this.orms=orms==null?new ArrayList<Map<String, String>>():orms; this.monitors=monitors==null?new ArrayList<Map<String, String>>():monitors; this.searchs=searchs==null?new ArrayList<Map<String, String>>():searchs; this.resources=resources==null?new ArrayList<Map<String, String>>():resources; this.amfs=amfs==null?new ArrayList<Map<String, String>>():amfs; this.jdbcs=jdbcs==null?new ArrayList<Map<String, String>>():jdbcs; this.mappings=mappings==null?new ArrayList<Map<String, String>>():mappings; // copy the file to extension dir if it is not already there if(moveIfNecessary){ Resource trg; Resource trgDir; try { trg = getExtensionFile(config, ext,id,name,version); trgDir = trg.getParentResource(); trgDir.mkdirs(); if(!ext.getParentResource().equals(trgDir)) { ResourceUtil.moveTo(ext, trg,true); } } catch(Throwable t){ throw Caster.toPageException(t); } this.extensionFile=trg; } else this.extensionFile=ext; } public RHExtension(Config config,Element el) throws PageException, IOException, BundleException { this(config,toResource(config,el),false); } private static Resource toResource(Config config, Element el) throws ApplicationException { String fileName = el.getAttribute("file-name"); if(StringUtil.isEmpty(fileName)) throw new ApplicationException("missing attribute [file-name]"); Resource res=getExtensionDir(config).getRealResource(fileName); if(!res.exists()) throw new ApplicationException("Extension ["+fileName+"] was not found at ["+res+"]"); return res; } private static Resource getExtensionFile(Config config, Resource ext, String id,String name, String version) { String fileName=HashUtil.create64BitHashAsString(id+version,Character.MAX_RADIX)+"."+ResourceUtil.getExtension(ext, "lex"); return getExtensionDir(config).getRealResource(fileName); } private static Resource getExtensionDir(Config config) { return config.getConfigDir().getRealResource("extensions/installed"); } public static BundleDefinition[] toBundleDefinitions(String strBundles) { if(StringUtil.isEmpty(strBundles,true)) return EMPTY_BD; String[] arrStrs = toArray(strBundles); BundleDefinition[] arrBDs; if(!ArrayUtil.isEmpty(arrStrs)) { arrBDs = new BundleDefinition[arrStrs.length]; int index; for(int i=0;i<arrStrs.length;i++){ index=arrStrs[i].indexOf(':'); if(index==-1) arrBDs[i]=new BundleDefinition(arrStrs[i].trim()); else { try { arrBDs[i]=new BundleDefinition(arrStrs[i].substring(0,index).trim(),arrStrs[i].substring(index+1).trim()); } catch (BundleException e) { throw new PageRuntimeException(e);// should not happen } } } } else arrBDs=EMPTY_BD; return arrBDs; } public void populate(Element el) { el.setAttribute("file-name", extensionFile.getName()); el.setAttribute("id", getId()); el.setAttribute("name", getName()); el.setAttribute("version", getVersion()); } private static String[] toArray(String str) { if(StringUtil.isEmpty(str,true)) return new String[0]; return ListUtil.listToStringArray(str.trim(), ','); } public static Query toQuery(Config config,RHExtension[] children) throws PageException { Log log = config.getLog("deploy"); Query qry = createQuery(); for(int i=0;i<children.length;i++) { try{ children[i].populate(qry); } catch(Throwable t){ log.error("extension", t); } } return qry; } public static Query toQuery(Config config,Element[] children) throws PageException { Log log = config.getLog("deploy"); Query qry = createQuery(); for(int i=0;i<children.length;i++) { try{ new RHExtension(config,children[i]).populate(qry); } catch(Throwable t){ log.error("extension", t); } } return qry; } private static Query createQuery() throws DatabaseException { return new QueryImpl(new Key[]{ KeyConstants._id ,KeyConstants._version ,KeyConstants._name ,KeyConstants._description ,KeyConstants._image ,TRIAL ,CATEGORIES ,START_BUNDLES ,BUNDLES ,FLDS ,TLDS ,TAGS ,FUNCTIONS ,CONTEXTS ,WEBCONTEXTS ,APPLICATIONS ,PLUGINS ,EVENT_GATEWAYS ,ARCHIVES }, 0, "Extensions"); } private void populate(Query qry) throws PageException { int row=qry.addRow(); qry.setAt(KeyConstants._id, row, getId()); qry.setAt(KeyConstants._name, row, name); qry.setAt(KeyConstants._image, row, getImage()); qry.setAt(KeyConstants._description, row, description); qry.setAt(KeyConstants._version, row, getVersion()==null?null:getVersion().toString()); qry.setAt(TRIAL, row, isTrial()); //qry.setAt(JARS, row,Caster.toArray(getJars())); qry.setAt(FLDS, row, Caster.toArray(getFlds())); qry.setAt(TLDS, row, Caster.toArray(getTlds())); qry.setAt(FUNCTIONS, row, Caster.toArray(getFunctions())); qry.setAt(ARCHIVES, row, Caster.toArray(getArchives())); qry.setAt(TAGS, row, Caster.toArray(getTags())); qry.setAt(CONTEXTS, row, Caster.toArray(getContexts())); qry.setAt(WEBCONTEXTS, row, Caster.toArray(getWebContexts())); qry.setAt(EVENT_GATEWAYS, row, Caster.toArray(getEventGateways())); qry.setAt(CATEGORIES, row, Caster.toArray(getCategories())); qry.setAt(APPLICATIONS, row, Caster.toArray(getApplications())); qry.setAt(PLUGINS, row, Caster.toArray(getPlugins())); qry.setAt(START_BUNDLES, row, Caster.toBoolean(getStartBundles())); BundleFile[] bfs = getBundlesFiles(); Query qryBundles=new QueryImpl(new Key[]{KeyConstants._name,KeyConstants._version}, bfs.length, "bundles"); for(int i=0;i<bfs.length;i++){ qryBundles.setAt(KeyConstants._name, i+1, bfs[i].getSymbolicName()); if(bfs[i].getVersion()!=null) qryBundles.setAt(KeyConstants._version, i+1, bfs[i].getVersionAsString()); } qry.setAt(BUNDLES, row,qryBundles); } public String getId() { return id; } public String getImage() { return image; } public String getVersion() { return version; } public BundleFile[] getBundlesFiles() { return bundlesfiles; } public boolean getStartBundles() { return startBundles; } /*private static void moveToFailedFolder(Resource deployDirectory,Resource res) { Resource dir = deployDirectory.getRealResource("failed-to-deploy"); Resource dst = dir.getRealResource(res.getName()); dir.mkdirs(); try { if(dst.exists()) dst.remove(true); ResourceUtil.moveTo(res, dst,true); } catch (Throwable t) {} // TODO Auto-generated method stub }*/ private static Manifest toManifest(Config config,InputStream is, Manifest defaultValue) { try { Charset cs = config.getResourceCharset(); String str = IOUtil.toString(is,cs); if(StringUtil.isEmpty(str,true)) return defaultValue; str=str.trim()+"\n"; return new Manifest(new ByteArrayInputStream(str.getBytes(cs))); } catch (Throwable t) { return defaultValue; } } private static String toBase64(InputStream is, String defaultValue) { try { byte[] bytes = IOUtil.toBytes(is); if(ArrayUtil.isEmpty(bytes)) return defaultValue; return Caster.toB64(bytes,defaultValue); } catch (Throwable t) { return defaultValue; } } private static String unwrap(String value) { char startDoubleQuote=(char)8220; char endDoubleQuote=(char)8221; if(StringUtil.isEmpty(value,true)) return ""; value=value.trim(); String res = unwrap(value,'"'); if(res.length()<value.length()) return res; res = unwrap(value,'\''); if(res.length()<value.length()) return res; boolean changed=false; if(value.charAt(0)==startDoubleQuote) { value='"'+value.substring(1); changed=true; } if(value.charAt(value.length()-1)==endDoubleQuote) { value=value.substring(0,value.length()-1)+'"'; changed=true; } return changed?unwrap(value,'"'):value; } private static String unwrap(String value, char del) { value=value.trim(); if(StringUtil.startsWith(value, del) && StringUtil.endsWith(value, del)) { return value.substring(1, value.length()-1); } return value; } public static ClassDefinition<?> toClassDefinition(Config config, Map<String, String> map) { String _class=map.get("class"); String _name=map.get("bundle-name"); if(StringUtil.isEmpty(_name)) _name=map.get("bundleName"); if(StringUtil.isEmpty(_name)) _name=map.get("bundlename"); if(StringUtil.isEmpty(_name)) _name=map.get("name"); String _version=map.get("bundle-version"); if(StringUtil.isEmpty(_version)) _version=map.get("bundleVersion"); if(StringUtil.isEmpty(_version)) _version=map.get("bundleversion"); if(StringUtil.isEmpty(_version)) _version=map.get("version"); return new lucee.transformer.library.ClassDefinitionImpl( _class ,_name ,_version ,config.getIdentification()); } private static List<Map<String,String>> toSettings(Log log, String str) { try { Object res = DeserializeJSON.call(null, str); // only a single row if(!Decision.isArray(res) && Decision.isStruct(res)) { List<Map<String,String>> list = new ArrayList<>(); _toSetting(list, Caster.toMap(res)); return list; } // multiple rows if(Decision.isArray(res)) { List tmpList=Caster.toList(res); Iterator it = tmpList.iterator(); List<Map<String,String>> list=new ArrayList<>(); while(it.hasNext()) { _toSetting(list,Caster.toMap(it.next())); } return list; } } catch (Throwable t) { log.error("Extension Installation", t); } return null; } private static void _toSetting(List<Map<String, String>> list, Map src) throws PageException { Entry e; Iterator<Entry> it = src.entrySet().iterator(); Map<String,String> map=new HashMap<String,String>(); while(it.hasNext()){ e = it.next(); map.put(Caster.toString(e.getKey()), Caster.toString(e.getValue())); } list.add(map); } private static boolean startsWith(String path,String type, String name) { return StringUtil.startsWithIgnoreCase(path, name+"/") || StringUtil.startsWithIgnoreCase(path, type+"/"+name+"/"); } private static String fileName(ZipEntry entry) { String name = entry.getName(); int index=name.lastIndexOf('/'); if(index==-1) return name; return name.substring(index+1); } private static String subFolder(ZipEntry entry) { String name = entry.getName(); int index=name.indexOf('/'); if(index==-1) return name; return name.substring(index+1); } private static BundleDefinition toBundleDefinition(InputStream is, String name,String extensionVersion,boolean closeStream) throws IOException, BundleException, ApplicationException { Resource tmp=SystemUtil.getTempDirectory().getRealResource(name); try{ IOUtil.copy(is, tmp,closeStream); BundleFile bf = new BundleFile(tmp); if(bf.isBundle()) throw new ApplicationException("Jar ["+name+"] is not a valid OSGi Bundle"); return new BundleDefinition(bf.getSymbolicName(), bf.getVersion()); } finally { tmp.delete(); } } public String getName() { return name; } public boolean isTrial() { return trial; } public String getDescription() { return description; } public BundleFile[] getBundlesfiles() { return bundlesfiles; } public String[] getFlds() { return flds==null?EMPTY:flds; } public String[] getTlds() { return tlds==null?EMPTY:tlds; } public String[] getFunctions() { return functions==null?EMPTY:functions; } public String[] getArchives() { return archives==null?EMPTY:archives; } public String[] getTags() { return tags==null?EMPTY:tags; } public String[] getEventGateways() { return gateways==null?EMPTY:gateways; } public String[] getApplications() { return applications==null?EMPTY:applications; } public String[] getPlugins() { return plugins==null?EMPTY:plugins; } public String[] getContexts() { return contexts==null?EMPTY:contexts; } public String[] getWebContexts() { return webContexts==null?EMPTY:webContexts; } public String[] getCategories() { return categories==null?EMPTY:categories; } public List<Map<String, String>> getCacheHandlers() { return cacheHandlers; } public List<Map<String, String>> getOrms() { return orms; } public List<Map<String, String>> getMonitors() { return monitors; } public List<Map<String, String>> getSearchs() { return searchs; } public List<Map<String, String>> getResources() { return resources; } public List<Map<String, String>> getAMFs() { return amfs; } public List<Map<String, String>> getJdbcs() { return jdbcs; } public List<Map<String, String>> getMappings() { return mappings; } public Resource getExtensionFile() { return extensionFile; } @Override public boolean equals(Object objOther) { if(objOther == this) return true; if(!(objOther instanceof RHExtension)) return false; RHExtension other=(RHExtension) objOther; if(!id.equals(other.id)) return false; if(!name.equals(other.name)) return false; if(!version.equals(other.version)) return false; if(trial!=other.trial) return false; return true; } }
package fr.loicdelorme.followUpYourGarden.controllers; import java.io.IOException; import java.sql.SQLException; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.stage.Stage; import fr.loicdelorme.followUpYourGarden.core.models.TypeOfPlants; import fr.loicdelorme.followUpYourGarden.core.services.TypeOfPlantsServices; import fr.loicdelorme.followUpYourGarden.core.services.exceptions.InvalidTypeOfPlantsIdException; import fr.loicdelorme.followUpYourGarden.core.services.exceptions.InvalidTypeOfPlantsWordingException; import fr.loicdelorme.followUpYourGarden.core.services.exceptions.MissingTypeOfPlantsIdException; import fr.loicdelorme.followUpYourGarden.core.services.exceptions.MissingTypeOfPlantsWordingException; public class TypeOfPlantsFormController extends Controller { /** * The title. */ @FXML private Label title; /** * The wording label. */ @FXML private Label wordingLabel; /** * The wording. */ @FXML private TextField wording; /** * The valid button. */ @FXML private Button valid; /** * The cancel button. */ @FXML private Button cancel; /** * If it's update form. */ private boolean isUpdateForm; /** * The type of plants. */ private TypeOfPlants typeOfPlants; /** * The type of plants services. */ private TypeOfPlantsServices typeOfPlantsServices; /** * The stage. */ private Stage stage; /** * The bundle. */ private ResourceBundle bundle; /** * Create a type of plants form controller. * * @param typeOfPlants * The type of plants. * @param typeOfPlantsServices * The type of plants services. * @param stage * The stage. * @param bundle * The bundle. */ public TypeOfPlantsFormController(TypeOfPlants typeOfPlants, TypeOfPlantsServices typeOfPlantsServices, Stage stage, ResourceBundle bundle) { this.typeOfPlants = typeOfPlants; this.typeOfPlantsServices = typeOfPlantsServices; this.stage = stage; this.bundle = bundle; if (this.typeOfPlants == null) { this.title.setText(this.bundle.getString("typeOfPlantsAdditionFormTitle")); this.wording.setPromptText(this.bundle.getString("typeOfPlantsWordingPromptText")); this.isUpdateForm = false; } else { this.title.setText(this.bundle.getString("typeOfPlantsModificationFormTitle")); this.wording.setText(this.typeOfPlants.getWording()); this.isUpdateForm = true; } this.wordingLabel.setText(this.bundle.getString("typeOfPlantsWordingLabel")); this.valid.setText(this.bundle.getString("typeOfPlantsValidButton")); this.cancel.setText(this.bundle.getString("typeOfPlantsCancelButton")); this.stage.setResizable(false); } /** * The on click valid action. */ public void onValidAction() { try { if (this.isUpdateForm) { this.typeOfPlantsServices.updateTypeOfPlants(this.wording.getText(), this.typeOfPlants); this.displayInformation(this.bundle.getString("operationSuccess"), null, this.bundle.getString("typeOfPlantsModificationSuccess")); this.stage.close(); } else { this.typeOfPlantsServices.addTypeOfPlants(this.wording.getText()); this.displayInformation(this.bundle.getString("operationSuccess"), null, this.bundle.getString("typeOfPlantsAdditionSuccess")); this.stage.close(); } } catch (MissingTypeOfPlantsIdException | MissingTypeOfPlantsWordingException | InvalidTypeOfPlantsIdException | InvalidTypeOfPlantsWordingException e) { this.displayError(this.bundle.getString("invalidFormTitle"), this.bundle.getString("invalidFormHeader"), e.getMessage()); } catch (ClassNotFoundException e) { this.saveError(this.bundle.getString("errorFilePath"), this.bundle.getString("errorFileExtension"), e); this.displayError(this.bundle.getString("driverErrorTitle"), this.bundle.getString("driverErrorHeader"), e.getMessage()); } catch (SQLException e) { this.saveError(this.bundle.getString("errorFilePath"), this.bundle.getString("errorFileExtension"), e); this.displayError(this.bundle.getString("sqlErrorTitle"), this.bundle.getString("sqlErrorHeader"), e.getMessage()); } catch (IOException e) { this.saveError(this.bundle.getString("errorFilePath"), this.bundle.getString("errorFileExtension"), e); this.displayError(this.bundle.getString("ioErrorTitle"), this.bundle.getString("ioErrorHeader"), e.getMessage()); } } /** * The on click cancel action. */ public void onCancelAction() { this.stage.close(); } }
package nl.mvdr.tinustris.engine; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import nl.mvdr.tinustris.gui.GameRenderer; import nl.mvdr.tinustris.input.InputController; import nl.mvdr.tinustris.input.InputState; import nl.mvdr.tinustris.model.FrameAndInputStatesContainer; import nl.mvdr.tinustris.model.GameState; import nl.mvdr.tinustris.model.GameStateHolder; /** * Offers functionality for starting and stopping the game loop. * * @param <S> game state type * * @author Martijn van de Rijdt */ @Slf4j @RequiredArgsConstructor @ToString public class GameLoop<S extends GameState> { /** Update rate for the game state. */ private static final double GAME_HERTZ = 60.0; /** How much time each frame should take for our target update rate, in nanoseconds. */ public static final double TIME_BETWEEN_UPDATES = 1_000_000_000 / GAME_HERTZ; /** At the very most we will update the game this many times before a new render. **/ private static final int MAX_UPDATES_BEFORE_RENDER = 5; /** Target frame rate for rendering the game. May be lower than the update rate. */ private static final double TARGET_FPS = GAME_HERTZ; /** Target time between renders, in nanoseconds. */ private static final double TARGET_TIME_BETWEEN_RENDERS = 1_000_000_000 / TARGET_FPS; /** Input controllers. */ @NonNull private final List<InputController> inputControllers; /** Game engine. */ @NonNull private final GameEngine<S> gameEngine; /** Game renderer. */ @NonNull private final GameRenderer<S> gameRenderer; /** Game state holder. */ @NonNull private final GameStateHolder<S> holder; /** Input listeners. */ @NonNull private final List<Consumer<FrameAndInputStatesContainer>> localInputListeners; /** Indicates whether the game should be running. */ @Getter private boolean running; /** Indicates whether the game is paused. */ private boolean paused; /** Starts the game loop. */ public void start() { running = true; paused = false; Thread loop = new Thread(this::gameLoop, "Game loop"); loop.start(); } /** Game loop. Should be run on a dedicated thread. */ private void gameLoop() { // The moment the game state was last updated. double lastUpdateTime = System.nanoTime(); // The moment the game was last rendered. double lastRenderTime = System.nanoTime(); // Number of frames processed in the current second. int framesThisSecond = 0; // Start of the current second. int lastSecondTime = (int) (lastUpdateTime / 1_000_000_000); // Total frame counter. int totalUpdateCount = 0; holder.addGameState(gameEngine.initGameState()); gameRenderer.render(holder.retrieveLatestGameState()); log.info("Starting main game loop."); try { while (running && !holder.isGameOver()) { double now = System.nanoTime(); int updateCount = 0; if (!paused) { // Do as many game updates as we need to, potentially playing catchup. while (TIME_BETWEEN_UPDATES < now - lastUpdateTime && updateCount < MAX_UPDATES_BEFORE_RENDER) { List<InputState> inputStates = retrieveAndPublishInputStates(totalUpdateCount); S gameState = holder.retrieveLatestGameState(); gameState = gameEngine.computeNextState(holder.retrieveLatestGameState(), inputStates); holder.addGameState(gameState); lastUpdateTime += TIME_BETWEEN_UPDATES; updateCount++; totalUpdateCount++; } // If for some reason an update takes forever, we don't want to do an insane number of catchups. // If you were doing some sort of game that needed to keep EXACT time, you would get rid of this. if (now - lastUpdateTime > TIME_BETWEEN_UPDATES) { lastUpdateTime = now - TIME_BETWEEN_UPDATES; } // Render. gameRenderer.render(holder.retrieveLatestGameState()); framesThisSecond++; lastRenderTime = now; // Log the number of frames. int thisSecond = (int) (lastUpdateTime / 1_000_000_000); if (lastSecondTime < thisSecond) { log.info("New second: {}, frames in previous second: {}, total update count: {}.", thisSecond, framesThisSecond, totalUpdateCount); framesThisSecond = 0; lastSecondTime = thisSecond; } // Yield until it has been at least the target time between renders. This saves the CPU from // hogging. while (now - lastRenderTime < TARGET_TIME_BETWEEN_RENDERS && now - lastUpdateTime < TIME_BETWEEN_UPDATES) { Thread.yield(); // This stops the app from consuming all your CPU. It makes this slightly less accurate, but is // worth it. You can remove this line and it will still work (better), your CPU just climbs on // certain OSes. Thread.sleep(1); now = System.nanoTime(); } } } } catch (RuntimeException | InterruptedException e) { // In case of InterruptedException: no need to re-interrupt the thread, it will terminate immediately. log.error("Fatal exception encountered in game loop.", e); } running = false; log.info("Finished main game loop. Final game state: {}", holder.retrieveLatestGameState()); } /** * Retrieves the current inputs for all players. * * @param updateIndex index of the current frame / update * @return inputs */ private List<InputState> retrieveAndPublishInputStates(int updateIndex) { // Get the input states. List<InputState> inputStates = inputControllers.stream() .map(InputController::getInputState) .collect(Collectors.toList()); // Inform listeners of new local inputs Map<Integer, InputState> inputStateMap = IntStream.range(0, inputStates.size()) .filter(i -> inputControllers.get(i).isLocal()) .boxed() .collect(Collectors.toMap(Function.identity(), inputStates::get)); localInputListeners.forEach(listener -> listener.accept(new FrameAndInputStatesContainer(updateIndex, inputStateMap))); return inputStates; } /** Stops the game loop. */ public void stop() { log.info("Stopping the game."); running = false; } /** Pauses the game. */ public void pause() { log.info("Pausing the game."); paused = true; } /** Unpauses the game. */ public void unpause() { log.info("Unpausing the game."); paused = false; } /** Pauses or unpauses the game. */ public void togglePaused() { log.info("Toggling the pause."); paused = !paused; log.info("Game paused: " + paused); } }
package ca.concordia.cssanalyser.preprocessors.util.less; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import com.github.sommeri.less4j.LessSource; import com.github.sommeri.less4j.core.ast.ASTCssNode; import com.github.sommeri.less4j.core.ast.CssString; import com.github.sommeri.less4j.core.ast.Expression; import com.github.sommeri.less4j.core.ast.FunctionExpression; import com.github.sommeri.less4j.core.ast.Import; import com.github.sommeri.less4j.core.ast.StyleSheet; import ca.concordia.cssanalyser.app.FileLogger; import ca.concordia.cssanalyser.io.IOHelper; import ca.concordia.cssanalyser.migration.topreprocessors.less.LessPrinter; import ca.concordia.cssanalyser.parser.less.LessCSSParser; import ca.concordia.cssanalyser.parser.less.ModifiedLessFileSource; public class ImportInliner { private static final Logger LOGGER = FileLogger.getLogger(ImportInliner.class); public static void inlineImportsAll(String inputPath, boolean onlyReplaceLess) { List<File> files = IOHelper.searchForFiles(inputPath, ".less"); inlineImportsAll(files, onlyReplaceLess); } public static void inlineImportsAll(List<File> filesList, boolean onlyImportLessFiles) { for (File lessFile : filesList) { LOGGER.info("Inlining imports in {}", lessFile.getAbsolutePath()); replaceImports(lessFile.getAbsolutePath(), onlyImportLessFiles); } } public static void replaceImports(String lessFilePath, boolean onlyImportLessFiles) { try { String replacedImports = replaceImports(new File(lessFilePath), onlyImportLessFiles); if (!"".equals(replacedImports)) IOHelper.writeStringToFile(replacedImports, getOutputFilePath(lessFilePath)); } catch (IOException e) { e.printStackTrace(); } } static String replaceImports(File lessFile, boolean onlyImportLessFiles) throws IOException { try { StyleSheet lessStyleSheet = LessCSSParser.getLessStyleSheet(new ModifiedLessFileSource(lessFile)); List<Import> allImports = getAllImports(lessStyleSheet); String toReturn = IOHelper.readFileToString(lessFile.getAbsolutePath()); for(Import importNode : allImports) { try { String url = getURLFromImportStatement(importNode); if (!"".equals(url)) { if (!onlyImportLessFiles && url.endsWith(".css")) continue; if (url.contains("@{")) { LOGGER.warn("In {} (line {}) URL expression has to be evaluated because it needs string interpolation", lessFile.getAbsolutePath(), importNode.getSourceLine()); } else { // Inline! File importedFile = new File(url); if (!importedFile.isAbsolute()) { importedFile = new File(url); url = lessFile.getParentFile().getAbsolutePath() + File.separator + url; } if (!importedFile.exists()) { if (url.toLowerCase().lastIndexOf(".less") != url.length() - 5) { importedFile = new File(url + ".less"); } if (!onlyImportLessFiles && !importedFile.exists()) { if (url.toLowerCase().lastIndexOf(".css") != url.length() - 4) { importedFile = new File(url + ".css"); } } } if (importedFile.exists()) { String importedFileText = replaceImports(importedFile, onlyImportLessFiles); try { StyleSheet replacedImportsImportedStyleSheet = LessCSSParser.getLessStyleSheet(new LessSource.StringSource(importedFileText)); lessStyleSheet.addMemberAfter(replacedImportsImportedStyleSheet, importNode); } catch (RuntimeException rte) { LOGGER.warn(lessFile.getAbsolutePath()); rte.printStackTrace(); } lessStyleSheet.removeMember(importNode); toReturn = (new LessPrinter()).getString(lessStyleSheet); } else { LOGGER.warn("In {} (line {}), imported file {} does not exist", lessFile.getAbsolutePath(), importNode.getSourceLine(), url); } } } } catch (Exception ex) { ex.printStackTrace(); } } return toReturn; } catch (Exception e) { e.printStackTrace(); } return ""; } public static String getURLFromImportStatement(Import importNode) throws Exception { Expression urlExpression = importNode.getUrlExpression(); String url = ""; if (urlExpression instanceof CssString) { CssString cssString = (CssString) urlExpression; url = cssString.getValue(); } else if (urlExpression instanceof FunctionExpression) { FunctionExpression functionExpression = (FunctionExpression) urlExpression; if ("url".equals(functionExpression.getName())) { url = (new LessPrinter()).getStringForNode(functionExpression.getParameter()); if (url.startsWith("'") || url.startsWith("\"")) // Remove quotes url = url.substring(1, url.length() - 1); } else { throw new Exception( String.format( "Cannot handle function %s when importing at line %s: ", functionExpression.getSourceLine(), functionExpression.getName() )); } } else { throw new Exception( String.format("In line %s, the URL expression is of type %s", urlExpression.getSourceLine(), urlExpression.getClass().getName())); } return url; } public static List<Import> getAllImports(ASTCssNode child) { List<Import> toReturn = new ArrayList<>(); if (child instanceof Import) toReturn.add((Import)child); else { for (ASTCssNode c : child.getChilds()) toReturn.addAll(getAllImports(c)); } return toReturn; } private static String getOutputFilePath(String inputFilePath) { File inputFile = new File(inputFilePath); int dotPosition = inputFile.getName().lastIndexOf("."); String outputFileName = inputFile.getName(); String extension = ""; if (dotPosition >= 0) { extension = inputFile.getName().substring(dotPosition + 1); outputFileName = outputFileName.replace(extension, ""); } outputFileName += "importsInlined." + extension; return inputFile.getParentFile().getAbsolutePath() + File.separator + outputFileName; } }
package com.blackducksoftware.integration.hub.bamboo.tasks; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.joda.time.DateTime; import org.restlet.engine.Engine; import org.restlet.engine.connector.HttpClientHelper; import com.atlassian.bamboo.configuration.ConfigurationMap; import com.atlassian.bamboo.fileserver.SystemDirectory; import com.atlassian.bamboo.process.EnvironmentVariableAccessor; import com.atlassian.bamboo.process.ProcessService; import com.atlassian.bamboo.task.TaskContext; import com.atlassian.bamboo.task.TaskException; import com.atlassian.bamboo.task.TaskResult; import com.atlassian.bamboo.task.TaskResultBuilder; import com.atlassian.bamboo.task.TaskType; import com.atlassian.bamboo.v2.build.BuildContext; import com.atlassian.util.concurrent.NotNull; import com.blackducksoftware.integration.hub.HubIntRestService; import com.blackducksoftware.integration.hub.HubSupportHelper; import com.blackducksoftware.integration.hub.ScanExecutor; import com.blackducksoftware.integration.hub.ScanExecutor.Result; import com.blackducksoftware.integration.hub.bamboo.BDBambooHubPluginException; import com.blackducksoftware.integration.hub.bamboo.HubBambooLogger; import com.blackducksoftware.integration.hub.bamboo.HubBambooUtils; import com.blackducksoftware.integration.hub.bamboo.config.ConfigManager; import com.blackducksoftware.integration.hub.bamboo.config.HubConfig; import com.blackducksoftware.integration.hub.bamboo.config.HubProxyInfo; import com.blackducksoftware.integration.hub.cli.CLIInstaller; import com.blackducksoftware.integration.hub.exception.BDRestException; import com.blackducksoftware.integration.hub.exception.HubIntegrationException; import com.blackducksoftware.integration.hub.exception.MissingPolicyStatusException; import com.blackducksoftware.integration.hub.exception.ProjectDoesNotExistException; import com.blackducksoftware.integration.hub.exception.VersionDoesNotExistException; import com.blackducksoftware.integration.hub.job.HubScanJobConfig; import com.blackducksoftware.integration.hub.job.HubScanJobConfigBuilder; import com.blackducksoftware.integration.hub.logging.IntLogger; import com.blackducksoftware.integration.hub.policy.api.PolicyStatus; import com.blackducksoftware.integration.hub.policy.api.PolicyStatusEnum; import com.blackducksoftware.integration.hub.polling.HubEventPolling; import com.blackducksoftware.integration.hub.project.api.ProjectItem; import com.blackducksoftware.integration.hub.report.api.HubReportGenerationInfo; import com.blackducksoftware.integration.hub.util.HostnameHelper; import com.blackducksoftware.integration.hub.version.api.DistributionEnum; import com.blackducksoftware.integration.hub.version.api.PhaseEnum; import com.blackducksoftware.integration.hub.version.api.ReleaseItem; public class HubScanTask implements TaskType { private final static String CLI_FOLDER_NAME = "tools/HubCLI"; private final ConfigManager configManager; private final ProcessService processService; private final EnvironmentVariableAccessor environmentVariableAccessor; public HubScanTask(final ConfigManager configManager, final ProcessService processService, final EnvironmentVariableAccessor environmentVariableAccessor) { this.configManager = configManager; this.processService = processService; this.environmentVariableAccessor = environmentVariableAccessor; } public TaskResult execute(final TaskContext taskContext) throws TaskException { final TaskResultBuilder resultBuilder = TaskResultBuilder.newBuilder(taskContext).success(); final HubBambooLogger logger = new HubBambooLogger(taskContext.getBuildLogger()); try { final HubConfig hubConfig = configManager.readConfig(); final HubIntRestService service = getService(hubConfig); final HubScanJobConfig jobConfig = getJobConfig(taskContext.getConfigurationMap(), taskContext.getWorkingDirectory(), logger); final HubProxyInfo proxyInfo = HubBambooUtils.getInstance().createProxyInfo(hubConfig); printGlobalConfiguration(hubConfig, proxyInfo, logger); printConfiguration(taskContext, hubConfig, logger, jobConfig); service.setCookies(hubConfig.getHubUser(), hubConfig.getHubPass()); final String localHostName = HostnameHelper.getMyHostname(); logger.info("Running on machine : " + localHostName); // install the CLI final CLIInstaller installer = installCLI(logger, service, localHostName); if (installer == null || !installer.getCLIExists(logger)) { logger.error("Could not find the Hub scan CLI"); resultBuilder.failed(); return resultBuilder.build(); } final File hubCLI = installer.getCLI(); final File oneJarFile = installer.getOneJarFile(); final File javaExec = installer.getProvidedJavaExec(); final HubSupportHelper hubSupport = new HubSupportHelper(); hubSupport.checkHubSupport(service, logger); ProjectItem project = null; ReleaseItem version = null; final String projectName = jobConfig.getProjectName(); final String projectVersion = jobConfig.getVersion(); if (StringUtils.isNotBlank(projectName) && StringUtils.isNotBlank(projectVersion)) { project = ensureProjectExists(service, logger, projectName); version = ensureVersionExists(service, logger, projectVersion, project, jobConfig); logger.debug("Found Project : " + projectName); logger.debug("Found Version : " + projectVersion); } // run the scan final DateTime beforeScanTime = new DateTime(); final ScanExecutor scan = performScan(taskContext, resultBuilder, logger, service, oneJarFile, hubCLI, javaExec, hubConfig, jobConfig, proxyInfo, hubSupport); final DateTime afterScanTime = new DateTime(); // check the policy failures final boolean isFailOnPolicySelected = taskContext.getConfigurationMap() .getAsBoolean(HubScanParamEnum.FAIL_ON_POLICY_VIOLATION.getKey()); if (isFailOnPolicySelected && !hubSupport.isPolicyApiSupport()) { logger.error("This version of the Hub does not have support for Policies."); resultBuilder.failed(); return resultBuilder.build(); } else if (isFailOnPolicySelected) { final HubReportGenerationInfo bomUpdateInfo = new HubReportGenerationInfo(); bomUpdateInfo.setService(service); bomUpdateInfo.setHostname(HostnameHelper.getMyHostname()); bomUpdateInfo.setScanTargets(jobConfig.getScanTargetPaths()); bomUpdateInfo.setMaximumWaitTime(jobConfig.getMaxWaitTimeForBomUpdateInMilliseconds()); bomUpdateInfo.setBeforeScanTime(beforeScanTime); bomUpdateInfo.setAfterScanTime(afterScanTime); bomUpdateInfo.setScanStatusDirectory(scan.getScanStatusDirectoryPath()); final TaskResultBuilder policyResult = checkPolicyFailures(resultBuilder, taskContext, logger, service, hubSupport, bomUpdateInfo, version.getLink(ReleaseItem.POLICY_STATUS_LINK)); return policyResult.build(); } } catch (final HubIntegrationException e) { logger.error("Hub Scan Task error", e); } catch (final URISyntaxException e) { logger.error("Hub Scan Task error", e); } catch (final BDRestException e) { logger.error("Hub Scan Task error", e); } catch (final IOException e) { logger.error("Hub Scan Task error", e); } catch (final InterruptedException e) { logger.error("Hub Scan Task error", e); } catch (final BDBambooHubPluginException e) { logger.error("Hub Scan Task error", e); } return resultBuilder.build(); } private HubScanJobConfig getJobConfig(final ConfigurationMap configMap, final File workingDirectory, final IntLogger logger) throws HubIntegrationException, IOException { final String project = configMap.get(HubScanParamEnum.PROJECT.getKey()); final String version = configMap.get(HubScanParamEnum.VERSION.getKey()); final String phase = configMap.get(HubScanParamEnum.PHASE.getKey()); final String distribution = configMap.get(HubScanParamEnum.DISTRIBUTION.getKey()); final String generateRiskReport = configMap.get(HubScanParamEnum.GENERATE_RISK_REPORT.getKey()); final String maxWaitTimeForBomUpdate = configMap.get(HubScanParamEnum.MAX_WAIT_TIME_FOR_BOM_UPDATE.getKey()); final String scanMemory = configMap.get(HubScanParamEnum.SCANMEMORY.getKey()); final String targets = configMap.get(HubScanParamEnum.TARGETS.getKey()); final List<String> scanTargets = HubBambooUtils.getInstance().createScanTargetPaths(targets, workingDirectory); if (scanTargets.isEmpty()) { // no targets specified assume the working directory. scanTargets.add(workingDirectory.getAbsolutePath()); } final HubScanJobConfigBuilder hubScanJobConfigBuilder = new HubScanJobConfigBuilder(); hubScanJobConfigBuilder.setProjectName(project); hubScanJobConfigBuilder.setVersion(version); hubScanJobConfigBuilder.setPhase(PhaseEnum.getPhaseByDisplayValue(phase).name()); hubScanJobConfigBuilder.setDistribution(DistributionEnum.getDistributionByDisplayValue(distribution).name()); hubScanJobConfigBuilder.setWorkingDirectory(workingDirectory.getAbsolutePath()); hubScanJobConfigBuilder.setShouldGenerateRiskReport(generateRiskReport); hubScanJobConfigBuilder.setMaxWaitTimeForBomUpdate(maxWaitTimeForBomUpdate); hubScanJobConfigBuilder.setScanMemory(scanMemory); hubScanJobConfigBuilder.addAllScanTargetPaths(scanTargets); hubScanJobConfigBuilder.disableScanTargetPathExistenceCheck(); return hubScanJobConfigBuilder.build(logger); } private CLIInstaller installCLI(final IntLogger logger, final HubIntRestService restService, final String localHostName) { logger.info("Checking Hub CLI installation"); try { final File toolsDir = new File(SystemDirectory.getApplicationHome(), CLI_FOLDER_NAME); // make the directories for the hub scan CLI tool if (!toolsDir.exists()) { toolsDir.mkdirs(); } final CLIInstaller installer = new CLIInstaller(toolsDir); installer.performInstallation(logger, restService, localHostName); return installer; } catch (final IOException e) { logger.error(e); } catch (final InterruptedException e) { logger.error(e); } catch (final BDRestException e) { logger.error(e); } catch (final URISyntaxException e) { logger.error(e); } catch (final HubIntegrationException e) { logger.error(e); } catch (final Exception e) { logger.error(e); } return null; } private HubIntRestService getService(final HubConfig hubConfig) { // configure the Restlet engine so that the HTTPHandle and classes // from the com.sun.net.httpserver package // do not need to be used at runtime to make client calls. // DO NOT REMOVE THIS or the OSGI bundle will throw a // ClassNotFoundException for com.sun.net.httpserver.HttpHandler. // Since we are acting as a client we do not need the httpserver // components. // This workaround found here: Engine.register(false); Engine.getInstance().getRegisteredClients().add(new HttpClientHelper(null)); final HubIntRestService service = new HubIntRestService(hubConfig.getHubUrl()); HubBambooUtils.getInstance().configureProxyToService(hubConfig, service); return service; } public void printGlobalConfiguration(final HubConfig hubConfig, final HubProxyInfo proxyInfo, final IntLogger logger) { if (hubConfig == null) { return; } logger.info("--> Hub Server Url : " + hubConfig.getHubUrl()); if (StringUtils.isNotBlank(hubConfig.getHubUser())) { logger.info("--> Hub User : " + hubConfig.getHubUser()); } if (proxyInfo != null) { if (StringUtils.isNotBlank(proxyInfo.getHost())) { logger.info("--> Proxy Host : " + proxyInfo.getHost()); } if (proxyInfo.getPort() != null) { logger.info("--> Proxy Port : " + proxyInfo.getPort()); } if (StringUtils.isNotBlank(proxyInfo.getIgnoredProxyHosts())) { logger.info("--> No Proxy Hosts : " + proxyInfo.getIgnoredProxyHosts()); } if (StringUtils.isNotBlank(proxyInfo.getProxyUsername())) { logger.info("--> Proxy Username : " + proxyInfo.getProxyUsername()); } } } public void printConfiguration(final TaskContext taskContext, final HubConfig hubConfig, final IntLogger logger, final HubScanJobConfig jobConfig) throws IOException, InterruptedException { logger.info("Initializing - Hub Bamboo Plugin"); logger.info("-> Bamboo home directory: " + SystemDirectory.getApplicationHome()); final BuildContext buildContext = taskContext.getBuildContext(); logger.info("-> Using Url : " + hubConfig.getHubUrl()); logger.info("-> Using Username : " + hubConfig.getHubUser()); logger.info("-> Using Build Full Name : " + buildContext.getDisplayName()); logger.info("-> Using Build Number : " + buildContext.getBuildNumber()); logger.info("-> Using Build Workspace Path : " + taskContext.getWorkingDirectory().getAbsolutePath()); logger.info( "-> Using Hub Project Name : " + jobConfig.getProjectName() + ", Version : " + jobConfig.getVersion() + ", Phase : " + jobConfig.getPhase() + ", Distribution : " + jobConfig.getDistribution()); logger.info("-> Scanning the following targets : "); for (final String target : jobConfig.getScanTargetPaths()) { logger.info("-> " + target); } // logger.info("-> Generate Hub report : " + // jobConfig.isShouldGenerateRiskReport()); final String formattedTime = String.format("%d minutes", TimeUnit.MILLISECONDS.toMinutes(jobConfig.getMaxWaitTimeForBomUpdateInMilliseconds())); logger.info("-> Maximum wait time for the BOM Update : " + formattedTime); } public ScanExecutor performScan(final TaskContext taskContext, final TaskResultBuilder resultBuilder, final IntLogger logger, final HubIntRestService service, final File oneJarFile, final File scanExec, File javaExec, final HubConfig hubConfig, final HubScanJobConfig jobConfig, final HubProxyInfo proxyInfo, final HubSupportHelper supportHelper) throws HubIntegrationException, MalformedURLException, URISyntaxException { final BambooScanExecutor scan = new BambooScanExecutor(hubConfig.getHubUrl(), hubConfig.getHubUser(), hubConfig.getHubPass(), jobConfig.getScanTargetPaths(), taskContext.getBuildContext().getBuildNumber(), supportHelper); scan.setLogger(logger); scan.setTaskContext(taskContext); scan.setProcessService(processService); scan.setEnvironmentVariableAccessor(environmentVariableAccessor); if (proxyInfo != null) { final URL hubUrl = new URL(hubConfig.getHubUrl()); if (!HubProxyInfo.checkMatchingNoProxyHostPatterns(hubUrl.getHost(), proxyInfo.getNoProxyHostPatterns())) { addProxySettingsToScanner(logger, scan, proxyInfo); } } scan.setScanMemory(jobConfig.getScanMemory()); scan.setWorkingDirectory(jobConfig.getWorkingDirectory()); scan.setVerboseRun(true); if (StringUtils.isNotBlank(jobConfig.getProjectName()) && StringUtils.isNotBlank(jobConfig.getVersion())) { scan.setProject(jobConfig.getProjectName()); scan.setVersion(jobConfig.getVersion()); } if (javaExec == null) { String javaHome = getEnvironmentVariable("JAVA_HOME", logger); if (StringUtils.isBlank(javaHome)) { // We couldn't get the JAVA_HOME variable so lets try to get the // home // of the java that is running this process javaHome = System.getProperty("java.home"); } javaExec = new File(javaHome); if (StringUtils.isBlank(javaHome) || javaExec == null || !javaExec.exists()) { throw new HubIntegrationException( "The JAVA_HOME could not be determined, the Hub CLI can not be executed."); } javaExec = new File(javaExec, "bin"); if (SystemUtils.IS_OS_WINDOWS) { javaExec = new File(javaExec, "java.exe"); } else { javaExec = new File(javaExec, "java"); } } final Result scanResult = scan.setupAndRunScan(scanExec.getAbsolutePath(), oneJarFile.getAbsolutePath(), javaExec.getAbsolutePath()); if (scanResult != Result.SUCCESS) { resultBuilder.failed(); // fail build } return scan; } public void addProxySettingsToScanner(final IntLogger logger, final BambooScanExecutor scan, final HubProxyInfo proxyInfo) throws HubIntegrationException, URISyntaxException, MalformedURLException { if (proxyInfo != null) { if (StringUtils.isNotBlank(proxyInfo.getHost()) && proxyInfo.getPort() != 0) { if (StringUtils.isNotBlank(proxyInfo.getProxyUsername()) && StringUtils.isNotBlank(proxyInfo.getProxyPassword())) { scan.setProxyHost(proxyInfo.getHost()); scan.setProxyPort(proxyInfo.getPort()); scan.setProxyUsername(proxyInfo.getProxyUsername()); scan.setProxyPassword(proxyInfo.getProxyPassword()); } else { scan.setProxyHost(proxyInfo.getHost()); scan.setProxyPort(proxyInfo.getPort()); } if (logger != null) { logger.debug("Using proxy: '" + proxyInfo.getHost() + "' at Port: '" + proxyInfo.getPort() + "'"); } } } } private ProjectItem ensureProjectExists(final HubIntRestService service, final IntLogger logger, final String projectName) throws IOException, URISyntaxException, BDBambooHubPluginException { ProjectItem project = null; try { project = service.getProjectByName(projectName); } catch (final NullPointerException npe) { project = createProject(service, logger, projectName); } catch (final ProjectDoesNotExistException e) { project = createProject(service, logger, projectName); } catch (final BDRestException e) { if (e.getResource() != null) { if (e.getResource() != null) { logger.error("Status : " + e.getResource().getStatus().getCode()); logger.error("Response : " + e.getResource().getResponse().getEntityAsText()); } throw new BDBambooHubPluginException("Problem getting the Project. ", e); } } return project; } private ProjectItem createProject(final HubIntRestService service, final IntLogger logger, final String projectName) throws IOException, URISyntaxException, BDBambooHubPluginException { // Project was not found, try to create it ProjectItem project = null; try { final String projectUrl = service.createHubProject(projectName); project = service.getProject(projectUrl); } catch (final BDRestException e1) { if (e1.getResource() != null) { logger.error("Status : " + e1.getResource().getStatus().getCode()); logger.error("Response : " + e1.getResource().getResponse().getEntityAsText()); } throw new BDBambooHubPluginException("Problem creating the Project. ", e1); } return project; } /** * Ensures the Version exists. Returns the version URL */ private ReleaseItem ensureVersionExists(final HubIntRestService service, final IntLogger logger, final String projectVersion, final ProjectItem project, final HubScanJobConfig jobConfig) throws IOException, URISyntaxException, BDBambooHubPluginException { ReleaseItem version = null; try { version = service.getVersion(project, projectVersion); if (!version.getPhase().equals(jobConfig.getPhase())) { logger.warn( "The selected Phase does not match the Phase of this Version. If you wish to update the Phase please do so in the Hub UI."); } if (!version.getDistribution().equals(jobConfig.getDistribution())) { logger.warn( "The selected Distribution does not match the Distribution of this Version. If you wish to update the Distribution please do so in the Hub UI."); } } catch (final NullPointerException npe) { version = createVersion(service, logger, projectVersion, project, jobConfig); } catch (final VersionDoesNotExistException e) { version = createVersion(service, logger, projectVersion, project, jobConfig); } catch (final BDRestException e) { throw new BDBambooHubPluginException("Could not retrieve or create the specified version.", e); } return version; } private ReleaseItem createVersion(final HubIntRestService service, final IntLogger logger, final String projectVersion, final ProjectItem project, final HubScanJobConfig jobConfig) throws IOException, URISyntaxException, BDBambooHubPluginException { ReleaseItem version = null; try { final String versionURL = service.createHubVersion(project, projectVersion, jobConfig.getPhase(), jobConfig.getDistribution()); version = service.getProjectVersion(versionURL); } catch (final BDRestException e1) { if (e1.getResource() != null) { logger.error("Status : " + e1.getResource().getStatus().getCode()); logger.error("Response : " + e1.getResource().getResponse().getEntityAsText()); } throw new BDBambooHubPluginException("Problem creating the Version. ", e1); } return version; } private String getEnvironmentVariable(@NotNull final String parameterName, final IntLogger logger) { final Map<String, String> envVars = environmentVariableAccessor.getEnvironment(); final String value = envVars.get(parameterName); if (value == null || value.trim().length() == 0) { return null; } final String result = value.trim(); return result; } private TaskResultBuilder checkPolicyFailures(final TaskResultBuilder resultBuilder, final TaskContext taskContext, final IntLogger logger, final HubIntRestService service, final HubSupportHelper hubSupport, final HubReportGenerationInfo bomUpdateInfo, final String policyStatusUrl) { try { waitForBomToBeUpdated(logger, service, hubSupport, bomUpdateInfo, taskContext); try { // We use this conditional in case there are other failure // conditions in the future final PolicyStatus policyStatus = service.getPolicyStatus(policyStatusUrl); if (policyStatus == null) { logger.error("Could not find any information about the Policy status of the bom."); return resultBuilder.failed(); } if (policyStatus.getOverallStatusEnum() == PolicyStatusEnum.IN_VIOLATION) { return resultBuilder.failed(); } if (policyStatus.getCountInViolation() == null) { logger.error("Could not find the number of bom entries In Violation of a Policy."); } else { logger.info("Found " + policyStatus.getCountInViolation().getValue() + " bom entries to be In Violation of a defined Policy."); } if (policyStatus.getCountInViolationOverridden() == null) { logger.error("Could not find the number of bom entries In Violation Overridden of a Policy."); } else { logger.info("Found " + policyStatus.getCountInViolationOverridden().getValue() + " bom entries to be In Violation of a defined Policy, but they have been overridden."); } if (policyStatus.getCountNotInViolation() == null) { logger.error("Could not find the number of bom entries Not In Violation of a Policy."); } else { logger.info("Found " + policyStatus.getCountNotInViolation().getValue() + " bom entries to be Not In Violation of a defined Policy."); } return resultBuilder.success(); } catch (final MissingPolicyStatusException e) { logger.warn(e.getMessage()); return resultBuilder.success(); } } catch (final BDBambooHubPluginException e) { logger.error(e.getMessage(), e); return resultBuilder.failed(); } catch (final HubIntegrationException e) { logger.error(e.getMessage(), e); return resultBuilder.failed(); } catch (final URISyntaxException e) { logger.error(e.getMessage(), e); return resultBuilder.failed(); } catch (final BDRestException e) { logger.error(e.getMessage(), e); return resultBuilder.failed(); } catch (final InterruptedException e) { logger.error(e.getMessage(), e); return resultBuilder.failed(); } catch (final IOException e) { logger.error(e.getMessage(), e); return resultBuilder.failed(); } } public void waitForBomToBeUpdated(final IntLogger logger, final HubIntRestService service, final HubSupportHelper supportHelper, final HubReportGenerationInfo bomUpdateInfo, final TaskContext taskContext) throws BDBambooHubPluginException, InterruptedException, BDRestException, HubIntegrationException, URISyntaxException, IOException { final HubEventPolling hubEventPolling = new HubEventPolling(service); if (supportHelper.isCliStatusDirOptionSupport()) { hubEventPolling.assertBomUpToDate(bomUpdateInfo, logger); } else { hubEventPolling.assertBomUpToDate(bomUpdateInfo); } } }
package org.wso2.carbon.uuf.core; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; public class StaticLookup { private final String componentName; private final String componentContext; private final SetMultimap<String, Renderable> bindings; private final Map<String, Fragment> fragments; public StaticLookup(String componentName, String componentContext, Set<Fragment> fragments, SetMultimap<String, ? extends Renderable> bindings, Set<Component> childComponents) { this.componentName = componentName + "."; this.componentContext = componentContext; this.fragments = fragments.stream().collect(Collectors.toMap(f -> getFullyQualifiedName(f.getName()), f -> f)); this.bindings = HashMultimap.create(); for (Map.Entry<String, ? extends Renderable> entry : bindings.entries()) { this.bindings.put(getFullyQualifiedName(entry.getKey()), entry.getValue()); } for (Component childComponent : childComponents) { StaticLookup childComponentStaticLookup = childComponent.getStaticLookup(); this.fragments.putAll(childComponentStaticLookup.fragments); this.bindings.putAll(childComponentStaticLookup.bindings); } } private String getFullyQualifiedName(String name) { return componentName + name; } public Optional<Set<? extends Renderable>> getBindings(String zoneName) { if (zoneName.indexOf('.') == -1) { zoneName = getFullyQualifiedName(zoneName); } return Optional.ofNullable(bindings.get(zoneName)); } public Optional<Fragment> getFragment(String fragmentName) { return Optional.ofNullable(fragments.get(fragmentName)); } }
package com.elmakers.mine.bukkit.action.builtin; import com.elmakers.mine.bukkit.action.CompoundAction; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.effect.EffectPlay; import com.elmakers.mine.bukkit.api.effect.EffectPlayer; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellResult; import com.elmakers.mine.bukkit.api.spell.TargetType; import com.elmakers.mine.bukkit.math.VectorTransform; import com.elmakers.mine.bukkit.spell.BaseSpell; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.Target; import com.elmakers.mine.bukkit.utility.Targeting; import de.slikey.effectlib.util.DynamicLocation; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.UUID; public class CustomProjectileAction extends CompoundAction { private Targeting targeting; private int interval; private int lifetime; private int range; private double speed; private VectorTransform velocityTransform; private double spread; private double movementSpread; private double maxSpread; private int startDistance; private String projectileEffectKey; private String hitEffectKey; private String tickEffectKey; private double gravity; private double drag; private double tickSize; private boolean reorient; private boolean useWandLocation; private boolean useEyeLocation; private boolean useTargetLocation; private boolean trackEntity; private double trackCursorRange; private double trackSpeed; private int targetSelfTimeout; private boolean breaksBlocks; private double targetBreakables; private int targetBreakableSize; private boolean bypassBackfire; private boolean reverseDirection; private int blockHitLimit; private int entityHitLimit; private Location launchLocation; private long flightTime; private double distanceTravelled; private double effectDistanceTravelled; private boolean hasTickEffects; private boolean hasStepEffects; private boolean hasBlockMissEffects; private boolean hasPreHitEffects; private int entityHitCount; private Set<UUID> entitiesHit; private int blockHitCount; private boolean missed; private long lastUpdate; private long nextUpdate; private long deadline; private long targetSelfDeadline; private Vector velocity = null; private DynamicLocation effectLocation = null; private Collection<EffectPlay> activeProjectileEffects; @Override public void initialize(Spell spell, ConfigurationSection parameters) { super.initialize(spell, parameters); targeting = new Targeting(); if (parameters.isConfigurationSection("velocity_transform")) { velocityTransform = new VectorTransform(parameters.getConfigurationSection("velocity_transform")); } else { velocityTransform = null; } } @Override public void prepare(CastContext context, ConfigurationSection parameters) { super.prepare(context, parameters); targeting.processParameters(parameters); interval = parameters.getInt("interval", 30); lifetime = parameters.getInt("lifetime", 8000); reverseDirection = parameters.getBoolean("reverse", false); startDistance = parameters.getInt("start", 0); range = parameters.getInt("range", 0); projectileEffectKey = parameters.getString("projectile_effects", "projectile"); hitEffectKey = parameters.getString("hit_effects", "hit"); tickEffectKey = parameters.getString("tick_effects", "tick"); gravity = parameters.getDouble("gravity", 0); drag = parameters.getDouble("drag", 0); tickSize = parameters.getDouble("tick_size", 0.5); reorient = parameters.getBoolean("reorient", false); useWandLocation = parameters.getBoolean("use_wand_location", true); useEyeLocation = parameters.getBoolean("use_eye_location", true); useTargetLocation = parameters.getBoolean("use_target_location", true); trackEntity = parameters.getBoolean("track_target", false); targetSelfTimeout = parameters.getInt("target_self_timeout", 0); breaksBlocks = parameters.getBoolean("break_blocks", true); targetBreakables = parameters.getDouble("target_breakables", 1); targetBreakableSize = parameters.getInt("breakable_size", 1); bypassBackfire = parameters.getBoolean("bypass_backfire", false); spread = parameters.getDouble("spread", 0); maxSpread = parameters.getDouble("spread_max", 0); movementSpread = parameters.getDouble("spread_movement", 0); trackCursorRange = parameters.getDouble("track_range", 0); trackSpeed = parameters.getDouble("track_speed", 0); int hitLimit = parameters.getInt("hit_count", 1); entityHitLimit = parameters.getInt("entity_hit_count", hitLimit); blockHitLimit = parameters.getInt("block_hit_count", hitLimit); range *= context.getMage().getRangeMultiplier(); speed = parameters.getDouble("speed", 1); speed = parameters.getDouble("velocity", speed * 20); // Some parameter tweaks to make sure things are sane TargetType targetType = targeting.getTargetType(); if (targetType == TargetType.NONE) { targeting.setTargetType(TargetType.OTHER); } // Flags to optimize FX calls hasTickEffects = context.getEffects(tickEffectKey).size() > 0; hasBlockMissEffects = context.getEffects("blockmiss").size() > 0; hasStepEffects = context.getEffects("step").size() > 0; hasPreHitEffects = context.getEffects("prehit").size() > 0; } @Override public boolean next(CastContext context) { return !missed && entityHitCount < entityHitLimit && blockHitCount < blockHitLimit; } @Override public void reset(CastContext context) { super.reset(context); targeting.reset(); long now = System.currentTimeMillis(); nextUpdate = 0; distanceTravelled = 0; lastUpdate = 0; deadline = now + lifetime; targetSelfDeadline = targetSelfTimeout > 0 ? now + targetSelfTimeout : 0; effectLocation = null; velocity = null; activeProjectileEffects = null; entityHitCount = 0; entitiesHit = null; blockHitCount = 0; missed = false; } @Override public SpellResult start(CastContext context) { if (movementSpread > 0) { Entity sourceEntity = context.getEntity(); double entitySpeed = sourceEntity != null ? sourceEntity.getVelocity().lengthSquared() : 0; if (entitySpeed > 0.01) { spread += Math.min(movementSpread * entitySpeed, maxSpread); context.getMage().sendDebugMessage(ChatColor.DARK_RED + " Applying spread of " + ChatColor.RED + spread + ChatColor.DARK_RED + " from speed^2 of " + ChatColor.GOLD + entitySpeed, 3); } } return SpellResult.CAST; } @Override public SpellResult step(CastContext context) { long now = System.currentTimeMillis(); if (now < nextUpdate) { return SpellResult.PENDING; } if (now > deadline) { return miss(); } if (targetSelfDeadline > 0 && now > targetSelfDeadline) { targetSelfDeadline = 0; context.setTargetsCaster(true); } nextUpdate = now + interval; // Check for initialization required // TODO: Move this to start()? Location projectileLocation = null; if (velocity == null) { Location targetLocation = context.getTargetLocation(); if (useWandLocation) { projectileLocation = context.getWandLocation().clone(); } else if (useEyeLocation) { projectileLocation = context.getEyeLocation().clone(); } else { projectileLocation = context.getLocation().clone(); } launchLocation = projectileLocation.clone(); if (targetLocation != null && !reorient && useTargetLocation) { velocity = targetLocation.toVector().subtract(projectileLocation.toVector()).normalize(); launchLocation.setDirection(velocity); } else { velocity = context.getDirection().clone().normalize(); } if (spread > 0) { Random random = context.getRandom(); velocity.setX(velocity.getX() + (random.nextDouble() * spread - spread / 2)); velocity.setY(velocity.getY() + (random.nextDouble() * spread - spread / 2)); velocity.setZ(velocity.getZ() + (random.nextDouble() * spread - spread / 2)); velocity.normalize(); } if (startDistance != 0) { projectileLocation.add(velocity.clone().multiply(startDistance)); } if (reverseDirection) { velocity = velocity.multiply(-1); } projectileLocation.setDirection(velocity); actionContext.setTargetLocation(projectileLocation); actionContext.setTargetEntity(null); actionContext.setDirection(velocity); // Start up projectile FX Collection<EffectPlayer> projectileEffects = context.getEffects(projectileEffectKey); for (EffectPlayer apiEffectPlayer : projectileEffects) { if (effectLocation == null) { effectLocation = new DynamicLocation(projectileLocation); effectLocation.setDirection(velocity); } if (activeProjectileEffects == null) { activeProjectileEffects = new ArrayList<EffectPlay>(); } // Hrm- this is ugly, but I don't want the API to depend on EffectLib. if (apiEffectPlayer instanceof com.elmakers.mine.bukkit.effect.EffectPlayer) { com.elmakers.mine.bukkit.effect.EffectPlayer effectPlayer = (com.elmakers.mine.bukkit.effect.EffectPlayer)apiEffectPlayer; effectPlayer.setEffectPlayList(activeProjectileEffects); effectPlayer.startEffects(effectLocation, null); } } } else { projectileLocation = actionContext.getTargetLocation(); if (effectLocation != null) { effectLocation.updateFrom(projectileLocation); effectLocation.setDirection(velocity); } } // Advance position // We default to 50 ms travel time (one tick) for the first iteration. long delta = lastUpdate > 0 ? now - lastUpdate : 50; lastUpdate = now; flightTime += delta; // Apply gravity, drag or other velocity modifiers Vector targetVelocity = null; if (trackEntity) { Entity targetEntity = context.getTargetEntity(); if (targetEntity != null && targetEntity.isValid() && context.canTarget(targetEntity)) { Location targetLocation = targetEntity instanceof LivingEntity ? ((LivingEntity)targetEntity).getEyeLocation() : targetEntity.getLocation(); targetVelocity = targetLocation.toVector().subtract(projectileLocation.toVector()).normalize(); } } else if (trackCursorRange > 0) { /* We need to first find out where the player is looking and multiply it by how far the player wants the whip to extend * Finally after all that, we adjust the velocity of the projectile to go towards the cursor point */ Vector playerCursor = context.getDirection().clone().normalize().multiply(trackCursorRange); playerCursor = context.getEyeLocation().toVector().add(playerCursor); targetVelocity = playerCursor.subtract(projectileLocation.toVector()).normalize(); } else if (reorient) { targetVelocity = context.getDirection().clone().normalize(); } else if (velocityTransform != null) { targetVelocity = velocityTransform.get(launchLocation, (double)flightTime / 1000); // This is expensive, but necessary for variable speed to work properly // with targeting and range-checking if (targetVelocity != null) { speed = targetVelocity.length(); if (speed > 0) { targetVelocity.normalize(); } else { targetVelocity.setX(1); } } } else { if (gravity > 0) { velocity.setY(velocity.getY() - gravity * delta / 50).normalize(); } if (drag > 0) { speed -= drag * delta / 50; if (speed <= 0) { return miss(); } } } if (targetVelocity != null) { if (trackSpeed > 0) { double steerDistanceSquared = trackSpeed * trackSpeed; double distanceSquared = targetVelocity.distanceSquared(velocity); if (distanceSquared <= steerDistanceSquared) { velocity = targetVelocity; } else { Vector targetDirection = targetVelocity.subtract(velocity).normalize().multiply(steerDistanceSquared); velocity.add(targetDirection); } } else { velocity = targetVelocity; } } projectileLocation.setDirection(velocity); targeting.setIgnoreEntities(entitiesHit); targeting.start(projectileLocation); // Advance targeting to find Entity or Block double distance = speed * delta / 1000; if (range > 0) { distance = Math.min(distance, range - distanceTravelled); } context.addWork((int)Math.ceil(distance)); Target target = targeting.target(actionContext, distance); Location targetLocation; Targeting.TargetingResult targetingResult = targeting.getResult(); if (targetingResult == Targeting.TargetingResult.MISS) { if (hasBlockMissEffects) { actionContext.setTargetLocation(target.getLocation()); actionContext.playEffects("blockmiss"); } targetLocation = projectileLocation.clone().add(velocity.clone().multiply(distance)); context.getMage().sendDebugMessage(ChatColor.DARK_BLUE + "Projectile miss: " + ChatColor.DARK_PURPLE + " at " + targetLocation.getBlock().getType() + " : " + targetLocation.toVector() + " from range of " + distance + " over time " + delta, 7); } else { if (hasPreHitEffects) { actionContext.playEffects("prehit"); } targetLocation = target.getLocation(); // Debugging if (targetLocation == null) { targetLocation = projectileLocation; context.getLogger().warning("Targeting hit, with no target location: " + targetingResult + " with " + targeting.getTargetType() + " from " + context.getSpell().getName()); } context.getMage().sendDebugMessage(ChatColor.BLUE + "Projectile hit: " + ChatColor.LIGHT_PURPLE + targetingResult.name().toLowerCase() + ChatColor.BLUE + " at " + ChatColor.GOLD + targetLocation.getBlock().getType() + ChatColor.BLUE + " from " + ChatColor.GRAY + projectileLocation.getBlock() + ChatColor.BLUE + " to " + ChatColor.GRAY + targetLocation.toVector() + ChatColor.BLUE + " from range of " + ChatColor.GOLD + distance + ChatColor.BLUE + " over time " + ChatColor.DARK_PURPLE + delta, 4); distance = targetLocation.distance(projectileLocation); } distanceTravelled += distance; effectDistanceTravelled += distance; // Max Height check int y = targetLocation.getBlockY(); boolean maxHeight = y >= targetLocation.getWorld().getMaxHeight(); boolean minHeight = y <= 0; if (maxHeight) { targetLocation.setY(targetLocation.getWorld().getMaxHeight()); } else if (minHeight) { targetLocation.setY(0); } if (hasTickEffects && effectDistanceTravelled > tickSize) { // Sane limit here Vector speedVector = velocity.clone().multiply(tickSize); for (int i = 0; i < 256; i++) { actionContext.setTargetLocation(projectileLocation); actionContext.playEffects(tickEffectKey); projectileLocation.add(speedVector); effectDistanceTravelled -= tickSize; if (effectDistanceTravelled < tickSize) break; } } actionContext.setTargetLocation(targetLocation); actionContext.setTargetEntity(target.getEntity()); if (hasStepEffects) { actionContext.playEffects("step"); } if (maxHeight || minHeight) { return miss(); } if (range > 0 && distanceTravelled >= range) { return miss(); } Block block = targetLocation.getBlock(); if (!block.getChunk().isLoaded()) { return miss(); } if (targetingResult == Targeting.TargetingResult.BLOCK) { return hitBlock(block); } else if (targetingResult == Targeting.TargetingResult.ENTITY) { entityHitCount++; Entity hitEntity = target.getEntity(); if (hitEntity != null && entityHitLimit > 1) { if (entitiesHit == null) { entitiesHit = new HashSet<UUID>(); } entitiesHit.add(hitEntity.getUniqueId()); } return hit(); } return SpellResult.PENDING; } protected SpellResult hitBlock(Block block) { boolean continueProjectile = false; if (!bypassBackfire && actionContext.isReflective(block)) { double reflective = actionContext.getReflective(block); if (actionContext.getRandom().nextDouble() < reflective) { trackEntity = false; reorient = false; distanceTravelled = 0; actionContext.setTargetsCaster(true); // Calculate angle of reflection Location targetLocation = actionContext.getTargetLocation(); Vector normal = CompatibilityUtils.getNormal(block, targetLocation); velocity.multiply(-1); velocity = velocity.subtract(normal.multiply(2 * velocity.dot(normal))).normalize(); velocity.multiply(-1); // Offset position slightly to avoid hitting again actionContext.setTargetLocation(targetLocation.add(velocity.clone().multiply(0.05))); // actionContext.setTargetLocation(targetLocation.add(normal.normalize().multiply(2))); actionContext.getMage().sendDebugMessage(ChatColor.AQUA + "Projectile reflected: " + ChatColor.LIGHT_PURPLE + " at " + ChatColor.GRAY + block + ChatColor.AQUA + " with normal vector of " + ChatColor.LIGHT_PURPLE + normal, 4); actionContext.playEffects("reflect"); continueProjectile = true; } } if (targetBreakables > 0 && breaksBlocks && actionContext.isBreakable(block)) { targetBreakables -= targeting.breakBlock(actionContext, block, Math.min(targetBreakableSize, targetBreakables)); if (targetBreakables > 0) { continueProjectile = true; } } if (!continueProjectile) { blockHitCount++; } return continueProjectile ? SpellResult.PENDING : hit(); } protected SpellResult miss() { missed = true; return hit(); } protected SpellResult hit() { if (activeProjectileEffects != null) { for (EffectPlay play : activeProjectileEffects) { play.cancel(); } } if (actionContext == null) { return SpellResult.NO_ACTION; } actionContext.playEffects(hitEffectKey); return startActions(); } @Override public void getParameterNames(Spell spell, Collection<String> parameters) { super.getParameterNames(spell, parameters); parameters.add("interval"); parameters.add("lifetime"); parameters.add("speed"); parameters.add("start"); parameters.add("gravity"); parameters.add("drag"); parameters.add("target_entities"); parameters.add("track_target"); parameters.add("spread"); } @Override public void getParameterOptions(Spell spell, String parameterKey, Collection<String> examples) { super.getParameterOptions(spell, parameterKey, examples); if (parameterKey.equals("speed") || parameterKey.equals("lifetime") || parameterKey.equals("interval") || parameterKey.equals("start") || parameterKey.equals("size") || parameterKey.equals("gravity") || parameterKey.equals("drag") || parameterKey.equals("tick_size") || parameterKey.equals("spread")) { examples.addAll(Arrays.asList(BaseSpell.EXAMPLE_SIZES)); } else if (parameterKey.equals("target_entities") || parameterKey.equals("track_target")) { examples.addAll(Arrays.asList(BaseSpell.EXAMPLE_BOOLEANS)); } } }
package com.fasterxml.jackson.dataformat.xml.ser; import java.io.IOException; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.PropertyName; import com.fasterxml.jackson.databind.SerializationConfig; import com.fasterxml.jackson.databind.ser.SerializerFactory; import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider; import com.fasterxml.jackson.databind.util.TokenBuffer; import com.fasterxml.jackson.dataformat.xml.util.StaxUtil; import com.fasterxml.jackson.dataformat.xml.util.TypeUtil; import com.fasterxml.jackson.dataformat.xml.util.XmlRootNameLookup; /** * We need to override some parts of * {@link com.fasterxml.jackson.databind.SerializerProvider} * implementation to handle oddities of XML output, like "extra" root element. */ public class XmlSerializerProvider extends DefaultSerializerProvider { // As of 2.7 private static final long serialVersionUID = 1L; /** * If all we get to serialize is a null, there's no way to figure out * expected root name; so let's just default to something like "&lt;null>"... */ protected final static QName ROOT_NAME_FOR_NULL = new QName("null"); protected final XmlRootNameLookup _rootNameLookup; public XmlSerializerProvider(XmlRootNameLookup rootNames) { super(); _rootNameLookup = rootNames; } public XmlSerializerProvider(XmlSerializerProvider src, SerializationConfig config, SerializerFactory f) { super(src, config, f); _rootNameLookup = src._rootNameLookup; } @Override public DefaultSerializerProvider createInstance(SerializationConfig config, SerializerFactory jsf) { return new XmlSerializerProvider(this, config, jsf); } @SuppressWarnings("resource") @Override public void serializeValue(JsonGenerator gen, Object value) throws IOException { if (value == null) { _serializeXmlNull(gen); return; } final Class<?> cls = value.getClass(); final boolean asArray; final ToXmlGenerator xgen = _asXmlGenerator(gen); if (xgen == null) { // called by convertValue() asArray = false; } else { QName rootName = _rootNameFromConfig(); if (rootName == null) { rootName = _rootNameLookup.findRootName(cls, _config); } _initWithRootName(xgen, rootName); asArray = TypeUtil.isIndexedType(cls); if (asArray) { _startRootArray(xgen, rootName); } } // From super-class implementation final JsonSerializer<Object> ser = findTypedValueSerializer(cls, true, null); try { ser.serialize(value, gen, this); } catch (Exception e) { // but wrap RuntimeExceptions, to get path information throw _wrapAsIOE(gen, e); } // end of super-class implementation if (asArray) { gen.writeEndObject(); } } // @since 2.1 @SuppressWarnings("resource") @Override public void serializeValue(JsonGenerator gen, Object value, JavaType rootType, JsonSerializer<Object> ser) throws IOException { if (value == null) { _serializeXmlNull(gen); return; } final boolean asArray; final ToXmlGenerator xgen = _asXmlGenerator(gen); if (xgen == null) { // called by convertValue() asArray = false; } else { QName rootName = _rootNameFromConfig(); if (rootName == null) { rootName = _rootNameLookup.findRootName(rootType, _config); } _initWithRootName(xgen, rootName); asArray = TypeUtil.isIndexedType(rootType); if (asArray) { _startRootArray(xgen, rootName); } } if (ser == null) { ser = findTypedValueSerializer(rootType, true, null); } // From super-class implementation try { ser.serialize(value, gen, this); } catch (Exception e) { // but others do need to be, to get path etc throw _wrapAsIOE(gen, e); } // end of super-class implementation if (asArray) { gen.writeEndObject(); } } protected void _serializeXmlNull(JsonGenerator jgen) throws IOException { if (jgen instanceof ToXmlGenerator) _initWithRootName((ToXmlGenerator) jgen, ROOT_NAME_FOR_NULL); super.serializeValue(jgen, null); } protected void _startRootArray(ToXmlGenerator xgen, QName rootName) throws IOException { xgen.writeStartObject(); // Could repeat root name, but what's the point? How to customize? xgen.writeFieldName("item"); } protected void _initWithRootName(ToXmlGenerator xgen, QName rootName) throws IOException { /* 28-Nov-2012, tatu: We should only initialize the root * name if no name has been set, as per [dataformat-xml#42], * to allow for custom serializers to work. */ if (!xgen.setNextNameIfMissing(rootName)) { // however, if we are root, we... insist if (xgen.inRoot()) { xgen.setNextName(rootName); } } xgen.initGenerator(); String ns = rootName.getNamespaceURI(); /* [Issue#26] If we just try writing root element with namespace, * we will get an explicit prefix. But we'd rather use the default * namespace, so let's try to force that. */ if (ns != null && ns.length() > 0) { try { xgen.getStaxWriter().setDefaultNamespace(ns); } catch (XMLStreamException e) { StaxUtil.throwXmlAsIOException(e); } } } protected QName _rootNameFromConfig() { PropertyName name = _config.getFullRootName(); if (name == null) { return null; } String ns = name.getNamespace(); if (ns == null || ns.isEmpty()) { return new QName(name.getSimpleName()); } return new QName(ns, name.getSimpleName()); } protected ToXmlGenerator _asXmlGenerator(JsonGenerator gen) throws JsonMappingException { // [Issue#71]: When converting, we actually get TokenBuffer, which is fine if (!(gen instanceof ToXmlGenerator)) { // but verify if (!(gen instanceof TokenBuffer)) { throw JsonMappingException.from(gen, "XmlMapper does not with generators of type other than ToXmlGenerator; got: "+gen.getClass().getName()); } return null; } return (ToXmlGenerator) gen; } protected IOException _wrapAsIOE(JsonGenerator g, Exception e) { if (e instanceof IOException) { return (IOException) e; } String msg = e.getMessage(); if (msg == null) { msg = "[no message for "+e.getClass().getName()+"]"; } return new JsonMappingException(g, msg, e); } }
package com.fincatto.documentofiscal.nfe400.webservices; import com.fincatto.documentofiscal.DFLog; import com.fincatto.documentofiscal.DFModelo; import com.fincatto.documentofiscal.nfe.NFeConfig; import com.fincatto.documentofiscal.nfe400.NotaFiscalChaveParser; import com.fincatto.documentofiscal.nfe400.classes.NFAutorizador400; import com.fincatto.documentofiscal.nfe400.classes.evento.NFEnviaEventoRetorno; import com.fincatto.documentofiscal.nfe400.classes.evento.cancelamento.NFEnviaEventoCancelamento; import com.fincatto.documentofiscal.nfe400.classes.evento.cancelamento.NFEventoCancelamento; import com.fincatto.documentofiscal.nfe400.classes.evento.cancelamento.NFInfoCancelamento; import com.fincatto.documentofiscal.nfe400.classes.evento.cancelamento.NFInfoEventoCancelamento; import com.fincatto.documentofiscal.nfe400.webservices.gerado.NFeRecepcaoEvento4Stub; import com.fincatto.documentofiscal.nfe400.webservices.gerado.NFeRecepcaoEvento4Stub.NfeResultMsg; import com.fincatto.documentofiscal.utils.DFAssinaturaDigital; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.util.AXIOMUtil; import java.math.BigDecimal; import java.time.ZonedDateTime; import java.util.Collections; class WSCancelamento implements DFLog { private static final BigDecimal VERSAO_LEIAUTE = new BigDecimal("1.00"); private static final String DESCRICAO_EVENTO = "Cancelamento"; private static final String EVENTO_CANCELAMENTO = "110111"; private static final String DESCRICAO_EVENTO_CANCELAMENTO_POR_SUBSTITUICAO = "Cancelamento por substituicao"; private static final String EVENTO_CANCELAMENTO_POR_SUBSTITUICAO = "110112"; private final NFeConfig config; WSCancelamento(final NFeConfig config) { this.config = config; } NFEnviaEventoRetorno cancelaNotaAssinada(final String chaveAcesso, final String eventoAssinadoXml) throws Exception { final OMElement omElementResult = this.efetuaCancelamento(eventoAssinadoXml, chaveAcesso); return this.config.getPersister().read(NFEnviaEventoRetorno.class, omElementResult.toString()); } NFEnviaEventoRetorno cancelaNota(final String chaveAcesso, final String numeroProtocolo, final String motivo) throws Exception { final String cancelamentoNotaXML = this.gerarDadosCancelamento(chaveAcesso, numeroProtocolo, motivo).toString(); final String xmlAssinado = new DFAssinaturaDigital(this.config).assinarDocumento(cancelamentoNotaXML); final OMElement omElementResult = this.efetuaCancelamento(xmlAssinado, chaveAcesso); return this.config.getPersister().read(NFEnviaEventoRetorno.class, omElementResult.toString()); } private OMElement efetuaCancelamento(final String xmlAssinado, final String chaveAcesso) throws Exception { final NFeRecepcaoEvento4Stub.NfeDadosMsg dados = new NFeRecepcaoEvento4Stub.NfeDadosMsg(); final OMElement omElementXML = AXIOMUtil.stringToOM(xmlAssinado); this.getLogger().debug(omElementXML.toString()); dados.setExtraElement(omElementXML); final NotaFiscalChaveParser parser = new NotaFiscalChaveParser(chaveAcesso); final NFAutorizador400 autorizador = NFAutorizador400.valueOfChaveAcesso(chaveAcesso); final String urlWebService = DFModelo.NFCE.equals(parser.getModelo()) ? autorizador.getNfceRecepcaoEvento(this.config.getAmbiente()) : autorizador.getRecepcaoEvento(this.config.getAmbiente()); if (urlWebService == null) { throw new IllegalArgumentException("Nao foi possivel encontrar URL para RecepcaoEvento " + parser.getModelo().name() + ", autorizador " + autorizador.name()); } final NfeResultMsg nfeRecepcaoEvento = new NFeRecepcaoEvento4Stub(urlWebService, config).nfeRecepcaoEvento(dados); final OMElement omElementResult = nfeRecepcaoEvento.getExtraElement(); this.getLogger().debug(omElementResult.toString()); return omElementResult; } private NFEnviaEventoCancelamento gerarDadosCancelamento(final String chaveAcesso, final String numeroProtocolo, final String motivo) { final NotaFiscalChaveParser chaveParser = new NotaFiscalChaveParser(chaveAcesso); final NFInfoCancelamento cancelamento = new NFInfoCancelamento(); cancelamento.setDescricaoEvento(WSCancelamento.DESCRICAO_EVENTO); cancelamento.setVersao(WSCancelamento.VERSAO_LEIAUTE); cancelamento.setJustificativa(motivo); cancelamento.setProtocoloAutorizacao(numeroProtocolo); final NFInfoEventoCancelamento infoEvento = new NFInfoEventoCancelamento(); infoEvento.setAmbiente(this.config.getAmbiente()); infoEvento.setChave(chaveAcesso); if (Integer.parseInt(chaveParser.getSerie()) >= 920 && Integer.parseInt(chaveParser.getSerie()) <= 969 && chaveParser.isEmitentePessoaFisica()) { infoEvento.setCpf(chaveParser.getCpfEmitente()); } else { infoEvento.setCnpj(chaveParser.getCnpjEmitente()); } infoEvento.setDataHoraEvento(ZonedDateTime.now(this.config.getTimeZone().toZoneId())); infoEvento.setId(String.format("ID%s%s0%s", WSCancelamento.EVENTO_CANCELAMENTO, chaveAcesso, "1")); infoEvento.setNumeroSequencialEvento(1); infoEvento.setOrgao(chaveParser.getNFUnidadeFederativa()); infoEvento.setCodigoEvento(WSCancelamento.EVENTO_CANCELAMENTO); infoEvento.setVersaoEvento(WSCancelamento.VERSAO_LEIAUTE); infoEvento.setCancelamento(cancelamento); final NFEventoCancelamento evento = new NFEventoCancelamento(); evento.setInfoEvento(infoEvento); evento.setVersao(WSCancelamento.VERSAO_LEIAUTE); final NFEnviaEventoCancelamento enviaEvento = new NFEnviaEventoCancelamento(); enviaEvento.setEvento(Collections.singletonList(evento)); enviaEvento.setIdLote(Long.toString(ZonedDateTime.now(this.config.getTimeZone().toZoneId()).toInstant().toEpochMilli())); enviaEvento.setVersao(WSCancelamento.VERSAO_LEIAUTE); return enviaEvento; } NFEnviaEventoRetorno cancelaNotaPorSubstituicao(final String chaveAcesso, final String numeroProtocolo, final String motivo, final String versaoAplicativoAutorizador, final String chaveSubstituta) throws Exception { final String cancelamentoNotaXML = this.gerarDadosCancelamentoPorSubstituicao(chaveAcesso, numeroProtocolo, motivo, versaoAplicativoAutorizador, chaveSubstituta).toString(); final String xmlAssinado = new DFAssinaturaDigital(this.config).assinarDocumento(cancelamentoNotaXML); final OMElement omElementResult = this.efetuaCancelamento(xmlAssinado, chaveAcesso); return this.config.getPersister().read(NFEnviaEventoRetorno.class, omElementResult.toString()); } private NFEnviaEventoCancelamento gerarDadosCancelamentoPorSubstituicao(final String chaveAcesso, final String numeroProtocolo, final String motivo, final String versaoAplicativoAutorizador, final String chaveSubstituta) { final NotaFiscalChaveParser chaveParser = new NotaFiscalChaveParser(chaveAcesso); if(DFModelo.NFE.equals(chaveParser.getModelo())) throw new IllegalArgumentException("Evento nao permitido para modelo 55 - NFe!"); final NFInfoCancelamento cancelamento = new NFInfoCancelamento(); cancelamento.setDescricaoEvento(WSCancelamento.DESCRICAO_EVENTO_CANCELAMENTO_POR_SUBSTITUICAO); cancelamento.setUfAutorizador(chaveParser.getNFUnidadeFederativa()); cancelamento.setTipoAutorizador("1");//como orientado no manual cancelamento.setVersaoAplicativo(versaoAplicativoAutorizador); cancelamento.setVersao(WSCancelamento.VERSAO_LEIAUTE); cancelamento.setJustificativa(motivo); cancelamento.setProtocoloAutorizacao(numeroProtocolo); cancelamento.setChaveAcessoSubstituta(chaveSubstituta); final NFInfoEventoCancelamento infoEvento = new NFInfoEventoCancelamento(); infoEvento.setAmbiente(this.config.getAmbiente()); infoEvento.setChave(chaveAcesso); if (Integer.parseInt(chaveParser.getSerie()) >= 920 && Integer.parseInt(chaveParser.getSerie()) <= 969) { infoEvento.setCpf(chaveParser.getCnpjEmitente().substring(3)); } else { infoEvento.setCnpj(chaveParser.getCnpjEmitente()); } infoEvento.setDataHoraEvento(ZonedDateTime.now(this.config.getTimeZone().toZoneId())); infoEvento.setId(String.format("ID%s%s0%s", WSCancelamento.EVENTO_CANCELAMENTO_POR_SUBSTITUICAO, chaveAcesso, "1")); infoEvento.setNumeroSequencialEvento(1); infoEvento.setOrgao(chaveParser.getNFUnidadeFederativa()); infoEvento.setCodigoEvento(WSCancelamento.EVENTO_CANCELAMENTO_POR_SUBSTITUICAO); infoEvento.setVersaoEvento(WSCancelamento.VERSAO_LEIAUTE); infoEvento.setCancelamento(cancelamento); final NFEventoCancelamento evento = new NFEventoCancelamento(); evento.setInfoEvento(infoEvento); evento.setVersao(WSCancelamento.VERSAO_LEIAUTE); final NFEnviaEventoCancelamento enviaEvento = new NFEnviaEventoCancelamento(); enviaEvento.setEvento(Collections.singletonList(evento)); enviaEvento.setIdLote(Long.toString(ZonedDateTime.now(this.config.getTimeZone().toZoneId()).toInstant().toEpochMilli())); enviaEvento.setVersao(WSCancelamento.VERSAO_LEIAUTE); return enviaEvento; } }
package com.github.anba.es6draft.runtime.types.builtins; import static com.github.anba.es6draft.runtime.AbstractOperations.CreateOwnDataProperty; import static com.github.anba.es6draft.runtime.AbstractOperations.IsCallable; import static com.github.anba.es6draft.runtime.AbstractOperations.SameValue; import static com.github.anba.es6draft.runtime.internal.Errors.throwTypeError; import static com.github.anba.es6draft.runtime.objects.internal.ListIterator.FromListIterator; import static com.github.anba.es6draft.runtime.objects.internal.ListIterator.MakeListIterator; import static com.github.anba.es6draft.runtime.types.Undefined.UNDEFINED; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Set; import com.github.anba.es6draft.runtime.ExecutionContext; import com.github.anba.es6draft.runtime.Realm; import com.github.anba.es6draft.runtime.internal.Messages; import com.github.anba.es6draft.runtime.internal.ObjectAllocator; import com.github.anba.es6draft.runtime.internal.SimpleIterator; import com.github.anba.es6draft.runtime.types.Callable; import com.github.anba.es6draft.runtime.types.Intrinsics; import com.github.anba.es6draft.runtime.types.Property; import com.github.anba.es6draft.runtime.types.PropertyDescriptor; import com.github.anba.es6draft.runtime.types.ScriptObject; import com.github.anba.es6draft.runtime.types.Symbol; import com.github.anba.es6draft.runtime.types.Type; /** * <h1>9 ECMAScript Ordinary and Exotic Objects Behaviours</h1> * <ul> * <li>9.1 Ordinary Object Internal Methods and Internal Data Properties * </ul> */ public class OrdinaryObject implements ScriptObject { // Map<String|Symbol, Property> properties private LinkedHashMap<Object, Property> properties = new LinkedHashMap<>(); /** [[Realm]] */ @SuppressWarnings("unused") private final Realm realm; /** [[Prototype]] */ private ScriptObject prototype = null; /** [[Extensible]] */ private boolean extensible = true; public OrdinaryObject(Realm realm) { this.realm = realm; } /** [[Prototype]] */ public final ScriptObject getPrototype() { return prototype; } /** [[Prototype]] */ public final void setPrototype(ScriptObject prototype) { this.prototype = prototype; } /** [[Extensible]] */ protected final boolean isExtensible() { return extensible; } /** [[HasOwnProperty]] (P) */ protected boolean hasOwnProperty(ExecutionContext cx, String propertyKey) { // optimised: HasOwnProperty(cx, this, propertyKey) return __has__(propertyKey); } /** [[HasOwnProperty]] (P) */ protected boolean hasOwnProperty(ExecutionContext cx, Symbol propertyKey) { // optimised: HasOwnProperty(cx, this, propertyKey) return __has__(propertyKey); } private void __put__(Object propertyKey, Property property) { assert propertyKey instanceof String || propertyKey instanceof Symbol; properties.put(propertyKey, property); } private boolean __has__(Object propertyKey) { assert propertyKey instanceof String || propertyKey instanceof Symbol; return properties.containsKey(propertyKey); } private Property __get__(Object propertyKey) { assert propertyKey instanceof String || propertyKey instanceof Symbol; return properties.get(propertyKey); } private void __delete__(Object propertyKey) { assert propertyKey instanceof String || propertyKey instanceof Symbol; properties.remove(propertyKey); } private Set<Object> __keys__() { return properties.keySet(); } /** 9.1.1 [[GetPrototypeOf]] ( ) */ @Override public ScriptObject getPrototypeOf(ExecutionContext cx) { return prototype; } /** 9.1.2 [[SetPrototypeOf]] (V) */ @Override public boolean setPrototypeOf(ExecutionContext cx, ScriptObject prototype) { /* steps 1-3 */ boolean extensible = this.extensible; ScriptObject current = this.prototype; /* step 4 */ if (prototype == current) { // SameValue(prototype, current) return true; } /* step 5 */ if (!extensible) { return false; } /* step 6 */ if (prototype != null) { ScriptObject p = prototype; while (p != null) { if (p == this) { // SameValue(p, O) return false; } p = p.getPrototypeOf(cx); } } /* step 7 */ this.prototype = prototype; /* step 8 */ return true; } /** 9.1.3 [[IsExtensible]] ( ) */ @Override public boolean isExtensible(ExecutionContext cx) { return extensible; } /** 9.1.4 [[PreventExtensions]] ( ) */ @Override public boolean preventExtensions(ExecutionContext cx) { this.extensible = false; return true; } /** 9.1.5 [[GetOwnProperty]] (P) */ @Override public Property getOwnProperty(ExecutionContext cx, String propertyKey) { return ordinaryGetOwnProperty(propertyKey); } /** 9.1.5 [[GetOwnProperty]] (P) */ @Override public Property getOwnProperty(ExecutionContext cx, Symbol propertyKey) { return ordinaryGetOwnProperty(propertyKey); } /** * 9.1.5.1 OrdinaryGetOwnProperty (O, P) */ protected final Property ordinaryGetOwnProperty(String propertyKey) { Property desc = __get__(propertyKey); /* step 2 */ if (desc == null) { return null; } /* steps 3-9 */ return desc; } /** * 9.1.5.1 OrdinaryGetOwnProperty (O, P) */ protected final Property ordinaryGetOwnProperty(Symbol propertyKey) { Property desc = __get__(propertyKey); /* step 2 */ if (desc == null) { return null; } /* steps 3-9 */ return desc; } /** 9.1.6 [[DefineOwnProperty]] (P, Desc) */ @Override public boolean defineOwnProperty(ExecutionContext cx, String propertyKey, PropertyDescriptor desc) { /* step 1 */ return ordinaryDefineOwnProperty(propertyKey, desc); } /** 9.1.6 [[DefineOwnProperty]] (P, Desc) */ @Override public boolean defineOwnProperty(ExecutionContext cx, Symbol propertyKey, PropertyDescriptor desc) { /* step 1 */ return ordinaryDefineOwnProperty(propertyKey, desc); } /** * 9.1.6.1 OrdinaryDefineOwnProperty (O, P, Desc) */ protected final boolean ordinaryDefineOwnProperty(String propertyKey, PropertyDescriptor desc) { /* step 1 */ Property current = ordinaryGetOwnProperty(propertyKey); /* step 2 */ boolean extensible = isExtensible(); /* step 3 */ return __validateAndApplyPropertyDescriptor(this, propertyKey, extensible, desc, current); } /** * 9.1.6.1 OrdinaryDefineOwnProperty (O, P, Desc) */ protected final boolean ordinaryDefineOwnProperty(Symbol propertyKey, PropertyDescriptor desc) { /* step 1 */ Property current = ordinaryGetOwnProperty(propertyKey); /* step 2 */ boolean extensible = isExtensible(); /* step 3 */ return __validateAndApplyPropertyDescriptor(this, propertyKey, extensible, desc, current); } /** * 9.1.6.2 IsCompatiblePropertyDescriptor (Extensible, Desc, Current) */ protected static final boolean IsCompatiblePropertyDescriptor(boolean extensible, PropertyDescriptor desc, Property current) { /* step 1 */ return __validateAndApplyPropertyDescriptor(null, null, extensible, desc, current); } /** * 9.1.6.3 ValidateAndApplyPropertyDescriptor (O, P, extensible, Desc, current) */ protected static final boolean ValidateAndApplyPropertyDescriptor(OrdinaryObject object, String propertyKey, boolean extensible, PropertyDescriptor desc, Property current) { return __validateAndApplyPropertyDescriptor(object, propertyKey, extensible, desc, current); } /** * 9.1.6.3 ValidateAndApplyPropertyDescriptor (O, P, extensible, Desc, current) */ protected static final boolean ValidateAndApplyPropertyDescriptor(OrdinaryObject object, Symbol propertyKey, boolean extensible, PropertyDescriptor desc, Property current) { return __validateAndApplyPropertyDescriptor(object, propertyKey, extensible, desc, current); } /** * 9.1.6.3 ValidateAndApplyPropertyDescriptor (O, P, extensible, Desc, current) */ private static final boolean __validateAndApplyPropertyDescriptor(OrdinaryObject object, Object propertyKey, boolean extensible, PropertyDescriptor desc, Property current) { @SuppressWarnings("unused") String reason; reject: { /* step 1 */ assert (object == null || propertyKey != null); /* step 2 */ if (current == null && !extensible) { reason = "not extensible"; break reject; } /* step 3 */ if (current == null && extensible) { if (desc.isGenericDescriptor() || desc.isDataDescriptor()) { if (object != null) { object.__put__(propertyKey, desc.toProperty()); } } else { assert desc.isAccessorDescriptor(); if (object != null) { object.__put__(propertyKey, desc.toProperty()); } } return true; } /* step 4 */ if (desc.isEmpty()) { return true; } /* step 5 */ if (current.isSubset(desc)) { return true; } /* step 6 */ if (!current.isConfigurable()) { if (desc.isConfigurable()) { reason = "changing configurable"; break reject; } if (desc.hasEnumerable() && desc.isEnumerable() != current.isEnumerable()) { reason = "changing enumerable"; break reject; } } if (desc.isGenericDescriptor()) { /* step 7 */ // no further validation required, proceed below... } else if (desc.isDataDescriptor() != current.isDataDescriptor()) { /* step 8 */ if (!current.isConfigurable()) { reason = "changing data/accessor"; break reject; } if (current.isDataDescriptor()) { if (object != null) { object.__get__(propertyKey).toAccessorProperty(); } } else { if (object != null) { object.__get__(propertyKey).toDataProperty(); } } } else if (desc.isDataDescriptor() && current.isDataDescriptor()) { /* step 9 */ if (!current.isConfigurable()) { if (!current.isWritable() && desc.isWritable()) { reason = "changing writable"; break reject; } if (!current.isWritable()) { if (desc.hasValue() && !SameValue(desc.getValue(), current.getValue())) { reason = "changing value"; break reject; } } } } else { /* step 10 */ assert desc.isAccessorDescriptor() && current.isAccessorDescriptor(); if (!current.isConfigurable()) { if (desc.hasSetter() && !SameValue(desc.getSetter(), current.getSetter())) { reason = "changing setter"; break reject; } if (desc.hasGetter() && !SameValue(desc.getGetter(), current.getGetter())) { reason = "changing getter"; break reject; } } } /* step 11 */ if (object != null) { object.__get__(propertyKey).apply(desc); } /* step 12 */ return true; } return false; } /** * 9.1.7 [[HasProperty]](P) */ @Override public boolean hasProperty(ExecutionContext cx, String propertyKey) { /* step 1 (implicit) */ /* steps 2-3 */ boolean hasOwn = hasOwnProperty(cx, propertyKey); /* step 4 */ if (!hasOwn) { ScriptObject parent = getPrototypeOf(cx); if (parent != null) { return parent.hasProperty(cx, propertyKey); } } /* step 5 */ return hasOwn; } /** * 9.1.7 [[HasProperty]](P) */ @Override public boolean hasProperty(ExecutionContext cx, Symbol propertyKey) { /* step 1 (implicit) */ /* steps 2-3 */ boolean hasOwn = hasOwnProperty(cx, propertyKey); /* step 4 */ if (!hasOwn) { ScriptObject parent = getPrototypeOf(cx); if (parent != null) { return parent.hasProperty(cx, propertyKey); } } /* step 5 */ return hasOwn; } /** 9.1.8 [[Get]] (P, Receiver) */ @Override public Object get(ExecutionContext cx, String propertyKey, Object receiver) { /* step 1 (implicit) */ /* steps 2-3 */ Property desc = getOwnProperty(cx, propertyKey); /* step 4 */ if (desc == null) { ScriptObject parent = getPrototypeOf(cx); if (parent == null) { return UNDEFINED; } return parent.get(cx, propertyKey, receiver); } /* step 5 */ if (desc.isDataDescriptor()) { return desc.getValue(); } assert desc.isAccessorDescriptor(); /* step 6 */ Callable getter = desc.getGetter(); /* step 7 */ if (getter == null) { return UNDEFINED; } /* step 8 */ return getter.call(cx, receiver); } /** 9.1.8 [[Get]] (P, Receiver) */ @Override public Object get(ExecutionContext cx, Symbol propertyKey, Object receiver) { /* step 1 (implicit) */ /* steps 2-3 */ Property desc = getOwnProperty(cx, propertyKey); /* step 4 */ if (desc == null) { ScriptObject parent = getPrototypeOf(cx); if (parent == null) { return UNDEFINED; } return parent.get(cx, propertyKey, receiver); } /* step 5 */ if (desc.isDataDescriptor()) { return desc.getValue(); } assert desc.isAccessorDescriptor(); /* step 6 */ Callable getter = desc.getGetter(); /* step 7 */ if (getter == null) { return UNDEFINED; } /* step 8 */ return getter.call(cx, receiver); } /** 9.1.9 [[Set] (P, V, Receiver) */ @Override public boolean set(ExecutionContext cx, String propertyKey, Object value, Object receiver) { /* step 1 (implicit) */ /* steps 2-3 */ Property ownDesc = getOwnProperty(cx, propertyKey); /* step 4 */ if (ownDesc == null) { ScriptObject parent = getPrototypeOf(cx); if (parent != null) { return parent.set(cx, propertyKey, value, receiver); } else { ownDesc = new PropertyDescriptor(UNDEFINED, true, true, true).toProperty(); } } /* step 5 */ if (ownDesc.isDataDescriptor()) { if (!ownDesc.isWritable()) { return false; } if (!Type.isObject(receiver)) { return false; } ScriptObject _receiver = Type.objectValue(receiver); Property existingDescriptor = _receiver.getOwnProperty(cx, propertyKey); if (existingDescriptor != null) { PropertyDescriptor valueDesc = new PropertyDescriptor(value); return _receiver.defineOwnProperty(cx, propertyKey, valueDesc); } else { return CreateOwnDataProperty(cx, _receiver, propertyKey, value); } } /* step 6 */ assert ownDesc.isAccessorDescriptor(); Callable setter = ownDesc.getSetter(); if (setter == null) { return false; } setter.call(cx, receiver, value); return true; } /** 9.1.9 [[Set] (P, V, Receiver) */ @Override public boolean set(ExecutionContext cx, Symbol propertyKey, Object value, Object receiver) { /* step 1 (implicit) */ /* steps 2-3 */ Property ownDesc = getOwnProperty(cx, propertyKey); /* step 4 */ if (ownDesc == null) { ScriptObject parent = getPrototypeOf(cx); if (parent != null) { return parent.set(cx, propertyKey, value, receiver); } else { ownDesc = new PropertyDescriptor(UNDEFINED, true, true, true).toProperty(); } } /* step 5 */ if (ownDesc.isDataDescriptor()) { if (!ownDesc.isWritable()) { return false; } if (!Type.isObject(receiver)) { return false; } ScriptObject _receiver = Type.objectValue(receiver); Property existingDescriptor = _receiver.getOwnProperty(cx, propertyKey); if (existingDescriptor != null) { PropertyDescriptor valueDesc = new PropertyDescriptor(value); return _receiver.defineOwnProperty(cx, propertyKey, valueDesc); } else { return CreateOwnDataProperty(cx, _receiver, propertyKey, value); } } /* step 6 */ assert ownDesc.isAccessorDescriptor(); Callable setter = ownDesc.getSetter(); if (setter == null) { return false; } setter.call(cx, receiver, value); return true; } /** 9.1.10 [[Invoke]] (P, ArgumentsList, Receiver) */ @Override public final Object invoke(ExecutionContext cx, String propertyKey, Object[] arguments, Object receiver) { /* steps 1-2 (implicit) */ /* steps 3-4 */ Object method = get(cx, propertyKey, receiver); /* step 5 */ if (!Type.isObject(method)) { if (Type.isUndefined(method)) { throwTypeError(cx, Messages.Key.MethodNotFound, propertyKey); } throwTypeError(cx, Messages.Key.NotObjectType); } /* step 6 */ if (!IsCallable(method)) { throwTypeError(cx, Messages.Key.NotCallable); } /* step 7 */ return ((Callable) method).call(cx, receiver, arguments); } /** 9.1.10 [[Invoke]] (P, ArgumentsList, Receiver) */ @Override public final Object invoke(ExecutionContext cx, Symbol propertyKey, Object[] arguments, Object receiver) { /* steps 1-2 (implicit) */ /* steps 3-4 */ Object method = get(cx, propertyKey, receiver); /* step 5 */ if (!Type.isObject(method)) { if (Type.isUndefined(method)) { throwTypeError(cx, Messages.Key.MethodNotFound, propertyKey.toString()); } throwTypeError(cx, Messages.Key.NotObjectType); } /* step 6 */ if (!IsCallable(method)) { throwTypeError(cx, Messages.Key.NotCallable); } /* step 7 */ return ((Callable) method).call(cx, receiver, arguments); } /** 9.1.11 [[Delete]] (P) */ @Override public boolean delete(ExecutionContext cx, String propertyKey) { /* step 2 */ Property desc = getOwnProperty(cx, propertyKey); /* step 3 */ if (desc == null) { return true; } /* step 4 */ if (desc.isConfigurable()) { __delete__(propertyKey); return true; } /* step 5 */ return false; } /** 9.1.11 [[Delete]] (P) */ @Override public boolean delete(ExecutionContext cx, Symbol propertyKey) { /* step 2 */ Property desc = getOwnProperty(cx, propertyKey); /* step 3 */ if (desc == null) { return true; } /* step 4 */ if (desc.isConfigurable()) { __delete__(propertyKey); return true; } /* step 5 */ return false; } /** 9.1.12 [[Enumerate]] () */ @Override public final ScriptObject enumerate(ExecutionContext cx) { return MakeListIterator(cx, new EnumKeysIterator(cx, this)); } /** 9.1.12 [[Enumerate]] () */ protected Collection<String> enumerateKeys() { List<String> propList = new ArrayList<>(); for (Object key : __keys__()) { if (key instanceof String) { propList.add((String) key); } } return propList; } protected boolean isEnumerableOwnProperty(String key) { Property prop = ordinaryGetOwnProperty(key); return (prop != null && prop.isEnumerable()); } private static final class EnumKeysIterator extends SimpleIterator<Object> { private final ExecutionContext cx; private OrdinaryObject obj; private HashSet<Object> visitedKeys = new HashSet<>(); private Iterator<String> keys; private Iterator<?> protoKeys; EnumKeysIterator(ExecutionContext cx, OrdinaryObject obj) { this.cx = cx; this.obj = obj; this.keys = obj.enumerateKeys().iterator(); } @Override protected Object tryNext() { HashSet<Object> visitedKeys = this.visitedKeys; Iterator<String> keys = this.keys; if (keys != null) { assert protoKeys == null; while (keys.hasNext()) { String key = keys.next(); if (visitedKeys.add(key) && obj.isEnumerableOwnProperty(key)) { return key; } } // switch to prototype enumerate ScriptObject proto = this.obj.getPrototypeOf(cx); if (proto != null) { if (proto instanceof OrdinaryObject) { this.obj = ((OrdinaryObject) proto); this.keys = ((OrdinaryObject) proto).enumerateKeys().iterator(); return tryNext(); } else { this.obj = null; this.keys = null; this.protoKeys = FromListIterator(cx, proto.enumerate(cx)); } } else { this.obj = null; this.keys = null; this.protoKeys = null; } } Iterator<?> protoKeys = this.protoKeys; if (protoKeys != null) { while (protoKeys.hasNext()) { Object key = protoKeys.next(); if (visitedKeys.add(key)) { return key; } } // visited all inherited keys this.protoKeys = null; } return null; } } /** 9.1.13 [[OwnPropertyKeys]] ( ) */ @Override public final ScriptObject ownPropertyKeys(ExecutionContext cx) { return MakeListIterator(cx, enumerateOwnKeys().iterator()); } /** 9.1.13 [[OwnPropertyKeys]] ( ) */ protected Collection<Object> enumerateOwnKeys() { return new ArrayList<>(__keys__()); } private static class DefaultAllocator implements ObjectAllocator<OrdinaryObject> { static final ObjectAllocator<OrdinaryObject> INSTANCE = new DefaultAllocator(); @Override public OrdinaryObject newInstance(Realm realm) { return new OrdinaryObject(realm); } } /** 9.1.14 ObjectCreate Abstract Operation */ public static OrdinaryObject ObjectCreate(ExecutionContext cx) { return ObjectCreate(cx, Intrinsics.ObjectPrototype, DefaultAllocator.INSTANCE); } /** 9.1.14 ObjectCreate Abstract Operation */ public static OrdinaryObject ObjectCreate(ExecutionContext cx, ScriptObject proto) { return ObjectCreate(cx, proto, DefaultAllocator.INSTANCE); } /** 9.1.14 ObjectCreate Abstract Operation */ public static OrdinaryObject ObjectCreate(ExecutionContext cx, Intrinsics proto) { return ObjectCreate(cx, proto, DefaultAllocator.INSTANCE); } /** 9.1.14 ObjectCreate Abstract Operation */ public static <OBJECT extends OrdinaryObject> OBJECT ObjectCreate(ExecutionContext cx, ScriptObject proto, ObjectAllocator<OBJECT> allocator) { OBJECT obj = allocator.newInstance(cx.getRealm()); obj.setPrototype(proto); return obj; } /** 9.1.14 ObjectCreate Abstract Operation */ public static <OBJECT extends OrdinaryObject> OBJECT ObjectCreate(ExecutionContext cx, Intrinsics proto, ObjectAllocator<OBJECT> allocator) { OBJECT obj = allocator.newInstance(cx.getRealm()); obj.setPrototype(cx.getIntrinsic(proto)); return obj; } }
package com.github.steveice10.mc.protocol.data.game.chunk; import com.github.steveice10.mc.protocol.data.game.world.block.BlockState; import com.github.steveice10.mc.protocol.util.NetUtil; import com.github.steveice10.mc.protocol.util.ObjectUtil; import com.github.steveice10.packetlib.io.NetInput; import com.github.steveice10.packetlib.io.NetOutput; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; public class BlockStorage { private static final BlockState AIR = new BlockState(0); private int blockCount = 0; private int bitsPerEntry; private List<BlockState> states; private FlexibleStorage storage; public BlockStorage() { this.bitsPerEntry = 4; this.states = new ArrayList<BlockState>(); this.states.add(AIR); this.storage = new FlexibleStorage(this.bitsPerEntry, 4096); } public BlockStorage(NetInput in) throws IOException { this.blockCount = in.readShort(); this.bitsPerEntry = in.readUnsignedByte(); this.states = new ArrayList<BlockState>(); int stateCount = this.bitsPerEntry > 8 ? 0 : in.readVarInt(); for(int i = 0; i < stateCount; i++) { this.states.add(NetUtil.readBlockState(in)); } this.storage = new FlexibleStorage(this.bitsPerEntry, in.readLongs(in.readVarInt())); } private static int index(int x, int y, int z) { return y << 8 | z << 4 | x; } private static BlockState rawToState(int raw) { return new BlockState(raw); } private static int stateToRaw(BlockState state) { return state.getId(); } public void write(NetOutput out) throws IOException { out.writeShort(this.blockCount); out.writeByte(this.bitsPerEntry); if (this.bitsPerEntry <= 8) { out.writeVarInt(this.states.size()); for (BlockState state : this.states) { NetUtil.writeBlockState(out, state); } } long[] data = this.storage.getData(); out.writeVarInt(data.length); out.writeLongs(data); } public int getBitsPerEntry() { return this.bitsPerEntry; } public List<BlockState> getStates() { return Collections.unmodifiableList(this.states); } public FlexibleStorage getStorage() { return this.storage; } public BlockState get(int x, int y, int z) { int id = this.storage.get(index(x, y, z)); return this.bitsPerEntry <= 8 ? (id >= 0 && id < this.states.size() ? this.states.get(id) : AIR) : rawToState(id); } public void set(int x, int y, int z, BlockState state) { if (state.getId() != AIR.getId()) { blockCount++; } else { blockCount } int id = this.bitsPerEntry <= 8 ? this.states.indexOf(state) : stateToRaw(state); if(id == -1) { this.states.add(state); if(this.states.size() > 1 << this.bitsPerEntry) { this.bitsPerEntry++; List<BlockState> oldStates = this.states; if(this.bitsPerEntry > 8) { oldStates = new ArrayList<BlockState>(this.states); this.states.clear(); this.bitsPerEntry = 13; } FlexibleStorage oldStorage = this.storage; this.storage = new FlexibleStorage(this.bitsPerEntry, this.storage.getSize()); for(int index = 0; index < this.storage.getSize(); index++) { this.storage.set(index, this.bitsPerEntry <= 8 ? oldStorage.get(index) : stateToRaw(oldStates.get(index))); } } id = this.bitsPerEntry <= 8 ? this.states.indexOf(state) : stateToRaw(state); } this.storage.set(index(x, y, z), id); } public boolean isEmpty() { for(int index = 0; index < this.storage.getSize(); index++) { if(this.storage.get(index) != 0) { return false; } } return true; } @Override public boolean equals(Object o) { if(this == o) return true; if(!(o instanceof BlockStorage)) return false; BlockStorage that = (BlockStorage) o; return this.bitsPerEntry == that.bitsPerEntry && Objects.equals(this.states, that.states) && Objects.equals(this.storage, that.storage); } @Override public int hashCode() { return ObjectUtil.hashCode(this.bitsPerEntry, this.states, this.storage); } @Override public String toString() { return ObjectUtil.toString(this); } }
package com.google.step.YOUR_PROJECT_NAME_HERE.external; import com.google.step.YOUR_PROJECT_NAME_HERE.data.Card; import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; public final class W3SchoolClient { private static final String CARD_TITLE_ID = "h1"; private static final String CARD_DESC_ID = "p"; private static final String CARD_SNIPPET_ID = "w3-example"; private static final String CARD_CODE_ID = "w3-code"; public Card search(String w3Link) { Document doc; try { doc = Jsoup.connect(w3Link).get(); Elements titles = doc.getElementsByTag(CARD_TITLE_ID); Elements descriptions = doc.getElementsByTag(CARD_DESC_ID); Elements snippets = doc.getElementsByClass(CARD_SNIPPET_ID); String title = ""; String description = ""; String code = ""; if (!titles.isEmpty() && !descriptions.isEmpty() && !snippets.isEmpty()) { title = titles.first().text(); description = descriptions.first().text(); code = snippets.first().getElementsByClass(CARD_CODE_ID).text(); } if (!title.isEmpty() && !description.isEmpty() && !code.isEmpty()) { return new Card(title, code, w3Link, description); } return null; } catch (IOException e) { return null; } } }
package com.gruppe27.fellesprosjekt.server.controllers; import com.gruppe27.fellesprosjekt.common.Event; import com.gruppe27.fellesprosjekt.common.User; import com.gruppe27.fellesprosjekt.common.messages.ErrorMessage; import com.gruppe27.fellesprosjekt.common.messages.EventMessage; import com.gruppe27.fellesprosjekt.common.messages.GeneralMessage; import com.gruppe27.fellesprosjekt.server.CalendarConnection; import com.gruppe27.fellesprosjekt.server.DatabaseConnector; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.LocalDate; import java.util.HashSet; public class EventController { private static EventController instance = null; private static final String EVENT_QUERY = "SELECT Event.id, Event.name, Event.date, Event.start, Event.end, Creator.username, Creator.name, " + "Participant.username, Participant.name, UserEvent.status " + "FROM Event JOIN User AS Creator ON Event.creator = Creator.username " + "JOIN UserEvent ON Event.id = UserEvent.event_id " + "JOIN User AS Participant ON UserEvent.username = Participant.username "; protected EventController() { } public static EventController getInstance() { if (instance == null) { instance = new EventController(); } return instance; } public void handleMessage(CalendarConnection connection, Object message) { EventMessage eventMessage = (EventMessage) message; switch (eventMessage.getCommand()) { case CREATE_EVENT: createEvent(connection, eventMessage.getEvent()); break; case SEND_EVENTS: sendEvents(connection, eventMessage.getFrom(), eventMessage.getTo()); break; } } private void sendEvents(CalendarConnection connection, LocalDate from, LocalDate to) { try { String query = EVENT_QUERY + "WHERE (Event.date >= ? AND Event.date <= ?) AND " + "? IN (SELECT username FROM UserEvent WHERE event_id=Event.id)"; PreparedStatement statement = DatabaseConnector.getConnection().prepareStatement(query); statement.setString(1, from.toString()); statement.setString(2, to.toString()); statement.setString(3, connection.getUser().getUsername()); ResultSet resultSet = statement.executeQuery(); HashSet<Event> events = parseEventResult(resultSet, connection.getUser().getUsername()); EventMessage createdMessage = new EventMessage(EventMessage.Command.RECEIVE_EVENTS, events); connection.sendTCP(createdMessage); System.out.println("sent " + events.size() + "events."); } catch (SQLException e) { e.printStackTrace(); ErrorMessage error = new ErrorMessage(); connection.sendTCP(error); } } private HashSet<Event> parseEventResult(ResultSet result, String username) throws SQLException { int currentEventId = -1; Event event = null; HashSet<Event> events = new HashSet<>(); while (result.next()) { if (result.getInt(1) != currentEventId) { event = new Event(); currentEventId = result.getInt(1); event.setName(result.getString(2)); event.setDate(result.getDate(3).toLocalDate()); event.setStartTime(result.getTime(4).toLocalTime()); event.setEndTime(result.getTime(5).toLocalTime()); User creator = new User(result.getString(6), result.getString(7)); User participant = new User(result.getString(8), result.getString(9)); if (participant.getUsername().equals(username)) { event.setStatus(Event.Status.valueOf(result.getString(10))); } event.addParticipant(participant); event.setCreator(creator); event.setId(currentEventId); events.add(event); System.out.println("add event"); } else { if (event == null) { return events; } User participant = new User(result.getString(8), result.getString(9)); if (participant.getUsername().equals(username)) { event.setStatus(Event.Status.valueOf(result.getString(10))); } event.addParticipant(participant); System.out.println("Add user"); } } return events; } private void createEvent(CalendarConnection connection, Event event) { try { PreparedStatement statement = DatabaseConnector.getConnection().prepareStatement( "INSERT INTO Event(name, date, start, end, creator, room) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS ); statement.setString(1, event.getName()); statement.setString(2, event.getDate().toString()); statement.setString(3, event.getStartTime().toString()); statement.setString(4, event.getEndTime().toString()); statement.setString(5, connection.getUser().getUsername()); statement.setString(6, event.getRoom().getRoomName()); int result = statement.executeUpdate(); int eventId; ResultSet eventIdResultSet = statement.getGeneratedKeys(); eventIdResultSet.next(); eventId = eventIdResultSet.getInt(1); event.setId(eventId); int number_of_participants = 0; for (User participant: event.getUserParticipants()) { PreparedStatement participantStatement = DatabaseConnector.getConnection().prepareStatement( "INSERT INTO UserEvent(username,event_id) VALUES (?,?)" ); participantStatement.setString(1, participant.getUsername()); participantStatement.setInt(2, eventId); int participantResult = participantStatement.executeUpdate(); number_of_participants += participantResult; NotificationController.getInstance().newEventNotification(event, participant); } System.out.println(number_of_participants + " participants added to event."); System.out.println(result + " rows affected"); GeneralMessage createdMessage = new GeneralMessage(GeneralMessage.Command.SUCCESSFUL_CREATE, "Avtalen " + event.getName() + " opprettet."); connection.sendTCP(createdMessage); } catch (SQLException e) { e.printStackTrace(); ErrorMessage error = new ErrorMessage(); connection.sendTCP(error); } } }
package com.tomtom.services.configuration.implementation; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.google.common.base.Splitter; import com.tomtom.services.configuration.ConfigurationServiceProperties; import com.tomtom.services.configuration.domain.Node; import com.tomtom.services.configuration.dto.NodeDTO; import com.tomtom.services.configuration.dto.SearchResultDTO; import com.tomtom.services.configuration.dto.SearchResultsDTO; import com.tomtom.speedtools.apivalidation.exceptions.ApiException; import com.tomtom.speedtools.objects.Immutables; import com.tomtom.speedtools.objects.Tuple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.inject.Inject; import javax.ws.rs.core.Response.Status; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import static com.google.common.base.Strings.nullToEmpty; import static com.tomtom.services.configuration.TreeResource.*; import static com.tomtom.speedtools.objects.Objects.notNullOr; /** * This class implements the search tree, which consists of nodes and leafs. Every node can have * 0 or more children nodes and 0 or 1 leaf node. There is a single root node. * * Nodes have a match string, an optional list of child nodes and an optional leaf with parameters. * Node match strings are unique within children nodes and cannot be empty, except for the root node * which is absent. */ @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") public class Configuration { private static final Logger LOG = LoggerFactory.getLogger(Configuration.class); private final boolean initialConfigurationOK; /** * The root node of the tree. */ @Nonnull private final Node root; /** * The URL to read the configuration tree from. */ @Nonnull private final ConfigurationServiceProperties configurationServiceProperties; @Inject public Configuration(@Nonnull final ConfigurationServiceProperties configurationServiceProperties) throws IncorrectConfigurationException { // Call the helper constructor and read the configuration as one large string. this(configurationServiceProperties, readConfiguration(configurationServiceProperties.getStartupConfigurationURI())); } /** * Package private. Constructor used for testing the class. Allows you to inject a string configuration directly. * This constructor is also used by the "real" external constructor to pass the configuration file contents. * * @param configurationServiceProperties Configuration. * @param overrideStartupConfiguration String configuration which overrides the configuration URL. * Note that the regular constructor uses this as well. */ Configuration( @Nonnull final ConfigurationServiceProperties configurationServiceProperties, @Nullable final String overrideStartupConfiguration) throws IncorrectConfigurationException { // Create an empty root. NodeDTO realRoot = new NodeDTO(null, null, null, null, null, null, null); boolean realInitialConfigurationOK = false; this.configurationServiceProperties = configurationServiceProperties; // If the configuration is specified as a parameter (in tests), use that one. if (overrideStartupConfiguration != null) { try { // Read the tree and validate. final NodeDTO root = getRootNodeAndValidateTree( configurationServiceProperties.getStartupConfigurationURI(), overrideStartupConfiguration); LOG.info("Tree: Startup configuration read OK, startupConfiguration={}", root); // Use the root just read as the real root. realRoot = root; realInitialConfigurationOK = true; } catch (final ApiException | IncorrectConfigurationException e) { LOG.error("Tree: Startup configuration cannot be read: {}", e.getMessage()); throw new IncorrectConfigurationException(e.getMessage()); } } // Convert the DTO tree to a domain tree. this.root = new Node(realRoot, null); this.initialConfigurationOK = realInitialConfigurationOK; } /** * Return if startup configuration was correctly read or not. This may be used at startup time to prevent * the service from booting up. * * @return True if the config is OK. */ public boolean isStartupConfigurationOK() { return initialConfigurationOK; } /** * Return the URI of the start-up configuration. * * @return URI of start-up configuration. */ @Nonnull public String getStartupConfigurationURI() { return configurationServiceProperties.getStartupConfigurationURI(); } /** * Get the root node. * * @return Root node. Has an empty match strings. */ @Nonnull public Node getRoot() { return root; } /** * Find the deepest node which matches the provide search path and which has a leaf with parameters * attached to it. * * @param levelSearchTermsList A list of queries, which consists of a map: (level-name: search-term). * @return Empty list if no matching node was found. Otherwise a list of tuples with the parameters of the deepest node found * and the full path to the matching node. */ @Nonnull SearchResultsDTO matchNode(@Nonnull final List<Map<String, String>> levelSearchTermsList) { // Result list. final List<SearchResultDTO> results = new ArrayList<>(); // Process all search queries. for (final Map<String, String> levelSearchTerms : levelSearchTermsList) { LOG.debug("matchNode: search #{}, levelSearchTerms={}", results.size() + 1, levelSearchTerms.toString()); /* * Search tree for parameters. Start with assuming the search fails and the result is * the ultimate fallback: the parameters of the root node. */ Node nodeOfParameters = root; // This points at the node the parameters were taken from. Node nodeToCheck = root; // This points at the node to we need to dive into. if (root.getLevels() != null) { // Only execute search if levels actually exist. for (final String levelName : root.getLevels()) { boolean found = false; // This indicates whether we found a match or not. // Find the corresponding search term in the query. final String searchTerm = nullToEmpty(levelSearchTerms.get(levelName)); LOG.debug("matchNode: {}={}", levelName, searchTerm); /** * Check all children nodes of this node (if they exist). */ final Collection<Node> children = nodeToCheck.getNodes(); if (children != null) { /** * First check all 'exact' literal (non-regex) matches. If the string match is exact, * regular expression matches will not be checked. This is to make sure that if * a ".*" node is specified "left of" other nodes, it does not overrule literal * matches. */ final List<Node> nonExactMatches = new ArrayList<>(); for (final Node child : children) { // The name of children is a regex. final String name = child.getMatch(); assert name != null; // Check if the term matches the node name literally. //noinspection ConstantConditions if (searchTerm.matches(createCaseInsensitivePattern(Pattern.quote(name)))) { LOG.debug("matchNode: FOUND, literal match, {}={}", levelName, name); found = true; /** * Remember the parameters of this child node, as it is more specific than the * one kept until now. */ if (child.getParameters() != null) { nodeOfParameters = child; } // Start next search in this subtree. nodeToCheck = child; break; } else { // Keep this node for second round, checking regex matches. nonExactMatches.add(child); } } // Second round: only if no exact match was found, check regular expressions. if (!found) { for (final Node child : nonExactMatches) { // The name of children is a regex. final String match = child.getMatch(); assert match != null; //noinspection ConstantConditions if (searchTerm.matches(createCaseInsensitivePattern(match))) { LOG.debug("matchNode: FOUND, regular expression match, {}={}", levelName, match); found = true; /** * Remember the parameters of this child node, as it is more specific than the * one kept until now. */ if (child.getParameters() != null) { nodeOfParameters = child; } // Start next search in this subtree. nodeToCheck = child; break; } } } } // Stop searching for deeper path terms if we couldn't find a match for this term. if (!found) { LOG.debug("matchNode: NOT FOUND, nothing for {}={}", levelName, searchTerm); break; } } } final SearchResultDTO searchResult; //noinspection ObjectEquality if (nodeOfParameters == root) { if (root.getParameters() == null) { /** * If no parameters were found, anywhere, then return an empty list. This indicates at least one * of the queries was not successful. The other queries will not even be executed. */ return new SearchResultsDTO(Immutables.emptyList()); } else { // Return the non-null root parameters as a fallback if no matches were found. searchResult = new SearchResultDTO(root); } } else { // Return the non-null parameters of the found node. searchResult = new SearchResultDTO(nodeOfParameters); } // Set the 'searched' attribute. @SuppressWarnings("NonConstantStringShouldBeStringBuffer") String searched = ""; for (final String levelName : root.getLevels()) { final String searchTerm = nullToEmpty(levelSearchTerms.get(levelName)); searched = searched + (searched.isEmpty() ? "" : "&") + levelName + '=' + searchTerm; } searchResult.setSearched(searched); // Set the 'matched' of the node from which the parameters were gotten. final String matched = getMatchedValue(0, root, nodeOfParameters, "").getValue1(); searchResult.setMatched(matched); results.add(searchResult); LOG.debug("matchNode: searched={}, matched={}", searched, matched); } final SearchResultsDTO searchResults = new SearchResultsDTO(results); return searchResults; } /** * Given a full node path, return the node and its parent node, or null. * * Important: If the root node is found, the parent node is ALSO the root node. This is primarily because * you cannot return a null value in a tuple. * * @param fullNodePath Full path to a node, separated by separators. * @return Null if not found. Otherwise a tuple with the node found (value 1) and its parent node (value 2). */ @Nullable Node findNode(@Nonnull final String fullNodePath) { // Trim path. final String trimmedFullNodePath = fullNodePath.trim(); // Return root node if path is empty. if (trimmedFullNodePath.isEmpty()) { // Important: root has no parent, but you cannot return null as a parent either, so return root as well. return root; } // Search tree for right node. Node node = root; for (final String sub : Splitter.on(SEPARATOR_PATH).trimResults().split(trimmedFullNodePath)) { boolean found = false; final Collection<Node> children = node.getNodes(); if (children != null) { for (final Node child : children) { final String name = notNullOr(child.getMatch(), ""); if (name.equals(sub)) { found = true; node = child; break; } } } if (!found) { return null; } } return node; } /** * Get matched search terms. Note that the node object itself will be searched for, so the method * will use an object equality test to find a specific node, not an equals() test. * * @param level Number of level at which we are searching. * @param tree Tree to search the node in. * @param node Node to search for. * @param pathPrefix Path to be used as prefix (without trailing '/'). * This is supplied to be able to make the method recursively callable. * @return A tuple with as value 1 the matched search terms, within the specified tree and as value 2 a boolean * which indicates whether the node was found or not. If not, the returned path equals the path prefix. */ @Nonnull private Tuple<String, Boolean> getMatchedValue( final int level, @Nonnull final Node tree, @Nullable final Node node, @Nonnull final String pathPrefix) { if (tree.getNodes() != null) { for (final Node child : tree.getNodes()) { // Get level name. assert root.getLevels() != null; assert level < root.getLevels().size(); @SuppressWarnings("ConstantConditions") final String levelName = root.getLevels().get(level); // Get match string from node. final String nodeMatch = notNullOr(child.getMatch(), ""); // Check if this is the exact node (object equality). //noinspection ObjectEquality if (child == node) { // Get level name and append search term. return new Tuple<>(pathPrefix + (pathPrefix.isEmpty() ? "" : "&") + levelName + '=' + nodeMatch, true); } else { final Tuple<String, Boolean> found = getMatchedValue(level + 1, child, node, pathPrefix + (pathPrefix.isEmpty() ? "" : "&") + levelName + '=' + nodeMatch); if (found.getValue2()) { return found; } } } } return new Tuple<>(pathPrefix, false); } /** * Read a configuration from a URI, which may be prefixed http:, https:, file: or classpath:. * The configuration is returned as a single concatenated string. * * @param uri URI to read from. * @return Concatenated input lines, or null if reading the configuration failed. */ @Nonnull private static String readConfiguration(@Nonnull final String uri) throws IncorrectConfigurationException { InputStreamReader inputStreamReader = null; try { if (uri.startsWith("http:") || uri.startsWith("https:")) { final URL httpURL = new URL(uri); final HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection(); connection.setRequestMethod("GET"); final int responseCode = connection.getResponseCode(); if (responseCode != Status.OK.getStatusCode()) { throw new IncorrectConfigurationException("Could not read startup configuration, uri=" + uri + ", responseCode={}" + responseCode); } //noinspection IOResourceOpenedButNotSafelyClosed inputStreamReader = new InputStreamReader(connection.getInputStream()); } else if (uri.startsWith("file:")) { final String filename = uri.replaceFirst("file::?", ""); LOG.debug("readConfiguration: read file={}", filename); //noinspection IOResourceOpenedButNotSafelyClosed inputStreamReader = new FileReader(filename); } else if (uri.startsWith("classpath:")) { final String filename = uri.replaceFirst("classpath::?", ""); LOG.debug("readConfiguration: read from classpath={}", filename); final InputStream resourceAsStream = Configuration.class.getClassLoader().getResourceAsStream(filename); if (resourceAsStream == null) { throw new IncorrectConfigurationException("File not found on classpath: uri=" + uri); } //noinspection IOResourceOpenedButNotSafelyClosed inputStreamReader = new InputStreamReader(resourceAsStream); } else { throw new IncorrectConfigurationException("Unknown protocol, must specify 'http:', 'https:', 'file:', or 'classpath:'."); } } catch (final IOException e) { LOG.warn("readConfiguration: {}, message={}", uri, e.getMessage()); try { assert inputStreamReader != null; //noinspection ConstantConditions inputStreamReader.close(); } catch (final IOException ignored) { // Ignored. } throw new IncorrectConfigurationException("Cannot read configuration, url=" + uri + ", exception=" + e.getMessage()); } // Read input stream. final StringBuilder sb = new StringBuilder(); try { //noinspection NestedTryStatement try (BufferedReader buffer = new BufferedReader(inputStreamReader)) { String inputLine; while ((inputLine = buffer.readLine()) != null) { LOG.trace("readConfiguration: {}", inputLine); sb.append(inputLine); sb.append('\n'); } } } catch (final IOException e) { throw new IncorrectConfigurationException("readConfiguration: Could not parse configuration, uri={}" + uri + ", response=" + sb + ", message=" + e.getMessage()); } return sb.toString(); } @Nonnull private static NodeDTO getRootNodeAndValidateTree( @Nonnull final String include, @Nonnull final String content) throws IncorrectConfigurationException { // Read the tree from the configuration. final NodeDTO root = getChildNodeFromConfiguration(include, content, new ArrayList<>()); // Check if the match string of the root is null; all child match strings have been checked by now (when tree was read in). if (root.getMatch() != null) { throw new IncorrectConfigurationException("Configuration is not OK! Top-level root node must not contain a match string."); } // Check 'levels' specification. if (root.getLevels() == null) { // The 'levels' element can only be empty if the configuration is empty. if (root.getNodes() != null) { throw new IncorrectConfigurationException("No 'levels' found: unique names must be specified for all node levels."); } } else { // Check correctness of level names. final Set<String> levels = new HashSet<>(); for (final String level : root.getLevels()) { // Level name must be non-empty. if (level.isEmpty()) { throw new IncorrectConfigurationException("Level name cannot be empty."); } // Level name cannot contain certain characters, like [,;/]. if (!isValidMatchString(level)) { throw new IncorrectConfigurationException("Level name cannot contain '" + SEPARATOR_WRONG + "', '" + SEPARATOR_PATH + "' or '" + SEPARATOR_QUERY + "'."); } // Level names must be unique. if (levels.contains(level.toLowerCase())) { throw new IncorrectConfigurationException("Level name '" + level + "' was specified more than once."); } levels.add(level.toLowerCase()); } // If the levels are specified there must be at least as many order names as there are node levels. final int deepestLevel = deepestNodeLevel(root.getNodes(), 1); if (root.getLevels().size() < deepestLevel) { throw new IncorrectConfigurationException("Incorrect number of 'levels' specified, expecting at least " + deepestLevel + " levels"); } } // Validate the root (and all of its children). root.validate(); return root; } private static boolean isValidMatchString(@Nonnull final String match) { return ((match.indexOf(SEPARATOR_WRONG) + match.indexOf(SEPARATOR_PATH) + match.indexOf(SEPARATOR_QUERY)) == -3); } @Nonnull private static List<NodeDTO> getChildNodeListFromConfiguration( @Nonnull final String include, @Nonnull final String content, @Nonnull final List<String> included) throws IncorrectConfigurationException { // Read tree as JSON or XML. try { // Try to read as JSON first. final ObjectMapper mapper = new ObjectMapper(); mapper.configure(Feature.ALLOW_COMMENTS, true); return mapper.readValue(content, new TypeReference<List<NodeDTO>>(){}); } catch (final IOException e1) { try { // If JSON fails, try XML instead. final XmlMapper mapper = new XmlMapper(); return mapper.readValue(content, new TypeReference<List<NodeDTO>>(){}); } catch (final IOException e2) { // Not valid JSON or XML. final String msg; final String jsonError = e1.getMessage(); final String xmlError = e2.getMessage(); if (jsonError.startsWith("Unexpected character ('<'")) { msg = "XML ERROR: " + xmlError; } else { msg = "JSON ERROR: " + jsonError; } throw new IncorrectConfigurationException("Configuration is NOT OK! Should be valid JSON or XML\n" + msg); } } } @Nonnull private static NodeDTO getChildNodeFromConfiguration( @Nonnull final String include, @Nonnull final String content, @Nonnull final List<String> included) throws IncorrectConfigurationException { // Read tree as JSON or XML. NodeDTO tree; try { // Try to read as JSON first. final ObjectMapper mapper = new ObjectMapper(); mapper.configure(Feature.ALLOW_COMMENTS, true); tree = mapper.readValue(content, NodeDTO.class); } catch (final IOException e1) { try { // If JSON fails, try XML instead. final XmlMapper mapper = new XmlMapper(); tree = mapper.readValue(content, NodeDTO.class); } catch (final IOException e2) { // Not valid JSON or XML. final String msg; final String jsonError = e1.getMessage(); final String xmlError = e2.getMessage(); if (jsonError.startsWith("Unexpected character ('<'")) { msg = "XML ERROR: " + xmlError; } else { msg = "JSON ERROR: " + jsonError; } throw new IncorrectConfigurationException("Configuration is NOT OK! Should be valid JSON or XML\n" + msg); } } // Inline all includes recursively. expandAllIncludes(tree, included); // Check if node match strings do not conflict. if (!checkNodeMatchStringsRoot(tree)) { throw new IncorrectConfigurationException("Configuration is not OK! " + "Nodes match strings are incorrectly formatted, not unique or contain incorrect key/value pairs."); } // Validate the (sub)tree. tree.validate(); LOG.debug("getRootNodeFromConfiguration: Configuration for node '{}' is OK", include); return tree; } /** * Return the deepest node level. * * @param nodes Current level of nodes. * @param level Current index of level. * @return Deepest level found. */ private static int deepestNodeLevel(@Nullable final Collection<NodeDTO> nodes, final int level) { if (nodes == null) { // This level wasn't a real level. return level - 1; } // This level is a real level. int deepest = level; for (final NodeDTO node : nodes) { final int newLevel = deepestNodeLevel(node.getNodes(), level + 1); deepest = Math.max(deepest, newLevel); } return deepest; } /** * Give a series of nodes at the same level, check if the match strings are OK. * Check the children as well * * @param root Root node. * @return True if all OK, false otherwise. */ private static boolean checkNodeMatchStringsRoot(@Nonnull final NodeDTO root) { return checkNodeMatchStringsChildren(root.getNodes()); } /** * Give a series of nodes at the same level, check if the match strings are OK. * Check the children as well * * @param children Set of nodes. * @return True if all OK, false otherwise. */ private static boolean checkNodeMatchStringsChildren(@Nullable final List<NodeDTO> children) { if (children == null) { return true; } boolean ok = true; final Set<String> matches = new HashSet<>(); // Node match strings (per level). for (final NodeDTO child : children) { final String match = child.getMatch(); if (match == null) { ok = false; LOG.error("checkNodeMatchStringsChildren: match cannot be null"); } else if (match.isEmpty()) { ok = false; LOG.error("checkNodeMatchStringsChildren: match cannot be empty"); } else if (!isValidMatchString(match)) { ok = false; LOG.error("checkNodeMatchStringsChildren: incorrect format fort match"); } else if (matches.contains(match)) { ok = false; LOG.error("checkNodeMatchStringsChildren: match string must be unique, match={}", match); } else { matches.add(match); ok = ok && checkNodeMatchStringsChildren(child.getNodes()); } } return ok; } /** * Expand all the included subtrees in a node. * * @param tree Node to expand. * @param included Memory of which include files were processed. * @throws IncorrectConfigurationException If include recursion was detected. * @return Replacements for the node that was just expanded. */ private static List<NodeDTO> expandAllIncludes( @Nonnull final NodeDTO tree, @Nonnull final List<String> included) throws IncorrectConfigurationException { final String include = tree.getInclude(); final String includeArray = tree.getIncludeArray(); if (include != null || includeArray != null) { LOG.info("expandAllIncludes: Include specified, include={}", include); List<NodeDTO> replacement; if (include != null) { // Check endless recursion. if (included.contains(include)) { throw new IncorrectConfigurationException("Endless recursion detected at include=" + include); } // Push name to stack. included.add(0, include); // Read JSON content from include. final String content = readConfiguration(include); // Parse nodes from content. replacement = Arrays.asList(getChildNodeFromConfiguration(include, content, included)); } else { // Check endless recursion. if (includeArray != null && included.contains(includeArray)) { throw new IncorrectConfigurationException("Endless recursion detected at include=" + includeArray); } // Push name to stack. included.add(0, includeArray); // Read JSON content from include. final String content = readConfiguration(include); // Parse nodes from content. replacement = getChildNodeListFromConfiguration(include, content, included); } // Expand all includes in children, and construct list of replacements final List<NodeDTO> children = new ArrayList<NodeDTO>(); for (final NodeDTO child : replacement) { children.addAll(expandAllIncludes(child, included)); } // Pop name from stack. final String removed = included.remove(0); assert removed.equals(include); return children; } else { // Include not specified. Process children. final List<NodeDTO> children = tree.getNodes(); if (children != null) { final List<NodeDTO> replacement = new ArrayList<NodeDTO>(); for (final NodeDTO child : children) { replacement.addAll(expandAllIncludes(child, included)); } children.clear(); children.addAll(replacement); } return Arrays.asList(tree); } } /** * Create a regex pattern which matches strings case-insensitive. * * @param pattern Pattern to make case-insensitive. * @return Case-insensitive pattern. */ @Nonnull private static String createCaseInsensitivePattern(@Nonnull final String pattern) { return "(?i:" + pattern + ')'; } }
/** * UnionFind/Disjoint Set data structure implementation. This code was inspired by the union find * implementation found in 'Algorithms Fourth Edition' by Robert Sedgewick and Kevin Wayne. * * @author William Fiset, william.alexandre.fiset@gmail.com */ package com.williamfiset.algorithms.datastructures.unionfind; public class UnionFind { // The number of elements in this union find private int size; // Used to track the size of each of the component private int[] sz; // id[i] points to the parent of i, if id[i] = i then i is a root node private int[] id; // Tracks the number of components in the union find private int numComponents; public UnionFind(int size) { if (size <= 0) throw new IllegalArgumentException("Size <= 0 is not allowed"); this.size = numComponents = size; sz = new int[size]; id = new int[size]; for (int i = 0; i < size; i++) { id[i] = i; // Link to itself (self root) sz[i] = 1; // Each component is originally of size one } } // Find which component/set 'p' belongs to, takes amortized constant time. public int find(int p) { // Find the root of the component/set int root = p; while (root != id[root]) root = id[root]; // Compress the path leading back to the root. // Doing this operation is called "path compression" // and is what gives us amortized time complexity. while (p != root) { int next = id[p]; id[p] = root; p = next; } return root; } // This is an alternative recursive formulation for the find method // public int find(int p) { // if (p == id[p]) return p; // return id[p] = find(id[p]); // Return whether or not the elements 'p' and // 'q' are in the same components/set. public boolean connected(int p, int q) { return find(p) == find(q); } // Return the size of the components/set 'p' belongs to public int componentSize(int p) { return sz[find(p)]; } // Return the number of elements in this UnionFind/Disjoint set public int size() { return size; } // Returns the number of remaining components/sets public int components() { return numComponents; } // Unify the components/sets containing elements 'p' and 'q' public void unify(int p, int q) { // These elements are already in the same group! if (connected(p, q)) return; int root1 = find(p); int root2 = find(q); // Merge smaller component/set into the larger one. if (sz[root1] < sz[root2]) { sz[root2] += sz[root1]; id[root1] = root2; id[root2] = 0; } else { sz[root1] += sz[root2]; id[root2] = root1; id[root1] = 0; } // Since the roots found are different we know that the // number of components/sets has decreased by one numComponents } }
package ml.duncte123.skybot.commands.essentials.eval.filter; import groovy.lang.Closure; import groovy.lang.Script; import Java.lang.VRCubeException; import ml.duncte123.skybot.entities.delegate.*; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.User; import org.kohsuke.groovy.sandbox.GroovyValueFilter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.regex.Pattern; public class EvalFilter extends GroovyValueFilter { private static final Set<Class<?>> ALLOWED_TYPES = new HashSet<>(); /** * Filter arrays of * * @author ramidzkh */ private static final Pattern ARRAY_FILTER = Pattern.compile( // Case insensitive "(?i)" // Decimals and Octals + "((\\[(\\s*[0-9]+\\s*)\\])" // Binary + "|(\\[(\\s*)(0b)([01_]*)(\\s*)\\])" // Hexadecimal + "|(\\[\\s*(0x)[0-9a-f]+(\\s*)\\]))"), MENTION_FILTER = Pattern.compile("<@[0-9]{18}>"); /** * Constructor */ public EvalFilter() { ALLOWED_TYPES.addAll(Arrays.asList(ALLOWED_TYPES_LIST)); } /** * This filters the script * @param o the script to filter * @return the script if it passes the filter */ @Override public final Object filter(Object o) { if (o==null || ALLOWED_TYPES.contains(o.getClass()) ) return o; if(o instanceof JDA) return new JDADelegate((JDA) o); if(o instanceof User) return new UserDelegate((User) o); if(o instanceof Guild) return new GuildDelegate((Guild) o); if(o instanceof Script) return o; if(o instanceof Closure) throw new SecurityException("Closures are not allowed."); throw new VRCubeException("Class not allowed: " + o.getClass().getName()); } @Override public Object onSetArray(Invoker invoker, Object receiver, Object index, Object value) throws Throwable { throw new VRCubeException( String.format("Cannot set array on %s, Class: %s, Index: %s, Value: %s", receiver.toString(), receiver.getClass().getComponentType().getName(), index.toString(), value.toString())); } /** * This checks if the script contains any loop * @param toFilter the script to filter * @return true if the script contains a loop */ public boolean filterLoops(String toFilter) { return Pattern.compile( //for or while loop "((while|for)" + //Stuff in the brackets "\\s*\\(.*\\))|" + // Other groovy loops "(\\.step|\\.times|\\.upto|\\.each)" //match and find ).matcher(toFilter).find(); } /** * This checks if the script contains an array * @param toFilter the script to filter * @return true if the script contains an array */ public boolean filterArrays(String toFilter) { //Big thanks to ramidzkh return ARRAY_FILTER.matcher(toFilter).find(); } /** * This contains a list of all the allowed classes */ private static final Class<?>[] ALLOWED_TYPES_LIST = { String.class, Boolean.class, boolean.class, Byte.class, byte.class, Character.class, char.class, Short.class, short.class, Integer.class, int.class, Float.class, float.class, Long.class, long.class, Double.class, double.class, Arrays.class, List.class, ArrayList.class, BigDecimal.class, BigInteger.class, JDADelegate.class, UserDelegate.class, GuildDelegate.class }; public boolean containsMentions(String string) { return MENTION_FILTER.matcher(string).find(); } }
package net.mcft.copy.betterstorage.container; import java.lang.reflect.Field; import net.mcft.copy.betterstorage.inventory.InventoryCraftingStation; import net.mcft.copy.betterstorage.inventory.InventoryTileEntity; import net.mcft.copy.betterstorage.item.recipe.VanillaStationCrafting; import net.mcft.copy.betterstorage.utils.ReflectionUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.inventory.Slot; import net.minecraft.inventory.SlotCrafting; import net.minecraft.item.ItemStack; import net.minecraftforge.common.MinecraftForge; import cpw.mods.fml.common.eventhandler.EventBus; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ContainerCraftingStation extends ContainerBetterStorage { public InventoryCraftingStation inv; private InventoryCrafting craftMatrix; private CustomSlotCrafting slotCrafting; private int lastOutputIsReal = 0; private int lastProgress = 0; public ContainerCraftingStation(EntityPlayer player, IInventory inventory) { super(player, inventory, 9, 2); } @Override public int getHeight() { return 209; } @Override protected void setupInventoryContainer() { inv = ((inventory instanceof InventoryCraftingStation) ? (InventoryCraftingStation)inventory : ((InventoryCraftingStation)((InventoryTileEntity)inventory).inventory)); craftMatrix = new InventoryCrafting(this, 3, 3); ReflectionUtils.set(InventoryCrafting.class, craftMatrix, inv.crafting, "stackList"); slotCrafting = new CustomSlotCrafting(player, null, null, 0, 0, 0); // Crafting for (int y = 0; y < 3; y++) for (int x = 0; x < 3; x++) addSlotToContainer(new SlotBetterStorage( this, inventory, x + y * 3, 17 + x * 18, 17 + y * 18)); // Output for (int y = 0; y < 3; y++) for (int x = 0; x < 3; x++) addSlotToContainer(new SlotStationOutput( this, inventory, 9 + x + y * 3, 107 + x * 18, 17 + y * 18)); // Inventory for (int y = 0; y < getRows(); y++) for (int x = 0; x < getColumns(); x++) addSlotToContainer(new SlotBetterStorage( this, inventory, 18 + x + y * getColumns(), 8 + x * 18, 76 + y * 18)); } @Override protected boolean inInventory(int slot) { return (super.inInventory(slot) && (slot >= 9)); } @Override protected int transferStart(int slot) { return (!inInventory(slot) ? 18 : super.transferStart(slot)); } @Override public void detectAndSendChanges() { super.detectAndSendChanges(); int outputIsReal = (inv.outputIsReal ? 1 : 0); sendUpdateIfChanged(0, outputIsReal, lastOutputIsReal); lastOutputIsReal = outputIsReal; int progress = ((inv.currentCrafting != null) ? Math.min(inv.progress, inv.currentCrafting.getCraftingTime()) : 0); sendUpdateIfChanged(1, progress, lastProgress); lastProgress = progress; } @Override @SideOnly(Side.CLIENT) public void updateProgressBar(int id, int val) { if (id == 0) inv.outputIsReal = (val != 0); else if (id == 1) inv.progress = val; } @Override public ItemStack slotClick(int slotId, int button, int special, EntityPlayer player) { if (!inv.outputIsReal && (inv.currentCrafting != null) && (slotId >= 9) && (slotId < 18) && (inv.output[slotId - 9] != null) && inv.canTake(player)) { // For full compatibility with vanilla, we do special stuff here. if (inv.currentCrafting instanceof VanillaStationCrafting) { MinecraftForge.EVENT_BUS.post(new PlayerEvent.ItemCraftedEvent(player, inv.output[slotId - 9], craftMatrix)); slotCrafting.onCrafting(inv.output[slotId - 9]); } inv.craft(player); } return super.slotClick(slotId, button, special, player); } @Override public void onSlotChanged(int slot) { if (slot < 9) inv.inputChanged(); } @Override public boolean func_94530_a(ItemStack stack, Slot slot) { // This controls if double-clicking has an effect on the slot. return (super.func_94530_a(stack, slot) && ((slot.slotNumber < 9) || (slot.slotNumber >= 18))); } }
package org.oucs.gaboto.model.query.defined; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import org.oucs.gaboto.entities.pool.GabotoEntityPool; import org.oucs.gaboto.exceptions.CorruptDataException; import org.oucs.gaboto.exceptions.GabotoException; import org.oucs.gaboto.exceptions.GabotoRuntimeException; import org.oucs.gaboto.exceptions.NoTimeIndexSetException; import org.oucs.gaboto.model.Gaboto; import org.oucs.gaboto.model.GabotoSnapshot; import org.oucs.gaboto.model.query.GabotoQueryImpl; import org.oucs.gaboto.timedim.TimeInstant; /** * Query that allows to execute a SPARQL Construct query. * * @author Arno Mittelbach * @version 0.1 */ public class SimpleConstructSPARQLQuery extends GabotoQueryImpl { private TimeInstant timeInstant; private String query; public SimpleConstructSPARQLQuery(TimeInstant ti, File query) throws GabotoException { super(); this.timeInstant = ti; readFile(query); } public SimpleConstructSPARQLQuery(TimeInstant ti, String query) throws GabotoException { super(); this.timeInstant = ti; this.query = query; } public SimpleConstructSPARQLQuery(Gaboto gaboto, TimeInstant ti, File query) { super(gaboto); this.timeInstant = ti; readFile(query); } public SimpleConstructSPARQLQuery(Gaboto gaboto, TimeInstant ti, String query) { super(gaboto); this.timeInstant = ti; this.query = query; } private void readFile(File queryFile) { if (!queryFile.exists()) throw new IllegalArgumentException(queryFile.getAbsolutePath() + " does not exist"); StringBuilder contents = new StringBuilder(); try { BufferedReader input = new BufferedReader(new FileReader(queryFile)); try { String line = null; while ((line = input.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } } catch (IOException e) { throw new GabotoRuntimeException(e); } finally { input.close(); } } catch (IOException e) { throw new GabotoRuntimeException(e); } this.query = contents.toString(); } @Override public int getResultType() { return GabotoQueryImpl.RESULT_TYPE_ENTITY_POOL; } @Override protected Object execute() throws NoTimeIndexSetException, CorruptDataException { GabotoSnapshot snapshot = getGaboto().getSnapshot(timeInstant); GabotoSnapshot intermediateSnap = snapshot.execSPARQLConstruct(query); // create resultPool from model GabotoEntityPool resultPool = intermediateSnap.buildEntityPool(); // set snapshot resultPool.setSnapshot(snapshot); return resultPool; } @Override protected void doPrepare() throws GabotoException { // TODO Auto-generated method stub } }
package org.pcap4j.packet; import static org.pcap4j.util.ByteArrays.*; import java.net.Inet6Address; import java.util.Arrays; import org.pcap4j.packet.IcmpV6CommonPacket.IpV6NeighborDiscoveryOption; import org.pcap4j.packet.namednumber.IpV6NeighborDiscoveryOptionType; import org.pcap4j.util.ByteArrays; /** * @author Kaito Yamada * @since pcap4j 0.9.15 */ public final class IpV6NeighborDiscoveryPrefixInformationOption implements IpV6NeighborDiscoveryOption { /* * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Type | Length | Prefix Length |L|A| Reserved1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Valid Lifetime | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Preferred Lifetime | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Reserved2 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | * + + * | | * + Prefix + * | | * + + * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * Type=3 */ private static final long serialVersionUID = -1397830548673996516L; private static final int TYPE_OFFSET = 0; private static final int TYPE_SIZE = BYTE_SIZE_IN_BYTES; private static final int LENGTH_OFFSET = TYPE_OFFSET + TYPE_SIZE; private static final int LENGTH_SIZE = BYTE_SIZE_IN_BYTES; private static final int PREFIX_LENGTH_OFFSET = LENGTH_OFFSET + LENGTH_SIZE; private static final int PREFIX_LENGTH_SIZE = BYTE_SIZE_IN_BYTES; private static final int L_A_RESERVED1_OFFSET = PREFIX_LENGTH_OFFSET + PREFIX_LENGTH_SIZE; private static final int L_A_RESERVED1_SIZE = BYTE_SIZE_IN_BYTES; private static final int VALID_LIFETIME_OFFSET = L_A_RESERVED1_OFFSET + L_A_RESERVED1_SIZE; private static final int VALID_LIFETIME_SIZE = INT_SIZE_IN_BYTES; private static final int PREFERRED_LIFETIME_OFFSET = VALID_LIFETIME_OFFSET + VALID_LIFETIME_SIZE; private static final int PREFERRED_LIFETIME_SIZE = INT_SIZE_IN_BYTES; private static final int RESERVED2_OFFSET = PREFERRED_LIFETIME_OFFSET + PREFERRED_LIFETIME_SIZE; private static final int RESERVED2_SIZE = INT_SIZE_IN_BYTES; private static final int PREFIX_OFFSET = RESERVED2_OFFSET + RESERVED2_SIZE; private static final int PREFIX_SIZE = INET6_ADDRESS_SIZE_IN_BYTES; private static final int IPV6_NEIGHBOR_DISCOVERY_PREFIX_INFORMATION_OPTION_SIZE = PREFIX_OFFSET + PREFIX_SIZE; private final IpV6NeighborDiscoveryOptionType type = IpV6NeighborDiscoveryOptionType.PREFIX_INFORMATION; private final byte length; private final byte prefixLength; private final boolean onLinkFlag; // L field private final boolean addressConfigurationFlag; // A field private final byte reserved1; private final int validLifetime; private final int preferredLifetime; private final int reserved2; private final Inet6Address prefix; /** * * @param rawData * @return a new IpV6NeighborDiscoveryPrefixInformationOption object. */ public static IpV6NeighborDiscoveryPrefixInformationOption newInstance( byte[] rawData ) { return new IpV6NeighborDiscoveryPrefixInformationOption(rawData); } private IpV6NeighborDiscoveryPrefixInformationOption(byte[] rawData) { if (rawData == null) { throw new NullPointerException("rawData may not be null"); } if (rawData.length < IPV6_NEIGHBOR_DISCOVERY_PREFIX_INFORMATION_OPTION_SIZE) { StringBuilder sb = new StringBuilder(50); sb.append("The raw data length must be more than 31. rawData: ") .append(ByteArrays.toHexString(rawData, " ")); throw new IllegalRawDataException(sb.toString()); } if (rawData[TYPE_OFFSET] != getType().value()) { StringBuilder sb = new StringBuilder(100); sb.append("The type must be: ") .append(getType().valueAsString()) .append(" rawData: ") .append(ByteArrays.toHexString(rawData, " ")); throw new IllegalRawDataException(sb.toString()); } if ( rawData[LENGTH_OFFSET] != IPV6_NEIGHBOR_DISCOVERY_PREFIX_INFORMATION_OPTION_SIZE / 8 ) { throw new IllegalRawDataException( "Invalid value of length field: " + rawData[LENGTH_OFFSET] ); } this.length = rawData[LENGTH_OFFSET]; if (rawData.length < length * 8) { StringBuilder sb = new StringBuilder(100); sb.append("The raw data is too short to build this option. ") .append(length * 8) .append(" bytes data is needed. data: ") .append(ByteArrays.toHexString(rawData, " ")); throw new IllegalRawDataException(sb.toString()); } this.prefixLength = ByteArrays.getByte(rawData, PREFIX_LENGTH_OFFSET); byte tmp = ByteArrays.getByte(rawData, L_A_RESERVED1_OFFSET); this.onLinkFlag = (tmp & 0x80) != 0; this.addressConfigurationFlag = (tmp & 0x40) != 0; this.reserved1 = (byte)(0x3F & tmp); this.validLifetime = ByteArrays.getInt(rawData, VALID_LIFETIME_OFFSET); this.preferredLifetime = ByteArrays.getInt(rawData, PREFERRED_LIFETIME_OFFSET); this.reserved2 = ByteArrays.getInt(rawData, RESERVED2_OFFSET); this.prefix = ByteArrays.getInet6Address(rawData, PREFIX_OFFSET); } private IpV6NeighborDiscoveryPrefixInformationOption(Builder builder) { if ( builder == null || builder.prefix == null ) { StringBuilder sb = new StringBuilder(); sb.append("builder: ").append(builder) .append(" builder.prefix: ").append(builder.prefix); throw new NullPointerException(sb.toString()); } if ((builder.reserved1 & 0xC0) != 0) { throw new IllegalArgumentException( "Invalid reserved1: " + builder.reserved1 ); } this.prefixLength = builder.prefixLength; this.onLinkFlag = builder.onLinkFlag; this.addressConfigurationFlag = builder.addressConfigurationFlag; this.reserved1 = builder.reserved1; this.validLifetime = builder.validLifetime; this.preferredLifetime = builder.preferredLifetime; this.reserved2 = builder.reserved2; this.prefix = builder.prefix; if (builder.correctLengthAtBuild) { this.length = (byte)(length() / 8); } else { this.length = builder.length; } } public IpV6NeighborDiscoveryOptionType getType() { return type; } /** * * @return length */ public byte getLength() { return length; } /** * * @return length */ public int getLengthAsInt() { return 0xFF & length; } /** * * @return prefixLength */ public byte getPrefixLength() { return prefixLength; } /** * * @return prefixLength */ public int getPrefixLengthAsInt() { return 0xFF & prefixLength; } /** * * @return onLinkFlag */ public boolean getOnLinkFlag() { return onLinkFlag; } /** * * @return addressConfigurationFlag */ public boolean getAddressConfigurationFlag() { return addressConfigurationFlag; } /** * * @return reserved1 */ public byte getReserved1() { return reserved1; } /** * * @return validLifetime */ public int getValidLifetime() { return validLifetime; } /** * @return validLifetime */ public long getValidLifetimeAsLong() { return validLifetime & 0xFFFFFFFFL; } /** * * @return preferredLifetime */ public int getPreferredLifetime() { return preferredLifetime; } /** * * @return preferredLifetime */ public long getPreferredLifetimeAsLong() { return preferredLifetime & 0xFFFFFFFFL; } /** * * @return reserved2 */ public int getReserved2() { return reserved2; } /** * * @return prefix */ public Inet6Address getPrefix() { return prefix; } public int length() { return IPV6_NEIGHBOR_DISCOVERY_PREFIX_INFORMATION_OPTION_SIZE; } public byte[] getRawData() { byte[] rawData = new byte[length()]; rawData[TYPE_OFFSET] = getType().value(); rawData[LENGTH_OFFSET] = length; rawData[PREFIX_LENGTH_OFFSET] = prefixLength; rawData[L_A_RESERVED1_OFFSET] = (byte)(0x3F & reserved1); if (onLinkFlag) { rawData[L_A_RESERVED1_OFFSET] |= 1 << 7; } if (addressConfigurationFlag) { rawData[L_A_RESERVED1_OFFSET] |= 1 << 6; } System.arraycopy( ByteArrays.toByteArray(validLifetime), 0, rawData, VALID_LIFETIME_OFFSET, VALID_LIFETIME_SIZE ); System.arraycopy( ByteArrays.toByteArray(preferredLifetime), 0, rawData, PREFERRED_LIFETIME_OFFSET, PREFERRED_LIFETIME_SIZE ); System.arraycopy( ByteArrays.toByteArray(reserved2), 0, rawData, RESERVED2_OFFSET, RESERVED2_SIZE ); System.arraycopy( ByteArrays.toByteArray(prefix), 0, rawData, PREFIX_OFFSET, PREFIX_SIZE ); return rawData; } /** * * @return a new Builder object populated with this object's fields. */ public Builder getBuilder() { return new Builder(this); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[Type: ") .append(getType()); sb.append("] [Length: ") .append(getLengthAsInt()) .append(" (").append(getLengthAsInt() * 8); sb.append(" bytes)] [Prefix Length: ") .append(getPrefixLengthAsInt()); sb.append("] [on-link flag: ") .append(getOnLinkFlag()); sb.append("] [address-configuration flag: ") .append(getAddressConfigurationFlag()); sb.append("] [Reserved1: ") .append(getReserved1()); sb.append("] [Valid Lifetime: ") .append(getValidLifetimeAsLong()); sb.append("] [Preferred Lifetime: ") .append(getPreferredLifetimeAsLong()); sb.append("] [Reserved2: ") .append(getReserved2()); sb.append("] [Prefix: ") .append(getPrefix()); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!this.getClass().isInstance(obj)) { return false; } return Arrays.equals((getClass().cast(obj)).getRawData(), getRawData()); } @Override public int hashCode() { return Arrays.hashCode(getRawData()); } /** * @author Kaito Yamada * @since pcap4j 0.9.15 */ public static final class Builder implements LengthBuilder<IpV6NeighborDiscoveryPrefixInformationOption> { private byte length; private byte prefixLength; private boolean onLinkFlag; // L field private boolean addressConfigurationFlag; // A field private byte reserved1; private int validLifetime; private int preferredLifetime; private int reserved2; private Inet6Address prefix; private boolean correctLengthAtBuild; public Builder() {} private Builder(IpV6NeighborDiscoveryPrefixInformationOption option) { this.length = option.length; this.prefixLength = option.prefixLength; this.onLinkFlag = option.onLinkFlag; this.addressConfigurationFlag = option.addressConfigurationFlag; this.reserved1 = option.reserved1; this.validLifetime = option.validLifetime; this.preferredLifetime = option.preferredLifetime; this.reserved2 = option.reserved2; this.prefix = option.prefix; } /** * * @param length * @return this Builder object for method chaining. */ public Builder length(byte length) { this.length = length; return this; } /** * * @param prefixLength * @return this Builder object for method chaining. */ public Builder prefixLength(byte prefixLength) { this.prefixLength = prefixLength; return this; } /** * * @param onLinkFlag * @return this Builder object for method chaining. */ public Builder onLinkFlag(boolean onLinkFlag) { this.onLinkFlag = onLinkFlag; return this; } /** * * @param addressConfigurationFlag * @return this Builder object for method chaining. */ public Builder addressConfigurationFlag(boolean addressConfigurationFlag) { this.addressConfigurationFlag = addressConfigurationFlag; return this; } /** * * @param reserved1 * @return this Builder object for method chaining. */ public Builder reserved1(byte reserved1) { this.reserved1 = reserved1; return this; } /** * * @param validLifetime * @return this Builder object for method chaining. */ public Builder validLifetime(int validLifetime) { this.validLifetime = validLifetime; return this; } /** * * @param preferredLifetime * @return this Builder object for method chaining. */ public Builder preferredLifetime(int preferredLifetime) { this.preferredLifetime = preferredLifetime; return this; } /** * * @param reserved2 * @return this Builder object for method chaining. */ public Builder reserved2(int reserved2) { this.reserved2 = reserved2; return this; } /** * * @param prefix * @return this Builder object for method chaining. */ public Builder prefix(Inet6Address prefix) { this.prefix = prefix; return this; } public Builder correctLengthAtBuild(boolean correctLengthAtBuild) { this.correctLengthAtBuild = correctLengthAtBuild; return this; } public IpV6NeighborDiscoveryPrefixInformationOption build() { return new IpV6NeighborDiscoveryPrefixInformationOption(this); } } }
package org.spongepowered.mod.mixin.core.common; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent; import org.spongepowered.api.Game; import org.spongepowered.api.entity.Transform; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.entity.living.player.RespawnPlayerEvent; import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.event.world.LoadWorldEvent; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.sink.MessageSink; import org.spongepowered.api.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.common.SpongeImplFactory; import org.spongepowered.common.entity.PlayerTracker; import org.spongepowered.common.interfaces.IMixinChunk; import org.spongepowered.common.util.StaticMixinHelper; import org.spongepowered.mod.interfaces.IMixinPlayerRespawnEvent; import java.util.Optional; @Mixin(value = SpongeImplFactory.class, remap = false) public abstract class MixinSpongeImplFactory { @Overwrite public static LoadWorldEvent createLoadWorldEvent(Game game, World world) { return (LoadWorldEvent) new WorldEvent.Load((net.minecraft.world.World) world); } @Overwrite public static ClientConnectionEvent.Join createClientConnectionEventJoin(Game game, Cause cause, Text originalMessage, Text message, MessageSink originalSink, MessageSink sink, Player targetEntity) { final ClientConnectionEvent.Join event = (ClientConnectionEvent.Join) new PlayerEvent.PlayerLoggedInEvent((EntityPlayer) targetEntity); event.setSink(sink); event.setMessage(message); return event; } @Overwrite public static RespawnPlayerEvent createRespawnPlayerEvent(Game game, Cause cause, Transform<World> fromTransform, Transform<World> toTransform, Player targetEntity, boolean bedSpawn) { final RespawnPlayerEvent event = (RespawnPlayerEvent) new PlayerEvent.PlayerRespawnEvent((EntityPlayer) targetEntity); ((IMixinPlayerRespawnEvent) event).setIsBedSpawn(bedSpawn); event.setToTransform(toTransform); return event; } @Overwrite public static ClientConnectionEvent.Disconnect createClientConnectionEventDisconnect(Game game, Cause cause, Text originalMessage, Text message, MessageSink originalSink, MessageSink sink, Player targetEntity) { final ClientConnectionEvent.Disconnect event = (ClientConnectionEvent.Disconnect) new PlayerEvent.PlayerLoggedOutEvent((EntityPlayer) targetEntity); event.setMessage(message); event.setSink(sink); return event; } @Overwrite public static boolean blockHasTileEntity(Block block, IBlockState state) { return block.hasTileEntity(state); } @Overwrite public static int getBlockLightValue(Block block, BlockPos pos, IBlockAccess world) { return block.getLightValue(world, pos); } @Overwrite public static int getBlockLightOpacity(Block block, IBlockAccess world, BlockPos pos) { return block.getLightOpacity(world, pos); } @Overwrite public static boolean shouldRefresh(TileEntity tile, net.minecraft.world.World world, BlockPos pos, IBlockState oldState, IBlockState newState) { return tile.shouldRefresh(world, pos, oldState, newState); } @Overwrite public static TileEntity createTileEntity(Block block, net.minecraft.world.World world, IBlockState state) { return block.createTileEntity(world, state); } // Required for torches and comparators @Overwrite public static void updateComparatorOutputLevel(net.minecraft.world.World world, BlockPos pos, Block blockIn) { Optional<User> user = Optional.empty(); IMixinChunk spongeChunk = null; if (StaticMixinHelper.packetPlayer != null || StaticMixinHelper.blockEventUser != null) { user = Optional .of(StaticMixinHelper.packetPlayer != null ? (User) StaticMixinHelper.packetPlayer : (User) StaticMixinHelper.blockEventUser); } else { spongeChunk = (IMixinChunk) world.getChunkFromBlockCoords(pos); user = Optional.empty(); if (spongeChunk != null) { user = spongeChunk.getBlockNotifier(pos); } } for (EnumFacing enumfacing : EnumFacing.values()) { BlockPos blockpos1 = pos.offset(enumfacing); if (world.isBlockLoaded(blockpos1)) { IBlockState iblockstate = world.getBlockState(blockpos1); iblockstate.getBlock().onNeighborChange(world, blockpos1, pos); if (user.isPresent()) { spongeChunk = (IMixinChunk) world.getChunkFromBlockCoords(blockpos1); if (spongeChunk != null) { spongeChunk.addTrackedBlockPosition(iblockstate.getBlock(), blockpos1, user.get(), PlayerTracker.Type.NOTIFIER); } } if (iblockstate.getBlock().isNormalCube(world, blockpos1)) { BlockPos posOther = blockpos1.offset(enumfacing); Block other = world.getBlockState(posOther).getBlock(); if (other.getWeakChanges(world, posOther)) { other.onNeighborChange(world, posOther, pos); if (user.isPresent()) { spongeChunk = (IMixinChunk) world.getChunkFromBlockCoords(posOther); if (spongeChunk != null) { spongeChunk.addTrackedBlockPosition(other, posOther, user.get(), PlayerTracker.Type.NOTIFIER); } } } } } } } }
package org.javarosa.core.model.instance; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Vector; import org.javarosa.core.model.IDataReference; import org.javarosa.core.services.storage.Persistable; import org.javarosa.core.util.CacheTable; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.ExtUtil; import org.javarosa.core.util.externalizable.ExtWrapNullable; import org.javarosa.core.util.externalizable.PrototypeFactory; /** * A data instance represents a tree structure of abstract tree * elements which can be accessed and read with tree references. It is * a supertype of different types of concrete models which may or may not * be read only. * * @author ctsims * */ public abstract class DataInstance<T extends AbstractTreeElement<T>> implements Persistable { /** The integer Id of the model */ private int recordid = -1; /** The name for this data model */ protected String name; /** The ID of the form that this is a model for */ protected int formId; protected String instanceid; private CacheTable<TreeReference, T> referenceCache; public DataInstance() { referenceCache = new CacheTable<TreeReference, T>(); } public DataInstance(String instanceid) { this.instanceid = instanceid; referenceCache = new CacheTable<TreeReference, T>(); } public static TreeReference unpackReference(IDataReference ref) { return (TreeReference) ref.getReference(); } public abstract AbstractTreeElement<T> getBase(); public abstract T getRoot(); public String getInstanceId() { return instanceid; } /** * Whether the structure of this instance is only available at runtime. * * @return true if the instance structure is available and runtime and can't * be checked for consistency until the reference is made available. False * otherwise. * */ public boolean isRuntimeEvaluated() { return false; } public T resolveReference(TreeReference ref) { T t = referenceCache.retrieve(ref); if(t != null) { return t; } if (!ref.isAbsolute()){ return null; } AbstractTreeElement<T> node = getBase(); T result = null; for (int i = 0; i < ref.size(); i++) { String name = ref.getName(i); int mult = ref.getMultiplicity(i); if(mult == TreeReference.INDEX_ATTRIBUTE) { //Should we possibly just return here? //I guess technically we could step back... node = result = node.getAttribute(null, name); continue; } if (mult == TreeReference.INDEX_UNBOUND) { if (node.getChildMultiplicity(name) == 1) { mult = 0; } else { // reference is not unambiguous node = result = null; break; } } node = result = node.getChild(name, mult); if (node == null) { break; } } t = (node == getBase() ? null : result); // never return a reference to '/' referenceCache.register(ref, t); return t; } public Vector explodeReference(TreeReference ref) { if (!ref.isAbsolute()) return null; Vector nodes = new Vector(); AbstractTreeElement<T> cur = getBase(); for (int i = 0; i < ref.size(); i++) { String name = ref.getName(i); int mult = ref.getMultiplicity(i); //If the next node down the line is an attribute if(mult == TreeReference.INDEX_ATTRIBUTE) { //This is not the attribute we're testing if(cur != getBase()) { //Add the current node nodes.addElement(cur); } cur = cur.getAttribute(null, name); } //Otherwise, it's another child element else { if (mult == TreeReference.INDEX_UNBOUND) { if (cur.getChildMultiplicity(name) == 1) { mult = 0; } else { // reference is not unambiguous return null; } } if (cur != getBase()) { nodes.addElement(cur); } cur = cur.getChild(name, mult); if (cur == null) { return null; } } } return nodes; } public T getTemplate(TreeReference ref) { T node = getTemplatePath(ref); return (node == null ? null : ((node.isRepeatable() || node.isAttribute()) ? node : null)); } public T getTemplatePath(TreeReference ref) { if (!ref.isAbsolute()) { return null; } T walker = null; AbstractTreeElement<T> node = getBase(); for (int i = 0; i < ref.size(); i++) { String name = ref.getName(i); if(ref.getMultiplicity(i) == TreeReference.INDEX_ATTRIBUTE) { node = walker = node.getAttribute(null, name); } else { T newNode = node.getChild(name, TreeReference.INDEX_TEMPLATE); if (newNode == null) { newNode = node.getChild(name, 0); } if (newNode == null) { return null; } node = walker = newNode; } } return walker; } public T resolveReference(IDataReference binding) { return resolveReference(unpackReference(binding)); } public void setFormId(int formId) { this.formId = formId; } public int getFormId() { return this.formId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { String name = "NULL"; if(this.name != null) { name = this.name; } return name; } public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { recordid = ExtUtil.readInt(in); formId = ExtUtil.readInt(in); name = (String) ExtUtil.read(in, new ExtWrapNullable(String.class), pf); instanceid = (String) ExtUtil.nullIfEmpty(ExtUtil.readString(in)); } public void writeExternal(DataOutputStream out) throws IOException { ExtUtil.writeNumeric(out, recordid); ExtUtil.writeNumeric(out, formId); ExtUtil.write(out, new ExtWrapNullable(name)); ExtUtil.write(out, ExtUtil.emptyIfNull(instanceid)); } public int getID() { return recordid; } public void setID(int recordid) { this.recordid = recordid; } public abstract void initialize(InstanceInitializationFactory initializer, String instanceId); }
package org.javarosa.core.model.instance; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Vector; import org.javarosa.core.model.IDataReference; import org.javarosa.core.services.storage.Persistable; import org.javarosa.core.util.CacheTable; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.ExtUtil; import org.javarosa.core.util.externalizable.ExtWrapNullable; import org.javarosa.core.util.externalizable.PrototypeFactory; /** * A data instance represents a tree structure of abstract tree * elements which can be accessed and read with tree references. It is * a supertype of different types of concrete models which may or may not * be read only. * * @author ctsims * */ public abstract class DataInstance<T extends AbstractTreeElement<T>> implements Persistable { /** The integer Id of the model */ private int recordid = -1; /** The name for this data model */ protected String name; /** The ID of the form that this is a model for */ protected int formId; protected String instanceid; private CacheTable<TreeReference, T> referenceCache; public DataInstance() { referenceCache = new CacheTable<TreeReference, T>(); } public DataInstance(String instanceid) { this.instanceid = instanceid; referenceCache = new CacheTable<TreeReference, T>(); } public static TreeReference unpackReference(IDataReference ref) { return (TreeReference) ref.getReference(); } public abstract AbstractTreeElement<T> getBase(); public abstract T getRoot(); public String getInstanceId() { return instanceid; } /** * Whether the structure of this instance is only available at runtime. * * @return true if the instance structure is available and runtime and can't * be checked for consistency until the reference is made available. False * otherwise. * */ public boolean isRuntimeEvaluated() { return false; } public T resolveReference(TreeReference ref) { if (!ref.isAbsolute()){ return null; } T t = referenceCache.retrieve(ref); if(t != null && (t.getValue() != null)){ return t; } AbstractTreeElement<T> node = getBase(); T result = null; for (int i = 0; i < ref.size(); i++) { String name = ref.getName(i); int mult = ref.getMultiplicity(i); if(mult == TreeReference.INDEX_ATTRIBUTE) { //Should we possibly just return here? //I guess technically we could step back... node = result = node.getAttribute(null, name); continue; } if (mult == TreeReference.INDEX_UNBOUND) { if (node.getChildMultiplicity(name) == 1) { mult = 0; } else { // reference is not unambiguous node = result = null; break; } } node = result = node.getChild(name, mult); if (node == null) { break; } } t = (node == getBase() ? null : result); // never return a reference to '/' referenceCache.register(ref, t); return t; } public Vector explodeReference(TreeReference ref) { if (!ref.isAbsolute()) return null; Vector nodes = new Vector(); AbstractTreeElement<T> cur = getBase(); for (int i = 0; i < ref.size(); i++) { String name = ref.getName(i); int mult = ref.getMultiplicity(i); //If the next node down the line is an attribute if(mult == TreeReference.INDEX_ATTRIBUTE) { //This is not the attribute we're testing if(cur != getBase()) { //Add the current node nodes.addElement(cur); } cur = cur.getAttribute(null, name); } //Otherwise, it's another child element else { if (mult == TreeReference.INDEX_UNBOUND) { if (cur.getChildMultiplicity(name) == 1) { mult = 0; } else { // reference is not unambiguous return null; } } if (cur != getBase()) { nodes.addElement(cur); } cur = cur.getChild(name, mult); if (cur == null) { return null; } } } return nodes; } public T getTemplate(TreeReference ref) { T node = getTemplatePath(ref); return (node == null ? null : ((node.isRepeatable() || node.isAttribute()) ? node : null)); } public T getTemplatePath(TreeReference ref) { if (!ref.isAbsolute()) { return null; } T walker = null; AbstractTreeElement<T> node = getBase(); for (int i = 0; i < ref.size(); i++) { String name = ref.getName(i); if(ref.getMultiplicity(i) == TreeReference.INDEX_ATTRIBUTE) { node = walker = node.getAttribute(null, name); } else { T newNode = node.getChild(name, TreeReference.INDEX_TEMPLATE); if (newNode == null) { newNode = node.getChild(name, 0); } if (newNode == null) { return null; } node = walker = newNode; } } return walker; } public T resolveReference(IDataReference binding) { return resolveReference(unpackReference(binding)); } public void setFormId(int formId) { this.formId = formId; } public int getFormId() { return this.formId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { String name = "NULL"; if(this.name != null) { name = this.name; } return name; } public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { recordid = ExtUtil.readInt(in); formId = ExtUtil.readInt(in); name = (String) ExtUtil.read(in, new ExtWrapNullable(String.class), pf); instanceid = (String) ExtUtil.nullIfEmpty(ExtUtil.readString(in)); } public void writeExternal(DataOutputStream out) throws IOException { ExtUtil.writeNumeric(out, recordid); ExtUtil.writeNumeric(out, formId); ExtUtil.write(out, new ExtWrapNullable(name)); ExtUtil.write(out, ExtUtil.emptyIfNull(instanceid)); } public int getID() { return recordid; } public void setID(int recordid) { this.recordid = recordid; } public abstract void initialize(InstanceInitializationFactory initializer, String instanceId); }
package org.jpos.simulator; import java.io.File; import java.io.IOException; import java.io.FileInputStream; import java.util.Map; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import org.jpos.iso.ISOMsg; import org.jpos.iso.ISOComponent; import org.jpos.iso.ISOUtil; import org.jpos.iso.ISODate; import org.jpos.iso.ISOField; import org.jpos.iso.ISOHeader; import org.jpos.iso.ISOPackager; import org.jpos.iso.ISOException; import org.jpos.iso.packager.XMLPackager; import org.jpos.q2.QBeanSupport; import org.jpos.util.Logger; import org.jpos.util.LogEvent; import org.jdom.Element; import org.jpos.iso.MUX; import org.jpos.util.NameRegistrar; import bsh.Interpreter; import bsh.BshClassManager; import bsh.EvalError; import bsh.UtilEvalError; public class TestRunner extends org.jpos.q2.QBeanSupport implements Runnable { MUX mux; ISOPackager packager; Interpreter bsh; public static final long TIMEOUT = 60000; public TestRunner () { super(); } protected void initService() throws ISOException { packager = new XMLPackager(); } protected void startService() { new Thread(this).start(); } public void run () { try { Interpreter bsh = initBSH (); mux = (MUX) NameRegistrar.get ("mux." + cfg.get ("mux")); List suite = initSuite (getPersist().getChild ("test-suite")); runSuite (suite, mux, bsh); } catch (NameRegistrar.NotFoundException e) { LogEvent evt = getLog().createError (); evt.addMessage (e); evt.addMessage (NameRegistrar.getInstance()); Logger.log (evt); } catch (Throwable t) { getLog().error (t); } if (cfg.getBoolean ("shutdown")) shutdownQ2(); } private void runSuite (List suite, MUX mux, Interpreter bsh) throws ISOException, EvalError { LogEvent evt = getLog().createLogEvent ("results"); Iterator iter = suite.iterator(); long start = System.currentTimeMillis(); long serverTime = 0; for (int i=1; iter.hasNext(); i++) { TestCase tc = (TestCase) iter.next(); getLog().trace ( " + tc.getName() + " ] ISOMsg m = (ISOMsg) tc.getRequest().clone(); if (tc.getPreEvaluationScript() != null) { bsh.set ("testcase", tc); bsh.set ("request", m); bsh.eval (tc.getPreEvaluationScript()); } tc.setExpandedRequest (applyRequestProps (m, bsh)); tc.start(); tc.setResponse (mux.request (m, tc.getTimeout())); tc.end (); assertResponse (tc, bsh); evt.addMessage (i + ": " + tc.toString()); serverTime += tc.elapsed(); if (!tc.ok()) { getLog().error (tc); if (!tc.isContinueOnErrors()) break; } } long end = System.currentTimeMillis(); long simulatorTime = end - start - serverTime; long total = end - start; evt.addMessage ( "elapsed server=" + serverTime + "ms(" + percentage (serverTime, total) + "%)" + ", simulator=" + simulatorTime + "ms(" + percentage (simulatorTime, total) + "%)" + ", total=" + total + "ms, shutdown=" + cfg.getBoolean("shutdown") ); ISOUtil.sleep (100); // let the channel do its logging first if (cfg.getBoolean ("shutdown")) evt.addMessage ("Shutting down"); Logger.log (evt); } private List initSuite (Element suite) throws IOException, ISOException { List l = new ArrayList(); String prefix = suite.getChildTextTrim ("path"); Iterator iter = suite.getChildren ("test").iterator(); while (iter.hasNext ()) { Element e = (Element) iter.next (); boolean cont = "yes".equals (e.getAttributeValue ("continue")); String s = e.getAttributeValue ("count"); int count = s != null ? Integer.parseInt (s) : 1; String path = e.getAttributeValue ("file"); String name = e.getAttributeValue ("name"); if (name == null) name = path; for (int i=0; i<count; i++) { TestCase tc = new TestCase (name); tc.setContinueOnErrors (cont); tc.setRequest (getMessage (prefix + path + "_s")); tc.setExpectedResponse (getMessage (prefix + path + "_r")); tc.setPreEvaluationScript (e.getChildTextTrim ("init")); tc.setPostEvaluationScript (e.getChildTextTrim ("post")); String to = e.getAttributeValue ("timeout"); if (to != null) tc.setTimeout (Long.parseLong (to)); else tc.setTimeout (cfg.getLong ("timeout", TIMEOUT)); l.add (tc); } } return l; } private ISOMsg getMessage (String filename) throws IOException, ISOException { File f = new File (filename); FileInputStream fis = new FileInputStream (f); try { byte[] b = new byte[fis.available()]; fis.read (b); ISOMsg m = new ISOMsg (); m.setPackager (packager); m.unpack (b); return m; } finally { fis.close(); } } private boolean processResponse (ISOMsg er, ISOMsg m, ISOMsg expected, Interpreter bsh) throws ISOException, EvalError { int maxField = Math.max(m.getMaxField(), expected.getMaxField()); for (int i=0; i<=maxField; i++) { if (expected.hasField (i)) { ISOComponent c = expected.getComponent (i); if (c instanceof ISOField) { String value = expected.getString (i); if (value.charAt (0) == '!' && value.length() > 1) { bsh.set ("value", m.getString (i)); Object ret = bsh.eval (value.substring (1)); if (ret instanceof Boolean) if (!((Boolean)ret).booleanValue()) return false; m.unset (i); expected.unset (i); } else if (value.startsWith("*M")) { if (m.hasField (i)) { expected.unset (i); m.unset (i); } else { return false; } } else if (value.startsWith("*E")) { if (m.hasField (i) && er.hasField (i)) { expected.set (i, er.getString (i)); } else { return false; } } } else if (c instanceof ISOMsg) { ISOMsg rc = (ISOMsg) m.getComponent (i); ISOMsg innerExpectedResponse = (ISOMsg) er.getComponent (i); if (rc instanceof ISOMsg) { processResponse (innerExpectedResponse, (ISOMsg) rc, (ISOMsg) c, bsh); } } } else { m.unset (i); } } return true; } private boolean assertResponse (TestCase tc, Interpreter bsh) throws ISOException, EvalError { if (tc.getResponse() == null) { tc.setResultCode (TestCase.TIMEOUT); return false; } ISOMsg c = (ISOMsg) tc.getResponse().clone(); ISOMsg expected = (ISOMsg) tc.getExpectedResponse().clone(); ISOMsg er = (ISOMsg) tc.getExpandedRequest().clone(); c.setHeader ((ISOHeader) null); if (!processResponse (er, c, expected, bsh)) { tc.setResultCode (TestCase.FAILURE); return false; } ISOPackager p = new XMLPackager(); expected.setPackager(p); c.setPackager(p); if (tc.getPostEvaluationScript() != null) { bsh.set ("testcase", tc); bsh.set ("response", tc.getResponse()); Object ret = bsh.eval (tc.getPostEvaluationScript()); if (ret instanceof Boolean) { if (!((Boolean)ret).booleanValue()){ tc.setResultCode (TestCase.FAILURE); return false; } } } if (!(new String(c.pack())).equals(new String(expected.pack()))) { tc.setResultCode (TestCase.FAILURE); return false; } tc.setResultCode (TestCase.OK); return true; } private void eval (Element e, String name, Interpreter bsh) throws EvalError { Element ee = e.getChild (name); if (ee != null) bsh.eval (ee.getText()); } private Interpreter initBSH () throws UtilEvalError, EvalError { Interpreter bsh = new Interpreter (); BshClassManager bcm = bsh.getClassManager(); bcm.setClassPath(getServer().getLoader().getURLs()); bcm.setClassLoader(getServer().getLoader()); bsh.set ("qbean", this); bsh.set ("log", getLog()); bsh.eval (getPersist().getChildTextTrim ("init")); return bsh; } private ISOMsg applyRequestProps (ISOMsg m, Interpreter bsh) throws ISOException, EvalError { int maxField = m.getMaxField(); for (int i=0; i<=maxField; i++) { if (m.hasField(i)) { ISOComponent c = m.getComponent (i); if (c instanceof ISOMsg) { applyRequestProps ((ISOMsg) c, bsh); } else if (c instanceof ISOField) { String value = (String) c.getValue(); if (value.length() > 0) { try { if (value.charAt (0) == '!') { m.set (i, bsh.eval (value.substring(1)).toString()); } else if (value.charAt (0) == ' m.set (i, ISOUtil.hex2byte(bsh.eval (value.substring(1)).toString())); } } catch (NullPointerException e) { m.unset (i); } } } } } return m; } private long percentage (long a, long b) { double d = (double) a / b; return (long) (d * 100.00); } }
package org.jcryptool.core; import java.util.Locale; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; /** * This class controls all aspects of the application's execution * * @author Dominik Schadow * @version 1.0.0 */ public class Application implements IApplication { /* * (non-Javadoc) * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext) */ public Object start(IApplicationContext context) throws Exception { try { if (Locale.getDefault() != Locale.GERMAN && Locale.getDefault() != Locale.ENGLISH) { System.setProperty("osgi.nl", "en"); // fixes Platform.getNL() Locale.setDefault(Locale.ENGLISH); } } catch (Exception e) { e.printStackTrace(); } Display display = PlatformUI.createDisplay(); try { int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor()); if (returnCode == PlatformUI.RETURN_RESTART) return IApplication.EXIT_RESTART; else return IApplication.EXIT_OK; } finally { display.dispose(); } } /* * (non-Javadoc) * @see org.eclipse.equinox.app.IApplication#stop() */ public void stop() { final IWorkbench workbench = PlatformUI.getWorkbench(); if (workbench == null) return; final Display display = workbench.getDisplay(); display.syncExec(new Runnable() { public void run() { if (!display.isDisposed()) workbench.close(); } }); } }
package cn.cerc.ui.panels; import javax.servlet.http.HttpServletRequest; import cn.cerc.core.Record; import cn.cerc.mis.core.IForm; import cn.cerc.ui.columns.IColumn; import cn.cerc.ui.columns.IDataColumn; import cn.cerc.ui.core.Component; import cn.cerc.ui.core.HtmlWriter; import cn.cerc.ui.core.UIOriginComponent; import cn.cerc.ui.parts.UIComponent; import cn.cerc.ui.vcl.UIButton; import cn.cerc.ui.vcl.UIButtonSubmit; import cn.cerc.ui.vcl.UIDiv; import cn.cerc.ui.vcl.UIForm; public class UIViewPanel extends UIOriginComponent { private UIForm uiform; private UIButton submit; private HttpServletRequest request; private UIComponent content; private Record record; private String title; private IForm form; public UIViewPanel(UIComponent owner) { super(owner); if (this.getOrigin() instanceof IForm) { form = (IForm) this.getOrigin(); this.request = form.getRequest(); } uiform = new UIForm(this); uiform.setCssClass("viewPanel"); this.content = new UIOriginComponent(uiform); submit = new UIButtonSubmit(uiform.getBottom()); submit.setText(""); this.title = ""; } @Override public void output(HtmlWriter html) { if (!form.getClient().isPhone()) { UIDiv div = new UIDiv(); div.setCssClass("panelTitle"); div.setText(this.getTitle()); div.output(html); } uiform.outHead(html); for (UIComponent component : content) { if (component instanceof IDataColumn) { IDataColumn column = (IDataColumn) component; if (column.isHidden()) { column.setRecord(record); column.outputLine(html); } } } html.print("<ul>"); for (UIComponent component : content) { if (component instanceof IColumn) { if (component instanceof IDataColumn) { IDataColumn column = (IDataColumn) component; if (!column.isHidden()) { column.setRecord(record); column.setReadonly(true); html.print("<li>"); column.outputLine(html); html.print("</li>"); } } else { IColumn column = (IColumn) component; html.print("<li>"); column.outputLine(html); html.print("</li>"); } } } html.print("</ul>"); uiform.outFoot(html); } public void setAction(String action) { uiform.setAction(action); } public String readAll() { return request.getParameter(submit.getName()); } public UIComponent getContent() { return content; } @Override public void addComponent(Component component) { if (component instanceof IColumn) { this.content.addComponent(component); } else { super.addComponent(component); } } public Record getRecord() { return record; } public UIViewPanel setRecord(Record record) { this.record = record; return this; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public UIForm getUiform() { return uiform; } public UIButton getSubmit() { return submit; } }
package org.hanuna.gitalk.swing_ui; import org.hanuna.gitalk.graph.graph_elements.GraphElement; import org.hanuna.gitalk.printmodel.GraphPrintCell; import org.hanuna.gitalk.swing_ui.render.GraphCommitCellRender; import org.hanuna.gitalk.swing_ui.render.painters.GraphCellPainter; import org.hanuna.gitalk.swing_ui.render.painters.SimpleGraphCellPainter; import org.hanuna.gitalk.ui_controller.EventsController; import org.hanuna.gitalk.ui_controller.UI_Controller; import org.hanuna.gitalk.ui_controller.table_models.GraphCommitCell; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * @author erokhins */ public class UI_GraphTable extends JTable { private final UI_Controller ui_controller; private final GraphCellPainter graphPainter = new SimpleGraphCellPainter(); private final MouseAdapter mouseAdapter = new MyMouseAdapter(); public UI_GraphTable(UI_Controller ui_controller) { super(ui_controller.getGraphTableModel()); this.ui_controller = ui_controller; prepare(); } private void prepare() { setDefaultRenderer(GraphCommitCell.class, new GraphCommitCellRender(graphPainter)); setRowHeight(GraphCommitCell.HEIGHT_CELL); setShowHorizontalLines(false); setIntercellSpacing(new Dimension(0, 0)); getColumnModel().getColumn(0).setPreferredWidth(800); getColumnModel().getColumn(1).setMinWidth(80); getColumnModel().getColumn(2).setMinWidth(80); addMouseMotionListener(mouseAdapter); addMouseListener(mouseAdapter); ui_controller.addControllerListener(new EventsController.ControllerListener() { @Override public void jumpToRow(int rowIndex) { scrollRectToVisible(getCellRect(rowIndex, 0, false)); setRowSelectionInterval(rowIndex, rowIndex); scrollRectToVisible(getCellRect(rowIndex, 0, false)); } @Override public void updateTable() { updateUI(); } }); } private class MyMouseAdapter extends MouseAdapter { @Nullable private GraphElement overCell(MouseEvent e) { int rowIndex = e.getY() / GraphCommitCell.HEIGHT_CELL; int y = e.getY() - rowIndex * GraphCommitCell.HEIGHT_CELL; int x = e.getX(); GraphCommitCell commitCell = (GraphCommitCell) UI_GraphTable.this.getModel().getValueAt(rowIndex, 0); GraphPrintCell row = commitCell.getPrintCell(); return graphPainter.mouseOver(row, x, y); } @Override public void mouseClicked(MouseEvent e) { ui_controller.click(overCell(e)); } @Override public void mouseMoved(MouseEvent e) { ui_controller.over(overCell(e)); } } }
package org.ensembl.healthcheck.testcase.generic; 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 java.util.Iterator; import java.text.DecimalFormat; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.Team; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; import org.ensembl.healthcheck.Species; import org.ensembl.healthcheck.util.Utils; /** * Compare the gene names in the current database with those from the equivalent database on the secondary server. */ public class ComparePreviousVersionGeneNames extends SingleDatabaseTestCase { /** * Create a new testcase. */ public ComparePreviousVersionGeneNames() { addToGroup("release"); addToGroup("core_xrefs"); setDescription("Compare gene names in the current database with those from the equivalent database on the secondary server."); setTeamResponsible(Team.GENEBUILD); setSecondTeamResponsible(Team.CORE); } /** * This only applies to core and Vega databases. */ public void types() { removeAppliesToType(DatabaseType.OTHERFEATURES); removeAppliesToType(DatabaseType.ESTGENE); removeAppliesToType(DatabaseType.CDNA); removeAppliesToType(DatabaseType.RNASEQ); } public boolean run(DatabaseRegistryEntry dbre) { boolean result = true; //this test only applies to the human db if ( !dbre.getSpecies().equals(Species.HOMO_SAPIENS) ) { return result; } Connection currentCon = dbre.getConnection(); DatabaseRegistryEntry previous = getEquivalentFromSecondaryServer(dbre); if (previous == null) { return result; } Connection previousCon = previous.getConnection(); // Get data from previous database, compare each one with equivalent on // current float displayXrefCount = new Integer(getRowCount(currentCon, "SELECT COUNT(1) FROM gene WHERE display_xref_id IS NOT NULL" ) ); float displayXrefPreviousCount = new Integer(getRowCount(previousCon, "SELECT COUNT(1) FROM gene WHERE display_xref_id IS NOT NULL" ) ); if (displayXrefCount == 0 || displayXrefPreviousCount == 0 ) { ReportManager.problem(this, currentCon, "display xref count is 0 in the current or previous database"); result = false; return result; } String previousSQL = "SELECT stable_id, db_name, dbprimary_acc FROM gene JOIN gene_stable_id USING(gene_id) LEFT JOIN xref ON display_xref_id = xref_id LEFT JOIN external_db USING(external_db_id)"; String currentSQL = "SELECT stable_id, db_name, dbprimary_acc FROM gene JOIN gene_stable_id USING(gene_id) LEFT JOIN xref ON display_xref_id = xref_id LEFT JOIN external_db USING(external_db_id) WHERE stable_id = ?"; int missingIds = 0; int accessionsChanged = 0; HashMap < String, Integer > changeCounts = new HashMap < String, Integer >(); try { PreparedStatement previousStmt = previousCon.prepareStatement(previousSQL); PreparedStatement currentStmt = currentCon.prepareStatement(currentSQL); ResultSet previousRS = previousStmt.executeQuery(); while (previousRS.next()) { String stableId = previousRS.getString(1); String previousDbName = previousRS.getString(2); String previousAccession = previousRS.getString(3); currentStmt.setString(1, stableId); ResultSet currentRS = currentStmt.executeQuery(); if (currentRS == null) { missingIds ++; currentRS.close(); continue; } if (!currentRS.next()) { missingIds ++; currentRS.close(); continue; } String currentDbName = currentRS.getString(2); String currentAccession = currentRS.getString(3); if (previousDbName == null) { previousDbName = "null"; } if (previousAccession == null) { previousAccession = "null"; } if (currentDbName == null) { currentDbName = "null"; } if (currentAccession == null) { currentAccession = "null"; } if (!currentAccession.equals(previousAccession) && currentDbName.equals(previousDbName) ) { //store counts of display xrefs where accession changed - same source accessionsChanged ++; } if (!currentDbName.equals(previousDbName) ) { //store counts of display xrefs where source changed String dbNames = previousDbName + " to " + currentDbName; if (changeCounts.containsKey(dbNames) ) { int changeCount = changeCounts.get(dbNames); changeCount ++; changeCounts.put(dbNames, changeCount); } else { changeCounts.put(dbNames,1); } } currentRS.close(); } previousRS.close(); currentStmt.close(); previousStmt.close(); } catch (SQLException e) { System.err.println("Error executing SQL"); e.printStackTrace(); } float changedSource = 0; float totalCount = 0; float percentageChange = 0; if ( changeCounts.size() > 0 || accessionsChanged > 0 ) { Iterator<String> iter = changeCounts.keySet().iterator(); while(iter.hasNext()) { String key = iter.next(); int changeCount = changeCounts.get(key); changedSource += changeCount; } totalCount = changedSource + accessionsChanged; percentageChange = totalCount/displayXrefPreviousCount * 100 ; if (percentageChange > 1) { result = false; } } if (!result) { DecimalFormat twoDForm = new DecimalFormat(" float percentage = missingIds/displayXrefPreviousCount * 100; percentage = Float.valueOf(twoDForm.format(percentage)); if (missingIds > 0 ) { ReportManager.problem(this, currentCon, missingIds + "(" + percentage + "%) stable ids missing from the current database "); } percentage = accessionsChanged/displayXrefPreviousCount * 100; percentage = Float.valueOf(twoDForm.format(percentage)); if (accessionsChanged > 0 ) { ReportManager.problem(this, currentCon, accessionsChanged + "(" +percentage + "%) display xref primary accessions changed for the same source "); } percentageChange = changedSource/displayXrefPreviousCount * 100 ; percentageChange = Float.valueOf(twoDForm.format(percentageChange)); ReportManager.problem(this, currentCon, percentageChange + "% of gene display xrefs changed source: (from [previous source] to [current source] )"); //print out counts and percentages of changes Iterator<String> iter = changeCounts.keySet().iterator(); while(iter.hasNext()) { String key = iter.next(); int changeCount = changeCounts.get(key); percentage = changeCount/displayXrefPreviousCount * 100; percentage = Float.valueOf(twoDForm.format(percentage)); ReportManager.problem(this, currentCon, changeCount +"("+ percentage +"%) gene display xrefs changed source from " + key); } } return result; } } // ComparePreviousVersionGeneNames
import java.io.File; import java.io.InputStream; import java.io.Serializable; import java.util.Properties; import org.apache.commons.configuration.ConfigurationException; import org.gluu.site.ldap.persistence.util.ReflectHelper; import org.jboss.seam.Component; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.Destroy; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.log.Log; import org.python.core.PyException; import org.python.core.PyObject; import org.python.util.PythonInterpreter; import org.xdi.exception.PythonException; import org.xdi.util.StringHelper; @Scope(ScopeType.APPLICATION) @Name("pythonService") @AutoCreate public class PythonService implements Serializable { private static final long serialVersionUID = 3398422090669045605L; @Logger private Log log; private PythonInterpreter pythonInterpreter; private boolean interpereterReady; /* * Initialize singleton instance during startup */ public boolean initPythonInterpreter() { boolean result = false; if (isInitInterpreter()) { try { PythonInterpreter.initialize(getPreProperties(), getPostProperties(), null); this.pythonInterpreter = new PythonInterpreter(); result = true; } catch (PyException ex) { log.error("Failed to initialize PythonInterpreter correctly", ex); } catch (Exception ex) { log.error("Failed to initialize PythonInterpreter correctly", ex); } } this.interpereterReady = result; return result; } /** * When application undeploy we need clean up pythonInterpreter */ @Destroy public void destroy() { log.debug("Destroying pythonInterpreter component"); if (this.pythonInterpreter != null) { this.pythonInterpreter.cleanup(); } } private Properties getPreProperties() { Properties props = System.getProperties(); Properties clonedProps = (Properties) props.clone(); clonedProps.setProperty("java.class.path", "."); clonedProps.setProperty("java.library.path", ""); clonedProps.remove("javax.net.ssl.trustStore"); clonedProps.remove("javax.net.ssl.trustStorePassword"); return clonedProps; } private Properties getPostProperties() { Properties props = getPreProperties(); String catalinaTmpFolder = System.getProperty("java.io.tmpdir") + File.separator + "python" + File.separator + "cachedir"; props.setProperty("python.cachedir", catalinaTmpFolder); String pythonHome = System.getenv("PYTHON_HOME"); if (StringHelper.isNotEmpty(pythonHome)) { props.setProperty("python.home", pythonHome); } // Register custom python modules String oxAuthPythonModulesPath = System.getProperty("catalina.home") + File.separator + "conf" + File.separator + "python"; props.setProperty("python.path", oxAuthPythonModulesPath); return props; } private boolean isInitInterpreter() { String pythonHome = System.getenv("PYTHON_HOME"); return StringHelper.isNotEmpty(pythonHome); } public <T> T loadPythonScript(String scriptName, String scriptPythonType, Class<T> scriptJavaType, PyObject[] constructorArgs) throws PythonException { if (!interpereterReady || StringHelper.isEmpty(scriptName)) { return null; } try { this.pythonInterpreter.execfile(scriptName); } catch (Exception ex) { throw new PythonException(String.format("Failed to load python file '%s'", scriptName), ex); } return loadPythonScript(scriptPythonType, scriptJavaType, constructorArgs, this.pythonInterpreter); } public <T> T loadPythonScript(InputStream scriptFile, String scriptPythonType, Class<T> scriptJavaType, PyObject[] constructorArgs) throws PythonException { if (!interpereterReady || (scriptFile == null)) { return null; } try { this.pythonInterpreter.execfile(scriptFile); } catch (Exception ex) { throw new PythonException(String.format("Failed to load python file '%s'", scriptFile), ex); } return loadPythonScript(scriptPythonType, scriptJavaType, constructorArgs, this.pythonInterpreter); } @SuppressWarnings("unchecked") private <T> T loadPythonScript(String scriptPythonType, Class<T> scriptJavaType, PyObject[] constructorArgs, PythonInterpreter interpreter) throws PythonException { PyObject scriptPythonTypeObject = interpreter.get(scriptPythonType); if (scriptPythonTypeObject == null) { return null; } PyObject scriptPythonTypeClass; try { scriptPythonTypeClass = scriptPythonTypeObject.__call__(constructorArgs); } catch (Exception ex) { throw new PythonException(String.format("Failed to initialize python class '%s'", scriptPythonType), ex); } Object scriptJavaClass = scriptPythonTypeClass.__tojava__(scriptJavaType); if (!ReflectHelper.assignableFrom(scriptJavaClass.getClass(), scriptJavaType)) { return null; } return (T) scriptJavaClass; } /** * Get pythonService instance * @return PythonService instance */ public static PythonService instance() { return (PythonService) Component.getInstance(PythonService.class); } }
package engine.game; import java.util.ArrayList; import java.util.List; import engine.events.Event; import engine.events.TimedEvent; /** * Manages the event progression for a level * * @author Tom Puglisi * */ public class StoryBoard { private List<Event> eventList; public StoryBoard (Event ... events) { eventList = new ArrayList<Event>(); addEvent(events); } public boolean addEvent (Event ... events) { for (Event event : events) { eventList.add(event); } return true; } /** * Update all events * * @return false if the StoryBoard has no more events to update */ public boolean update () { if (eventList.size() == 0) { return false; } updateEvent(getCurrentEvent()); return true; } /** * If an event is complete, remove it from the list * * @param event */ private void updateEvent (Event event) { if (!event.update()) { eventList.remove(event); } } /** * * @return the next event in the List, if there is one */ private Event getCurrentEvent () { if (eventList.size() > 0) { return eventList.get(0); } return null; } /** * Sets the current event's start conditions to true, but only if they are not already true */ public void startNextEvent () { Event currentEvent = getCurrentEvent(); if (currentEvent != null && !currentEvent.canStart()) { currentEvent.setCanStart(); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package erp.mtrn.data; import cfd.DAttributeOptionCondicionesPago; import cfd.DAttributeOptionImpuestoRetencion; import cfd.DAttributeOptionImpuestoTraslado; import cfd.DAttributeOptionMoneda; import cfd.DAttributeOptionTipoComprobante; import cfd.DElement; import cfd.ext.bachoco.DElementLineItem; import cfd.ext.bachoco.DElementPayment; import cfd.ext.elektra.DElementAp; import cfd.ext.elektra.DElementDetailItems; import cfd.ext.elektra.DElementDetalle; import cfd.ext.elektra.DElementImpuestos; import cfd.ext.elektra.DElementProducto; import cfd.ext.elektra.DElementTrasladado; import cfd.ext.facturainterfactura.DElementCuerpo; import cfd.ext.facturainterfactura.DElementFacturainterfactura; import cfd.ext.soriana.DElementArticulos; import cfd.ext.soriana.DElementDSCargaRemisionProv; import cfd.ext.soriana.DElementFolioNotaEntrada; import erp.SClient; import erp.cfd.SCfdConsts; import erp.cfd.SCfdDataConcepto; import erp.cfd.SCfdDataImpuesto; import erp.client.SClientInterface; import erp.data.SDataConstants; import erp.data.SDataConstantsSys; import erp.data.SDataReadDescriptions; import erp.data.SDataUtilities; import erp.gui.session.SSessionCustom; import erp.gui.session.SSessionItem; import erp.lib.SLibConstants; import erp.lib.SLibTimeUtilities; import erp.lib.SLibUtilities; import erp.mbps.data.SDataBizPartnerBranch; import erp.mfin.data.SDataRecord; import erp.mfin.data.SDataRecordEntry; import erp.mfin.data.SFinAccountConfig; import erp.mfin.data.SFinAccountConfigEntry; import erp.mfin.data.SFinAccountUtilities; import erp.mfin.data.SFinAmount; import erp.mfin.data.SFinTaxes; import erp.mod.SModSysConsts; import erp.mod.trn.db.SDbMmsConfig; import erp.mod.trn.db.STrnUtils; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.Vector; import sa.lib.SLibConsts; import sa.lib.SLibUtils; import sa.lib.db.SDbConsts; /** * * @author Sergio Flores */ public class SDataDps extends erp.lib.data.SDataRegistry implements java.io.Serializable, erp.cfd.SCfdXml { public static final int FIELD_REF_BKR = 1; public static final int FIELD_SAL_AGT = 2; public static final int FIELD_SAL_AGT_SUP = 3; public static final int FIELD_CLO_COMMS = 4; public static final int FIELD_CLO_COMMS_USR = 5; public static final int FIELD_USR = 6; protected int mnPkYearId; protected int mnPkDocId; protected java.util.Date mtDate; protected java.util.Date mtDateDoc; protected java.util.Date mtDateStartCredit; protected java.util.Date mtDateShipment_n; protected java.util.Date mtDateDelivery_n; protected java.util.Date mtDateDocLapsing_n; protected java.util.Date mtDateDocDelivery_n; protected java.lang.String msNumberSeries; protected java.lang.String msNumber; protected java.lang.String msNumberReference; protected java.lang.String msCommissionsReference; protected int mnApproveYear; protected int mnApproveNumber; protected int mnDaysOfCredit; protected boolean mbIsDiscountDocApplying; protected boolean mbIsDiscountDocPercentage; protected double mdDiscountDocPercentage; protected double mdSubtotalProvisional_r; protected double mdDiscountDoc_r; protected double mdSubtotal_r; protected double mdTaxCharged_r; protected double mdTaxRetained_r; protected double mdTotal_r; protected double mdCommissions_r; protected double mdExchangeRate; protected double mdExchangeRateSystem; protected double mdSubtotalProvisionalCy_r; protected double mdDiscountDocCy_r; protected double mdSubtotalCy_r; protected double mdTaxChargedCy_r; protected double mdTaxRetainedCy_r; protected double mdTotalCy_r; protected double mdCommissionsCy_r; protected java.lang.String msDriver; protected java.lang.String msPlate; protected java.lang.String msTicket; protected int mnShipments; protected int mnPayments; protected java.lang.String msPaymentMethod; protected java.lang.String msPaymentAccount; protected boolean mbIsPublic; protected boolean mbIsLinked; protected boolean mbIsClosed; protected boolean mbIsClosedCommissions; protected boolean mbIsShipped; protected boolean mbIsRebill; protected boolean mbIsAudited; protected boolean mbIsAuthorized; protected boolean mbIsRecordAutomatic; protected boolean mbIsCopy; protected boolean mbIsCopied; protected boolean mbIsSystem; protected boolean mbIsDeleted; protected int mnFkDpsCategoryId; protected int mnFkDpsClassId; protected int mnFkDpsTypeId; protected int mnFkPaymentTypeId; protected int mnFkPaymentSystemTypeId; protected int mnFkDpsStatusId; protected int mnFkDpsValidityStatusId; protected int mnFkDpsAuthorizationStatusId; protected int mnFkDpsNatureId; protected int mnFkCompanyBranchId; protected int mnFkBizPartnerId_r; protected int mnFkBizPartnerBranchId; protected int mnFkBizPartnerBranchAddressId; protected int mnFkBizPartnerAltId_r; protected int mnFkBizPartnerBranchAltId; protected int mnFkBizPartnerBranchAddressAltId; protected int mnFkContactBizPartnerBranchId_n; protected int mnFkContactContactId_n; protected int mnFkTaxIdentityEmisorTypeId; protected int mnFkTaxIdentityReceptorTypeId; protected int mnFkLanguajeId; protected int mnFkCurrencyId; protected int mnFkSalesAgentId_n; protected int mnFkSalesAgentBizPartnerId_n; protected int mnFkSalesSupervisorId_n; protected int mnFkSalesSupervisorBizPartnerId_n; protected int mnFkIncotermId; protected int mnFkSpotSourceId_n; protected int mnFkSpotDestinyId_n; protected int mnFkModeOfTransportationTypeId; protected int mnFkCarrierTypeId; protected int mnFkCarrierId_n; protected int mnFkVehicleTypeId_n; protected int mnFkVehicleId_n; protected int mnFkSourceYearId_n; protected int mnFkSourceDocId_n; protected int mnFkMfgYearId_n; protected int mnFkMfgOrderId_n; protected int mnFkUserLinkedId; protected int mnFkUserClosedId; protected int mnFkUserClosedCommissionsId; protected int mnFkUserShippedId; protected int mnFkUserAuditedId; protected int mnFkUserAuthorizedId; protected int mnFkUserNewId; protected int mnFkUserEditId; protected int mnFkUserDeleteId; protected java.util.Date mtUserLinkedTs; protected java.util.Date mtUserClosedTs; protected java.util.Date mtUserClosedCommissionsTs; protected java.util.Date mtUserShippedTs; protected java.util.Date mtUserAuditedTs; protected java.util.Date mtUserAuthorizedTs; protected java.util.Date mtUserNewTs; protected java.util.Date mtUserEditTs; protected java.util.Date mtUserDeleteTs; protected java.util.Vector<SDataDpsEntry> mvDbmsDpsEntries; protected java.util.Vector<SDataDpsNotes> mvDbmsDpsNotes; protected java.lang.Object moDbmsRecordKey; protected java.util.Date mtDbmsRecordDate; protected java.lang.String msDbmsCurrency; protected java.lang.String msDbmsCurrencyKey; protected boolean mbAuxIsFormerRecordAutomatic; protected java.lang.Object moAuxFormerRecordKey; protected erp.mtrn.data.SCfdParams moAuxCfdParams; protected boolean mbAuxIsNeedCfd; protected boolean mbAuxIsValidate; protected erp.mtrn.data.SDataDpsAddenda moDbmsDataAddenda; protected erp.mtrn.data.SDataDpsAddendaEntry moDataAddendaEntry; protected erp.mtrn.data.SDataCfd moDbmsDataCfd; protected String msCfdExpeditionLocality; protected String msCfdExpeditionState; protected double mdCfdIvaPorcentaje; public SDataDps() { super(SDataConstants.TRN_DPS); mlRegistryTimeout = 1000 * 60 * 60 * 2; // 2 hr mvDbmsDpsEntries = new Vector<>(); mvDbmsDpsNotes = new Vector<>(); reset(); } /* * Private functions */ private boolean isDpsAuthorized(java.sql.Connection connection) throws java.sql.SQLException, java.lang.Exception { boolean isAutorized = false; Statement oStatement = null; SDataUserConfigurationTransaction oUserConfig = null; oStatement = connection.createStatement(); oUserConfig = new SDataUserConfigurationTransaction(); if (oUserConfig.read(new int[] { mbIsRegistryNew ? mnFkUserNewId : mnFkUserEditId }, oStatement) != SLibConstants.DB_ACTION_READ_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } else { if (mnFkDpsCategoryId == SDataConstantsSys.TRNS_CT_DPS_PUR) { if (isOrderPur() && (oUserConfig.getPurchasesOrderLimit_n() == 0 || oUserConfig.getPurchasesOrderLimit_n() >= mdTotal_r)) { isAutorized = true; } else if (isDocumentPur() && (oUserConfig.getPurchasesDocLimit_n() == 0 || oUserConfig.getPurchasesDocLimit_n() >= mdTotal_r)) { isAutorized = true; } } else if (mnFkDpsCategoryId == SDataConstantsSys.TRNS_CT_DPS_SAL) { if (isOrderSal() && (oUserConfig.getSalesOrderLimit_n() == 0 || oUserConfig.getSalesOrderLimit_n() >= mdTotal_r)) { isAutorized = true; } else if (isDocumentSal() && (oUserConfig.getSalesDocLimit_n() == 0 || oUserConfig.getSalesDocLimit_n() >= mdTotal_r)) { isAutorized = true; } } } return isAutorized; } private void updateAuthorizationStatus(java.sql.Connection connection) throws java.sql.SQLException, java.lang.Exception { boolean isAutPurOrd = false; boolean isAutPurDps = false; boolean isAutSalOrd = false; boolean isAutSalDps = false; String sql = ""; Statement statement = null; ResultSet resultSet = null; if (!mbIsDeleted && (isOrder() || isDocument())) { statement = connection.createStatement(); // XXX It is needed a "session" object in SDataRegistry objects in order to know current company, company branch, current entities, decimal an date format objects, etc. sql = "SELECT fid_bp FROM erp.bpsu_bpb WHERE id_bpb = " + mnFkCompanyBranchId + " "; resultSet = statement.executeQuery(sql); if (!resultSet.next()) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } else { sql = "SELECT b_authorn_pur_ord, b_authorn_pur_doc, b_authorn_sal_ord, b_authorn_sal_doc FROM cfg_param_co WHERE id_co = " + resultSet.getInt("fid_bp") + " "; resultSet = statement.executeQuery(sql); if (!resultSet.next()) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } else { isAutPurOrd = resultSet.getBoolean("b_authorn_pur_ord"); isAutPurDps = resultSet.getBoolean("b_authorn_pur_doc"); isAutSalOrd = resultSet.getBoolean("b_authorn_sal_ord"); isAutSalDps = resultSet.getBoolean("b_authorn_sal_doc"); } } if (isOrderPur() && isAutPurOrd || isDocumentPur() && isAutPurDps || isOrderSal() && isAutSalOrd || isDocumentSal() && isAutSalDps) { if (isDpsAuthorized(connection)) { mbIsAuthorized = true; mnFkDpsAuthorizationStatusId = SDataConstantsSys.TRNS_ST_DPS_AUTHORN_AUTHORN; } else { mbIsAuthorized = false; mnFkDpsAuthorizationStatusId = SDataConstantsSys.TRNS_ST_DPS_AUTHORN_PENDING; } mnFkUserAuthorizedId = mbIsRegistryNew ? mnFkUserNewId : mnFkUserEditId; } } } private boolean isDebitForBizPartner() { return isDocumentSal() || isAdjustmentPur(); } private boolean isDebitForOperations() { return isDocumentPur() || isAdjustmentSal(); } private boolean isDebitForTaxes(int taxType) { return isDocumentPur() && taxType == SModSysConsts.FINS_TP_TAX_CHARGED || isDocumentSal() && taxType == SModSysConsts.FINS_TP_TAX_RETAINED || isAdjustmentPur() && taxType == SModSysConsts.FINS_TP_TAX_RETAINED || isAdjustmentSal() && taxType == SModSysConsts.FINS_TP_TAX_CHARGED; } private boolean deleteRecord(java.lang.Object recordKey, boolean deleteWholeRecord, java.sql.Connection connection) throws java.lang.Exception { SDataRecord record = new SDataRecord(); Statement statement = connection.createStatement(); if (record.read(recordKey, statement) != SLibConstants.DB_ACTION_READ_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ); } else { if (deleteWholeRecord) { record.setIsRegistryEdited(true); record.setIsDeleted(true); record.setFkUserDeleteId(mnFkUserDeleteId); for (SDataRecordEntry entry : record.getDbmsRecordEntries()) { if (!entry.getIsDeleted()) { // Delete aswell all non-deleted entries: entry.setIsRegistryEdited(true); entry.setIsDeleted(true); entry.setFkUserDeleteId(mnFkUserDeleteId); } } } else { for (SDataRecordEntry entry : record.getDbmsRecordEntries()) { if (!entry.getIsDeleted()) { // Delete aswell all non-deleted entries: if (isDocument()) { if (entry.getFkDpsYearId_n() == mnPkYearId && entry.getFkDpsDocId_n() == mnPkDocId) { entry.setIsRegistryEdited(true); entry.setIsDeleted(true); entry.setFkUserDeleteId(mnFkUserDeleteId); } } else { if (entry.getFkDpsAdjustmentYearId_n() == mnPkYearId && entry.getFkDpsAdjustmentDocId_n() == mnPkDocId) { entry.setIsRegistryEdited(true); entry.setIsDeleted(true); entry.setFkUserDeleteId(mnFkUserDeleteId); } } } } } if (record.save(connection) != SLibConstants.DB_ACTION_SAVE_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE); } } return true; } private void deleteLinks(java.sql.Statement statement) throws java.sql.SQLException { String sql = ""; sql = "DELETE FROM trn_dps_dps_supply WHERE id_src_year = " + mnPkYearId + " AND id_src_doc = " + mnPkDocId + " "; statement.execute(sql); sql = "DELETE FROM trn_dps_dps_supply WHERE id_des_year = " + mnPkYearId + " AND id_des_doc = " + mnPkDocId + " "; statement.execute(sql); sql = "DELETE FROM trn_dps_dps_adj WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " "; statement.execute(sql); sql = "DELETE FROM trn_dps_dps_adj WHERE id_adj_year = " + mnPkYearId + " AND id_adj_doc = " + mnPkDocId + " "; statement.execute(sql); sql = "DELETE FROM trn_dps_riss WHERE id_old_year = " + mnPkYearId + " AND id_old_doc = " + mnPkDocId + " "; statement.execute(sql); sql = "DELETE FROM trn_dps_riss WHERE id_new_year = " + mnPkYearId + " AND id_new_doc = " + mnPkDocId + " "; statement.execute(sql); sql = "DELETE FROM trn_dps_repl WHERE id_old_year = " + mnPkYearId + " AND id_old_doc = " + mnPkDocId + " "; statement.execute(sql); sql = "DELETE FROM trn_dps_repl WHERE id_new_year = " + mnPkYearId + " AND id_new_doc = " + mnPkDocId + " "; statement.execute(sql); sql = "DELETE FROM trn_dps_iog_chg WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " "; statement.execute(sql); sql = "DELETE FROM trn_dps_iog_war WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " "; statement.execute(sql); sql = "DELETE FROM trn_dsm_ety WHERE fid_src_dps_year_n = " + mnPkYearId + " AND fid_src_dps_doc_n = " + mnPkDocId + " "; statement.execute(sql); sql = "DELETE FROM trn_dsm_ety WHERE fid_des_dps_year_n = " + mnPkYearId + " AND fid_des_dps_doc_n = " + mnPkDocId + " "; statement.execute(sql); sql = "DELETE FROM mkt_comms_pay_ety WHERE fk_year = " + mnPkYearId + " AND fk_doc = " + mnPkDocId + " "; statement.execute(sql); sql = "DELETE FROM mkt_comms WHERE id_year = " + mnPkYearId + " AND id_doc = " + mnPkDocId + " "; statement.execute(sql); } private void clearEntryDeliveryReferences(java.sql.Statement statement) throws java.sql.SQLException { String sql = "UPDATE trn_dps_ety SET con_prc_year = 0, con_prc_mon = 0 WHERE id_year = " + mnPkYearId + " AND id_doc = " + mnPkDocId; statement.execute(sql); } private java.lang.String getAccountingRecordType() { String type = ""; int[] docClassKey = new int[] { mnFkDpsCategoryId, mnFkDpsClassId }; if (SLibUtilities.compareKeys(docClassKey, SDataConstantsSys.TRNS_CL_DPS_PUR_DOC)) { type = SDataConstantsSys.FINU_TP_REC_PUR; } else if (SLibUtilities.compareKeys(docClassKey, SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ)) { type = SDataConstantsSys.FINU_TP_REC_PUR; } else if (SLibUtilities.compareKeys(docClassKey, SDataConstantsSys.TRNS_CL_DPS_SAL_DOC)) { type = SDataConstantsSys.FINU_TP_REC_SAL; } else if (SLibUtilities.compareKeys(docClassKey, SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ)) { type = SDataConstantsSys.FINU_TP_REC_SAL; } return type; } private java.lang.Object createAccountingRecordKey(java.sql.Statement statement) throws java.lang.Exception { int[] period = null; Object[] key = null; SDataBizPartnerBranch branch = new SDataBizPartnerBranch(); if (branch.read(new int[] { mnFkCompanyBranchId }, statement) != SLibConstants.DB_ACTION_READ_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } else { period = SLibTimeUtilities.digestYearMonth(mtDate); key = new Object[5]; key[0] = period[0]; key[1] = period[1]; key[2] = branch.getDbmsDataCompanyBranchBkc().getPkBookkepingCenterId(); key[3] = getAccountingRecordType(); key[4] = 0; } return key; } private erp.mfin.data.SDataRecordEntry createAccountingRecordEntry(java.lang.String accountId, java.lang.String costCenterId, int[] accMoveSubclassKey, int[] sysAccountTypeKey, int[] sysMoveTypeKey, int[] sysMoveTypeKeyXXX, int[] auxDpsKey) { SDataRecordEntry entry = new SDataRecordEntry(); entry.setPkYearId((Integer) ((Object[]) moDbmsRecordKey)[0]); entry.setPkPeriodId((Integer) ((Object[]) moDbmsRecordKey)[1]); entry.setPkBookkeepingCenterId((Integer) ((Object[]) moDbmsRecordKey)[2]); entry.setPkRecordTypeId((String) ((Object[]) moDbmsRecordKey)[3]); entry.setPkNumberId((Integer) ((Object[]) moDbmsRecordKey)[4]); entry.setPkEntryId(0); entry.setConcept(""); entry.setReference(""); entry.setIsReferenceTax(false); entry.setDebit(0); entry.setCredit(0); entry.setExchangeRate(mdExchangeRate); entry.setExchangeRateSystem(mdExchangeRateSystem); entry.setDebitCy(0); entry.setCreditCy(0); entry.setUnits(0); entry.setSortingPosition(0); entry.setIsSystem(true); entry.setIsDeleted(false); entry.setFkAccountIdXXX(accountId); entry.setFkAccountingMoveTypeId(accMoveSubclassKey[0]); entry.setFkAccountingMoveClassId(accMoveSubclassKey[1]); entry.setFkAccountingMoveSubclassId(accMoveSubclassKey[2]); entry.setFkSystemMoveClassId(sysMoveTypeKey[0]); entry.setFkSystemMoveTypeId(sysMoveTypeKey[1]); entry.setFkSystemAccountClassId(sysAccountTypeKey[0]); entry.setFkSystemAccountTypeId(sysAccountTypeKey[1]); entry.setFkSystemMoveCategoryIdXXX(sysMoveTypeKeyXXX[0]); entry.setFkSystemMoveTypeIdXXX(sysMoveTypeKeyXXX[1]); entry.setFkCurrencyId(mnFkCurrencyId); entry.setFkCostCenterIdXXX_n(costCenterId); entry.setFkCheckWalletId_n(0); entry.setFkCheckId_n(0); entry.setFkBizPartnerId_nr(mnFkBizPartnerId_r); entry.setFkBizPartnerBranchId_n(mnFkBizPartnerBranchId); entry.setFkReferenceCategoryId_n(0); entry.setFkCompanyBranchId_n(0); entry.setFkEntityId_n(0); entry.setFkTaxBasicId_n(0); entry.setFkTaxId_n(0); entry.setFkYearId_n(0); if (isDocument()) { entry.setFkDpsYearId_n(mnPkYearId); entry.setFkDpsDocId_n(mnPkDocId); entry.setFkDpsAdjustmentYearId_n(0); entry.setFkDpsAdjustmentDocId_n(0); } else { entry.setFkDpsYearId_n(auxDpsKey[0]); entry.setFkDpsDocId_n(auxDpsKey[1]); entry.setFkDpsAdjustmentYearId_n(mnPkYearId); entry.setFkDpsAdjustmentDocId_n(mnPkDocId); } entry.setFkDiogYearId_n(0); entry.setFkDiogDocId_n(0); entry.setFkItemId_n(0); entry.setFkItemAuxId_n(0); entry.setFkUnitId_n(0); if (mbIsRegistryNew) { entry.setFkUserNewId(mnFkUserNewId); entry.setFkUserEditId(mnFkUserNewId); } else { entry.setFkUserNewId(mnFkUserEditId); entry.setFkUserEditId(mnFkUserEditId); } return entry; } private boolean testDeletion(java.sql.Connection poConnection, java.lang.String psMsg, int pnAction) throws java.sql.SQLException, java.lang.Exception { int i = 0; int[] anPeriodKey = null; double dBalance; double dBalanceCy; String sSql = ""; String sMsg = psMsg; String sMsgAux = ""; Statement oStatement = null; ResultSet oResultSet = null; DecimalFormat oDecimalFormat = new DecimalFormat("$ #,##0.00"); CallableStatement oCallableStatement = null; if (pnAction == SDbConsts.ACTION_DELETE && mbIsDeleted) { mnDbmsErrorId = 1; msDbmsError = sMsg + "¡El documento ya está eliminado!"; throw new Exception(msDbmsError); } else if (pnAction == SDbConsts.ACTION_ANNUL && mnFkDpsStatusId == SDataConstantsSys.TRNS_ST_DPS_ANNULED) { mnDbmsErrorId = 2; msDbmsError = sMsg + "¡El documento ya está anulado!"; throw new Exception(msDbmsError); } else if (mbIsSystem) { mnDbmsErrorId = 11; msDbmsError = sMsg + "¡El documento es de sistema!"; throw new Exception(msDbmsError); } else if (mbIsAudited) { mnDbmsErrorId = 12; msDbmsError = sMsg + "¡El documento está auditado!"; throw new Exception(msDbmsError); } else if (mbIsAuthorized) { mnDbmsErrorId = 13; msDbmsError = sMsg + "¡El documento está autorizado!"; throw new Exception(msDbmsError); } else if (pnAction == SDbConsts.ACTION_DELETE && moDbmsDataCfd != null && moDbmsDataCfd.isStamped()) { mnDbmsErrorId = 21; msDbmsError = sMsg + "¡El documento está timbrado!"; throw new Exception(msDbmsError); } else if (moDbmsDataCfd != null && !mbAuxIsValidate && moDbmsDataCfd.getIsProcessingWebService()) { mnDbmsErrorId = 22; msDbmsError = sMsg + "¡" + SCfdConsts.ERR_MSG_PROCESSING_WEB_SERVICE + "!"; throw new Exception(msDbmsError); } else if (moDbmsDataCfd != null && !mbAuxIsValidate && pnAction != SDbConsts.ACTION_ANNUL && moDbmsDataCfd.getIsProcessingStorageXml()) { mnDbmsErrorId = 23; msDbmsError = sMsg + "¡" + SCfdConsts.ERR_MSG_PROCESSING_XML_STORAGE + "!"; throw new Exception(msDbmsError); } else if (mnFkDpsStatusId != SDataConstantsSys.TRNS_ST_DPS_EMITED) { mnDbmsErrorId = 41; msDbmsError = sMsg + "¡El documento debe tener estatus 'emitido'!"; throw new Exception(msDbmsError); } else if (mnFkDpsValidityStatusId != SDataConstantsSys.TRNS_ST_DPS_VAL_EFF) { mnDbmsErrorId = 42; msDbmsError = sMsg + "¡El documento debe tener estatus de validez 'efectivo'!"; throw new Exception(msDbmsError); } else if (mbIsShipped) { mnDbmsErrorId = 51; msDbmsError = sMsg + "¡El documento está embarcado!"; throw new Exception(msDbmsError); } else { // Check that document's date belongs to an open period: i = 1; anPeriodKey = SLibTimeUtilities.digestYearMonth(mtDate); oCallableStatement = poConnection.prepareCall("{ CALL fin_year_per_st(?, ?, ?) }"); oCallableStatement.setInt(i++, anPeriodKey[0]); oCallableStatement.setInt(i++, anPeriodKey[1]); oCallableStatement.registerOutParameter(i++, java.sql.Types.INTEGER); oCallableStatement.execute(); if (oCallableStatement.getBoolean(i - 1)) { mnDbmsErrorId = 101; msDbmsError = sMsg + "¡El período contable de la fecha del documento está cerrado!"; throw new Exception(msDbmsError); } if (isDocument()) { // Check that document's balance is equal to document's value: i = 1; anPeriodKey = SLibTimeUtilities.digestYearMonth(mtDate); oCallableStatement = poConnection.prepareCall("{ CALL trn_dps_bal(?, ?, ?, ?, ?, ?) }"); oCallableStatement.setInt(i++, mnPkYearId); oCallableStatement.setInt(i++, mnPkDocId); oCallableStatement.setInt(i++, getAccountSystemTypeForBizPartnerXXX()); oCallableStatement.registerOutParameter(i++, java.sql.Types.DECIMAL); oCallableStatement.registerOutParameter(i++, java.sql.Types.DECIMAL); oCallableStatement.registerOutParameter(i++, java.sql.Types.SMALLINT); oCallableStatement.execute(); dBalance = oCallableStatement.getDouble(i - 3); dBalanceCy = oCallableStatement.getDouble(i - 2); if (isDocumentPur()) { dBalance *= -1d; dBalanceCy *= -1d; } if (dBalance != mdTotal_r) { mnDbmsErrorId = 101; msDbmsError = sMsg + "¡El saldo del documento en la moneda local, " + oDecimalFormat.format(dBalance) + ", " + "es distinto al total del mismo, " + oDecimalFormat.format(mdTotal_r) + "!"; throw new Exception(msDbmsError); } if (dBalanceCy != mdTotalCy_r) { mnDbmsErrorId = 101; msDbmsError = sMsg + "¡El saldo del documento en la moneda del documento, " + oDecimalFormat.format(dBalanceCy) + ", " + "es distinto al total del mismo, " + oDecimalFormat.format(mdTotalCy_r) + "!"; throw new Exception(msDbmsError); } } oStatement = poConnection.createStatement(); for (i = 201; i <= 224; i++) { switch (i) { case 201: sSql = "SELECT count(*) AS f_count FROM trn_dps_dps_supply WHERE id_src_year = " + mnPkYearId + " AND id_src_doc = " + mnPkDocId + " "; sMsgAux = "¡El documento tiene vínculo(s) con otro(s) documento(s) como origen!"; break; case 203: sSql = "SELECT count(*) AS f_count FROM trn_dps_dps_adj WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " "; sMsgAux = "¡El documento está asociado con otro documento de ajuste!"; break; case 205: sSql = "SELECT count(*) AS f_count FROM trn_diog WHERE fid_dps_year_n = " + mnPkYearId + " AND fid_dps_doc_n = " + mnPkDocId + " AND b_del = 0 "; sMsgAux = "¡El documento está asociado con un documento de entradas y salidas de mercancías!"; break; case 206: sSql = "SELECT count(*) AS f_count " + "FROM trn_diog AS d " + "INNER JOIN trn_diog_ety AS de ON d.id_year = de.id_year AND d.id_doc = de.id_doc " + "WHERE de.fid_dps_year_n = " + mnPkYearId + " AND de.fid_dps_doc_n = " + mnPkDocId + " AND de.fid_dps_adj_year_n IS NULL AND de.fid_dps_adj_doc_n IS NULL AND de.b_del = 0 AND d.b_del = 0 "; sMsgAux = "¡El documento está asociado con un surtido de almacén!"; break; case 207: sSql = "SELECT count(*) AS f_count " + "FROM trn_diog AS d " + "INNER JOIN trn_diog_ety AS de ON d.id_year = de.id_year AND d.id_doc = de.id_doc " + "WHERE de.fid_dps_year_n = " + mnPkYearId + " AND de.fid_dps_doc_n = " + mnPkDocId + " AND de.fid_dps_adj_year_n IS NOT NULL AND de.fid_dps_adj_doc_n IS NOT NULL AND de.b_del = 0 AND d.b_del = 0 "; sMsgAux = "¡El documento está asociado con una devolución de almacén como documento!"; break; case 208: sSql = "SELECT count(*) AS f_count " + "FROM trn_diog AS d " + "INNER JOIN trn_diog_ety AS de ON d.id_year = de.id_year AND d.id_doc = de.id_doc " + "WHERE de.fid_dps_adj_year_n = " + mnPkYearId + " AND de.fid_dps_adj_doc_n = " + mnPkDocId + " AND de.b_del = 0 AND d.b_del = 0 "; sMsgAux = "¡El documento está asociado con una devolución de almacén como documento de ajuste!"; break; case 209: sSql = "SELECT count(*) AS f_count " + "FROM mkt_comms " + "WHERE id_year = " + mnPkYearId + " AND id_doc = " + mnPkDocId + " AND b_del = 0 "; sMsgAux = "¡El documento está asociado con un documento de comisiones!"; break; case 210: // Not longer needed since September 2014, due to new commissions tables. break; case 211: sSql = "SELECT count(*) AS f_count FROM trn_dps_riss WHERE id_old_year = " + mnPkYearId + " AND id_old_doc = " + mnPkDocId + " "; sMsgAux = "¡El documento ha sido reimpreso!"; break; case 212: sSql = "SELECT count(*) AS f_count FROM trn_dps_riss WHERE id_new_year = " + mnPkYearId + " AND id_new_doc = " + mnPkDocId + " "; sMsgAux = "¡El documento es el reemplazo de otro documento!"; break; case 213: sSql = "SELECT count(*) AS f_count FROM trn_dps_repl WHERE id_old_year = " + mnPkYearId + " AND id_old_doc = " + mnPkDocId + " "; sMsgAux = "¡El documento ha sido sustituído!"; break; case 214: sSql = "SELECT count(*) AS f_count FROM trn_dps_repl WHERE id_new_year = " + mnPkYearId + " AND id_new_doc = " + mnPkDocId + " "; sMsgAux = "¡El documento es la sustitución de otro documento!"; break; case 215: sSql = "SELECT count(*) AS f_count FROM trn_dps_iog_chg WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " "; sMsgAux = "¡El documento está asociado con un cambio de compras-ventas!"; break; case 216: sSql = "SELECT count(*) AS f_count FROM trn_dps_iog_war WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " "; sMsgAux = "¡El documento está asociado con una garantía de compras-ventas!"; break; case 217: sSql = "SELECT count(*) AS f_count FROM trn_dsm_ety WHERE fid_src_dps_year_n = " + mnPkYearId + " AND fid_src_dps_doc_n = " + mnPkDocId + " AND b_del = 0 "; sMsgAux = "¡El documento está asociado con un movimiento de asociado de negocios como origen!"; break; case 218: sSql = "SELECT count(*) AS f_count FROM trn_dsm_ety WHERE fid_des_dps_year_n = " + mnPkYearId + " AND fid_des_dps_doc_n = " + mnPkDocId + " AND b_del = 0 "; sMsgAux = "¡El documento está asociado con un movimiento de asociado de negocios como destino!"; break; case 219: sSql = "SELECT count(*) AS f_count " + "FROM fin_rec AS r INNER JOIN fin_rec_ety AS re ON " + "r.id_year = re.id_year AND r.id_per = re.id_per AND r.id_bkc = re.id_bkc AND r.id_tp_rec = re.id_tp_rec AND r.id_num = re.id_num AND " + "r.b_del = 0 AND re.b_del = 0 AND re.fid_dps_year_n = " + mnPkYearId + " AND re.fid_dps_doc_n = " + mnPkDocId + " AND " + "r.id_tp_rec IN ('" + SDataConstantsSys.FINU_TP_REC_FY_OPEN + "', '" + SDataConstantsSys.FINU_TP_REC_FY_END + "') "; sMsgAux = "¡El documento está en uso por pólizas contables de cierre o apertura de ejercicio como documento!"; break; case 220: sSql = "SELECT count(*) AS f_count " + "FROM fin_rec AS r INNER JOIN fin_rec_ety AS re ON " + "r.id_year = re.id_year AND r.id_per = re.id_per AND r.id_bkc = re.id_bkc AND r.id_tp_rec = re.id_tp_rec AND r.id_num = re.id_num AND " + "r.b_del = 0 AND re.b_del = 0 AND re.fid_dps_adj_year_n = " + mnPkYearId + " AND re.fid_dps_adj_doc_n = " + mnPkDocId + " AND " + "r.id_tp_rec IN ('" + SDataConstantsSys.FINU_TP_REC_FY_OPEN + "', '" + SDataConstantsSys.FINU_TP_REC_FY_END + "') "; sMsgAux = "¡El documento está en uso por pólizas contables de cierre o apertura de ejercicio como documento de ajuste!"; break; case 221: if (isDocument() || isAdjustment()) { sSql = "SELECT count(*) AS f_count " + "FROM fin_rec AS r INNER JOIN fin_rec_ety AS re ON " + "r.id_year = re.id_year AND r.id_per = re.id_per AND r.id_bkc = re.id_bkc AND r.id_tp_rec = re.id_tp_rec AND r.id_num = re.id_num AND " + "r.b_del = 0 AND re.b_del = 0 AND re.fid_dps_year_n = " + mnPkYearId + " AND re.fid_dps_doc_n = " + mnPkDocId + " AND " + "re.fid_tp_acc_mov <> " + getAccountingMoveSubclassKey()[0] + " "; sMsgAux = "¡El documento está en uso por pólizas contables como documento!"; } else { sSql = ""; } break; case 222: if (isDocument() || isAdjustment()) { sSql = "SELECT count(*) AS f_count " + "FROM fin_rec AS r INNER JOIN fin_rec_ety AS re ON " + "r.id_year = re.id_year AND r.id_per = re.id_per AND r.id_bkc = re.id_bkc AND r.id_tp_rec = re.id_tp_rec AND r.id_num = re.id_num AND " + "r.b_del = 0 AND re.b_del = 0 AND re.fid_dps_adj_year_n = " + mnPkYearId + " AND re.fid_dps_adj_doc_n = " + mnPkDocId + " AND " + "re.fid_tp_acc_mov <> " + getAccountingMoveSubclassKey()[0] + " "; sMsgAux = "¡El documento está en uso por pólizas contables como documento de ajuste!"; } else { sSql = ""; } break; case 223: sSql = "SELECT count(*) AS f_count " + "FROM log_ship " + "WHERE b_del = 0 AND fk_ord_year_n = " + mnPkYearId + " AND fk_ord_doc_n = " + mnPkDocId + " "; sMsgAux = "¡El documento está asociado a un documento de embarques!"; break; case 224: sSql = "SELECT count(*) AS f_count " + "FROM log_ship AS d " + "INNER JOIN log_ship_dest_ety AS de ON d.id_ship = de.id_ship " + "WHERE d.b_del = 0 AND de.fk_dps_year_n = " + mnPkYearId + " AND de.fk_dps_doc_n = " + mnPkDocId + " "; sMsgAux = "¡El documento está asociado a una partida de un destino de un documento de embarques!"; break; default: sSql = ""; sMsgAux = ""; } if (sSql.length() > 0) { oResultSet = oStatement.executeQuery(sSql); if (oResultSet.next() && oResultSet.getInt("f_count") > 0) { mnDbmsErrorId = i; msDbmsError = sMsg + sMsgAux; throw new Exception(msDbmsError); } } } } return true; // if this line is reached, no errors were found } private boolean testRevertDeletion(java.lang.String psMsg, int pnAction) throws java.sql.SQLException, java.lang.Exception { if (pnAction == SDbConsts.ACTION_DELETE && !mbIsDeleted) { mnDbmsErrorId = 2; msDbmsError = psMsg + "El documento ya está desmarcado como eliminado."; throw new Exception(msDbmsError); } else if (pnAction == SDbConsts.ACTION_ANNUL && mnFkDpsStatusId != SDataConstantsSys.TRNS_ST_DPS_ANNULED) { mnDbmsErrorId = 1; msDbmsError = psMsg + "El documento ya está desmarcado como anulado."; throw new Exception(msDbmsError); } return true; // if this line is reached, no errors were found } private void calculateDpsTotal(erp.client.SClientInterface piClient_n, int pnDecs) throws SQLException, Exception { double dSubtotalProvisional = 0; double dDiscountDoc = 0; double dSubtotal = 0; double dTaxCharged = 0; double dTaxRetained = 0; double dTotal = 0; double dCommissions = 0; double dDifference = 0; SSessionItem oSessionItem = null; mdSubtotalProvisionalCy_r = 0; mdDiscountDocCy_r = 0; mdSubtotalCy_r = 0; mdTaxChargedCy_r = 0; mdTaxRetainedCy_r = 0; mdTotalCy_r = 0; mdCommissionsCy_r = 0; if (piClient_n != null) { pnDecs = piClient_n.getSessionXXX().getParamsErp().getDecimalsValue(); } else if (pnDecs == 0) { pnDecs = 2; } for (SDataDpsEntry entry : mvDbmsDpsEntries) { if (!entry.getIsDeleted()) { if (piClient_n != null) { oSessionItem = ((SSessionCustom) piClient_n.getSession().getSessionCustom()).getSessionItem(entry.getFkItemId()); if (oSessionItem.getFkUnitAlternativeTypeId() != SDataConstantsSys.ITMU_TP_UNIT_NA && oSessionItem.getUnitAlternativeBaseEquivalence() == 0) { entry.setAuxPreserveQuantity(true); } entry.calculateTotal(piClient_n, mtDate, mnFkTaxIdentityEmisorTypeId, mnFkTaxIdentityReceptorTypeId, mbIsDiscountDocPercentage, mdDiscountDocPercentage, mdExchangeRate); } if (entry.isAccountable()) { mdSubtotalProvisionalCy_r += entry.getSubtotalProvisionalCy_r(); mdDiscountDocCy_r += entry.getDiscountDocCy(); mdSubtotalCy_r += entry.getSubtotalCy_r(); mdTaxChargedCy_r += entry.getTaxChargedCy_r(); mdTaxRetainedCy_r += entry.getTaxRetainedCy_r(); mdTotalCy_r += entry.getTotalCy_r(); mdCommissionsCy_r += entry.getCommissionsCy_r(); dSubtotalProvisional += entry.getSubtotalProvisional_r(); dDiscountDoc += entry.getDiscountDoc(); dSubtotal += entry.getSubtotal_r(); dTaxCharged += entry.getTaxCharged_r(); dTaxRetained += entry.getTaxRetained_r(); dTotal += entry.getTotal_r(); dCommissions += entry.getCommissions_r(); } } } /* * DOCUMENT'S DOMESTIC CURRENCY VALUE CALCULATION NOTES: * Total value of document in domestic currency must be calculated as following, * in order to prevent decimal differences due to exchange rate when document * was emited in foreign currencies. */ // Total: mdTotal_r = SLibUtilities.round(mdTotalCy_r * mdExchangeRate, pnDecs); // Taxes: mdTaxCharged_r = dTaxCharged; mdTaxRetained_r = dTaxRetained; // Subtotal: mdSubtotal_r = SLibUtilities.round(mdTotal_r - mdTaxCharged_r + mdTaxRetained_r, pnDecs); mdDiscountDoc_r = SLibUtilities.round(mdDiscountDocCy_r * mdExchangeRate, pnDecs); mdSubtotalProvisional_r = SLibUtilities.round(mdSubtotal_r + mdDiscountDoc_r, pnDecs); // Commissions: mdCommissions_r = SLibUtilities.round(mdCommissionsCy_r * mdExchangeRate, pnDecs); // Adjust any exchange rate difference: dDifference = SLibUtilities.round(mdSubtotal_r - dSubtotal, pnDecs); if (dDifference != 0) { SDataDpsEntry greaterEntry = null; // Find greater document entry: for (SDataDpsEntry entry : mvDbmsDpsEntries) { if (entry.isAccountable()) { if (greaterEntry == null) { greaterEntry = entry; } else { if (entry.getSubtotal_r() > greaterEntry.getSubtotal_r()) { greaterEntry = entry; } } } } // Adjust decimal differences in domestic currency: if (greaterEntry != null) { greaterEntry.setIsRegistryEdited(true); greaterEntry.setSubtotal_r(SLibUtilities.round(greaterEntry.getSubtotal_r() + dDifference, pnDecs)); greaterEntry.setSubtotalProvisional_r(SLibUtilities.round(greaterEntry.getSubtotalProvisional_r() + dDifference, pnDecs)); } } } private int getBizPartnerCategoryId() { int type = SDataConstantsSys.UNDEFINED; if (isDocumentPur() || isAdjustmentPur()) { type = SDataConstantsSys.BPSS_CT_BP_SUP; } else if (isDocumentSal() || isAdjustmentSal()) { type = SDataConstantsSys.BPSS_CT_BP_CUS; } return type; } private int getItemAccountTypeId(erp.mtrn.data.SDataDpsEntry entry) { int type = SDataConstantsSys.UNDEFINED; if (isDocumentPur()) { type = SDataConstantsSys.FINS_TP_ACC_ITEM_PUR; } else if (isDocumentSal()) { type = SDataConstantsSys.FINS_TP_ACC_ITEM_SAL; } else if (isAdjustmentPur()) { type = entry.getFkDpsAdjustmentTypeId() == SDataConstantsSys.TRNS_TP_DPS_ADJ_RET ? SDataConstantsSys.FINS_TP_ACC_ITEM_PUR_ADJ_DEV : SDataConstantsSys.FINS_TP_ACC_ITEM_PUR_ADJ_DISC; } else if (isAdjustmentSal()) { type = entry.getFkDpsAdjustmentTypeId() == SDataConstantsSys.TRNS_TP_DPS_ADJ_RET ? SDataConstantsSys.FINS_TP_ACC_ITEM_SAL_ADJ_DEV : SDataConstantsSys.FINS_TP_ACC_ITEM_SAL_ADJ_DISC; } return type; } private int[] getSystemAccountTypeKey() { int[] type = null; if (isDocumentPur() || isAdjustmentPur()) { type = SModSysConsts.FINS_TP_SYS_ACC_BPR_SUP_BAL; } else if (isDocumentSal() || isAdjustmentSal()) { type = SModSysConsts.FINS_TP_SYS_ACC_BPR_CUS_BAL; } else { type = SModSysConsts.FINS_TP_SYS_ACC_NA_NA; } return type; } private int getAccountSystemTypeForBizPartnerXXX() { int systemType = SLibConstants.UNDEFINED; if (isDocumentPur() || isAdjustmentPur()) { systemType = SDataConstantsSys.FINS_TP_ACC_SYS_SUP; } else if (isDocumentSal() || isAdjustmentSal()) { systemType = SDataConstantsSys.FINS_TP_ACC_SYS_CUS; } return systemType; } private int[] getSystemMoveTypeForBizPartner() { int[] type = SModSysConsts.FINS_TP_SYS_MOV_JOU_DBT; if (isDocumentPur()) { type = SModSysConsts.FINS_TP_SYS_MOV_PUR; } else if (isAdjustmentPur()) { if (SLibUtils.compareKeys(getDpsTypeKey(), SDataConstantsSys.TRNU_TP_DPS_PUR_CN)) { type = SModSysConsts.FINS_TP_SYS_MOV_PUR_DEC; } else { type = SModSysConsts.FINS_TP_SYS_MOV_PUR_INC; } } else if (isDocumentSal()) { type = SModSysConsts.FINS_TP_SYS_MOV_SAL; } else if (isAdjustmentSal()) { if (SLibUtils.compareKeys(getDpsTypeKey(), SDataConstantsSys.TRNU_TP_DPS_SAL_CN)) { type = SModSysConsts.FINS_TP_SYS_MOV_SAL_DEC; } else { type = SModSysConsts.FINS_TP_SYS_MOV_SAL_INC; } } return type; } private int[] getSystemMoveTypeForBizPartnerXXX() { int[] type = SDataConstantsSys.FINS_TP_SYS_MOV_NA; if (isDocumentPur() || isAdjustmentPur()) { type = SDataConstantsSys.FINS_TP_SYS_MOV_BPS_SUP; } else if (isDocumentSal() || isAdjustmentSal()) { type = SDataConstantsSys.FINS_TP_SYS_MOV_BPS_CUS; } return type; } private int[] getSystemMoveTypeForItem(final int adjustmentType) { int[] type = SModSysConsts.FINS_TP_SYS_MOV_JOU_DBT; if (isDocumentPur()) { type = SModSysConsts.FINS_TP_SYS_MOV_PUR; } else if (isAdjustmentPur()) { if (SLibUtils.compareKeys(getDpsTypeKey(), SDataConstantsSys.TRNU_TP_DPS_PUR_CN)) { type = adjustmentType == SDataConstantsSys.TRNS_TP_DPS_ADJ_DISC ? SModSysConsts.FINS_TP_SYS_MOV_PUR_DEC_DIS : SModSysConsts.FINS_TP_SYS_MOV_PUR_DEC_RET; } else { type = adjustmentType == SDataConstantsSys.TRNS_TP_DPS_ADJ_DISC ? SModSysConsts.FINS_TP_SYS_MOV_PUR_INC_INC : SModSysConsts.FINS_TP_SYS_MOV_PUR_INC_ADD; } } else if (isDocumentSal()) { type = SModSysConsts.FINS_TP_SYS_MOV_SAL; } else if (isAdjustmentSal()) { if (SLibUtils.compareKeys(getDpsTypeKey(), SDataConstantsSys.TRNU_TP_DPS_SAL_CN)) { type = adjustmentType == SDataConstantsSys.TRNS_TP_DPS_ADJ_DISC ? SModSysConsts.FINS_TP_SYS_MOV_SAL_DEC_DIS : SModSysConsts.FINS_TP_SYS_MOV_SAL_DEC_RET; } else { type = adjustmentType == SDataConstantsSys.TRNS_TP_DPS_ADJ_DISC ? SModSysConsts.FINS_TP_SYS_MOV_SAL_INC_INC : SModSysConsts.FINS_TP_SYS_MOV_SAL_INC_ADD; } } return type; } private int[] getSystemMoveTypeForItemXXX() { return SDataConstantsSys.FINS_TP_SYS_MOV_NA; } private int[] getSystemMoveTypeForTax(final int taxType, final int taxAppType) { int[] type = SModSysConsts.FINS_TP_SYS_MOV_JOU_DBT; if (isDocumentPur() || isAdjustmentPur()) { if (taxType == SModSysConsts.FINS_TP_TAX_CHARGED) { type = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SModSysConsts.FINS_TP_SYS_MOV_PUR_TAX_DBT_PAI : SModSysConsts.FINS_TP_SYS_MOV_PUR_TAX_DBT_PEN; } else { type = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SModSysConsts.FINS_TP_SYS_MOV_PUR_TAX_CDT_PAI : SModSysConsts.FINS_TP_SYS_MOV_PUR_TAX_CDT_PEN; } } else if (isDocumentSal() || isAdjustmentSal()) { if (taxType == SModSysConsts.FINS_TP_TAX_CHARGED) { type = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SModSysConsts.FINS_TP_SYS_MOV_SAL_TAX_CDT_PAI : SModSysConsts.FINS_TP_SYS_MOV_SAL_TAX_CDT_PEN; } else { type = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SModSysConsts.FINS_TP_SYS_MOV_SAL_TAX_DBT_PAI : SModSysConsts.FINS_TP_SYS_MOV_SAL_TAX_DBT_PEN; } } return type; } private int[] getSystemMoveTypeForTaxXXX(final int taxType, final int taxAppType) { int[] type = SDataConstantsSys.FINS_TP_SYS_MOV_NA; if (isDocumentPur() || isAdjustmentPur()) { if (taxType == SModSysConsts.FINS_TP_TAX_CHARGED) { type = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SDataConstantsSys.FINS_TP_SYS_MOV_TAX_DBT : SDataConstantsSys.FINS_TP_SYS_MOV_TAX_DBT_PEND; } else { type = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SDataConstantsSys.FINS_TP_SYS_MOV_TAX_CDT : SDataConstantsSys.FINS_TP_SYS_MOV_TAX_CDT_PEND; } } else if (isDocumentSal() || isAdjustmentSal()) { if (taxType == SModSysConsts.FINS_TP_TAX_CHARGED) { type = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SDataConstantsSys.FINS_TP_SYS_MOV_TAX_CDT : SDataConstantsSys.FINS_TP_SYS_MOV_TAX_CDT_PEND; } else { type = taxAppType == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SDataConstantsSys.FINS_TP_SYS_MOV_TAX_DBT : SDataConstantsSys.FINS_TP_SYS_MOV_TAX_DBT_PEND; } } return type; } /* * Public functions */ public int[] getAccountingMoveSubclassKey() { int[] moveSubclassKey = null; if (isDocumentPur()) { moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_PUR; } else if (isAdjustmentPur()) { moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_PUR_ADJ_DISC; } else if (isDocumentSal()) { moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_SAL; } else if (isAdjustmentSal()) { moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_SAL_ADJ_DISC; } return moveSubclassKey; } public int[] getAccountingMoveSubclassKeyForAdjs() { int[] moveSubclassKey = null; if (isDocumentPur()) { moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_PUR_ADJ_DISC; } else if (isDocumentSal()) { moveSubclassKey = SDataConstantsSys.FINS_CLS_ACC_MOV_SAL_ADJ_DISC; } return moveSubclassKey; } public boolean isForSales() { return mnFkDpsCategoryId == SDataConstantsSys.TRNS_CT_DPS_SAL; } public boolean isForPurchases() { return mnFkDpsCategoryId == SDataConstantsSys.TRNS_CT_DPS_PUR; } public boolean isDocument() { return isDocumentPur() || isDocumentSal(); } public boolean isDocumentPur() { return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_PUR_DOC); } public boolean isDocumentSal() { return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_SAL_DOC); } public boolean isDocumentOrAdjustment() { return isDocument() || isAdjustment(); } public boolean isDocumentOrAdjustmentPur() { return isDocumentPur() || isAdjustmentPur(); } public boolean isDocumentOrAdjustmentSal() { return isDocumentSal() || isAdjustmentSal(); } public boolean isAdjustment() { return isAdjustmentPur() || isAdjustmentSal(); } public boolean isAdjustmentPur() { return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ); } public boolean isAdjustmentSal() { return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ); } public boolean isOrder() { return isOrderPur() || isOrderSal(); } public boolean isOrderPur() { return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_PUR_ORD); } public boolean isOrderSal() { return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_SAL_ORD); } public boolean isEstimate() { return isEstimatePur() || isEstimateSal(); } public boolean isEstimatePur() { return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_PUR_EST); } public boolean isEstimateSal() { return SLibUtilities.compareKeys(getDpsClassKey(), SDataConstantsSys.TRNS_CL_DPS_SAL_EST); } public int[] getDpsCategoryKey() { return new int[] { mnFkDpsCategoryId }; } public int[] getDpsClassKey() { return new int[] { mnFkDpsCategoryId, mnFkDpsClassId }; } public int[] getDpsTypeKey() { return new int[] { mnFkDpsCategoryId, mnFkDpsClassId, mnFkDpsTypeId }; } public void setPkYearId(int n) { mnPkYearId = n; } public void setPkDocId(int n) { mnPkDocId = n; } public void setDate(java.util.Date t) { mtDate = t; } public void setDateDoc(java.util.Date t) { mtDateDoc = t; } public void setDateStartCredit(java.util.Date t) { mtDateStartCredit = t; } public void setDateShipment_n(java.util.Date t) { mtDateShipment_n = t; } public void setDateDelivery_n(java.util.Date t) { mtDateDelivery_n = t; } public void setDateDocLapsing_n(java.util.Date t) { mtDateDocLapsing_n = t; } public void setDateDocDelivery_n(java.util.Date t) { mtDateDocDelivery_n = t; } public void setNumberSeries(java.lang.String s) { msNumberSeries = s; } public void setNumber(java.lang.String s) { msNumber = s; } public void setNumberReference(java.lang.String s) { msNumberReference = s; } public void setCommissionsReference(java.lang.String s) { msCommissionsReference = s; } public void setApproveYear(int n) { mnApproveYear = n; } public void setApproveNumber(int n) { mnApproveNumber = n; } public void setDaysOfCredit(int n) { mnDaysOfCredit = n; } public void setIsDiscountDocApplying(boolean b) { mbIsDiscountDocApplying = b; } public void setIsDiscountDocPercentage(boolean b) { mbIsDiscountDocPercentage = b; } public void setDiscountDocPercentage(double d) { mdDiscountDocPercentage = d; } public void setSubtotalProvisional_r(double d) { mdSubtotalProvisional_r = d; } public void setDiscountDoc_r(double d) { mdDiscountDoc_r = d; } public void setSubtotal_r(double d) { mdSubtotal_r = d; } public void setTaxCharged_r(double d) { mdTaxCharged_r = d; } public void setTaxRetained_r(double d) { mdTaxRetained_r = d; } public void setTotal_r(double d) { mdTotal_r = d; } public void setCommissions_r(double d) { mdCommissions_r = d; } public void setExchangeRate(double d) { mdExchangeRate = d; } public void setExchangeRateSystem(double d) { mdExchangeRateSystem = d; } public void setSubtotalProvisionalCy_r(double d) { mdSubtotalProvisionalCy_r = d; } public void setDiscountDocCy_r(double d) { mdDiscountDocCy_r = d; } public void setSubtotalCy_r(double d) { mdSubtotalCy_r = d; } public void setTaxChargedCy_r(double d) { mdTaxChargedCy_r = d; } public void setTaxRetainedCy_r(double d) { mdTaxRetainedCy_r = d; } public void setTotalCy_r(double d) { mdTotalCy_r = d; } public void setCommissionsCy_r(double d) { mdCommissionsCy_r = d; } public void setDriver(java.lang.String s) { msDriver = s; } public void setPlate(java.lang.String s) { msPlate = s; } public void setTicket(java.lang.String s) { msTicket = s; } public void setShipments(int n) { mnShipments = n; } public void setPayments(int n) { mnPayments = n; } public void setPaymentMethod(java.lang.String s) { msPaymentMethod = s; } public void setPaymentAccount(java.lang.String s) { msPaymentAccount = s; } public void setIsPublic(boolean b) { mbIsPublic = b; } public void setIsLinked(boolean b) { mbIsLinked = b; } public void setIsClosed(boolean b) { mbIsClosed = b; } public void setIsClosedCommissions(boolean b) { mbIsClosedCommissions = b; } public void setIsShipped(boolean b) { mbIsShipped = b; } public void setIsRebill(boolean b) { mbIsRebill = b; } public void setIsAudited(boolean b) { mbIsAudited = b; } public void setIsAuthorized(boolean b) { mbIsAuthorized = b; } public void setIsRecordAutomatic(boolean b) { mbIsRecordAutomatic = b; } public void setIsCopy(boolean b) { mbIsCopy = b; } public void setIsCopied(boolean b) { mbIsCopied = b; } public void setIsSystem(boolean b) { mbIsSystem = b; } public void setIsDeleted(boolean b) { mbIsDeleted = b; } public void setFkDpsCategoryId(int n) { mnFkDpsCategoryId = n; } public void setFkDpsClassId(int n) { mnFkDpsClassId = n; } public void setFkDpsTypeId(int n) { mnFkDpsTypeId = n; } public void setFkPaymentTypeId(int n) { mnFkPaymentTypeId = n; } public void setFkPaymentSystemTypeId(int n) { mnFkPaymentSystemTypeId = n; } public void setFkDpsStatusId(int n) { mnFkDpsStatusId = n; } public void setFkDpsValidityStatusId(int n) { mnFkDpsValidityStatusId = n; } public void setFkDpsAuthorizationStatusId(int n) { mnFkDpsAuthorizationStatusId = n; } public void setFkDpsNatureId(int n) { mnFkDpsNatureId = n; } public void setFkCompanyBranchId(int n) { mnFkCompanyBranchId = n; } public void setFkBizPartnerId_r(int n) { mnFkBizPartnerId_r = n; } public void setFkBizPartnerBranchId(int n) { mnFkBizPartnerBranchId = n; } public void setFkBizPartnerBranchAddressId(int n) { mnFkBizPartnerBranchAddressId = n; } public void setFkBizPartnerAltId_r(int n) { mnFkBizPartnerAltId_r = n; } public void setFkBizPartnerBranchAltId(int n) { mnFkBizPartnerBranchAltId = n; } public void setFkBizPartnerBranchAddressAltId(int n) { mnFkBizPartnerBranchAddressAltId = n; } public void setFkContactBizPartnerBranchId_n(int n) { mnFkContactBizPartnerBranchId_n = n; } public void setFkContactContactId_n(int n) { mnFkContactContactId_n = n; } public void setFkTaxIdentityEmisorTypeId(int n) { mnFkTaxIdentityEmisorTypeId = n; } public void setFkTaxIdentityReceptorTypeId(int n) { mnFkTaxIdentityReceptorTypeId = n; } public void setFkLanguajeId(int n) { mnFkLanguajeId = n; } public void setFkCurrencyId(int n) { mnFkCurrencyId = n; } public void setFkSalesAgentId_n(int n) { mnFkSalesAgentId_n = n; } public void setFkSalesAgentBizPartnerId_n(int n) { mnFkSalesAgentBizPartnerId_n = n; } public void setFkSalesSupervisorId_n(int n) { mnFkSalesSupervisorId_n = n; } public void setFkSalesSupervisorBizPartnerId_n(int n) { mnFkSalesSupervisorBizPartnerId_n = n; } public void setFkIncotermId(int n) { mnFkIncotermId = n; } public void setFkSpotSourceId_n(int n) { mnFkSpotSourceId_n = n; } public void setFkSpotDestinyId_n(int n) { mnFkSpotDestinyId_n = n; } public void setFkModeOfTransportationTypeId(int n) { mnFkModeOfTransportationTypeId = n; } public void setFkCarrierTypeId(int n) { mnFkCarrierTypeId = n; } public void setFkCarrierId_n(int n) { mnFkCarrierId_n = n; } public void setFkVehicleTypeId_n(int n) { mnFkVehicleTypeId_n = n; } public void setFkVehicleId_n(int n) { mnFkVehicleId_n = n; } public void setFkSourceYearId_n(int n) { mnFkSourceYearId_n = n; } public void setFkSourceDocId_n(int n) { mnFkSourceDocId_n = n; } public void setFkMfgYearId_n(int n) { mnFkMfgYearId_n = n; } public void setFkMfgOrderId_n(int n) { mnFkMfgOrderId_n = n; } public void setFkUserLinkedId(int n) { mnFkUserLinkedId = n; } public void setFkUserClosedId(int n) { mnFkUserClosedId = n; } public void setFkUserClosedCommissionsId(int n) { mnFkUserClosedCommissionsId = n; } public void setFkUserShippedId(int n) { mnFkUserShippedId = n; } public void setFkUserAuditedId(int n) { mnFkUserAuditedId = n; } public void setFkUserAuthorizedId(int n) { mnFkUserAuthorizedId = n; } public void setFkUserNewId(int n) { mnFkUserNewId = n; } public void setFkUserEditId(int n) { mnFkUserEditId = n; } public void setFkUserDeleteId(int n) { mnFkUserDeleteId = n; } public void setUserLinkedTs(java.util.Date t) { mtUserLinkedTs = t; } public void setUserClosedTs(java.util.Date t) { mtUserClosedTs = t; } public void setUserClosedCommissionsTs(java.util.Date t) { mtUserClosedCommissionsTs = t; } public void setUserShippedTs(java.util.Date t) { mtUserShippedTs = t; } public void setUserAuditedTs(java.util.Date t) { mtUserAuditedTs = t; } public void setUserAuthorizedTs(java.util.Date t) { mtUserAuthorizedTs = t; } public void setUserNewTs(java.util.Date t) { mtUserNewTs = t; } public void setUserEditTs(java.util.Date t) { mtUserEditTs = t; } public void setUserDeleteTs(java.util.Date t) { mtUserDeleteTs = t; } public int getPkYearId() { return mnPkYearId; } public int getPkDocId() { return mnPkDocId; } public java.util.Date getDate() { return mtDate; } public java.util.Date getDateDoc() { return mtDateDoc; } public java.util.Date getDateStartCredit() { return mtDateStartCredit; } public java.util.Date getDateShipment_n() { return mtDateShipment_n; } public java.util.Date getDateDelivery_n() { return mtDateDelivery_n; } public java.util.Date getDateDocLapsing_n() { return mtDateDocLapsing_n; } public java.util.Date getDateDocDelivery_n() { return mtDateDocDelivery_n; } public java.lang.String getNumberSeries() { return msNumberSeries; } public java.lang.String getNumber() { return msNumber; } public java.lang.String getNumberReference() { return msNumberReference; } public java.lang.String getCommissionsReference() { return msCommissionsReference; } public int getApproveYear() { return mnApproveYear; } public int getApproveNumber() { return mnApproveNumber; } public int getDaysOfCredit() { return mnDaysOfCredit; } public boolean getIsDiscountDocApplying() { return mbIsDiscountDocApplying; } public boolean getIsDiscountDocPercentage() { return mbIsDiscountDocPercentage; } public double getDiscountDocPercentage() { return mdDiscountDocPercentage; } public double getSubtotalProvisional_r() { return mdSubtotalProvisional_r; } public double getDiscountDoc_r() { return mdDiscountDoc_r; } public double getSubtotal_r() { return mdSubtotal_r; } public double getTaxCharged_r() { return mdTaxCharged_r; } public double getTaxRetained_r() { return mdTaxRetained_r; } public double getTotal_r() { return mdTotal_r; } public double getCommissions_r() { return mdCommissions_r; } public double getExchangeRate() { return mdExchangeRate; } public double getExchangeRateSystem() { return mdExchangeRateSystem; } public double getSubtotalProvisionalCy_r() { return mdSubtotalProvisionalCy_r; } public double getDiscountDocCy_r() { return mdDiscountDocCy_r; } public double getSubtotalCy_r() { return mdSubtotalCy_r; } public double getTaxChargedCy_r() { return mdTaxChargedCy_r; } public double getTaxRetainedCy_r() { return mdTaxRetainedCy_r; } public double getTotalCy_r() { return mdTotalCy_r; } public double getCommissionsCy_r() { return mdCommissionsCy_r; } public java.lang.String getDriver() { return msDriver; } public java.lang.String getPlate() { return msPlate; } public java.lang.String getTicket() { return msTicket; } public int getShipments() { return mnShipments; } public int getPayments() { return mnPayments; } public java.lang.String getPaymentMethod() { return msPaymentMethod; } public java.lang.String getPaymentAccount() { return msPaymentAccount; } public boolean getIsPublic() { return mbIsPublic; } public boolean getIsLinked() { return mbIsLinked; } public boolean getIsClosed() { return mbIsClosed; } public boolean getIsClosedCommissions() { return mbIsClosedCommissions; } public boolean getIsShipped() { return mbIsShipped; } public boolean getIsRebill() { return mbIsRebill; } public boolean getIsAudited() { return mbIsAudited; } public boolean getIsAuthorized() { return mbIsAuthorized; } public boolean getIsRecordAutomatic() { return mbIsRecordAutomatic; } public boolean getIsCopy() { return mbIsCopy; } public boolean getIsCopied() { return mbIsCopied; } public boolean getIsSystem() { return mbIsSystem; } public boolean getIsDeleted() { return mbIsDeleted; } public int getFkDpsCategoryId() { return mnFkDpsCategoryId; } public int getFkDpsClassId() { return mnFkDpsClassId; } public int getFkDpsTypeId() { return mnFkDpsTypeId; } public int getFkPaymentTypeId() { return mnFkPaymentTypeId; } public int getFkPaymentSystemTypeId() { return mnFkPaymentSystemTypeId; } public int getFkDpsStatusId() { return mnFkDpsStatusId; } public int getFkDpsValidityStatusId() { return mnFkDpsValidityStatusId; } public int getFkDpsAuthorizationStatusId() { return mnFkDpsAuthorizationStatusId; } public int getFkDpsNatureId() { return mnFkDpsNatureId; } public int getFkCompanyBranchId() { return mnFkCompanyBranchId; } public int getFkBizPartnerId_r() { return mnFkBizPartnerId_r; } public int getFkBizPartnerBranchId() { return mnFkBizPartnerBranchId; } public int getFkBizPartnerBranchAddressId() { return mnFkBizPartnerBranchAddressId; } public int getFkBizPartnerAltId_r() { return mnFkBizPartnerAltId_r; } public int getFkBizPartnerBranchAltId() { return mnFkBizPartnerBranchAltId; } public int getFkBizPartnerBranchAddressAltId() { return mnFkBizPartnerBranchAddressAltId; } public int getFkContactBizPartnerBranchId_n() { return mnFkContactBizPartnerBranchId_n; } public int getFkContactContactId_n() { return mnFkContactContactId_n; } public int getFkTaxIdentityEmisorTypeId() { return mnFkTaxIdentityEmisorTypeId; } public int getFkTaxIdentityReceptorTypeId() { return mnFkTaxIdentityReceptorTypeId; } public int getFkLanguajeId() { return mnFkLanguajeId; } public int getFkCurrencyId() { return mnFkCurrencyId; } public int getFkSalesAgentId_n() { return mnFkSalesAgentId_n; } public int getFkSalesAgentBizPartnerId_n() { return mnFkSalesAgentBizPartnerId_n; } public int getFkSalesSupervisorId_n() { return mnFkSalesSupervisorId_n; } public int getFkSalesSupervisorBizPartnerId_n() { return mnFkSalesSupervisorBizPartnerId_n; } public int getFkIncotermId() { return mnFkIncotermId; } public int getFkSpotSourceId_n() { return mnFkSpotSourceId_n; } public int getFkSpotDestinyId_n() { return mnFkSpotDestinyId_n; } public int getFkModeOfTransportationTypeId() { return mnFkModeOfTransportationTypeId; } public int getFkCarrierTypeId() { return mnFkCarrierTypeId; } public int getFkCarrierId_n() { return mnFkCarrierId_n; } public int getFkVehicleTypeId_n() { return mnFkVehicleTypeId_n; } public int getFkVehicleId_n() { return mnFkVehicleId_n; } public int getFkSourceYearId_n() { return mnFkSourceYearId_n; } public int getFkSourceDocId_n() { return mnFkSourceDocId_n; } public int getFkMfgYearId_n() { return mnFkMfgYearId_n; } public int getFkMfgOrderId_n() { return mnFkMfgOrderId_n; } public int getFkUserLinkedId() { return mnFkUserLinkedId; } public int getFkUserClosedId() { return mnFkUserClosedId; } public int getFkUserClosedCommissionsId() { return mnFkUserClosedCommissionsId; } public int getFkUserShippedId() { return mnFkUserShippedId; } public int getFkUserAuditedId() { return mnFkUserAuditedId; } public int getFkUserAuthorizedId() { return mnFkUserAuthorizedId; } public int getFkUserNewId() { return mnFkUserNewId; } public int getFkUserEditId() { return mnFkUserEditId; } public int getFkUserDeleteId() { return mnFkUserDeleteId; } public java.util.Date getUserLinkedTs() { return mtUserLinkedTs; } public java.util.Date getUserClosedTs() { return mtUserClosedTs; } public java.util.Date getUserClosedCommissionsTs() { return mtUserClosedCommissionsTs; } public java.util.Date getUserShippedTs() { return mtUserShippedTs; } public java.util.Date getUserAuditedTs() { return mtUserAuditedTs; } public java.util.Date getUserAuthorizedTs() { return mtUserAuthorizedTs; } public java.util.Date getUserNewTs() { return mtUserNewTs; } public java.util.Date getUserEditTs() { return mtUserEditTs; } public java.util.Date getUserDeleteTs() { return mtUserDeleteTs; } public java.util.Vector<erp.mtrn.data.SDataDpsEntry> getDbmsDpsEntries() { return mvDbmsDpsEntries; } public java.util.Vector<erp.mtrn.data.SDataDpsNotes> getDbmsDpsNotes() { return mvDbmsDpsNotes; } public void setDbmsRecordKey(java.lang.Object o) { moDbmsRecordKey = o; } public void setDbmsRecordDate(java.util.Date t) { mtDbmsRecordDate = t; } public void setDbmsCurrency(java.lang.String s) { msDbmsCurrency = s; } public void setDbmsCurrencyKey(java.lang.String s) { msDbmsCurrencyKey = s; } public void setAuxIsFormerRecordAutomatic(boolean b) { mbAuxIsFormerRecordAutomatic = b; } public void setAuxFormerRecordKey(java.lang.Object o) { moAuxFormerRecordKey = o; } public void setAuxCfdParams(erp.mtrn.data.SCfdParams o) { moAuxCfdParams = o; } public void setAuxIsNeedCfd(boolean b) { mbAuxIsNeedCfd = b; } public void setAuxIsValidate(boolean b) { mbAuxIsValidate = b; } public void setDbmsDataAddenda(erp.mtrn.data.SDataDpsAddenda o) { moDbmsDataAddenda = o; } public void setDbmsDataCfd(erp.mtrn.data.SDataCfd o) { moDbmsDataCfd = o; } public java.lang.Object getDbmsRecordKey() { return moDbmsRecordKey; } public java.util.Date getDbmsRecordDate() { return mtDbmsRecordDate; } public java.lang.String getDbmsCurrency() { return msDbmsCurrency; } public java.lang.String getDbmsCurrencyKey() { return msDbmsCurrencyKey; } public boolean getAuxIsFormerRecordAutomatic() { return mbAuxIsFormerRecordAutomatic; } public java.lang.Object getAuxFormerRecordKey() { return moAuxFormerRecordKey; } public erp.mtrn.data.SCfdParams getAuxCfdParams() { return moAuxCfdParams; } public boolean getAuxIsNeedCfd() { return mbAuxIsNeedCfd; } public boolean getAuxIsValidate() { return mbAuxIsValidate; } public erp.mtrn.data.SDataDpsAddenda getDbmsDataAddenda() { return moDbmsDataAddenda; } public erp.mtrn.data.SDataCfd getDbmsDataCfd() { return moDbmsDataCfd; } public erp.mtrn.data.SDataDpsEntry getDbmsDpsEntry(int[] pk) { SDataDpsEntry entry = null; for (SDataDpsEntry e : mvDbmsDpsEntries) { if (SLibUtilities.compareKeys(pk, e.getPrimaryKey())) { entry = e; break; } } return entry; } public erp.mtrn.data.SDataDpsNotes getDbmsDpsNotes(int[] pk) { SDataDpsNotes notes = null; for (SDataDpsNotes n : mvDbmsDpsNotes) { if (SLibUtilities.compareKeys(pk, n.getPrimaryKey())) { notes = n; break; } } return notes; } public java.lang.String getDpsNumber() { return STrnUtils.formatDocNumber(msNumberSeries, msNumber); } @Override public void setPrimaryKey(java.lang.Object pk) { mnPkYearId = ((int[]) pk)[0]; mnPkDocId = ((int[]) pk)[1]; } @Override public java.lang.Object getPrimaryKey() { return new int[] { mnPkYearId, mnPkDocId }; } @Override public final void reset() { super.resetRegistry(); mnPkYearId = 0; mnPkDocId = 0; mtDate = null; mtDateDoc = null; mtDateStartCredit = null; mtDateShipment_n = null; mtDateDelivery_n = null; mtDateDocLapsing_n = null; mtDateDocDelivery_n = null; msNumberSeries = ""; msNumber = ""; msNumberReference = ""; msCommissionsReference = ""; mnApproveYear = 0; mnApproveNumber = 0; mnDaysOfCredit = 0; mbIsDiscountDocApplying = false; mbIsDiscountDocPercentage = false; mdDiscountDocPercentage = 0; mdSubtotalProvisional_r = 0; mdDiscountDoc_r = 0; mdSubtotal_r = 0; mdTaxCharged_r = 0; mdTaxRetained_r = 0; mdTotal_r = 0; mdCommissions_r = 0; mdExchangeRate = 0; mdExchangeRateSystem = 0; mdSubtotalProvisionalCy_r = 0; mdDiscountDocCy_r = 0; mdSubtotalCy_r = 0; mdTaxChargedCy_r = 0; mdTaxRetainedCy_r = 0; mdTotalCy_r = 0; mdCommissionsCy_r = 0; msDriver = ""; msPlate = ""; msTicket = ""; mnShipments = 0; mnPayments = 0; msPaymentMethod = ""; msPaymentAccount = ""; mbIsPublic = false; mbIsLinked = false; mbIsClosed = false; mbIsClosedCommissions = false; mbIsShipped = false; mbIsRebill = false; mbIsAudited = false; mbIsAuthorized = false; mbIsRecordAutomatic = false; mbIsCopy = false; mbIsCopied = false; mbIsSystem = false; mbIsDeleted = false; mnFkDpsCategoryId = 0; mnFkDpsClassId = 0; mnFkDpsTypeId = 0; mnFkPaymentTypeId = 0; mnFkPaymentSystemTypeId = 0; mnFkDpsStatusId = 0; mnFkDpsValidityStatusId = 0; mnFkDpsAuthorizationStatusId = 0; mnFkDpsNatureId = 0; mnFkCompanyBranchId = 0; mnFkBizPartnerId_r = 0; mnFkBizPartnerBranchId = 0; mnFkBizPartnerBranchAddressId = 0; mnFkBizPartnerAltId_r = 0; mnFkBizPartnerBranchAltId = 0; mnFkBizPartnerBranchAddressAltId = 0; mnFkContactBizPartnerBranchId_n = 0; mnFkContactContactId_n = 0; mnFkTaxIdentityEmisorTypeId = 0; mnFkTaxIdentityReceptorTypeId = 0; mnFkLanguajeId = 0; mnFkCurrencyId = 0; mnFkSalesAgentId_n = 0; mnFkSalesAgentBizPartnerId_n = 0; mnFkSalesSupervisorId_n = 0; mnFkSalesSupervisorBizPartnerId_n = 0; mnFkIncotermId = 0; mnFkSpotSourceId_n = 0; mnFkSpotDestinyId_n = 0; mnFkModeOfTransportationTypeId = 0; mnFkCarrierTypeId = 0; mnFkCarrierId_n = 0; mnFkVehicleTypeId_n = 0; mnFkVehicleId_n = 0; mnFkSourceYearId_n = 0; mnFkSourceDocId_n = 0; mnFkMfgYearId_n = 0; mnFkMfgOrderId_n = 0; mnFkUserLinkedId = 0; mnFkUserClosedId = 0; mnFkUserClosedCommissionsId = 0; mnFkUserShippedId = 0; mnFkUserAuditedId = 0; mnFkUserAuthorizedId = 0; mnFkUserNewId = 0; mnFkUserEditId = 0; mnFkUserDeleteId = 0; mtUserLinkedTs = null; mtUserClosedTs = null; mtUserClosedCommissionsTs = null; mtUserShippedTs = null; mtUserAuditedTs = null; mtUserAuthorizedTs = null; mtUserNewTs = null; mtUserEditTs = null; mtUserDeleteTs = null; mvDbmsDpsEntries.clear(); mvDbmsDpsNotes.clear(); moDbmsRecordKey = null; mtDbmsRecordDate = null; msDbmsCurrency = ""; msDbmsCurrencyKey = ""; mbAuxIsFormerRecordAutomatic = false; moAuxFormerRecordKey = null; moAuxCfdParams = null; mbAuxIsNeedCfd = false; moDbmsDataAddenda = null; moDbmsDataCfd = null; msCfdExpeditionLocality = ""; msCfdExpeditionState = ""; } @Override public int read(java.lang.Object pk, java.sql.Statement statement) { int[] anKey = (int[]) pk; int[] anMoveSubclassKey = null; String sSql = ""; String[] asSql = null; ResultSet oResultSet = null; Statement oStatementAux = null; mnLastDbActionResult = SLibConstants.UNDEFINED; reset(); try { sSql = "SELECT d.*, c.cur, c.cur_key FROM trn_dps AS d INNER JOIN erp.cfgu_cur AS c ON d.fid_cur = c.id_cur " + "WHERE id_year = " + anKey[0] + " AND id_doc = " + anKey[1] + " "; oResultSet = statement.executeQuery(sSql); if (!oResultSet.next()) { throw new Exception(SLibConstants.MSG_ERR_REG_FOUND_NOT); } else { mnPkYearId = oResultSet.getInt("d.id_year"); mnPkDocId = oResultSet.getInt("d.id_doc"); mtDate = oResultSet.getDate("d.dt"); mtDateDoc = oResultSet.getDate("d.dt_doc"); mtDateStartCredit = oResultSet.getDate("d.dt_start_cred"); mtDateShipment_n = oResultSet.getDate("d.dt_shipment_n"); mtDateDelivery_n = oResultSet.getDate("d.dt_delivery_n"); mtDateDocLapsing_n = oResultSet.getDate("d.dt_doc_lapsing_n"); mtDateDocDelivery_n = oResultSet.getDate("d.dt_doc_delivery_n"); msNumberSeries = oResultSet.getString("d.num_ser"); msNumber = oResultSet.getString("d.num"); msNumberReference = oResultSet.getString("d.num_ref"); msCommissionsReference = oResultSet.getString("d.comms_ref"); mnApproveYear = oResultSet.getInt("d.approve_year"); mnApproveNumber = oResultSet.getInt("d.approve_num"); mnDaysOfCredit = oResultSet.getInt("d.days_cred"); mbIsDiscountDocApplying = oResultSet.getBoolean("d.b_disc_doc"); mbIsDiscountDocPercentage = oResultSet.getBoolean("d.b_disc_doc_per"); mdDiscountDocPercentage = oResultSet.getDouble("d.disc_doc_per"); mdSubtotalProvisional_r = oResultSet.getDouble("d.stot_prov_r"); mdDiscountDoc_r = oResultSet.getDouble("d.disc_doc_r"); mdSubtotal_r = oResultSet.getDouble("d.stot_r"); mdTaxCharged_r = oResultSet.getDouble("d.tax_charged_r"); mdTaxRetained_r = oResultSet.getDouble("d.tax_retained_r"); mdTotal_r = oResultSet.getDouble("d.tot_r"); mdCommissions_r = oResultSet.getDouble("d.comms_r"); mdExchangeRate = oResultSet.getDouble("d.exc_rate"); mdExchangeRateSystem = oResultSet.getDouble("d.exc_rate_sys"); mdSubtotalProvisionalCy_r = oResultSet.getDouble("d.stot_prov_cur_r"); mdDiscountDocCy_r = oResultSet.getDouble("d.disc_doc_cur_r"); mdSubtotalCy_r = oResultSet.getDouble("d.stot_cur_r"); mdTaxChargedCy_r = oResultSet.getDouble("d.tax_charged_cur_r"); mdTaxRetainedCy_r = oResultSet.getDouble("d.tax_retained_cur_r"); mdTotalCy_r = oResultSet.getDouble("d.tot_cur_r"); mdCommissionsCy_r = oResultSet.getDouble("d.comms_cur_r"); msDriver = oResultSet.getString("d.driver"); msPlate = oResultSet.getString("d.plate"); msTicket = oResultSet.getString("d.ticket"); mnShipments = oResultSet.getInt("d.shipments"); mnPayments = oResultSet.getInt("d.payments"); msPaymentMethod = oResultSet.getString("d.pay_method"); msPaymentAccount = oResultSet.getString("d.pay_account"); mbIsPublic = oResultSet.getBoolean("d.b_pub"); mbIsLinked = oResultSet.getBoolean("d.b_link"); mbIsClosed = oResultSet.getBoolean("d.b_close"); mbIsClosedCommissions = oResultSet.getBoolean("d.b_close_comms"); mbIsShipped = oResultSet.getBoolean("d.b_ship"); mbIsRebill = oResultSet.getBoolean("b_rebill"); mbIsAudited = oResultSet.getBoolean("d.b_audit"); mbIsAuthorized = oResultSet.getBoolean("d.b_authorn"); mbIsRecordAutomatic = oResultSet.getBoolean("d.b_rec_aut"); mbIsCopy = oResultSet.getBoolean("d.b_copy"); mbIsCopied = oResultSet.getBoolean("d.b_copied"); mbIsSystem = oResultSet.getBoolean("d.b_sys"); mbIsDeleted = oResultSet.getBoolean("d.b_del"); mnFkDpsCategoryId = oResultSet.getInt("d.fid_ct_dps"); mnFkDpsClassId = oResultSet.getInt("d.fid_cl_dps"); mnFkDpsTypeId = oResultSet.getInt("d.fid_tp_dps"); mnFkPaymentTypeId = oResultSet.getInt("d.fid_tp_pay"); mnFkPaymentSystemTypeId = oResultSet.getInt("d.fid_tp_pay_sys"); mnFkDpsStatusId = oResultSet.getInt("d.fid_st_dps"); mnFkDpsValidityStatusId = oResultSet.getInt("d.fid_st_dps_val"); mnFkDpsAuthorizationStatusId = oResultSet.getInt("d.fid_st_dps_authorn"); mnFkDpsNatureId = oResultSet.getInt("fid_dps_nat"); mnFkCompanyBranchId = oResultSet.getInt("d.fid_cob"); mnFkBizPartnerId_r = oResultSet.getInt("d.fid_bp_r"); mnFkBizPartnerBranchId = oResultSet.getInt("d.fid_bpb"); mnFkBizPartnerBranchAddressId = oResultSet.getInt("d.fid_add"); mnFkBizPartnerAltId_r = oResultSet.getInt("d.fid_bp_alt_r"); mnFkBizPartnerBranchAltId = oResultSet.getInt("d.fid_bpb_alt"); mnFkBizPartnerBranchAddressAltId = oResultSet.getInt("d.fid_add_alt"); mnFkContactBizPartnerBranchId_n = oResultSet.getInt("d.fid_con_bpb_n"); mnFkContactContactId_n = oResultSet.getInt("d.fid_con_con_n"); mnFkTaxIdentityEmisorTypeId = oResultSet.getInt("d.fid_tp_tax_idy_emir"); mnFkTaxIdentityReceptorTypeId = oResultSet.getInt("d.fid_tp_tax_idy_recr"); mnFkLanguajeId = oResultSet.getInt("d.fid_lan"); mnFkCurrencyId = oResultSet.getInt("d.fid_cur"); mnFkSalesAgentId_n = oResultSet.getInt("d.fid_sal_agt_n"); mnFkSalesAgentBizPartnerId_n = oResultSet.getInt("d.fid_sal_agt_bp_n"); mnFkSalesSupervisorId_n = oResultSet.getInt("d.fid_sal_sup_n"); mnFkSalesSupervisorBizPartnerId_n = oResultSet.getInt("d.fid_sal_sup_bp_n"); mnFkIncotermId = oResultSet.getInt("d.fid_inc"); mnFkSpotSourceId_n = oResultSet.getInt("d.fid_spot_src_n"); mnFkSpotDestinyId_n = oResultSet.getInt("d.fid_spot_des_n"); mnFkModeOfTransportationTypeId = oResultSet.getInt("d.fid_tp_mot"); mnFkCarrierTypeId = oResultSet.getInt("d.fid_tp_car"); mnFkCarrierId_n = oResultSet.getInt("d.fid_car_n"); mnFkVehicleTypeId_n = oResultSet.getInt("d.fid_tp_veh_n"); mnFkVehicleId_n = oResultSet.getInt("d.fid_veh_n"); mnFkSourceYearId_n = oResultSet.getInt("d.fid_src_year_n"); mnFkSourceDocId_n = oResultSet.getInt("d.fid_src_doc_n"); mnFkMfgYearId_n = oResultSet.getInt("d.fid_mfg_year_n"); mnFkMfgOrderId_n = oResultSet.getInt("d.fid_mfg_ord_n"); mnFkUserLinkedId = oResultSet.getInt("d.fid_usr_link"); mnFkUserClosedId = oResultSet.getInt("d.fid_usr_close"); mnFkUserClosedCommissionsId = oResultSet.getInt("d.fid_usr_close_comms"); mnFkUserShippedId = oResultSet.getInt("d.fid_usr_ship"); mnFkUserAuditedId = oResultSet.getInt("d.fid_usr_audit"); mnFkUserAuthorizedId = oResultSet.getInt("d.fid_usr_authorn"); mnFkUserNewId = oResultSet.getInt("d.fid_usr_new"); mnFkUserEditId = oResultSet.getInt("d.fid_usr_edit"); mnFkUserDeleteId = oResultSet.getInt("d.fid_usr_del"); mtUserLinkedTs = oResultSet.getTimestamp("d.ts_link"); mtUserClosedTs = oResultSet.getTimestamp("d.ts_close"); mtUserClosedCommissionsTs = oResultSet.getTimestamp("d.ts_close_comms"); mtUserShippedTs = oResultSet.getTimestamp("d.ts_ship"); mtUserAuditedTs = oResultSet.getTimestamp("d.ts_audit"); mtUserAuthorizedTs = oResultSet.getTimestamp("d.ts_authorn"); mtUserNewTs = oResultSet.getTimestamp("d.ts_new"); mtUserEditTs = oResultSet.getTimestamp("d.ts_edit"); mtUserDeleteTs = oResultSet.getTimestamp("d.ts_del"); msDbmsCurrency = oResultSet.getString("c.cur"); msDbmsCurrencyKey = oResultSet.getString("c.cur_key"); oStatementAux = statement.getConnection().createStatement(); // Read aswell document notes: sSql = "SELECT id_year, id_doc, id_nts FROM trn_dps_nts " + "WHERE id_year = " + anKey[0] + " AND id_doc = " + anKey[1] + " " + "ORDER BY id_year, id_doc, id_nts "; oResultSet = statement.executeQuery(sSql); while (oResultSet.next()) { SDataDpsNotes note = new SDataDpsNotes(); if (note.read(new int[] { oResultSet.getInt("id_year"), oResultSet.getInt("id_doc"), oResultSet.getInt("id_nts") }, oStatementAux) != SLibConstants.DB_ACTION_READ_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } else { mvDbmsDpsNotes.add(note); } } // Read aswell document entries: sSql = "SELECT id_year, id_doc, id_ety FROM trn_dps_ety " + "WHERE id_year = " + anKey[0] + " AND id_doc = " + anKey[1] + " " + "ORDER BY fid_tp_dps_ety = " + SDataConstantsSys.TRNS_TP_DPS_ETY_VIRT + ", sort_pos, id_ety "; oResultSet = statement.executeQuery(sSql); while (oResultSet.next()) { SDataDpsEntry entry = new SDataDpsEntry(); if (entry.read(new int[] { oResultSet.getInt("id_year"), oResultSet.getInt("id_doc"), oResultSet.getInt("id_ety") }, oStatementAux) != SLibConstants.DB_ACTION_READ_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } else { mvDbmsDpsEntries.add(entry); } } // Check if document class requires an accounting record: anMoveSubclassKey = getAccountingMoveSubclassKey(); if (anMoveSubclassKey != null) { // Read aswell accounting record: /* * Attempt 1: try to find accounting record directly. * Attempt 2: try to find accounting record only in non-deleted records. * Attempt 3: if needed, try to find accounting record in all records. */ asSql = new String[3]; // Query for attempt 1: asSql[0] = "SELECT fid_rec_year AS f_year, fid_rec_per AS f_per, fid_rec_bkc AS f_bkc, fid_rec_tp_rec AS f_tp_rec, fid_rec_num AS f_num " + "FROM trn_dps_rec WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " "; // Query for attempts 2 and 3: sSql = "SELECT DISTINCT id_year AS f_year, id_per AS f_per, id_bkc AS f_bkc, id_tp_rec AS f_tp_rec, id_num AS f_num FROM fin_rec_ety WHERE " + "fid_tp_acc_mov = " + anMoveSubclassKey[0] + " AND fid_cl_acc_mov = " + anMoveSubclassKey[1] + " AND fid_cls_acc_mov = " + anMoveSubclassKey[2] + " AND " + (isDocument() ? "fid_dps_year_n = " + mnPkYearId + " AND fid_dps_doc_n = " + mnPkDocId + " " : "fid_dps_adj_year_n = " + mnPkYearId + " AND fid_dps_adj_doc_n = " + mnPkDocId + " "); asSql[1] = sSql + "AND b_del = 0 ORDER BY id_ety DESC "; asSql[2] = sSql + "ORDER BY id_ety DESC "; for (int i = 0; i < asSql.length; i++) { oResultSet = statement.executeQuery(asSql[i]); if (oResultSet.next()) { moDbmsRecordKey = new Object[5]; ((Object[]) moDbmsRecordKey)[0] = oResultSet.getInt("f_year"); ((Object[]) moDbmsRecordKey)[1] = oResultSet.getInt("f_per"); ((Object[]) moDbmsRecordKey)[2] = oResultSet.getInt("f_bkc"); ((Object[]) moDbmsRecordKey)[3] = oResultSet.getString("f_tp_rec"); ((Object[]) moDbmsRecordKey)[4] = oResultSet.getInt("f_num"); sSql = "SELECT dt FROM fin_rec WHERE id_year = " + ((Object[]) moDbmsRecordKey)[0] + " AND id_per = " + ((Object[]) moDbmsRecordKey)[1] + " AND " + "id_bkc = " + ((Object[]) moDbmsRecordKey)[2] + " AND id_tp_rec = '" + ((Object[]) moDbmsRecordKey)[3] + "' AND id_num = " + ((Object[]) moDbmsRecordKey)[4] + " "; oResultSet = statement.executeQuery(sSql); if (!oResultSet.next()) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } else { mtDbmsRecordDate = oResultSet.getDate("dt"); mbAuxIsFormerRecordAutomatic = mbIsRecordAutomatic; moAuxFormerRecordKey = new Object[5]; ((Object[]) moAuxFormerRecordKey)[0] = ((Object[]) moDbmsRecordKey)[0]; ((Object[]) moAuxFormerRecordKey)[1] = ((Object[]) moDbmsRecordKey)[1]; ((Object[]) moAuxFormerRecordKey)[2] = ((Object[]) moDbmsRecordKey)[2]; ((Object[]) moAuxFormerRecordKey)[3] = ((Object[]) moDbmsRecordKey)[3]; ((Object[]) moAuxFormerRecordKey)[4] = ((Object[]) moDbmsRecordKey)[4]; } break; // accounting record was found! } } } // Read XML: sSql = "SELECT id_cfd FROM trn_cfd WHERE fid_dps_year_n = " + anKey[0] + " AND fid_dps_doc_n = " + anKey[1] + " "; oResultSet = statement.executeQuery(sSql); if (oResultSet.next()) { moDbmsDataCfd = new SDataCfd(); if (moDbmsDataCfd.read(new int[] { oResultSet.getInt("id_cfd") }, oStatementAux)!= SLibConstants.DB_ACTION_READ_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } } // Read addenda: sSql = "SELECT COUNT(*) FROM trn_dps_add WHERE id_year = " + anKey[0] + " AND id_doc = " + anKey[1] + " "; oResultSet = statement.executeQuery(sSql); if (oResultSet.next()) { if (oResultSet.getInt(1) > 0) { moDbmsDataAddenda = new SDataDpsAddenda(); if (moDbmsDataAddenda.read(anKey, oStatementAux)!= SLibConstants.DB_ACTION_READ_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } } } mbIsRegistryNew = false; mnLastDbActionResult = SLibConstants.DB_ACTION_READ_OK; } } catch (java.sql.SQLException e) { mnLastDbActionResult = SLibConstants.DB_ACTION_READ_ERROR; SLibUtilities.printOutException(this, e); } catch (java.lang.Exception e) { mnLastDbActionResult = SLibConstants.DB_ACTION_READ_ERROR; SLibUtilities.printOutException(this, e); } return mnLastDbActionResult; } @Override public int save(java.sql.Connection connection) { int i = 0; int j = 0; int nParam = 0; int nSortingPosition = 0; int nDecimals = 4; int nTaxTypeId = SLibConsts.UNDEFINED; int nTaxAppTypeId = SLibConsts.UNDEFINED; int nRecordEntryPosition = 0; double dDebit = 0; double dCredit = 0; double dDebitCy = 0; double dCreditCy = 0; double dHigherValue = 0; boolean isNewRecord = false; int[] anMoveSubclassKey = null; int[] anSysAccountTypeKey = null; int[] anSysMoveTypeKey = null; int[] anSysMoveTypeKeyXXX = null; String sSql = ""; String sConcept = ""; String sConceptAux = ""; String sConceptEntry = ""; String sConceptEntryAux = ""; String sAccountId = ""; Statement oStatement = null; ResultSet oResultSet = null; CallableStatement oCallableStatement = null; SDataRecord oRecord = null; SDataRecordEntry oRecordEntry = null; SFinTaxes oFinTaxes = null; SFinAccountConfig oConfigBizPartnerOps = null; SFinAccountConfig oConfigBizPartnerPay = null; SFinAccountConfig oConfigItem = null; ArrayList<SFinAmount> aValues = null; ArrayList<SFinAmount> aTotals = new ArrayList<>(); ArrayList<int[]> aAuxDpsKeys = new ArrayList<>(); mnLastDbActionResult = SLibConstants.UNDEFINED; try { updateAuthorizationStatus(connection); // applys only for orders and documents //System.out.println("dps 1"); nParam = 1; oCallableStatement = connection.prepareCall( "{ CALL trn_dps_save(" + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + "?, ?, ? ) }"); oCallableStatement.setInt(nParam++, mnPkYearId); oCallableStatement.setInt(nParam++, mnPkDocId); oCallableStatement.setDate(nParam++, new java.sql.Date(mtDate.getTime())); oCallableStatement.setDate(nParam++, new java.sql.Date(mtDateDoc.getTime())); oCallableStatement.setDate(nParam++, new java.sql.Date(mtDateStartCredit.getTime())); if (mtDateShipment_n != null) oCallableStatement.setDate(nParam++, new java.sql.Date(mtDateShipment_n.getTime())); else oCallableStatement.setNull(nParam++, java.sql.Types.DATE); if (mtDateDelivery_n != null) oCallableStatement.setDate(nParam++, new java.sql.Date(mtDateDelivery_n.getTime())); else oCallableStatement.setNull(nParam++, java.sql.Types.DATE); if (mtDateDocLapsing_n != null) oCallableStatement.setDate(nParam++, new java.sql.Date(mtDateDocLapsing_n.getTime())); else oCallableStatement.setNull(nParam++, java.sql.Types.DATE); if (mtDateDocDelivery_n != null) oCallableStatement.setDate(nParam++, new java.sql.Date(mtDateDocDelivery_n.getTime())); else oCallableStatement.setNull(nParam++, java.sql.Types.DATE); oCallableStatement.setString(nParam++, msNumberSeries); oCallableStatement.setString(nParam++, msNumber); oCallableStatement.setString(nParam++, msNumberReference); oCallableStatement.setString(nParam++, msCommissionsReference); oCallableStatement.setInt(nParam++, mnApproveYear); oCallableStatement.setInt(nParam++, mnApproveNumber); oCallableStatement.setInt(nParam++, mnDaysOfCredit); oCallableStatement.setBoolean(nParam++, mbIsDiscountDocApplying); oCallableStatement.setBoolean(nParam++, mbIsDiscountDocPercentage); oCallableStatement.setDouble(nParam++, mdDiscountDocPercentage); oCallableStatement.setDouble(nParam++, mdSubtotalProvisional_r); oCallableStatement.setDouble(nParam++, mdDiscountDoc_r); oCallableStatement.setDouble(nParam++, mdSubtotal_r); oCallableStatement.setDouble(nParam++, mdTaxCharged_r); oCallableStatement.setDouble(nParam++, mdTaxRetained_r); oCallableStatement.setDouble(nParam++, mdTotal_r); oCallableStatement.setDouble(nParam++, mdCommissions_r); oCallableStatement.setDouble(nParam++, mdExchangeRate); oCallableStatement.setDouble(nParam++, mdExchangeRateSystem); oCallableStatement.setDouble(nParam++, mdSubtotalProvisionalCy_r); oCallableStatement.setDouble(nParam++, mdDiscountDocCy_r); oCallableStatement.setDouble(nParam++, mdSubtotalCy_r); oCallableStatement.setDouble(nParam++, mdTaxChargedCy_r); oCallableStatement.setDouble(nParam++, mdTaxRetainedCy_r); oCallableStatement.setDouble(nParam++, mdTotalCy_r); oCallableStatement.setDouble(nParam++, mdCommissionsCy_r); oCallableStatement.setString(nParam++, msDriver); oCallableStatement.setString(nParam++, msPlate); oCallableStatement.setString(nParam++, msTicket); oCallableStatement.setInt(nParam++, mnShipments); oCallableStatement.setInt(nParam++, mnPayments); oCallableStatement.setString(nParam++, msPaymentMethod); oCallableStatement.setString(nParam++, msPaymentAccount); oCallableStatement.setBoolean(nParam++, mbIsPublic); oCallableStatement.setBoolean(nParam++, mbIsLinked); oCallableStatement.setBoolean(nParam++, mbIsClosed); oCallableStatement.setBoolean(nParam++, mbIsClosedCommissions); oCallableStatement.setBoolean(nParam++, mbIsShipped); oCallableStatement.setBoolean(nParam++, mbIsRebill); oCallableStatement.setBoolean(nParam++, mbIsAudited); oCallableStatement.setBoolean(nParam++, mbIsAuthorized); oCallableStatement.setBoolean(nParam++, mbIsRecordAutomatic); oCallableStatement.setBoolean(nParam++, mbIsCopy); oCallableStatement.setBoolean(nParam++, mbIsCopied); oCallableStatement.setBoolean(nParam++, mbIsSystem); oCallableStatement.setBoolean(nParam++, mbIsDeleted); oCallableStatement.setInt(nParam++, mnFkDpsCategoryId); oCallableStatement.setInt(nParam++, mnFkDpsClassId); oCallableStatement.setInt(nParam++, mnFkDpsTypeId); oCallableStatement.setInt(nParam++, mnFkPaymentTypeId); oCallableStatement.setInt(nParam++, mnFkPaymentSystemTypeId); oCallableStatement.setInt(nParam++, mnFkDpsStatusId); oCallableStatement.setInt(nParam++, mnFkDpsValidityStatusId); oCallableStatement.setInt(nParam++, mnFkDpsAuthorizationStatusId); oCallableStatement.setInt(nParam++, mnFkDpsNatureId); oCallableStatement.setInt(nParam++, mnFkCompanyBranchId); oCallableStatement.setInt(nParam++, mnFkBizPartnerId_r); oCallableStatement.setInt(nParam++, mnFkBizPartnerBranchId); oCallableStatement.setInt(nParam++, mnFkBizPartnerBranchAddressId); oCallableStatement.setInt(nParam++, mnFkBizPartnerAltId_r); oCallableStatement.setInt(nParam++, mnFkBizPartnerBranchAltId); oCallableStatement.setInt(nParam++, mnFkBizPartnerBranchAddressAltId); if (mnFkContactBizPartnerBranchId_n > 0) oCallableStatement.setInt(nParam++, mnFkContactBizPartnerBranchId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER); if (mnFkContactContactId_n > 0) oCallableStatement.setInt(nParam++, mnFkContactContactId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.SMALLINT); oCallableStatement.setInt(nParam++, mnFkTaxIdentityEmisorTypeId); oCallableStatement.setInt(nParam++, mnFkTaxIdentityReceptorTypeId); oCallableStatement.setInt(nParam++, mnFkLanguajeId); oCallableStatement.setInt(nParam++, mnFkCurrencyId); if (mnFkSalesAgentId_n > 0) oCallableStatement.setInt(nParam++, mnFkSalesAgentId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER); if (mnFkSalesAgentBizPartnerId_n > 0) oCallableStatement.setInt(nParam++, mnFkSalesAgentBizPartnerId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER); if (mnFkSalesSupervisorId_n > 0) oCallableStatement.setInt(nParam++, mnFkSalesSupervisorId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER); if (mnFkSalesSupervisorBizPartnerId_n > 0) oCallableStatement.setInt(nParam++, mnFkSalesSupervisorBizPartnerId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER); oCallableStatement.setInt(nParam++, mnFkIncotermId); if (mnFkSpotSourceId_n > 0) oCallableStatement.setInt(nParam++, mnFkSpotSourceId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.SMALLINT); if (mnFkSpotDestinyId_n > 0) oCallableStatement.setInt(nParam++, mnFkSpotDestinyId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.SMALLINT); oCallableStatement.setInt(nParam++, mnFkModeOfTransportationTypeId); oCallableStatement.setInt(nParam++, mnFkCarrierTypeId); if (mnFkCarrierId_n > 0) oCallableStatement.setInt(nParam++, mnFkCarrierId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER); if (mnFkVehicleTypeId_n > 0) oCallableStatement.setInt(nParam++, mnFkVehicleTypeId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.SMALLINT); if (mnFkVehicleId_n > 0) oCallableStatement.setInt(nParam++, mnFkVehicleId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.SMALLINT); if (mnFkSourceYearId_n > 0) oCallableStatement.setInt(nParam++, mnFkSourceYearId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER); if (mnFkSourceDocId_n > 0) oCallableStatement.setInt(nParam++, mnFkSourceDocId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER); if (mnFkMfgYearId_n > 0) oCallableStatement.setInt(nParam++, mnFkMfgYearId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.SMALLINT); if (mnFkMfgOrderId_n > 0) oCallableStatement.setInt(nParam++, mnFkMfgOrderId_n); else oCallableStatement.setNull(nParam++, java.sql.Types.INTEGER); oCallableStatement.setInt(nParam++, mnFkUserLinkedId); oCallableStatement.setInt(nParam++, mnFkUserClosedId); oCallableStatement.setInt(nParam++, mnFkUserClosedCommissionsId); oCallableStatement.setInt(nParam++, mnFkUserShippedId); oCallableStatement.setInt(nParam++, mnFkUserAuditedId); oCallableStatement.setInt(nParam++, mnFkUserAuthorizedId); oCallableStatement.setInt(nParam++, mbIsRegistryNew ? mnFkUserNewId : mnFkUserEditId); oCallableStatement.registerOutParameter(nParam++, java.sql.Types.INTEGER); oCallableStatement.registerOutParameter(nParam++, java.sql.Types.SMALLINT); oCallableStatement.registerOutParameter(nParam++, java.sql.Types.VARCHAR); oCallableStatement.execute(); //System.out.println("dps 2"); mnPkDocId = oCallableStatement.getInt(nParam - 3); mnDbmsErrorId = oCallableStatement.getInt(nParam - 2); msDbmsError = oCallableStatement.getString(nParam - 1); //System.out.println("dps 3"); if (mnDbmsErrorId != 0) { throw new Exception(msDbmsError); } else { oStatement = connection.createStatement(); oFinTaxes = new SFinTaxes(oStatement); // 1. Obtain decimals for calculations: //System.out.println("dps 3.1"); sSql = "SELECT decs_val FROM erp.cfg_param_erp WHERE id_erp = 1 "; oResultSet = oStatement.executeQuery(sSql); if (oResultSet.next()) { nDecimals = oResultSet.getInt("decs_val"); } // 2. Save aswell document entries: nSortingPosition = 0; for (SDataDpsEntry entry : mvDbmsDpsEntries) { if (entry.getIsRegistryNew() || entry.getIsRegistryEdited()) { entry.setPkYearId(mnPkYearId); entry.setPkDocId(mnPkDocId); if (entry.getIsDeleted() || entry.getFkDpsEntryTypeId() == SDataConstantsSys.TRNS_TP_DPS_ETY_VIRT) { entry.setSortingPosition(0); } else { entry.setSortingPosition(++nSortingPosition); } if (entry.save(connection) != SLibConstants.DB_ACTION_SAVE_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE_DEP); } } } // 3. Save aswell document notes: for (SDataDpsNotes notes : mvDbmsDpsNotes) { if (notes.getIsRegistryNew() || notes.getIsRegistryEdited()) { notes.setPkYearId(mnPkYearId); notes.setPkDocId(mnPkDocId); if (notes.save(connection) != SLibConstants.DB_ACTION_SAVE_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE_DEP); } } } // 4. Save aswell journal voucher if this document class requires it: //System.out.println("dps 3.4"); anMoveSubclassKey = getAccountingMoveSubclassKey(); //System.out.println("dps 3.5"); if (anMoveSubclassKey != null) { // 4.1 Prepare journal voucher (accounting record): //System.out.println("dps 3.5.1"); if (mbIsDeleted) { // Delete aswell former journal voucher: if (moAuxFormerRecordKey != null) { // If document had automatic journal voucher, delete it including its header: deleteRecord(moAuxFormerRecordKey, mbAuxIsFormerRecordAutomatic, connection); } } else { // Save aswell journal voucher: if (moDbmsRecordKey == null) { if (!mbIsRecordAutomatic) { // Journal voucher is not automatic: throw new Exception("No se ha especificado la póliza contable de usuario."); } else { // Journal voucher is automatic: if (moAuxFormerRecordKey == null || !mbAuxIsFormerRecordAutomatic) { isNewRecord = true; moDbmsRecordKey = (Object[]) createAccountingRecordKey(oStatement); } else { if (SLibTimeUtilities.isBelongingToPeriod(mtDate, (Integer) ((Object[]) moAuxFormerRecordKey)[0], (Integer) ((Object[]) moAuxFormerRecordKey)[1])) { moDbmsRecordKey = moAuxFormerRecordKey; } else { isNewRecord = true; moDbmsRecordKey = (Object[]) createAccountingRecordKey(oStatement); } } } } if (moAuxFormerRecordKey != null) { // If document was previously saved, delete former accounting moves, if needed, including its header: deleteRecord(moAuxFormerRecordKey, (mbAuxIsFormerRecordAutomatic && !mbIsRecordAutomatic) || (mbAuxIsFormerRecordAutomatic && isNewRecord), connection); } // 4.2 Save document's journal voucher (accounting record): // 4.2.1 Define journal voucher's concept: sSql = "SELECT code FROM erp.trnu_tp_dps WHERE " + "id_ct_dps = " + mnFkDpsCategoryId + " AND id_cl_dps = " + mnFkDpsClassId + " AND id_tp_dps = " + mnFkDpsTypeId + " "; oResultSet = oStatement.executeQuery(sSql); if (oResultSet.next()) { sConcept += oResultSet.getString("code") + " " + msNumberSeries + (msNumberSeries.length() == 0 ? "" : "-") + msNumber + "; "; } else { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } sSql = "SELECT bp_comm FROM erp.bpsu_bp WHERE id_bp = " + mnFkBizPartnerId_r + " "; oResultSet = oStatement.executeQuery(sSql); if (oResultSet.next()) { sConcept += oResultSet.getString("bp_comm"); } else { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } for (SDataDpsEntry entry : mvDbmsDpsEntries) { if (!entry.getIsDeleted()) { sConceptEntry = entry.getConcept(); break; } } sConceptAux = sConcept; if (!sConceptEntry.isEmpty()) { sConcept += "; " + sConceptEntry; } if (sConcept.length() > 100) { sConcept = sConcept.substring(0, 100 - 3).trim() + "..."; } // 4.2.2 Save journal voucher: nSortingPosition = 0; oRecord = new SDataRecord(); if (!isNewRecord) { if (oRecord.read(moDbmsRecordKey, oStatement) != SLibConstants.DB_ACTION_READ_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } if (oRecord.getIsDeleted()) { oRecord.setIsDeleted(false); } if (mbIsRecordAutomatic) { oRecord.setDate(mtDate); oRecord.setConcept(sConcept); } for (SDataRecordEntry entry : oRecord.getDbmsRecordEntries()) { if (!entry.getIsDeleted()) { nSortingPosition = entry.getSortingPosition(); } } } else { oRecord.setPrimaryKey(moDbmsRecordKey); oRecord.setDate(mtDate); oRecord.setConcept(sConcept); oRecord.setIsAudited(false); oRecord.setIsAuthorized(false); oRecord.setIsSystem(true); oRecord.setIsDeleted(false); oRecord.setFkCompanyBranchId(mnFkCompanyBranchId); oRecord.setFkCompanyBranchId_n(0); oRecord.setFkAccountCashId_n(0); if (mbIsRegistryNew) { oRecord.setFkUserNewId(mnFkUserNewId); oRecord.setFkUserEditId(mnFkUserNewId); } else { oRecord.setFkUserNewId(mnFkUserEditId); oRecord.setFkUserEditId(mnFkUserEditId); } } // 4.3 Business partner's asset or liability: oConfigBizPartnerOps = new SFinAccountConfig(SFinAccountUtilities.obtainBizPartnerAccountConfigs( mnFkBizPartnerId_r, getBizPartnerCategoryId(), oRecord.getPkBookkeepingCenterId(), mtDate, SDataConstantsSys.FINS_TP_ACC_BP_OP, isDebitForBizPartner(), oStatement)); if (isDocument()) { // One accounting record entry per document: aTotals.add(new SFinAmount(mdTotal_r, mdTotalCy_r)); } else { // One accounting record entry per each document entry: for (SDataDpsEntry entry : mvDbmsDpsEntries) { if (entry.isAccountable()) { aTotals.add(new SFinAmount(entry.getTotal_r(), entry.getTotalCy_r())); aAuxDpsKeys.add(new int[] { entry.getAuxPkDpsYearId(), entry.getAuxPkDpsDocId() }); } } } anSysAccountTypeKey = getSystemAccountTypeKey(); anSysMoveTypeKey = getSystemMoveTypeForBizPartner(); anSysMoveTypeKeyXXX = getSystemMoveTypeForBizPartnerXXX(); for (i = 0; i < aTotals.size(); i++) { aValues = oConfigBizPartnerOps.prorateAmount(aTotals.get(i)); for (j = 0; j < oConfigBizPartnerOps.getAccountConfigEntries().size(); j++) { oRecordEntry = createAccountingRecordEntry( oConfigBizPartnerOps.getAccountConfigEntries().get(j).getAccountId(), oConfigBizPartnerOps.getAccountConfigEntries().get(j).getCostCenterId(), anMoveSubclassKey, anSysAccountTypeKey, anSysMoveTypeKey, anSysMoveTypeKeyXXX, isDocument() ? null : aAuxDpsKeys.get(i)); if (isDebitForBizPartner()) { oRecordEntry.setDebit(aValues.get(j).Amount); oRecordEntry.setCredit(0); oRecordEntry.setDebitCy(aValues.get(j).AmountCy); oRecordEntry.setCreditCy(0); } else { oRecordEntry.setDebit(0); oRecordEntry.setCredit(aValues.get(j).Amount); oRecordEntry.setDebitCy(0); oRecordEntry.setCreditCy(aValues.get(j).AmountCy); } oRecordEntry.setConcept(sConcept); oRecordEntry.setSortingPosition(++nSortingPosition); oRecord.getDbmsRecordEntries().add(oRecordEntry); } } // 4.4 Purchases or sales: for (SDataDpsEntry entry : mvDbmsDpsEntries) { if (entry.isAccountable()) { oConfigItem = new SFinAccountConfig(SFinAccountUtilities.obtainItemAccountConfigs( entry.getFkItemRefId_n() != SLibConstants.UNDEFINED ? entry.getFkItemRefId_n() : entry.getFkItemId(), oRecord.getPkBookkeepingCenterId(), mtDate, getItemAccountTypeId(entry), isDebitForOperations(), oStatement)); sConceptEntryAux = sConceptAux; anSysAccountTypeKey = SModSysConsts.FINS_TP_SYS_ACC_NA_NA; anSysMoveTypeKey = getSystemMoveTypeForItem(entry.getFkDpsAdjustmentTypeId()); anSysMoveTypeKeyXXX = getSystemMoveTypeForItemXXX(); aValues = oConfigItem.prorateAmount(new SFinAmount(entry.getSubtotal_r(), entry.getSubtotalCy_r())); for (i = 0; i < oConfigItem.getAccountConfigEntries().size(); i++) { oRecordEntry = createAccountingRecordEntry( oConfigItem.getAccountConfigEntries().get(i).getAccountId(), !entry.getFkCostCenterId_n().isEmpty() ? entry.getFkCostCenterId_n() : oConfigItem.getAccountConfigEntries().get(i).getCostCenterId(), anMoveSubclassKey, anSysAccountTypeKey, anSysMoveTypeKey, anSysMoveTypeKeyXXX, isDocument() ? null : new int[] { entry.getAuxPkDpsYearId(), entry.getAuxPkDpsDocId() }); if (isDebitForOperations()) { oRecordEntry.setDebit(aValues.get(i).Amount); oRecordEntry.setCredit(0); oRecordEntry.setDebitCy(aValues.get(i).AmountCy); oRecordEntry.setCreditCy(0); } else { oRecordEntry.setDebit(0); oRecordEntry.setCredit(aValues.get(i).Amount); oRecordEntry.setDebitCy(0); oRecordEntry.setCreditCy(aValues.get(i).AmountCy); } sConceptEntryAux += (entry.getConcept().length() <= 0 ? "" : "; " + entry.getConcept()); if (sConceptEntryAux.length() > 100) { sConceptEntryAux = sConceptEntryAux.substring(0, 100 - 3).trim() + "..."; } oRecordEntry.setConcept(sConceptEntryAux); oRecordEntry.setSortingPosition(++nSortingPosition); if (entry.getFkItemRefId_n() == 0) { oRecordEntry.setUnits(entry.getOriginalQuantity()); oRecordEntry.setFkItemId_n(entry.getFkItemId()); oRecordEntry.setFkUnitId_n(entry.getFkOriginalUnitId()); oRecordEntry.setFkItemAuxId_n(SLibConstants.UNDEFINED); } else { oRecordEntry.setUnits(0); oRecordEntry.setFkItemId_n(entry.getFkItemRefId_n()); oRecordEntry.setFkUnitId_n(SModSysConsts.ITMU_UNIT_NA); oRecordEntry.setFkItemAuxId_n(entry.getFkItemId()); } oRecord.getDbmsRecordEntries().add(oRecordEntry); } for (SDataDpsEntryTax tax : entry.getDbmsEntryTaxes()) { oFinTaxes.addTax(isDocument() ? new int[] { mnPkYearId, mnPkDocId } : new int[] { entry.getAuxPkDpsYearId(), entry.getAuxPkDpsDocId() }, new int[] { tax.getPkTaxBasicId(), tax.getPkTaxId() }, tax.getTax(), tax.getTaxCy()); } } } // 4.5 Purchases or sales taxes: for (SFinTaxes.STax tax : oFinTaxes.getTaxes()) { sAccountId = SFinAccountUtilities.obtainTaxAccountId(tax.getTaxKey(), mnFkDpsCategoryId, mtDate, tax.getFkTaxApplicationTypeId() == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SDataConstantsSys.FINX_ACC_PAY : SDataConstantsSys.FINX_ACC_PAY_PEND, oStatement); sSql = "SELECT fid_tp_tax, fid_tp_tax_app FROM erp.finu_tax " + "WHERE id_tax_bas = " + tax.getPkTaxBasicId() + " AND id_tax = " + tax.getPkTaxId() + " "; oResultSet = oStatement.executeQuery(sSql); if (oResultSet.next()) { nTaxTypeId = oResultSet.getInt("fid_tp_tax"); nTaxAppTypeId = oResultSet.getInt("fid_tp_tax_app"); } else { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } anSysAccountTypeKey = SModSysConsts.FINS_TP_SYS_ACC_NA_NA; anSysMoveTypeKey = getSystemMoveTypeForTax(nTaxTypeId, nTaxAppTypeId); anSysMoveTypeKeyXXX = getSystemMoveTypeForTaxXXX(nTaxTypeId, nTaxAppTypeId); oRecordEntry = createAccountingRecordEntry( sAccountId, "", anMoveSubclassKey, anSysAccountTypeKey, anSysMoveTypeKey, anSysMoveTypeKeyXXX, isDocument() ? null : tax.getAuxDpsKey()); if (isDebitForTaxes(tax.getFkTaxTypeId())) { oRecordEntry.setDebit(tax.getValue()); oRecordEntry.setCredit(0); oRecordEntry.setDebitCy(tax.getValueCy()); oRecordEntry.setCreditCy(0); } else { oRecordEntry.setDebit(0); oRecordEntry.setCredit(tax.getValue()); oRecordEntry.setDebitCy(0); oRecordEntry.setCreditCy(tax.getValueCy()); } oRecordEntry.setConcept(sConcept); oRecordEntry.setSortingPosition(++nSortingPosition); oRecordEntry.setFkTaxBasicId_n(tax.getPkTaxBasicId()); oRecordEntry.setFkTaxId_n(tax.getPkTaxId()); oRecord.getDbmsRecordEntries().add(oRecordEntry); } // 4.6 Validate accounting record: nRecordEntryPosition = 0; dHigherValue = 0; for (i = 0; i < oRecord.getDbmsRecordEntries().size(); i++) { oRecordEntry = oRecord.getDbmsRecordEntries().get(i); if (!oRecordEntry.getIsDeleted()) { dDebit += oRecordEntry.getDebit(); dCredit += oRecordEntry.getCredit(); dDebitCy += oRecordEntry.getDebitCy(); dCreditCy += oRecordEntry.getCreditCy(); if (SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_SAL_DOC) || SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ)) { if (oRecordEntry.getDebit() > dHigherValue) { dHigherValue = oRecordEntry.getDebit(); nRecordEntryPosition = i; } } else if (SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ) || SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_PUR_DOC)) { if (oRecordEntry.getCredit() > dHigherValue) { dHigherValue = oRecordEntry.getCredit(); nRecordEntryPosition = i; } } } } if (dDebit != dCredit) { oRecordEntry = oRecord.getDbmsRecordEntries().get(nRecordEntryPosition); if (SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_SAL_DOC) || SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_PUR_ADJ)) { if (dDebit > dCredit) { oRecordEntry.setDebit(SLibUtilities.round(oRecordEntry.getDebit() - (dDebit - dCredit), nDecimals)); } else { oRecordEntry.setDebit(SLibUtilities.round(oRecordEntry.getDebit() + (dCredit - dDebit), nDecimals)); } } else if (SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_SAL_ADJ) || SLibUtils.compareKeys(new int[] { mnFkDpsCategoryId, mnFkDpsClassId }, SDataConstantsSys.TRNS_CL_DPS_PUR_DOC)) { if (dDebit < dCredit) { oRecordEntry.setCredit(SLibUtilities.round(oRecordEntry.getCredit() - (dCredit - dDebit), nDecimals)); } else { oRecordEntry.setCredit(SLibUtilities.round(oRecordEntry.getCredit() + (dDebit - dCredit), nDecimals)); } } oRecord.getDbmsRecordEntries().set(nRecordEntryPosition, oRecordEntry); } // 4.7 Finally, save journal voucher (acounting record): if (oRecord.save(connection) != SLibConstants.DB_ACTION_SAVE_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE_DEP); } else { sSql = "DELETE FROM trn_dps_rec WHERE id_dps_year = " + mnPkYearId + " AND id_dps_doc = " + mnPkDocId + " "; oStatement.execute(sSql); sSql = "INSERT INTO trn_dps_rec VALUES (" + mnPkYearId + ", " + mnPkDocId + ", " + oRecord.getPkYearId() + ", " + oRecord.getPkPeriodId() + ", " + oRecord.getPkBookkeepingCenterId() + ", " + "'" + oRecord.getPkRecordTypeId() + "', " + oRecord.getPkNumberId() + ") "; oStatement.execute(sSql); moDbmsRecordKey = oRecord.getPrimaryKey(); mtDbmsRecordDate = oRecord.getDate(); } } //System.out.println("dps 3.5.2"); } // 5. If document is deleted, delete aswell its links: //System.out.println("dps 3.6"); if (mbIsDeleted) { deleteLinks(oStatement); } // Save addenda: if (moAuxCfdParams != null) { moDbmsDataAddenda = new SDataDpsAddenda(); moDbmsDataAddenda.setPkYearId(mnPkYearId); moDbmsDataAddenda.setPkDocId(mnPkDocId); moDbmsDataAddenda.setLorealFolioNotaRecepcion(moAuxCfdParams.getLorealFolioNotaRecepcion()); moDbmsDataAddenda.setBachocoSociedad(moAuxCfdParams.getBachocoSociedad()); moDbmsDataAddenda.setBachocoOrganizacionCompra(moAuxCfdParams.getBachocoOrganizacionCompra()); moDbmsDataAddenda.setBachocoDivision(moAuxCfdParams.getBachocoDivision()); moDbmsDataAddenda.setModeloDpsDescripcion(moAuxCfdParams.getModeloDpsDescripcion()); moDbmsDataAddenda.setSorianaTienda(moAuxCfdParams.getSorianaTienda()); moDbmsDataAddenda.setSorianaEntregaMercancia(moAuxCfdParams.getSorianaEntregaMercancia()); moDbmsDataAddenda.setSorianaRemisionFecha(moAuxCfdParams.getSorianaFechaRemision() == null ? mtDate : moAuxCfdParams.getSorianaFechaRemision()); moDbmsDataAddenda.setSorianaRemisionFolio(moAuxCfdParams.getSorianaFolioRemision()); moDbmsDataAddenda.setSorianaPedidoFolio(moAuxCfdParams.getSorianaFolioPedido()); moDbmsDataAddenda.setSorianaBultoTipo(moAuxCfdParams.getSorianaTipoBulto()); moDbmsDataAddenda.setSorianaBultoCantidad(moAuxCfdParams.getSorianaCantidadBulto()); moDbmsDataAddenda.setSorianaNotaEntradaFolio(moAuxCfdParams.getSorianaNotaEntradaFolio()); moDbmsDataAddenda.setCfdAddendaSubtype(moAuxCfdParams.getCfdAddendaSubtype()); moDbmsDataAddenda.setFkCfdAddendaTypeId(moAuxCfdParams.getTipoAddenda()); moDbmsDataAddenda.getDbmsDpsAddEntries().clear(); for (SDataDpsEntry entry : mvDbmsDpsEntries) { moDataAddendaEntry = new SDataDpsAddendaEntry(); moDataAddendaEntry.setPkYearId(entry.getPkYearId()); moDataAddendaEntry.setPkDocId(entry.getPkDocId()); moDataAddendaEntry.setPkEntryId(entry.getPkEntryId()); moDataAddendaEntry.setBachocoNumeroPosicion(entry.getDbmsDpsAddBachocoNumberPosition()); moDataAddendaEntry.setBachocoCentro(entry.getDbmsDpsAddBachocoCenter()); moDataAddendaEntry.setLorealEntryNumber(entry.getDbmsDpsAddLorealEntryNumber()); moDataAddendaEntry.setSorianaCodigo(entry.getDbmsDpsAddSorianaBarCode()); moDataAddendaEntry.setElektraOrder(entry.getDbmsDpsAddElektraOrder()); moDataAddendaEntry.setElektraBarcode(entry.getDbmsDpsAddElektraBarcode()); moDataAddendaEntry.setElektraCages(entry.getDbmsDpsAddElektraCages()); moDataAddendaEntry.setElektraCagePriceUnitary(entry.getDbmsDpsAddElektraCagePriceUnitary()); moDataAddendaEntry.setElektraParts(entry.getDbmsDpsAddElektraParts()); moDataAddendaEntry.setElektraPartPriceUnitary(entry.getDbmsDpsAddElektraPartPriceUnitary()); moDbmsDataAddenda.getDbmsDpsAddEntries().add(moDataAddendaEntry); } if (moAuxCfdParams.getTipoAddenda() != SDataConstantsSys.BPSS_TP_CFD_ADD_NA) { if (moDbmsDataAddenda.save(connection) != SLibConstants.DB_ACTION_SAVE_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE_DEP); } } else { if (moDbmsDataAddenda.delete(connection) != SLibConstants.DB_ACTION_DELETE_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_DELETE_DEP); } } } // Save XML of purchases when provided: if (moDbmsDataCfd != null && mnFkDpsCategoryId == SDataConstantsSys.TRNS_CT_DPS_PUR) { moDbmsDataCfd.setFkDpsYearId_n(mnPkYearId); moDbmsDataCfd.setFkDpsDocId_n(mnPkDocId); moDbmsDataCfd.setTimestamp(mtDate); if (moDbmsDataCfd.save(connection) != SLibConstants.DB_ACTION_SAVE_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE_DEP); } } mbIsRegistryNew = false; mnLastDbActionResult = SLibConstants.DB_ACTION_SAVE_OK; } } catch (SQLException e) { mnLastDbActionResult = SLibConstants.DB_ACTION_SAVE_ERROR; SLibUtilities.printOutException(this, e); } catch (Exception e) { mnLastDbActionResult = SLibConstants.DB_ACTION_SAVE_ERROR; SLibUtilities.printOutException(this, e); } return mnLastDbActionResult; } @Override public java.util.Date getLastDbUpdate() { return mtUserEditTs; } @Override public int canSave(java.sql.Connection connection) { int[] anMoveSubclassKey = null; Object[] oRecordKey = null; String sSql = ""; String sTax = ""; String sItem = ""; String sAccountId = ""; Statement oStatement = null; ResultSet oResultSet = null; Vector<SFinAccountConfigEntry> vAccountConfigs = null; SFinTaxes oFinanceTaxes = null; mnLastDbActionResult = SLibConstants.DB_CAN_SAVE_YES; // Check if all elements of this DPS have an account for automatic accounting: try { //System.out.println("dps canSave 1"); anMoveSubclassKey = getAccountingMoveSubclassKey(); //System.out.println("dps canSave 2"); if (anMoveSubclassKey != null) { // Current document needs an accounting record: //System.out.println("dps canSave 2.1"); oStatement = connection.createStatement(); oFinanceTaxes = new SFinTaxes(oStatement); //System.out.println("dps canSave 2.2"); oRecordKey = (Object[]) createAccountingRecordKey(oStatement); // 1. Check business partner's liability or asset: //System.out.println("dps canSave 2.3"); try { vAccountConfigs = SFinAccountUtilities.obtainBizPartnerAccountConfigs( mnFkBizPartnerId_r, getBizPartnerCategoryId(), (Integer) oRecordKey[2], mtDate, SDataConstantsSys.FINS_TP_ACC_BP_OP, isDebitForBizPartner(), oStatement); } catch (Exception e) { msDbmsError = "No se encontró la configuración de las cuentas contables de sistema para el asociado de negocios.\n[" + e + "]"; throw new Exception(msDbmsError); } // 2. Check purchases or sales: //System.out.println("dps canSave 2.4"); for (SDataDpsEntry entry : mvDbmsDpsEntries) { //System.out.println("dps canSave 2.4.1"); if (entry.isAccountable()) { //System.out.println("dps canSave 2.4.1.1"); try { if (entry.getFkItemRefId_n() == 0) { sItem = entry.getConcept(); } else { sSql = "SELECT item FROM erp.itmu_item WHERE id_item = " + entry.getFkItemRefId_n() + " "; oResultSet = oStatement.executeQuery(sSql); if (!oResultSet.next()) { msDbmsError = "No se encontró el nombre del ítem " + entry.getFkItemRefId_n() + "."; throw new Exception(msDbmsError); } else { sItem = oResultSet.getString("item"); } } vAccountConfigs = SFinAccountUtilities.obtainItemAccountConfigs( entry.getFkItemRefId_n() != 0 ? entry.getFkItemRefId_n() : entry.getFkItemId(), (Integer) oRecordKey[2], mtDate, getItemAccountTypeId(entry), isDebitForOperations(), oStatement); for (SFinAccountConfigEntry config : vAccountConfigs) { sAccountId = config.getAccountId(); sAccountId = sAccountId.replaceAll("0", ""); sAccountId = sAccountId.replaceAll("-", ""); if (sAccountId.length() == 0) { msDbmsError = "La configuración de las cuentas contables de sistema para el ítem:\n'" + sItem + "' es la cuenta vacía."; throw new Exception(msDbmsError); } } } catch (Exception e) { msDbmsError = "No se encontró la configuración de las cuentas contables de sistema para el ítem:\n'" + sItem + "'.\n[" + e + "]"; throw new Exception(msDbmsError); } for (SDataDpsEntryTax tax : entry.getDbmsEntryTaxes()) { oFinanceTaxes.addTax(isDocument() ? new int[] { mnPkYearId, mnPkDocId } : new int[] { entry.getAuxPkDpsYearId(), entry.getAuxPkDpsDocId() }, new int[] { tax.getPkTaxBasicId(), tax.getPkTaxId() }, tax.getTax(), tax.getTaxCy()); } } } // 3. Check purchases or sales taxes: //System.out.println("dps canSave 2.5"); for (SFinTaxes.STax tax : oFinanceTaxes.getTaxes()) { try { sAccountId = SFinAccountUtilities.obtainTaxAccountId(tax.getTaxKey(), mnFkDpsCategoryId, mtDate, tax.getFkTaxApplicationTypeId() == SModSysConsts.FINS_TP_TAX_APP_ACCR ? SDataConstantsSys.FINX_ACC_PAY : SDataConstantsSys.FINX_ACC_PAY_PEND, oStatement); } catch (Exception e) { // Read tax name: sSql = "SELECT tax FROM erp.finu_tax WHERE id_tax_bas = " + tax.getPkTaxBasicId() + " AND id_tax = " + tax.getPkTaxId() + " "; oResultSet = oStatement.executeQuery(sSql); if (!oResultSet.next()) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } else { sTax = oResultSet.getString("tax"); } msDbmsError = "No se encontró la configuración de las cuentas contables de sistema para el impuesto:\n'" + sTax + "'.\n[" + e + "]"; throw new Exception(msDbmsError); } } //System.out.println("dps canSave 2.6"); } } catch (SQLException exception) { mnLastDbActionResult = SLibConstants.DB_CAN_SAVE_NO; if (msDbmsError.isEmpty()) { msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_SAVE; } SLibUtilities.printOutException(this, exception); } catch (Exception exception) { mnLastDbActionResult = SLibConstants.DB_CAN_SAVE_NO; if (msDbmsError.isEmpty()) { msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_SAVE; } SLibUtilities.printOutException(this, exception); } return mnLastDbActionResult; } @Override public int canAnnul(java.sql.Connection connection) { mnLastDbActionResult = SLibConstants.UNDEFINED; try { if (testDeletion(connection, "No se puede anular el documento: ", SDbConsts.ACTION_ANNUL)) { mnLastDbActionResult = SLibConstants.DB_CAN_ANNUL_YES; } } catch (SQLException exception) { mnLastDbActionResult = SLibConstants.DB_CAN_ANNUL_NO; if (msDbmsError.isEmpty()) { msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_ANNUL; } SLibUtilities.printOutException(this, exception); } catch (Exception exception) { mnLastDbActionResult = SLibConstants.DB_CAN_ANNUL_NO; if (msDbmsError.isEmpty()) { msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_ANNUL; } SLibUtilities.printOutException(this, exception); } return mnLastDbActionResult; } @Override public int canDelete(java.sql.Connection connection) { mnLastDbActionResult = SLibConstants.UNDEFINED; try { if (testDeletion(connection, "No se puede eliminar el documento: ", SDbConsts.ACTION_DELETE)) { mnLastDbActionResult = SLibConstants.DB_CAN_DELETE_YES; } } catch (SQLException exception) { mnLastDbActionResult = SLibConstants.DB_CAN_DELETE_NO; if (msDbmsError.isEmpty()) { msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_DELETE; } SLibUtilities.printOutException(this, exception); } catch (Exception exception) { mnLastDbActionResult = SLibConstants.DB_CAN_DELETE_NO; if (msDbmsError.isEmpty()) { msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_DELETE; } SLibUtilities.printOutException(this, exception); } return mnLastDbActionResult; } @Override public int annul(java.sql.Connection connection) { int nDecs = 2; String sSql = ""; String sMsg = "No se puede anular el documento: "; Statement oStatement = null; ResultSet oResultSet = null; mnLastDbActionResult = SLibConstants.UNDEFINED; try { oStatement = connection.createStatement(); if (mbIsRegistryRequestAnnul) { // Set DPS as annuled: if (testDeletion(connection, sMsg, SDbConsts.ACTION_ANNUL)) { mnFkDpsStatusId = SDataConstantsSys.TRNS_ST_DPS_ANNULED; sSql = "UPDATE trn_dps SET fid_st_dps = " + SDataConstantsSys.TRNS_ST_DPS_ANNULED + ", " + "stot_prov_r = 0, disc_doc_r = 0, stot_r = 0, tax_charged_r = 0, tax_retained_r = 0, tot_r = 0, " + "stot_prov_cur_r = 0, disc_doc_cur_r = 0, stot_cur_r = 0, tax_charged_cur_r = 0, tax_retained_cur_r = 0, tot_cur_r = 0, " + "fid_usr_edit = " + mnFkUserEditId + ", ts_edit = NOW() " + "WHERE id_year = " + mnPkYearId + " AND id_doc = " + mnPkDocId + " "; oStatement.execute(sSql); if (moAuxFormerRecordKey != null) { // If document had automatic accounting record, delete it including its header: deleteRecord(moAuxFormerRecordKey, mbAuxIsFormerRecordAutomatic, connection); } deleteLinks(oStatement); if (moDbmsDataCfd != null) { moDbmsDataCfd.annul(connection); } mnLastDbActionResult = SLibConstants.DB_ACTION_ANNUL_OK; } } else { // Revert DPS annulation: if (testRevertDeletion(sMsg, SDbConsts.ACTION_ANNUL)) { // 1. Set DPS fields: mnFkDpsStatusId = SDataConstantsSys.TRNS_ST_DPS_EMITED; // 2. Obtain decimals for calculations: sSql = "SELECT decs_val FROM erp.cfg_param_erp WHERE id_erp = 1 "; oResultSet = oStatement.executeQuery(sSql); if (oResultSet.next()) { nDecs = oResultSet.getInt("decs_val"); } // 3. Recalculate DPS value: calculateDpsTotal(null, nDecs); // 4. Save DPS again (this will re-create accounting record again): if (save(connection) == SLibConstants.DB_ACTION_SAVE_OK) { mnLastDbActionResult = SLibConstants.DB_ACTION_ANNUL_OK; } } } } catch (SQLException exception) { mnLastDbActionResult = SLibConstants.DB_ACTION_ANNUL_ERROR; SLibUtilities.printOutException(this, exception); } catch (Exception exception) { mnLastDbActionResult = SLibConstants.DB_ACTION_ANNUL_ERROR; SLibUtilities.printOutException(this, exception); } return mnLastDbActionResult; } @Override public int delete(java.sql.Connection connection) { String sSql = ""; String sMsg = "No se puede eliminar el documento: "; Statement oStatement = null; mnLastDbActionResult = SLibConstants.UNDEFINED; try { oStatement = connection.createStatement(); if (mbIsRegistryRequestDelete) { // Set DPS as deleted: if (testDeletion(connection, sMsg, SDbConsts.ACTION_DELETE)) { mbIsDeleted = true; sSql = "UPDATE trn_dps SET b_del = 1, fid_usr_del = " + mnFkUserDeleteId + ", ts_del = NOW() " + "WHERE id_year = " + mnPkYearId + " AND id_doc = " + mnPkDocId + " "; oStatement.execute(sSql); if (moAuxFormerRecordKey != null) { // If document had automatic accounting record, delete it including its header: deleteRecord(moAuxFormerRecordKey, mbAuxIsFormerRecordAutomatic, connection); } deleteLinks(oStatement); clearEntryDeliveryReferences(oStatement); mnLastDbActionResult = SLibConstants.DB_ACTION_DELETE_OK; } } else { // Revert DPS deletion: if (testRevertDeletion(sMsg, SDbConsts.ACTION_DELETE)) { // 1. Set DPS fields: mbIsDeleted = false; // 4. Save DPS again (this will re-create accounting record again): if (save(connection) == SLibConstants.DB_ACTION_SAVE_OK) { mnLastDbActionResult = SLibConstants.DB_ACTION_DELETE_OK; } else { throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE); } } } } catch (SQLException exception) { mnLastDbActionResult = SLibConstants.DB_ACTION_DELETE_ERROR; SLibUtilities.printOutException(this, exception); } catch (Exception exception) { mnLastDbActionResult = SLibConstants.DB_ACTION_DELETE_ERROR; SLibUtilities.printOutException(this, exception); } return mnLastDbActionResult; } /** * Calculates DPS value. * @param client ERP Client. Can be null, and each DPS entry is not calculated, original values remains as the original ones. */ public void calculateTotal(erp.client.SClientInterface client) throws SQLException, Exception { calculateDpsTotal(client, 0); } /** * Resets all members related to accounting record. */ public void resetRecord() { moDbmsRecordKey = null; mtDbmsRecordDate = null; mbAuxIsFormerRecordAutomatic = false; moAuxFormerRecordKey = null; } /** * Create addenda for L'Oreal * @param dIvaPct Tax rate applied to DPS * @return Addenda * @throws java.lang.Exception */ private DElementFacturainterfactura computeAddendaLoreal(double dIvapct) throws java.lang.Exception { int nMoneda = 0; int nCondigoPago = 0; double dIvaPctCuerpo = 0; java.util.Date tDate = null; GregorianCalendar oGregorianCalendar = null; int[] anDateDps = SLibTimeUtilities.digestDate(mtDate); int[] anDateEdit = SLibTimeUtilities.digestDate(mtUserEditTs); Vector<DElementCuerpo> vCuerpo = new Vector<>(); if (SLibUtilities.compareKeys(anDateDps, anDateEdit)) { tDate = mtUserEditTs; } else { oGregorianCalendar = new GregorianCalendar(); oGregorianCalendar.setTime(mtUserEditTs); oGregorianCalendar.set(GregorianCalendar.YEAR, anDateDps[0]); oGregorianCalendar.set(GregorianCalendar.MONTH, anDateDps[1] - 1); // January is month 0 oGregorianCalendar.set(GregorianCalendar.DATE, anDateDps[2]); tDate = oGregorianCalendar.getTime(); } nCondigoPago = moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getEffectiveDaysOfCredit(); for (SDataDpsEntry entry : mvDbmsDpsEntries) { if (entry.isAccountable()) { DElementCuerpo cuerpo = new DElementCuerpo(); dIvaPctCuerpo = entry.getDbmsEntryTaxes().get(0).getPercentage() * 100; if (dIvapct == dIvaPctCuerpo) { cuerpo.getAttPartida().setInteger(entry.getDbmsDpsAddLorealEntryNumber()); cuerpo.getAttCantidad().setDouble(entry.getOriginalQuantity()); cuerpo.getAttConcepto().setString(entry.getConcept()); cuerpo.getAttPUnitario().setDouble(entry.getPriceUnitary()); cuerpo.getAttImporte().setDouble(entry.getSubtotal_r()); cuerpo.getAttUnidadMedida().setString(entry.getDbmsUnitSymbol().toUpperCase()); } else { cuerpo.getAttPartida().setInteger(entry.getDbmsDpsAddLorealEntryNumber()); cuerpo.getAttCantidad().setDouble(entry.getOriginalQuantity()); cuerpo.getAttConcepto().setString(entry.getConcept()); cuerpo.getAttPUnitario().setDouble(entry.getPriceUnitary()); cuerpo.getAttImporte().setDouble(entry.getSubtotal_r()); cuerpo.getAttUnidadMedida().setString(entry.getDbmsUnitSymbol().toUpperCase()); cuerpo.getAttIva().setDouble(entry.getTaxCharged_r()); cuerpo.getAttIVAPCT().setDouble(dIvaPctCuerpo); } vCuerpo.add(cuerpo); } } switch (mnFkCurrencyId) { case 1: // MXN nMoneda = DAttributeOptionMoneda.CFD_MXN; break; case 2: // USD nMoneda = DAttributeOptionMoneda.CFD_USD; break; case 3: // EUR nMoneda = DAttributeOptionMoneda.CFD_EUR; break; default: throw new Exception("La moneda debe ser conocida (" + mnFkCurrencyId + ")."); } DElementFacturainterfactura addendaLoreal = new DElementFacturainterfactura(); addendaLoreal.getAttxmlns().setString("https: addendaLoreal.getAttTipoDocumento().setString("Factura"); addendaLoreal.getAttschemaLocation().setString("https: addendaLoreal.getEltEmisor().getAttRefEmisor().setString("0103399"); addendaLoreal.getEltReceptor().getAttRefReceptor().setString("0101427"); addendaLoreal.getEltEncabezado().getAttMoneda().setOption(nMoneda); addendaLoreal.getEltEncabezado().getAttFolioOrdenCompra().setString(msNumberReference); addendaLoreal.getEltEncabezado().getAttFolioNotaRecepcion().setString(moAuxCfdParams.getLorealFolioNotaRecepcion()); addendaLoreal.getEltEncabezado().getAttFecha().setDatetime(tDate); addendaLoreal.getEltEncabezado().getAttCondicionPago().setString("" + nCondigoPago); addendaLoreal.getEltEncabezado().getAttIVAPCT().setDouble(dIvapct); addendaLoreal.getEltEncabezado().getAttNumProveedor().setString(moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey()); addendaLoreal.getEltEncabezado().getAttCargoTipo().setString(""); addendaLoreal.getEltEncabezado().getAttSubTotal().setDouble(mdSubtotal_r); addendaLoreal.getEltEncabezado().getAttSerie().setString(msNumberSeries); addendaLoreal.getEltEncabezado().getAttFolio().setString(msNumber); addendaLoreal.getEltEncabezado().getAttIva().setDouble(mdTaxCharged_r); addendaLoreal.getEltEncabezado().getAttTotal().setDouble(mdTotal_r); addendaLoreal.getEltEncabezado().getAttObservaciones().setString(""); addendaLoreal.getEltEncabezado().getEltHijosEncabezado().addAll(vCuerpo); return addendaLoreal; } /** * Create addenda for Bachoco * @param dIvaPct Tax rate applied to DPS * @return Addenda * @throws java.lang.Exception */ private DElementPayment computeAddendaBachoco(double dIvapct) throws java.lang.Exception { int nMoneda = 0; String sStatusDoc = ""; String sEntityType = ""; String sReceptorNumber = ""; java.util.Date tDate = null; GregorianCalendar oGregorianCalendar = null; SimpleDateFormat oSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); int[] anDateDps = SLibTimeUtilities.digestDate(mtDate); int[] anDateEdit = SLibTimeUtilities.digestDate(mtUserEditTs); int[] anTypeDoc = {mnFkDpsCategoryId, mnFkDpsClassId, mnFkDpsTypeId}; Vector<DElementLineItem> vLineItem = new Vector<>(); if (SLibUtilities.compareKeys(anDateDps, anDateEdit)) { tDate = mtUserEditTs; } else { oGregorianCalendar = new GregorianCalendar(); oGregorianCalendar.setTime(mtUserEditTs); oGregorianCalendar.set(GregorianCalendar.YEAR, anDateDps[0]); oGregorianCalendar.set(GregorianCalendar.MONTH, anDateDps[1] - 1); // January is month 0 oGregorianCalendar.set(GregorianCalendar.DATE, anDateDps[2]); tDate = oGregorianCalendar.getTime(); oSimpleDateFormat.format(tDate); } switch (mnFkDpsStatusId) { case SDataConstantsSys.TRNS_ST_DPS_EMITED: sStatusDoc = "ORIGINAL"; break; case SDataConstantsSys.TRNS_ST_DPS_ANNULED: sStatusDoc = "DELETE"; break; default: break; } if (SLibUtilities.compareKeys(anTypeDoc, SDataConstantsSys.TRNU_TP_DPS_SAL_INV)) { sEntityType = "INVOICE"; } else if (SLibUtilities.compareKeys(anTypeDoc, SDataConstantsSys.TRNU_TP_DPS_SAL_CN)) { sEntityType = "CREDIT_NOTE"; } for (int i = 0; i < (10 - moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey().length()); i++) { sReceptorNumber += "0"; } sReceptorNumber += moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey(); for (SDataDpsEntry entry : mvDbmsDpsEntries) { if (entry.isAccountable()) { DElementLineItem vItem = new DElementLineItem(); vItem.getAttType().setString("SimpleinvoiceLineItemType"); vItem.getAttNumber().setInteger(entry.getDbmsDpsAddBachocoNumberPosition()); vItem.getEltTradeItemIdentification().getEltGtin().setValue(entry.getDbmsDpsAddBachocoCenter()); vItem.getEltAditionalQuantity().getAttQuantityType().setString("NUM_CONSUMER_UNITS"); // XXX UNIDAD CONSUMO vItem.getEltAditionalQuantity().setValue("" + entry.getOriginalQuantity()); vItem.getEltNetPrice().getEltAmount().setValue("" + entry.getPriceUnitary()); vItem.getEltAdditionalInformation().getEltReferenceIdentification().getAttType().setString("ON"); vItem.getEltAdditionalInformation().getEltReferenceIdentification().setValue("X"); // ORDEN DE INVERSION vLineItem.add(vItem); } } switch (mnFkCurrencyId) { case 1: // MXN nMoneda = DAttributeOptionMoneda.CFD_MXN; break; case 2: // USD nMoneda = DAttributeOptionMoneda.CFD_USD; break; case 3: // EUR nMoneda = DAttributeOptionMoneda.CFD_EUR; break; default: throw new Exception("La moneda debe ser conocida (" + mnFkCurrencyId + ")."); } DElementPayment addendaBachoco = new DElementPayment(); addendaBachoco.getAttType().setString("SimpleInvoiceType"); addendaBachoco.getAttContentVersion().setString("1.3.1"); addendaBachoco.getAttDocStructureVersion().setString("AMC7.1"); addendaBachoco.getAttDocStatus().setString(sStatusDoc); addendaBachoco.getAttDeliveryDate().setDate(tDate); addendaBachoco.getEltPaymentIdentification().getEltEntityType().setValue(sEntityType); addendaBachoco.getEltPaymentIdentification().getEltCreatorIdentification().setValue(msNumberSeries + msNumber); addendaBachoco.getEltSpecialInstruction().getAttCode().setString("PUR"); addendaBachoco.getEltSpecialInstruction().getEltText().setValue("X"); addendaBachoco.getEltOrderIdentification().getEltReferenceIdentification().getAttType().setString("ON"); addendaBachoco.getEltOrderIdentification().getEltReferenceIdentification().setValue(msNumberReference); addendaBachoco.getEltDeliveryNote().getEltReferenceIdentification().setValue(moAuxCfdParams.getBachocoDivision()); addendaBachoco.getEltBuyer().getEltGln().setValue("X"); addendaBachoco.getEltBuyer().getEltContactInformation().getEltPersonOrDepartmentName().getEltText().setValue(moAuxCfdParams.getBachocoOrganizacionCompra()); addendaBachoco.getEltSeller().getEltGln().setValue(sReceptorNumber); addendaBachoco.getEltShipTo().getEltGln().setValue(moAuxCfdParams.getBachocoSociedad()); addendaBachoco.getEltInvoiceCreator().getEltAlternatePartyIdentification().getAttType().setString("IA"); addendaBachoco.getEltInvoiceCreator().getEltAlternatePartyIdentification().setValue(sReceptorNumber); addendaBachoco.getEltCustoms().getEltAlternatePartyIdentification().getAttType().setString("TN"); addendaBachoco.getEltCustoms().getEltAlternatePartyIdentification().setValue("X"); // XXX No. PEDIMENTO addendaBachoco.getEltCurrency().getAttCurrencyISOCode().setOption(nMoneda); addendaBachoco.getEltCurrency().getEltCurrencyFunction().setValue("BILLING_CURRENCY"); // DIVISA DE FACTURACION addendaBachoco.getEltItem().getEltHijosLineItem().addAll(vLineItem); addendaBachoco.getEltTotalAmount().getEltAmount().setValue("" + mdSubtotalCy_r); addendaBachoco.getEltTax().getAttType().setString("VAT"); // XXX IMPUESTO addendaBachoco.getEltTax().getEltTaxPercentage().setValue("" + dIvapct); addendaBachoco.getEltTax().getEltTaxAmount().setValue("" + mdTaxCharged_r); addendaBachoco.getEltTax().getEltTaxCategory().setValue("TRANSFERIDO"); // XXX TIPO IMPUESTO addendaBachoco.getEltPayableAmount().getEltAmount().setValue("" + mdTotal_r); return addendaBachoco; } /** * Create addenda for Soriana * @return Addenda * @throws java.lang.Exception */ private DElementDSCargaRemisionProv computeAddendaSoriana() throws java.lang.Exception { int totalItems = 0; Date tDate = null; GregorianCalendar oGregorianCalendar = null; SimpleDateFormat oSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); int[] anDateDps = SLibTimeUtilities.digestDate(mtDate); int[] anDateEdit = SLibTimeUtilities.digestDate(mtUserEditTs); Vector<DElementArticulos> vArticulos = new Vector<>(); if (SLibUtilities.compareKeys(anDateDps, anDateEdit)) { tDate = mtUserEditTs; } else { oGregorianCalendar = new GregorianCalendar(); oGregorianCalendar.setTime(mtUserEditTs); oGregorianCalendar.set(GregorianCalendar.YEAR, anDateDps[0]); oGregorianCalendar.set(GregorianCalendar.MONTH, anDateDps[1] - 1); // January is month 0 oGregorianCalendar.set(GregorianCalendar.DATE, anDateDps[2]); tDate = oGregorianCalendar.getTime(); oSimpleDateFormat.format(tDate); } DElementDSCargaRemisionProv addendaSoriana = new DElementDSCargaRemisionProv(); totalItems = 0; for (SDataDpsEntry entry : mvDbmsDpsEntries) { if (entry.isAccountable()) { DElementArticulos vItem = new DElementArticulos(); vItem.getEltProveedor().setValue(moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey()); vItem.getEltRemision().setValue("" + moAuxCfdParams.getSorianaFolioRemision()); // Serie - Folio del XML (Factura) vItem.getEltFolio().setValue(moAuxCfdParams.getSorianaFolioPedido()); // Folio del pedido vItem.getEltTienda().setValue("" + moAuxCfdParams.getSorianaTienda()); vItem.getEltCodigoBarras().setValue(entry.getDbmsDpsAddSorianaBarCode()); vItem.getEltCantCompra().setValue("" + entry.getOriginalQuantity()); vItem.getEltCostoNeto().setValue("" + entry.getPriceUnitary()); vItem.getEltIeps().setValue("0.00"); vItem.getEltIva().setValue("0.00"); vArticulos.add(vItem); totalItems += entry.getOriginalQuantity(); } } addendaSoriana.getEltRemision().getEltProveedor().setValue(moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey()); addendaSoriana.getEltRemision().getEltRemision().setValue("" + moAuxCfdParams.getSorianaFolioRemision()); // Serie - Folio del XML (Factura) addendaSoriana.getEltRemision().getEltConsecutivo().setValue("0"); // Si se entrega en parcialidades addendaSoriana.getEltRemision().getEltFechaRemision().setValue("" + moAuxCfdParams.getSorianaFechaRemision() + "T00:00:00"); addendaSoriana.getEltRemision().getEltTienda().setValue("" + moAuxCfdParams.getSorianaTienda()); addendaSoriana.getEltRemision().getEltTipoMoneda().setValue("" + mnFkCurrencyId); addendaSoriana.getEltRemision().getEltTipoBulto().setValue("" + moAuxCfdParams.getSorianaTipoBulto()); addendaSoriana.getEltRemision().getEltEntregaMercancia().setValue("" + moAuxCfdParams.getSorianaEntregaMercancia()); addendaSoriana.getEltRemision().getEltCumpleFiscal().setValue("true"); addendaSoriana.getEltRemision().getEltCantidadBultos().setValue("" + moAuxCfdParams.getSorianaCantidadBulto()); addendaSoriana.getEltRemision().getEltSubTotal().setValue("" + mdSubtotal_r); addendaSoriana.getEltRemision().getEltDescuentos().setValue("" + mdDiscountDoc_r); addendaSoriana.getEltRemision().getEltIeps().setValue("0.00"); // Si no aplica indicar 0 addendaSoriana.getEltRemision().getEltIva().setValue("0.00"); // Si no aplica indicar 0 addendaSoriana.getEltRemision().getEltOtrosImpuestos().setValue("0.00"); // Otros imptos ej. retenciones addendaSoriana.getEltRemision().getEltTotal().setValue("" + mdTotal_r); addendaSoriana.getEltRemision().getEltCantidadPedidos().setValue("1"); addendaSoriana.getEltRemision().getEltFechaEntrega().setValue("" + (mtDateDocDelivery_n == null ? mtDate : mtDateDocDelivery_n) + "T00:00:00"); addendaSoriana.getEltPedido().getEltProveedor().setValue(moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey()); addendaSoriana.getEltPedido().getEltRemision().setValue("" + moAuxCfdParams.getSorianaFolioRemision()); // Serie - Folio del XML (Factura) addendaSoriana.getEltPedido().getEltFolio().setValue(moAuxCfdParams.getSorianaFolioPedido()); // Folio del pedido addendaSoriana.getEltPedido().getEltTienda().setValue("" + moAuxCfdParams.getSorianaTienda()); addendaSoriana.getEltPedido().getEltCantArticulos().setValue("" + totalItems); if (moAuxCfdParams.getCfdAddendaSubtype() == SDataConstantsSys.BPSS_STP_CFD_ADD_SORIANA_EXT) { cfd.ext.soriana.DElementPedidoEmitidoProveedor pedidoEmitidoProveedor = new cfd.ext.soriana.DElementPedidoEmitidoProveedor("SI"); cfd.ext.soriana.DElementFolioNotaEntrada folioNotaEntrada = new DElementFolioNotaEntrada(moAuxCfdParams.getSorianaNotaEntradaFolio()); addendaSoriana.getEltRemision().setEltOpcFolioNotaEntrada(folioNotaEntrada); addendaSoriana.getEltPedido().setEltOpcPedidoEmitidoProveedor(pedidoEmitidoProveedor); } addendaSoriana.getEltArticulos().getEltHijosArticulos().addAll(vArticulos); //addendaSoriana.getEltCajas().getEltRemision().setValue("A-00047"); //addendaSoriana.getEltArticulosCajas().getEltRemision().setValue("A-00047"); return addendaSoriana; } /** * Create addenda for Grupo Modelo * @param dIvaPct Tax rate applied to DPS * @return Addenda * @throws java.lang.Exception */ @SuppressWarnings("empty-statement") private cfd.ext.grupomodelo.DElementAddendaModelo computeAddendaGrupoModelo(double dIvapct) throws java.lang.Exception { int nMoneda = 0; int nQty = 0; int nIvaPercentage = 0; String sStatusDoc = ""; String sEntityType = ""; String sReceptorNumber = ""; java.util.Date tDate = null; GregorianCalendar oGregorianCalendar = null; SimpleDateFormat oSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); DecimalFormat oDecimalFormat = new DecimalFormat("#0.00"); int[] anDateDps = SLibTimeUtilities.digestDate(mtDate); int[] anDateEdit = SLibTimeUtilities.digestDate(mtUserEditTs); int[] anTypeDoc = {mnFkDpsCategoryId, mnFkDpsClassId, mnFkDpsTypeId}; Vector<cfd.ext.grupomodelo.DElementLineItem> vLineItem = new Vector<>(); if (SLibUtilities.compareKeys(anDateDps, anDateEdit)) { tDate = mtUserEditTs; } else { oGregorianCalendar = new GregorianCalendar(); oGregorianCalendar.setTime(mtUserEditTs); oGregorianCalendar.set(GregorianCalendar.YEAR, anDateDps[0]); oGregorianCalendar.set(GregorianCalendar.MONTH, anDateDps[1] - 1); // January is month 0 oGregorianCalendar.set(GregorianCalendar.DATE, anDateDps[2]); tDate = oGregorianCalendar.getTime(); oSimpleDateFormat.format(tDate); } switch (mnFkDpsStatusId) { case SDataConstantsSys.TRNS_ST_DPS_EMITED: sStatusDoc = "ORIGINAL"; break; case SDataConstantsSys.TRNS_ST_DPS_ANNULED: sStatusDoc = "DELETE"; break; } if (SLibUtilities.compareKeys(anTypeDoc, SDataConstantsSys.TRNU_TP_DPS_SAL_INV)) { sEntityType = "FA"; } sReceptorNumber += moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getCompanyKey(); nIvaPercentage = (int) dIvapct; for (SDataDpsEntry entry : mvDbmsDpsEntries) { if (entry.isAccountable()) { nQty = (int) entry.getOriginalQuantity(); int[] anSubTypeDoc = { entry.getFkDpsAdjustmentTypeId(), entry.getFkDpsAdjustmentSubtypeId() }; cfd.ext.grupomodelo.DElementLineItem vItem = new cfd.ext.grupomodelo.DElementLineItem(); vItem.getAttType().setString("SimpleinvoiceLineItemType"); vItem.getAttNumber().setInteger(entry.getSortingPosition() * 10); vItem.getEltTradeItemIdentification().getEltGtin().setValue(entry.getConceptKey()); vItem.getEltAlternateTradeItemIdentification().getAttType().setString("BUYER_ASSIGNED"); vItem.getEltAlternateTradeItemIdentification().setValue(sReceptorNumber); vItem.getEltTradeItemDescriptionInformation().getAttLanguage().setString("ES"); vItem.getEltTradeItemDescriptionInformation().getEltLongText().setValue(entry.msConcept.length() > 35 ? entry.msConcept.substring(0, 34) : entry.msConcept); vItem.getEltInvoicedQuantity().getAttUnit().setString(entry.getDbmsOriginalUnitSymbol()); vItem.getEltInvoicedQuantity().setValue("" + nQty); vItem.getEltGrossPrice().getEltAmount().setValue("" + oDecimalFormat.format(entry.getPriceUnitaryCy())); vItem.getEltNetPrice().getEltAmount().setValue("" + oDecimalFormat.format(entry.getTotalCy_r() / entry.getOriginalQuantity())); vItem.getEltAdditionalInformation().getEltReferenceIdentification().getAttType().setString("DQ"); vItem.getEltAdditionalInformation().getEltReferenceIdentification().setValue(msNumberSeries + msNumber); vItem.getEltTradeItemTaxInformation().getEltTaxTypeDescription().setValue("VAT"); vItem.getEltTradeItemTaxInformation().getEltTaxCategory().setValue("TRANSFERIDO"); vItem.getEltTradeItemTaxInformation().getEltItemTaxAmount().getEltTaxPercentage().setValue("" + nIvaPercentage); vItem.getEltTradeItemTaxInformation().getEltItemTaxAmount().getEltTaxAmount().setValue("" + oDecimalFormat.format(entry.getPriceUnitaryCy() * (dIvapct / 100))); vItem.getEltTotalLineAmount().getEltGrossAmount().getEltAmount().setValue("" + oDecimalFormat.format(entry.getSubtotalCy_r())); vItem.getEltTotalLineAmount().getEltNetAmount().getEltAmount().setValue("" + oDecimalFormat.format(entry.getTotalCy_r())); vLineItem.add(vItem); if (SLibUtilities.compareKeys(anSubTypeDoc, SDataConstantsSys.TRNS_STP_DPS_ADJ_RET_RET)) { sEntityType = "ND"; } else if (SLibUtilities.compareKeys(anSubTypeDoc, SDataConstantsSys.TRNS_STP_DPS_ADJ_DISC_PRICE)) { sEntityType = "NA"; } else if (SLibUtilities.compareKeys(anSubTypeDoc, SDataConstantsSys.TRNS_STP_DPS_ADJ_DISC_DISC)) { sEntityType = "NE"; } } } switch (mnFkCurrencyId) { case 1: // MXN nMoneda = DAttributeOptionMoneda.CFD_MXN; break; case 2: // USD nMoneda = DAttributeOptionMoneda.CFD_USD; break; case 3: // EUR nMoneda = DAttributeOptionMoneda.CFD_EUR; break; default: throw new Exception("La moneda debe ser conocida (" + mnFkCurrencyId + ")."); } cfd.ext.grupomodelo.DElementAddendaModelo addendagrupomodelo = new cfd.ext.grupomodelo.DElementAddendaModelo(); addendagrupomodelo.getAttXmlns().setString("http: addendagrupomodelo.getAttSchemaLocation().setString("http: addendagrupomodelo.getEltPayment().getAttType().setString("SimpleInvoiceType"); addendagrupomodelo.getEltPayment().getAttContentVersion().setString("1.3.1"); addendagrupomodelo.getEltPayment().getAttDocStructureVersion().setString("AMC7.1"); addendagrupomodelo.getEltPayment().getAttDocStatus().setString(sStatusDoc); addendagrupomodelo.getEltPayment().getEltPaymentIdentification().getEltEntityType().setValue(sEntityType); addendagrupomodelo.getEltPayment().getEltPaymentIdentification().getEltCreatorIdentification().setValue(msNumberSeries + msNumber); addendagrupomodelo.getEltPayment().getEltSpecialInstruction().getAttCode().setString("PUR"); addendagrupomodelo.getEltPayment().getEltSpecialInstruction().getEltText().setValue(moAuxCfdParams.getModeloDpsDescripcion()); addendagrupomodelo.getEltPayment().getEltOrderIdentification().getEltReferenceIdentification().getAttType().setString("ON"); addendagrupomodelo.getEltPayment().getEltOrderIdentification().getEltReferenceIdentification().setValue(msNumberReference); addendagrupomodelo.getEltPayment().getEltOrderIdentification().getEltReferenceDate().setValue(oSimpleDateFormat.format(tDate)); addendagrupomodelo.getEltPayment().getEltBuyer().getEltGln().setValue("7504001186019"); addendagrupomodelo.getEltPayment().getEltBuyer().getEltContactInformation().getEltPersonOrDepartmentName().getEltText().setValue(moAuxCfdParams.getBachocoSociedad()); addendagrupomodelo.getEltPayment().getEltInvoiceCreator().getEltGln().setValue("7500000000000"); addendagrupomodelo.getEltPayment().getEltInvoiceCreator().getEltAlternatePartyIdentification().getAttType().setString("IA"); addendagrupomodelo.getEltPayment().getEltInvoiceCreator().getEltAlternatePartyIdentification().setValue(sReceptorNumber); addendagrupomodelo.getEltPayment().getEltInvoiceCreator().getEltNameAddress().getEltName().setValue(moAuxCfdParams.getEmisor().getProperName().length() > 35 ? moAuxCfdParams.getEmisor().getProperName().substring(0, 34) : moAuxCfdParams.getEmisor().getProperName()); addendagrupomodelo.getEltPayment().getEltInvoiceCreator().getEltNameAddress().getEltStreetAddressOne().setValue(moAuxCfdParams.getEmisor().getDbmsHqBranch().getDbmsBizPartnerBranchAddressOfficial().getStreet()); addendagrupomodelo.getEltPayment().getEltInvoiceCreator().getEltNameAddress().getEltCity().setValue(moAuxCfdParams.getEmisor().getDbmsHqBranch().getDbmsBizPartnerBranchAddressOfficial().getState()); addendagrupomodelo.getEltPayment().getEltInvoiceCreator().getEltNameAddress().getEltPostalCode().setValue(moAuxCfdParams.getEmisor().getDbmsHqBranch().getDbmsBizPartnerBranchAddressOfficial().getZipCode()); addendagrupomodelo.getEltPayment().getEltCurrency().getAttCurrencyISOCode().setOption(nMoneda); addendagrupomodelo.getEltPayment().getEltCurrency().getEltCurrencyFunction().setValue("BILLING_CURRENCY"); addendagrupomodelo.getEltPayment().getEltCurrency().getEltCurrencyRate().setValue("" + oDecimalFormat.format(mdExchangeRate)); addendagrupomodelo.getEltPayment().getEltTotalAmount().getEltAmount().setValue("" + oDecimalFormat.format(mdTotalCy_r)); addendagrupomodelo.getEltPayment().getEltBaseAmount().getEltAmount().setValue("" + oDecimalFormat.format(mdSubtotalCy_r)); addendagrupomodelo.getEltPayment().getEltTax().getAttType().setString("VAT"); addendagrupomodelo.getEltPayment().getEltTax().getEltTaxPercentage().setValue("" + oDecimalFormat.format(dIvapct)); addendagrupomodelo.getEltPayment().getEltTax().getEltTaxAmount().setValue("" + oDecimalFormat.format(mdTaxCharged_r)); addendagrupomodelo.getEltPayment().getEltTax().getEltTaxCategory().setValue("TRANSFERIDO"); addendagrupomodelo.getEltPayment().getEltPayableAmount().getEltAmount().setValue("" + oDecimalFormat.format(mdTotal_r)); addendagrupomodelo.getEltPayment().getEltItem().getEltHijosLineItem().addAll(vLineItem); return addendagrupomodelo; } /** * Create addenda for Elektra * @param dIvaPct Tax rate applied to DPS * @return Addenda * @throws java.lang.Exception */ @SuppressWarnings("empty-statement") private cfd.ext.elektra.DElementAp computeAddendaElektra() throws java.lang.Exception { double dImpuestosTrasladados = 0; int[] anTypeDoc = {mnFkDpsCategoryId, mnFkDpsClassId, mnFkDpsTypeId}; String sNotes = ""; cfd.ext.elektra.DElementDetailItems oDetailItems = new DElementDetailItems(); cfd.ext.elektra.DElementDetalle oDetalle = null; cfd.ext.elektra.DElementProducto oProducto = null; cfd.ext.elektra.DElementTrasladado oTrasladado = null; cfd.ext.elektra.DElementImpuestos oImpuestos = null; for (SDataDpsNotes notes : mvDbmsDpsNotes) { sNotes += notes.getNotes() + "\n"; } for (SDataDpsEntry entry : mvDbmsDpsEntries) { if (entry.isAccountable()) { oDetalle = new DElementDetalle(); oDetalle.getAttFolio().setString(entry.getDbmsDpsAddElektraOrder()); oProducto = new DElementProducto(); oProducto.getAttCodigoBarras().setString(entry.getDbmsDpsAddElektraBarcode()); oProducto.getAttCajasEntregadas().setInteger(entry.getDbmsDpsAddElektraCages()); oProducto.getAttPrecioUnitarioCaja().setDouble(entry.getDbmsDpsAddElektraCagePriceUnitary()); oProducto.getAttPiezasEntregadas().setInteger(entry.getDbmsDpsAddElektraParts()); oProducto.getAttPrecioUnitarioPieza().setDouble(entry.getDbmsDpsAddElektraPartPriceUnitary()); oImpuestos = new DElementImpuestos(); dImpuestosTrasladados = 0; for (SDataDpsEntryTax tax : entry.getDbmsEntryTaxes()) { oTrasladado = new DElementTrasladado(); switch (tax.getFkTaxTypeId()) { case SModSysConsts.FINS_TP_TAX_RETAINED: switch (tax.getPkTaxBasicId()) { case 1: // IVA break; case 2: // ISR break; default: } break; case SModSysConsts.FINS_TP_TAX_CHARGED: switch (tax.getPkTaxBasicId()) { case 1: // IVA oTrasladado.getAttImpuesto().setString("IVA"); break; case 3: // IEPS oTrasladado.getAttImpuesto().setString("IEPS"); break; default: } oTrasladado.getAttImporte().setDouble(tax.getTaxCy()); oTrasladado.getAttTasa().setDouble(tax.getPercentage()); dImpuestosTrasladados += tax.getValue(); break; default: } oImpuestos.getEltImpuestosTrasladados().getEltTrasladado().add(oTrasladado); } oDetalle.getEltProducto().getEltImpuestos().getAttTotalImpuestosTrasladados().setDouble(dImpuestosTrasladados); oDetalle.getEltProducto().getEltImpuestos().getEltImpuestosTrasladados().getEltTrasladado().addAll(oImpuestos.getEltImpuestosTrasladados().getEltTrasladado()); oDetalle.getEltProducto().getAttCodigoBarras().setString(oProducto.getAttCodigoBarras().getString()); oDetalle.getEltProducto().getAttCajasEntregadas().setInteger(oProducto.getAttCajasEntregadas().getInteger()); oDetalle.getEltProducto().getAttPrecioUnitarioCaja().setDouble(oProducto.getAttPrecioUnitarioCaja().getDouble()); oDetalle.getEltProducto().getAttPiezasEntregadas().setInteger(oProducto.getAttPiezasEntregadas().getInteger()); oDetalle.getEltProducto().getAttPrecioUnitarioPieza().setDouble(oProducto.getAttPrecioUnitarioPieza().getDouble()); oDetailItems.getEltDetalle().add(oDetalle); } } DElementAp addendaelektra = new DElementAp(); addendaelektra.getAttXmlns().setString("http: addendaelektra.getAttSchemaLocation().setString("http: addendaelektra.getAttTipoComprobante().setString( SLibUtilities.compareKeys(anTypeDoc, SDataConstantsSys.TRNU_TP_DPS_SAL_INV) ? "FE" : SLibUtilities.compareKeys(anTypeDoc, SDataConstantsSys.TRNU_TP_DPS_SAL_CN) ? "NC" : SLibUtilities.compareKeys(anTypeDoc, SDataConstantsSys.TRNU_TP_DPS_SAL_REC) ? "ND" : "?"); addendaelektra.getAttPlazoPago().setString(mnDaysOfCredit + " DIAS"); // XXX: Validate is 'DIAS' is declared like a constant addendaelektra.getAttObservaciones().setString(sNotes); addendaelektra.getEltDetalleProductos().getEltDetalle().addAll(oDetailItems.getEltDetalle()); return addendaelektra; } /* XXX Check if this modification must remain (sflores, 2012-07-24). if (dImpto != 0) { */ /* XXX Check if this modification must remain (sflores, 2012-07-24). } */ /* XXX Check if this modification must remain (sflores, 2012-07-24). if (dImpto != 0) { */ /* XXX Check if this modification must remain (sflores, 2012-07-24). } */ /* XXX Check if this modification must remain (sflores, 2012-07-24). if (dImpto != 0) { */ /* XXX Check if this modification must remain (sflores, 2012-07-24). } */ /* XXX Check if this modification must remain (sflores, 2012-07-24). if (dImpto != 0) { */ /* XXX Check if this modification must remain (sflores, 2012-07-24). } */ /* } } if (impuestosTrasladados.getEltHijosImpuestoTrasladado().size() > 0) { comprobante.getEltImpuestos().getAttTotalImpuestosTrasladados().setDouble(dTotalImptoTrasladado); comprobante.getEltImpuestos().setEltOpcImpuestosTrasladados(impuestosTrasladados); } // Addenda: switch (mnFkCurrencyId) { case 1: // MXN nMoneda = DAttributeOptionMoneda.CFD_MXN; break; case 2: // USD nMoneda = DAttributeOptionMoneda.CFD_USD; break; case 3: // EUR nMoneda = DAttributeOptionMoneda.CFD_EUR; break; default: throw new Exception("La moneda debe ser conocida (" + mnFkCurrencyId + ")."); } if (moAuxCfdParams.getAgregarAddenda()) { // Create element Addenda1: DElementAddenda1 addenda1 = new DElementAddenda1(); addenda1.getEltMoneda().getAttClaveMoneda().setOption(nMoneda); addenda1.getEltMoneda().getAttTipoDeCambio().setDouble(mdExchangeRate); addenda1.getEltAdicional().getAttDiasDeCredito().setInteger(mnDaysOfCredit); addenda1.getEltAdicional().getAttEmbarque().setString(""); addenda1.getEltAdicional().getAttOrdenDeEmbarque().setString(""); addenda1.getEltAdicional().getAttOrdenDeCompra().setString(msNumberReference); addenda1.getEltAdicional().getAttContrato().setString(moAuxCfdParams.getContrato()); addenda1.getEltAdicional().getAttPedido().setString(moAuxCfdParams.getPedido()); addenda1.getEltAdicional().getAttFactura().setString(moAuxCfdParams.getFactura()); addenda1.getEltAdicional().getAttCliente().setString(moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getKey()); addenda1.getEltAdicional().getAttSucursal().setString("" + mnFkCompanyBranchId); addenda1.getEltAdicional().getAttAgente().setString("" + mnFkSalesAgentId_n); addenda1.getEltAdicional().getAttRuta().setString(moAuxCfdParams.getRuta()); addenda1.getEltAdicional().getAttChofer().setString(msDriver); addenda1.getEltAdicional().getAttPlacas().setString(msPlate); addenda1.getEltAdicional().getAttBoleto().setString(msTicket); addenda1.getEltAdicional().getAttPesoBruto().setDouble(dTotalPesoBruto); addenda1.getEltAdicional().getAttPesoNeto().setDouble(dTotalPesoNeto); addenda1.getEltAdicional().getAttUnidadPesoBruto().setString(moAuxCfdParams.getUnidadPesoBruto()); addenda1.getEltAdicional().getAttUnidadPesoNeto().setString(moAuxCfdParams.getUnidadPesoNeto()); addenda1.getEltAdicional().getEltAdicionalConceptos().getEltHijosAdicionalConcepto().addAll(vConcepto); vNota.clear(); for (SDataDpsNotes notes : mvDbmsDpsNotes) { if (!notes.getIsDeleted() && notes.getIsPrintable()) { DElementNota nota = new DElementNota(); nota.getAttTexto().setString(notes.getNotes()); vNota.add(nota); } } if (vNota.size() > 0) { DElementNotas notas = new DElementNotas(); notas.getEltHijosNota().addAll(vNota); addenda1.getEltAdicional().setEltOpcNotas(notas); } DElementPagare pagare = new DElementPagare(); pagare.getAttFecha().setDate(mtDate); pagare.getAttFechaDeVencimiento().setDate(SLibTimeUtilities.addDate(mtDateStartCredit, 0, 0, mnDaysOfCredit)); pagare.getAttImporte().setDouble(mdTotalCy_r); pagare.getAttClaveMoneda().setString(msDbmsCurrencyKey); pagare.getAttInteresMoratorio().setDouble(moAuxCfdParams.getInterestDelayRate()); addenda1.setEltOpcPagare(pagare); cfd.ver3.DElementAddenda addenda = new cfd.ver3.DElementAddenda(); addenda.getElements().add(addenda1); // Create custom addendas when needed: if (isDocumentSal() || isAdjustmentSal()) { switch (moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getFkCfdAddendaTypeId()) { case SDataConstantsSys.BPSS_TP_CFD_ADD_SORIANA: addenda.getElements().add(computeAddendaSoriana()); break; case SDataConstantsSys.BPSS_TP_CFD_ADD_LOREAL: addenda.getElements().add(computeAddendaLoreal(dIvaPorcentaje)); break; case SDataConstantsSys.BPSS_TP_CFD_ADD_BACHOCO: addenda.getElements().add(computeAddendaBachoco(dIvaPorcentaje)); break; case SDataConstantsSys.BPSS_TP_CFD_ADD_MODELO: addenda.getElements().add(computeAddendaGrupoModelo(dIvaPorcentaje)); break; case SDataConstantsSys.BPSS_TP_CFD_ADD_ELEKTRA: addenda.getElements().add(computeAddendaElektra()); break; default: } } // Add elements to Comprobante: comprobante.setEltOpcAddenda(addenda); } return comprobante; } */ @Override public int getCfdTipoCfdXml() { return SCfdConsts.CFD_TYPE_DPS; } @Override public String getCfdSerie() { return msNumberSeries; } @Override public String getCfdFolio() { return msNumber; } @Override public String getCfdReferencia() { return msNumberReference; } @Override public Date getCfdFecha() { int[] anDateDps = SLibTimeUtilities.digestDate(mtDate); int[] anDateEdit = SLibTimeUtilities.digestDate(mtUserEditTs); java.util.Date tDate = null; GregorianCalendar oGregorianCalendar = null; if (SLibUtilities.compareKeys(anDateDps, anDateEdit)) { tDate = mtUserEditTs; } else { oGregorianCalendar = new GregorianCalendar(); oGregorianCalendar.setTime(mtUserEditTs); oGregorianCalendar.set(GregorianCalendar.YEAR, anDateDps[0]); oGregorianCalendar.set(GregorianCalendar.MONTH, anDateDps[1] - 1); // January is month 0 oGregorianCalendar.set(GregorianCalendar.DATE, anDateDps[2]); tDate = oGregorianCalendar.getTime(); } return tDate; } @Override public int getCfdFormaDePago() { return mnPayments; } @Override public int getCfdCondicionesDePago() { return mnFkPaymentTypeId == SDataConstantsSys.TRNS_TP_PAY_CASH ? DAttributeOptionCondicionesPago.CFD_CONTADO : DAttributeOptionCondicionesPago.CFD_CREDITO; } @Override public double getCfdSubTotal() { return mdSubtotalProvisionalCy_r; } @Override public double getCfdDescuento() { return 0; } @Override public String getCfdMotivoDescuento() { return ""; } @Override public double getCfdTipoCambio() { return mdExchangeRate; } @Override public String getCfdMoneda() { return msDbmsCurrencyKey; } @Override public double getCfdTotal() { return mdTotalCy_r; } @Override public int getCfdTipoDeComprobante() { return isDocument() ? DAttributeOptionTipoComprobante.CFD_INGRESO : DAttributeOptionTipoComprobante.CFD_EGRESO; } @Override public String getCfdMetodoDePago() { return msPaymentMethod; } @Override public String getCfdNumCtaPago() { return msPaymentAccount; } @Override public int getEmisor() { return moAuxCfdParams.getEmisor().getPkBizPartnerId(); } @Override public int getSucursalEmisor() { return mnFkCompanyBranchId; } @Override public int getReceptor() { return mnFkBizPartnerId_r; } @Override public int getSucursalReceptor() { return mnFkBizPartnerBranchId; } @Override public ArrayList<DElement> getCfdElementRegimenFiscal() { ArrayList<DElement> regimes = null; DElement regimen = null; for (int i = 0; i < moAuxCfdParams.getRegimenFiscal().length; i++) { regimes = new ArrayList<DElement>(); regimen = new cfd.ver3.DElementRegimenFiscal(); ((cfd.ver3.DElementRegimenFiscal) regimen).getAttRegimen().setString(moAuxCfdParams.getRegimenFiscal()[i]); regimes.add(regimen); } return regimes; } @Override public DElement getCfdElementAddenda() { DElement addenda = null; // Create custom addendas when needed: try { if (moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getFkCfdAddendaTypeId() != SDataConstantsSys.BPSS_TP_CFD_ADD_NA) { addenda = new cfd.ver3.DElementAddenda(); if (isDocumentSal() || isAdjustmentSal()) { switch (moAuxCfdParams.getReceptor().getDbmsCategorySettingsCus().getFkCfdAddendaTypeId()) { case SDataConstantsSys.BPSS_TP_CFD_ADD_SORIANA: ((cfd.ver3.DElementAddenda) addenda).getElements().add(computeAddendaSoriana()); break; case SDataConstantsSys.BPSS_TP_CFD_ADD_LOREAL: ((cfd.ver3.DElementAddenda) addenda).getElements().add(computeAddendaLoreal(mdCfdIvaPorcentaje)); break; case SDataConstantsSys.BPSS_TP_CFD_ADD_BACHOCO: ((cfd.ver3.DElementAddenda) addenda).getElements().add(computeAddendaBachoco(mdCfdIvaPorcentaje)); break; case SDataConstantsSys.BPSS_TP_CFD_ADD_MODELO: ((cfd.ver3.DElementAddenda) addenda).getElements().add(computeAddendaGrupoModelo(mdCfdIvaPorcentaje)); break; case SDataConstantsSys.BPSS_TP_CFD_ADD_ELEKTRA: ((cfd.ver3.DElementAddenda) addenda).getElements().add(computeAddendaElektra()); break; default: throw new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN); } } } } catch (Exception e) { SLibUtils.showException(this, e); } return addenda; } @Override public DElement getCfdElementComplemento() { return null; } @Override public ArrayList<SCfdDataConcepto> getCfdConceptos() { String descripcion = ""; SCfdDataConcepto conceptoXml = null; ArrayList<SCfdDataConcepto> conceptosXml = new ArrayList<SCfdDataConcepto>(); for (SDataDpsEntry dpsEntry : mvDbmsDpsEntries) { if (dpsEntry.isAccountable()) { descripcion = dpsEntry.getConcept(); for (SDataDpsEntryNotes dpsEntryNotes : dpsEntry.getDbmsEntryNotes()) { if (dpsEntryNotes.getIsCfd()) { descripcion += "\n- " + dpsEntryNotes.getNotes(); } } conceptoXml = new SCfdDataConcepto(); conceptoXml.setNoIdentificacion(dpsEntry.getConceptKey()); conceptoXml.setUnidad(dpsEntry.getDbmsOriginalUnitSymbol()); conceptoXml.setCantidad(dpsEntry.getOriginalQuantity()); conceptoXml.setDescripcion(descripcion); conceptoXml.setValorUnitario(dpsEntry.getSubtotalCy_r() / dpsEntry.getOriginalQuantity()); conceptoXml.setImporte(dpsEntry.getSubtotalCy_r()); conceptosXml.add(conceptoXml); } } return conceptosXml; } @Override public ArrayList<SCfdDataImpuesto> getCfdImpuestos() { double dImptoTasa = 0; double dImpto = 0; Double oValue = null; Set<Double> setKeyImptos = null; HashMap<Double, Double> hmImpto = null; HashMap<Double, Double> hmRetenidoIva = new HashMap<Double, Double>(); HashMap<Double, Double> hmRetenidoIsr = new HashMap<Double, Double>(); HashMap<Double, Double> hmTrasladadoIva = new HashMap<Double, Double>(); HashMap<Double, Double> hmTrasladadoIeps = new HashMap<Double, Double>(); ArrayList<SCfdDataImpuesto> impuestosXml = null; SCfdDataImpuesto impuestoXml = null; impuestosXml = new ArrayList<SCfdDataImpuesto>(); try { for (SDataDpsEntry entry : mvDbmsDpsEntries) { if (entry.isAccountable()) { for (SDataDpsEntryTax tax : entry.getDbmsEntryTaxes()) { if (tax.getFkTaxCalculationTypeId() != SModSysConsts.FINS_TP_TAX_CAL_RATE) { throw new Exception("Todos los impuestos deben ser en base a una tasa (" + tax.getFkTaxCalculationTypeId() + ")."); } else { hmImpto = null; dImptoTasa = 0; switch (tax.getFkTaxTypeId()) { case SModSysConsts.FINS_TP_TAX_RETAINED: switch (tax.getPkTaxBasicId()) { case 1: // IVA dImptoTasa = 1; // on CFDI's XML retained taxes have no rate hmImpto = hmRetenidoIva; break; case 2: // ISR dImptoTasa = 1; // on CFDI's XML retained taxes have no rate hmImpto = hmRetenidoIsr; break; default: throw new Exception("Todos los impuestos retenidos deben ser conocidos (" + tax.getPkTaxBasicId() + ")."); } break; case SModSysConsts.FINS_TP_TAX_CHARGED: switch (tax.getPkTaxBasicId()) { case 1: // IVA hmImpto = hmTrasladadoIva; break; case 3: // IEPS hmImpto = hmTrasladadoIeps; break; default: throw new Exception("Todos los impuestos trasladados deben ser conocidos (" + tax.getPkTaxBasicId() + ")."); } break; default: throw new Exception("Todos los tipos de impuestos deben ser conocidos (" + tax.getFkTaxTypeId() + ")."); } if (dImptoTasa == 0) { dImptoTasa = tax.getPercentage(); } oValue = hmImpto.get(dImptoTasa); dImpto = oValue == null ? 0 : oValue.doubleValue(); hmImpto.put(dImptoTasa, dImpto + tax.getTaxCy()); } } } } // Retained taxes: hmImpto = hmRetenidoIva; if (!hmImpto.isEmpty()) { setKeyImptos = hmImpto.keySet(); for (Double key : setKeyImptos) { dImpto = hmImpto.get(key); if (dImpto != 0) { impuestoXml = new SCfdDataImpuesto(); impuestoXml.setImpuesto(DAttributeOptionImpuestoRetencion.CFD_IVA); impuestoXml.setImpuestoBasico(SModSysConsts.FINS_TP_TAX_RETAINED); impuestoXml.setTasa(1); impuestoXml.setImporte(dImpto); impuestosXml.add(impuestoXml); } } } hmImpto = hmRetenidoIsr; if (!hmImpto.isEmpty()) { setKeyImptos = hmImpto.keySet(); for (Double key : setKeyImptos) { dImpto = hmImpto.get(key); if (dImpto != 0) { impuestoXml = new SCfdDataImpuesto(); impuestoXml.setImpuesto(DAttributeOptionImpuestoRetencion.CFD_ISR); impuestoXml.setImpuestoBasico(SModSysConsts.FINS_TP_TAX_RETAINED); impuestoXml.setTasa(1); impuestoXml.setImporte(dImpto); impuestosXml.add(impuestoXml); } } } // Charged taxes: hmImpto = hmTrasladadoIva; if (!hmImpto.isEmpty()) { setKeyImptos = hmImpto.keySet(); for (Double key : setKeyImptos) { dImpto = hmImpto.get(key); impuestoXml = new SCfdDataImpuesto(); impuestoXml.setImpuesto(DAttributeOptionImpuestoTraslado.CFD_IVA); impuestoXml.setImpuestoBasico(SModSysConsts.FINS_TP_TAX_CHARGED); impuestoXml.setTasa(key * 100.0); impuestoXml.setImporte(dImpto); mdCfdIvaPorcentaje = (key * 100.0); impuestosXml.add(impuestoXml); } } hmImpto = hmTrasladadoIeps; if (!hmImpto.isEmpty()) { setKeyImptos = hmImpto.keySet(); for (Double key : setKeyImptos) { dImpto = hmImpto.get(key); impuestoXml = new SCfdDataImpuesto(); impuestoXml.setImpuesto(DAttributeOptionImpuestoTraslado.CFD_IEPS); impuestoXml.setImpuestoBasico(SModSysConsts.FINS_TP_TAX_CHARGED); impuestoXml.setTasa(key * 100.0); impuestoXml.setImporte(dImpto); impuestosXml.add(impuestoXml); } } } catch (Exception e) { SLibUtils.showException(this, e); } return impuestosXml; } public void saveField(java.sql.Connection connection, final int[] pk, final int field, final Object value) throws Exception { String sSql = ""; mnLastDbActionResult = SLibConstants.UNDEFINED; sSql = "UPDATE trn_dps SET "; switch (field) { case FIELD_REF_BKR: sSql += "comms_ref = '" + value + "' "; break; case FIELD_SAL_AGT: sSql += "fid_sal_agt_n = " + value + " "; break; case FIELD_SAL_AGT_SUP: sSql += "fid_sal_sup_n = " + value + " "; break; case FIELD_CLO_COMMS: sSql += "b_close_comms = " + value + " "; break; case FIELD_CLO_COMMS_USR: sSql += "fid_usr_close_comms = " + value + ", ts_close_comms = NOW() "; case FIELD_USR: sSql += "fid_usr_edit = " + value + ", ts_edit = NOW() "; break; default: throw new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN); } sSql += "WHERE id_year = " + pk[0] + " AND id_doc = " + pk[1]; connection.createStatement().execute(sSql); mnLastDbActionResult = SLibConstants.DB_ACTION_SAVE_OK; } public void sendMail(SClientInterface client, Object dpsKey, int mmsType) { int[] mmsConfigKey = null; String msg = ""; String companyName = ""; String bpName = ""; String dpsDestNumber = ""; String dpsReference = ""; ArrayList<String> toRecipients = null; HashSet<String> setCfgEmail = new HashSet<>(); SDbMmsConfig mmsConfig = null; SDataDpsType moDpsType = null; SDataDps dpsDest = null; boolean isEdited = false; boolean send = true; read(dpsKey, client.getSession().getStatement()); isEdited = mtUserNewTs.compareTo(mtUserEditTs) != 0; companyName = client.getSessionXXX().getCompany().getCompany(); bpName = SDataReadDescriptions.getCatalogueDescription(client, SDataConstants.BPSU_BP, new int[] { mnFkBizPartnerId_r }, SLibConstants.DESCRIPTION_NAME); moDpsType = (SDataDpsType) SDataUtilities.readRegistry(client, SDataConstants.TRNU_TP_DPS, getDpsTypeKey(), SLibConstants.EXEC_MODE_VERBOSE); dpsReference = !getNumberReference().isEmpty() ? getNumberReference() : "N/D"; toRecipients = new ArrayList<>(); for (SDataDpsEntry entry : mvDbmsDpsEntries) { try { mmsConfigKey = STrnUtilities.readMmsConfigurationByLinkType(client, mmsType, entry.getFkItemId()); if (mmsConfigKey[0] != SLibConstants.UNDEFINED) { mmsConfig = new SDbMmsConfig(); mmsConfig.read(client.getSession(), mmsConfigKey); setCfgEmail.add(mmsConfig.getEmail()); } } catch (java.lang.Exception e) { SLibUtilities.renderException(this, e); } } if (!setCfgEmail.isEmpty()) { msg = "Se enviará correo de notificación a los siguientes destinatarios:"; for (String email : setCfgEmail) { msg += "\n" + email; } client.showMsgBoxInformation(msg); } else { send = false; } if (send) { for (String cfgEmail : setCfgEmail) { try { msg = STrnUtilities.computeMailHeaderBeginTable(companyName, moDpsType.getDpsType(), getDpsNumber(), bpName, mtDate, (isEdited ? mtUserEditTs : mtUserNewTs), isEdited, mbIsRebill); for (SDataDpsEntry entry : mvDbmsDpsEntries) { mmsConfigKey = STrnUtilities.readMmsConfigurationByLinkType(client, mmsType, entry.getFkItemId()); if (mmsConfigKey[0] != SLibConstants.UNDEFINED) { mmsConfig = new SDbMmsConfig(); mmsConfig.read(client.getSession(), mmsConfigKey); if (cfgEmail.compareTo(mmsConfig.getEmail()) == 0) { if (entry.getDbmsDpsLinksAsDestiny()!= null && !entry.getDbmsDpsLinksAsDestiny().isEmpty()) { dpsDest = (SDataDps) SDataUtilities.readRegistry(client, SDataConstants.TRN_DPS, entry.getDbmsDpsLinksAsDestiny().get(0).getDbmsSourceDpsKey(), SLibConstants.EXEC_MODE_STEALTH); dpsDestNumber = dpsDest.getDpsNumber(); } else { dpsDestNumber = "N/D"; } msg += STrnUtilities.computeMailItem(client, entry.getFkItemId(), entry.getFkOriginalUnitId(), entry.getConceptKey(), entry.getConcept(), dpsDestNumber, msNumberSeries, msNumber, dpsReference, entry.getOriginalQuantity(), entry.getDbmsUnitSymbol(), getDate(), getDate(), getDpsTypeKey(), isEdited, mbIsRebill); } } } msg += STrnUtilities.computeMailFooterEndTable(SClient.APP_NAME , SClient.APP_COPYRIGHT, SClient.APP_PROVIDER, SClient.VENDOR_WEBSITE , SClient.APP_RELEASE); toRecipients.add(cfgEmail); STrnUtilities.sendMail(client, mmsType, toRecipients, null, null, msg); toRecipients.clear(); } catch (java.lang.Exception e) { SLibUtilities.printOutException(this, e); } } } } }
package org.geogit.storage.mongo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.geogit.api.ObjectId; import org.geogit.api.RevCommit; import org.geogit.api.RevFeature; import org.geogit.api.RevFeatureType; import org.geogit.api.RevObject; import org.geogit.api.RevTag; import org.geogit.api.RevTree; import org.geogit.repository.RepositoryConnectionException; import org.geogit.storage.BulkOpListener; import org.geogit.storage.ConfigDatabase; import org.geogit.storage.ObjectDatabase; import org.geogit.storage.ObjectInserter; import org.geogit.storage.ObjectSerializingFactory; import org.geogit.storage.ObjectWriter; import org.geogit.storage.datastream.DataStreamSerializationFactory; import com.google.common.base.Functions; import com.google.common.collect.AbstractIterator; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.WriteResult; public class MongoObjectDatabase implements ObjectDatabase { private final MongoConnectionManager manager; protected final ConfigDatabase config; private MongoClient client = null; protected DB db = null; protected DBCollection collection = null; protected ObjectSerializingFactory serializers = new DataStreamSerializationFactory(); private String collectionName; @Inject public MongoObjectDatabase(ConfigDatabase config, MongoConnectionManager manager) { this(config, manager, "objects"); } MongoObjectDatabase(ConfigDatabase config, MongoConnectionManager manager, String collectionName) { this.config = config; this.manager = manager; this.collectionName = collectionName; } private RevObject fromBytes(ObjectId id, byte[] buffer) { ByteArrayInputStream byteStream = new ByteArrayInputStream(buffer); RevObject result = serializers.createObjectReader().read(id, byteStream); return result; } private byte[] toBytes(RevObject object) { ObjectWriter<RevObject> writer = serializers.createObjectWriter(object.getType()); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); try { writer.write(object, byteStream); } catch (IOException e) { throw new RuntimeException(e); } return byteStream.toByteArray(); } protected String getCollectionName() { return collectionName; } @Override public synchronized void open() { if (client != null) { return; } String hostname = config.get("mongodb.host").get(); int port = config.get("mongodb.port", Integer.class).get(); client = manager.acquire(new MongoAddress(hostname, port)); db = client.getDB("geogit"); collection = db.getCollection(getCollectionName()); collection.ensureIndex("oid"); } @Override public synchronized boolean isOpen() { return client != null; } @Override public void configure() throws RepositoryConnectionException { RepositoryConnectionException.StorageType.OBJECT.configure(config, "mongodb", "0.1"); config.put("mongodb.uri", config.get("mongodb.uri").or(config.getGlobal("mongodb.uri")).or("mongodb://localhost:27017/")); config.put("mongodb.database", config.get("mongodb.database").or(config.getGlobal("mongodb.database")).or("geogit")); } @Override public void checkConfig() throws RepositoryConnectionException { RepositoryConnectionException.StorageType.OBJECT.verify(config, "mongodb", "0.1"); } @Override public synchronized void close() { if (client != null) { manager.release(client); } client = null; db = null; collection = null; } @Override public boolean exists(ObjectId id) { DBObject query = new BasicDBObject(); query.put("oid", id.toString()); return collection.find(query).hasNext(); } @Override public List<ObjectId> lookUp(final String partialId) { if (partialId.matches("[a-fA-F0-9]+")) { DBObject regex = new BasicDBObject(); regex.put("$regex", "^" + partialId); DBObject query = new BasicDBObject(); query.put("oid", regex); DBCursor cursor = collection.find(query); List<ObjectId> ids = new ArrayList<ObjectId>(); while (cursor.hasNext()) { DBObject elem = cursor.next(); String oid = (String) elem.get("oid"); ids.add(ObjectId.valueOf(oid)); } return ids; } else { throw new IllegalArgumentException( "Prefix query must be done with hexadecimal values only"); } } @Override public RevObject get(ObjectId id) { RevObject result = getIfPresent(id); if (result != null) { return result; } else { throw new NoSuchElementException("No object with id: " + id); } } @Override public <T extends RevObject> T get(ObjectId id, Class<T> clazz) { return clazz.cast(get(id)); } @Override public RevObject getIfPresent(ObjectId id) { DBObject query = new BasicDBObject(); query.put("oid", id.toString()); DBCursor results = collection.find(query); if (results.hasNext()) { DBObject result = results.next(); return fromBytes(id, (byte[]) result.get("serialized_object")); } else { return null; } } @Override public <T extends RevObject> T getIfPresent(ObjectId id, Class<T> clazz) { return clazz.cast(getIfPresent(id)); } @Override public RevTree getTree(ObjectId id) { return get(id, RevTree.class); } @Override public RevFeature getFeature(ObjectId id) { return get(id, RevFeature.class); } @Override public RevFeatureType getFeatureType(ObjectId id) { return get(id, RevFeatureType.class); } @Override public RevCommit getCommit(ObjectId id) { return get(id, RevCommit.class); } @Override public RevTag getTag(ObjectId id) { return get(id, RevTag.class); } private long deleteChunk(List<ObjectId> ids) { List<String> idStrings = Lists.transform(ids, Functions.toStringFunction()); DBObject query = BasicDBObjectBuilder.start().push("oid").add("$in", idStrings).pop().get(); WriteResult result = collection.remove(query); return result.getN(); } @Override public boolean delete(ObjectId id) { DBObject query = new BasicDBObject(); query.put("oid", id.toString()); return collection.remove(query).getLastError().ok(); } @Override public long deleteAll(Iterator<ObjectId> ids) { return deleteAll(ids, BulkOpListener.NOOP_LISTENER); } @Override public long deleteAll(Iterator<ObjectId> ids, BulkOpListener listener) { Iterator<List<ObjectId>> chunks = Iterators.partition(ids, 500); long count = 0; while (chunks.hasNext()) { count += deleteChunk(chunks.next()); } return count; } @Override public boolean put(final RevObject object) { DBObject query = new BasicDBObject(); query.put("oid", object.getId().toString()); DBObject record = new BasicDBObject(); record.put("oid", object.getId().toString()); record.put("serialized_object", toBytes(object)); return collection.update(query, record, true, false).getLastError().ok(); } @Override public void putAll(final Iterator<? extends RevObject> objects) { putAll(objects, BulkOpListener.NOOP_LISTENER); } @Override public void putAll(Iterator<? extends RevObject> objects, BulkOpListener listener) { while (objects.hasNext()) { RevObject object = objects.next(); boolean put = put(object); if (put) { listener.inserted(object, null); } } } @Override public ObjectInserter newObjectInserter() { return new ObjectInserter(this); } @Override public Iterator<RevObject> getAll(Iterable<ObjectId> ids) { return getAll(ids, BulkOpListener.NOOP_LISTENER); } @Override public Iterator<RevObject> getAll(final Iterable<ObjectId> ids, final BulkOpListener listener) { return new AbstractIterator<RevObject>() { final Iterator<ObjectId> queryIds = ids.iterator(); @Override protected RevObject computeNext() { RevObject obj = null; while (obj == null) { if (!queryIds.hasNext()) { return endOfData(); } ObjectId id = queryIds.next(); obj = getIfPresent(id); if (obj == null) { listener.notFound(id); } else { listener.found(obj, null); } } return obj == null ? endOfData() : obj; } }; } public DBCollection getCollection(String name) { return db.getCollection(name); } }
package com.continuuity.logging.save; import ch.qos.logback.classic.spi.ILoggingEvent; import com.continuuity.common.conf.CConfiguration; import com.continuuity.common.conf.Constants; import com.continuuity.common.logging.LoggingContext; import com.continuuity.data.operation.OperationContext; import com.continuuity.data.operation.executor.OperationExecutor; import com.continuuity.logging.LoggingConfiguration; import com.continuuity.logging.appender.kafka.KafkaTopic; import com.continuuity.logging.appender.kafka.LoggingEventSerializer; import com.continuuity.logging.context.LoggingContextHelper; import com.continuuity.logging.kafka.Callback; import com.continuuity.logging.kafka.KafkaConsumer; import com.continuuity.logging.kafka.KafkaLogEvent; import com.google.common.base.Preconditions; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.HashBasedTable; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Table; import com.google.common.util.concurrent.AbstractIdleService; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningScheduledExecutorService; import com.google.common.util.concurrent.MoreExecutors; import kafka.common.OffsetOutOfRangeException; import org.apache.avro.generic.GenericRecord; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocalFileSystem; import org.apache.hadoop.fs.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import static com.continuuity.logging.LoggingConfiguration.KafkaHost; import static com.continuuity.logging.save.CheckpointManager.CheckpointInfo; /** * Saves logs published through Kafka. */ @SuppressWarnings("FieldCanBeLocal") public final class LogSaver extends AbstractIdleService { private static final Logger LOG = LoggerFactory.getLogger(LogSaver.class); private final List<KafkaHost> seedBrokers; private final String topic; private final int partition; private final LoggingEventSerializer serializer; private final Path logBaseDir; private final CConfiguration cConfig; private final Configuration hConfig; private final OperationExecutor opex; private final OperationContext operationContext; private final CheckpointManager checkpointManager; private final FileMetaDataManager fileMetaDataManager; private final Table<Long, String, List<KafkaLogEvent>> messageTable; private final long kafkaErrorSleepMs = 2000; private final long kafkaEmptySleepMs = 2000; private final int kafkaSaveFetchTimeoutMs = 1000; private final int syncIntervalBytes; private final long checkpointIntervalMs; private final long inactiveIntervalMs; private final long eventBucketIntervalMs; private final long eventProcessingDelayMs; private final long retentionDurationMs; private final long maxLogFileSizeBytes; private final int numThreads = 2; private static final String TABLE_NAME = LoggingConfiguration.LOG_META_DATA_TABLE; private volatile ListeningScheduledExecutorService listeningScheduledExecutorService; private volatile Future<?> subTaskFutures; private volatile ScheduledFuture<?> scheduledFutures; public LogSaver(OperationExecutor opex, int partition, Configuration hConfig, CConfiguration cConfig) throws IOException { LOG.info("Initializing LogSaver..."); Preconditions.checkNotNull(opex, "Opex cannot be null"); String kafkaSeedBrokers = cConfig.get(LoggingConfiguration.KAFKA_SEED_BROKERS); Preconditions.checkArgument(kafkaSeedBrokers != null && !kafkaSeedBrokers.isEmpty(), "Kafka seed brokers config is not available"); this.seedBrokers = LoggingConfiguration.getKafkaSeedBrokers(kafkaSeedBrokers); Preconditions.checkNotNull(this.seedBrokers, "Not able to parse Kafka seed brokers"); LOG.info(String.format("Kafka seed brokers are %s", kafkaSeedBrokers)); String account = cConfig.get(LoggingConfiguration.LOG_RUN_ACCOUNT); Preconditions.checkNotNull(account, "Account cannot be null"); this.topic = KafkaTopic.getTopic(); LOG.info(String.format("Kafka topic is %s", this.topic)); this.partition = partition; LOG.info(String.format("Kafka partition is %d", partition)); this.serializer = new LoggingEventSerializer(); this.cConfig = cConfig; this.hConfig = hConfig; this.opex = opex; this.operationContext = new OperationContext(account); this.checkpointManager = new CheckpointManager(this.opex, operationContext, topic, partition, TABLE_NAME); this.fileMetaDataManager = new FileMetaDataManager(opex, operationContext, TABLE_NAME); this.messageTable = HashBasedTable.create(); String baseDir = cConfig.get(LoggingConfiguration.LOG_BASE_DIR); Preconditions.checkNotNull(baseDir, "Log base dir cannot be null"); this.logBaseDir = new Path(baseDir); LOG.info(String.format("Log base dir is %s", logBaseDir)); long retentionDurationDays = cConfig.getLong(LoggingConfiguration.LOG_RETENTION_DURATION_DAYS, LoggingConfiguration.DEFAULT_LOG_RETENTION_DURATION_DAYS); Preconditions.checkArgument(retentionDurationDays > 0, "Log file retention duration is invalid: %s", retentionDurationDays); this.retentionDurationMs = TimeUnit.MILLISECONDS.convert(retentionDurationDays, TimeUnit.DAYS); this.maxLogFileSizeBytes = cConfig.getLong(LoggingConfiguration.LOG_MAX_FILE_SIZE_BYTES, 100 * 1024 * 1024); Preconditions.checkArgument(maxLogFileSizeBytes > 0, "Max log file size is invalid: %s", maxLogFileSizeBytes); this.syncIntervalBytes = cConfig.getInt(LoggingConfiguration.LOG_FILE_SYNC_INTERVAL_BYTES, 5 * 1024 * 1024); Preconditions.checkArgument(this.syncIntervalBytes > 0, "Log file sync interval is invalid: %s", this.syncIntervalBytes); this.checkpointIntervalMs = cConfig.getLong(LoggingConfiguration.LOG_SAVER_CHECKPOINT_INTERVAL_MS, LoggingConfiguration.DEFAULT_LOG_SAVER_CHECKPOINT_INTERVAL_MS); Preconditions.checkArgument(this.checkpointIntervalMs > 0, "Checkpoint interval is invalid: %s", this.checkpointIntervalMs); this.inactiveIntervalMs = cConfig.getLong(LoggingConfiguration.LOG_SAVER_INACTIVE_FILE_INTERVAL_MS, LoggingConfiguration.DEFAULT_LOG_SAVER_INACTIVE_FILE_INTERVAL_MS); Preconditions.checkArgument(this.inactiveIntervalMs > 0, "Inactive interval is invalid: %s", this.inactiveIntervalMs); this.eventBucketIntervalMs = cConfig.getLong(LoggingConfiguration.LOG_SAVER_EVENT_BUCKET_INTERVAL_MS, LoggingConfiguration.DEFAULT_LOG_SAVER_EVENT_BUCKET_INTERVAL_MS); Preconditions.checkArgument(this.eventBucketIntervalMs > 0, "Event bucket interval is invalid: %s", this.eventBucketIntervalMs); this.eventProcessingDelayMs = cConfig.getLong(LoggingConfiguration.LOG_SAVER_EVENT_PROCESSING_DELAY_MS, LoggingConfiguration.DEFAULT_LOG_SAVER_EVENT_PROCESSING_DELAY_MS); Preconditions.checkArgument(this.eventProcessingDelayMs > 0, "Event processing delay interval is invalid: %s", this.eventProcessingDelayMs); } @Override protected void startUp() throws Exception { LOG.info("Starting LogSaver..."); listeningScheduledExecutorService = MoreExecutors.listeningDecorator(Executors.newScheduledThreadPool(numThreads)); List<ListenableFuture<?>> futures = Lists.newArrayList(); ListenableFuture<?> future = listeningScheduledExecutorService.submit(new LogCollector()); futures.add(future); future = listeningScheduledExecutorService.submit(new LogWriter(hConfig)); futures.add(future); subTaskFutures = Futures.allAsList(futures); scheduledFutures = listeningScheduledExecutorService.scheduleAtFixedRate( new LogCleanup(getFileSystem(cConfig, hConfig), fileMetaDataManager, logBaseDir, retentionDurationMs), 10, 24 * 60, TimeUnit.MINUTES); } @Override protected void shutDown() throws Exception { // Wait for sub tasks to complete subTaskFutures.get(); scheduledFutures.cancel(false); LOG.info("Stopping LogSaver..."); listeningScheduledExecutorService.shutdownNow(); } private final class LogCollector implements Runnable, Callback { long lastOffset; @Override public void run() { KafkaConsumer kafkaConsumer = new KafkaConsumer(seedBrokers, topic, partition, kafkaSaveFetchTimeoutMs); try { // Wait for service to start start().get(); CheckpointInfo checkpointInfo = checkpointManager.getCheckpoint(); lastOffset = checkpointInfo == null ? -1 : checkpointInfo.getOffset(); LOG.info(String.format("Starting LogCollector for topic %s, partition %d, offset %d.", topic, partition, lastOffset)); while (isRunning()) { try { int msgCount = kafkaConsumer.fetchMessages(lastOffset + 1, this); if (msgCount == 0) { LOG.debug("Got 0 messages from Kafka, sleeping..."); TimeUnit.MILLISECONDS.sleep(kafkaEmptySleepMs); } else { LOG.debug(String.format("Processed %d log messages from Kafka for topic %s, partition %s, offset %d", msgCount, topic, partition, lastOffset)); } } catch (OffsetOutOfRangeException e) { // Reset offset to earliest available long earliestOffset = kafkaConsumer.fetchOffset(KafkaConsumer.Offset.EARLIEST); LOG.warn(String.format("Offset %d is out of range. Resetting to earliest available offset %d", lastOffset + 1, earliestOffset)); lastOffset = earliestOffset - 1; } catch (Throwable e) { LOG.error( String.format("Caught exception during fetch of topic %s, partition %d, will try again after %d ms:", topic, partition, kafkaErrorSleepMs), e); try { TimeUnit.MILLISECONDS.sleep(kafkaErrorSleepMs); } catch (InterruptedException e1) { LOG.error(String.format("Caught InterruptedException for topic %s, partition %d", topic, partition), e1); Thread.currentThread().interrupt(); } } } LOG.info(String.format("Stopping LogCollector for topic %s, partition %d.", topic, partition)); } catch (Throwable e) { LOG.error("Caught unexpected exception. Terminating...", e); } finally { try { kafkaConsumer.close(); } catch (IOException e) { LOG.error(String.format("Caught exception while closing KafkaConsumer for topic %s, partition %d:", topic, partition), e); } } } @Override public void handle(long offset, ByteBuffer msgBuffer) { try { GenericRecord genericRecord = serializer.toGenericRecord(msgBuffer); ILoggingEvent event = serializer.fromGenericRecord(genericRecord); LoggingContext loggingContext = LoggingContextHelper.getLoggingContext(event.getMDCPropertyMap()); synchronized (messageTable) { long key = event.getTimeStamp() / eventBucketIntervalMs; List<KafkaLogEvent> msgList = messageTable.get(key, loggingContext.getLogPathFragment()); if (msgList == null) { msgList = Lists.newArrayList(); messageTable.put(key, loggingContext.getLogPathFragment(), msgList); } msgList.add(new KafkaLogEvent(genericRecord, event, loggingContext, offset)); } lastOffset = offset; } catch (Exception e) { LOG.warn(String.format("Exception while processing message with offset %d. Skipping it.", offset)); } } } private final class LogWriter implements Runnable { private final FileSystem fileSystem; private LogWriter(Configuration hConfig) throws Exception { this.fileSystem = getFileSystem(cConfig, hConfig); } @Override public void run() { LOG.info(String.format("Starting LogWriter for topic %s, partition %d.", topic, partition)); AvroFileWriter avroFileWriter = new AvroFileWriter(checkpointManager, fileMetaDataManager, fileSystem, logBaseDir, serializer.getAvroSchema(), maxLogFileSizeBytes, syncIntervalBytes, checkpointIntervalMs, inactiveIntervalMs); ListMultimap<String, KafkaLogEvent> writeListMap = ArrayListMultimap.create(); int messages = 0; try { // Wait for service to start start().get(); while (isRunning()) { try { // Read new messages only if previous write was successful. if (writeListMap.isEmpty()) { messages = 0; long processKey = (System.currentTimeMillis() - eventProcessingDelayMs) / eventBucketIntervalMs; synchronized (messageTable) { for (Iterator<Table.Cell<Long, String, List<KafkaLogEvent>>> it = messageTable.cellSet().iterator(); it.hasNext(); ) { Table.Cell<Long, String, List<KafkaLogEvent>> cell = it.next(); // Process only messages older than eventProcessingDelayMs if (cell.getRowKey() >= processKey) { continue; } writeListMap.putAll(cell.getColumnKey(), cell.getValue()); messages += cell.getValue().size(); it.remove(); } } } if (writeListMap.isEmpty()) { LOG.debug("Got 0 messages to save, sleeping..."); TimeUnit.MILLISECONDS.sleep(kafkaEmptySleepMs); } else { LOG.debug(String.format("Got %d log messages to save for topic %s, partition %s", messages, topic, partition)); } for (Iterator<String> it = writeListMap.keySet().iterator(); it.hasNext(); ) { String key = it.next(); List<KafkaLogEvent> list = writeListMap.get(key); Collections.sort(list); avroFileWriter.append(list); // Remove successfully written message it.remove(); } } catch (Throwable e) { LOG.error( String.format("Caught exception during save of topic %s, partition %d, will try again after %d ms:", topic, partition, kafkaErrorSleepMs), e); try { TimeUnit.MILLISECONDS.sleep(kafkaErrorSleepMs); } catch (InterruptedException e1) { LOG.error(String.format("Caught InterruptedException for topic %s, partition %d", topic, partition), e1); Thread.currentThread().interrupt(); } } } LOG.info(String.format("Stopping LogWriter for topic %s, partition %d.", topic, partition)); } catch (InterruptedException e) { LOG.error(String.format("Caught InterruptedException for topic %s, partition %d", topic, partition), e); Thread.currentThread().interrupt(); } catch (Throwable t) { LOG.error("Caught unexpected exception. Terminating...", t); } finally { try { try { avroFileWriter.close(); } finally { fileSystem.close(); } } catch (IOException e) { LOG.error(String.format("Caught exception while closing objects for topic %s, partition %d:", topic, partition), e); } } } } private static FileSystem getFileSystem(CConfiguration cConfig, Configuration hConfig) throws Exception { String hdfsUser = cConfig.get(Constants.CFG_HDFS_USER); FileSystem fileSystem; if (hdfsUser == null) { LOG.info("Create FileSystem with no user."); fileSystem = FileSystem.get(FileSystem.getDefaultUri(hConfig), hConfig); } else { LOG.info("Create FileSystem with user {}", hdfsUser); fileSystem = FileSystem.get(FileSystem.getDefaultUri(hConfig), hConfig, hdfsUser); } // local file system's hflush() does not work. Using the raw local file system fixes it. if (fileSystem instanceof LocalFileSystem) { fileSystem = ((LocalFileSystem) fileSystem).getRawFileSystem(); } return fileSystem; } }
package com.stratio.connector.deep.connection; import com.stratio.connector.deep.util.ContextProperties; import com.stratio.deep.core.context.DeepSparkContext; import org.apache.log4j.Logger; import org.testng.annotations.BeforeClass; public class DeepContextConnectorTest { private static final Logger logger = Logger.getLogger(DeepContextConnectorTest.class); /** * Default Deep HOST using 127.0.0.1. */ private static final String DEFAULT_HOST = "127.0.0.1"; protected static DeepSparkContext context = null; @BeforeClass public static void setUp(){ //TODO Start All the DeepSparkContext // Creating the Deep Context String job = "java:deepSparkContext"; String [] args = null; //TODO loadTestData } /** * Establish the connection with DeepSparkContext in order to be able to retrieve metadata from the * system columns with the connection config. * * @param host The target host. * @return Whether the connection has been established or not. */ protected static boolean connect(String host) { boolean result = false; return result; } }
package net.canadensys.dataportal.vascan; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; /** * Integration tests of the rendered vernacular page * @author canadensys * */ public class VernacularPageIntegrationTest extends AbstractIntegrationTest{ @FindBy(css = "div#content") private WebElement contentDiv; //make sure we find the footer since this is the last processed element @FindBy(css = "div#footer") private WebElement footerDiv; @Before public void setup() { browser = new FirefoxDriver(); } @Test public void testAcceptedVenacularPage() { //Coordinates is the landing page browser.get(TESTING_SERVER_URL + "vernacular/26256"); //bind the WebElement to the current page PageFactory.initElements(browser, this); assertEquals("if du Canada",contentDiv.findElement(By.cssSelector("h1")).getText()); assertEquals("sprite sprite-accepted",contentDiv.findElement(By.cssSelector("h1 + p")).getAttribute("class")); assertEquals("Taxus canadensis Marshall", contentDiv.findElement(By.cssSelector("p.sprite-redirect_accepted a")).getText()); assertEquals("div",footerDiv.getTagName()); } @Test public void testSynonymVernacularPage(){ //get a synonym browser.get(TESTING_SERVER_URL + "vernacular/26258"); PageFactory.initElements(browser, this); assertEquals("buis", contentDiv.findElement(By.cssSelector("h1")).getText()); assertEquals("sprite sprite-synonym",contentDiv.findElement(By.cssSelector("h1 + p")).getAttribute("class")); assertEquals("Taxus canadensis Marshall", contentDiv.findElement(By.cssSelector("p.sprite-redirect_accepted a")).getText()); assertEquals("div",footerDiv.getTagName()); } @After public void tearDown() { browser.close(); } }
package cn.momia.common.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class AbstractService { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractService.class); private static Map<String, Map<String, Method>> classSetterMethods = new HashMap<String, Map<String, Method>>(); private Date lastReloadTime = null; private int reloadIntervalMinutes = 24 * 60; private JdbcTemplate jdbcTemplate; private TransactionTemplate transactionTemplate; public void setReloadIntervalMinutes(int reloadIntervalMinutes) { this.reloadIntervalMinutes = reloadIntervalMinutes; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void setTransactionTemplate(TransactionTemplate transactionTemplate) { this.transactionTemplate = transactionTemplate; } protected synchronized void reload() { if (!isOutOfDate()) return; try { doReload(); } catch (Exception e) { LOGGER.error("reload exception", e); } finally { lastReloadTime = new Date(); } } protected boolean isOutOfDate() { return lastReloadTime == null || lastReloadTime.before(new Date(new Date().getTime() - reloadIntervalMinutes * 60 * 1000)); } protected void doReload() { } public int queryInt(String sql) { return queryInt(sql, null); } public int queryInt(String sql, Object[] args) { List<Integer> results = queryIntList(sql, args); return results.isEmpty() ? 0 : results.get(0); } public List<Integer> queryIntList(String sql) { return jdbcTemplate.queryForList(sql, Integer.class); } public List<Integer> queryIntList(String sql, Object[] args) { return jdbcTemplate.queryForList(sql, args, Integer.class); } public long queryLong(String sql) { return queryLong(sql, null); } public long queryLong(String sql, Object[] args) { List<Long> results = queryLongList(sql, args); return results.isEmpty() ? 0 : results.get(0); } public List<Long> queryLongList(String sql) { return jdbcTemplate.queryForList(sql, Long.class); } public List<Long> queryLongList(String sql, Object[] args) { return jdbcTemplate.queryForList(sql, args, Long.class); } public String queryString(String sql, Object[] args, String defaultValue) { List<String> results = queryStringList(sql, args); return results.isEmpty() ? defaultValue : results.get(0); } public List<String> queryStringList(String sql) { return jdbcTemplate.queryForList(sql, String.class); } public List<String> queryStringList(String sql, Object[] args) { return jdbcTemplate.queryForList(sql, args, String.class); } public Date queryDate(String sql, Object[] args, Date defaultValue) { List<Date> results = queryDateList(sql, args); return results.isEmpty() ? defaultValue : results.get(0); } public List<Date> queryDateList(String sql, Object[] args) { return jdbcTemplate.queryForList(sql, args, Date.class); } public <T> T queryObject(String sql, Class<T> clazz, T defaultValue) { return queryObject(sql, null, clazz, defaultValue); } public <T> T queryObject(String sql, Object[] args, Class<T> clazz, T defaultValue) { List<T> objects = queryObjectList(sql, args, clazz); return objects.isEmpty() ? defaultValue : objects.get(0); } public <K, V> Map<K, V> queryMap(String sql, Class<K> keyClass, Class<V> valueClass) { return queryMap(sql, null, keyClass, valueClass); } public <K, V> Map<K, V> queryMap(String sql, Object[] args, final Class<K> keyClass, final Class<V> valueClass) { final Map<K, V> map = new HashMap<K, V>(); jdbcTemplate.query(sql, args, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { map.put(keyClass.cast(rs.getObject(1)), valueClass.cast(rs.getObject(2))); } }); return map; } public <K, V> Map<K, List<V>> queryListMap(String sql, Class<K> keyClass, Class<V> valueClass) { return queryListMap(sql, null, keyClass, valueClass); } public <K, V> Map<K, List<V>> queryListMap(String sql, Object[] args, final Class<K> keyClass, final Class<V> valueClass) { final Map<K, List<V>> map = new HashMap<K, List<V>>(); jdbcTemplate.query(sql, args, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { K key = keyClass.cast(rs.getObject(1)); V value = valueClass.cast(rs.getObject(2)); List<V> list = map.get(key); if (list == null) { list = new ArrayList<V>(); map.put(key, list); } list.add(value); } }); return map; } public <T> List<T> queryObjectList(String sql, Class<T> clazz) { return queryObjectList(sql, null, clazz); } public <T> List<T> queryObjectList(String sql, Object[] args, Class<T> clazz) { List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql, args); List<T> list = new ArrayList<T>(); for (Map<String, Object> row : rows) { try { list.add(buildObject(row, clazz)); } catch (Exception e) { LOGGER.error("invalid row value: {}", row, e); } } return list; } private <T> T buildObject(Map<String, Object> row, Class<T> clazz) throws IllegalAccessException, InstantiationException, InvocationTargetException { T t = clazz.newInstance(); Map<String, Method> methods = getSetterMethods(clazz); for (Map.Entry<String, Method> entry : methods.entrySet()) { String fieldName = entry.getKey(); Method method = entry.getValue(); Object fieldValue = row.get(fieldName); if (fieldValue != null) { Class<?> paramType = method.getParameterTypes()[0]; if (paramType == Boolean.class || paramType == boolean.class) { method.invoke(t, ((Integer) fieldValue) == 1); } else { method.invoke(t, fieldValue); } } } return t; } private <T> Map<String, Method> getSetterMethods(Class<T> clazz) { Map<String, Method> methods = classSetterMethods.get(clazz.getName()); if (methods == null) { synchronized (this) { methods = classSetterMethods.get(clazz.getName()); if (methods == null) { methods = new HashMap<String, Method>(); Method[] allMethods = clazz.getMethods(); for (Method method : allMethods) { String methodName = method.getName(); if (methodName.length() > 3 && methodName.startsWith("set") && method.getParameterTypes().length == 1) methods.put(methodName.substring(3), method); } classSetterMethods.put(clazz.getName(), methods); } } } return methods; } protected void query(String sql, RowCallbackHandler handler) { query(sql, null, handler); } protected void query(String sql, Object[] args, RowCallbackHandler handler) { jdbcTemplate.query(sql, args, handler); } protected KeyHolder insert(PreparedStatementCreator psc) { KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(psc, keyHolder); return keyHolder; } protected boolean update(String sql, Object[] args) { return jdbcTemplate.update(sql, args) >= 1; } protected int singleUpdate(String sql, Object[] args) { return jdbcTemplate.update(sql, args); } protected int[] batchUpdate(String sql, List<Object[]> argsList) { return jdbcTemplate.batchUpdate(sql, argsList); } protected void execute(TransactionCallback callback) { transactionTemplate.execute(callback); } }
// PushManager.java // Pushwoosh Push Notifications SDK package com.arellomobile.android.push; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.location.Location; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import com.arellomobile.android.push.exception.PushWooshException; import com.arellomobile.android.push.preference.SoundType; import com.arellomobile.android.push.preference.VibrateType; import com.arellomobile.android.push.tags.SendPushTagsAsyncTask; import com.arellomobile.android.push.tags.SendPushTagsCallBack; import com.arellomobile.android.push.utils.executor.ExecutorHelper; import com.arellomobile.android.push.utils.GeneralUtils; import com.arellomobile.android.push.utils.PreferenceUtils; import com.arellomobile.android.push.utils.WorkerTask; import com.google.android.gcm.GCMRegistrar; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Push notifications manager */ public class PushManager { // app id in the backend private volatile String mAppId; volatile static String mSenderId; private static final String HTML_URL_FORMAT = "https://cp.pushwoosh.com/content/%s"; public static final String REGISTER_EVENT = "REGISTER_EVENT"; public static final String REGISTER_ERROR_EVENT = "REGISTER_ERROR_EVENT"; public static final String UNREGISTER_EVENT = "UNREGISTER_EVENT"; public static final String UNREGISTER_ERROR_EVENT = "UNREGISTER_ERROR_EVENT"; public static final String PUSH_RECEIVE_EVENT = "PUSH_RECEIVE_EVENT"; public static final String REGISTER_BROAD_CAST_ACTION = "com.arellomobile.android.push.REGISTER_BROAD_CAST_ACTION"; private Context mContext; private Bundle mLastBundle; Context getContext() { return mContext; } private static final Object mSyncObj = new Object(); private static AsyncTask<Void, Void, Void> mRegistrationAsyncTask; PushManager(Context context) { GeneralUtils.checkNotNull(context, "context"); mContext = context; mAppId = PreferenceUtils.getApplicationId(context); mSenderId = PreferenceUtils.getSenderId(context); } /** * Init push manager * * @param context * @param appId Pushwoosh Application ID * @param senderId ProjectID from Google GCM */ public PushManager(Context context, String appId, String senderId) { this(context); mAppId = appId; mSenderId = senderId; PreferenceUtils.setApplicationId(context, mAppId); PreferenceUtils.setSenderId(context, senderId); } public void onStartup(Context context) { onStartup(context, true); } /** * Must be called after initialization. Registers app with GCM and Pushwoosh if necessary. After registration calls {@link PushEventsTransmitter#onRegistered(Context, String) PushEventsTransmitter.onRegistered(Context context, String registrationId)} * * @param context current context * @param registerAppOpen send service message that app has been opened (for stats) */ public void onStartup(Context context, boolean registerAppOpen) { GeneralUtils.checkNotNullOrEmpty(mAppId, "mAppId"); GeneralUtils.checkNotNullOrEmpty(mSenderId, "mSenderId"); // Make sure the device has the proper dependencies. GCMRegistrar.checkDevice(context); // Make sure the manifest was properly set - comment out this line // while developing the app, then uncomment it when it's ready. GCMRegistrar.checkManifest(context); if(registerAppOpen) sendAppOpen(context); final String regId = GCMRegistrar.getRegistrationId(context); if (regId.equals("")) { // Automatically registers application on startup. GCMRegistrar.register(context, mSenderId); } else { if (context instanceof Activity) { if (((Activity) context).getIntent().hasExtra(PushManager.PUSH_RECEIVE_EVENT)) { // if this method calls because of push message, we don't need to register return; } } String oldAppId = PreferenceUtils.getApplicationId(context); if (!oldAppId.equals(mAppId)) { registerOnPushWoosh(context, regId); } else { if (neededToRequestPushWooshServer(context)) { registerOnPushWoosh(context, regId); } else { PushEventsTransmitter.onRegistered(context, regId); } } } } /** * Starts tracking Geo Push Notifications */ public void startTrackingGeoPushes() { mContext.startService(new Intent(mContext, GeoLocationService.class)); } /** * Stop tracking Geo Push Notifications */ public void stopTrackingGeoPushes() { mContext.stopService(new Intent(mContext, GeoLocationService.class)); } /** * Unregister from push notifications */ public void unregister() { cancelPrevRegisterTask(); GCMRegistrar.unregister(mContext); } /** * Get push notification user data * * @return string user data, or null */ public String getCustomData() { if (mLastBundle == null) { return null; } return mLastBundle.getString("u"); } /** * Send tags synchronously. * WARNING! * Be sure to call this method from working thread. * If not, you will freeze UI or runtime exception on Android >= 3.0 * * @param tags tags to send. Value can be String or Integer only - if not Exception will be thrown * @return wrong tags. key is name of the tag * @throws PushWooshException */ public static Map<String, String> sendTagsFromBG(Context context, Map<String, Object> tags) throws PushWooshException { Map<String, String> wrongTags = new HashMap<String, String>(); try { JSONArray wrongTagsArray = DeviceFeature2_5.sendTags(context, tags); for (int i = 0; i < wrongTagsArray.length(); ++i) { JSONObject reason = wrongTagsArray.getJSONObject(i); wrongTags.put(reason.getString("tag"), reason.getString("reason")); } } catch (Exception e) { throw new PushWooshException(e); } return wrongTags; } /** * Send tags asynchronously from UI * * @param context * @param tags tags to send. Value can be String or Integer only - if not Exception will be thrown * @param callBack result callback */ @SuppressWarnings("unchecked") public static void sendTagsFromUI(Context context, Map<String, Object> tags, SendPushTagsCallBack callBack) { new SendPushTagsAsyncTask(context, callBack).execute(tags); } /** * Send tags asynchronously * * @param context * @param tags tags to send. Value can be String or Integer only - if not Exception will be thrown * @param callBack execute result callback */ public static void sendTags(final Context context, final Map<String, Object> tags, final SendPushTagsCallBack callBack) { Handler handler = new Handler(context.getMainLooper()); handler.post(new Runnable() { @SuppressWarnings("unchecked") public void run() { new SendPushTagsAsyncTask(context, callBack).execute(tags); } }); } /** * Get tags listener */ public interface GetTagsListener { /** * Called when tags received * * @param tags received tags map */ public void onTagsReceived(Map<String, Object> tags); /** * Called when request failed * * @param e Exception */ public void onError(Exception e); } /** * Get tags from Pushwoosh service synchronously * * @param context * @return tags, or null */ public static Map<String, Object> getTagsSync(final Context context) { if (GCMRegistrar.isRegisteredOnServer(context) == false) return null; return DeviceFeature2_5.getTags(context); } /** * Get tags from Pushwoosh service asynchronously * * @param context * @return tags, or null */ public static void getTagsAsync(final Context context, final GetTagsListener listener) { if (GCMRegistrar.isRegisteredOnServer(context) == false) return; Handler handler = new Handler(context.getMainLooper()); handler.post(new Runnable() { public void run() { AsyncTask<Void, Void, Void> task = new WorkerTask(context) { @Override protected void doWork(Context context) { Map<String, Object> tags; try { tags = DeviceFeature2_5.getTags(context); listener.onTagsReceived(tags); } catch (Exception e) { listener.onError(e); } } }; ExecutorHelper.executeAsyncTask(task); } }); } /** * Send location to Pushwoosh service asynchronously * * @param context * @param location */ public static void sendLocation(final Context context, final Location location) { if (GCMRegistrar.isRegisteredOnServer(context) == false) return; Handler handler = new Handler(context.getMainLooper()); handler.post(new Runnable() { public void run() { AsyncTask<Void, Void, Void> task = new WorkerTask(context) { @Override protected void doWork(Context context) { try { DeviceFeature2_5.getNearestZone(context, location); } catch (Exception e) { // e.printStackTrace(); } } }; ExecutorHelper.executeAsyncTask(task); } }); } /** * Allows multiple notifications in notification bar. * * @param context */ public static void setMultiNotificationMode(Context context) { PreferenceUtils.setMultiMode(context, true); } /** * Allows only the last notification in notification bar. */ public static void setSimpleNotificationMode(Context context) { PreferenceUtils.setMultiMode(context, false); } /** * Change sound notification type * * @param context * @param soundNotificationType target sound type */ public static void setSoundNotificationType(Context context, SoundType soundNotificationType) { PreferenceUtils.setSoundType(context, soundNotificationType); } /** * Change vibration notification type * * @param context * @param vibrateNotificationType target vibration type */ public static void setVibrateNotificationType(Context context, VibrateType vibrateNotificationType) { PreferenceUtils.setVibrateType(context, vibrateNotificationType); } /** * Enable/disable screen light when notification message arrives * * @param context * @param lightsOn */ public static void setLightScreenOnNotification(Context context, boolean lightsOn) { PreferenceUtils.setLightScreenOnNotification(context, lightsOn); } /** * Enable/disable LED highlight when notification message arrives * * @param context * @param ledOn */ public static void setEnableLED(Context context, boolean ledOn) { PreferenceUtils.setEnableLED(context, ledOn); } /** * Called during push message processing, processes push notifications payload. Used internally! * * @param activity that handles push notification * @return false if activity doesn't have pushBundle, true otherwise */ boolean onHandlePush(Activity activity) { Bundle pushBundle = activity.getIntent().getBundleExtra("pushBundle"); if (null == pushBundle || null == mContext) { return false; } mLastBundle = pushBundle; JSONObject dataObject = new JSONObject(); Set<String> keys = pushBundle.keySet(); for (String key : keys) { //backward compatibility if(key.equals("u")) { try { dataObject.put("userdata", pushBundle.get("u")); } catch (JSONException e) { // pass } } try { dataObject.put(key, pushBundle.get(key)); } catch (JSONException e) { // pass } } PushEventsTransmitter.onMessageReceive(mContext, dataObject.toString(), pushBundle); // push message handling String url = (String) pushBundle.get("h"); if (url != null) { url = String.format(HTML_URL_FORMAT, url); // show browser Intent intent = new Intent(activity, PushWebview.class); intent.putExtra("url", url); activity.startActivity(intent); } String customPageUrl = (String) pushBundle.get("r"); if(customPageUrl != null) { // show browser Intent intent = new Intent(activity, PushWebview.class); intent.putExtra("url", customPageUrl); activity.startActivity(intent); } //temporary disable this code until the server supports it String packageName = (String) pushBundle.get("l"); if(false && packageName != null) { Intent launchIntent = null; try { launchIntent = mContext.getPackageManager().getLaunchIntentForPackage(packageName); } catch(Exception e) { // if no application found } if(launchIntent != null) { activity.startActivity(launchIntent); } else { url = (String) pushBundle.get("al"); if (url != null) { launchIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(launchIntent); } } } // send pushwoosh callback sendPushStat(mContext, pushBundle.getString("p")); return true; } /** * Check if we need to registrer on Pushwoosh * * @param context * @return true if registered in last 10 min, false otherwise */ private boolean neededToRequestPushWooshServer(Context context) { Calendar nowTime = Calendar.getInstance(); Calendar tenMinutesBefore = Calendar.getInstance(); tenMinutesBefore.add(Calendar.MINUTE, -10); // decrement 10 minutes Calendar lastPushWooshRegistrationTime = Calendar.getInstance(); lastPushWooshRegistrationTime.setTime(new Date(PreferenceUtils.getLastRegistration(context))); if (tenMinutesBefore.before(lastPushWooshRegistrationTime) && lastPushWooshRegistrationTime.before(nowTime)) { // tenMinutesBefore <= lastPushWooshRegistrationTime <= nowTime return false; } return true; } /** * Registers on Pushwoosh service asynchronously * * @param context * @param regId registration ID */ private void registerOnPushWoosh(final Context context, final String regId) { cancelPrevRegisterTask(); Handler handler = new Handler(context.getMainLooper()); handler.post(new Runnable() { public void run() { // if not register yet or an other id detected mRegistrationAsyncTask = getRegisterAsyncTask(context, regId); ExecutorHelper.executeAsyncTask(mRegistrationAsyncTask); } }); } /** * Sends push stat asynchronously * @param context * @param hash */ void sendPushStat(final Context context, final String hash) { Handler handler = new Handler(context.getMainLooper()); handler.post(new Runnable() { public void run() { AsyncTask<Void, Void, Void> task = new WorkerTask(context) { @Override protected void doWork(Context context) { DeviceFeature2_5.sendPushStat(context, hash); } }; ExecutorHelper.executeAsyncTask(task); } }); } /** * Sends service message that app has been opened * * @param context */ private void sendAppOpen(final Context context) { Handler handler = new Handler(context.getMainLooper()); handler.post(new Runnable() { public void run() { AsyncTask<Void, Void, Void> task = new WorkerTask(context) { @Override protected void doWork(Context context) { DeviceFeature2_5.sendAppOpen(context); } }; ExecutorHelper.executeAsyncTask(task); } }); } /** * Sends goal achieved asynchronously * * @param context * @param goal * @param count */ public static void sendGoalAchieved(final Context context, final String goal, final Integer count) { Handler handler = new Handler(context.getMainLooper()); handler.post(new Runnable() { public void run() { AsyncTask<Void, Void, Void> task = new WorkerTask(context) { @Override protected void doWork(Context context) { DeviceFeature2_5.sendGoalAchieved(context, goal, count); } }; ExecutorHelper.executeAsyncTask(task); } }); } /** * Gets asynchronous registration task * * @param context * @param regId registration ID * @return task that make registration asynchronously */ private AsyncTask<Void, Void, Void> getRegisterAsyncTask(final Context context, final String regId) { return new WorkerTask(context) { @Override protected void doWork(Context context) { DeviceRegistrar.registerWithServer(mContext, regId); } }; } /** * Cancels previous registration task */ private void cancelPrevRegisterTask() { synchronized (mSyncObj) { if (null != mRegistrationAsyncTask) { mRegistrationAsyncTask.cancel(true); } mRegistrationAsyncTask = null; } } /** * Schedules a local notification * @param context * @param message notification message * @param seconds delay (in seconds) until the message will be sent */ static public void scheduleLocalNotification(Context context, String message, int seconds) { scheduleLocalNotification(context, message, null, seconds); } /** * Schedules a local notification with extras * * Extras parameters: * title - message title, same as message parameter * l - link to open when notification has been tapped * b - banner URL to show in the notification instead of text * u - user data * i - identifier string of the image from the app to use as the icon in the notification * ci - URL of the icon to use in the notification * * @param context * @param message notification message * @param extras notification extras parameters * @param seconds delay (in seconds) until the message will be sent */ static public void scheduleLocalNotification(Context context, String message, Bundle extras, int seconds) { AlarmReceiver.setAlarm(context, message, extras, seconds); } /** * Removes all scheduled local notifications * @param context */ static public void clearLocalNotifications(Context context) { AlarmReceiver.clearAlarm(context); } static public Map<String, Object> incrementalTag(Integer value) { Map<String, Object> result = new HashMap<String, Object>(); result.put("operation", "increment"); result.put("value", value); return result; } }
package org.codehaus.mojo.exec.project2; import org.apache.log4j.Logger; import com.sun.java_cup.internal.runtime.Symbol; /** * Used for manual integrationtest of the java goal. * */ public class App { static Logger log = Logger.getLogger(App.class); public static void main( String[] args ) { System.out.println("I was started. So obviously I found the main class"); App app = new App(); try { Class log = app.getClass().getClassLoader().loadClass( "org.apache.log4j.Logger" ); if ( null != log ) { System.out.println( "Found the compile dependency" ); } } catch ( Exception e ) { System.out.println( "Did not find the compile dependency" ); } try { Class testCase = app.getClass().getClassLoader().loadClass( "junit.framework.TestCase" ); if ( null != testCase ) { System.out.println( "Found the test dependency" ); } } catch ( Exception e ) { System.out.println( "Did not found the test dependency" ); } try { Class fileUtils = app.getClass().getClassLoader().loadClass( "org.apache.commons.io.FileUtils" ); if ( null != fileUtils ) { System.out.println( "Found the runtime dependency" ); } } catch ( Exception e ) { System.out.println( "Did not find the runtime dependency" ); } String value = System.getProperty("propkey"); if (null != value) { System.out.println("Found the system propery passed"); } } }
package org.jtrim2.collections; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.RandomAccess; /** * @see ArraysEx#viewAsList(Object[], int, int) */ final class ArrayView<E> extends AbstractList<E> implements RandomAccess, Serializable { private static final long serialVersionUID = 6130770601174237790L; private final int offset; private final int length; private final E[] array; public ArrayView(E[] array, int offset, int length) { Objects.requireNonNull(array, "array"); if (length < 0) { throw new ArrayIndexOutOfBoundsException( "length must be non-negative."); } if (offset < 0) { throw new ArrayIndexOutOfBoundsException( "offset must be non-negative."); } int endIndex = offset + length; if (array.length < endIndex || endIndex < 0) { // if offset + length overflows the result will be a negative value. throw new ArrayIndexOutOfBoundsException( "The array is not long enough." + " Size: " + array.length + ", Required: " + ((long)offset + (long)length)); } this.offset = offset; this.length = length; this.array = array; } @Override public int size() { return length; } @Override public boolean isEmpty() { return length == 0; } @Override public boolean contains(Object o) { return indexOf(o) >= 0; } @Override public Object[] toArray() { Object[] result = new Object[length]; System.arraycopy(array, offset, result, 0, length); return result; } @Override public <T> T[] toArray(T[] a) { if (a.length < length) { @SuppressWarnings("unchecked") T[] result = Arrays.copyOfRange(array, offset, offset + length, (Class<? extends T[]>)a.getClass()); return result; } System.arraycopy(array, offset, a, 0, length); if (a.length > length) { a[length] = null; } return a; } @Override public boolean add(E e) { throw new UnsupportedOperationException("This list is readonly."); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException("This list is readonly."); } @Override public boolean addAll(Collection<? extends E> c) { throw new UnsupportedOperationException("This list is readonly."); } @Override public boolean addAll(int index, Collection<? extends E> c) { throw new UnsupportedOperationException("This list is readonly."); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException("This list is readonly."); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException("This list is readonly."); } @Override public void clear() { throw new UnsupportedOperationException("This list is readonly."); } @Override public E get(int index) { if (index < 0 || index >= length) { throw new IndexOutOfBoundsException("Index " + index + " is not in range: [0, " + length + ")"); } return array[offset + index]; } @Override public E set(int index, E element) { throw new UnsupportedOperationException("This list is readonly."); } @Override public void add(int index, E element) { throw new UnsupportedOperationException("This list is readonly."); } @Override public E remove(int index) { throw new UnsupportedOperationException("This list is readonly."); } @Override public int indexOf(Object o) { final int endOffset = offset + length; if (o == null) { for (int i = offset; i < endOffset; i++) { if (array[i] == null) { return i - offset; } } } else { for (int i = offset; i < endOffset; i++) { if (o.equals(array[i])) { return i - offset; } } } return -1; } @Override public int lastIndexOf(Object o) { final int lastIndex = offset + length - 1; final int firstIndex = offset; if (o == null) { for (int i = lastIndex; i >= firstIndex; i if (array[i] == null) { return i - offset; } } } else { for (int i = lastIndex; i >= firstIndex; i if (o.equals(array[i])) { return i - offset; } } } return -1; } @Override public List<E> subList(int fromIndex, int toIndex) { return new ArrayView<>(array, offset + fromIndex, toIndex - fromIndex); } }
package org.jdesktop.swingx.graphics; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Transparency; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.JComponent; /** * <p><code>GraphicsUtilities</code> contains a set of tools to perform * common graphics operations easily. These operations are divided into * several themes, listed below.</p> * * <h2>Compatible Images</h2> * * <p>Compatible images can, and should, be used to increase drawing * performance. This class provides a number of methods to load compatible * images directly from files or to convert existing images to compatibles * images.</p> * * <h2>Creating Thumbnails</h2> * * <p>This class provides a number of methods to easily scale down images. * Some of these methods offer a trade-off between speed and result quality and * should be used all the time. They also offer the advantage of producing * compatible images, thus automatically resulting into better runtime * performance.</p> * * <p>All these methods are both faster than * {@link java.awt.Image#getScaledInstance(int, int, int)} and produce * better-looking results than the various <code>drawImage()</code> methods * in {@link java.awt.Graphics}, which can be used for image scaling.</p> * * <h2>Image Manipulation</h2> * * <p>This class provides two methods to get and set pixels in a buffered image. * These methods try to avoid unmanaging the image in order to keep good * performance.</p> * * @author Romain Guy <romain.guy@mac.com> * @author rbair * @author Karl Schaefer */ @SuppressWarnings("nls") public class GraphicsUtilities { private GraphicsUtilities() { } // Returns the graphics configuration for the primary screen private static GraphicsConfiguration getGraphicsConfiguration() { return GraphicsEnvironment.getLocalGraphicsEnvironment(). getDefaultScreenDevice().getDefaultConfiguration(); } private static boolean isHeadless() { return GraphicsEnvironment.isHeadless(); } /** * Converts the specified image into a compatible buffered image. * * @param img * the image to convert * @return a compatible buffered image of the input */ public static BufferedImage convertToBufferedImage(Image img) { BufferedImage buff = createCompatibleTranslucentImage( img.getWidth(null), img.getHeight(null)); Graphics2D g2 = buff.createGraphics(); try { g2.drawImage(img, 0, 0, null); } finally { g2.dispose(); } return buff; } /** * <p>Returns a new <code>BufferedImage</code> using the same color model * as the image passed as a parameter. The returned image is only compatible * with the image passed as a parameter. This does not mean the returned * image is compatible with the hardware.</p> * * @param image the reference image from which the color model of the new * image is obtained * @return a new <code>BufferedImage</code>, compatible with the color model * of <code>image</code> */ public static BufferedImage createColorModelCompatibleImage(BufferedImage image) { ColorModel cm = image.getColorModel(); return new BufferedImage(cm, cm.createCompatibleWritableRaster(image.getWidth(), image.getHeight()), cm.isAlphaPremultiplied(), null); } /** * <p>Returns a new compatible image with the same width, height and * transparency as the image specified as a parameter. That is, the * returned BufferedImage will be compatible with the graphics hardware. * If this method is called in a headless environment, then * the returned BufferedImage will be compatible with the source * image.</p> * * @see java.awt.Transparency * @see #createCompatibleImage(int, int) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param image the reference image from which the dimension and the * transparency of the new image are obtained * @return a new compatible <code>BufferedImage</code> with the same * dimension and transparency as <code>image</code> */ public static BufferedImage createCompatibleImage(BufferedImage image) { return createCompatibleImage(image, image.getWidth(), image.getHeight()); } /** * <p>Returns a new compatible image of the specified width and height, and * the same transparency setting as the image specified as a parameter. * That is, the returned <code>BufferedImage</code> is compatible with * the graphics hardware. If the method is called in a headless * environment, then the returned BufferedImage will be compatible with * the source image.</p> * * @see java.awt.Transparency * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param width the width of the new image * @param height the height of the new image * @param image the reference image from which the transparency of the new * image is obtained * @return a new compatible <code>BufferedImage</code> with the same * transparency as <code>image</code> and the specified dimension */ public static BufferedImage createCompatibleImage(BufferedImage image, int width, int height) { return isHeadless() ? new BufferedImage(width, height, image.getType()) : getGraphicsConfiguration().createCompatibleImage(width, height, image.getTransparency()); } /** * <p>Returns a new opaque compatible image of the specified width and * height. That is, the returned <code>BufferedImage</code> is compatible with * the graphics hardware. If the method is called in a headless * environment, then the returned BufferedImage will be compatible with * the source image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param width the width of the new image * @param height the height of the new image * @return a new opaque compatible <code>BufferedImage</code> of the * specified width and height */ public static BufferedImage createCompatibleImage(int width, int height) { return isHeadless() ? new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) : getGraphicsConfiguration().createCompatibleImage(width, height); } /** * <p>Returns a new translucent compatible image of the specified width and * height. That is, the returned <code>BufferedImage</code> is compatible with * the graphics hardware. If the method is called in a headless * environment, then the returned BufferedImage will be compatible with * the source image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param width the width of the new image * @param height the height of the new image * @return a new translucent compatible <code>BufferedImage</code> of the * specified width and height */ public static BufferedImage createCompatibleTranslucentImage(int width, int height) { return isHeadless() ? new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) : getGraphicsConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT); } /** * <p> * Returns a new compatible image from a stream. The image is loaded from * the specified stream and then turned, if necessary into a compatible * image. * </p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleImage(int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param in * the stream of the picture to load as a compatible image * @return a new translucent compatible <code>BufferedImage</code> of the * specified width and height * @throws java.io.IOException * if the image cannot be read or loaded */ public static BufferedImage loadCompatibleImage(InputStream in) throws IOException { BufferedImage image = ImageIO.read(in); if(image == null) return null; return toCompatibleImage(image); } /** * <p>Returns a new compatible image from a URL. The image is loaded from the * specified location and then turned, if necessary into a compatible * image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleImage(int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param resource the URL of the picture to load as a compatible image * @return a new translucent compatible <code>BufferedImage</code> of the * specified width and height * @throws java.io.IOException if the image cannot be read or loaded */ public static BufferedImage loadCompatibleImage(URL resource) throws IOException { BufferedImage image = ImageIO.read(resource); return toCompatibleImage(image); } /** * <p>Return a new compatible image that contains a copy of the specified * image. This method ensures an image is compatible with the hardware, * and therefore optimized for fast blitting operations.</p> * * <p>If the method is called in a headless environment, then the returned * <code>BufferedImage</code> will be the source image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleImage(int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @param image the image to copy into a new compatible image * @return a new compatible copy, with the * same width and height and transparency and content, of <code>image</code> */ public static BufferedImage toCompatibleImage(BufferedImage image) { if (isHeadless()) { return image; } if (image.getColorModel().equals( getGraphicsConfiguration().getColorModel())) { return image; } BufferedImage compatibleImage = getGraphicsConfiguration().createCompatibleImage( image.getWidth(), image.getHeight(), image.getTransparency()); Graphics g = compatibleImage.getGraphics(); try { g.drawImage(image, 0, 0, null); } finally { g.dispose(); } return compatibleImage; } public static BufferedImage createThumbnailFast(BufferedImage image, int newSize) { float ratio; int width = image.getWidth(); int height = image.getHeight(); if (width > height) { if (newSize >= width) { throw new IllegalArgumentException("newSize must be lower than" + " the image width"); } else if (newSize <= 0) { throw new IllegalArgumentException("newSize must" + " be greater than 0"); } ratio = (float) width / (float) height; width = newSize; height = (int) (newSize / ratio); } else { if (newSize >= height) { throw new IllegalArgumentException("newSize must be lower than" + " the image height"); } else if (newSize <= 0) { throw new IllegalArgumentException("newSize must" + " be greater than 0"); } ratio = (float) height / (float) width; height = newSize; width = (int) (newSize / ratio); } BufferedImage temp = createCompatibleImage(image, width, height); Graphics2D g2 = temp.createGraphics(); try { g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null); } finally { g2.dispose(); } return temp; } public static BufferedImage createThumbnailFast(BufferedImage image, int newWidth, int newHeight) { if (newWidth >= image.getWidth() || newHeight >= image.getHeight()) { throw new IllegalArgumentException("newWidth and newHeight cannot" + " be greater than the image" + " dimensions"); } else if (newWidth <= 0 || newHeight <= 0) { throw new IllegalArgumentException("newWidth and newHeight must" + " be greater than 0"); } BufferedImage temp = createCompatibleImage(image, newWidth, newHeight); Graphics2D g2 = temp.createGraphics(); try { g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null); } finally { g2.dispose(); } return temp; } public static BufferedImage createThumbnail(BufferedImage image, int newSize) { int width = image.getWidth(); int height = image.getHeight(); boolean isTranslucent = image.getTransparency() != Transparency.OPAQUE; boolean isWidthGreater = width > height; if (isWidthGreater) { if (newSize >= width) { throw new IllegalArgumentException("newSize must be lower than" + " the image width"); } } else if (newSize >= height) { throw new IllegalArgumentException("newSize must be lower than" + " the image height"); } if (newSize <= 0) { throw new IllegalArgumentException("newSize must" + " be greater than 0"); } float ratioWH = (float) width / (float) height; float ratioHW = (float) height / (float) width; BufferedImage thumb = image; BufferedImage temp = null; Graphics2D g2 = null; try { int previousWidth = width; int previousHeight = height; do { if (isWidthGreater) { width /= 2; if (width < newSize) { width = newSize; } height = (int) (width / ratioWH); } else { height /= 2; if (height < newSize) { height = newSize; } width = (int) (height / ratioHW); } if (temp == null || isTranslucent) { if (g2 != null) { //do not need to wrap with finally //outer finally block will ensure //that resources are properly reclaimed g2.dispose(); } temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } g2.drawImage(thumb, 0, 0, width, height, 0, 0, previousWidth, previousHeight, null); previousWidth = width; previousHeight = height; thumb = temp; } while (newSize != (isWidthGreater ? width : height)); } finally { if (g2 != null) { g2.dispose(); } } if (width != thumb.getWidth() || height != thumb.getHeight()) { temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); try { g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(thumb, 0, 0, width, height, 0, 0, width, height, null); } finally { g2.dispose(); } thumb = temp; } return thumb; } public static BufferedImage createThumbnail(BufferedImage image, int newWidth, int newHeight) { int width = image.getWidth(); int height = image.getHeight(); boolean isTranslucent = image.getTransparency() != Transparency.OPAQUE; if (newWidth >= width || newHeight >= height) { throw new IllegalArgumentException("newWidth and newHeight cannot" + " be greater than the image" + " dimensions"); } else if (newWidth <= 0 || newHeight <= 0) { throw new IllegalArgumentException("newWidth and newHeight must" + " be greater than 0"); } BufferedImage thumb = image; BufferedImage temp = null; Graphics2D g2 = null; try { int previousWidth = width; int previousHeight = height; do { if (width > newWidth) { width /= 2; if (width < newWidth) { width = newWidth; } } if (height > newHeight) { height /= 2; if (height < newHeight) { height = newHeight; } } if (temp == null || isTranslucent) { if (g2 != null) { //do not need to wrap with finally //outer finally block will ensure //that resources are properly reclaimed g2.dispose(); } temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } g2.drawImage(thumb, 0, 0, width, height, 0, 0, previousWidth, previousHeight, null); previousWidth = width; previousHeight = height; thumb = temp; } while (width != newWidth || height != newHeight); } finally { if (g2 != null) { g2.dispose(); } } if (width != thumb.getWidth() || height != thumb.getHeight()) { temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); try { g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(thumb, 0, 0, width, height, 0, 0, width, height, null); } finally { g2.dispose(); } thumb = temp; } return thumb; } public static int[] getPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) { if (w == 0 || h == 0) { return new int[0]; } if (pixels == null) { pixels = new int[w * h]; } else if (pixels.length < w * h) { throw new IllegalArgumentException("pixels array must have a length" + " >= w*h"); } int imageType = img.getType(); if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) { Raster raster = img.getRaster(); return (int[]) raster.getDataElements(x, y, w, h, pixels); } // Unmanages the image return img.getRGB(x, y, w, h, pixels, 0, w); } public static void setPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) { if (pixels == null || w == 0 || h == 0) { return; } else if (pixels.length < w * h) { throw new IllegalArgumentException("pixels array must have a length" + " >= w*h"); } int imageType = img.getType(); if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) { WritableRaster raster = img.getRaster(); raster.setDataElements(x, y, w, h, pixels); } else { // Unmanages the image img.setRGB(x, y, w, h, pixels, 0, w); } } /** * Clears the data from the image. * * @param img * the image to erase */ public static void clear(Image img) { Graphics g = img.getGraphics(); try { if (g instanceof Graphics2D) { ((Graphics2D) g).setComposite(AlphaComposite.Clear); } else { g.setColor(new Color(0, 0, 0, 0)); } g.fillRect(0, 0, img.getWidth(null), img.getHeight(null)); } finally { g.dispose(); } } /** * Sets the clip on a graphics object by merging a supplied clip with the existing one. The new * clip will be an intersection of the old clip and the supplied clip. The old clip shape will * be returned. This is useful for resetting the old clip after an operation is performed. * * @param g * the graphics object to update * @param clip * a new clipping region to add to the graphics clip. * @return the current clipping region of the supplied graphics object. This may return {@code * null} if the current clip is {@code null}. * @throws NullPointerException * if any parameter is {@code null} * @deprecated Use {@link ShapeUtils#mergeClip(Graphics,Shape)} instead */ @Deprecated public static Shape mergeClip(Graphics g, Shape clip) { return ShapeUtils.mergeClip(g, clip); } /** * Draws an image on top of a component by doing a 3x3 grid stretch of the image * using the specified insets. */ public static void tileStretchPaint(Graphics g, JComponent comp, BufferedImage img, Insets ins) { int left = ins.left; int right = ins.right; int top = ins.top; int bottom = ins.bottom; // top g.drawImage(img, 0,0,left,top, 0,0,left,top, null); g.drawImage(img, left, 0, comp.getWidth() - right, top, left, 0, img.getWidth() - right, top, null); g.drawImage(img, comp.getWidth() - right, 0, comp.getWidth(), top, img.getWidth() - right, 0, img.getWidth(), top, null); // middle g.drawImage(img, 0, top, left, comp.getHeight()-bottom, 0, top, left, img.getHeight()-bottom, null); g.drawImage(img, left, top, comp.getWidth()-right, comp.getHeight()-bottom, left, top, img.getWidth()-right, img.getHeight()-bottom, null); g.drawImage(img, comp.getWidth()-right, top, comp.getWidth(), comp.getHeight()-bottom, img.getWidth()-right, top, img.getWidth(), img.getHeight()-bottom, null); // bottom g.drawImage(img, 0,comp.getHeight()-bottom, left, comp.getHeight(), 0,img.getHeight()-bottom, left,img.getHeight(), null); g.drawImage(img, left, comp.getHeight()-bottom, comp.getWidth()-right, comp.getHeight(), left, img.getHeight()-bottom, img.getWidth()-right, img.getHeight(), null); g.drawImage(img, comp.getWidth()-right, comp.getHeight()-bottom, comp.getWidth(), comp.getHeight(), img.getWidth()-right, img.getHeight()-bottom, img.getWidth(), img.getHeight(), null); } }
package org.cytoscape.browser.internal; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.KeyboardFocusManager; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Window; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collection; import java.util.EventObject; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JTable; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.TransferHandler; import javax.swing.border.Border; import javax.swing.border.TitledBorder; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import org.cytoscape.application.CyApplicationManager; import org.cytoscape.browser.internal.util.TableBrowserUtil; import org.cytoscape.equations.EquationCompiler; import org.cytoscape.event.CyEventHelper; import org.cytoscape.model.CyColumn; import org.cytoscape.model.CyIdentifiable; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyRow; import org.cytoscape.model.CyTable; import org.cytoscape.model.CyTableManager; import org.cytoscape.model.events.ColumnCreatedEvent; import org.cytoscape.model.events.ColumnCreatedListener; import org.cytoscape.model.events.ColumnDeletedEvent; import org.cytoscape.model.events.ColumnDeletedListener; import org.cytoscape.model.events.ColumnNameChangedEvent; import org.cytoscape.model.events.ColumnNameChangedListener; import org.cytoscape.model.events.RowSetRecord; import org.cytoscape.model.events.RowsSetEvent; import org.cytoscape.model.events.RowsSetListener; import org.cytoscape.view.model.CyNetworkView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BrowserTable extends JTable implements MouseListener, ActionListener, MouseMotionListener, ColumnCreatedListener, ColumnDeletedListener, ColumnNameChangedListener, RowsSetListener { private static final long serialVersionUID = 4415856756184765301L; private static final Logger logger = LoggerFactory.getLogger(BrowserTable.class); private static final Font BORDER_FONT = new Font("Sans-serif", Font.BOLD, 12); private static final TableCellRenderer cellRenderer = new BrowserTableCellRenderer(); private static final String MAC_OS_ID = "mac"; private Clipboard systemClipboard; private CellEditorRemover editorRemover = null; private final HashMap<String, Integer> columnWidthMap = new HashMap<String, Integer>(); // For right-click menu private JPopupMenu rightClickPopupMenu; private JPopupMenu rightClickHeaderPopupMenu; private JMenuItem openFormulaBuilderMenuItem = null; private final EquationCompiler compiler; private final PopupMenuHelper popupMenuHelper; private boolean updateColumnComparators; private final CyApplicationManager applicationManager; private final CyEventHelper eventHelper; private final CyTableManager tableManager; private JPopupMenu cellMenu; private int sortedColumnIndex; private boolean sortedColumnAscending; public BrowserTable(final EquationCompiler compiler, final PopupMenuHelper popupMenuHelper, final CyApplicationManager applicationManager, final CyEventHelper eventHelper, final CyTableManager tableManager) { this.compiler = compiler; this.popupMenuHelper = popupMenuHelper; this.updateColumnComparators = false; this.applicationManager = applicationManager; this.eventHelper = eventHelper; this.tableManager = tableManager; this.sortedColumnAscending = true; this.sortedColumnIndex = -1; initHeader(); setCellSelectionEnabled(true); setDefaultEditor(Object.class, new MultiLineTableCellEditor()); getPopupMenu(); getHeaderPopupMenu(); setKeyStroke(); setTransferHandler(new BrowserTableTransferHandler()); } public void setUpdateComparators(final boolean updateColumnComparators) { this.updateColumnComparators = updateColumnComparators; } /** * Routine which determines if we are running on mac platform */ private boolean isMacPlatform() { String os = System.getProperty("os.name"); return os.regionMatches(true, 0, MAC_OS_ID, 0, MAC_OS_ID.length()); } protected void initHeader() { this.setBackground(Color.white); final JTableHeader header = getTableHeader(); header.addMouseMotionListener(this); header.setBackground(Color.white); header.setOpaque(false); header.setDefaultRenderer(new CustomHeaderRenderer()); header.addMouseListener(this); header.getColumnModel().setColumnSelectionAllowed(true); setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); final BrowserTable table = this; // Event handler. Define actions when mouse is clicked. addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { final int viewColumn = getColumnModel().getColumnIndexAtX(e.getX()); final int viewRow = e.getY() / getRowHeight(); final BrowserTableModel tableModel = (BrowserTableModel) table.getModel(); int modelColumn = convertColumnIndexToModel(viewColumn); int modelRow = convertRowIndexToModel(viewRow); // Bail out if we're at the ID column: if (tableModel.isPrimaryKey(modelColumn)) return; // Make sure the column and row we're clicking on actually // exists! if (modelColumn >= tableModel.getColumnCount() || modelRow >= tableModel.getRowCount()) return; // If action is right click, then show edit pop-up menu if ((SwingUtilities.isRightMouseButton(e)) || (isMacPlatform() && e.isControlDown())) { final CyColumn cyColumn = tableModel.getColumn(modelColumn); final Object primaryKeyValue = ((ValidatedObjectAndEditString) tableModel.getValueAt(modelRow, tableModel.getDataTable().getPrimaryKey().getName())).getValidatedObject(); popupMenuHelper.createTableCellMenu(cyColumn, primaryKeyValue, table, e.getX(), e.getY()); } else if (SwingUtilities.isLeftMouseButton(e) && (getSelectedRows().length != 0)) { // Display List menu. showListContents(modelRow, modelColumn, e); } } @Override public void mouseReleased(MouseEvent e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { selectFromTable(); } }); } }); } private void selectFromTable() { final TableModel model = this.getModel(); if (model instanceof BrowserTableModel == false) return; final BrowserTableModel btModel = (BrowserTableModel) model; if (btModel.isShowAll() == false) return; final CyTable table = btModel.getDataTable(); final CyColumn pKey = table.getPrimaryKey(); final String pKeyName = pKey.getName(); final int[] rowsSelected = getSelectedRows(); if (rowsSelected.length == 0) return; final int selectedRowCount = getSelectedRowCount(); final Set<CyRow> targetRows = new HashSet<CyRow>(); for (int i = 0; i < selectedRowCount; i++) { // getting the row from data table solves the problem with hidden or // moved SUID column. However, since the rows might be sorted we // need to convert the index to model final ValidatedObjectAndEditString selected = (ValidatedObjectAndEditString) btModel.getValueAt( convertRowIndexToModel(rowsSelected[i]), pKeyName); targetRows.add(btModel.getRow(selected.getValidatedObject())); } // Clear selection for non-global table if (tableManager.getGlobalTables().contains(table) == false) { List<CyRow> allRows = btModel.getDataTable().getAllRows(); for (CyRow row : allRows) { final Boolean val = row.get(CyNetwork.SELECTED, Boolean.class); if (targetRows.contains(row)) { row.set(CyNetwork.SELECTED, true); continue; } if (val != null && (val == true)) row.set(CyNetwork.SELECTED, false); } final CyNetworkView curView = applicationManager.getCurrentNetworkView(); if (curView != null) { eventHelper.flushPayloadEvents(); curView.updateView(); } } } private void setKeyStroke() { final KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK, false); // Identifying the copy KeyStroke user can modify this // to copy on some other Key combination. this.registerKeyboardAction(this, "Copy", copy, JComponent.WHEN_FOCUSED); systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); } @Override public TableCellRenderer getCellRenderer(int row, int column) { return cellRenderer; } @Override public boolean isCellEditable(final int row, final int column) { return this.getModel().isCellEditable(convertRowIndexToModel(row), convertColumnIndexToModel(column)); } @Override public boolean editCellAt(int row, int column, EventObject e) { if (cellEditor != null && !cellEditor.stopCellEditing()) return false; if (row < 0 || row >= getRowCount() || column < 0 || column >= getColumnCount()) return false; if (!isCellEditable(row, column)) return false; if (editorRemover == null) { KeyboardFocusManager fm = KeyboardFocusManager.getCurrentKeyboardFocusManager(); editorRemover = new CellEditorRemover(fm); fm.addPropertyChangeListener("permanentFocusOwner", editorRemover); } TableCellEditor editor = getCellEditor(row, column); // remember the table row, because tableModel will disappear if // user click on open space on canvas, so we have to remember it before // it is gone BrowserTableModel model = (BrowserTableModel) this.getModel(); CyRow cyRow = model.getCyRow(convertRowIndexToModel(row)); String columnName = model.getColumnName(convertColumnIndexToModel(column)); editorRemover.setCellData(cyRow, columnName); if ((editor != null) && editor.isCellEditable(e)) { // Do this first so that the bounds of the JTextArea editor // will be correct. setEditingRow(row); setEditingColumn(column); setCellEditor(editor); editor.addCellEditorListener(this); editorComp = prepareEditor(editor, row, column); if (editorComp == null) { removeEditor(); return false; } Rectangle cellRect = getCellRect(row, column, false); if (editor instanceof MultiLineTableCellEditor) { Dimension prefSize = editorComp.getPreferredSize(); ((JComponent) editorComp).putClientProperty(MultiLineTableCellEditor.UPDATE_BOUNDS, Boolean.TRUE); editorComp.setBounds(cellRect.x, cellRect.y, Math.max(cellRect.width, prefSize.width), Math.max(cellRect.height, prefSize.height)); ((JComponent) editorComp).putClientProperty(MultiLineTableCellEditor.UPDATE_BOUNDS, Boolean.FALSE); } else editorComp.setBounds(cellRect); add(editorComp); editorComp.validate(); return true; } return false; } public void showListContents(int modelRow, int modelColumn, MouseEvent e) { final BrowserTableModel model = (BrowserTableModel) getModel(); final Class<?> columnType = model.getColumn(modelColumn).getType(); if (columnType == List.class) { final ValidatedObjectAndEditString value = (ValidatedObjectAndEditString) model.getValueAt(modelRow, modelColumn); if (value != null) { final List<?> list = (List<?>) value.getValidatedObject(); if (list != null && !list.isEmpty()) { cellMenu = new JPopupMenu(); getCellContentView(List.class, list, "List Contains:", e); } } } } private void getCellContentView(final Class<?> type, final List<?> listItems, final String borderTitle, final MouseEvent e) { JMenu curItem = null; String dispName; for (final Object item : listItems) { dispName = item.toString(); if (dispName.length() > 60) { dispName = dispName.substring(0, 59) + " ..."; } curItem = new JMenu(dispName); curItem.setBackground(Color.white); curItem.add(getPopupMenu()); JMenuItem copyAll = new JMenuItem("Copy all"); copyAll.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { final StringBuilder builder = new StringBuilder(); for (Object oneEntry : listItems) builder.append(oneEntry.toString() + "\t"); final StringSelection selection = new StringSelection(builder.toString()); systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); systemClipboard.setContents(selection, selection); } }); curItem.add(copyAll); JMenuItem copy = new JMenuItem("Copy one entry"); copy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { final StringSelection selection = new StringSelection(item.toString()); systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); systemClipboard.setContents(selection, selection); } }); curItem.add(copy); curItem.add(popupMenuHelper.getOpenLinkMenu(dispName)); cellMenu.add(curItem); } final Border popupBorder = BorderFactory.createTitledBorder(null, borderTitle, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, BORDER_FONT, Color.BLUE); cellMenu.setBorder(popupBorder); cellMenu.setBackground(Color.WHITE); cellMenu.show(e.getComponent(), e.getX(), e.getY()); } /** * This method initializes rightClickPopupMenu * * @return the inilialised pop-up menu */ public JPopupMenu getPopupMenu() { if (rightClickPopupMenu != null) return rightClickPopupMenu; rightClickPopupMenu = new JPopupMenu(); openFormulaBuilderMenuItem = new JMenuItem("Open Formula Builder"); final JTable table = this; openFormulaBuilderMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(final ActionEvent e) { final int cellRow = table.getSelectedRow(); final int cellColumn = table.getSelectedColumn(); final BrowserTableModel tableModel = (BrowserTableModel) getModel(); final JFrame rootFrame = (JFrame) SwingUtilities.getRoot(table); if (cellRow == -1 || cellColumn == -1 || !tableModel.isCellEditable(cellRow, cellColumn)) JOptionPane.showMessageDialog(rootFrame, "Can't enter a formula w/o a selected cell.", "Information", JOptionPane.INFORMATION_MESSAGE); else { final String columnName = tableModel.getColumnName(cellColumn); final Map<String, Class> attribNameToTypeMap = new HashMap<String, Class>(); FormulaBuilderDialog formulaBuilderDialog = new FormulaBuilderDialog(compiler, BrowserTable.this, rootFrame, columnName); formulaBuilderDialog.setLocationRelativeTo(rootFrame); formulaBuilderDialog.setVisible(true); } } }); return rightClickPopupMenu; } private JPopupMenu getHeaderPopupMenu() { if (rightClickHeaderPopupMenu != null) return rightClickHeaderPopupMenu; rightClickHeaderPopupMenu = new JPopupMenu(); return rightClickHeaderPopupMenu; } @Override public void mouseReleased(MouseEvent event) { } @Override public void mousePressed(MouseEvent event) { } @Override public void mouseClicked(final MouseEvent event) { /* * Check to ensure we have selected only a contiguous block of cells. */ final int numcols = this.getSelectedColumnCount(); final int numrows = this.getSelectedRowCount(); final int[] rowsselected = this.getSelectedRows(); final int[] colsselected = this.getSelectedColumns(); // Return if no cell is selected. if (numcols == 0 && numrows == 0) return null; if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0] && numrows == rowsselected.length) && (numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0] && numcols == colsselected.length))) { final JFrame rootFrame = (JFrame) SwingUtilities.getRoot(this); JOptionPane.showMessageDialog(rootFrame, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE); return null; } for (int i = 0; i < numrows; i++) { for (int j = 0; j < numcols; j++) { final Object cellValue = this.getValueAt(rowsselected[i], colsselected[j]); if (cellValue == null) continue; final String cellText = ((ValidatedObjectAndEditString) cellValue).getEditString(); sbf.append(cellText); if (j < (numcols - 1)) sbf.append("\t"); } sbf.append("\n"); } final StringSelection selection = new StringSelection(sbf.toString()); systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); systemClipboard.setContents(selection, selection); return sbf.toString(); } @Override public void mouseDragged(MouseEvent e) { // save the column width, if user adjust column width manually if (e.getSource() instanceof JTableHeader) { final int index = getColumnModel().getColumnIndexAtX(e.getX()); if (index != -1) { int colWidth = getColumnModel().getColumn(index).getWidth(); this.columnWidthMap.put(this.getColumnName(index), new Integer(colWidth)); } } } @Override public void mouseMoved(MouseEvent e) { } private class CellEditorRemover implements PropertyChangeListener { private final KeyboardFocusManager focusManager; private BrowserTableModel model; private int row = -1, column = -1; private CyRow cyRow; private String columnName; public CellEditorRemover(final KeyboardFocusManager fm) { this.focusManager = fm; } public void propertyChange(PropertyChangeEvent ev) { if (!isEditing()) { return; } Component c = focusManager.getPermanentFocusOwner(); while (c != null) { if (c == BrowserTable.this) { // focus remains inside the table return; } else if (c instanceof Window) { if (c == SwingUtilities.getRoot(BrowserTable.this)) { try { getCellEditor().stopCellEditing(); } catch (Exception e) { getCellEditor().cancelCellEditing(); // Update the cell data based on the remembered // value updateAttributeAfterCellLostFocus(); } } break; } c = c.getParent(); } } // Cell data passed from previous TableModel, because tableModel will // disappear if // user click on open space on canvas, so we have to remember it before // it is gone public void setCellData(CyRow row, String columnName) { this.cyRow = row; this.columnName = columnName; } private void updateAttributeAfterCellLostFocus() { ArrayList parsedData = TableBrowserUtil.parseCellInput(cyRow.getTable(), columnName, MultiLineTableCellEditor.lastValueUserEntered); if (parsedData.get(0) != null) { cyRow.set(columnName, MultiLineTableCellEditor.lastValueUserEntered); } else { // Error // discard the change } } } public void addColumn(final TableColumn aColumn) { super.addColumn(aColumn); if (!updateColumnComparators) return; final TableRowSorter rowSorter = (TableRowSorter) getRowSorter(); if (rowSorter == null) return; final BrowserTableModel tableModel = (BrowserTableModel)getModel(); final Class<?> rowDataType = tableModel.getColumnByModelIndex(aColumn.getModelIndex()).getType(); rowSorter.setComparator(aColumn.getModelIndex(), new ValidatedObjectAndEditStringComparator(rowDataType)); } @Override public void paint(Graphics graphics) { synchronized (getModel()) { super.paint(graphics); } } private static class BrowserTableTransferHandler extends TransferHandler { @Override protected Transferable createTransferable(JComponent source) { // Encode cell data in Excel format so we can copy/paste list // attributes as multi-line cells. StringBuilder builder = new StringBuilder(); BrowserTable table = (BrowserTable) source; for (int rowIndex : table.getSelectedRows()) { boolean firstColumn = true; for (int columnIndex : table.getSelectedColumns()) { if (!firstColumn) { builder.append("\t"); } else { firstColumn = false; } Object object = table.getValueAt(rowIndex, columnIndex); if (object instanceof ValidatedObjectAndEditString) { ValidatedObjectAndEditString raw = (ValidatedObjectAndEditString) object; Object validatedObject = raw.getValidatedObject(); if (validatedObject instanceof Collection) { builder.append("\""); boolean firstRow = true; for (Object member : (Collection<?>) validatedObject) { if (!firstRow) { builder.append("\r"); } else { firstRow = false; } builder.append(member.toString().replaceAll("\"", "\"\"")); } builder.append("\""); } else { builder.append(validatedObject.toString()); } } else { if (object != null) { builder.append(object.toString()); } } } builder.append("\n"); } return new StringSelection(builder.toString()); } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY; } } /** * Select rows in the table when something selected in the network view. * @param rows */ private void bulkUpdate(final Collection<RowSetRecord> rows) { BrowserTableModel model = (BrowserTableModel) getModel(); CyTable dataTable = model.getDataTable(); final Map<Long, Boolean> suidMapSelected = new HashMap<Long, Boolean>(); final Map<Long, Boolean> suidMapUnselected = new HashMap<Long, Boolean>(); for(RowSetRecord rowSetRecord : rows) { if(rowSetRecord.getColumn().equals(CyNetwork.SELECTED)){ if(((Boolean)rowSetRecord.getValue()) == true){ suidMapSelected.put(rowSetRecord.getRow().get(CyIdentifiable.SUID, Long.class), (Boolean) rowSetRecord.getValue()); } else{ suidMapUnselected.put(rowSetRecord.getRow().get(CyIdentifiable.SUID, Long.class), (Boolean) rowSetRecord.getValue()); } } } final String pKeyName = dataTable.getPrimaryKey().getName(); final int rowCount = getRowCount(); for(int i=0; i<rowCount; i++) { //getting the row from data table solves the problem with hidden or moved SUID column. However, since the rows might be sorted we need to convert the index to model int modelRow = convertRowIndexToModel(i); final ValidatedObjectAndEditString tableKey = (ValidatedObjectAndEditString) model.getValueAt(modelRow, pKeyName ); Long pk = null; try{ // TODO: Temp fix: is it a requirement that all CyTables have a Long SUID column as PK? pk = Long.parseLong(tableKey.getEditString()); } catch (NumberFormatException nfe) { System.out.println("Error parsing long from table " + getName() + ": " + nfe.getMessage()); } if(pk != null) { if (suidMapSelected.keySet().contains(pk)){ addRowSelectionInterval(i, i); }else if (suidMapUnselected.keySet().contains(pk)){ removeRowSelectionInterval(i, i); } } } } }
package com.webtrekk.webtrekksdk; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.os.Looper; import android.support.annotation.Nullable; import android.webkit.JavascriptInterface; import android.webkit.WebView; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import com.webtrekk.webtrekksdk.Modules.ExceptionHandler; import com.webtrekk.webtrekksdk.Request.RequestFactory; import com.webtrekk.webtrekksdk.Request.TrackingRequest; import com.webtrekk.webtrekksdk.TrackingParameter.Parameter; import com.webtrekk.webtrekksdk.Configuration.ActivityConfiguration; import com.webtrekk.webtrekksdk.Utils.ActivityListener; import com.webtrekk.webtrekksdk.Utils.ActivityTrackingStatus; import com.webtrekk.webtrekksdk.Utils.HelperFunctions; import com.webtrekk.webtrekksdk.Configuration.TrackingConfiguration; import com.webtrekk.webtrekksdk.Configuration.TrackingConfigurationDownloadTask; import com.webtrekk.webtrekksdk.Configuration.TrackingConfigurationXmlParser; import com.webtrekk.webtrekksdk.Utils.WebtrekkLogging; /** * The WebtrekkSDK main class, the developer/customer interacts with the SDK through this class. */ public class Webtrekk implements ActivityListener.Callback { //name of the preference strings public static final String PREFERENCE_FILE_NAME = "webtrekk-preferences"; public static final String PREFERENCE_KEY_EVER_ID = "everId"; public static final String PREFERENCE_APP_VERSIONCODE = "appVersion"; public static final String PREFERENCE_KEY_INSTALLATION_FLAG = "InstallationFlag"; public static final String PREFERENCE_KEY_CONFIGURATION = "webtrekkTrackingConfiguration"; public static String mTrackingLibraryVersionUI; public static String mTrackingLibraryVersion; final private RequestFactory mRequestFactory = new RequestFactory(); private TrackingConfiguration trackingConfiguration; private Context mContext; //Current status of activities private ActivityListener mActivityStatus; final private ExceptionHandler mExceptionHandler = new ExceptionHandler(); private ProductListTracker mProductListTracker; private boolean mIsInitialized; /** * non public constructor to create a Webtrekk Instance as * makes use of the Singleton Pattern here. */ Webtrekk() { } private static class SingletonHolder { static final Webtrekk webtrekk = new Webtrekk(); } /** * public method to get the singleton instance of the webtrekk object, * @return webtrekk instance */ public static Webtrekk getInstance() { return SingletonHolder.webtrekk; } /** * this initializes the webtrekk tracking configuration, it has to be called only once when the * application starts, for example in the Application Class or the Main Activitys onCreate. * Use R.raw.webtrekk_config as default configID * @param app application instance * */ final public void initWebtrekk(final Application app) { initWebtrekk(app, R.raw.webtrekk_config); } /** * this initializes the webtrekk tracking configuration, it has to be called only once when the * application starts, for example in the Application Class or the Main Activitys onCreate. * @param app application instance * @param configResourceID id of config resource * */ final public void initWebtrekk(final Application app, int configResourceID) { if (app == null) { throw new IllegalArgumentException("no valid app"); } initVersions(app.getApplicationContext()); initAutoTracking(app); initWebtrekk(app.getApplicationContext(), configResourceID); } /** * @deprecated use {@link #initWebtrekk(Application, int)} instead * this initializes the webtrekk tracking configuration, it has to be called only once when the * application starts, for example in the Application Class or the Main Activitys onCreate. * Use R.raw.webtrekk_config as default configID * @param c * */ void initWebtrekk(final Context c) { initWebtrekk(c, R.raw.webtrekk_config); } /** * this initializes the webtrekk tracking configuration, it has to be called only once when the * application starts, for example in the Application Class or the Main Activitys onCreate * @param c the application mContext / mContext of the main activity * @param configResourceID resource config ID. */ void initWebtrekk(final Context c, int configResourceID) { if (c == null) { throw new IllegalArgumentException("no valid mContext"); } if (mIsInitialized) { //this can also occur on screen orientation changes //TODO: recheck desired behaviour return; } this.mContext = c; boolean isFirstStart = HelperFunctions.firstStart(mContext); initTrackingConfiguration(configResourceID); mRequestFactory.init(mContext, trackingConfiguration, this); //TODO: make sure this can not break //Application act = (Application) mContext.getApplicationContext(); mExceptionHandler.init(mRequestFactory, mContext); mProductListTracker = new ProductListTracker(trackingConfiguration, mContext); WebtrekkLogging.log("requestUrlStore created: max requests - " + trackingConfiguration.getMaxRequests()); WebtrekkLogging.log("tracking initialized"); mIsInitialized = true; } /** * returns if initWebtrekk was called successfully for this object * @return true if initialization was called and false otherwise. */ public boolean isInitialized() { return mIsInitialized; } final void initTrackingConfiguration(int configResourceID) { initTrackingConfiguration(null, configResourceID); } /** * initializes the tracking configuration, either from xml, or shared prefs, or remote * always takes the newest version, and stores it in the shared preferences for future reference * in case it can not get a new remote config and remote config is enabled, the old config is used * * @param configurationString for unit testing only */ final void initTrackingConfiguration(final String configurationString, int configResourceID) { // always parse the local raw config version first, this is fallback, default and also the way to fix broken online configs //TODO: this could me more elegant by only parsing it when its a new app version which needs to be set anyway String trackingConfigurationString; String defaultConfigurationString = null; if (configurationString == null) { try { trackingConfigurationString = HelperFunctions.stringFromStream(mContext.getResources().openRawResource(configResourceID)); } catch (IOException e) { WebtrekkLogging.log("no custom config was found, illegal state, provide a valid config in res id:"+configResourceID); throw new IllegalStateException("can not load xml configuration file, invalid state"); } if(trackingConfigurationString.length() < 80) { // neccesary to make sure it uses the placeholder which has 66 chars length WebtrekkLogging.log("no custom config was found, illegal state, provide a valid config in res id:"+configResourceID); throw new IllegalStateException("can not load xml configuration file, invalid state"); } } else { trackingConfigurationString = configurationString; } try { // parse default configuration without default, will throw exceptions when its not valid trackingConfiguration = new TrackingConfigurationXmlParser().parse(trackingConfigurationString); } catch (Exception e) { throw new IllegalStateException("invalid xml configuration file, invalid state: " + e.getMessage() + "\n"+trackingConfigurationString); } if(trackingConfiguration != null && trackingConfiguration.isEnableRemoteConfiguration()) { SharedPreferences sharedPrefs = HelperFunctions.getWebTrekkSharedPreference(mContext); // second check if a newer remote config version is stored locally if(sharedPrefs.contains(Webtrekk.PREFERENCE_KEY_CONFIGURATION)) { WebtrekkLogging.log("found trackingConfiguration in preferences"); // in this case we already have a configuration xml stored // parse the existing one and check if an update is online available trackingConfigurationString = sharedPrefs.getString(Webtrekk.PREFERENCE_KEY_CONFIGURATION, null); TrackingConfiguration sharedPreferencetrackingConfiguration = null; try { sharedPreferencetrackingConfiguration = new TrackingConfigurationXmlParser().parse(trackingConfigurationString); if(sharedPreferencetrackingConfiguration.getVersion() > trackingConfiguration.getVersion()) { // in this case there is a newer, so replace th old one trackingConfiguration = sharedPreferencetrackingConfiguration; } } catch (IOException e) { WebtrekkLogging.log("ioexception parsing the configuration string", e); } catch(XmlPullParserException e) { WebtrekkLogging.log("exception parsing the configuration string", e); } } // third check online for newer versions //TODO: maybe store just the version number locally in preferences might reduce some parsing new TrackingConfigurationDownloadTask(this, null).execute(trackingConfiguration.getTrackingConfigurationUrl()); } // check if we have a valid configuration if(trackingConfiguration != null && trackingConfiguration.validateConfiguration()) { WebtrekkLogging.log("xml trackingConfiguration value: trackid - " + trackingConfiguration.getTrackId()); WebtrekkLogging.log("xml trackingConfiguration value: trackdomain - " + trackingConfiguration.getTrackDomain()); WebtrekkLogging.log("xml trackingConfiguration value: send_delay - " + trackingConfiguration.getSendDelay()); for(ActivityConfiguration cfg : trackingConfiguration.getActivityConfigurations().values()) { WebtrekkLogging.log("xml trackingConfiguration activity for: " + cfg.getClassName() + " mapped to: " + cfg.getMappingName() + " autotracked: " + cfg.isAutoTrack()); } } else { WebtrekkLogging.log("error loading the configuration - can not initialize tracking"); throw new IllegalStateException("could not get valid configuration, invalid state"); } WebtrekkLogging.log("tracking configuration initialized"); } /** * this functions enables the automatic activity tracking in case its enabled in the configuration * @param app application object of the tracked app, can either be a custom one or required by getApplication() */ void initAutoTracking(Application app){ if(mActivityStatus == null) { WebtrekkLogging.log("enabling callbacks"); mActivityStatus = new ActivityListener(this); mActivityStatus.init(app); } } /** * this method immediately stops tracking, for example when a user opted out * tracking will be in invalid state, until init is called again */ public void stopTracking() { if(mRequestFactory.getRequestUrlStore() != null) { mRequestFactory.stopSendURLProcess(); mRequestFactory.getRequestUrlStore().clearAllTrackingData(); } } /** * checks if logging is enabled * @return boolean if logging is enabled */ public static boolean isLoggingEnabled() { return WebtrekkLogging.isLogging(); } /** * enables the logging for all SDK log outputs * @param logging enables/disables the webtrekk logging */ public static void setLoggingEnabled(boolean logging) { WebtrekkLogging.setIsLogging(logging); } public boolean isSampling() { return mRequestFactory.isSampling(); } /** * returns the mContext with which the webtrekk instance was initialized, this can not be changed * * @return mContext */ public Context getContext() { return mContext; } public String getCurrentActivityName() { return mRequestFactory.getCurrentActivityName(); } /** * @deprecated * Don't call this function. If you need override page name call {@link Webtrekk#setCustomPageName(String)} instead * @param currentActivityName */ public void setCurrentActivityName(String currentActivityName) { mRequestFactory.setCurrentActivityName(currentActivityName); } /** * set custom page name. This name overrides page name that either provided by activity name or *set in <mappingname> tag in configuration xml. name is cleaned on next activity start. * @param pageName */ public void setCustomPageName(String pageName) { mRequestFactory.setCustomPageName(pageName); } /** * this is the default tracking method which creates an empty tracking trackingParameter object * it only tracks the auto tracked values like lib version, resolution, page name */ public void track() { track(new TrackingParameter()); } /** * this method gets called when auto tracking is enabled and one of the lifycycle methods is called */ void autoTrackActivity() { // only track if auto tracking is enabled for that activity // the default value and the activities autoTracked value is based on the global xml settings boolean autoTrack = trackingConfiguration.isAutoTracked(); if(trackingConfiguration.getActivityConfigurations()!= null && trackingConfiguration.getActivityConfigurations().containsKey(mRequestFactory.getCurrentActivityName())) { autoTrack = trackingConfiguration.getActivityConfigurations().get(mRequestFactory.getCurrentActivityName()).isAutoTrack(); } if(autoTrack) { track(); } } public void track(final TrackingParameter tp) { if (mRequestFactory.getRequestUrlStore() == null || trackingConfiguration == null) { WebtrekkLogging.log("webtrekk has not been initialized"); return; } if (mRequestFactory.getCurrentActivityName() == null) { WebtrekkLogging.log("no running activity, call startActivity first"); return; } if(tp == null) { WebtrekkLogging.log("TrackingParams is null"); return; } boolean addCDBRequestType = false; if (WebtrekkUserParameters.needUpdateCDBRequest(mContext)){ WebtrekkUserParameters userPar = new WebtrekkUserParameters(); if (userPar.restoreFromSettings(mContext)){ tp.add(userPar.getParameters()); tp.setCustomUserParameters(userPar.getCustomParameters()); addCDBRequestType = true; } } TrackingRequest request = mRequestFactory.createTrackingRequest(tp); if (addCDBRequestType){ request.setMergedRequest(TrackingRequest.RequestType.CDB); } mRequestFactory.addRequest(request); mRequestFactory.setLasTrackTime(System.currentTimeMillis()); } /** * Send CDB request with user parameters. You should use constructor of WebtrekkUserParameters to define any parameters you would like to include * For example: * webtrekk.track(new WebtrekkUserParameters.</br> * setEmail("some email").</br> * setPhone("some phone")) * @param userParameters - user parameters */ public void track(WebtrekkUserParameters userParameters) { if (userParameters.saveToSettings(mContext)) WebtrekkLogging.log("CDB request is received and saved to settings"); else { WebtrekkLogging.log("Nothing to send as request don't have any not null parameters."); return; } TrackingParameter trackingParameter = new TrackingParameter(); trackingParameter.add(userParameters.getParameters()); trackingParameter.add(Parameter.EVERID, getEverId()); trackingParameter.setCustomUserParameters(userParameters.getCustomParameters()); TrackingRequest request = new TrackingRequest(trackingParameter, trackingConfiguration, TrackingRequest.RequestType.CDB); mRequestFactory.addRequest(request); WebtrekkLogging.log("CDB request is sent"); WebtrekkUserParameters.updateCDBRequestDate(mContext); } /** * track exception that is caught by internal application handler. * @param ex - caught exception */ public void trackException(Throwable ex) { mExceptionHandler.trackCatched(ex); } /** * track exception info that user can provide. * @param name max 255 characters * @param message max 255 characters */ public void trackException(String name, String message) { mExceptionHandler.trackInfo(name, message); } /** * this function is be called automatically by activity flow listener * @hide * */ @Override public void onStart(boolean isRecreationInProcess, ActivityTrackingStatus.STATUS status, long inactivityTime, String activityName) { if (mRequestFactory.getRequestUrlStore() == null || trackingConfiguration == null) { WebtrekkLogging.log("webtrekk has not been initialized"); return; } //reset page URL if activity is changed if (!isRecreationInProcess) { resetPageURLTrack(); mRequestFactory.setCurrentActivityName(activityName); } if(status == ActivityTrackingStatus.STATUS.FIRST_ACTIVITY_STARTED) { onFirstActivityStart(); } // track only if it isn't in background and session timeout isn't passed if (status == ActivityTrackingStatus.STATUS.RETURNINIG_FROM_BACKGROUND){ if (inactivityTime > trackingConfiguration.getResendOnStartEventTime()) mRequestFactory.forceNewSession(); mRequestFactory.restore(); } autoTrackActivity(); } /** * this method gets called when the first activity of the application has started * it loads the old requests from the backupfile and tries to send them *@hide */ private void onFirstActivityStart() { mRequestFactory.onFirstStart(); mRequestFactory.onSendIntervalOver(); } /** * this function is be called automatically by activity flow listener * open activities and knows when to exit * @hide */ @Override public void onStop(ActivityTrackingStatus.STATUS status) { if (mRequestFactory.getRequestUrlStore() == null || trackingConfiguration == null) { throw new IllegalStateException("webtrekk has not been initialized"); } switch (status) { case SHUT_DOWNING: stop(); break; case GOING_TO_BACKGROUND: flush(); break; } } /** * @hide * Is called when activity is destroyed to double check that queries are saved and threads are stopped * as in some cases stop isn't called during application showt down. */ @Override public void onDestroy(ActivityTrackingStatus.STATUS status) { if(status == ActivityTrackingStatus.STATUS.SHUT_DOWNING) { stop(); } } /** * this method gets called when application is going to be closed * it stores all requests to file and stop threads. * @hide */ void stop() { mRequestFactory.stop(); } /** * this method gets called when application is going to background * it stores all requests to file. */ private void flush() { mRequestFactory.flush(); } void setContext(Context context) { this.mContext = context; } RequestFactory getRequestFactory() { return mRequestFactory; } public boolean isOptout() { return mRequestFactory.isOptout(); } /** * this method is for the opt out switch, when called it will set the shared preferences of opt out * and also stops tracking in case the user opts out * @param value boolean value indicating if the user opted out or not */ public void setOptout(boolean value) { mRequestFactory.setIsOptout(value); } /** * Set url for tracking for each activity. This value is reset for each new activity * Value is override PAGE_URL parameter in activity configuration if any. * @param url * @return */ public boolean setPageURL(String url) { ActivityConfiguration acConf = trackingConfiguration.getActivityConfigurations().get(mRequestFactory.getCurrentActivityName()); if (!HelperFunctions.testIsValidURL(url)) { WebtrekkLogging.log("setPageURL. Invalid url format"); return false; }else { if (acConf != null) { acConf.setOverridenPageURL(url); return true; } else { WebtrekkLogging.log("setPageURL. Activity configuration isn't defined."); return false; } } } //reset overrated URLTrack private void resetPageURLTrack() { ActivityConfiguration acConf = trackingConfiguration.getActivityConfigurations().get(mRequestFactory.getCurrentActivityName()); if (acConf != null) acConf.resetOverridenPageURL(); } /** * Retruns recommendation object that can be used to query recommendation(s) * Each time method returns new instance of recommendation object that is initialized accornding to * configuration xml. Using WebtrekkRecommendations object you can have independed several recommendation * request. * @return WebtrekkRecommendations object */ public WebtrekkRecommendations getRecommendations() { return new WebtrekkRecommendations(trackingConfiguration, mContext); } public ProductListTracker getProductListTracker(){ return mProductListTracker; } /** * Send manual tracks to server from tracks queue. Is done in separate thread and can be called from UI thread. * It must be called when <sendDelay> is zero, otherwise no message is sent to server. * @return true if sending is called and false if previous send procedure hasn't called or nothing to send * or manual send mode is off (<sendDelay> not zero). */ public boolean send() { if (mRequestFactory.getTrackingConfiguration().getSendDelay() == 0) { return mRequestFactory.onSendIntervalOver(); }else { WebtrekkLogging.log("Custom url send mode isn't switched on. Send isn't available. For custom send mode set <sendDelay> to zero "); return false; } } /** * allows to set global tracking parameter which will be added to all requests * @return */ public TrackingParameter getGlobalTrackingParameter() { return mRequestFactory.getGlobalTrackingParameter(); } public void setGlobalTrackingParameter(TrackingParameter globalTrackingParameter) { mRequestFactory.setGlobalTrackingParameter(globalTrackingParameter); } public TrackingParameter getConstGlobalTrackingParameter() { return mRequestFactory.getConstGlobalTrackingParameter(); } public void setConstGlobalTrackingParameter(TrackingParameter constGlobalTrackingParameter) { mRequestFactory.setConstGlobalTrackingParameter(constGlobalTrackingParameter); } /** * this method allows the customer to access the custom parameters which will be replaced by the mapping lter * * @return */ public Map<String, String> getCustomParameter() { return mRequestFactory.getCustomParameter(); } /** * this method alles the customer to set the custom parameters map * */ public void setCustomParameter(Map<String, String> customParameter) { mRequestFactory.setCustomParameter(customParameter); } /** *Returns current EverId. EverId is generated automatically by SDK, but you can set is manual as well. * @return current EverId */ public String getEverId() { return HelperFunctions.getEverId(mContext); } /** * Returns Tracking ID list defined in configuration xml. In most cased it is one item, * but theoretically it can be list divided by commas. null if Webtrekk is not initialized. * @return current Tracking ID */ public List<String> getTrackingIDs() { if (trackingConfiguration == null){ WebtrekkLogging.log("webtrekk has not been initialized"); return null; }else { return Arrays.asList(trackingConfiguration.getTrackId().split(",")); } } /** * set EverId. This ever ID will be used for all tracking request until application reinstall. * @param everId - 19 digits string value */ public void setEverId(String everId) { if (mContext == null) { WebtrekkLogging.log("Can't set ever id. Please initialize SDK first."); return; } if (!everId.matches("\\d{19}")) { WebtrekkLogging.log("Incorrect everID should have 19 digits"); return; } HelperFunctions.setEverId(mContext, everId); mRequestFactory.initEverID(); } /** * Set deeplink attribution media code. This media code will be sent once with the next tracking request * @param mediaCode - media code */ public void setMediaCode(String mediaCode) { if (mContext == null) { WebtrekkLogging.log("Can't set media code. Please initialize SDK first."); return; } HelperFunctions.setDeepLinkMediaCode(mContext, mediaCode); } //class for webVeiwCallback static class AndroidWebViewCallback{ private final Context mContext; AndroidWebViewCallback(@Nullable Context context){ mContext = context; } @JavascriptInterface public String getEverId(){ return HelperFunctions.getEverId(mContext); } } /** * Use this function to establish user connection between App and Web tracking. In that case * Webtrekk use everId from App to track website that is opened by WebView. Please note that website * should have Webtrekk integrated as well with PIXEL minimum version 4.4.0. * This function should be called before first main WebView page loading and in UI thread. * * @param webView - webView instance can't be null */ public void setupWebView(WebView webView){ if (mContext == null){ WebtrekkLogging.log("Can't setup WebView. Please initialize SDK first."); return; } if (webView == null){ WebtrekkLogging.log("Can't setup WebView. WebView parameter is null."); return; } if (Looper.getMainLooper().getThread() != Thread.currentThread()){ WebtrekkLogging.log("Can't setup WebView. Function should be called from UI thread."); return; } final String everId = HelperFunctions.getEverId(mContext);; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { webView.addJavascriptInterface(new AndroidWebViewCallback(mContext), "WebtrekkAndroidWebViewCallback"); } else { webView.loadUrl("javascript: var webtrekkApplicationEverId = \"" + everId + "\";"); } } /** * @hide * @return */ public TrackingConfiguration getTrackingConfiguration() { return trackingConfiguration; } /** * @hide * @param trackingConfiguration */ public void setTrackingConfiguration(TrackingConfiguration trackingConfiguration) { this.trackingConfiguration = trackingConfiguration; mRequestFactory.setTrackingConfiguration(trackingConfiguration); } /** * @hide * @param context */ private void initVersions(Context context) { mTrackingLibraryVersionUI = context.getResources().getString(R.string.version_name); mTrackingLibraryVersion = mTrackingLibraryVersionUI.replaceAll("\\D",""); } /** * for unit testing in the application and debugging */ public int getVersion() { return trackingConfiguration.getVersion(); } public String getTrackDomain() { return trackingConfiguration.getTrackDomain(); } public int getSampling() { return trackingConfiguration.getSampling(); } public void setIsSampling(boolean isSampling ) { mRequestFactory.setIsSampling(isSampling); } public int getSendDelay() { return trackingConfiguration.getSendDelay(); } public int getResendOnStartEventTime() { return trackingConfiguration.getResendOnStartEventTime(); } public int getMaxRequests() { return trackingConfiguration.getMaxRequests(); } public String getTrackingConfigurationUrl() { return trackingConfiguration.getTrackingConfigurationUrl(); } public boolean isAutoTracked() { return trackingConfiguration.isAutoTracked(); } public boolean isAutoTrackApiLevel() { return trackingConfiguration.isAutoTrackApiLevel(); } public boolean isEnableRemoteConfiguration() { return trackingConfiguration.isEnableRemoteConfiguration(); } /** * @deprecated use {@link #getTrackingIDs()} instead * @return */ public String getTrackId(){ return getTrackingIDs().get(0); } }
package com.redshape.utils.system.console; import org.junit.Test; import java.io.File; import java.io.IOException; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; public class ConsoleTest { public static final String USER_HOME_DIR = System.getProperty("user.home"); public static final String SUBDIR_1_PATH = USER_HOME_DIR + File.separator + "subdir.1"; public static final String SUBDIR_2_PATH = SUBDIR_1_PATH + File.separator + "subdir.2"; @Test public void testCheckExists() throws IOException { IConsole console = new Console(); assertTrue(console.checkExists(USER_HOME_DIR)); assertFalse(console.checkExists(SUBDIR_1_PATH)); } @SuppressWarnings("ResultOfMethodCallIgnored") @Test public void testMkdir() throws IOException { IConsole console = new Console(); assertFalse( new File(SUBDIR_2_PATH).exists() ); console.mkdir(SUBDIR_2_PATH); assertTrue(new File(SUBDIR_2_PATH).exists()); new File(SUBDIR_2_PATH).delete(); new File(SUBDIR_1_PATH).delete(); } @SuppressWarnings("ResultOfMethodCallIgnored") @Test public void testDeleteFile() throws IOException { new File(SUBDIR_1_PATH).mkdir(); new File(SUBDIR_2_PATH).mkdir(); IConsole console = new Console(); assertTrue( new File(SUBDIR_2_PATH).exists() ); console.deleteFile(SUBDIR_1_PATH); assertFalse( new File(SUBDIR_1_PATH).exists() ); } }
package org.wisdom.api.utils; import java.util.Map; import java.util.TreeMap; /** * A list of known mime types. */ public class KnownMimeTypes { public static final Map<String, String> EXTENSIONS; private KnownMimeTypes(){ //Hide implicit constructor } static { EXTENSIONS = new TreeMap<>(); EXTENSIONS.put("3dm", "x-world/x-3dmf"); EXTENSIONS.put("3dmf", "x-world/x-3dmf"); EXTENSIONS.put("7z", "application/x-7z-compressed"); EXTENSIONS.put("a", "application/octet-stream"); EXTENSIONS.put("aab", "application/x-authorware-bin"); EXTENSIONS.put("aam", "application/x-authorware-map"); EXTENSIONS.put("aas", "application/x-authorware-seg"); EXTENSIONS.put("abc", "text/vndabc"); EXTENSIONS.put("ace", "application/x-ace-compressed"); EXTENSIONS.put("acgi", "text/html"); EXTENSIONS.put("afl", "video/animaflex"); EXTENSIONS.put("ai", "application/postscript"); EXTENSIONS.put("aif", "audio/aiff"); EXTENSIONS.put("aifc", "audio/aiff"); EXTENSIONS.put("aiff", "audio/aiff"); EXTENSIONS.put("aim", "application/x-aim"); EXTENSIONS.put("aip", "text/x-audiosoft-intra"); EXTENSIONS.put("alz", "application/x-alz-compressed"); EXTENSIONS.put("ani", "application/x-navi-animation"); EXTENSIONS.put("aos", "application/x-nokia-9000-communicator-add-on-software"); EXTENSIONS.put("aps", "application/mime"); EXTENSIONS.put("arc", "application/x-arc-compressed"); EXTENSIONS.put("arj", "application/arj"); EXTENSIONS.put("art", "image/x-jg"); EXTENSIONS.put("asf", "video/x-ms-asf"); EXTENSIONS.put("asm", "text/x-asm"); EXTENSIONS.put("asp", "text/asp"); EXTENSIONS.put("asx", "application/x-mplayer2"); EXTENSIONS.put("au", "audio/basic"); EXTENSIONS.put("avi", "video/x-msvideo"); EXTENSIONS.put("avs", "video/avs-video"); EXTENSIONS.put("bcpio", "application/x-bcpio"); EXTENSIONS.put("bin", "application/mac-binary"); EXTENSIONS.put("bmp", "image/bmp"); EXTENSIONS.put("boo", "application/book"); EXTENSIONS.put("book", "application/book"); EXTENSIONS.put("boz", "application/x-bzip2"); EXTENSIONS.put("bsh", "application/x-bsh"); EXTENSIONS.put("bz2", "application/x-bzip2"); EXTENSIONS.put("bz", "application/x-bzip"); EXTENSIONS.put("c++", "text/plain"); EXTENSIONS.put("c", "text/x-c"); EXTENSIONS.put("cab", "application/vnd.ms-cab-compressed"); EXTENSIONS.put("cat", "application/vndms-pkiseccat"); EXTENSIONS.put("cc", "text/x-c"); EXTENSIONS.put("ccad", "application/clariscad"); EXTENSIONS.put("cco", "application/x-cocoa"); EXTENSIONS.put("cdf", "application/cdf"); EXTENSIONS.put("cer", "application/pkix-cert"); EXTENSIONS.put("cha", "application/x-chat"); EXTENSIONS.put("chat", "application/x-chat"); EXTENSIONS.put("chrt", "application/vnd.kde.kchart"); EXTENSIONS.put("class", "application/java"); EXTENSIONS.put("# ? class", "application/java-vm"); EXTENSIONS.put("com", "text/plain"); EXTENSIONS.put("conf", "text/plain"); EXTENSIONS.put("cpio", "application/x-cpio"); EXTENSIONS.put("cpp", "text/x-c"); EXTENSIONS.put("cpt", "application/mac-compactpro"); EXTENSIONS.put("crl", "application/pkcs-crl"); EXTENSIONS.put("crt", "application/pkix-cert"); EXTENSIONS.put("crx", "application/x-chrome-extension"); EXTENSIONS.put("csh", "text/x-scriptcsh"); EXTENSIONS.put("css", "text/css"); EXTENSIONS.put("csv", "text/csv"); EXTENSIONS.put("cxx", "text/plain"); EXTENSIONS.put("dar", "application/x-dar"); EXTENSIONS.put("dcr", "application/x-director"); EXTENSIONS.put("deb", "application/x-debian-package"); EXTENSIONS.put("deepv", "application/x-deepv"); EXTENSIONS.put("def", "text/plain"); EXTENSIONS.put("der", "application/x-x509-ca-cert"); EXTENSIONS.put("dif", "video/x-dv"); EXTENSIONS.put("dir", "application/x-director"); EXTENSIONS.put("divx", "video/divx"); EXTENSIONS.put("dl", "video/dl"); EXTENSIONS.put("dmg", "application/x-apple-diskimage"); EXTENSIONS.put("doc", "application/msword"); EXTENSIONS.put("dot", "application/msword"); EXTENSIONS.put("dp", "application/commonground"); EXTENSIONS.put("drw", "application/drafting"); EXTENSIONS.put("dump", "application/octet-stream"); EXTENSIONS.put("dv", "video/x-dv"); EXTENSIONS.put("dvi", "application/x-dvi"); EXTENSIONS.put("dwf", "drawing/x-dwf=(old)"); EXTENSIONS.put("dwg", "application/acad"); EXTENSIONS.put("dxf", "application/dxf"); EXTENSIONS.put("dxr", "application/x-director"); EXTENSIONS.put("el", "text/x-scriptelisp"); EXTENSIONS.put("elc", "application/x-bytecodeelisp=(compiled=elisp)"); EXTENSIONS.put("eml", "message/rfc822"); EXTENSIONS.put("env", "application/x-envoy"); EXTENSIONS.put("eps", "application/postscript"); EXTENSIONS.put("es", "application/x-esrehber"); EXTENSIONS.put("etx", "text/x-setext"); EXTENSIONS.put("evy", "application/envoy"); EXTENSIONS.put("exe", "application/octet-stream"); EXTENSIONS.put("f77", "text/x-fortran"); EXTENSIONS.put("f90", "text/x-fortran"); EXTENSIONS.put("f", "text/x-fortran"); EXTENSIONS.put("fdf", "application/vndfdf"); EXTENSIONS.put("fif", "application/fractals"); EXTENSIONS.put("fli", "video/fli"); EXTENSIONS.put("flo", "image/florian"); EXTENSIONS.put("flv", "video/x-flv"); EXTENSIONS.put("flx", "text/vndfmiflexstor"); EXTENSIONS.put("fmf", "video/x-atomic3d-feature"); EXTENSIONS.put("for", "text/x-fortran"); EXTENSIONS.put("fpx", "image/vndfpx"); EXTENSIONS.put("frl", "application/freeloader"); EXTENSIONS.put("funk", "audio/make"); EXTENSIONS.put("g3", "image/g3fax"); EXTENSIONS.put("g", "text/plain"); EXTENSIONS.put("gif", "image/gif"); EXTENSIONS.put("gl", "video/gl"); EXTENSIONS.put("gsd", "audio/x-gsm"); EXTENSIONS.put("gsm", "audio/x-gsm"); EXTENSIONS.put("gsp", "application/x-gsp"); EXTENSIONS.put("gss", "application/x-gss"); EXTENSIONS.put("gtar", "application/x-gtar"); EXTENSIONS.put("gz", "application/x-compressed"); EXTENSIONS.put("gzip", "application/x-gzip"); EXTENSIONS.put("h", "text/x-h"); EXTENSIONS.put("hdf", "application/x-hdf"); EXTENSIONS.put("help", "application/x-helpfile"); EXTENSIONS.put("hgl", "application/vndhp-hpgl"); EXTENSIONS.put("hh", "text/x-h"); EXTENSIONS.put("hlb", "text/x-script"); EXTENSIONS.put("hlp", "application/hlp"); EXTENSIONS.put("hpg", "application/vndhp-hpgl"); EXTENSIONS.put("hpgl", "application/vndhp-hpgl"); EXTENSIONS.put("hqx", "application/binhex"); EXTENSIONS.put("hta", "application/hta"); EXTENSIONS.put("htc", "text/x-component"); EXTENSIONS.put("htm", "text/html"); EXTENSIONS.put("html", "text/html"); EXTENSIONS.put("htmls", "text/html"); EXTENSIONS.put("htt", "text/webviewhtml"); EXTENSIONS.put("htx", "text/html"); EXTENSIONS.put("ice", "x-conference/x-cooltalk"); EXTENSIONS.put("ico", "image/x-icon"); EXTENSIONS.put("ics", "text/calendar"); EXTENSIONS.put("icz", "text/calendar"); EXTENSIONS.put("idc", "text/plain"); EXTENSIONS.put("ief", "image/ief"); EXTENSIONS.put("iefs", "image/ief"); EXTENSIONS.put("iges", "application/iges"); EXTENSIONS.put("igs", "application/iges"); EXTENSIONS.put("ima", "application/x-ima"); EXTENSIONS.put("imap", "application/x-httpd-imap"); EXTENSIONS.put("inf", "application/inf"); EXTENSIONS.put("ins", "application/x-internett-signup"); EXTENSIONS.put("ip", "application/x-ip2"); EXTENSIONS.put("isu", "video/x-isvideo"); EXTENSIONS.put("it", "audio/it"); EXTENSIONS.put("iv", "application/x-inventor"); EXTENSIONS.put("ivr", "i-world/i-vrml"); EXTENSIONS.put("ivy", "application/x-livescreen"); EXTENSIONS.put("jam", "audio/x-jam"); EXTENSIONS.put("jav", "text/x-java-source"); EXTENSIONS.put("java", "text/x-java-source"); EXTENSIONS.put("jcm", "application/x-java-commerce"); EXTENSIONS.put("jfif-tbnl", "image/jpeg"); EXTENSIONS.put("jfif", "image/jpeg"); EXTENSIONS.put("jnlp", "application/x-java-jnlp-file"); EXTENSIONS.put("jpe", "image/jpeg"); EXTENSIONS.put("jpeg", "image/jpeg"); EXTENSIONS.put("jpg", "image/jpeg"); EXTENSIONS.put("jps", "image/x-jps"); EXTENSIONS.put("js", "application/javascript"); EXTENSIONS.put("json", "application/json"); EXTENSIONS.put("jut", "image/jutvision"); EXTENSIONS.put("kar", "audio/midi"); EXTENSIONS.put("karbon", "application/vnd.kde.karbon"); EXTENSIONS.put("kfo", "application/vnd.kde.kformula"); EXTENSIONS.put("flw", "application/vnd.kde.kivio"); EXTENSIONS.put("kml", "application/vnd.google-earth.kml+xml"); EXTENSIONS.put("kmz", "application/vnd.google-earth.kmz"); EXTENSIONS.put("kon", "application/vnd.kde.kontour"); EXTENSIONS.put("kpr", "application/vnd.kde.kpresenter"); EXTENSIONS.put("kpt", "application/vnd.kde.kpresenter"); EXTENSIONS.put("ksp", "application/vnd.kde.kspread"); EXTENSIONS.put("kwd", "application/vnd.kde.kword"); EXTENSIONS.put("kwt", "application/vnd.kde.kword"); EXTENSIONS.put("ksh", "text/x-scriptksh"); EXTENSIONS.put("la", "audio/nspaudio"); EXTENSIONS.put("lam", "audio/x-liveaudio"); EXTENSIONS.put("latex", "application/x-latex"); EXTENSIONS.put("lha", "application/lha"); EXTENSIONS.put("lhx", "application/octet-stream"); EXTENSIONS.put("list", "text/plain"); EXTENSIONS.put("lma", "audio/nspaudio"); EXTENSIONS.put("log", "text/plain"); EXTENSIONS.put("lsp", "text/x-scriptlisp"); EXTENSIONS.put("lst", "text/plain"); EXTENSIONS.put("lsx", "text/x-la-asf"); EXTENSIONS.put("ltx", "application/x-latex"); EXTENSIONS.put("lzh", "application/octet-stream"); EXTENSIONS.put("lzx", "application/lzx"); EXTENSIONS.put("m1v", "video/mpeg"); EXTENSIONS.put("m2a", "audio/mpeg"); EXTENSIONS.put("m2v", "video/mpeg"); EXTENSIONS.put("m3u", "audio/x-mpegurl"); EXTENSIONS.put("m", "text/x-m"); EXTENSIONS.put("man", "application/x-troff-man"); EXTENSIONS.put("manifest", "text/cache-manifest"); EXTENSIONS.put("map", "application/x-navimap"); EXTENSIONS.put("mar", "text/plain"); EXTENSIONS.put("mbd", "application/mbedlet"); EXTENSIONS.put("mc$", "application/x-magic-cap-package-10"); EXTENSIONS.put("mcd", "application/mcad"); EXTENSIONS.put("mcf", "text/mcf"); EXTENSIONS.put("mcp", "application/netmc"); EXTENSIONS.put("me", "application/x-troff-me"); EXTENSIONS.put("mht", "message/rfc822"); EXTENSIONS.put("mhtml", "message/rfc822"); EXTENSIONS.put("mid", "application/x-midi"); EXTENSIONS.put("midi", "application/x-midi"); EXTENSIONS.put("mif", "application/x-frame"); EXTENSIONS.put("mime", "message/rfc822"); EXTENSIONS.put("mjf", "audio/x-vndaudioexplosionmjuicemediafile"); EXTENSIONS.put("mjpg", "video/x-motion-jpeg"); EXTENSIONS.put("mm", "application/base64"); EXTENSIONS.put("mme", "application/base64"); EXTENSIONS.put("mod", "audio/mod"); EXTENSIONS.put("moov", "video/quicktime"); EXTENSIONS.put("mov", "video/quicktime"); EXTENSIONS.put("movie", "video/x-sgi-movie"); EXTENSIONS.put("mp2", "audio/mpeg"); EXTENSIONS.put("mp3", "audio/mpeg3"); EXTENSIONS.put("mp4", "video/mp4"); EXTENSIONS.put("mpa", "audio/mpeg"); EXTENSIONS.put("mpc", "application/x-project"); EXTENSIONS.put("mpe", "video/mpeg"); EXTENSIONS.put("mpeg", "video/mpeg"); EXTENSIONS.put("mpg", "video/mpeg"); EXTENSIONS.put("mpga", "audio/mpeg"); EXTENSIONS.put("mpp", "application/vndms-project"); EXTENSIONS.put("mpt", "application/x-project"); EXTENSIONS.put("mpv", "application/x-project"); EXTENSIONS.put("mpx", "application/x-project"); EXTENSIONS.put("mrc", "application/marc"); EXTENSIONS.put("ms", "application/x-troff-ms"); EXTENSIONS.put("mv", "video/x-sgi-movie"); EXTENSIONS.put("my", "audio/make"); EXTENSIONS.put("mzz", "application/x-vndaudioexplosionmzz"); EXTENSIONS.put("nap", "image/naplps"); EXTENSIONS.put("naplps", "image/naplps"); EXTENSIONS.put("nc", "application/x-netcdf"); EXTENSIONS.put("ncm", "application/vndnokiaconfiguration-message"); EXTENSIONS.put("nif", "image/x-niff"); EXTENSIONS.put("niff", "image/x-niff"); EXTENSIONS.put("nix", "application/x-mix-transfer"); EXTENSIONS.put("nsc", "application/x-conference"); EXTENSIONS.put("nvd", "application/x-navidoc"); EXTENSIONS.put("o", "application/octet-stream"); EXTENSIONS.put("oda", "application/oda"); EXTENSIONS.put("odb", "application/vnd.oasis.opendocument.database"); EXTENSIONS.put("odc", "application/vnd.oasis.opendocument.chart"); EXTENSIONS.put("odf", "application/vnd.oasis.opendocument.formula"); EXTENSIONS.put("odg", "application/vnd.oasis.opendocument.graphics"); EXTENSIONS.put("odi", "application/vnd.oasis.opendocument.image"); EXTENSIONS.put("odm", "application/vnd.oasis.opendocument.text-master"); EXTENSIONS.put("odp", "application/vnd.oasis.opendocument.presentation"); EXTENSIONS.put("ods", "application/vnd.oasis.opendocument.spreadsheet"); EXTENSIONS.put("odt", "application/vnd.oasis.opendocument.text"); EXTENSIONS.put("oga", "audio/ogg"); EXTENSIONS.put("ogg", "audio/ogg"); EXTENSIONS.put("ogv", "video/ogg"); EXTENSIONS.put("omc", "application/x-omc"); EXTENSIONS.put("omcd", "application/x-omcdatamaker"); EXTENSIONS.put("omcr", "application/x-omcregerator"); EXTENSIONS.put("otc", "application/vnd.oasis.opendocument.chart-template"); EXTENSIONS.put("otf", "application/vnd.oasis.opendocument.formula-template"); EXTENSIONS.put("otg", "application/vnd.oasis.opendocument.graphics-template"); EXTENSIONS.put("oth", "application/vnd.oasis.opendocument.text-web"); EXTENSIONS.put("oti", "application/vnd.oasis.opendocument.image-template"); EXTENSIONS.put("otm", "application/vnd.oasis.opendocument.text-master"); EXTENSIONS.put("otp", "application/vnd.oasis.opendocument.presentation-template"); EXTENSIONS.put("ots", "application/vnd.oasis.opendocument.spreadsheet-template"); EXTENSIONS.put("ott", "application/vnd.oasis.opendocument.text-template"); EXTENSIONS.put("p10", "application/pkcs10"); EXTENSIONS.put("p12", "application/pkcs-12"); EXTENSIONS.put("p7a", "application/x-pkcs7-signature"); EXTENSIONS.put("p7c", "application/pkcs7-mime"); EXTENSIONS.put("p7m", "application/pkcs7-mime"); EXTENSIONS.put("p7r", "application/x-pkcs7-certreqresp"); EXTENSIONS.put("p7s", "application/pkcs7-signature"); EXTENSIONS.put("p", "text/x-pascal"); EXTENSIONS.put("part", "application/pro_eng"); EXTENSIONS.put("pas", "text/pascal"); EXTENSIONS.put("pbm", "image/x-portable-bitmap"); EXTENSIONS.put("pcl", "application/vndhp-pcl"); EXTENSIONS.put("pct", "image/x-pict"); EXTENSIONS.put("pcx", "image/x-pcx"); EXTENSIONS.put("pdb", "chemical/x-pdb"); EXTENSIONS.put("pdf", "application/pdf"); EXTENSIONS.put("pfunk", "audio/make"); EXTENSIONS.put("pgm", "image/x-portable-graymap"); EXTENSIONS.put("pic", "image/pict"); EXTENSIONS.put("pict", "image/pict"); EXTENSIONS.put("pkg", "application/x-newton-compatible-pkg"); EXTENSIONS.put("pko", "application/vndms-pkipko"); EXTENSIONS.put("pl", "text/x-scriptperl"); EXTENSIONS.put("plx", "application/x-pixclscript"); EXTENSIONS.put("pm4", "application/x-pagemaker"); EXTENSIONS.put("pm5", "application/x-pagemaker"); EXTENSIONS.put("pm", "text/x-scriptperl-module"); EXTENSIONS.put("png", "image/png"); EXTENSIONS.put("pnm", "application/x-portable-anymap"); EXTENSIONS.put("pot", "application/mspowerpoint"); EXTENSIONS.put("pov", "model/x-pov"); EXTENSIONS.put("ppa", "application/vndms-powerpoint"); EXTENSIONS.put("ppm", "image/x-portable-pixmap"); EXTENSIONS.put("pps", "application/mspowerpoint"); EXTENSIONS.put("ppt", "application/mspowerpoint"); EXTENSIONS.put("ppz", "application/mspowerpoint"); EXTENSIONS.put("pre", "application/x-freelance"); EXTENSIONS.put("prt", "application/pro_eng"); EXTENSIONS.put("ps", "application/postscript"); EXTENSIONS.put("psd", "application/octet-stream"); EXTENSIONS.put("pvu", "paleovu/x-pv"); EXTENSIONS.put("pwz", "application/vndms-powerpoint"); EXTENSIONS.put("py", "text/x-scriptphyton"); EXTENSIONS.put("pyc", "applicaiton/x-bytecodepython"); EXTENSIONS.put("qcp", "audio/vndqcelp"); EXTENSIONS.put("qd3", "x-world/x-3dmf"); EXTENSIONS.put("qd3d", "x-world/x-3dmf"); EXTENSIONS.put("qif", "image/x-quicktime"); EXTENSIONS.put("qt", "video/quicktime"); EXTENSIONS.put("qtc", "video/x-qtc"); EXTENSIONS.put("qti", "image/x-quicktime"); EXTENSIONS.put("qtif", "image/x-quicktime"); EXTENSIONS.put("ra", "audio/x-pn-realaudio"); EXTENSIONS.put("ram", "audio/x-pn-realaudio"); EXTENSIONS.put("rar", "application/x-rar-compressed"); EXTENSIONS.put("ras", "application/x-cmu-raster"); EXTENSIONS.put("rast", "image/cmu-raster"); EXTENSIONS.put("rexx", "text/x-scriptrexx"); EXTENSIONS.put("rf", "image/vndrn-realflash"); EXTENSIONS.put("rgb", "image/x-rgb"); EXTENSIONS.put("rm", "application/vndrn-realmedia"); EXTENSIONS.put("rmi", "audio/mid"); EXTENSIONS.put("rmm", "audio/x-pn-realaudio"); EXTENSIONS.put("rmp", "audio/x-pn-realaudio"); EXTENSIONS.put("rng", "application/ringing-tones"); EXTENSIONS.put("rnx", "application/vndrn-realplayer"); EXTENSIONS.put("roff", "application/x-troff"); EXTENSIONS.put("rp", "image/vndrn-realpix"); EXTENSIONS.put("rpm", "audio/x-pn-realaudio-plugin"); EXTENSIONS.put("rt", "text/vndrn-realtext"); EXTENSIONS.put("rtf", "text/richtext"); EXTENSIONS.put("rtx", "text/richtext"); EXTENSIONS.put("rv", "video/vndrn-realvideo"); EXTENSIONS.put("s", "text/x-asm"); EXTENSIONS.put("s3m", "audio/s3m"); EXTENSIONS.put("s7z", "application/x-7z-compressed"); EXTENSIONS.put("saveme", "application/octet-stream"); EXTENSIONS.put("sbk", "application/x-tbook"); EXTENSIONS.put("scm", "text/x-scriptscheme"); EXTENSIONS.put("sdml", "text/plain"); EXTENSIONS.put("sdp", "application/sdp"); EXTENSIONS.put("sdr", "application/sounder"); EXTENSIONS.put("sea", "application/sea"); EXTENSIONS.put("set", "application/set"); EXTENSIONS.put("sgm", "text/x-sgml"); EXTENSIONS.put("sgml", "text/x-sgml"); EXTENSIONS.put("sh", "text/x-scriptsh"); EXTENSIONS.put("shar", "application/x-bsh"); EXTENSIONS.put("shtml", "text/x-server-parsed-html"); EXTENSIONS.put("sid", "audio/x-psid"); EXTENSIONS.put("skd", "application/x-koan"); EXTENSIONS.put("skm", "application/x-koan"); EXTENSIONS.put("skp", "application/x-koan"); EXTENSIONS.put("skt", "application/x-koan"); EXTENSIONS.put("sit", "application/x-stuffit"); EXTENSIONS.put("sitx", "application/x-stuffitx"); EXTENSIONS.put("sl", "application/x-seelogo"); EXTENSIONS.put("smi", "application/smil"); EXTENSIONS.put("smil", "application/smil"); EXTENSIONS.put("snd", "audio/basic"); EXTENSIONS.put("sol", "application/solids"); EXTENSIONS.put("spc", "text/x-speech"); EXTENSIONS.put("spl", "application/futuresplash"); EXTENSIONS.put("spr", "application/x-sprite"); EXTENSIONS.put("sprite", "application/x-sprite"); EXTENSIONS.put("spx", "audio/ogg"); EXTENSIONS.put("src", "application/x-wais-source"); EXTENSIONS.put("ssi", "text/x-server-parsed-html"); EXTENSIONS.put("ssm", "application/streamingmedia"); EXTENSIONS.put("sst", "application/vndms-pkicertstore"); EXTENSIONS.put("step", "application/step"); EXTENSIONS.put("stl", "application/sla"); EXTENSIONS.put("stp", "application/step"); EXTENSIONS.put("sv4cpio", "application/x-sv4cpio"); EXTENSIONS.put("sv4crc", "application/x-sv4crc"); EXTENSIONS.put("svf", "image/vnddwg"); EXTENSIONS.put("svg", "image/svg+xml"); EXTENSIONS.put("svr", "application/x-world"); EXTENSIONS.put("swf", "application/x-shockwave-flash"); EXTENSIONS.put("t", "application/x-troff"); EXTENSIONS.put("talk", "text/x-speech"); EXTENSIONS.put("tar", "application/x-tar"); EXTENSIONS.put("tbk", "application/toolbook"); EXTENSIONS.put("tcl", "text/x-scripttcl"); EXTENSIONS.put("tcsh", "text/x-scripttcsh"); EXTENSIONS.put("tex", "application/x-tex"); EXTENSIONS.put("texi", "application/x-texinfo"); EXTENSIONS.put("texinfo", "application/x-texinfo"); EXTENSIONS.put("text", "text/plain"); EXTENSIONS.put("tgz", "application/gnutar"); EXTENSIONS.put("tif", "image/tiff"); EXTENSIONS.put("tiff", "image/tiff"); EXTENSIONS.put("tr", "application/x-troff"); EXTENSIONS.put("tsi", "audio/tsp-audio"); EXTENSIONS.put("tsp", "application/dsptype"); EXTENSIONS.put("tsv", "text/tab-separated-values"); EXTENSIONS.put("turbot", "image/florian"); EXTENSIONS.put("txt", "text/plain"); EXTENSIONS.put("uil", "text/x-uil"); EXTENSIONS.put("uni", "text/uri-list"); EXTENSIONS.put("unis", "text/uri-list"); EXTENSIONS.put("unv", "application/i-deas"); EXTENSIONS.put("uri", "text/uri-list"); EXTENSIONS.put("uris", "text/uri-list"); EXTENSIONS.put("ustar", "application/x-ustar"); EXTENSIONS.put("uu", "text/x-uuencode"); EXTENSIONS.put("uue", "text/x-uuencode"); EXTENSIONS.put("vcd", "application/x-cdlink"); EXTENSIONS.put("vcf", "text/x-vcard"); EXTENSIONS.put("vcard", "text/x-vcard"); EXTENSIONS.put("vcs", "text/x-vcalendar"); EXTENSIONS.put("vda", "application/vda"); EXTENSIONS.put("vdo", "video/vdo"); EXTENSIONS.put("vew", "application/groupwise"); EXTENSIONS.put("viv", "video/vivo"); EXTENSIONS.put("vivo", "video/vivo"); EXTENSIONS.put("vmd", "application/vocaltec-media-desc"); EXTENSIONS.put("vmf", "application/vocaltec-media-file"); EXTENSIONS.put("voc", "audio/voc"); EXTENSIONS.put("vos", "video/vosaic"); EXTENSIONS.put("vox", "audio/voxware"); EXTENSIONS.put("vqe", "audio/x-twinvq-plugin"); EXTENSIONS.put("vqf", "audio/x-twinvq"); EXTENSIONS.put("vql", "audio/x-twinvq-plugin"); EXTENSIONS.put("vrml", "application/x-vrml"); EXTENSIONS.put("vrt", "x-world/x-vrt"); EXTENSIONS.put("vsd", "application/x-visio"); EXTENSIONS.put("vst", "application/x-visio"); EXTENSIONS.put("vsw", "application/x-visio"); EXTENSIONS.put("w60", "application/wordperfect60"); EXTENSIONS.put("w61", "application/wordperfect61"); EXTENSIONS.put("w6w", "application/msword"); EXTENSIONS.put("wav", "audio/wav"); EXTENSIONS.put("wb1", "application/x-qpro"); EXTENSIONS.put("wbmp", "image/vnd.wap.wbmp"); EXTENSIONS.put("web", "application/vndxara"); EXTENSIONS.put("wiz", "application/msword"); EXTENSIONS.put("wk1", "application/x-123"); EXTENSIONS.put("wmf", "windows/metafile"); EXTENSIONS.put("wml", "text/vnd.wap.wml"); EXTENSIONS.put("wmlc", "application/vnd.wap.wmlc"); EXTENSIONS.put("wmls", "text/vnd.wap.wmlscript"); EXTENSIONS.put("wmlsc", "application/vnd.wap.wmlscriptc"); EXTENSIONS.put("word", "application/msword"); EXTENSIONS.put("wp5", "application/wordperfect"); EXTENSIONS.put("wp6", "application/wordperfect"); EXTENSIONS.put("wp", "application/wordperfect"); EXTENSIONS.put("wpd", "application/wordperfect"); EXTENSIONS.put("wq1", "application/x-lotus"); EXTENSIONS.put("wri", "application/mswrite"); EXTENSIONS.put("wrl", "application/x-world"); EXTENSIONS.put("wrz", "model/vrml"); EXTENSIONS.put("wsc", "text/scriplet"); EXTENSIONS.put("wsrc", "application/x-wais-source"); EXTENSIONS.put("wtk", "application/x-wintalk"); EXTENSIONS.put("x-png", "image/png"); EXTENSIONS.put("xbm", "image/x-xbitmap"); EXTENSIONS.put("xdr", "video/x-amt-demorun"); EXTENSIONS.put("xgz", "xgl/drawing"); EXTENSIONS.put("xif", "image/vndxiff"); EXTENSIONS.put("xl", "application/excel"); EXTENSIONS.put("xla", "application/excel"); EXTENSIONS.put("xlb", "application/excel"); EXTENSIONS.put("xlc", "application/excel"); EXTENSIONS.put("xld", "application/excel"); EXTENSIONS.put("xlk", "application/excel"); EXTENSIONS.put("xll", "application/excel"); EXTENSIONS.put("xlm", "application/excel"); EXTENSIONS.put("xls", "application/excel"); EXTENSIONS.put("xlt", "application/excel"); EXTENSIONS.put("xlv", "application/excel"); EXTENSIONS.put("xlw", "application/excel"); EXTENSIONS.put("xm", "audio/xm"); EXTENSIONS.put("xml", "text/xml"); EXTENSIONS.put("xmz", "xgl/movie"); EXTENSIONS.put("xpix", "application/x-vndls-xpix"); EXTENSIONS.put("xpm", "image/x-xpixmap"); EXTENSIONS.put("xsr", "video/x-amt-showrun"); EXTENSIONS.put("xwd", "image/x-xwd"); EXTENSIONS.put("xyz", "chemical/x-pdb"); EXTENSIONS.put("z", "application/x-compress"); EXTENSIONS.put("zip", "application/zip"); EXTENSIONS.put("zoo", "application/octet-stream"); EXTENSIONS.put("zsh", "text/x-scriptzsh"); EXTENSIONS.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); EXTENSIONS.put("docm", "application/vnd.ms-word.document.macroEnabled.12"); EXTENSIONS.put("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"); EXTENSIONS.put("dotm", "application/vnd.ms-word.template.macroEnabled.12"); EXTENSIONS.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); EXTENSIONS.put("xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"); EXTENSIONS.put("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"); EXTENSIONS.put("xltm", "application/vnd.ms-excel.template.macroEnabled.12"); EXTENSIONS.put("xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"); EXTENSIONS.put("xlam", "application/vnd.ms-excel.addin.macroEnabled.12"); EXTENSIONS.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"); EXTENSIONS.put("pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"); EXTENSIONS.put("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"); EXTENSIONS.put("ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"); EXTENSIONS.put("potx", "application/vnd.openxmlformats-officedocument.presentationml.template"); EXTENSIONS.put("potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"); EXTENSIONS.put("ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"); EXTENSIONS.put("sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"); EXTENSIONS.put("sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"); EXTENSIONS.put("thmx", "application/vnd.ms-officetheme "); EXTENSIONS.put("onetoc", "application/onenote"); EXTENSIONS.put("onetoc2", "application/onenote"); EXTENSIONS.put("onetmp", "application/onenote"); EXTENSIONS.put("onepkg", "application/onenote"); //iWork" EXTENSIONS.put("key", "application/x-iwork-keynote-sffkey"); EXTENSIONS.put("kth", "application/x-iwork-keynote-sffkth"); EXTENSIONS.put("nmbtemplate", "application/x-iwork-numbers-sfftemplate"); EXTENSIONS.put("numbers", "application/x-iwork-numbers-sffnumbers"); EXTENSIONS.put("pages", "application/x-iwork-pages-sffpages"); EXTENSIONS.put("template", "application/x-iwork-pages-sfftemplate"); //Extensions for Mozilla apps (Firefox and friends) EXTENSIONS.put("xpi", "application/x-xpinstall"); } public static String getMimeTypeByExtension(String extension) { return EXTENSIONS.get(extension); } }
package io.vertx.ext.auth.authentication; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.http.HttpMethod; import io.vertx.core.json.JsonObject; /** * Abstract representation of a Credentials object. All implementations of this interface will define the * required types and parameters for the specific implementation. * * @author Paulo Lopes */ @VertxGen(concrete = false) public interface Credentials { /** * Implementors should override this method to perform validation. An argument is allowed to * allow custom validation, for example, when given a configuration property, a specific * property may be allowed to be null. * * @param arg optional argument or null. * @param <V> the generic type of the argument * @throws CredentialValidationException when the validation fails */ default <V> void checkValid(V arg) throws CredentialValidationException { } /** * Simple interop to downcast back to JSON for backwards compatibility. * * @return JSON representation of this credential. */ JsonObject toJson(); default Credentials applyHttpChallenge(String challenge, HttpMethod method, String uri, Integer nc, String cnonce) throws CredentialValidationException { if (challenge != null) { throw new CredentialValidationException("This implementation can't handle HTTP Authentication"); } return this; } default Credentials applyHttpChallenge(String challenge, HttpMethod method, String uri) throws CredentialValidationException { return applyHttpChallenge(challenge, method, uri, null, null); } default Credentials applyHttpChallenge(String challenge) throws CredentialValidationException { return applyHttpChallenge(challenge, null, null, null, null); } default String toHttpAuthorization() { throw new UnsupportedOperationException(getClass().getName() + " cannot be converted to a HTTP Authorization"); } }
/* $Log$ Revision 1.10 1999/02/25 08:01:27 rimassa Changed direct access to 'myName' and 'myAddress' variables to accessor method calls. Revision 1.9 1999/02/14 22:52:05 rimassa Renamed addBehaviour() calls to addSubBehaviour() calls. Revision 1.8 1998/10/18 16:10:38 rimassa Some code changes to avoid deprecated APIs. - Agent.parse() is now deprecated. Use ACLMessage.fromText(Reader r) instead. - ACLMessage() constructor is now deprecated. Use ACLMessage(String type) instead. - ACLMessage.dump() is now deprecated. Use ACLMessage.toText(Writer w) instead. Revision 1.7 1998/10/04 18:00:31 rimassa Added a 'Log:' field to every source file. */ package examples.ex5; // This agent allows a comprehensive testing of Agent Management // System agent. import java.io.*; import jade.core.*; import jade.lang.acl.*; public class amsTester extends Agent { private static class Receiver { // Utility class with private constructor -- do not instantiate. private Receiver() { } public static final ACLMessage receive(amsTester a, String messageType) { // Receive <messageType> message from peer MessageTemplate mt1 = MessageTemplate.MatchProtocol("fipa-request"); MessageTemplate mt2 = MessageTemplate.MatchConversationId(a.getConvID()); MessageTemplate mt3 = MessageTemplate.MatchSource("ams"); MessageTemplate mt4 = MessageTemplate.MatchType(messageType); MessageTemplate mt12 = MessageTemplate.and(mt1, mt2); MessageTemplate mt34 = MessageTemplate.and(mt3, mt4); MessageTemplate mt = MessageTemplate.and(mt12, mt34); ACLMessage msg = a.receive(mt); return msg; } } // End of Receiver class // Used to generate conversation IDs. private int convCounter = 0; // Name of the action the AMS will be required to perform private String myAction; // Values for the various parameters of the request to AMS agent private String agentName = null; private String address = null; private String signature = null; private String APState = null; private String delegateAgent = null; private String forwardAddress = null; // Holds the current conversation ID. private String convID; private boolean receivedAgree = false; private abstract class ReceiveBehaviour extends SimpleBehaviour { protected boolean finished = false; protected ReceiveBehaviour() { } public abstract void action(); public boolean done() { return finished; } } // End of ReceiveBehaviour class protected void setup() { int len = 0; byte[] buffer = new byte[1024]; try { System.out.println("Enter AMS agent action to perform:"); len = System.in.read(buffer); myAction = new String(buffer,0,len-1); System.out.println("Enter values for parameters (ENTER leaves them blank)"); System.out.print(":agent-name "); len = System.in.read(buffer); agentName = new String(buffer,0,len-1); System.out.print(":address "); len = System.in.read(buffer); address = new String(buffer,0,len-1); System.out.print(":signature "); len = System.in.read(buffer); signature = new String(buffer,0,len-1); System.out.print(":ap-state "); len = System.in.read(buffer); APState = new String(buffer,0,len-1); System.out.print(":delegate-agent-name "); len = System.in.read(buffer); delegateAgent = new String(buffer,0,len-1); System.out.print(":forward-address "); len = System.in.read(buffer); forwardAddress = new String(buffer,0,len-1); System.out.println(""); } catch(IOException ioe) { ioe.printStackTrace(); } ComplexBehaviour mainBehaviour = new SequentialBehaviour(this); mainBehaviour.addSubBehaviour(new OneShotBehaviour(this) { public void action() { System.out.println("Sending 'request' message to AMS"); sendRequest(); } }); ComplexBehaviour receive1stReply = NonDeterministicBehaviour.createWhenAny(this); receive1stReply.addSubBehaviour(new ReceiveBehaviour() { public void action() { ACLMessage msg = Receiver.receive(amsTester.this, "not-understood"); if(msg != null) dumpMessage(msg); finished = (msg != null); } }); receive1stReply.addSubBehaviour(new ReceiveBehaviour() { public void action() { ACLMessage msg = Receiver.receive(amsTester.this,"refuse"); if(msg != null) dumpMessage(msg); finished = (msg != null); } }); receive1stReply.addSubBehaviour(new ReceiveBehaviour() { public void action() { ACLMessage msg = Receiver.receive(amsTester.this,"agree"); if(msg != null) receiveAgree(msg); finished = (msg != null); } }); // Nondeterministically receives not-understood, refuse or agree. mainBehaviour.addSubBehaviour(receive1stReply); // If agree is received, also receive inform or failure messages. mainBehaviour.addSubBehaviour(new OneShotBehaviour(this) { public void action() { if(agreed()) { ComplexBehaviour receiveAfterAgree = NonDeterministicBehaviour.createWhenAny(amsTester.this); receiveAfterAgree.addSubBehaviour(new ReceiveBehaviour() { public void action() { ACLMessage msg = Receiver.receive(amsTester.this,"failure"); if(msg != null) handleFailure(msg); finished = (msg != null); } }); receiveAfterAgree.addSubBehaviour(new ReceiveBehaviour() { public void action() { ACLMessage msg = Receiver.receive(amsTester.this,"inform"); if(msg != null) handleInform(msg); finished = (msg != null); } }); // Schedules next behaviour for execution myAgent.addBehaviour(receiveAfterAgree); } else System.out.println("Protocol ended."); } }); addBehaviour(mainBehaviour); } // End of setup() public String getAction() { return myAction; } public boolean agreed() { return receivedAgree; } private String newConvID() { String s = new String(getLocalName() + (new Integer(convCounter).toString())); ++convCounter; return s; } public String getConvID() { return convID; } // Message handlers for various protocol steps. public void sendRequest() { convID = newConvID(); String text = "( request " + " :sender " + getLocalName() + " :receiver ams" + " :protocol fipa-request" + " :ontology fipa-agent-management" + " :language SL0" + " :content ( action ams ( " + myAction + " ( :ams-description "; if(agentName.length() > 0) text = text.concat("( :agent-name " + agentName + " )"); if(address.length() > 0) text = text.concat("( :address " + address + " )"); if(signature.length() > 0) text = text.concat("( :signature " + signature + " )"); if(APState.length() > 0) text = text.concat("( :ap-state " + APState + " )"); if(forwardAddress.length() > 0) text = text.concat("( :forward-address" + forwardAddress + " )"); if(delegateAgent.length() > 0) text = text.concat("( :delegate-agent-name" + delegateAgent + " )"); text = text + " ) ) )" + " :conversation-id " + convID + ")"; ACLMessage toSend = ACLMessage.fromText(new StringReader(text)); send(toSend); System.out.println("[Agent.sendRequest()]\tRequest sent"); } public void dumpMessage(ACLMessage msg) { System.out.println("[Agent.dumpMessage]\tReceived message:"); msg.toText(new BufferedWriter(new OutputStreamWriter(System.out))); } public void receiveAgree(ACLMessage msg) { System.out.println("[Agent.receiveAgree]\tSuccess!!! Responder agreed to do action !"); msg.toText(new BufferedWriter(new OutputStreamWriter(System.out))); receivedAgree = true; } public void handleFailure(ACLMessage msg) { System.out.println("Responder failed to process the request. Reason was:"); System.out.println(msg.getContent()); msg.toText(new BufferedWriter(new OutputStreamWriter(System.out))); } public void handleInform(ACLMessage msg) { System.out.println("Responder has just informed me that the action has been carried out."); msg.toText(new BufferedWriter(new OutputStreamWriter(System.out))); } }
package edu.cornell.mannlib.vitro.webapp.controller.jena; import java.io.IOException; import java.io.OutputStream; import java.io.StringWriter; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hp.hpl.jena.iri.IRI; import com.hp.hpl.jena.iri.IRIFactory; import com.hp.hpl.jena.ontology.AllValuesFromRestriction; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.ontology.Restriction; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.shared.Lock; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import edu.cornell.mannlib.vedit.controller.BaseEditController; import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; public class JenaAdminActions extends BaseEditController { private static final Log log = LogFactory.getLog(JenaAdminActions.class.getName()); private boolean checkURI( String uri ) { IRIFactory factory = IRIFactory.jenaImplementation(); IRI iri = factory.create( uri ); if (iri.hasViolation(false) ) { log.error("Bad URI: "+uri); log.error( "Only well-formed absolute URIrefs can be included in RDF/XML output: " + iri.violations(false).next().getShortMessage()); return true; } else { return false; } } private static final String VITRO = "http://vitro.mannlib.cornell.edu/ns/vitro/0.7 private static final String AKT_SUPPORT = "http://www.aktors.org/ontology/support private static final String AKT_PORTAL = "http://www.aktors.org/ontology/portal private void copyStatements(Model src, Model dest, Resource subj, Property pred, RDFNode obj) { for (Statement stmt : src.listStatements(subj,pred,obj).toList()) { String subjNs = stmt.getSubject().getNameSpace(); if (subjNs == null || (! (subjNs.equals(VITRO) || subjNs.equals(AKT_SUPPORT) || subjNs.equals(AKT_PORTAL) ) ) ) { if (stmt.getObject().isLiteral()) { dest.add(stmt); } else if (stmt.getObject().isResource()) { String objNs = ((Resource)stmt.getObject()).getNameSpace(); if (objNs == null || (! (objNs.equals(VITRO) || objNs.equals(AKT_SUPPORT) || objNs.equals(AKT_PORTAL) ) ) ) { dest.add(stmt); } } } } } /** * This doesn't really print just the TBox. It takes a copy of the model, removes all the individuals, and writes the result. */ private void outputTbox(HttpServletResponse response) { OntModel memoryModel = ModelAccess.on(getServletContext()).getBaseOntModel(); try { OntModel tempOntModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM); memoryModel.enterCriticalSection(Lock.READ); try { copyStatements(memoryModel,tempOntModel,null,RDF.type,OWL.Class); copyStatements(memoryModel,tempOntModel,null,RDF.type,OWL.ObjectProperty); copyStatements(memoryModel,tempOntModel,null,RDF.type,OWL.DatatypeProperty); copyStatements(memoryModel,tempOntModel,null,RDF.type,OWL.AnnotationProperty); copyStatements(memoryModel,tempOntModel,null,RDFS.subClassOf,null); copyStatements(memoryModel,tempOntModel,null,RDFS.subPropertyOf,null); copyStatements(memoryModel,tempOntModel,null,RDFS.domain,null); copyStatements(memoryModel,tempOntModel,null,RDFS.range,null); copyStatements(memoryModel,tempOntModel,null,OWL.inverseOf,null); } finally { memoryModel.leaveCriticalSection(); } response.setContentType("application/rdf+xml"); OutputStream out = response.getOutputStream(); tempOntModel.write(out); out.flush(); out.close(); tempOntModel = null; // Hit it, GC } catch (IOException e) { e.printStackTrace(); } } private Model extractTaxonomy(OntModel ontModel) { ontModel.enterCriticalSection(Lock.READ); Model taxonomyModel = ModelFactory.createDefaultModel(); try { HashSet<Resource> typeSet = new HashSet<Resource>(); for (Statement stmt : ontModel.listStatements((Resource)null,RDF.type,(RDFNode)null).toList()) { if (stmt.getObject().isResource()) { typeSet.add((Resource) stmt.getObject()); } } for (Resource classRes : ontModel.listClasses().toList()) { typeSet.add(classRes); } for (Resource ontClass : typeSet) { if (!ontClass.isAnon()) { // Only query for named classes System.out.println("Describing "+ontClass.getURI()); // We want a subgraph describing this class, including related BNodes String queryStr = "DESCRIBE <"+ontClass.getURI()+">"; Query describeQuery = QueryFactory.create(queryStr); QueryExecution qe = QueryExecutionFactory.create(describeQuery,ontModel); qe.execDescribe(taxonomyModel); } } } finally { ontModel.leaveCriticalSection(); } System.out.println("Cleaning out the vitro properties"); Model cleanModel = ModelFactory.createDefaultModel(); StmtIterator stmtIt = taxonomyModel.listStatements(); while (stmtIt.hasNext()) { Statement stmt = stmtIt.nextStatement(); if ( !(stmt.getPredicate().getURI().indexOf(VitroVocabulary.vitroURI)==0) ) { // if it's not a vitro internal property, copy it over cleanModel.add(stmt); } } return cleanModel; } private String testWriteXML() { StringBuffer output = new StringBuffer(); output.append("<html><head><title>Test Write XML</title></head><body><pre>\n"); OntModel model = ModelAccess.on(getServletContext()).getJenaOntModel(); Model tmp = ModelFactory.createDefaultModel(); boolean valid = true; for (Statement stmt : model.listStatements().toList() ) { tmp.add(stmt); StringWriter writer = new StringWriter(); try { tmp.write(writer, "RDF/XML"); } catch (Exception e) { valid = false; output.append(" output.append("Unable to write statement as RDF/XML:\n"); output.append("Subject : \n"+stmt.getSubject().getURI()); output.append("Subject : \n"+stmt.getPredicate().getURI()); String objectStr = (stmt.getObject().isLiteral()) ? ((Literal)stmt.getObject()).getLexicalForm() : ((Resource)stmt.getObject()).getURI(); output.append("Subject : \n"+objectStr); output.append("Exception: \n"); e.printStackTrace(); } tmp.removeAll(); } if (valid) { output.append("All statements were able to be written as RDF/XML\n"); } output.append("</body></html>"); return output.toString(); } private void printRestrictions() { OntModel memoryModel = (OntModel) getServletContext().getAttribute("pelletOntModel"); for (Restriction rest : memoryModel.listRestrictions().toList() ) { //System.out.println(); if (rest.isAllValuesFromRestriction()) { log.trace("All values from: "); AllValuesFromRestriction avfr = rest.asAllValuesFromRestriction(); Resource res = avfr.getAllValuesFrom(); if (res.canAs(OntClass.class)) { OntClass resClass = res.as(OntClass.class); for (Resource inst : resClass.listInstances().toList() ) { log.trace(" -"+inst.getURI()); } } } else if (rest.isSomeValuesFromRestriction()) { log.trace("Some values from: "); } else if (rest.isHasValueRestriction()) { log.trace("Has value: "); } log.trace("On property "+rest.getOnProperty().getURI()); for (Resource inst : rest.listInstances().toList() ) { log.trace(" "+inst.getURI()); } } } private void removeLongLiterals() { OntModel memoryModel = ModelAccess.on(getServletContext()).getJenaOntModel(); memoryModel.enterCriticalSection(Lock.WRITE); try { List<Statement> statementsToRemove = new LinkedList<Statement>(); for (Statement stmt : memoryModel.listStatements(null,null,(Literal)null).toList() ) { if (stmt.getObject().isLiteral()) { Literal lit = (Literal) stmt.getObject(); if ( lit.getString().length() > 24) { statementsToRemove.add(stmt); } } } for (Iterator<Statement> removeIt = statementsToRemove.iterator(); removeIt.hasNext(); ) { Statement stmt = removeIt.next(); memoryModel.remove(stmt); } } finally { memoryModel.leaveCriticalSection(); } } @Override public void doGet(HttpServletRequest req, HttpServletResponse response) { if (!isAuthorizedToDisplayPage(req, response, SimplePermission.USE_MISCELLANEOUS_ADMIN_PAGES.ACTIONS)) { return; } VitroRequest request = new VitroRequest(req); String actionStr = request.getParameter("action"); if (actionStr.equals("printRestrictions")) { printRestrictions(); } else if (actionStr.equals("outputTbox")) { outputTbox(response); } else if (actionStr.equals("testWriteXML")) { try { response.getWriter().write(testWriteXML()); } catch ( IOException ioe ) { throw new RuntimeException( ioe ); } } if (actionStr.equals("checkURIs")) { OntModel memoryModel = ModelAccess.on(getServletContext()).getJenaOntModel(); StmtIterator stmtIt = memoryModel.listStatements(); try { for (Statement stmt : stmtIt.toList() ) { boolean sFailed = false; boolean pFailed = false; boolean oFailed = false; String sURI = "<bNode>"; String pURI = "???"; String oURI = "<bNode>"; if (stmt.getSubject().getURI() != null) { sFailed = checkURI(sURI = stmt.getSubject().getURI()); } if (stmt.getPredicate().getURI() != null) { pFailed = checkURI(pURI = stmt.getPredicate().getURI()); } if (stmt.getObject().isResource() && ((Resource)stmt.getObject()).getURI() != null) { oFailed = checkURI(oURI = ((Resource)stmt.getObject()).getURI()); } if (sFailed || pFailed || oFailed) { log.debug(sURI+" | "+pURI+" | "+oURI); } } } finally { stmtIt.close(); } } if (actionStr.equals("output")) { OntModel memoryModel = null; if (request.getParameter("assertionsOnly") != null) { memoryModel = ModelAccess.on(getServletContext()).getBaseOntModel(); System.out.println("baseOntModel"); } else if (request.getParameter("inferences") != null) { memoryModel = ModelAccess.on(getServletContext()).getInferenceOntModel(); System.out.println("inferenceOntModel"); } else if (request.getParameter("pellet") != null) { memoryModel = (OntModel) getServletContext().getAttribute("pelletOntModel"); System.out.println("pelletOntModel"); } else { memoryModel = ModelAccess.on(getServletContext()).getJenaOntModel(); System.out.println("jenaOntModel"); } int subModelCount = memoryModel.listSubModels().toList().size(); System.out.println("Submodels: "+subModelCount); try { //response.setContentType("application/rdf+xml"); response.setContentType("application/x-turtle"); OutputStream out = response.getOutputStream(); memoryModel.write(out, "TTL"); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } if (actionStr.equals("removeLongLiterals")) { removeLongLiterals(); } if (actionStr.equals("outputTaxonomy")) { OntModel ontModel = ModelAccess.on(getServletContext()).getBaseOntModel(); Model taxonomyModel = extractTaxonomy(ontModel); try { taxonomyModel.write(response.getOutputStream()); } catch (Exception e) { log.error(e, e); } } } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) { doGet(request ,response); } }
package org.knowm.xchange.binance; import java.io.IOException; import java.math.BigDecimal; import java.util.List; import java.util.Map; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; 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 org.knowm.xchange.binance.dto.BinanceException; import org.knowm.xchange.binance.dto.account.*; import org.knowm.xchange.binance.dto.trade.BinanceCancelledOrder; import org.knowm.xchange.binance.dto.trade.BinanceListenKey; import org.knowm.xchange.binance.dto.trade.BinanceNewOrder; import org.knowm.xchange.binance.dto.trade.BinanceOrder; import org.knowm.xchange.binance.dto.trade.BinanceTrade; import org.knowm.xchange.binance.dto.trade.OrderSide; import org.knowm.xchange.binance.dto.trade.OrderType; import org.knowm.xchange.binance.dto.trade.TimeInForce; import si.mazi.rescu.ParamsDigest; @Path("") @Produces(MediaType.APPLICATION_JSON) public interface BinanceAuthenticated extends Binance { public static final String SIGNATURE = "signature"; static final String X_MBX_APIKEY = "X-MBX-APIKEY"; @POST @Path("api/v3/order") /** * Send in a new order * * @param symbol * @param side * @param type * @param timeInForce * @param quantity * @param price optional, must be provided for limit orders only * @param newClientOrderId optional, a unique id for the order. Automatically generated if not * sent. * @param stopPrice optional, used with stop orders * @param icebergQty optional, used with iceberg orders * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ BinanceNewOrder newOrder( @FormParam("symbol") String symbol, @FormParam("side") OrderSide side, @FormParam("type") OrderType type, @FormParam("timeInForce") TimeInForce timeInForce, @FormParam("quantity") BigDecimal quantity, @FormParam("price") BigDecimal price, @FormParam("newClientOrderId") String newClientOrderId, @FormParam("stopPrice") BigDecimal stopPrice, @FormParam("icebergQty") BigDecimal icebergQty, @FormParam("recvWindow") Long recvWindow, @FormParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @POST @Path("api/v3/order/test") /** * Test new order creation and signature/recvWindow long. Creates and validates a new order but * does not send it into the matching engine. * * @param symbol * @param side * @param type * @param timeInForce * @param quantity * @param price * @param newClientOrderId optional, a unique id for the order. Automatically generated by * default. * @param stopPrice optional, used with STOP orders * @param icebergQty optional used with icebergOrders * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ Object testNewOrder( @FormParam("symbol") String symbol, @FormParam("side") OrderSide side, @FormParam("type") OrderType type, @FormParam("timeInForce") TimeInForce timeInForce, @FormParam("quantity") BigDecimal quantity, @FormParam("price") BigDecimal price, @FormParam("newClientOrderId") String newClientOrderId, @FormParam("stopPrice") BigDecimal stopPrice, @FormParam("icebergQty") BigDecimal icebergQty, @FormParam("recvWindow") Long recvWindow, @FormParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("api/v3/order") /** * Check an order's status.<br> * Either orderId or origClientOrderId must be sent. * * @param symbol * @param orderId optional * @param origClientOrderId optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ BinanceOrder orderStatus( @QueryParam("symbol") String symbol, @QueryParam("orderId") long orderId, @QueryParam("origClientOrderId") String origClientOrderId, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @DELETE @Path("api/v3/order") /** * Cancel an active order. * * @param symbol * @param orderId optional * @param origClientOrderId optional * @param newClientOrderId optional, used to uniquely identify this cancel. Automatically * generated by default. * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ BinanceCancelledOrder cancelOrder( @QueryParam("symbol") String symbol, @QueryParam("orderId") long orderId, @QueryParam("origClientOrderId") String origClientOrderId, @QueryParam("newClientOrderId") String newClientOrderId, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("api/v3/openOrders") /** * Get all open orders on a symbol. * * @param symbol optional * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ List<BinanceOrder> openOrders( @QueryParam("symbol") String symbol, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("api/v3/openOrders") /** * Get all open orders without a symbol. * * @param symbol * @param recvWindow optional * @param timestamp mandatory * @return * @throws IOException * @throws BinanceException */ List<BinanceOrder> openOrders( @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("api/v3/allOrders") /** * Get all account orders; active, canceled, or filled. <br> * If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are * returned. * * @param symbol * @param orderId optional * @param limit optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ List<BinanceOrder> allOrders( @QueryParam("symbol") String symbol, @QueryParam("orderId") Long orderId, @QueryParam("limit") Integer limit, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("api/v3/account") /** * Get current account information. * * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ BinanceAccountInformation account( @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("api/v3/myTrades") /** * Get trades for a specific account and symbol. * * @param symbol * @param startTime optional * @param endTime optional * @param limit optional, default 500; max 1000. * @param fromId optional, tradeId to fetch from. Default gets most recent trades. * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ List<BinanceTrade> myTrades( @QueryParam("symbol") String symbol, @QueryParam("limit") Integer limit, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("fromId") Long fromId, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @POST @Path("wapi/v3/withdraw.html") /** * Submit a withdraw request. * * @param asset * @param address * @param addressTag optional for Ripple * @param amount * @param name optional, description of the address * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ WithdrawRequest withdraw( @FormParam("asset") String asset, @FormParam("address") String address, @FormParam("addressTag") String addressTag, @FormParam("amount") BigDecimal amount, @FormParam("name") String name, @FormParam("recvWindow") Long recvWindow, @FormParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("wapi/v3/depositHistory.html") /** * Fetch deposit history. * * @param asset optional * @param startTime optional * @param endTime optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ DepositList depositHistory( @QueryParam("asset") String asset, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("wapi/v3/withdrawHistory.html") /** * Fetch withdraw history. * * @param asset optional * @param startTime optional * @param endTime optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ WithdrawList withdrawHistory( @QueryParam("asset") String asset, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Fetch small amounts of assets exchanged BNB records. * * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @GET @Path("/wapi/v3/userAssetDribbletLog.html") AssetDribbletLogResponse getAssetDribbletLog( @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Fetch small amounts of assets exchanged BNB records. * * @param asset optional * @param startTime optional * @param endTime optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @GET @Path("/sapi/v1/asset/assetDividend") AssetDividendResponse getAssetDividend( @QueryParam("asset") String asset, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("wapi/v3/depositAddress.html") /** * Fetch deposit address. * * @param asset * @param recvWindow * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ DepositAddress depositAddress( @QueryParam("asset") String asset, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("wapi/v3/assetDetail.html") /** * Fetch asset details. * * @param recvWindow * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ AssetDetailResponse assetDetail( @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") long timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Returns a listen key for websocket login. * * @param apiKey the api key * @return * @throws BinanceException * @throws IOException */ @POST @Path("/api/v1/userDataStream") BinanceListenKey startUserDataStream(@HeaderParam(X_MBX_APIKEY) String apiKey) throws IOException, BinanceException; /** * Keeps the authenticated websocket session alive. * * @param apiKey the api key * @param listenKey the api secret * @return * @throws BinanceException * @throws IOException */ @PUT @Path("/api/v1/userDataStream?listenKey={listenKey}") Map<?, ?> keepAliveUserDataStream( @HeaderParam(X_MBX_APIKEY) String apiKey, @PathParam("listenKey") String listenKey) throws IOException, BinanceException; /** * Closes the websocket authenticated connection. * * @param apiKey the api key * @param listenKey the api secret * @return * @throws BinanceException * @throws IOException */ @DELETE @Path("/api/v1/userDataStream?listenKey={listenKey}") Map<?, ?> closeUserDataStream( @HeaderParam(X_MBX_APIKEY) String apiKey, @PathParam("listenKey") String listenKey) throws IOException, BinanceException; }
package edu.smcm.gamedev.butterseal; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; public class ButterSeal implements ApplicationListener { public static boolean ANDROID_MODE = true; public static final boolean PLAY_MUSIC = true; public static final int DEBUG = 10; BSSession session; BSInterface gui; @Override public void create() { session = new BSSession(); session.start(0); gui = new BSInterface(session); } @Override public void dispose() { gui.dispose(); } @Override public void render() { Gdx.gl.glClearColor(0,0,0,1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); if(!gui.player.state.isMoving) { gui.poll(Gdx.input); } gui.draw(); } @Override public void resize(int width, int height) { } @Override public void pause() { if(ButterSeal.ANDROID_MODE) { gui.dispose(); System.exit(0); } } @Override public void resume() { } } // Local Variables: // indent-tabs-mode: nil // End:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ca.teamdave.schwimmer.automodes.competition; import ca.teamdave.schwimmer.automodes.AutoModeDescriptor; import ca.teamdave.schwimmer.command.Command; import ca.teamdave.schwimmer.command.drive.DriveStop; import ca.teamdave.schwimmer.command.drive.DriveToPosition; import ca.teamdave.schwimmer.command.drive.FollowLine; import ca.teamdave.schwimmer.command.drive.TurnToHeading; import ca.teamdave.schwimmer.command.hopper.HopperHeight; import ca.teamdave.schwimmer.command.meta.Delay; import ca.teamdave.schwimmer.command.meta.Latch; import ca.teamdave.schwimmer.command.meta.Series; import ca.teamdave.schwimmer.command.pickup.PickupIntake; import ca.teamdave.schwimmer.command.pickup.PickupSpit; import ca.teamdave.schwimmer.command.pickup.PickupStop; import ca.teamdave.schwimmer.command.shooter.ShootDisks; import ca.teamdave.schwimmer.command.shooter.ShooterHeight; import ca.teamdave.schwimmer.util.Const; import ca.teamdave.schwimmer.util.DaveVector; /** * * @author leighpauls */ public class Back5Disk extends AutoModeDescriptor { public static Command getAsCommand() { double turnAngle = Const.getInstance().getDouble( "5_disk_turn_angle", 40); double driveAngle = Const.getInstance().getDouble( "5_disk_drive_angle", 25.0); double driveDistance = Const.getInstance().getDouble( "5_disk_drive_dist", 2.4); double drivePower = Const.getInstance().getDouble( "5_disk_drive_power", 0.3); double closeShotAngle = Const.getInstance().getDouble( "5_disk_close_angle", -5); return new Series(new Command[] { Back3Disk.getAsCommand(), // turn to disks and lower hopper new Latch(new Command[] { new TurnToHeading(turnAngle), new HopperHeight(false), }), new TurnToHeading(driveAngle), // drive forward and pick up new Latch(new Command[] { new PickupIntake(), // TODO: replace this with DriveToPosition new DriveToPosition( DaveVector.fromFieldRadial(driveDistance, driveAngle), drivePower ) }), new DriveStop(), new Delay(1.0), // raise the shooter, aim, and spit any caught disks new Latch(new Command[] { new PickupSpit(), new TurnToHeading(closeShotAngle), new ShooterHeight(true) }), new DriveStop(), // raise the hopper new Latch(new Command[] { // TODO: spin up the shooter wheels new HopperHeight(true), new PickupStop() }), // fire new ShootDisks(2) }); } public Command getTopLevelCommand() { return getAsCommand(); } public String getVisibleName() { return "Back 5 Disk"; } }
// WinControllerTest.java package de.htwg.battleship.controller.impl; import de.htwg.battleship.model.IPlayer; import de.htwg.battleship.model.IShip; import de.htwg.battleship.model.impl.Player; import de.htwg.battleship.model.impl.Ship; import de.htwg.battleship.util.StatCollection; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; /** * WinControllerTest tests the entire win controller. * @author Moritz Sauter (SauterMoritz@gmx.de) * @version 1.00 * @since 2014-12-14 */ public class WinControllerTest { /** * Set-Up method. */ @Before public final void setUp() { StatCollection.heightLenght = 2; StatCollection.shipNumberMax = 2; } /** * Test of win method, of class WinController. */ @Test public final void testNullWin() { IPlayer player1 = new Player(); IPlayer player2 = new Player(); IShip ship = new Ship(1, true, 0, 0); player1.getOwnBoard().addShip(ship); player2.getOwnBoard().addShip(ship); WinController wc = new WinController(player1, player2); IPlayer expRes = null; IPlayer result = wc.win(); assertEquals(expRes, result); } /** * Test of win method, result player1. */ @Test public final void testPlayer1Win() { IPlayer player1 = new Player(); IPlayer player2 = new Player(); IShip ship = new Ship(1, true, 0, 0); player1.getOwnBoard().addShip(ship); WinController wc = new WinController(player1, player2); IPlayer expRes = player1; IPlayer result = wc.win(); assertEquals(expRes, result); } /** * Test of win method, result player2. */ @Test public final void testPlayer2Win() { IPlayer player1 = new Player(); IPlayer player2 = new Player(); IShip ship = new Ship(1, true, 0, 0); player2.getOwnBoard().addShip(ship); WinController wc = new WinController(player1, player2); IPlayer expRes = player2; IPlayer result = wc.win(); assertEquals(expRes, result); } @Test public final void testPlayerDestroyed() { IPlayer player1 = new Player(); IPlayer player2 = new Player(); IShip ship = new Ship(1, true, 0, 0); player1.getOwnBoard().addShip(ship); player2.getOwnBoard().addShip(ship); IShip ship2 = new Ship(1, true, 1, 1); player1.getOwnBoard().addShip(ship2); player1.getOwnBoard().shoot(0, 0); WinController wc = new WinController(player1, player2); IPlayer expRes = null; IPlayer result = wc.win(); assertEquals(expRes, result); } }
package de.orolle.bigsense.update; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.Socket; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.FutureTask; import android.annotation.SuppressLint; import android.app.Notification; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.support.v4.app.NotificationCompat; import android.telephony.TelephonyManager; import android.util.Log; import de.orolle.bigsense.util.StreamPumper; /** * UpdateService connects to BigSenseWeb backend which * starts the update process. * The service connects to the backend server and than to the local ssh * server. The data between the 2 connections is transfered from one to * the other. * * @author Oliver Rolle * */ public class UpdateService extends Service { /** * prevents android from sleep */ private WakeLock mWakeLock; /** * Schedule update retry */ private final Timer timer = new Timer(); /** * Update interval. */ private long INTERVAL = 3600000; // every hour /** * Retry contact server timeout */ private long MAX_Retry_TIMEOUT = 30000; // try it 30 seconds /** * Remote SSH host and port */ public static final String SSH_HOST = "coolDomain.com"; public static final int SSH_PORT = 33822; private Process rootProcess; private static final String LOGTAG = "BigSense"; @SuppressLint({ "Wakelock", "WorldWriteableFiles" }) @Override public int onStartCommand(Intent intent, int flags, int startId) { Notification notification = new NotificationCompat.Builder(this).build(); startForeground(1337, notification); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "UpdateService"); mWakeLock.acquire(); //Store imei in file, so that the server can read it TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); String imei = TelephonyMgr.getDeviceId(); String path = getExternalFilesDir(null).getAbsolutePath(); FileOutputStream outputStream; try { outputStream = new FileOutputStream(new File(path + "/imei")); outputStream.write(imei.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } /* * Run update every hour */ timer.scheduleAtFixedRate(new TimerTask() { Socket remoteTunnel, localSSH; StreamPumper p0, p1; Thread t0, t1; @Override public void run() { Log.d(LOGTAG,"Run update, Starting of SSH-Server"); try { rootProcess = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(rootProcess.getOutputStream()); os.writeBytes("am force-stop com.icecoldapps.sshserver\n"); os.writeBytes("am start \"com.icecoldapps.sshserver/.viewStart\" &\n"); os.writeBytes("exit\n"); os.flush(); } catch (IOException e) { e.printStackTrace(); } if(remoteTunnel != null) { if(remoteTunnel.isClosed()) { stop(); } } if(localSSH != null) { if(localSSH.isClosed()) { stop(); } } if(p0 != null && p1 != null) { if(!p0.isFinished() && !p1.isFinished()) { return; } else { stop(); } } try { int tried = 0; while(tried < MAX_Retry_TIMEOUT/100 && (remoteTunnel == null || !remoteTunnel.isConnected())) { try { remoteTunnel = new Socket(SSH_HOST, SSH_PORT); } catch(Exception e) { } tried++; Thread.sleep(100); } //try it last time; if it doesn't work, this will throw an exception if(!remoteTunnel.isConnected()) remoteTunnel = new Socket(SSH_HOST, SSH_PORT); while(localSSH == null || !localSSH.isConnected()){ try { //try to connect as long till a connection is possible localSSH = new Socket("127.0.0.1", 33822); } catch (Exception e) { } Thread.sleep(100); } /* * Pump data from one to the other connection */ p0 = new StreamPumper(localSSH.getInputStream(), remoteTunnel.getOutputStream()); p1 = new StreamPumper(remoteTunnel.getInputStream(), localSSH.getOutputStream()); FutureTask<String> task0 = new FutureTask(p0); FutureTask<String> task1 = new FutureTask(p1); t1 = new Thread(task0); t0 = new Thread(task1); t0.start(); t1.start(); Log.i(LOGTAG, "!!!SSH Tunnel started!!!"); task1.get(); //This one is necessary, because it blocks till the ssh connection is over stopSSHServer(); stop(); }catch(Exception e) { e.printStackTrace(); stopSSHServer(); stop(); } } private void stopSSHServer() { try { rootProcess = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(rootProcess.getOutputStream()); os.writeBytes("am force-stop com.icecoldapps.sshserver\n"); os.writeBytes("exit\n"); os.flush(); Log.i(LOGTAG, "!!!SSH Tunnel stopped!!!"); } catch (IOException e) { e.printStackTrace(); } } private void stop() { try { remoteTunnel.close(); } catch (Exception e) {} try { localSSH.close(); } catch (Exception e) {} try { t0.stop(); } catch (Exception e) {} try { t1.stop(); } catch (Exception e) {} remoteTunnel = localSSH = null; t0 = t1 = null; p0 = p1 = null; } }, 1000, INTERVAL); return flags; } @Override public void onDestroy() { timer.cancel(); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; } }
package com.example.mikerah.cloverreader; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.mikerah.cloverreader.fourchan_api_wrapper.Board; import com.example.mikerah.cloverreader.fourchan_api_wrapper.Post; import com.example.mikerah.cloverreader.fourchan_api_wrapper.Thread; import org.w3c.dom.Text; import java.util.List; public class BoardFragment extends Fragment { private RecyclerView mRecyclerView; private Board mBoard; public static BoardFragment newBoardFragment(String boardName) { Bundle args = new Bundle(); args.putString("Board", boardName); BoardFragment fragment = new BoardFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); mBoard = Board.newBoard(getArguments().getString("Board")); new GetThreadsTask().execute(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_board,container,false); mRecyclerView = (RecyclerView) view.findViewById(R.id .fragment_threads_recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); return view; } private class ThreadHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private Thread mThread; private ImageView mThreadThumbnail; private TextView mThreadSubject; private TextView mThreadComment; public ThreadHolder(View threadView) { super(threadView); threadView.setOnClickListener(this); mThreadThumbnail = (ImageView) threadView.findViewById(R.id .post_img); mThreadSubject = (TextView) threadView.findViewById(R.id.post_subject); mThreadComment = (TextView) threadView.findViewById(R.id .post_comment); } public void bindThreadItem(Thread thread) { mThread = thread; Post topic = mThread.getTopic(); String threadSub = topic.getPostSubject(); String threadComment = topic.getPostComment(); mThreadSubject.setText(threadSub); mThreadComment.setText(threadComment); if(thread.getTopic().hasFile()) { String thumbnailUrl = thread.getTopic().getFile() .getFileUrl(); Glide.with(getActivity()).load(thumbnailUrl) .into(mThreadThumbnail); } } @Override public void onClick(View v) { Intent i = ThreadActivity.newIntent(getActivity(), mBoard, mThread); startActivity(i); } } private class ThreadAdapter extends RecyclerView.Adapter<ThreadHolder> { private List<Thread> mThreads; public ThreadAdapter(List<Thread> threads) { mThreads = threads; } @Override public ThreadHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(getActivity()); View view = inflater.inflate(R.layout.list_item_thread, parent, false); return new ThreadHolder(view); } @Override public void onBindViewHolder(ThreadHolder holder, int position) { Thread thread = mThreads.get(position); holder.bindThreadItem(thread); } @Override public int getItemCount() { return mThreads.size(); } } private class GetThreadsTask extends AsyncTask<Void,Void,List<Thread>> { @Override protected List<Thread> doInBackground(Void... params) { List<Thread> threads = mBoard.getAllThreads(); return threads; } @Override protected void onPostExecute(List<Thread> threads) { mRecyclerView.setAdapter(new ThreadAdapter(threads)); } } }
package ro.infoiasi.fiiadmis.db.dao; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.Lists; import org.apache.commons.lang.RandomStringUtils; import ro.infoiasi.fiiadmis.db.Table; import ro.infoiasi.fiiadmis.model.Entity; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.*; import java.util.List; import java.util.Scanner; public class EntityDAOImpl<E extends Entity> implements EntityDAO<E> { private final Table<E> table; private final Object toSync = new Object(); public EntityDAOImpl(Table<E> table) { this.table = table; } private E getSingleItem(Predicate<E> filter) throws IOException { try (BufferedReader reader = Files.newBufferedReader(table.getTablePath(), Charset.defaultCharset())) { String line = null; while ((line = reader.readLine()) != null) { if (line.isEmpty()) continue; // skipping empty lines E currentItem = table.getFormatter().read(line); if (filter.apply(currentItem)) { return currentItem; } } return null; // no items with this id was found } } private List<E> getMultipleItems(Predicate<E> filter) throws IOException { try (BufferedReader reader = Files.newBufferedReader(table.getTablePath(), Charset.defaultCharset())) { String line = null; final List<E> results = Lists.newArrayList(); while ((line = reader.readLine()) != null) { if (line.isEmpty()) continue; // skipping empty lines E currentItem = table.getFormatter().read(line); if (filter.apply(currentItem)) { results.add(currentItem); } } return results; } } @Override public String addItem(E item) throws IOException { String newId = RandomStringUtils.randomAlphanumeric(4); while (getItemById(newId) != null) { newId = RandomStringUtils.randomAlphanumeric(4); // ensuring that the id is unique } synchronized (toSync) { item.setId(newId); try (BufferedWriter writer = Files.newBufferedWriter(table.getTablePath(), Charset.defaultCharset(), StandardOpenOption.APPEND)) { writer.write(table.getFormatter().write(item)); writer.write(System.lineSeparator()); } return newId; } } @Override public E getItemById(final String entityId) throws IOException { Preconditions.checkArgument(entityId != null, "id must not be null"); return getSingleItem(new Predicate<E>() { @Override public boolean apply(E input) { return entityId.equals(input.getId()); } }); } @Override public List<E> getItems(Predicate<E> filter) throws IOException { Preconditions.checkArgument(filter != null, "Filter must not be null"); return getMultipleItems(filter); } @Override public void updateItem(E item) throws IOException { Preconditions.checkArgument(item != null, "The input must not be null"); synchronized (toSync) { Path tmpPath = Paths.get(table.getTablePath().toString() + ".tmp"); Scanner s = new Scanner(table.getTablePath()); try (BufferedWriter writer = Files.newBufferedWriter(tmpPath, Charset.defaultCharset())) { while (s.hasNextLine()) { String line = s.nextLine(); if (line.isEmpty()) continue; // skipping empty lines E currentE = table.getFormatter().read(line); if (item.getId().equals(currentE.getId())) { writer.write(table.getFormatter().write(item)); writer.write(System.lineSeparator()); } else { writer.write(line); writer.write(System.lineSeparator()); } } s.close(); } Files.move(tmpPath, table.getTablePath(), StandardCopyOption.REPLACE_EXISTING); } } @Override public void deleteItem(String entityId) throws IOException { Preconditions.checkArgument(entityId != null, "id must be null"); synchronized (toSync) { Path tmpPath = Paths.get(table.getTablePath().toString() + ".tmp"); Scanner s = new Scanner(table.getTablePath()); try (BufferedWriter writer = Files.newBufferedWriter(tmpPath, Charset.defaultCharset())) { while (s.hasNextLine()) { String line = s.nextLine(); if (line.isEmpty()) continue; // skipping empty lines E currentE = table.getFormatter().read(line); if (!entityId.equals(currentE.getId())) { writer.write(line); writer.write(System.lineSeparator()); } } s.close(); } Files.move(tmpPath, table.getTablePath(), StandardCopyOption.REPLACE_EXISTING); } } }
package owltools.gaf.lego; import static org.junit.Assert.*; import java.io.File; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.junit.Test; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLNamedIndividual; import owltools.gaf.lego.MolecularModelManager.OWLOperationResponse; import owltools.io.ParserWrapper; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class MolecularModelManagerTest extends AbstractLegoModelGeneratorTest { private static Logger LOG = Logger.getLogger(MolecularModelManagerTest.class); MolecularModelManager mmm; static{ Logger.getLogger("org.semanticweb.elk").setLevel(Level.ERROR); //Logger.getLogger(MinimalModelGenerator.class).setLevel(Level.ERROR); //Logger.getLogger(LegoModelGenerator.class).setLevel(Level.ERROR); //Logger.getLogger("org.semanticweb.elk.reasoner.indexing.hierarchy").setLevel(Level.ERROR); } @Test public void testM3() throws Exception { ParserWrapper pw = new ParserWrapper(); //w = new FileWriter(new File("target/lego.out")); g = pw.parseToOWLGraph(getResourceIRIString("go-mgi-signaling-test.obo")); g.mergeOntology(pw.parseOBO(getResourceIRIString("disease.obo"))); mmm = new MolecularModelManager(g); File gafPath = getResource("mgi-signaling.gaf"); mmm.loadGaf("mgi", gafPath); OWLClass p = g.getOWLClassByIdentifier("GO:0014029"); // neural crest formation String modelId = mmm.generateModel(p, "mgi"); LOG.info("Model: "+modelId); LegoModelGenerator model = mmm.getModel(modelId); Set<OWLNamedIndividual> inds = mmm.getIndividuals(modelId); LOG.info("Individuals: "+inds.size()); for (OWLNamedIndividual i : inds) { LOG.info("I="+i); } assertEquals(17, inds.size()); // TODO checkme // GO:0001158 ! enhancer sequence-specific DNA binding OWLOperationResponse response = mmm.createIndividual(modelId, g.getOWLClassByIdentifier("GO:0001158")); String bindingId = MolecularModelJsonRenderer.getId(response.getIndividuals().get(0), g); LOG.info("New: "+bindingId); // GO:0005654 ! nucleoplasm mmm.addOccursIn(modelId, bindingId, "GO:0005654"); mmm.addEnabledBy(modelId, bindingId, "PR:P123456"); // todo - add a test that results in an inconsistency List<Map<Object, Object>> objs = mmm.getIndividualObjects(modelId); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String js = gson.toJson(objs); LOG.info("INDS:" + js); // LOG.info(mmm.generateDot(modelId)); // LOG.info(mmm.generateImage(modelId)); // problematic due to missing dot application String q = "'molecular_function'"; inds = mmm.getIndividualsByQuery(modelId, q); LOG.info(q + " #inds = "+inds.size()); assertEquals(5, inds.size()); q = "'part_of' some 'neural crest formation'"; inds = mmm.getIndividualsByQuery(modelId, q); LOG.info(q + " #inds = "+inds.size()); assertEquals(6, inds.size()); } /** * The purpose of this test is to ensure that different models are properly insulated from each other. * * @throws Exception */ @Test public void testSeedingMultipleModels() throws Exception { ParserWrapper pw = new ParserWrapper(); g = pw.parseToOWLGraph(getResourceIRIString("go-mgi-signaling-test.obo")); mmm = new MolecularModelManager(g); //File gafPath = getResource("mgi-signaling.gaf"); ///mmm.loadGaf("mgi", gafPath); mmm.setPathToGafs(getResource("gene-associations").toString()); OWLClass p = g.getOWLClassByIdentifier("GO:0014029"); // neural crest formation String model1Id = mmm.generateModel(p, "mgi"); LOG.info("Model: "+model1Id); LegoModelGenerator model1 = mmm.getModel(model1Id); assertNotNull(model1); Set<OWLNamedIndividual> inds = mmm.getIndividuals(model1Id); LOG.info("Individuals: "+inds.size()); for (OWLNamedIndividual i : inds) { LOG.info("I="+i); } assertEquals(17, inds.size()); String model2Id = mmm.generateModel(p, "fake"); LOG.info("Model: "+model2Id); LegoModelGenerator model2 = mmm.getModel(model2Id); assertNotNull(model2); Set<OWLNamedIndividual> inds2 = mmm.getIndividuals(model2Id); LOG.info("Individuals: "+inds2.size()); for (OWLNamedIndividual i : inds2) { LOG.info("I="+i); } assertEquals(17, inds2.size()); for (OWLNamedIndividual i : inds) { assertFalse(inds2.contains(i)); } for (OWLNamedIndividual i : inds2) { assertFalse(inds.contains(i)); } // // GO:0001158 ! enhancer sequence-specific DNA binding // OWLOperationResponse response = mmm.createIndividual(model1Id, g.getOWLClassByIdentifier("GO:0001158")); // String bindingId = response.getIndividualIds().get(0); // LOG.info("New: "+bindingId); // // GO:0005654 ! nucleoplasm // mmm.addOccursIn(model1Id, bindingId, "GO:0005654"); // mmm.addEnabledBy(model1Id, bindingId, "PR:P123456"); // // todo - add a test that results in an inconsistency String js = renderJSON(model1Id); LOG.info("INDS:" + js); } private String renderJSON(String modelId) { List<Map<Object, Object>> objs = mmm.getIndividualObjects(modelId); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String js = gson.toJson(objs); return js; } @Test public void testDeleteIndividual() throws Exception { ParserWrapper pw = new ParserWrapper(); g = pw.parseToOWLGraph(getResourceIRIString("go-mgi-signaling-test.obo")); // GO:0038024 ! cargo receptor activity // GO:0042803 ! protein homodimerization activity mmm = new MolecularModelManager(g); String modelId = mmm.generateBlankModel(null); OWLOperationResponse resp = mmm.createIndividual(modelId, "GO:0038024"); OWLNamedIndividual i1 = resp.getIndividuals().get(0); resp = mmm.createIndividual(modelId, "GO:0042803"); OWLNamedIndividual i2 = resp.getIndividuals().get(0); mmm.addPartOf(modelId, i1, i2); // String js = renderJSON(modelId); // System.out.println("INDS:" + js); mmm.deleteIndividual(modelId, i2); // js = renderJSON(modelId); // System.out.println("INDS:" + js); Set<OWLNamedIndividual> individuals = mmm.getIndividuals(modelId); assertEquals(1, individuals.size()); } @Test public void testInferredType() throws Exception { ParserWrapper pw = new ParserWrapper(); g = pw.parseToOWLGraph(getResourceIRIString("go-mgi-signaling-test.obo")); // GO:0038024 ! cargo receptor activity // GO:0042803 ! protein homodimerization activity mmm = new MolecularModelManager(g); String modelId = mmm.generateBlankModel(null); OWLOperationResponse resp = mmm.createIndividual(modelId, "GO:0004872"); // receptor activity OWLNamedIndividual cc = resp.getIndividuals().get(0); resp = mmm.createIndividual(modelId, "GO:0007166"); // cell surface receptor signaling pathway OWLNamedIndividual mit = resp.getIndividuals().get(0); mmm.addPartOf(modelId, mit, cc); // we expect inference to be to: GO:0038023 signaling receptor activity System.out.println(renderJSON(modelId)); //List<Map<Object, Object>> gson = mmm.getIndividualObjects(modelId); //assertEquals(1, individuals.size()); } }
package com.javarush.task.task25.task2515; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; public class Space { private int width; private int height; private SpaceShip ship; private ArrayList<Ufo> ufos = new ArrayList<Ufo>(); private ArrayList<Bomb> bombs = new ArrayList<Bomb>(); private ArrayList<Rocket> rockets = new ArrayList<Rocket>(); public Space(int width, int height) { this.width = width; this.height = height; } public void run() { Canvas canvas = new Canvas(width, height); KeyboardObserver keyboardObserver = new KeyboardObserver(); keyboardObserver.start(); while (ship.isAlive()) { if (keyboardObserver.hasKeyEvents()) { KeyEvent event = keyboardObserver.getEventFromTop(); System.out.print(event.getKeyCode()); if (event.getKeyCode() == KeyEvent.VK_LEFT) ship.moveLeft(); else if (event.getKeyCode() == KeyEvent.VK_RIGHT) ship.moveRight(); else if (event.getKeyCode() == KeyEvent.VK_SPACE) ship.fire(); } moveAllItems(); checkBombs(); checkRockets(); removeDead(); createUfo(); canvas.clear(); draw(canvas); canvas.print(); Space.sleep(300); } System.out.println("Game Over!"); } public void moveAllItems() { for (BaseObject object : getAllItems()) { object.move(); } } public List<BaseObject> getAllItems() { ArrayList<BaseObject> list = new ArrayList<BaseObject>(ufos); list.add(ship); list.addAll(bombs); list.addAll(rockets); return list; } public void createUfo() { if (ufos.size() > 0) return; int random10 = (int) (Math.random() * 10); if (random10 == 0) { double x = Math.random() * width; double y = Math.random() * height / 2; ufos.add(new Ufo(x, y)); } } public void checkBombs() { for (Bomb bomb : bombs) { if (ship.isIntersect(bomb)) { ship.die(); bomb.die(); } if (bomb.getY() >= height) bomb.die(); } } public void checkRockets() { for (Rocket rocket : rockets) { for (Ufo ufo : ufos) { if (ufo.isIntersect(rocket)) { ufo.die(); rocket.die(); } } if (rocket.getY() <= 0) rocket.die(); } } public void removeDead() { for (BaseObject object : new ArrayList<BaseObject>(bombs)) { if (!object.isAlive()) bombs.remove(object); } for (BaseObject object : new ArrayList<BaseObject>(rockets)) { if (!object.isAlive()) rockets.remove(object); } for (BaseObject object : new ArrayList<BaseObject>(ufos)) { if (!object.isAlive()) ufos.remove(object); } } public void draw(Canvas canvas) { //draw game for (int i = 0; i < width + 2; i++) { for (int j = 0; j < height + 2; j++) { canvas.setPoint(i, j, '.'); } } for (int i = 0; i < width + 2; i++) { canvas.setPoint(i, 0, '-'); canvas.setPoint(i, height + 1, '-'); } for (int i = 0; i < height + 2; i++) { canvas.setPoint(0, i, '|'); canvas.setPoint(width + 1, i, '|'); } for (BaseObject object : getAllItems()) { object.draw(canvas); } } public SpaceShip getShip() { return ship; } public void setShip(SpaceShip ship) { this.ship = ship; } public ArrayList<Ufo> getUfos() { return ufos; } public int getWidth() { return width; } public int getHeight() { return height; } public ArrayList<Bomb> getBombs() { return bombs; } public ArrayList<Rocket> getRockets() { return rockets; } public static Space game; public static void main(String[] args) throws Exception { game = new Space(25, 25); game.setShip(new SpaceShip(10, 18)); game.run(); } public static void sleep(int delay) { try { Thread.sleep(delay); } catch (InterruptedException e) { } } }
package com.facebook.react.modules.core; import com.facebook.react.bridge.UiThreadUtil; import java.util.ArrayDeque; import javax.annotation.Nullable; import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.react.common.ReactConstants; /** * A simple wrapper around Choreographer that allows us to control the order certain callbacks * are executed within a given frame. The main difference is that we enforce this is accessed from * the UI thread: this is because this ordering cannot be guaranteed across multiple threads. */ public class ReactChoreographer { public enum CallbackType { /** * For use by perf markers that need to happen immediately after draw */ PERF_MARKERS(0), /** * For use by {@link com.facebook.react.uimanager.UIManagerModule} */ DISPATCH_UI(1), /** * For use by {@link com.facebook.react.animated.NativeAnimatedModule} */ NATIVE_ANIMATED_MODULE(2), /** * Events that make JS do things. */ TIMERS_EVENTS(3), /** * Event used to trigger the idle callback. Called after all UI work has been * dispatched to JS. */ IDLE_EVENT(4), ; private final int mOrder; private CallbackType(int order) { mOrder = order; } /*package*/ int getOrder() { return mOrder; } } private static ReactChoreographer sInstance; public static void initialize() { if (sInstance == null) { sInstance = new ReactChoreographer(); } } public static ReactChoreographer getInstance() { Assertions.assertNotNull(sInstance, "ReactChoreographer needs to be initialized."); return sInstance; } private @Nullable volatile ChoreographerCompat mChoreographer; private final ReactChoreographerDispatcher mReactChoreographerDispatcher; private final ArrayDeque<ChoreographerCompat.FrameCallback>[] mCallbackQueues; private int mTotalCallbacks = 0; private boolean mHasPostedCallback = false; private ReactChoreographer() { mReactChoreographerDispatcher = new ReactChoreographerDispatcher(); mCallbackQueues = new ArrayDeque[CallbackType.values().length]; for (int i = 0; i < mCallbackQueues.length; i++) { mCallbackQueues[i] = new ArrayDeque<>(); } initializeChoreographer(null); } public synchronized void postFrameCallback( CallbackType type, ChoreographerCompat.FrameCallback frameCallback) { mCallbackQueues[type.getOrder()].addLast(frameCallback); mTotalCallbacks++; Assertions.assertCondition(mTotalCallbacks > 0); if (!mHasPostedCallback) { if (mChoreographer == null) { initializeChoreographer(new Runnable(){ @Override public void run() { postFrameCallbackOnChoreographer(); } }); } else { postFrameCallbackOnChoreographer(); } } } public void postFrameCallbackOnChoreographer() { mChoreographer.postFrameCallback(mReactChoreographerDispatcher); mHasPostedCallback = true; } public void initializeChoreographer(@Nullable final Runnable runnable) { UiThreadUtil.runOnUiThread(new Runnable() { @Override public void run() { synchronized (ReactChoreographer.class) { if (mChoreographer == null) { mChoreographer = ChoreographerCompat.getInstance(); } } if (runnable != null) { runnable.run(); } } }); } public synchronized void removeFrameCallback( CallbackType type, ChoreographerCompat.FrameCallback frameCallback) { synchronized (ReactChoreographer.this) { if (mCallbackQueues[type.getOrder()].removeFirstOccurrence(frameCallback)) { mTotalCallbacks maybeRemoveFrameCallback(); } else { FLog.e(ReactConstants.TAG, "Tried to remove non-existent frame callback"); } } } private void maybeRemoveFrameCallback() { Assertions.assertCondition(mTotalCallbacks >= 0); if (mTotalCallbacks == 0 && mHasPostedCallback) { if (mChoreographer != null) { mChoreographer.removeFrameCallback(mReactChoreographerDispatcher); } mHasPostedCallback = false; } } private class ReactChoreographerDispatcher extends ChoreographerCompat.FrameCallback { @Override public void doFrame(long frameTimeNanos) { synchronized (ReactChoreographer.this) { mHasPostedCallback = false; for (int i = 0; i < mCallbackQueues.length; i++) { int initialLength = mCallbackQueues[i].size(); for (int callback = 0; callback < initialLength; callback++) { mCallbackQueues[i].removeFirst().doFrame(frameTimeNanos); mTotalCallbacks } } maybeRemoveFrameCallback(); } } } }
package edu.wustl.catissuecore.util.querysuite; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import edu.common.dynamicextensions.domaininterface.EntityInterface; import edu.wustl.catissuecore.applet.AppletConstants; import edu.wustl.catissuecore.bizlogic.querysuite.DefineGridViewBizLogic; import edu.wustl.catissuecore.bizlogic.querysuite.QueryOutputSpreadsheetBizLogic; import edu.wustl.catissuecore.bizlogic.querysuite.QueryOutputTreeBizLogic; import edu.wustl.catissuecore.querysuite.CatissueSqlGenerator; import edu.wustl.catissuecore.querysuite.QueryShoppingCart; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Variables; import edu.wustl.common.beans.QueryResultObjectDataBean; import edu.wustl.common.bizlogic.QueryBizLogic; import edu.wustl.common.dao.QuerySessionData; import edu.wustl.common.exception.BizLogicException; import edu.wustl.common.factory.AbstractBizLogicFactory; import edu.wustl.common.querysuite.exceptions.MultipleRootsException; import edu.wustl.common.querysuite.exceptions.SqlException; import edu.wustl.common.querysuite.factory.SqlGeneratorFactory; import edu.wustl.common.querysuite.queryengine.impl.SqlGenerator; import edu.wustl.common.querysuite.queryobject.IConstraints; import edu.wustl.common.querysuite.queryobject.IExpression; import edu.wustl.common.querysuite.queryobject.IOutputAttribute; import edu.wustl.common.querysuite.queryobject.IOutputTerm; import edu.wustl.common.querysuite.queryobject.IQuery; import edu.wustl.common.querysuite.queryobject.impl.OutputTreeDataNode; import edu.wustl.common.querysuite.queryobject.impl.ParameterizedQuery; import edu.wustl.common.querysuite.queryobject.impl.metadata.QueryOutputTreeAttributeMetadata; import edu.wustl.common.querysuite.queryobject.impl.metadata.SelectedColumnsMetadata; import edu.wustl.common.querysuite.queryobject.util.QueryObjectProcessor; import edu.wustl.common.tree.QueryTreeNodeData; import edu.wustl.common.util.XMLPropertyHandler; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.global.ApplicationProperties; /** * @author santhoshkumar_c * */ public class QueryModuleSearchQueryUtil { private HttpServletRequest request; private HttpSession session; private IQuery query; boolean isSavedQuery; QueryDetails queryDetailsObj; /** * @param request * @param query */ public QueryModuleSearchQueryUtil(HttpServletRequest request, IQuery query) { this.request = request; this.session = request.getSession(); this.query = query; isSavedQuery = Boolean.valueOf( (String) session.getAttribute(Constants.IS_SAVED_QUERY)); queryDetailsObj = new QueryDetails(session); } /** * This method extracts query object and forms results for tree and grid. * @param option * @return status */ public QueryModuleError searchQuery(String option) { session.removeAttribute(Constants.HYPERLINK_COLUMN_MAP); QueryModuleError status = QueryModuleError.SUCCESS; try { session.setAttribute(AppletConstants.QUERY_OBJECT, query); if(isSavedQuery) { processSaveQuery(); } if (queryDetailsObj.getSessionData() != null) { QueryOutputTreeBizLogic outputTreeBizLogic = auditQuery(); boolean hasCondOnIdentifiedField = edu.wustl.common.querysuite .security.utility.Utility.isConditionOnIdentifiedField(query); setDataInSession(option, outputTreeBizLogic, hasCondOnIdentifiedField); } } catch (QueryModuleException e) { status= e.getKey(); } return status; } /** * @param option * @param outputTreeBizLogic * @param hasCondOnIdentifiedField * @throws QueryModuleException */ private void setDataInSession(String option, QueryOutputTreeBizLogic outputTreeBizLogic, boolean hasCondOnIdentifiedField) throws QueryModuleException { int initialValue = 0; QueryModuleException queryModExp; try { for (OutputTreeDataNode outnode : queryDetailsObj.getRootOutputTreeNodeList()) { List<QueryTreeNodeData> treeData= null; treeData = outputTreeBizLogic.createDefaultOutputTreeData(initialValue, outnode, hasCondOnIdentifiedField, queryDetailsObj); initialValue = setTreeData(option, initialValue, treeData); } } catch (DAOException e) { queryModExp = new QueryModuleException(e.getMessage(), QueryModuleError.DAO_EXCEPTION); throw queryModExp; } catch (ClassNotFoundException e) { queryModExp = new QueryModuleException(e.getMessage(),QueryModuleError.CLASS_NOT_FOUND); throw queryModExp; } session.setAttribute(Constants.TREE_ROOTS, queryDetailsObj.getRootOutputTreeNodeList()); Long noOfTrees = Long.valueOf(queryDetailsObj.getRootOutputTreeNodeList().size()); session.setAttribute(Constants.NO_OF_TREES, noOfTrees); OutputTreeDataNode node = queryDetailsObj.getRootOutputTreeNodeList().get(0); processRecords(queryDetailsObj, node, hasCondOnIdentifiedField); } /** * @param option * @param initialValue * @param treeData * @return int * @throws QueryModuleException */ private int setTreeData(String option, int initialValue, List<QueryTreeNodeData> treeData) throws QueryModuleException { int resultsSize = treeData.size(); if(option == null) { if (resultsSize == 0) { throw new QueryModuleException("Query Returns Zero Results", QueryModuleError.NO_RESULT_PRESENT); } else if(resultsSize-1 > Variables.maximumTreeNodeLimit) { String resultSizeStr = String.valueOf(resultsSize-1); session.setAttribute(Constants.TREE_NODE_LIMIT_EXCEEDED_RECORDS, resultSizeStr); throw new QueryModuleException("Query Results Exceeded The Limit", QueryModuleError.RESULTS_MORE_THAN_LIMIT); } } else if(Constants.VIEW_LIMITED_RECORDS.equals(option)) { treeData = setLimitedTreeDataInSession(treeData .subList(0, Variables.maximumTreeNodeLimit+1)); } session.setAttribute(Constants.TREE_DATA + Constants.UNDERSCORE + initialValue, treeData); initialValue += 1; return initialValue; } /** * @return * @throws QueryModuleException */ private QueryOutputTreeBizLogic auditQuery() throws QueryModuleException { QueryBizLogic queryBizLogic = null; QueryModuleException queryModExp; QueryOutputTreeBizLogic outputTreeBizLogic = new QueryOutputTreeBizLogic(); try { queryBizLogic = (QueryBizLogic)AbstractBizLogicFactory.getBizLogic( ApplicationProperties.getValue("app.bizLogicFactory"), "getBizLogic", Constants.QUERY_INTERFACE_ID); String selectSql = (String)session.getAttribute(Constants.SAVE_GENERATED_SQL); queryBizLogic.insertQuery(selectSql, queryDetailsObj.getSessionData()); outputTreeBizLogic.createOutputTreeTable(selectSql, queryDetailsObj); } catch (BizLogicException e) { queryModExp = new QueryModuleException(e.getMessage(), QueryModuleError.DAO_EXCEPTION); throw queryModExp; } catch (ClassNotFoundException e) { queryModExp = new QueryModuleException(e.getMessage(), QueryModuleError.CLASS_NOT_FOUND); throw queryModExp; } catch (DAOException e) { queryModExp = new QueryModuleException(e.getMessage(), QueryModuleError.DAO_EXCEPTION); throw queryModExp; } return outputTreeBizLogic; } /** * @throws QueryModuleException */ private void processSaveQuery() throws QueryModuleException { SqlGenerator sqlGenerator = new CatissueSqlGenerator(); QueryModuleException queryModExp; try { session.setAttribute(Constants.SAVE_GENERATED_SQL, sqlGenerator.generateSQL(query)); session.setAttribute(Constants.OUTPUT_TERMS_COLUMNS,sqlGenerator.getOutputTermsColumns()); } catch(MultipleRootsException e) { queryModExp = new QueryModuleException(e.getMessage(), QueryModuleError.MULTIPLE_ROOT); throw queryModExp; } catch(SqlException e) { queryModExp = new QueryModuleException(e.getMessage(), QueryModuleError.SQL_EXCEPTION); throw queryModExp; } List<OutputTreeDataNode> rootOutputTreeNodeList = sqlGenerator.getRootOutputTreeNodeList(); session.setAttribute(Constants.SAVE_TREE_NODE_LIST, rootOutputTreeNodeList); queryDetailsObj.setRootOutputTreeNodeList(rootOutputTreeNodeList); Map<String, OutputTreeDataNode> uniqueIdNodesMap = QueryObjectProcessor .getAllChildrenNodes(rootOutputTreeNodeList); queryDetailsObj.setUniqueIdNodesMap(uniqueIdNodesMap); session.setAttribute(Constants.ID_NODES_MAP, uniqueIdNodesMap); Map<EntityInterface, List<EntityInterface>> mainEntityMap = QueryCSMUtil .setMainObjectErrorMessage(query, request.getSession(), queryDetailsObj); queryDetailsObj.setMainEntityMap(mainEntityMap); } /** * @param QueryDetailsObj * @param node * @param hasCondOnIdentifiedField * @throws QueryModuleException */ public void processRecords(QueryDetails QueryDetailsObj, OutputTreeDataNode node, boolean hasCondOnIdentifiedField) throws QueryModuleException { SelectedColumnsMetadata selectedColumnsMetadata = getAppropriateSelectedColumnMetadata(query, (SelectedColumnsMetadata) session.getAttribute(Constants.SELECTED_COLUMN_META_DATA)); selectedColumnsMetadata.setCurrentSelectedObject(node); QueryModuleException queryModExp; int recordsPerPage = setRecordsPerPage(); if(query.getId() != null && isSavedQuery ) { getSelectedColumnsMetadata(QueryDetailsObj, selectedColumnsMetadata); } QueryResultObjectDataBean queryResulObjectDataBean = QueryCSMUtil .getQueryResulObjectDataBean(node, QueryDetailsObj); Map<Long,QueryResultObjectDataBean> queryResultObjDataBeanMap = new HashMap<Long, QueryResultObjectDataBean>(); queryResultObjDataBeanMap.put(node.getId(), queryResulObjectDataBean); QueryOutputSpreadsheetBizLogic outputSpreadsheetBizLogic = new QueryOutputSpreadsheetBizLogic(); try { // deepti change SqlGenerator sqlGenerator = (SqlGenerator) SqlGeneratorFactory.getInstance(); Map<String, IOutputTerm> outputTermsColumns = sqlGenerator.getOutputTermsColumns(); if(outputTermsColumns == null) { outputTermsColumns = (Map<String, IOutputTerm>)session.getAttribute(Constants .OUTPUT_TERMS_COLUMNS); } session.setAttribute(Constants.OUTPUT_TERMS_COLUMNS, outputTermsColumns); Map<String, List<String>> spreadSheetDatamap = outputSpreadsheetBizLogic .createSpreadsheetData(Constants.TREENO_ZERO, node, QueryDetailsObj, null, recordsPerPage, selectedColumnsMetadata, queryResultObjDataBeanMap, hasCondOnIdentifiedField, query.getConstraints(), outputTermsColumns); setQuerySessionData(selectedColumnsMetadata, spreadSheetDatamap); } catch(DAOException e) { queryModExp = new QueryModuleException(e.getMessage(), QueryModuleError.DAO_EXCEPTION); throw queryModExp; } catch (ClassNotFoundException e) { queryModExp = new QueryModuleException(e.getMessage(), QueryModuleError.CLASS_NOT_FOUND); throw queryModExp; } } /** * @param query * @param selectedColumnsMetadata * @return */ private static SelectedColumnsMetadata getAppropriateSelectedColumnMetadata(IQuery query, SelectedColumnsMetadata selectedColumnsMetadata) { boolean isQueryChanged = false; if(query != null && selectedColumnsMetadata != null) { List<Integer> expressionIdsInQuery = new ArrayList<Integer>(); IConstraints constraints = query.getConstraints(); List<QueryOutputTreeAttributeMetadata> selAttributeMetaDataList = selectedColumnsMetadata .getSelectedAttributeMetaDataList(); for(IExpression expression : constraints) { if (expression.isInView()) { expressionIdsInQuery.add(Integer.valueOf(expression.getExpressionId())); } } int expressionId; for(QueryOutputTreeAttributeMetadata element :selAttributeMetaDataList) { expressionId = element.getTreeDataNode().getExpressionId(); if(!expressionIdsInQuery.contains(Integer.valueOf(expressionId))) { isQueryChanged = true; break; } } } if(isQueryChanged || selectedColumnsMetadata == null) { selectedColumnsMetadata = new SelectedColumnsMetadata(); selectedColumnsMetadata.setDefinedView(false); } return selectedColumnsMetadata; } /** It will set the results per page. * @return int */ private int setRecordsPerPage() { int recordsPerPage; String recordsPerPgSessionValue = (String) session.getAttribute(Constants.RESULTS_PER_PAGE); if (recordsPerPgSessionValue == null) { recordsPerPgSessionValue = XMLPropertyHandler .getValue(Constants.RECORDS_PER_PAGE_PROPERTY_NAME); session.setAttribute(Constants.RESULTS_PER_PAGE, recordsPerPgSessionValue); } recordsPerPage = Integer.valueOf(recordsPerPgSessionValue); return recordsPerPage; } /** * Set the data in session. * @param selectedColumnsMetadata * @param spreadSheetDatamap */ public void setQuerySessionData(SelectedColumnsMetadata selectedColumnsMetadata, Map<String, List<String>> spreadSheetDatamap) { QuerySessionData querySessionData = (QuerySessionData) spreadSheetDatamap .get(Constants.QUERY_SESSION_DATA); int totalNoOfRecords = querySessionData.getTotalNumberOfRecords(); session.setAttribute(Constants.QUERY_SESSION_DATA, querySessionData); session.setAttribute(Constants.TOTAL_RESULTS, Integer.valueOf(totalNoOfRecords)); QueryShoppingCart cart = (QueryShoppingCart)session.getAttribute(Constants.QUERY_SHOPPING_CART); String message = QueryModuleUtil.getMessageIfIdNotPresentForOrderableEntities( selectedColumnsMetadata, cart); session.setAttribute(Constants.VALIDATION_MESSAGE_FOR_ORDERING, message); session.setAttribute(Constants.PAGINATION_DATA_LIST, spreadSheetDatamap .get(Constants.SPREADSHEET_DATA_LIST)); session.setAttribute(Constants.SPREADSHEET_COLUMN_LIST, spreadSheetDatamap .get(Constants.SPREADSHEET_COLUMN_LIST)); session.setAttribute(Constants.SELECTED_COLUMN_META_DATA, spreadSheetDatamap .get(Constants.SELECTED_COLUMN_META_DATA)); session.setAttribute(Constants.QUERY_REASUL_OBJECT_DATA_MAP, spreadSheetDatamap .get(Constants.QUERY_REASUL_OBJECT_DATA_MAP)); session.setAttribute(Constants.DEFINE_VIEW_QUERY_REASULT_OBJECT_DATA_MAP, spreadSheetDatamap .get(Constants.DEFINE_VIEW_QUERY_REASULT_OBJECT_DATA_MAP)); } /** * @param QueryDetailsObj * @param selectedColumnsMetadata */ public void getSelectedColumnsMetadata(QueryDetails QueryDetailsObj, SelectedColumnsMetadata selectedColumnsMetadata) { List<IOutputAttribute> selAttributeList; if (query instanceof ParameterizedQuery) { ParameterizedQuery savedQuery = (ParameterizedQuery) query; selAttributeList = savedQuery.getOutputAttributeList(); if(!selAttributeList.isEmpty()) { DefineGridViewBizLogic gridViewBizLogic = new DefineGridViewBizLogic(); selectedColumnsMetadata.setSelectedOutputAttributeList(selAttributeList); gridViewBizLogic.getSelectedColumnMetadataForSavedQuery(QueryDetailsObj .getUniqueIdNodesMap().values(), selAttributeList, selectedColumnsMetadata); selectedColumnsMetadata.setDefinedView(true); } } } /** * This will set the limited tree data in session. * @param limitedRecordsList * @return */ public List<QueryTreeNodeData> setLimitedTreeDataInSession(List<QueryTreeNodeData> limitedRecordsList) { ArrayList<QueryTreeNodeData> limitedTreeData = new ArrayList<QueryTreeNodeData>(); limitedTreeData.addAll(limitedRecordsList); return limitedTreeData; } }
package com.jwetherell.algorithms.data_structures; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; public abstract class SegmentTree<D extends SegmentTree.Data> { protected Segment<D> root = null; /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(SegmentTreePrinter.getString(this)); return builder.toString(); } public abstract static class Data { public abstract Data combined(Data q); public abstract Data copy(); public abstract Data query(); public abstract Data update(Data q); } public abstract static class Segment<D extends Data> implements Comparable<Segment<D>> { protected Segment<D>[] segments = null; protected int length = 0; protected int half = 0; protected long start = 0; protected long end = 0; protected D data = null; protected boolean hasChildren() { return (segments!=null); } protected Segment<D> getLeftChild() { return segments[0]; } protected Segment<D> getRightChild() { return segments[1]; } } protected static class SegmentTreePrinter { public static <D extends SegmentTree.Data> String getString(SegmentTree<D> tree) { if (tree.root == null) return "Tree has no nodes."; return getString(tree.root, "", true); } private static <D extends SegmentTree.Data> String getString(Segment<D> segment, String prefix, boolean isTail) { StringBuilder builder = new StringBuilder(); builder.append( prefix + (isTail ? " " : " ") + "start=" + segment.start + " end=" + segment.end + " length=" + segment.length + " data=" + segment.data + "\n" ); List<Segment<D>> children = new ArrayList<Segment<D>>(); if (segment.segments!=null) { for (Segment<D> c : segment.segments) children.add(c); } if (children != null) { for (int i = 0; i < children.size() - 1; i++) { builder.append(getString(children.get(i), prefix + (isTail ? " " : " "), false)); } if (children.size() > 1) { builder.append(getString(children.get(children.size() - 1), prefix + (isTail ? " " : " "), true)); } } return builder.toString(); } } /** * Flat segment tree is a variant of segment tree that is designed to store a collection of non-overlapping * segments. This structure is efficient when you need to store values associated with 1 dimensional segments * that never overlap with each other. The end points of stored segments are inclusive, that is, when a * segment spans from 2 to 6, an arbitrary point x within that segment can take a value of 2 <= x <= 6. */ public static final class FlatSegmentTree<D extends FlatSegmentTree.NonOverlappingData> extends SegmentTree<D> { public FlatSegmentTree(List<NonOverlappingSegment<D>> segments) { if (segments.size()<=0) throw new InvalidParameterException("Segments list is empty."); Collections.sort(segments); //Make sure they are sorted //Make sure they don't overlap if (segments.size()>=2) { for (int i=0; i<(segments.size()-2); i++) { NonOverlappingSegment<D> s1 = segments.get(i); NonOverlappingSegment<D> s2 = segments.get(i+1); if (s1.end>s2.start) throw new InvalidParameterException("Segments are overlapping."); } } root = NonOverlappingSegment.createFromList(segments); } public void update(long index, D data) { ((NonOverlappingSegment<D>)root).update(index, data); } /** * Stabbing query */ public D query(long index) { return this.query(index, index); } /** * Range query */ public D query(long start, long end) { if (root==null) return null; if (start<root.start) start = root.start; if (end>root.end) end = root.end; return (D)((NonOverlappingSegment<D>)root).query(start, end); } public abstract static class NonOverlappingData extends Data { public static final class QuadrantData extends NonOverlappingData { public long quad1 = 0; public long quad2 = 0; public long quad3 = 0; public long quad4 = 0; public QuadrantData() { } public QuadrantData(long quad1, long quad2, long quad3, long quad4) { this.quad1 = quad1; this.quad2 = quad2; this.quad3 = quad3; this.quad4 = quad4; } @Override public Data combined(Data data) { QuadrantData q = null; if (data instanceof QuadrantData) { q = (QuadrantData) data; this.combined(q); } return this; } private void combined(QuadrantData q) { this.quad1 += q.quad1; this.quad2 += q.quad2; this.quad3 += q.quad3; this.quad4 += q.quad4; } @Override public QuadrantData copy() { QuadrantData copy = new QuadrantData(); copy.quad1 = this.quad1; copy.quad2 = this.quad2; copy.quad3 = this.quad3; copy.quad4 = this.quad4; return copy; } @Override public Data query() { return copy(); } @Override public Data update(Data data) { QuadrantData q = null; if (data instanceof QuadrantData) { q = (QuadrantData) data; this.update(q); } return this; } private void update(QuadrantData q) { this.quad1 = q.quad1; this.quad2 = q.quad2; this.quad3 = q.quad3; this.quad4 = q.quad4; } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(quad1).append(","); builder.append(quad2).append(","); builder.append(quad3).append(","); builder.append(quad4); return builder.toString(); } } public static final class RangeMaximumData<N extends Number> extends NonOverlappingData { public N maximum = null; public RangeMaximumData(N number) { this.maximum = number; } @SuppressWarnings("unchecked") @Override public Data combined(Data data) { RangeMaximumData<N> q = null; if (data instanceof RangeMaximumData) { q = (RangeMaximumData<N>) data; this.combined(q); } return this; } private void combined(RangeMaximumData<N> data) { if (data.maximum.doubleValue() > this.maximum.doubleValue()) { this.maximum = data.maximum; } } @Override public Data copy() { return new RangeMaximumData<N>(maximum); } @Override public Data query() { return copy(); } @SuppressWarnings("unchecked") @Override public Data update(Data data) { RangeMaximumData<N> q = null; if (data instanceof RangeMaximumData) { q = (RangeMaximumData<N>) data; this.update(q); } return this; } private void update(RangeMaximumData<N> data) { this.maximum = data.maximum; } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("maximum=").append(maximum); return builder.toString(); } } public static final class RangeMinimumData<N extends Number> extends NonOverlappingData { public N minimum = null; public RangeMinimumData(N number) { this.minimum = number; } @SuppressWarnings("unchecked") @Override public Data combined(Data data) { RangeMinimumData<N> q = null; if (data instanceof RangeMinimumData) { q = (RangeMinimumData<N>) data; this.combined(q); } return this; } private void combined(RangeMinimumData<N> data) { if (data.minimum.doubleValue() < this.minimum.doubleValue()) { this.minimum = data.minimum; } } @Override public Data copy() { return new RangeMinimumData<N>(minimum); } @Override public Data query() { return copy(); } @SuppressWarnings("unchecked") @Override public Data update(Data data) { RangeMinimumData<N> q = null; if (data instanceof RangeMinimumData) { q = (RangeMinimumData<N>) data; this.update(q); } return this; } private void update(RangeMinimumData<N> data) { this.minimum = data.minimum; } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("minimum=").append(minimum); return builder.toString(); } } public static final class RangeSumData<N extends Number> extends NonOverlappingData { public N sum = null; public RangeSumData(N number) { this.sum = number; } @SuppressWarnings("unchecked") @Override public Data combined(Data data) { RangeSumData<N> q = null; if (data instanceof RangeSumData) { q = (RangeSumData<N>) data; this.combined(q); } return this; } @SuppressWarnings("unchecked") private void combined(RangeSumData<N> data) { Double d1 = this.sum.doubleValue(); Double d2 = data.sum.doubleValue(); Double r = d1+d2; this.sum = (N)r; } @Override public Data copy() { return new RangeSumData<N>(sum); } @Override public Data query() { return copy(); } @SuppressWarnings("unchecked") @Override public Data update(Data data) { RangeSumData<N> q = null; if (data instanceof RangeSumData) { q = (RangeSumData<N>) data; this.update(q); } return this; } private void update(RangeSumData<N> data) { this.sum = data.sum; } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("sum=").append(sum); return builder.toString(); } } } public static final class NonOverlappingSegment<D extends NonOverlappingData> extends Segment<D> { public NonOverlappingSegment() { } @SuppressWarnings("unchecked") public NonOverlappingSegment(long index, D data) { this.length = 1; this.start = index; this.end = index; this.data = ((D)data.copy()); } @SuppressWarnings("unchecked") public NonOverlappingSegment(long start, long end, D data) { this.length = ((int)(end-start)); this.start = start; this.end = end; this.data = ((D)data.copy()); } @SuppressWarnings("unchecked") protected static <D extends NonOverlappingData> Segment<D> createFromList(List<NonOverlappingSegment<D>> segments) { NonOverlappingSegment<D> segment = new NonOverlappingSegment<D>(); segment.length = segments.size(); segment.start = segments.get(0).start; segment.end = segments.get(segment.length - 1).end; for (Segment<D> s : segments) { if (segment.data==null) segment.data = ((D)s.data.copy()); else segment.data.combined(s.data); //Update our data to reflect all children's data } //If segment is greater or equal to two, split data into children if (segment.length >= 2) { segment.half = segment.length / 2; List<NonOverlappingSegment<D>> s1 = new ArrayList<NonOverlappingSegment<D>>(); List<NonOverlappingSegment<D>> s2 = new ArrayList<NonOverlappingSegment<D>>(); for (int i = 0; i < segment.length; i++) { NonOverlappingSegment<D> s = segments.get(i); if (s.start<segment.start+segment.half) s1.add(s); else s2.add(s); } Segment<D> sub1 = createFromList(s1); Segment<D> sub2 = createFromList(s2); segment.segments = new Segment[] { sub1, sub2 }; } return segment; } public void update(long index, D data) { if (length >= 2) { if (index < start + half) { ((NonOverlappingSegment<D>)getLeftChild()).update(index, data); } else if (index >= start + half) { ((NonOverlappingSegment<D>)getRightChild()).update(index, data); } } if (index>=this.start && index<=this.end && !this.hasChildren()) { this.data.update(data); //update leaf } else { this.update(); //update from children } } @SuppressWarnings("unchecked") private void update() { this.data = null; for (Segment<D> d : segments) { if (this.data==null) this.data = ((D)d.data.copy()); else this.data.combined(d.data); } } @SuppressWarnings("unchecked") public D query(long startIndex, long endIndex) { if (startIndex == this.start && endIndex == this.end) { D dataToReturn = ((D)this.data.query()); return dataToReturn; } else if (startIndex <= getLeftChild().end && endIndex > getLeftChild().end) { Data q1 = ((NonOverlappingSegment<D>)getLeftChild()).query(startIndex, getLeftChild().end); Data q2 = ((NonOverlappingSegment<D>)getRightChild()).query(getRightChild().start, endIndex); return ((D)q1.combined(q2)); } else if (startIndex <= getLeftChild().end && endIndex <= getLeftChild().end) { return ((NonOverlappingSegment<D>)getLeftChild()).query(startIndex, endIndex); } return ((NonOverlappingSegment<D>)getRightChild()).query(startIndex, endIndex); } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("startIndex=").append(start).append("->"); builder.append("endIndex=").append(end).append(" "); builder.append("Data=").append(data).append("\n"); return builder.toString(); } /** * {@inheritDoc} */ @Override public int compareTo(Segment<D> p) { if (!(p instanceof NonOverlappingSegment)) return Integer.MIN_VALUE; NonOverlappingSegment<D> o = (NonOverlappingSegment<D>) p; if (this.start < o.start) return -1; if (o.start < this.start) return 1; if (this.end < o.end) return -1; if (o.end < this.end) return 1; return 0; } } } /** * Segment tree is a balanced-binary-tree based data structure efficient for detecting all intervals (or segments) * that contain a given point. The segments may overlap with each other. The end points of stored segments are * inclusive, that is, when an interval spans from 2 to 6, an arbitrary point x within that interval can take a * value of 2 <= x <=6. */ public static final class DynamicSegmentTree<D extends DynamicSegmentTree.OverlappingData> extends SegmentTree<D> { public DynamicSegmentTree(List<OverlappingSegment<D>> segments) { Collections.sort(segments); //Make sure they are sorted if (segments.size()<=0) return; root = OverlappingSegment.createFromList(segments); } public void update(long start, long end, D data) { ((OverlappingSegment<D>)root).update(start, end, data); } /** * Stabbing query */ public D query(long index) { if (root==null) return null; if (index<root.start) index = root.start; if (index>root.end) index = root.end; D result = ((OverlappingSegment<D>)root).query(index,null); return result; } /** * Range query */ public D query(long start, long end) { if (root==null) return null; if (start<root.start) start = root.start; if (end>root.end) end = root.end; D result = ((OverlappingSegment<D>)root).query(start, end, null); return result; } public abstract static class OverlappingData extends Data { public static final class IntervalData<O extends Object> extends OverlappingData { private Set<O> individualObjects = new TreeSet<O>(); //Sorted /** * Interval data using O as it's unique identifier * @param object Object which defines the interval data */ public IntervalData(O object) { this.individualObjects.add(object); } /** * Interval data list which should all be unique * @param list of interval data objects */ public IntervalData(Set<O> list) { this.individualObjects = list; //Make sure they are unique Iterator<O> iter = list.iterator(); while (iter.hasNext()) { O obj1 = iter.next(); O obj2 = null; if (iter.hasNext()) obj2 = iter.next(); if (obj1.equals(obj2)) throw new InvalidParameterException("Each interval data in the list must be unique."); } } public void add(O object) { this.individualObjects.add(object); } public void remove(O object) { this.individualObjects.remove(object); } @SuppressWarnings("unchecked") @Override public Data combined(Data data) { IntervalData<O> q = null; if (data instanceof IntervalData) { q = (IntervalData<O>) data; this.combined(q); } return this; } private void combined(IntervalData<O> data) { this.individualObjects.addAll(data.individualObjects); } @Override public Data copy() { Set<O> listCopy = new TreeSet<O>(); listCopy.addAll(individualObjects); return new IntervalData<O>(listCopy); } @Override public Data query() { return copy(); } @SuppressWarnings("unchecked") @Override public Data update(Data data) { IntervalData<O> q = null; if (data instanceof IntervalData) { q = (IntervalData<O>) data; this.update(q); } return this; } private void update(IntervalData<O> data) { this.individualObjects.clear(); this.individualObjects.addAll(data.individualObjects); } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("list=").append(individualObjects); return builder.toString(); } } } public static final class OverlappingSegment<D extends OverlappingData> extends Segment<D> { public OverlappingSegment() { } @SuppressWarnings("unchecked") public OverlappingSegment(long start, long end, D data) { this.length = ((int)(end-start)); this.start = start; this.end = end; this.data = ((D)data.copy()); } protected static <D extends OverlappingData> Segment<D> createFromList(List<OverlappingSegment<D>> list) { OverlappingSegment<D> segment = new OverlappingSegment<D>(); //Define the min and max points Segment<D> start = list.get(0); Segment<D> end = list.get(list.size()-1); segment.start = start.start-1; segment.end = end.end+1; segment.length = ((int)(segment.end-segment.start))+1; //Create the whole tree createTree(segment); addSegments(segment,list); return segment; } @SuppressWarnings("unchecked") private static <D extends OverlappingData> void createTree(Segment<D> segment) { if (segment.length >= 2) { segment.half = segment.length / 2; OverlappingSegment<D> sub1 = new OverlappingSegment<D>(); sub1.length = segment.half; sub1.start = segment.start; if (sub1.length>1) { sub1.end = segment.start + (segment.half-1); } else { sub1.end = segment.start; } OverlappingSegment<D> sub2 = new OverlappingSegment<D>(); sub2.length = segment.length-sub1.length; sub2.start = segment.start + segment.half; if (sub2.length>1) { sub2.start = segment.start + segment.half; sub2.end = segment.end; } else { sub2.start = segment.start + 1; sub2.end = sub2.start; } createTree(sub1); createTree(sub2); segment.segments = new Segment[] { sub1, sub2 }; } } private static <D extends OverlappingData> void addSegments(OverlappingSegment<D> segment, List<OverlappingSegment<D>> list) { for (OverlappingSegment<D> s : list) { segment.update(s.start, s.end, s.data); } } @SuppressWarnings("unchecked") public void update(long start, long end, D data) { //Update individual segment if (start==this.start && end==this.end) { if (this.data==null) this.data = ((D)data.copy()); this.data.combined(data); } else { long middleIndex = this.start+this.half; if (start<middleIndex && end>=middleIndex) { //Split the segment across the middle sector OverlappingSegment<D> s1 = new OverlappingSegment<D>(start,middleIndex-1,data); OverlappingSegment<D> s2 = new OverlappingSegment<D>(middleIndex,end,data); List<OverlappingSegment<D>> newList = new ArrayList<OverlappingSegment<D>>(); newList.add(s1); newList.add(s2); addSegments(this,newList); } else if (end<middleIndex) { ((OverlappingSegment<D>)this.getLeftChild()).update(start, end, data); } else { ((OverlappingSegment<D>)this.getRightChild()).update(start, end, data); } } } @SuppressWarnings("unchecked") public D query(long index, D result) { if (this.data!=null && index>=this.start && index<=this.end) { if (result==null) result = ((D)this.data.copy()); else result.combined(data); } //reached a leaf node, stop recursion if (!this.hasChildren()) return result; long middleIndex = this.start+this.half; if (index<middleIndex) { result = ((OverlappingSegment<D>) this.getLeftChild()).query(index,result); } else { result = ((OverlappingSegment<D>)this.getRightChild()).query(index,result); } return result; } @SuppressWarnings("unchecked") public D query(long start, long end, D result) { for (long i=start; i<=end; i++) { D r = (this.query(i, result)); if (r==null) { //Do nothing } else if (result==null) { result = (D)r.copy(); } else if (r!=null) { result.combined(r); } } return result; } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("startIndex=").append(start).append("->"); builder.append("endIndex=").append(end).append(" "); builder.append("Length=").append(length).append("\n"); builder.append("Data=").append(data).append("\n"); builder.append("\n"); return builder.toString(); } /** * {@inheritDoc} */ @Override public int compareTo(Segment<D> p) { if (!(p instanceof OverlappingSegment)) return Integer.MIN_VALUE; OverlappingSegment<D> o = (OverlappingSegment<D>) p; if (this.start < o.start) return -1; if (o.start < this.start) return 1; if (this.end < o.end) return -1; if (o.end < this.end) return 1; return 0; } } } }
package fitnesse.wiki; import fitnesse.util.StringUtil; import java.io.Serializable; import java.util.List; public interface WikiPage extends Serializable, Comparable { public static final String SECURE_READ = "secure-read"; public static final String SECURE_WRITE = "secure-write"; public static final String SECURE_TEST = "secure-test"; public static final String LAST_MODIFYING_USER = "LastModifyingUser"; public String[] ACTION_ATTRIBUTES = {"Test", "Suite", "Edit", "Versions", "Properties", "Refactor", "WhereUsed"}; public String[] NAVIGATION_ATTRIBUTES = {"RecentChanges", "Files", "Search"}; public String[] NON_SECURITY_ATTRIBUTES = StringUtil.combineArrays(ACTION_ATTRIBUTES, NAVIGATION_ATTRIBUTES); public String[] SECURITY_ATTRIBUTES = {SECURE_READ, SECURE_WRITE, SECURE_TEST}; public WikiPage getParent() throws Exception; public WikiPage getParentForVariables() throws Exception; //[acd] !include: getter for variable parent public void setParentForVariables(WikiPage parent); //[acd] !include: setter for variable parent public WikiPage addChildPage(String name) throws Exception; public boolean hasChildPage(String name) throws Exception; public WikiPage getChildPage(String name) throws Exception; public void removeChildPage(String name) throws Exception; public List<WikiPage> getChildren() throws Exception; public String getName() throws Exception; public PageData getData() throws Exception; public PageData getDataVersion(String versionName) throws Exception; public VersionInfo commit(PageData data) throws Exception; public PageCrawler getPageCrawler(); //TODO Delete these method alone with ProxyPage when the time is right. public boolean hasExtension(String extensionName); public Extension getExtension(String extensionName); }
package com.provinggrounds.match3things.activity; import com.proving.grounds.match3things.R; import com.provinggrounds.match3things.game.Grid; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.GridView; import android.support.v4.app.NavUtils; public class GameActivity extends Activity { Grid currentGameGrid; GridView gameGridView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); // Show the Up button in the action bar. setupActionBar(); currentGameGrid = new Grid(4, 4, 6); gameGridView = createGridView(currentGameGrid); } private GridView createGridView(Grid gameGrid) { GridView newGridView = new GridView(this); newGridView.setNumColumns(gameGrid.getWidth()); ArrayAdapter<int[]> gridAdapter = new ArrayAdapter<int[]>(this, R.layout.grid_element_text_view, gameGrid.getGameGrid()); newGridView.setAdapter(gridAdapter); return newGridView; } /** * Set up the {@link android.app.ActionBar}. */ private void setupActionBar() { getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.game, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // http://developer.android.com/design/patterns/navigation.html#up-vs-back NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } }
package com.redhat.ceylon.compiler.analyzer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import com.redhat.ceylon.compiler.context.Context; import com.redhat.ceylon.compiler.model.Class; import com.redhat.ceylon.compiler.model.ClassOrInterface; import com.redhat.ceylon.compiler.model.Functional; import com.redhat.ceylon.compiler.model.Interface; import com.redhat.ceylon.compiler.model.Package; import com.redhat.ceylon.compiler.model.Parameter; import com.redhat.ceylon.compiler.model.ParameterList; import com.redhat.ceylon.compiler.model.ProducedReference; import com.redhat.ceylon.compiler.model.ProducedType; import com.redhat.ceylon.compiler.model.ProducedTypedReference; import com.redhat.ceylon.compiler.model.Scope; import com.redhat.ceylon.compiler.model.TypeDeclaration; import com.redhat.ceylon.compiler.model.TypedDeclaration; import com.redhat.ceylon.compiler.model.Value; import com.redhat.ceylon.compiler.tree.Node; import com.redhat.ceylon.compiler.tree.Tree; import com.redhat.ceylon.compiler.tree.Tree.BinaryOperatorExpression; import com.redhat.ceylon.compiler.tree.Tree.LowerBound; import com.redhat.ceylon.compiler.tree.Tree.Primary; import com.redhat.ceylon.compiler.tree.Tree.SafeIndexOp; import com.redhat.ceylon.compiler.tree.Tree.SpecifierExpression; import com.redhat.ceylon.compiler.tree.Tree.Term; import com.redhat.ceylon.compiler.tree.Tree.TypeArgumentList; import com.redhat.ceylon.compiler.tree.Tree.UpperBound; import com.redhat.ceylon.compiler.tree.Tree.Variable; import com.redhat.ceylon.compiler.tree.Visitor; /** * Third and final phase of type analysis. * Finally visit all expressions and determine their types. * Use type inference to assign types to declarations with * the local modifier. Finally, assigns types to the * associated model objects of declarations declared using * the local modifier. * * @author Gavin King * */ public class ExpressionVisitor extends Visitor { private ClassOrInterface classOrInterface; private Tree.TypeOrSubtype returnType; private Context context; public ExpressionVisitor(Context context) { this.context = context; } public void visit(Tree.ClassDefinition that) { ClassOrInterface o = classOrInterface; classOrInterface = (Class) that.getDeclarationModel(); super.visit(that); classOrInterface = o; } public void visit(Tree.InterfaceDefinition that) { ClassOrInterface o = classOrInterface; classOrInterface = (Interface) that.getDeclarationModel(); super.visit(that); classOrInterface = o; } public void visit(Tree.ObjectDeclaration that) { ClassOrInterface o = classOrInterface; classOrInterface = (Class) ((Value) that.getDeclarationModel()).getType().getDeclaration(); super.visit(that); classOrInterface = o; } public void visit(Tree.ObjectArgument that) { ClassOrInterface o = classOrInterface; classOrInterface = (Class) ((Value) that.getDeclarationModel()).getType().getDeclaration(); super.visit(that); classOrInterface = o; } private Tree.TypeOrSubtype beginReturnScope(Tree.TypeOrSubtype t) { Tree.TypeOrSubtype ort = returnType; returnType = t; return ort; } private void endReturnScope(Tree.TypeOrSubtype t) { returnType = t; } @Override public void visit(Tree.Variable that) { super.visit(that); if (that.getSpecifierExpression()!=null) { inferType(that, that.getSpecifierExpression()); checkType(that, that.getSpecifierExpression()); } } @Override public void visit(Tree.IsCondition that) { if (that.getVariable()!=null) { that.getVariable().getSpecifierExpression().visit(this); } if (that.getExpression()!=null) { that.getExpression().visit(this); } } @Override public void visit(Tree.ExistsCondition that) { ProducedType t = null; Node n = that; Variable v = that.getVariable(); Class ot = getOptionalDeclaration(); if (v!=null) { SpecifierExpression se = v.getSpecifierExpression(); visit(se); inferType(v, se, ot); checkType(v, se, ot); t = se.getExpression().getTypeModel(); n = v; } if (that.getExpression()!=null) { that.getExpression().visit(this); t = that.getExpression().getTypeModel(); n = that.getExpression(); } if (t==null) { n.addError("could not determine if expression is of optional type"); } else if (t.getDeclaration()!=ot) { n.addError("expression is not of optional type"); } } @Override public void visit(Tree.BooleanCondition that) { super.visit(that); if (that.getExpression()!=null) { ProducedType t = that.getExpression().getTypeModel(); if (t==null) { that.addError("could not determine if expression is of boolean type"); } else { ProducedType bt = getBooleanDeclaration().getType(); if (!bt.isSupertypeOf(t)) { that.addError("expression is not of boolean type"); } } } } @Override public void visit(Tree.ValueIterator that) { super.visit(that); Interface it = getIterableDeclaration(); inferType(that.getVariable(), that.getSpecifierExpression(), it); checkType(that.getVariable(), that.getSpecifierExpression(), it); } @Override public void visit(Tree.KeyValueIterator that) { super.visit(that); //TODO: infer type from arguments to Iterable<Entry<K,V>> } @Override public void visit(Tree.AttributeDeclaration that) { super.visit(that); inferType(that, that.getSpecifierOrInitializerExpression()); checkType(that, that.getSpecifierOrInitializerExpression()); } @Override public void visit(Tree.SpecifierStatement that) { super.visit(that); checkType(that.getMember(), that.getSpecifierExpression()); } @Override public void visit(Tree.Parameter that) { super.visit(that); checkType(that, that.getSpecifierExpression()); } private void checkType(ProducedType dt, Tree.SpecifierOrInitializerExpression sie) { if (sie!=null) { ProducedType et = sie.getExpression().getTypeModel(); if ( et!=null && dt!=null) { if ( !dt.isSupertypeOf(et) ) { sie.addError("specifier expression not assignable to expected type: " + et.getProducedTypeName() + " is not " + dt.getProducedTypeName()); } } else { sie.addError("could not determine assignability of specified expression to expected type"); } } } private void checkType(Tree.Member td, Tree.SpecifierOrInitializerExpression sie) { checkType(td.getTypeModel(), sie); } private void checkType(Tree.TypedDeclaration td, Tree.SpecifierOrInitializerExpression sie) { checkType(td.getTypeOrSubtype().getTypeModel(), sie); } private void checkType(Tree.Variable var, Tree.SpecifierExpression se, TypeDeclaration otd) { ProducedType vt = var.getTypeOrSubtype().getTypeModel(); ProducedType t = otd.getProducedType(Collections.singletonList(vt)); checkType(t, se); } @Override public void visit(Tree.AttributeGetterDefinition that) { Tree.TypeOrSubtype rt = beginReturnScope(that.getTypeOrSubtype()); super.visit(that); inferType(that, that.getBlock()); endReturnScope(rt); } @Override public void visit(Tree.AttributeArgument that) { Tree.TypeOrSubtype rt = beginReturnScope(that.getTypeOrSubtype()); super.visit(that); //TODO: inferType(that, that.getBlock()); endReturnScope(rt); } @Override public void visit(Tree.AttributeSetterDefinition that) { Tree.TypeOrSubtype rt = beginReturnScope(that.getTypeOrSubtype()); super.visit(that); inferType(that, that.getBlock()); endReturnScope(rt); } @Override public void visit(Tree.MethodDeclaration that) { super.visit(that); inferType(that, that.getSpecifierExpression()); } @Override public void visit(Tree.MethodDefinition that) { Tree.TypeOrSubtype rt = beginReturnScope(that.getTypeOrSubtype()); super.visit(that); endReturnScope(rt); inferType(that, that.getBlock()); } @Override public void visit(Tree.MethodArgument that) { Tree.TypeOrSubtype rt = beginReturnScope(that.getTypeOrSubtype()); super.visit(that); endReturnScope(rt); //TODO: inferType(that, that.getBlock()); } //Type inference for members declared "local": private void inferType(Tree.TypedDeclaration that, Tree.Block block) { if (that.getTypeOrSubtype() instanceof Tree.LocalModifier) { if (block!=null) { setType((Tree.LocalModifier) that.getTypeOrSubtype(), block, that); } else { that.addError("could not infer type of: " + Util.name(that)); } } } private void inferType(Tree.TypedDeclaration that, Tree.SpecifierOrInitializerExpression spec) { if (that.getTypeOrSubtype() instanceof Tree.LocalModifier) { if (spec!=null) { setType((Tree.LocalModifier) that.getTypeOrSubtype(), spec, that); } else { that.addError("could not infer type of: " + Util.name(that)); } } } private void inferType(Tree.Variable that, Tree.SpecifierExpression se, TypeDeclaration td) { if (that.getTypeOrSubtype() instanceof Tree.LocalModifier) { if (se!=null) { setTypeFromTypeArgument((Tree.LocalModifier) that.getTypeOrSubtype(), se, that, td); } else { that.addError("could not infer type of: " + Util.name(that)); } } } private void setTypeFromTypeArgument(Tree.LocalModifier local, Tree.SpecifierExpression s, Tree.Variable that, TypeDeclaration td) { ProducedType ot = s.getExpression().getTypeModel(); //TODO: search for the correct type to look for the argument of! if (ot!=null && ot.getTypeArguments().size()==1) { ProducedType t = ot.getTypeArguments().values().iterator().next(); local.setTypeModel(t); ((TypedDeclaration) that.getDeclarationModel()).setType(t); } else { that.addError("could not infer type of: " + Util.name(that)); } } private void setType(Tree.LocalModifier local, Tree.SpecifierOrInitializerExpression s, Tree.TypedDeclaration that) { ProducedType t = s.getExpression().getTypeModel(); local.setTypeModel(t); ((TypedDeclaration) that.getDeclarationModel()).setType(t); } private void setType(Tree.LocalModifier local, Tree.Block block, Tree.TypedDeclaration that) { int s = block.getStatements().size(); Tree.Statement d = s==0 ? null : block.getStatements().get(s-1); if (d!=null && (d instanceof Tree.Return)) { ProducedType t = ((Tree.Return) d).getExpression().getTypeModel(); local.setTypeModel(t); ((TypedDeclaration) that.getDeclarationModel()).setType(t); } else { local.addError("could not infer type of: " + Util.name(that)); } } @Override public void visit(Tree.Return that) { super.visit(that); if (returnType==null) { that.addError("could not determine expected return type"); } else { Tree.Expression e = that.getExpression(); if ( returnType instanceof Tree.VoidModifier ) { if (e!=null) { that.addError("void methods may not return a value"); } } else if ( !(returnType instanceof Tree.LocalModifier) ) { if (e==null) { that.addError("non-void methods and getters must return a value"); } else { ProducedType et = returnType.getTypeModel(); ProducedType at = e.getTypeModel(); if (et!=null && at!=null) { if ( !et.isSupertypeOf(at) ) { that.addError("returned expression not assignable to expected return type: " + at.getProducedTypeName() + " is not " + et.getProducedTypeName()); } } else { that.addError("could not determine assignability of returned expression to expected return type"); } } } } } //Primaries: @Override public void visit(Tree.MemberExpression that) { that.getPrimary().visit(this); ProducedType pt = that.getPrimary().getTypeModel(); if (pt!=null) { if (pt.getDeclaration() instanceof Scope) { Tree.MemberOrType mt = that.getMemberOrType(); if (mt instanceof Tree.Member) { handleMemberReference(that, pt, (Tree.Member) mt); } else if (mt instanceof Tree.Type) { handleMemberTypeReference(that, pt, (Tree.Type) mt); } else if (mt instanceof Tree.Outer) { handleOuterReference(that, pt, mt); } else { that.addError("not a valid member reference"); } } else { //TODO: this case is temporary, until we // have support for type constraints } } } private void handleOuterReference(Tree.MemberExpression that, ProducedType pt, Tree.MemberOrType mt) { if (pt.getDeclaration() instanceof ClassOrInterface) { that.setTypeModel(getOuterType(mt, (ClassOrInterface) pt.getDeclaration())); //TODO: some kind of MemberReference } else { that.addError("can't use outer on a type parameter"); } } ProducedType unwrap(ProducedType pt, Tree.MemberExpression op) { if (op instanceof Tree.SafeMemberOp) { ProducedType ot = pt.getSupertype(getOptionalDeclaration()); if (ot==null) return pt; //TODO: proper error! return ot.getTypeArguments().values().iterator().next(); } else if (op instanceof Tree.SpreadOp) { ProducedType st = pt.getSupertype(getSequenceDeclaration()); if (st==null) return pt; //TODO: proper error! return st.getTypeArguments().values().iterator().next(); } else { return pt; } } ProducedType wrap(ProducedType pt, Tree.MemberExpression op) { if (op instanceof Tree.SafeMemberOp) { return getOptionalDeclaration().getProducedType(Collections.singletonList(pt)); } else if (op instanceof Tree.SpreadOp) { return getSequenceDeclaration().getProducedType(Collections.singletonList(pt)); } else { return pt; } } private void handleMemberTypeReference(Tree.MemberExpression that, ProducedType pt, Tree.Type tt) { pt = unwrap(pt, that); TypeDeclaration member = Util.getDeclaration((Scope) pt.getDeclaration(), tt, context); if (member==null) { tt.addError("could not determine target of member type reference: " + tt.getIdentifier().getText()); } else { List<ProducedType> typeArgs = getTypeArguments(tt, tt.getTypeArgumentList()); if (!com.redhat.ceylon.compiler.model.Util.acceptsArguments(member, typeArgs)) { tt.addError("member type does not accept the given type arguments"); } else { ProducedType t = pt.getTypeMember(member, typeArgs); that.setTypeModel(wrap(t, that)); //TODO: this is not correct, should be Callable that.setMemberReference(t); } } } private void handleMemberReference(Tree.MemberExpression that, ProducedType pt, Tree.Member m) { pt = unwrap(pt, that); TypedDeclaration member = Util.getDeclaration((Scope) pt.getDeclaration(), m, context); if (member==null) { m.addError("could not determine target of member reference: " + m.getIdentifier().getText()); } else { List<ProducedType> typeArgs = getTypeArguments(m, m.getTypeArgumentList()); if (!com.redhat.ceylon.compiler.model.Util.acceptsArguments(member, typeArgs)) { m.addError("member does not accept the given type arguments"); } else { ProducedTypedReference ptr = getMemberProducedReference(member, pt, m, typeArgs); if (ptr==null) { m.addError("member not found: " + member.getName() + " of type " + pt.getDeclaration().getName()); } else { ProducedType t = ptr.getType(); that.setMemberReference(ptr); //TODO: how do we wrap ptr??? that.setTypeModel(wrap(t, that)); //TODO: this is not correct, should be Callable } } } } private ProducedTypedReference getMemberProducedReference( TypedDeclaration member, ProducedType pt, Tree.Member m, List<ProducedType> typeArgs) { if (member.getContainer() instanceof ClassOrInterface) { //TODO: we should try each class/interface that contains // the current class/interface in turn until we // get to toplevel scope (the package) // ... or, well, perhaps not!! return pt.getTypedMember(member, typeArgs); } else { //TODO: should we even remove this one? return member.getProducedTypedReference(typeArgs); } } @Override public void visit(Tree.Annotation that) { //TODO: ignore annotations for now } @Override public void visit(Tree.InvocationExpression that) { super.visit(that); Tree.Primary pr = that.getPrimary(); if (pr==null) { that.addError("malformed expression"); } else { ProducedReference m = pr.getMemberReference(); if (m==null || !m.isFunctional()) { that.addError("receiving expression cannot be invoked"); } else { //that.setTypeModel(m.getType()); //THIS IS THE CORRECT ONE! that.setTypeModel(pr.getTypeModel()); //TODO: THIS IS A TEMPORARY HACK! List<ParameterList> pls = ((Functional) m.getDeclaration()).getParameterLists(); checkInvocationArguments(that, m, pls); } } } private void checkInvocationArguments(Tree.InvocationExpression that, ProducedReference pr, List<ParameterList> pls) { if (pls.isEmpty()) { that.addError("receiver does not define a parameter list"); } else { ParameterList pl = pls.get(0); Tree.PositionalArgumentList pal = that.getPositionalArgumentList(); if ( pal!=null ) { checkPositionalArguments(pl, pr, pal); } Tree.NamedArgumentList nal = that.getNamedArgumentList(); if (nal!=null) { checkNamedArguments(pl, pr, nal); } } } private void checkNamedArguments(ParameterList pl, ProducedReference pr, Tree.NamedArgumentList nal) { List<Tree.NamedArgument> na = nal.getNamedArguments(); Set<Parameter> foundParameters = new HashSet<Parameter>(); for (Tree.NamedArgument a: na) { Parameter p = getMatchingParameter(pl, a); if (p==null) { a.addError("no matching parameter for named argument: " + Util.name(a)); } else { foundParameters.add(p); checkNamedArgument(a, pr, p); } } Tree.SequencedArgument sa = nal.getSequencedArgument(); if (sa!=null) { Parameter sp = getSequencedParameter(pl); if (sp==null) { sa.addError("no matching sequenced parameter"); } else { foundParameters.add(sp); } //TODO: check type! } for (Parameter p: pl.getParameters()) { if (!foundParameters.contains(p) && !p.isDefaulted()) { nal.addError("missing named argument to parameter: " + p.getName()); } } } private void checkNamedArgument(Tree.NamedArgument a, ProducedReference pr, Parameter p) { if (p.getType()==null) { a.addError("parameter type not known: " + Util.name(a)); } else { ProducedType argType = null; if (a instanceof Tree.SpecifiedArgument) { argType = ((Tree.SpecifiedArgument) a).getSpecifierExpression().getExpression().getTypeModel(); } else if (a instanceof Tree.TypedArgument) { argType = ((Tree.TypedArgument) a).getTypeOrSubtype().getTypeModel(); } if (argType==null) { a.addError("could not determine assignability of argument to parameter: " + p.getName()); } else { ProducedType paramType = pr.getTypedParameter(p).getType(); if ( !paramType.getType().isSupertypeOf(argType) ) { a.addError("named argument not assignable to parameter type: " + Util.name(a) + " since " + argType.getProducedTypeName() + " is not " + paramType.getProducedTypeName()); } } } } private Parameter getMatchingParameter(ParameterList pl, Tree.NamedArgument na) { for (Parameter p: pl.getParameters()) { if (p.getName().equals(na.getIdentifier().getText())) { return p; } } return null; } private Parameter getSequencedParameter(ParameterList pl) { int s = pl.getParameters().size(); if (s==0) return null; Parameter p = pl.getParameters().get(s-1); if (p.isSequenced()) { return p; } else { return null; } } private void checkPositionalArguments(ParameterList pl, ProducedReference r, Tree.PositionalArgumentList pal) { List<Tree.PositionalArgument> args = pal.getPositionalArguments(); List<Parameter> params = pl.getParameters(); for (int i=0; i<params.size(); i++) { Parameter p = params.get(i); if (i>=args.size()) { if (!p.isDefaulted() && !p.isSequenced()) { pal.addError("no argument to parameter: " + p.getName()); } } else { Tree.PositionalArgument a = args.get(i); Tree.Expression e = a.getExpression(); if (e==null) { //TODO: this case is temporary until we get support for SPECIAL_ARGUMENTs } else { ProducedType argType = e.getTypeModel(); ProducedType paramType = r.getTypedParameter(p).getType(); if (paramType!=null && argType!=null) { if (!paramType.isSupertypeOf(argType)) { a.addError("argument not assignable to parameter type: " + p.getName() + " since " + argType.getProducedTypeName() + " is not " + paramType.getProducedTypeName()); } } else { a.addError("could not determine assignability of argument to parameter: " + p.getName()); } } } } //TODO: sequenced arguments! for (int i=params.size(); i<args.size(); i++) { args.get(i).addError("no matching parameter for argument"); } } @Override public void visit(Tree.IndexExpression that) { super.visit(that); ProducedType pt = type(that); if (pt==null) { that.addError("could not determine type of receiver"); } else { Interface s = getCorrespondenceDeclaration(); if (that instanceof SafeIndexOp) { ProducedType ot = pt.getSupertype( getOptionalDeclaration() ); if (ot!=null) { //TODO: add a proper error pt = ot.getTypeArguments().values().iterator().next(); } } ProducedType st = pt.getSupertype(s); if (st==null) { that.getPrimary().addError("receiving type of an index expression must be a Correspondence"); } else { List<ProducedType> args = st.getTypeArgumentList(); ProducedType kt = args.get(0); ProducedType vt = args.get(1); LowerBound lb = that.getLowerBound(); if (lb==null) { that.addError("missing lower bound"); } else { ProducedType lbt = lb.getExpression().getTypeModel(); if (lbt!=null) { if (!kt.isSupertypeOf(lbt)) { lb.addError("index must be of type: " + kt.getProducedTypeName()); } } } ClassOrInterface rtd; UpperBound ub = that.getUpperBound(); if (ub==null) { rtd = getOptionalDeclaration(); } else { rtd = getSequenceDeclaration(); ProducedType ubt = ub.getExpression().getTypeModel(); if (ubt!=null) { if (!kt.isSupertypeOf(ubt)) { ub.addError("index must be of type: " + kt.getProducedTypeName()); } } } ProducedType ot = rtd.getProducedType( Collections.singletonList(vt) ); if (that instanceof SafeIndexOp) { ot = getOptionalDeclaration().getProducedType( Collections.singletonList(ot) ); } that.setTypeModel(ot); } } } @Override public void visit(Tree.PostfixOperatorExpression that) { super.visit(that); ProducedType pt = type(that); that.setTypeModel(pt); } private ProducedType type(Tree.PostfixExpression that) { Primary p = that.getPrimary(); return p==null ? null : p.getTypeModel(); } @Override public void visit(Tree.PrefixOperatorExpression that) { super.visit(that); ProducedType pt = type(that); that.setTypeModel(pt); } @Override public void visit(Tree.SumOp that) { super.visit( (BinaryOperatorExpression) that ); ProducedType lhst = leftType(that); if (lhst!=null) { //take into account overloading of + operator if (lhst.isSubtypeOf(getStringDeclaration().getType())) { visitBinaryOperator(that, getStringDeclaration()); } else { visitBinaryOperator(that, getNumericDeclaration()); } } } private void visitComparisonOperator(Tree.BinaryOperatorExpression that, TypeDeclaration type) { ProducedType lhst = leftType(that); ProducedType rhst = rightType(that); if ( rhst!=null && lhst!=null ) { ProducedType nt = lhst.getSupertype(type); if (nt==null) { that.getLeftTerm().addError("must be of type: " + type.getName()); } else { that.setTypeModel( getBooleanDeclaration().getType() ); if (!nt.isSupertypeOf(rhst)) { that.getRightTerm().addError("must be of type: " + nt.getProducedTypeName()); } } } } private void visitRangeOperator(Tree.RangeOp that) { ProducedType lhst = leftType(that); ProducedType rhst = rightType(that); if ( rhst!=null && lhst!=null ) { if ( !lhst.isSubtypeOf(getOrdinalDeclaration().getType())) { that.getLeftTerm().addError("must be of type: Ordinal"); } if ( !rhst.isSubtypeOf(getOrdinalDeclaration().getType())) { that.getRightTerm().addError("must be of type: Ordinal"); } ProducedType ct = lhst.getSupertype(getComparableDeclaration()); if ( ct==null) { that.getLeftTerm().addError("must be of type: Comparable"); } else { ProducedType t = ct.getTypeArguments().values().iterator().next(); if ( !rhst.isSubtypeOf(t)) { that.getRightTerm().addError("must be of type: " + t.getProducedTypeName()); } else { that.setTypeModel( getRangeDeclaration().getProducedType( Collections.singletonList(t) ) ); } } } } private void visitEntryOperator(Tree.EntryOp that) { ProducedType lhst = leftType(that); ProducedType rhst = rightType(that); if ( rhst!=null && lhst!=null ) { ProducedType let = lhst.getSupertype(getEqualityDeclaration()); ProducedType ret = rhst.getSupertype(getEqualityDeclaration()); if ( let==null) { that.getLeftTerm().addError("must be of type: Equality"); } if ( ret==null) { that.getRightTerm().addError("must be of type: Equality"); } that.setTypeModel(getEntryDeclaration().getProducedType(Arrays.asList(new ProducedType[] {lhst,rhst}))); } } private void visitBinaryOperator(Tree.BinaryOperatorExpression that, TypeDeclaration type) { ProducedType lhst = leftType(that); ProducedType rhst = rightType(that); if ( rhst!=null && lhst!=null ) { ProducedType nt = lhst.getSupertype(type); if (nt==null) { that.getLeftTerm().addError("must be of type: " + type.getName()); } else { ProducedType t = nt.getTypeArguments().isEmpty() ? nt : nt.getTypeArguments().values().iterator().next(); that.setTypeModel(t); if (!nt.isSupertypeOf(rhst)) { that.getRightTerm().addError("must be of type: " + nt.getProducedTypeName()); } } } } private void visitDefaultOperator(Tree.DefaultOp that) { ProducedType lhst = leftType(that); ProducedType rhst = rightType(that); if ( rhst!=null && lhst!=null ) { Class otd = getOptionalDeclaration(); that.setTypeModel(rhst); ProducedType nt = rhst.getSupertype(otd); if (nt==null) { ProducedType ot = otd.getProducedType(Collections.singletonList(rhst)); if (!lhst.isSubtypeOf(ot)) { that.getLeftTerm().addError("must be of type: " + ot.getProducedTypeName()); } } else { if (!lhst.isSubtypeOf(rhst)) { that.getRightTerm().addError("must be of type: " + rhst.getProducedTypeName()); } } } } private void visitUnaryOperator(Tree.UnaryOperatorExpression that, TypeDeclaration type) { ProducedType t = type(that); if ( t!=null ) { ProducedType nt = t.getSupertype(type); if (nt==null) { that.getTerm().addError("must be of type: " + type.getName()); } else { ProducedType at = nt.getTypeArguments().isEmpty() ? nt : nt.getTypeArguments().values().iterator().next(); that.setTypeModel(at); } } } private TypeDeclaration getLanguageDeclaration(String type) { return (TypeDeclaration) Util.getLanguageModuleDeclaration(type, context); } private void visitFormatOperator(Tree.UnaryOperatorExpression that) { //TODO: reenable once we have extensions: /*ProducedType t = that.getTerm().getTypeModel(); if ( t!=null ) { if ( !getLanguageType("Formattable").isSupertypeOf(t) ) { that.getTerm().addError("must be of type: Formattable"); } }*/ that.setTypeModel( getStringDeclaration().getType() ); } private void visitExistsOperator(Tree.Exists that) { ProducedType t = type(that); if (t!=null) { if (t.getSupertype(getOptionalDeclaration())==null) { that.getTerm().addError("must be of type: Optional"); } } that.setTypeModel(getBooleanDeclaration().getType()); } private void visitAssignOperator(Tree.AssignOp that) { ProducedType rhst = rightType(that); ProducedType lhst = leftType(that); if ( rhst!=null && lhst!=null ) { if ( !rhst.isSubtypeOf(lhst) ) { that.getRightTerm().addError("must be of type " + lhst.getProducedTypeName()); } } //TODO: validate that the LHS really is assignable that.setTypeModel(rhst); } private ProducedType rightType(Tree.BinaryOperatorExpression that) { Term rt = that.getRightTerm(); return rt==null? null : rt.getTypeModel(); } private ProducedType leftType(Tree.BinaryOperatorExpression that) { Term lt = that.getLeftTerm(); return lt==null ? null : lt.getTypeModel(); } private ProducedType type(Tree.UnaryOperatorExpression that) { Term t = that.getTerm(); return t==null ? null : t.getTypeModel(); } @Override public void visit(Tree.ArithmeticOp that) { super.visit(that); visitBinaryOperator(that, getNumericDeclaration()); } @Override public void visit(Tree.BitwiseOp that) { super.visit(that); visitBinaryOperator(that, getSlotsDeclaration()); } @Override public void visit(Tree.LogicalOp that) { super.visit(that); visitBinaryOperator(that, getBooleanDeclaration()); } @Override public void visit(Tree.EqualityOp that) { super.visit(that); visitComparisonOperator(that, getEqualityDeclaration()); } @Override public void visit(Tree.ComparisonOp that) { super.visit(that); visitComparisonOperator(that, getComparableDeclaration()); } @Override public void visit(Tree.IdenticalOp that) { super.visit(that); visitComparisonOperator(that, getIdentifiableObjectDeclaration()); } @Override public void visit(Tree.DefaultOp that) { super.visit(that); visitDefaultOperator(that); } @Override public void visit(Tree.NegativeOp that) { super.visit(that); visitUnaryOperator(that, getNumericDeclaration()); } @Override public void visit(Tree.FlipOp that) { super.visit(that); visitUnaryOperator(that, getSlotsDeclaration()); } @Override public void visit(Tree.NotOp that) { super.visit(that); visitUnaryOperator(that, getBooleanDeclaration()); } @Override public void visit(Tree.AssignOp that) { super.visit(that); visitAssignOperator(that); } @Override public void visit(Tree.ArithmeticAssignmentOp that) { super.visit(that); visitBinaryOperator(that, getNumericDeclaration()); } @Override public void visit(Tree.LogicalAssignmentOp that) { super.visit(that); visitBinaryOperator(that, getBooleanDeclaration()); } @Override public void visit(Tree.BitwiseAssignmentOp that) { super.visit(that); visitBinaryOperator(that, getSlotsDeclaration()); } @Override public void visit(Tree.FormatOp that) { super.visit(that); visitFormatOperator(that); } @Override public void visit(Tree.RangeOp that) { super.visit(that); visitRangeOperator(that); } @Override public void visit(Tree.EntryOp that) { super.visit(that); visitEntryOperator(that); } @Override public void visit(Tree.Exists that) { super.visit(that); visitExistsOperator(that); } //Atoms: @Override public void visit(Tree.Member that) { //TODO: this does not correctly handle methods // and classes which are not subsequently // invoked (should return the callable type) TypedDeclaration d = Util.getDeclaration(that, context); if (d==null) { that.addError("could not determine target of member reference: " + that.getIdentifier().getText()); } else { if ( that.getIdentifier().getText().equals("getIt") ) { that.getIdentifier(); } List<ProducedType> typeArgs = getTypeArguments(that, that.getTypeArgumentList()); if (!com.redhat.ceylon.compiler.model.Util.acceptsArguments(d, typeArgs)) { that.addError("does not accept the given type arguments"); } else { ProducedReference pr = getProducedReference(d, classOrInterface, typeArgs); that.setMemberReference(pr); ProducedType t = pr.getType(); if (t==null) { that.addError("could not determine type of member reference: " + that.getIdentifier().getText()); } else { that.setTypeModel(t); } } } } private ProducedTypedReference getProducedReference(TypedDeclaration d, Scope scope, List<ProducedType> typeArgs) { //TODO: we need to try each class/interface that contains // the current class/interface in turn until we // get to toplevel scope (the package) //TODO: I think we even need to try control blocks and // method/attribute bodies! if ( d.getContainer() instanceof ClassOrInterface ) { //look for it as a declared or inherited //member of the current class or interface while ( !(scope instanceof Package) ) { if (scope instanceof ClassOrInterface) { ProducedTypedReference pr = ((ClassOrInterface) scope).getType().getTypedMember(d, typeArgs); if (pr!=null) { return pr; } } scope = scope.getContainer(); } //we will definitely find it, so this never occurs: throw new RuntimeException("member not found"); } else { //it must be a member of an outer scope return d.getProducedTypedReference(typeArgs); } } @Override public void visit(Tree.Expression that) { //i.e. this is a parenthesized expression super.visit(that); Tree.Term term = that.getTerm(); if (term==null) { that.addError("expression not well formed"); } else { ProducedType t = term.getTypeModel(); if (t==null) { that.addError("could not determine type of expression"); } else { that.setTypeModel(t); } } } @Override public void visit(Tree.Outer that) { that.setTypeModel(getOuterType(that, that.getScope())); } private ProducedType getOuterType(Node that, Scope scope) { Boolean foundInner = false; while (!(scope instanceof Package)) { if (scope instanceof ClassOrInterface) { if (foundInner) { return ((ClassOrInterface) scope).getType(); } else { foundInner = true; } } scope = scope.getContainer(); } that.addError("can't use outer outside of nested class or interface"); return null; } @Override public void visit(Tree.Super that) { if (classOrInterface==null) { that.addError("can't use super outside a class"); } else if (!(classOrInterface instanceof Class)) { that.addError("can't use super inside an interface"); } else { ProducedType t = classOrInterface.getExtendedType(); //TODO: type arguments that.setTypeModel(t); } } @Override public void visit(Tree.This that) { if (classOrInterface==null) { that.addError("can't use this outside a class or interface"); } else { that.setTypeModel(classOrInterface.getType()); } } @Override public void visit(Tree.Subtype that) { //TODO! } @Override public void visit(Tree.SequenceEnumeration that) { super.visit(that); ProducedType et = null; for (Tree.Expression e: that.getExpressionList().getExpressions()) { if (et==null) { et = e.getTypeModel(); } //TODO: determine the common supertype of all of them } if (et!=null) { Interface std = getSequenceDeclaration(); that.setTypeModel(std.getProducedType(Collections.singletonList(et))); } } @Override public void visit(Tree.StringTemplate that) { super.visit(that); //TODO: validate that the subexpression types are Formattable setLiteralType(that, getStringDeclaration()); } @Override public void visit(Tree.StringLiteral that) { setLiteralType(that, getStringDeclaration()); } @Override public void visit(Tree.NaturalLiteral that) { setLiteralType(that, getNaturalDeclaration()); } @Override public void visit(Tree.FloatLiteral that) { setLiteralType(that, getFloatDeclaration()); } @Override public void visit(Tree.CharLiteral that) { setLiteralType(that, getCharacterDeclaration()); } @Override public void visit(Tree.QuotedLiteral that) { setLiteralType(that, getQuotedDeclaration()); } private void setLiteralType(Tree.Atom that, TypeDeclaration languageType) { that.setTypeModel(languageType.getType()); } @Override public void visit(Tree.CompilerAnnotation that) { //don't visit the argument } //copy/pasted from TypeVisitor! private List<ProducedType> getTypeArguments(Tree.MemberOrType that, TypeArgumentList tal) { List<ProducedType> typeArguments = new ArrayList<ProducedType>(); if (tal!=null) { for (Tree.TypeOrSubtype ta: tal.getTypeOrSubtypes()) { ProducedType t = ta.getTypeModel(); if (t==null) { ta.addError("could not resolve type argument"); return null; } else { typeArguments.add(t); } } } return typeArguments; } private Interface getCorrespondenceDeclaration() { return (Interface) getLanguageDeclaration("Correspondence"); } private Interface getSequenceDeclaration() { return (Interface) getLanguageDeclaration("Sequence"); } private Class getOptionalDeclaration() { return (Class) getLanguageDeclaration("Optional"); } private Interface getIterableDeclaration() { return (Interface) getLanguageDeclaration("Iterable"); } private TypeDeclaration getNumericDeclaration() { return getLanguageDeclaration("Numeric"); } private TypeDeclaration getSlotsDeclaration() { return getLanguageDeclaration("Slots"); } private TypeDeclaration getBooleanDeclaration() { return getLanguageDeclaration("Boolean"); } private TypeDeclaration getStringDeclaration() { return getLanguageDeclaration("String"); } private TypeDeclaration getFloatDeclaration() { return getLanguageDeclaration("Float"); } private TypeDeclaration getNaturalDeclaration() { return getLanguageDeclaration("Natural"); } private TypeDeclaration getCharacterDeclaration() { return getLanguageDeclaration("Character"); } private TypeDeclaration getQuotedDeclaration() { return getLanguageDeclaration("Quoted"); } private TypeDeclaration getEqualityDeclaration() { return getLanguageDeclaration("Equality"); } private TypeDeclaration getComparableDeclaration() { return getLanguageDeclaration("Comparable"); } private TypeDeclaration getIdentifiableObjectDeclaration() { return getLanguageDeclaration("IdentifiableObject"); } private TypeDeclaration getOrdinalDeclaration() { return getLanguageDeclaration("Ordinal"); } private TypeDeclaration getRangeDeclaration() { return getLanguageDeclaration("Range"); } private TypeDeclaration getEntryDeclaration() { return getLanguageDeclaration("Entry"); } }
package ti.modules.titanium.platform; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollModule; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.KrollRuntime; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.kroll.common.Log; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.TiContext; import org.appcelerator.titanium.util.TiPlatformHelper; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.BatteryManager; @Kroll.module public class PlatformModule extends KrollModule { private static final String TAG = "PlatformModule"; @Kroll.constant public static final int BATTERY_STATE_UNKNOWN = 0; @Kroll.constant public static final int BATTERY_STATE_UNPLUGGED = 1; @Kroll.constant public static final int BATTERY_STATE_CHARGING = 2; @Kroll.constant public static final int BATTERY_STATE_FULL = 3; protected DisplayCapsProxy displayCaps; protected int batteryState; protected double batteryLevel; protected boolean batteryStateReady; protected BroadcastReceiver batteryStateReceiver; public PlatformModule() { super(); batteryState = BATTERY_STATE_UNKNOWN; batteryLevel = -1; } public PlatformModule(TiContext tiContext) { this(); } @Kroll.getProperty @Kroll.method public String getName() { return TiPlatformHelper.getInstance().getName(); } @Kroll.getProperty @Kroll.method public String getOsname() { return TiPlatformHelper.getInstance().getName(); } @Kroll.getProperty @Kroll.method public String getLocale() { return TiPlatformHelper.getInstance().getLocale(); } @Kroll.getProperty @Kroll.method public DisplayCapsProxy getDisplayCaps() { if (displayCaps == null) { displayCaps = new DisplayCapsProxy(); displayCaps.setActivity(TiApplication.getInstance().getCurrentActivity()); } return displayCaps; } @Kroll.getProperty @Kroll.method public int getProcessorCount() { return TiPlatformHelper.getInstance().getProcessorCount(); } @Kroll.getProperty @Kroll.method public String getUsername() { return TiPlatformHelper.getInstance().getUsername(); } @Kroll.getProperty @Kroll.method public String getVersion() { return TiPlatformHelper.getInstance().getVersion(); } @Kroll.getProperty @Kroll.method public double getAvailableMemory() { return TiPlatformHelper.getInstance().getAvailableMemory(); } @Kroll.getProperty @Kroll.method public String getModel() { return TiPlatformHelper.getInstance().getModel(); } @Kroll.getProperty @Kroll.method public String getManufacturer() { return TiPlatformHelper.getInstance().getManufacturer(); } @Kroll.getProperty @Kroll.method public String getOstype() { return TiPlatformHelper.getInstance().getOstype(); } @Kroll.getProperty @Kroll.method public String getArchitecture() { return TiPlatformHelper.getInstance().getArchitecture(); } @Kroll.getProperty @Kroll.method public String getAddress() { return TiPlatformHelper.getInstance().getIpAddress(); } @Kroll.getProperty @Kroll.method public String getNetmask() { return TiPlatformHelper.getInstance().getNetmask(); } @Kroll.method public boolean is24HourTimeFormat() { TiApplication app = TiApplication.getInstance(); if (app != null) { return android.text.format.DateFormat.is24HourFormat(app.getApplicationContext()); } return false; } @Kroll.method public String createUUID() { return TiPlatformHelper.getInstance().createUUID(); } @Kroll.method public boolean openURL(String url) { Log.d(TAG, "Launching viewer for: " + url, Log.DEBUG_MODE); Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); try { Activity activity = TiApplication.getAppRootOrCurrentActivity(); if(activity != null) { activity.startActivity(intent); } else { throw new ActivityNotFoundException("No valid root or current activity found for application instance"); } return true; } catch (ActivityNotFoundException e) { Log.e(TAG,"Activity not found: " + url, e); } return false; } @Kroll.getProperty @Kroll.method public String getMacaddress() { return TiPlatformHelper.getInstance().getMacaddress(); } @Kroll.getProperty @Kroll.method public String getId() { return TiPlatformHelper.getInstance().getMobileId(); } @Kroll.setProperty @Kroll.method public void setBatteryMonitoring(boolean monitor) { if (monitor && batteryStateReceiver == null) { registerBatteryStateReceiver(); } else if (!monitor && batteryStateReceiver != null) { unregisterBatteryStateReceiver(); batteryStateReceiver = null; } } @Kroll.getProperty @Kroll.method public boolean getBatteryMonitoring() { return batteryStateReceiver != null; } @Kroll.getProperty @Kroll.method public int getBatteryState() { return batteryState; } @Kroll.getProperty @Kroll.method public double getBatteryLevel() { return batteryLevel; } @Kroll.getProperty @Kroll.method public String getRuntime() { return KrollRuntime.getInstance().getRuntimeName(); } protected void registerBatteryStateReceiver() { batteryStateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int scale = intent.getIntExtra(TiC.PROPERTY_SCALE, -1); batteryLevel = convertBatteryLevel(intent.getIntExtra(TiC.PROPERTY_LEVEL, -1), scale); batteryState = convertBatteryStatus(intent.getIntExtra(TiC.PROPERTY_STATUS, -1)); KrollDict event = new KrollDict(); event.put(TiC.PROPERTY_LEVEL, batteryLevel); event.put(TiC.PROPERTY_STATE, batteryState); fireEvent(TiC.EVENT_BATTERY, event); } }; registerBatteryReceiver(batteryStateReceiver); } protected void unregisterBatteryStateReceiver() { getActivity().unregisterReceiver(batteryStateReceiver); } @Override public void eventListenerAdded(String type, int count, final KrollProxy proxy) { super.eventListenerAdded(type, count, proxy); if (TiC.EVENT_BATTERY.equals(type) && batteryStateReceiver == null) { registerBatteryStateReceiver(); } } @Override public void eventListenerRemoved(String type, int count, KrollProxy proxy) { super.eventListenerRemoved(type, count, proxy); if (TiC.EVENT_BATTERY.equals(type) && count == 0 && batteryStateReceiver != null) { unregisterBatteryStateReceiver(); batteryStateReceiver = null; } } private int convertBatteryStatus(int status) { int state = BATTERY_STATE_UNKNOWN; switch (status) { case BatteryManager.BATTERY_STATUS_CHARGING: { state = BATTERY_STATE_CHARGING; break; } case BatteryManager.BATTERY_STATUS_FULL: { state = BATTERY_STATE_FULL; break; } case BatteryManager.BATTERY_STATUS_DISCHARGING: case BatteryManager.BATTERY_STATUS_NOT_CHARGING: { state = BATTERY_STATE_UNPLUGGED; break; } } return state; } private double convertBatteryLevel(int level, int scale) { int l = -1; if (level >= 0 && scale > 0) { l = (level * 100) / scale; } return l; } private void registerBatteryReceiver(BroadcastReceiver batteryReceiver) { Activity a = getActivity(); IntentFilter batteryFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); a.registerReceiver(batteryReceiver, batteryFilter); } @Override public void onResume(Activity activity) { super.onResume(activity); if (batteryStateReceiver != null) { Log.i(TAG, "Reregistering battery changed receiver", Log.DEBUG_MODE); registerBatteryReceiver(batteryStateReceiver); } } @Override public void onPause(Activity activity) { super.onPause(activity); if (batteryStateReceiver != null) { unregisterBatteryStateReceiver(); batteryStateReceiver = null; } } @Override public void onDestroy(Activity activity) { super.onDestroy(activity); if (batteryStateReceiver != null) { unregisterBatteryStateReceiver(); batteryStateReceiver = null; } } @Override public String getApiName() { return "Ti.Platform"; } }
package foam.core; import foam.lib.parse.Parser; import java.util.Comparator; import java.util.Map; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; // ???: Why is this interface mutable? public interface PropertyInfo extends foam.mlang.Expr, Comparator { public PropertyInfo setClassInfo(ClassInfo p); public ClassInfo getClassInfo(); public boolean getTransient(); public boolean getRequired(); public String getName(); public Object get(Object obj); public void set(Object obj, Object value); public Parser jsonParser(); public void toJSON(foam.lib.json.Outputter outputter, StringBuilder out, Object value); public void diff(FObject o1, FObject o2, Map diff, PropertyInfo prop); public void setFromString(Object obj, String value); public Object fromXML(X x, XMLStreamReader reader); public void toXML(FObject obj, Document doc, Element objElement); }
#parse("main/Header.vm") package com.nativelibs4java.opencl; import static com.nativelibs4java.opencl.JavaCL.log; import static com.nativelibs4java.opencl.library.OpenCLLibrary.*; import static com.nativelibs4java.opencl.library.IOpenCLLibrary.*; import com.nativelibs4java.opencl.library.OpenCLLibrary; import com.ochafik.util.string.StringUtils; import org.bridj.*; import java.util.*; import java.lang.reflect.*; import java.util.logging.Level; import java.util.logging.Logger; /** * OpenCL error * @author ochafik */ @SuppressWarnings("serial") public class CLException extends RuntimeException { protected int code; CLException(String message, int code) { super(message); this.code = code; } public int getCode() { return code; } @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface ErrorCode { int value(); } public static class CLVersionException extends CLException { public CLVersionException(String message) { super(message, 0); } } public static class CLTypedException extends CLException { protected String message; public CLTypedException() { super("", 0); ErrorCode code = getClass().getAnnotation(ErrorCode.class); this.code = code.value(); this.message = getClass().getSimpleName(); } @Override public String getMessage() { return message + logSuffix; } void setKernelArg(CLKernel kernel, int argIndex, long size, Pointer<?> ptr) { message += " (kernel name = " + kernel.getFunctionName(); message += ", num args = " + kernel.getNumArgs(); message += ", arg index = " + argIndex; message += ", arg size = " + size; CLProgram program = kernel.getProgram(); if (program != null) message += ", source = <<<\n\t" + program.getSource().replaceAll("\n", "\n\t"); message += "\n>>> )"; } } @ErrorCode(CL_DEVICE_PARTITION_FAILED) public static class DevicePartitionFailed extends CLTypedException {} @ErrorCode(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST) public static class ExecStatusErrorForEventsInWaitList extends CLTypedException {} @ErrorCode(CL_MISALIGNED_SUB_BUFFER_OFFSET) public static class MisalignedSubBufferOffset extends CLTypedException {} @ErrorCode(CL_COMPILE_PROGRAM_FAILURE) public static class CompileProgramFailure extends CLTypedException {} @ErrorCode(CL_LINKER_NOT_AVAILABLE) public static class LinkerNotAvailable extends CLTypedException {} @ErrorCode(CL_LINK_PROGRAM_FAILURE) public static class LinkProgramFailure extends CLTypedException {} @ErrorCode(CL_KERNEL_ARG_INFO_NOT_AVAILABLE) public static class KernelArgInfoNotAvailable extends CLTypedException {} @ErrorCode(CL_IMAGE_FORMAT_MISMATCH) public static class ImageFormatMismatch extends CLTypedException {} @ErrorCode(CL_PROFILING_INFO_NOT_AVAILABLE) public static class ProfilingInfoNotAvailable extends CLTypedException {} @ErrorCode(CL_DEVICE_NOT_AVAILABLE) public static class DeviceNotAvailable extends CLTypedException {} @ErrorCode(CL_OUT_OF_RESOURCES) public static class OutOfResources extends CLTypedException {} @ErrorCode(CL_COMPILER_NOT_AVAILABLE) public static class CompilerNotAvailable extends CLTypedException {} @ErrorCode(CL_INVALID_GLOBAL_WORK_SIZE) public static class InvalidGlobalWorkSize extends CLTypedException {} @ErrorCode(CL_MAP_FAILURE) public static class MapFailure extends CLTypedException {} @ErrorCode(CL_MEM_OBJECT_ALLOCATION_FAILURE) public static class MemObjectAllocationFailure extends CLTypedException {} @ErrorCode(CL_INVALID_EVENT_WAIT_LIST) public static class InvalidEventWaitList extends CLTypedException {} @ErrorCode(CL_INVALID_ARG_INDEX) public static class InvalidArgIndex extends CLTypedException {} @ErrorCode(CL_INVALID_ARG_SIZE) public static class InvalidArgSize extends CLTypedException {} @ErrorCode(CL_INVALID_ARG_VALUE) public static class InvalidArgValue extends CLTypedException {} @ErrorCode(CL_INVALID_BINARY) public static class InvalidBinary extends CLTypedException {} @ErrorCode(CL_INVALID_EVENT) public static class InvalidEvent extends CLTypedException {} @ErrorCode(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR) public static class InvalidImageFormatDescriptor extends CLTypedException {} @ErrorCode(CL_INVALID_IMAGE_SIZE) public static class InvalidImageSize extends CLTypedException {} @ErrorCode(CL_INVALID_WORK_DIMENSION) public static class InvalidWorkDimension extends CLTypedException {} @ErrorCode(CL_INVALID_WORK_GROUP_SIZE) public static class InvalidWorkGroupSize extends CLTypedException {} @ErrorCode(CL_INVALID_WORK_ITEM_SIZE) public static class InvalidWorkItemSize extends CLTypedException {} @ErrorCode(CL_INVALID_OPERATION) public static class InvalidOperation extends CLTypedException {} @ErrorCode(CL_INVALID_BUFFER_SIZE) public static class InvalidBufferSize extends CLTypedException {} @ErrorCode(CL_INVALID_GLOBAL_OFFSET) public static class InvalidGlobalOffset extends CLTypedException {} @ErrorCode(CL_OUT_OF_HOST_MEMORY) public static class OutOfHostMemory extends CLTypedException {} @ErrorCode(CL_INVALID_COMPILER_OPTIONS) public static class InvalidCompilerOptions extends CLTypedException {} @ErrorCode(CL_INVALID_DEVICE) public static class InvalidDevice extends CLTypedException {} @ErrorCode(CL_INVALID_DEVICE_PARTITION_COUNT) public static class InvalidDevicePartitionCount extends CLTypedException {} @ErrorCode(CL_INVALID_HOST_PTR) public static class InvalidHostPtr extends CLTypedException {} @ErrorCode(CL_INVALID_IMAGE_DESCRIPTOR) public static class InvalidImageDescriptor extends CLTypedException {} @ErrorCode(CL_INVALID_LINKER_OPTIONS) public static class InvalidLinkerOptions extends CLTypedException {} @ErrorCode(CL_INVALID_PLATFORM) public static class InvalidPlatform extends CLTypedException {} @ErrorCode(CL_INVALID_PROPERTY) public static class InvalidProperty extends CLTypedException {} @ErrorCode(CL_INVALID_COMMAND_QUEUE) public static class InvalidCommandQueue extends CLTypedException {} @ErrorCode(CL_MEM_COPY_OVERLAP) public static class MemCopyOverlap extends CLTypedException {} @ErrorCode(CL_INVALID_CONTEXT) public static class InvalidContext extends CLTypedException {} @ErrorCode(CL_INVALID_KERNEL) public static class InvalidKernel extends CLTypedException {} @ErrorCode(CL_INVALID_GL_CONTEXT_APPLE) public static class InvalidGLContextApple extends CLTypedException {} @ErrorCode(CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR) public static class InvalidGLShareGroupReference extends CLTypedException {} @ErrorCode(CL_INVALID_GL_OBJECT) public static class InvalidGLObject extends CLTypedException {} @ErrorCode(CL_INVALID_KERNEL_ARGS) public static class InvalidKernelArgs extends CLTypedException {} @ErrorCode(CL_INVALID_KERNEL_DEFINITION) public static class InvalidKernelDefinition extends CLTypedException {} @ErrorCode(CL_INVALID_KERNEL_NAME) public static class InvalidKernelName extends CLTypedException {} @ErrorCode(CL_INVALID_MEM_OBJECT) public static class InvalidMemObject extends CLTypedException {} @ErrorCode(CL_INVALID_MIP_LEVEL) public static class InvalidMipLevel extends CLTypedException {} @ErrorCode(CL_INVALID_PROGRAM) public static class InvalidProgram extends CLTypedException {} @ErrorCode(CL_INVALID_PROGRAM_EXECUTABLE) public static class InvalidProgramExecutable extends CLTypedException {} @ErrorCode(CL_INVALID_QUEUE_PROPERTIES) public static class InvalidQueueProperties extends CLTypedException {} @ErrorCode(CL_INVALID_VALUE) public static class InvalidValue extends CLTypedException {} @ErrorCode(CL_INVALID_SAMPLER) public static class InvalidSampler extends CLTypedException {} @ErrorCode(CL_INVALID_DEVICE_TYPE) public static class InvalidDeviceType extends CLTypedException {} @ErrorCode(CL_INVALID_BUILD_OPTIONS) public static class InvalidBuildOptions extends CLTypedException {} @ErrorCode(CL_BUILD_PROGRAM_FAILURE) public static class BuildProgramFailure extends CLTypedException {} public static String errorString(int err) { if (err == CL_SUCCESS) return null; List<String> candidates = new ArrayList<String>(); for (Field f : OpenCLLibrary.class.getDeclaredFields()) { if (!Modifier.isStatic(f.getModifiers())) { continue; } if (f.getType().equals(Integer.TYPE)) { try { int i = (Integer) f.get(null); if (i == err) { String name = f.getName(), lname = name.toLowerCase(); if (lname.contains("invalid") || lname.contains("bad") || lname.contains("illegal") || lname.contains("wrong")) { candidates.clear(); candidates.add(name); break; } else candidates.add(name); } } catch (Exception e) { e.printStackTrace(); } } } return StringUtils.implode(candidates, " or "); } static boolean failedForLackOfMemory(int err, int previousAttempts) { switch (err) { case CL_SUCCESS: return false; case CL_OUT_OF_HOST_MEMORY: case CL_OUT_OF_RESOURCES: case CL_MEM_OBJECT_ALLOCATION_FAILURE: if (previousAttempts <= 1) { System.gc(); if (previousAttempts == 1) { try { Thread.sleep(100); } catch (InterruptedException ex) {} } return true; } default: error(err); assert false; // won't reach return false; } } static final String logSuffix = System.getenv("CL_LOG_ERRORS") == null ? " (make sure to log all errors with environment variable CL_LOG_ERRORS=stdout)" : ""; static Map<Integer, Class<? extends CLTypedException>> typedErrorClassesByCode; @SuppressWarnings("unchecked") public static void error(int err) { if (err == CL_SUCCESS) return; if (typedErrorClassesByCode == null) { typedErrorClassesByCode = new HashMap<Integer, Class<? extends CLTypedException>>(); for (Class<?> c : CLException.class.getDeclaredClasses()) { if (c == CLTypedException.class || !CLTypedException.class.isAssignableFrom(c)) continue; typedErrorClassesByCode.put(c.getAnnotation(ErrorCode.class).value(), (Class<? extends CLTypedException>)c); } } CLException toThrow = null; Class<? extends CLTypedException> c = typedErrorClassesByCode.get(err); if (c != null) { try { toThrow = c.newInstance(); } catch (InstantiationException ex) { assert log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { assert log(Level.SEVERE, null, ex); } } if (toThrow == null) toThrow = new CLException("OpenCL Error : " + errorString(err) + logSuffix, err); throw toThrow; } }
package org.zalando.nakadi.service; import org.springframework.web.util.UriComponentsBuilder; import org.zalando.nakadi.domain.PaginationLinks; import org.zalando.nakadi.repository.db.SubscriptionTokenLister; import java.util.Optional; import java.util.Set; public class SubscriptionsUriHelper { public static PaginationLinks.Link createSubscriptionListLink( final Optional<String> owningApplication, final Set<String> eventTypes, final int offset, final Optional<SubscriptionTokenLister.Token> token, final int limit, final boolean showStatus) { final UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromPath("/subscriptions"); if (!eventTypes.isEmpty()) { urlBuilder.queryParam("event_type", eventTypes.toArray()); } owningApplication.ifPresent(owningApp -> urlBuilder.queryParam("owning_application", owningApp)); if (showStatus) { urlBuilder.queryParam("show_status", "true"); } if (token.isPresent()) { urlBuilder.queryParam("token", token.get().encode()); } else { urlBuilder.queryParam("offset", offset); } return new PaginationLinks.Link(urlBuilder .queryParam("limit", limit) .build() .toString()); } }
package info.nightscout.androidaps.plugins.Wear; import android.os.Handler; import android.os.HandlerThread; import android.support.annotation.NonNull; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.LinkedList; import java.util.List; import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.DanaRHistoryRecord; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.DanaRInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.Actions.dialogs.FillDialog; import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.ProfileCircadianPercentage.CircadianPercentageProfilePlugin; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin; import info.nightscout.utils.BolusWizard; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; import info.nightscout.utils.ToastUtils; public class ActionStringHandler { public static final int TIMEOUT = 65 * 1000; private static long lastSentTimestamp = 0; private static String lastConfirmActionString = null; private static BolusWizard lastBolusWizard = null; private static HandlerThread handlerThread = new HandlerThread(FillDialog.class.getSimpleName()); static { handlerThread.start(); } public synchronized static void handleInitiate(String actionstring) { if (!BuildConfig.WEAR_CONTROL) return; lastBolusWizard = null; String rTitle = "CONFIRM"; //TODO: i18n String rMessage = ""; String rAction = ""; // do the parsing and check constraints String[] act = actionstring.split("\\s+"); if ("fillpreset".equals(act[0])) { ///////////////////////////////////// PRIME/FILL double amount = 0d; if ("1".equals(act[1])) { amount = SP.getDouble("fill_button1", 0.3); } else if ("2".equals(act[1])) { amount = SP.getDouble("fill_button2", 0d); } else if ("3".equals(act[1])) { amount = SP.getDouble("fill_button3", 0d); } else { return; } Double insulinAfterConstraints = MainApp.getConfigBuilder().applyBolusConstraints(amount); rMessage += MainApp.instance().getString(R.string.primefill) + ": " + insulinAfterConstraints + "U"; if (insulinAfterConstraints - amount != 0) rMessage += "\n" + MainApp.instance().getString(R.string.constraintapllied); rAction += "fill " + insulinAfterConstraints; } else if ("fill".equals(act[0])) { ////////////////////////////////////////////// PRIME/FILL double amount = SafeParse.stringToDouble(act[1]); Double insulinAfterConstraints = MainApp.getConfigBuilder().applyBolusConstraints(amount); rMessage += MainApp.instance().getString(R.string.primefill) + ": " + insulinAfterConstraints + "U"; if (insulinAfterConstraints - amount != 0) rMessage += "\n" + MainApp.instance().getString(R.string.constraintapllied); rAction += "fill " + insulinAfterConstraints; } else if ("bolus".equals(act[0])) { ////////////////////////////////////////////// BOLUS double insulin = SafeParse.stringToDouble(act[1]); int carbs = SafeParse.stringToInt(act[2]); Double insulinAfterConstraints = MainApp.getConfigBuilder().applyBolusConstraints(insulin); Integer carbsAfterConstraints = MainApp.getConfigBuilder().applyCarbsConstraints(carbs); rMessage += MainApp.instance().getString(R.string.bolus) + ": " + insulinAfterConstraints + "U\n"; rMessage += MainApp.instance().getString(R.string.carbs) + ": " + carbsAfterConstraints + "g"; if ((insulinAfterConstraints - insulin != 0) || (carbsAfterConstraints - carbs != 0)) { rMessage += "\n" + MainApp.instance().getString(R.string.constraintapllied); } rAction += "bolus " + insulinAfterConstraints + " " + carbsAfterConstraints; } else if ("temptarget".equals(act[0])) { ///////////////////////////////////////////////////////// TEMPTARGET boolean isMGDL = Boolean.parseBoolean(act[1]); Profile profile = MainApp.getConfigBuilder().getProfile(); if (profile == null) { sendError("No profile found!"); return; } if (profile.getUnits().equals(Constants.MGDL) != isMGDL) { sendError("Different units used on watch and phone!"); return; } int duration = SafeParse.stringToInt(act[2]); if (duration == 0) { rMessage += "Zero-Temp-Target - cancelling running Temp-Targets?"; rAction = "temptarget true 0 0 0"; } else { double low = SafeParse.stringToDouble(act[3]); double high = SafeParse.stringToDouble(act[4]); if (!isMGDL) { low *= Constants.MMOLL_TO_MGDL; high *= Constants.MMOLL_TO_MGDL; } if (low < Constants.VERY_HARD_LIMIT_TEMP_MIN_BG[0] || low > Constants.VERY_HARD_LIMIT_TEMP_MIN_BG[1]) { sendError("Min-BG out of range!"); return; } if (high < Constants.VERY_HARD_LIMIT_TEMP_MAX_BG[0] || high > Constants.VERY_HARD_LIMIT_TEMP_MAX_BG[1]) { sendError("Max-BG out of range!"); return; } rMessage += "Temptarget:\nMin: " + act[3] + "\nMax: " + act[4] + "\nDuration: " + act[2]; rAction = actionstring; } } else if ("status".equals(act[0])) { ////////////////////////////////////////////// STATUS rTitle = "STATUS"; rAction = "statusmessage"; if ("pump".equals(act[1])) { rTitle += " PUMP"; rMessage = getPumpStatus(); } else if ("loop".equals(act[1])) { rTitle += " LOOP"; rMessage = "TARGETS:\n" + getTargetsStatus(); rMessage += "\n\n" + getLoopStatus(); rMessage += "\n\nOAPS RESULT:\n" + getOAPSResultStatus();; } } else if ("wizard".equals(act[0])) { ////////////////////////////////////////////// WIZARD Integer carbsBeforeConstraints = SafeParse.stringToInt(act[1]); Integer carbsAfterConstraints = MainApp.getConfigBuilder().applyCarbsConstraints(carbsBeforeConstraints); if (carbsAfterConstraints - carbsBeforeConstraints != 0) { sendError("Carb constraint violation!"); return; } boolean useBG = Boolean.parseBoolean(act[2]); boolean useBolusIOB = Boolean.parseBoolean(act[3]); boolean useBasalIOB = Boolean.parseBoolean(act[4]); Profile profile = MainApp.getConfigBuilder().getProfile(); if (profile == null) { sendError("No profile found!"); return; } BgReading bgReading = DatabaseHelper.actualBg(); if (bgReading == null && useBG) { sendError("No recent BG to base calculation on!"); return; } DecimalFormat format = new DecimalFormat("0.00"); BolusWizard bolusWizard = new BolusWizard(); bolusWizard.doCalc(profile, carbsAfterConstraints, 0d, useBG ? bgReading.valueToUnits(profile.getUnits()) : 0d, 0d, useBolusIOB, useBasalIOB, false, false); Double insulinAfterConstraints = MainApp.getConfigBuilder().applyBolusConstraints(bolusWizard.calculatedTotalInsulin); if (insulinAfterConstraints - bolusWizard.calculatedTotalInsulin != 0) { sendError("Insulin contraint violation!" + "\nCannot deliver " + format.format(bolusWizard.calculatedTotalInsulin) + "!"); return; } if (bolusWizard.calculatedTotalInsulin < 0) { bolusWizard.calculatedTotalInsulin = 0d; } if (bolusWizard.calculatedTotalInsulin <= 0 && bolusWizard.carbs <= 0) { rAction = "info"; rTitle = "INFO"; } else { rAction = actionstring; } rMessage += "Carbs: " + bolusWizard.carbs + "g"; rMessage += "\nBolus: " + format.format(bolusWizard.calculatedTotalInsulin) + "U"; rMessage += "\n_____________"; rMessage += "\nCalc (IC:" + DecimalFormatter.to1Decimal(bolusWizard.ic) + ", " + "ISF:" + DecimalFormatter.to1Decimal(bolusWizard.sens) + "): "; rMessage += "\nFrom Carbs: " + format.format(bolusWizard.insulinFromCarbs) + "U"; if (useBG) rMessage += "\nFrom BG: " + format.format(bolusWizard.insulinFromBG) + "U"; if (useBolusIOB) rMessage += "\nBolus IOB: " + format.format(bolusWizard.insulingFromBolusIOB) + "U"; if (useBasalIOB) rMessage += "\nBasal IOB: " + format.format(bolusWizard.insulingFromBasalsIOB) + "U"; lastBolusWizard = bolusWizard; } else if("opencpp".equals(act[0])){ Object activeProfile = MainApp.getConfigBuilder().getActiveProfileInterface(); CircadianPercentageProfilePlugin cpp = (CircadianPercentageProfilePlugin) MainApp.getSpecificPlugin(CircadianPercentageProfilePlugin.class); if(cpp == null || activeProfile==null || cpp != activeProfile){ sendError("CPP not activated!"); return; } else { // read CPP values rTitle = "opencpp"; rMessage = "opencpp"; rAction = "opencpp" + " " + cpp.getPercentage() + " " + cpp.getTimeshift(); } } else if("cppset".equals(act[0])){ Object activeProfile = MainApp.getConfigBuilder().getActiveProfileInterface(); CircadianPercentageProfilePlugin cpp = (CircadianPercentageProfilePlugin) MainApp.getSpecificPlugin(CircadianPercentageProfilePlugin.class); if(cpp == null || activeProfile==null || cpp != activeProfile){ sendError("CPP not activated!"); return; } else { // read CPP values rMessage = "CPP:" + "\n\n"+ "Timeshift: " + act[1] + "\n" + "Percentage: " + act[2] + "%"; rAction = actionstring; } } else if("tddstats".equals(act[0])){ Object activePump = MainApp.getConfigBuilder().getActivePump(); PumpInterface dana = (PumpInterface) MainApp.getSpecificPlugin(DanaRPlugin.class); PumpInterface danaV2 = (PumpInterface) MainApp.getSpecificPlugin(DanaRv2Plugin.class); PumpInterface danaKorean = (PumpInterface) MainApp.getSpecificPlugin(DanaRKoreanPlugin.class); if((dana == null || dana != activePump) && (danaV2 == null || danaV2 != activePump) && (danaKorean == null || danaKorean != activePump) ){ sendError("Pump does not support TDDs!"); return; } else { // check if DB up to date List<DanaRHistoryRecord> dummies = new LinkedList<DanaRHistoryRecord>(); List<DanaRHistoryRecord> historyList = getTDDList(dummies); if(isOldData(historyList)){ rTitle = "TDD"; rAction = "statusmessage"; rMessage = "OLD DATA - "; //if pump is not busy: try to fetch data final PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); if (pump.isBusy()) { rMessage += MainApp.instance().getString(R.string.pumpbusy); } else { rMessage += "trying to fetch data from pump."; Handler handler = new Handler(handlerThread.getLooper()); handler.post(new Runnable() { @Override public void run() { ((DanaRInterface)pump).loadHistory(RecordTypes.RECORD_TYPE_DAILY); List<DanaRHistoryRecord> dummies = new LinkedList<DanaRHistoryRecord>(); List<DanaRHistoryRecord> historyList = getTDDList(dummies); if(isOldData(historyList)){ sendStatusmessage("TDD", "TDD: Still old data! Cannot load from pump."); } else { sendStatusmessage("TDD", generateTDDMessage(historyList, dummies)); } } }); } } else { rTitle = "TDD"; rAction = "statusmessage"; rMessage = generateTDDMessage(historyList, dummies); } } } else return; // send result WearFragment.getPlugin(MainApp.instance()).requestActionConfirmation(rTitle, rMessage, rAction); lastSentTimestamp = System.currentTimeMillis(); lastConfirmActionString = rAction; } private static String generateTDDMessage(List<DanaRHistoryRecord> historyList, List<DanaRHistoryRecord> dummies) { DateFormat df = new SimpleDateFormat("dd.MM."); String message = ""; CircadianPercentageProfilePlugin cpp = (CircadianPercentageProfilePlugin) MainApp.getSpecificPlugin(CircadianPercentageProfilePlugin.class); boolean isCPP = (cpp!= null && cpp.isEnabled(PluginBase.PROFILE)); double refTDD = 100; if(isCPP) refTDD = cpp.baseBasalSum()*2; int i = 0; double sum = 0d; double weighted03 = 0d; double weighted05 = 0d; double weighted07 = 0d; Collections.reverse(historyList); for (DanaRHistoryRecord record : historyList) { double tdd = record.recordDailyBolus + record.recordDailyBasal; if (i == 0) { weighted03 = tdd; weighted05 = tdd; weighted07 = tdd; } else { weighted07 = (weighted07 * 0.3 + tdd * 0.7); weighted05 = (weighted05 * 0.5 + tdd * 0.5); weighted03 = (weighted03 * 0.7 + tdd * 0.3); } i++; } message += "weighted:\n"; message += "0.3: " + DecimalFormatter.to2Decimal(weighted03) + "U " + (isCPP?(DecimalFormatter.to0Decimal(100*weighted03/refTDD) + "%"):"") + "\n"; message += "0.5: " + DecimalFormatter.to2Decimal(weighted05) + "U " + (isCPP?(DecimalFormatter.to0Decimal(100*weighted05/refTDD) + "%"):"") + "\n"; message += "0.7: " + DecimalFormatter.to2Decimal(weighted07) + "U " + (isCPP?(DecimalFormatter.to0Decimal(100*weighted07/refTDD) + "%"):"") + "\n"; message += "\n"; PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); if (pump != null && pump instanceof DanaRPlugin) { double tdd = DanaRPump.getInstance().dailyTotalUnits; message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (isCPP?(DecimalFormatter.to0Decimal(100*tdd/refTDD) + "%"):"") + "\n"; message += "\n"; } //add TDDs: Collections.reverse(historyList); for (DanaRHistoryRecord record : historyList) { double tdd = record.recordDailyBolus + record.recordDailyBasal; message += df.format(new Date(record.recordDate)) + " " + DecimalFormatter.to2Decimal(tdd) +"U " + (isCPP?(DecimalFormatter.to0Decimal(100*tdd/refTDD) + "%"):"") + (dummies.contains(record)?"x":"") +"\n"; } return message; } public static boolean isOldData(List<DanaRHistoryRecord> historyList) { DateFormat df = new SimpleDateFormat("dd.MM."); return (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).recordDate)).equals(df.format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24))))); } @NonNull public static List<DanaRHistoryRecord> getTDDList(List<DanaRHistoryRecord> returnDummies) { List<DanaRHistoryRecord> historyList = MainApp.getDbHelper().getDanaRHistoryRecordsByType(RecordTypes.RECORD_TYPE_DAILY); //only use newest 10 historyList = historyList.subList(0, Math.min(10, historyList.size())); //fill single gaps List<DanaRHistoryRecord> dummies = (returnDummies!=null)?returnDummies:(new LinkedList()); DateFormat df = new SimpleDateFormat("dd.MM."); for(int i = 0; i < historyList.size()-1; i++){ DanaRHistoryRecord elem1 = historyList.get(i); DanaRHistoryRecord elem2 = historyList.get(i+1); if (!df.format(new Date(elem1.recordDate)).equals(df.format(new Date(elem2.recordDate + 25*60*60*1000)))){ DanaRHistoryRecord dummy = new DanaRHistoryRecord(); dummy.recordDate = elem1.recordDate - 24*60*60*1000; dummy.recordDailyBasal = elem1.recordDailyBasal/2; dummy.recordDailyBolus = elem1.recordDailyBolus/2; dummies.add(dummy); elem1.recordDailyBasal /= 2; elem1.recordDailyBolus /= 2; } } historyList.addAll(dummies); Collections.sort(historyList, new Comparator<DanaRHistoryRecord>() { @Override public int compare(DanaRHistoryRecord lhs, DanaRHistoryRecord rhs) { return (int) (rhs.recordDate-lhs.recordDate); } }); return historyList; } @NonNull private static String getPumpStatus() { return MainApp.getConfigBuilder().shortStatus(false); } @NonNull private static String getLoopStatus() { String ret = ""; // decide if enabled/disabled closed/open; what Plugin as APS? final LoopPlugin activeloop = MainApp.getConfigBuilder().getActiveLoop(); if (activeloop != null && activeloop.isEnabled(activeloop.getType())) { if (MainApp.getConfigBuilder().isClosedModeEnabled()) { ret += "CLOSED LOOP\n"; } else { ret += "OPEN LOOP\n"; } final APSInterface aps = MainApp.getConfigBuilder().getActiveAPS(); ret += "APS: " + ((aps == null) ? "NO APS SELECTED!" : ((PluginBase) aps).getName()); if (activeloop.lastRun != null) { if (activeloop.lastRun.lastAPSRun != null) ret += "\nLast Run: " + DateUtil.timeString(activeloop.lastRun.lastAPSRun); if (activeloop.lastRun.lastEnact != null) ret += "\nLast Enact: " + DateUtil.timeString(activeloop.lastRun.lastEnact); } } else { ret += "LOOP DISABLED\n"; } return ret; } @NonNull private static String getTargetsStatus() { String ret = ""; if (!Config.APS) { return "Targets only apply in APS mode!"; } Profile profile = MainApp.getConfigBuilder().getProfile(); if (profile == null) { return "No profile set :("; } //Check for Temp-Target: TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory(System.currentTimeMillis()); if (tempTarget != null) { ret += "Temp Target: " + Profile.toUnitsString(tempTarget.low, Profile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits()) + " - " + Profile.toUnitsString(tempTarget.high, Profile.fromMgdlToUnits(tempTarget.high, profile.getUnits()), profile.getUnits()); ret += "\nuntil: " + DateUtil.timeString(tempTarget.originalEnd()); ret += "\n\n"; } //Default Range/Target Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; Double minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; Double targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL; if (!profile.getUnits().equals(Constants.MGDL)) { maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL; minBgDefault = Constants.MIN_BG_DEFAULT_MMOL; targetBgDefault = Constants.TARGET_BG_DEFAULT_MMOL; } ret += "DEFAULT RANGE: "; ret += SP.getDouble("openapsma_min_bg", minBgDefault) + " - " + SP.getDouble("openapsma_max_bg", maxBgDefault); ret += " target: " + SP.getDouble("openapsma_target_bg", targetBgDefault); return ret; } private static String getOAPSResultStatus() { String ret = ""; if (!Config.APS) { return "Only apply in APS mode!"; } Profile profile = MainApp.getConfigBuilder().getProfile(); if (profile == null) { return "No profile set :("; } APSInterface usedAPS = MainApp.getConfigBuilder().getActiveAPS(); if (usedAPS == null) { return "No active APS :(!"; } APSResult result = usedAPS.getLastAPSResult(); if (result == null) { return "Last result not available!"; } if (!result.changeRequested) { ret += MainApp.sResources.getString(R.string.nochangerequested) + "\n"; } else if (result.rate == 0 && result.duration == 0) { ret += MainApp.sResources.getString(R.string.canceltemp)+ "\n"; } else { ret += MainApp.sResources.getString(R.string.rate) + ": " + DecimalFormatter.to2Decimal(result.rate) + " U/h " + "(" + DecimalFormatter.to2Decimal(result.rate / MainApp.getConfigBuilder().getBaseBasalRate() * 100) + "%)\n" + MainApp.sResources.getString(R.string.duration) + ": " + DecimalFormatter.to0Decimal(result.duration) + " min\n"; } ret += "\n" + MainApp.sResources.getString(R.string.reason) + ": " + result.reason; return ret; } public synchronized static void handleConfirmation(String actionString) { if (!BuildConfig.WEAR_CONTROL) return; //Guard from old or duplicate confirmations if (lastConfirmActionString == null) return; if (!lastConfirmActionString.equals(actionString)) return; if (System.currentTimeMillis() - lastSentTimestamp > TIMEOUT) return; lastConfirmActionString = null; // do the parsing, check constraints and enact! String[] act = actionString.split("\\s+"); if ("fill".equals(act[0])) { Double amount = SafeParse.stringToDouble(act[1]); Double insulinAfterConstraints = MainApp.getConfigBuilder().applyBolusConstraints(amount); if (amount - insulinAfterConstraints != 0) { ToastUtils.showToastInUiThread(MainApp.instance(), "aborting: previously applied constraint changed"); sendError("aborting: previously applied constraint changed"); return; } doFillBolus(amount); } else if ("temptarget".equals(act[0])) { int duration = SafeParse.stringToInt(act[2]); double low = SafeParse.stringToDouble(act[3]); double high = SafeParse.stringToDouble(act[4]); boolean isMGDL = Boolean.parseBoolean(act[1]); if (!isMGDL) { low *= Constants.MMOLL_TO_MGDL; high *= Constants.MMOLL_TO_MGDL; } generateTempTarget(duration, low, high); } else if ("wizard".equals(act[0])) { //use last calculation as confirmed string matches doBolus(lastBolusWizard.calculatedTotalInsulin, lastBolusWizard.carbs); lastBolusWizard = null; } else if ("bolus".equals(act[0])) { double insulin = SafeParse.stringToDouble(act[1]); int carbs = SafeParse.stringToInt(act[2]); doBolus(insulin, carbs); } else if ("cppset".equals(act[0])) { int timeshift = SafeParse.stringToInt(act[1]); int percentage = SafeParse.stringToInt(act[2]); setCPP(percentage, timeshift); } else if ("dismissoverviewnotification".equals(act[0])){ MainApp.bus().post(new EventDismissNotification(SafeParse.stringToInt(act[1]))); } lastBolusWizard = null; } private static void setCPP(int percentage, int timeshift) { Object activeProfile = MainApp.getConfigBuilder().getActiveProfileInterface(); CircadianPercentageProfilePlugin cpp = (CircadianPercentageProfilePlugin) MainApp.getSpecificPlugin(CircadianPercentageProfilePlugin.class); if(cpp == null || activeProfile==null || cpp != activeProfile){ sendError("CPP not activated!"); return; } String msg = cpp.externallySetParameters(timeshift, percentage); if(msg != null && !"".equals(msg)){ String rTitle = "STATUS"; String rAction = "statusmessage"; WearFragment.getPlugin(MainApp.instance()).requestActionConfirmation(rTitle, msg, rAction); lastSentTimestamp = System.currentTimeMillis(); lastConfirmActionString = rAction; } } private static void generateTempTarget(int duration, double low, double high) { TempTarget tempTarget = new TempTarget(); tempTarget.date = System.currentTimeMillis(); tempTarget.durationInMinutes = duration; tempTarget.reason = "WearPlugin"; tempTarget.source = Source.USER; if (tempTarget.durationInMinutes != 0) { tempTarget.low = low; tempTarget.high = high; } else { tempTarget.low = 0; tempTarget.high = 0; } MainApp.getDbHelper().createOrUpdate(tempTarget); //TODO: Nightscout-Treatment for Temp-Target! //ConfigBuilderPlugin.uploadCareportalEntryToNS(data); } private static void doFillBolus(final Double amount) { //if(1==1)return; Handler handler = new Handler(handlerThread.getLooper()); handler.post(new Runnable() { @Override public void run() { DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); detailedBolusInfo.insulin = amount; detailedBolusInfo.addToTreatments = false; detailedBolusInfo.source = Source.USER; PumpEnactResult result = MainApp.getConfigBuilder().deliverTreatment(detailedBolusInfo); if (!result.success) { sendError(MainApp.sResources.getString(R.string.treatmentdeliveryerror) + "\n" + result.comment); } } }); } private static void doBolus(final Double amount, final Integer carbs) { //if(1==1)return; Handler handler = new Handler(handlerThread.getLooper()); handler.post(new Runnable() { @Override public void run() { DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); detailedBolusInfo.insulin = amount; detailedBolusInfo.carbs = carbs; detailedBolusInfo.source = Source.USER; PumpEnactResult result = MainApp.getConfigBuilder().deliverTreatment(detailedBolusInfo); if (!result.success) { sendError(MainApp.sResources.getString(R.string.treatmentdeliveryerror) + "\n" + result.comment); } } }); } private synchronized static void sendError(String errormessage) { WearFragment.getPlugin(MainApp.instance()).requestActionConfirmation("ERROR", errormessage, "error"); lastSentTimestamp = System.currentTimeMillis(); lastConfirmActionString = null; lastBolusWizard = null; } private synchronized static void sendStatusmessage(String title, String message) { WearFragment.getPlugin(MainApp.instance()).requestActionConfirmation(title, message, "statusmessage"); lastSentTimestamp = System.currentTimeMillis(); lastConfirmActionString = null; lastBolusWizard = null; } public synchronized static void expectNotificationAction(String message, int id) { String actionstring = "dismissoverviewnotification " + id; WearFragment.getPlugin(MainApp.instance()).requestActionConfirmation("DISMISS", message, actionstring); lastSentTimestamp = System.currentTimeMillis(); lastConfirmActionString = actionstring; lastBolusWizard = null; } }
package org.apache.jmeter.save.converters; import java.net.URLDecoder; import java.net.URLEncoder; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; /** * @author mstover * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class ConversionHelp { private static final String CHAR_SET = "UTF-8"; transient private static final Logger log = LoggingManager.getLoggerForClass(); public static String encode(String p) { try { String p1 = URLEncoder.encode(p,CHAR_SET); return p1; } catch (Exception e) { log.warn("System doesn't support utf-8",e); return p; } } public static String decode(String p) { try { return URLDecoder.decode(p,CHAR_SET); } catch (Exception e) { log.warn("System doesn't support utf-8",e); return p; } } }
package org.approvaltests.writers; import java.io.File; import java.sql.ResultSet; import org.approvaltests.core.ApprovalWriter; import com.spun.util.database.ResultSetWriter; import com.spun.util.io.FileUtils; import com.spun.util.velocity.ContextAware; import com.spun.util.velocity.ContextAware.ContextAwareMap; import com.spun.util.velocity.VelocityParser; public class ResultSetApprovalWriter implements ApprovalWriter { private final ResultSet resultSet; public ResultSetApprovalWriter(ResultSet resultSet) { this.resultSet = resultSet; } @Override public String getApprovalFilename(String base) { return base + Writer.approved + ".csv"; } @Override public String getReceivedFilename(String base) { return base + Writer.received + ".csv"; } @Override public String writeReceivedFile(String received) { String template = "#foreach ($row in $commons.asArray($metaData))$row.get()#if (!$row.isLast()),#end#end\n" + "\n" + "#foreach ($row in $results)\n" + "#foreach ($column in $commons.asArray($row))$commons.asExcel($column.get())#if (!$column.isLast()),#end#end \n" + "\n" + "#end "; ContextAwareMap map = new ContextAware.ContextAwareMap("metaData", ResultSetWriter.extractMetaData(resultSet)); map.put("results", ResultSetWriter.extractResults(resultSet)); String output = VelocityParser.parseString(template, map); FileUtils.writeFile(new File(received), output); return received; } }
package org.ovirt.engine.core.bll; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.bll.context.CompensationContext; import org.ovirt.engine.core.bll.network.macpoolmanager.MacPoolManagerStrategy; import org.ovirt.engine.core.bll.utils.PermissionSubject; import org.ovirt.engine.core.bll.utils.VmDeviceUtils; import org.ovirt.engine.core.bll.validator.VmValidationUtils; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.FeatureSupported; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VmManagementParametersBase; import org.ovirt.engine.core.common.backendinterfaces.BaseHandler; import org.ovirt.engine.core.common.businessentities.ActionGroup; import org.ovirt.engine.core.common.businessentities.ArchitectureType; import org.ovirt.engine.core.common.businessentities.CopyOnNewVersion; import org.ovirt.engine.core.common.businessentities.DisplayType; import org.ovirt.engine.core.common.businessentities.EditableDeviceOnVmStatusField; import org.ovirt.engine.core.common.businessentities.EditableField; import org.ovirt.engine.core.common.businessentities.EditableOnVm; import org.ovirt.engine.core.common.businessentities.EditableOnVmStatusField; import org.ovirt.engine.core.common.businessentities.GraphicsDevice; import org.ovirt.engine.core.common.businessentities.GraphicsType; import org.ovirt.engine.core.common.businessentities.GuestAgentStatus; import org.ovirt.engine.core.common.businessentities.Snapshot; import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType; import org.ovirt.engine.core.common.businessentities.UsbPolicy; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VmBase; import org.ovirt.engine.core.common.businessentities.VmDevice; import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType; import org.ovirt.engine.core.common.businessentities.VmDynamic; import org.ovirt.engine.core.common.businessentities.VmInit; import org.ovirt.engine.core.common.businessentities.VmNumaNode; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.common.businessentities.network.VmNic; import org.ovirt.engine.core.common.businessentities.storage.CinderDisk; import org.ovirt.engine.core.common.businessentities.storage.Disk; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.businessentities.storage.DiskInterface; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.errors.EngineError; import org.ovirt.engine.core.common.errors.EngineException; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.common.locks.LockingGroup; import org.ovirt.engine.core.common.osinfo.OsRepository; import org.ovirt.engine.core.common.queries.NameQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryReturnValue; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.utils.SimpleDependecyInjector; import org.ovirt.engine.core.common.utils.VmDeviceType; import org.ovirt.engine.core.common.utils.VmDeviceUpdate; import org.ovirt.engine.core.common.vdscommands.SetVmStatusVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.UpdateVmDynamicDataVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.RpmVersion; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase; import org.ovirt.engine.core.dao.VdsDynamicDao; import org.ovirt.engine.core.dao.VmInitDao; import org.ovirt.engine.core.dao.VmNumaNodeDao; import org.ovirt.engine.core.utils.ObjectIdentityChecker; import org.ovirt.engine.core.utils.linq.LinqUtils; import org.ovirt.engine.core.utils.linq.Predicate; import org.ovirt.engine.core.utils.lock.LockManager; import org.ovirt.engine.core.utils.lock.LockManagerFactory; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; import org.ovirt.engine.core.vdsbroker.ResourceManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class VmHandler { private static ObjectIdentityChecker updateVmsStatic; private static OsRepository osRepository; private static final Logger log = LoggerFactory.getLogger(VmHandler.class); private static Set<VdcActionType> COMMANDS_ALLOWED_ON_EXTERNAL_VMS = new HashSet<>(); private static Set<VdcActionType> COMMANDS_ALLOWED_ON_HOSTED_ENGINE = new HashSet<>(); public static void init() { Class<?>[] inspectedClassNames = new Class<?>[] { VmBase.class, VM.class, VmStatic.class, VmDynamic.class, VmManagementParametersBase.class }; osRepository = SimpleDependecyInjector.getInstance().get(OsRepository.class); updateVmsStatic = new ObjectIdentityChecker(VmHandler.class, Arrays.asList(inspectedClassNames)); for (Pair<EditableField, Field> pair : BaseHandler.extractAnnotatedFields(EditableField.class, (inspectedClassNames))) { updateVmsStatic.AddPermittedFields(pair.getSecond().getName()); } for (Pair<EditableOnVm, Field> pair : BaseHandler.extractAnnotatedFields(EditableOnVm.class, inspectedClassNames)) { updateVmsStatic.AddPermittedFields(pair.getSecond().getName()); } for (Pair<EditableOnVmStatusField, Field> pair : BaseHandler.extractAnnotatedFields(EditableOnVmStatusField.class, inspectedClassNames)) { updateVmsStatic.AddField(Arrays.asList(pair.getFirst().statuses()), pair.getSecond().getName()); if (pair.getFirst().isHotsetAllowed()) { updateVmsStatic.AddHotsetFields(pair.getSecond().getName()); } } for (Pair<EditableDeviceOnVmStatusField, Field> pair : BaseHandler.extractAnnotatedFields(EditableDeviceOnVmStatusField.class, inspectedClassNames)) { updateVmsStatic.AddField(Arrays.asList(pair.getFirst().statuses()), pair.getSecond().getName()); } COMMANDS_ALLOWED_ON_EXTERNAL_VMS.add(VdcActionType.MigrateVm); COMMANDS_ALLOWED_ON_EXTERNAL_VMS.add(VdcActionType.MigrateVmToServer); COMMANDS_ALLOWED_ON_EXTERNAL_VMS.add(VdcActionType.InternalMigrateVm); COMMANDS_ALLOWED_ON_EXTERNAL_VMS.add(VdcActionType.CancelMigrateVm); COMMANDS_ALLOWED_ON_EXTERNAL_VMS.add(VdcActionType.SetVmTicket); COMMANDS_ALLOWED_ON_EXTERNAL_VMS.add(VdcActionType.VmLogon); COMMANDS_ALLOWED_ON_EXTERNAL_VMS.add(VdcActionType.StopVm); COMMANDS_ALLOWED_ON_EXTERNAL_VMS.add(VdcActionType.ShutdownVm); COMMANDS_ALLOWED_ON_EXTERNAL_VMS.add(VdcActionType.RemoveVm); COMMANDS_ALLOWED_ON_EXTERNAL_VMS.add(VdcActionType.RebootVm); COMMANDS_ALLOWED_ON_HOSTED_ENGINE.add(VdcActionType.MigrateVm); COMMANDS_ALLOWED_ON_HOSTED_ENGINE.add(VdcActionType.MigrateVmToServer); COMMANDS_ALLOWED_ON_HOSTED_ENGINE.add(VdcActionType.InternalMigrateVm); COMMANDS_ALLOWED_ON_HOSTED_ENGINE.add(VdcActionType.CancelMigrateVm); COMMANDS_ALLOWED_ON_HOSTED_ENGINE.add(VdcActionType.SetVmTicket); COMMANDS_ALLOWED_ON_HOSTED_ENGINE.add(VdcActionType.VmLogon); COMMANDS_ALLOWED_ON_HOSTED_ENGINE.add(VdcActionType.UpdateVm); COMMANDS_ALLOWED_ON_HOSTED_ENGINE.add(VdcActionType.RemoveVm); } public static boolean isUpdateValid(VmStatic source, VmStatic destination, VMStatus status) { return updateVmsStatic.IsUpdateValid(source, destination, status); } public static List<String> getChangedFieldsForStatus(VmStatic source, VmStatic destination, VMStatus status) { return updateVmsStatic.getChangedFieldsForStatus(source, destination, status); } public static boolean isUpdateValid(VmStatic source, VmStatic destination, VMStatus status, boolean hotsetEnabled) { return updateVmsStatic.IsUpdateValid(source, destination, status, hotsetEnabled); } public static boolean isUpdateValid(VmStatic source, VmStatic destination) { return updateVmsStatic.IsUpdateValid(source, destination); } public static boolean isUpdateValidForVmDevice(String fieldName, VMStatus status) { return updateVmsStatic.IsFieldUpdatable(status, fieldName, null); } public static boolean copyNonEditableFieldsToDestination(VmStatic source, VmStatic destination, boolean hotSetEnabled) { return updateVmsStatic.copyNonEditableFieldsToDestination(source, destination, hotSetEnabled); } /** * Verifies the add vm command . * * @param reasons * The reasons. * @param nicsCount * How many vNICs need to be allocated. * @return */ public static boolean verifyAddVm(List<String> reasons, int nicsCount, int vmPriority, MacPoolManagerStrategy macPool) { boolean returnValue = true; if (macPool.getAvailableMacsCount() < nicsCount) { if (reasons != null) { reasons.add(EngineMessage.MAC_POOL_NOT_ENOUGH_MAC_ADDRESSES.toString()); } returnValue = false; } else if (!VmTemplateCommand.isVmPriorityValueLegal(vmPriority, reasons)) { returnValue = false; } return returnValue; } /** * Checks if VM with same name exists in the given DC. If no DC provided, check all VMs in the database. */ public static boolean isVmWithSameNameExistStatic(String vmName, Guid storagePoolId) { NameQueryParameters params = new NameQueryParameters(vmName); params.setDatacenterId(storagePoolId); VdcQueryReturnValue result = Backend.getInstance().runInternalQuery(VdcQueryType.IsVmWithSameNameExist, params); return (Boolean) (result.getReturnValue()); } /** * Lock the VM in a new transaction, saving compensation data of the old status. * * @param vm * The VM to lock. * @param compensationContext * Used to save the old VM status, for compensation purposes. */ public static void lockVm(final VmDynamic vm, final CompensationContext compensationContext) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { compensationContext.snapshotEntityStatus(vm); lockVm(vm.getId()); compensationContext.stateChanged(); return null; } }); } /** * Check VM status before locking it, If VM status is not down, we throw an exception. * * @param status * - The status of the VM */ private static void checkStatusBeforeLock(VMStatus status) { if (status == VMStatus.ImageLocked) { log.error("VM status cannot change to image locked, since it is already locked"); throw new EngineException(EngineError.IRS_IMAGE_STATUS_ILLEGAL); } } /** * Lock VM after check its status, If VM status is locked, we throw an exception. * * @param vmId * - The ID of the VM. */ public static void checkStatusAndLockVm(Guid vmId) { VmDynamic vmDynamic = DbFacade.getInstance().getVmDynamicDao().get(vmId); checkStatusBeforeLock(vmDynamic.getStatus()); lockVm(vmId); } /** * Lock VM with compensation, after checking its status, If VM status is locked, we throw an exception. * * @param vmId * - The ID of the VM, which we want to lock. * @param compensationContext * - Used to save the old VM status for compensation purposes. */ public static void checkStatusAndLockVm(Guid vmId, CompensationContext compensationContext) { VmDynamic vmDynamic = DbFacade.getInstance().getVmDynamicDao().get(vmId); checkStatusBeforeLock(vmDynamic.getStatus()); lockVm(vmDynamic, compensationContext); } public static void lockVm(Guid vmId) { Backend.getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.SetVmStatus, new SetVmStatusVDSCommandParameters(vmId, VMStatus.ImageLocked)); } /** * Unlock the VM in a new transaction, saving compensation data of the old status. * * @param vm * The VM to unlock. * @param compensationContext * Used to save the old VM status, for compensation purposes. */ public static void unlockVm(final VM vm, final CompensationContext compensationContext) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { compensationContext.snapshotEntityStatus(vm.getDynamicData()); unLockVm(vm); compensationContext.stateChanged(); return null; } }); } public static void unLockVm(VM vm) { Backend.getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.SetVmStatus, new SetVmStatusVDSCommandParameters(vm.getId(), VMStatus.Down)); vm.setStatus(VMStatus.Down); } public static void updateDisksFromDb(VM vm) { List<Disk> imageList = DbFacade.getInstance().getDiskDao().getAllForVm(vm.getId()); vm.clearDisks(); updateDisksForVm(vm, imageList); } public static void updateDisksForVm(VM vm, Collection<? extends Disk> disks) { for (Disk disk : disks) { if (disk.isAllowSnapshot() && !disk.isDiskSnapshot()) { DiskImage image = (DiskImage) disk; vm.getDiskMap().put(image.getId(), image); vm.getDiskList().add(image); } else { vm.getDiskMap().put(disk.getId(), disk); } } } /** * Fetch VmInit from Database * @param vm VmBase to set the VmInit into * @param secure if true don't return any password field * We want to set false only when running VM becase the VmInitDao * decrypt the password. */ public static void updateVmInitFromDB(VmBase vm, boolean secure) { VmInitDao db = DbFacade.getInstance().getVmInitDao(); vm.setVmInit(db.get(vm.getId())); if (vm.getVmInit() != null) { if (secure) { vm.getVmInit().setPasswordAlreadyStored(!StringUtils.isEmpty(vm.getVmInit().getRootPassword())); vm.getVmInit().setRootPassword(null); } else { vm.getVmInit().setPasswordAlreadyStored(false); } } } public static void addVmInitToDB(VmBase vm) { if (vm.getVmInit() != null) { vm.getVmInit().setId(vm.getId()); VmInitDao db = DbFacade.getInstance().getVmInitDao(); VmInit oldVmInit = db.get(vm.getId()); if (oldVmInit == null) { db.save(vm.getVmInit()); } else { if (vm.getVmInit().isPasswordAlreadyStored()) { // since we are not always returning the password in // updateVmInitFromDB() // method (we don't want to display it in the UI/API) we // don't want to override // the password if the flag is on vm.getVmInit().setRootPassword(oldVmInit.getRootPassword()); } db.update(vm.getVmInit()); } } } public static void updateVmInitToDB(VmBase vm) { if (vm.getVmInit() != null) { VmHandler.addVmInitToDB(vm); } else { VmHandler.removeVmInitFromDB(vm); } } public static void removeVmInitFromDB(VmBase vm) { VmInitDao db = DbFacade.getInstance().getVmInitDao(); db.remove(vm.getId()); } // if secure is true we don't return the stored password, only // indicate that the password is set via the PasswordAlreadyStored property public static List<VmInit> getVmInitByIds(List<Guid> ids, boolean secure) { VmInitDao db = DbFacade.getInstance().getVmInitDao(); List<VmInit> all = db.getVmInitByIds(ids); for (VmInit vmInit: all) { if (secure) { vmInit.setPasswordAlreadyStored(!StringUtils.isEmpty(vmInit.getRootPassword())); vmInit.setRootPassword(null); } else { vmInit.setPasswordAlreadyStored(false); } } return all; } /** * Filters the vm image disks/disk devices.<BR/> * note: luns will be filtered, only active image disks will be return. */ public static void filterImageDisksForVM(VM vm) { List<DiskImage> filteredDisks = ImagesHandler.filterImageDisks(vm.getDiskMap().values(), false, false, true); List<CinderDisk> filteredCinderDisks = ImagesHandler.filterDisksBasedOnCinder(vm.getDiskMap().values()); filteredDisks.addAll(filteredCinderDisks); Collection<? extends Disk> vmDisksToRemove = CollectionUtils.subtract(vm.getDiskMap().values(), filteredDisks); vm.clearDisks(); updateDisksForVm(vm, filteredDisks); for (Disk diskToRemove : vmDisksToRemove) { vm.getManagedVmDeviceMap().remove(diskToRemove.getId()); } } public static void updateNetworkInterfacesFromDb(VM vm) { List<VmNetworkInterface> interfaces = DbFacade.getInstance().getVmNetworkInterfaceDao().getAllForVm(vm.getId()); vm.setInterfaces(interfaces); } private static Version getApplicationVersion(final String part, final String appName) { try { return new RpmVersion(part, getAppName(part, appName), true); } catch (Exception e) { log.debug("Failed to create rpm version object, part '{}' appName '{}': {}", part, appName, e.getMessage()); log.debug("Exception", e); return null; } } private static String getAppName(final String part, final String appName) { if (StringUtils.contains(part, appName + "64")) { // 64 bit Agent has extension // to its name. return appName + "64"; } return appName; } /** * Updates the {@link VM}'s {@link VM#getGuestAgentVersion()} and {@link VM#getSpiceDriverVersion()} based on the * VM's {@link VM#getAppList()} property. * * @param vm * the VM */ public static void updateVmGuestAgentVersion(final VM vm) { if (vm.getAppList() != null) { final String[] parts = vm.getAppList().split("[,]", -1); if (parts != null && parts.length != 0) { final List<String> possibleAgentAppNames = Config.<List<String>> getValue(ConfigValues.AgentAppName); final Map<String, String> spiceDriversInGuest = Config.<Map<String, String>> getValue(ConfigValues.SpiceDriverNameInGuest); final String spiceDriverInGuest = spiceDriversInGuest.get(osRepository.getOsFamily(vm.getOs()).toLowerCase()); for (final String part : parts) { for (String agentName : possibleAgentAppNames) { if (StringUtils.containsIgnoreCase(part, agentName)) { vm.setGuestAgentVersion(getApplicationVersion(part, agentName)); } if (StringUtils.containsIgnoreCase(part, spiceDriverInGuest)) { vm.setSpiceDriverVersion(getApplicationVersion(part, spiceDriverInGuest)); } } } } } } public static void updateVmLock(final VM vm) { vm.setLockInfo(getLockManager().getLockInfo(String.format("%s%s", vm.getId(), LockingGroup.VM.name()))); } public static void updateOperationProgress(final VM vm) { vm.setBackgroundOperationDescription(ResourceManager.getInstance().getVmManager(vm.getId()).getConvertOperationDescription()); vm.setBackgroundOperationProgress(ResourceManager.getInstance().getVmManager(vm.getId()).getConvertOperationProgress()); } protected static LockManager getLockManager() { return LockManagerFactory.getLockManager(); } /** * Checks the validity of the given memory size according to OS type. * * @param vm * a vm|template. * @param clusterVersion * the vm's cluster version. * @return */ public static void warnMemorySizeLegal(VmBase vm, Version clusterVersion) { if (! VmValidationUtils.isMemorySizeLegal(vm.getOsId(), vm.getMemSizeMb(), clusterVersion)) { AuditLogableBase logable = new AuditLogableBase(); logable.setVmId(vm.getId()); logable.addCustomValue("VmName", vm.getName()); logable.addCustomValue("VmMemInMb", String.valueOf(vm.getMemSizeMb())); logable.addCustomValue("VmMinMemInMb", String.valueOf(VmValidationUtils.getMinMemorySizeInMb(vm.getOsId(), clusterVersion))); logable.addCustomValue("VmMaxMemInMb", String.valueOf(VmValidationUtils.getMaxMemorySizeInMb(vm.getOsId(), clusterVersion))); new AuditLogDirector().log(logable, AuditLogType.VM_MEMORY_NOT_IN_RECOMMENDED_RANGE); } } /** * Check if the OS type is supported. * * @param osId * Type of the OS. * @param architectureType * The architecture type. * @param reasons * The reasons.VdsGroups * @return */ public static boolean isOsTypeSupported(int osId, ArchitectureType architectureType, List<String> reasons) { boolean result = VmValidationUtils.isOsTypeSupported(osId, architectureType); if (!result) { reasons.add(EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_OS_TYPE_IS_NOT_SUPPORTED_BY_ARCHITECTURE_TYPE .toString()); } return result; } /** * Check if the graphics and display types are supported. * * @param osId * Type of the OS. * @param graphics * Collection of graphics types (SPICE, VNC). * @param displayType * Display type. * @param reasons * The reasons.VdsGroups * @param clusterVersion * The cluster version. * @return */ public static boolean isGraphicsAndDisplaySupported(int osId, Collection<GraphicsType> graphics, DisplayType displayType, List<String> reasons, Version clusterVersion) { boolean result = VmValidationUtils.isGraphicsAndDisplaySupported(osId, clusterVersion, graphics, displayType); if (!result) { reasons.add(EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_VM_DISPLAY_TYPE_IS_NOT_SUPPORTED_BY_OS.name()); } if (graphics.size() > 1 && !FeatureSupported.multipleGraphicsSupported(clusterVersion)) { reasons.add(EngineMessage.ACTION_TYPE_FAILED_ONLY_ONE_GRAPHICS_SUPPORTED_IN_THIS_CLUSTER_LEVEL.name()); result = false; } return result; } /** * Check if the OS type is supported for VirtIO-SCSI. * * @param osId * Type of the OS * @param clusterVersion * Cluster's version * @param reasons * Reasons List * @return */ public static boolean isOsTypeSupportedForVirtioScsi(int osId, Version clusterVersion, List<String> reasons) { boolean result = VmValidationUtils.isDiskInterfaceSupportedByOs(osId, clusterVersion, DiskInterface.VirtIO_SCSI); if (!result) { reasons.add(EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_OS_TYPE_DOES_NOT_SUPPORT_VIRTIO_SCSI.name()); } return result; } /** * Check if the interface name is not duplicate in the list of interfaces. * * @param interfaces * - List of interfaces the VM/Template got. * @param interfaceName * - Candidate for interface name. * @param messages * - Messages for CanDoAction(). * @return - True , if name is valid, false, if name already exist. */ public static boolean isNotDuplicateInterfaceName(List<VmNic> interfaces, final String interfaceName, List<String> messages) { // Interface iface = interfaces.FirstOrDefault(i => i.name == // AddVmInterfaceParameters.Interface.name); VmNic iface = LinqUtils.firstOrNull(interfaces, new Predicate<VmNic>() { @Override public boolean eval(VmNic i) { return i.getName().equals(interfaceName); } }); if (iface != null) { messages.add(EngineMessage.NETWORK_INTERFACE_NAME_ALREADY_IN_USE.name()); return false; } return true; } /** * Checks number of monitors validation according to VM and Graphics types. * * @param graphicsTypes * Collection of graphics types of a VM. * @param numOfMonitors * Number of monitors * @param reasons * Messages for CanDoAction(). * @return */ public static boolean isNumOfMonitorsLegal(Collection<GraphicsType> graphicsTypes, int numOfMonitors, List<String> reasons) { boolean legal = false; if (graphicsTypes.contains(GraphicsType.VNC)) { legal = (numOfMonitors <= 1); } else if (graphicsTypes.contains(GraphicsType.SPICE)) { // contains spice and doesn't contain vnc legal = (numOfMonitors <= getMaxNumberOfMonitors()); } if (!legal) { reasons.add(EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_NUM_OF_MONITORS.toString()); } return legal; } public static boolean isSingleQxlDeviceLegal(DisplayType displayType, int osId, List<String> reasons, Version compatibilityVersion) { if (!FeatureSupported.singleQxlPci(compatibilityVersion)) { reasons.add(EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_SINGLE_DEVICE_INCOMPATIBLE_VERSION.toString()); return false; } if (displayType != DisplayType.qxl) { reasons.add(EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_SINGLE_DEVICE_DISPLAY_TYPE.toString()); return false; } if (!osRepository.isSingleQxlDeviceEnabled(osId)) { reasons.add(EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_SINGLE_DEVICE_OS_TYPE.toString()); return false; } return true; } /** * get max of allowed monitors from config config value is a comma separated list of integers * * @return */ private static int getMaxNumberOfMonitors() { int max = 0; String numOfMonitorsStr = Config.getValue(ConfigValues.ValidNumOfMonitors).toString().replaceAll("[\\[\\]]", ""); String values[] = numOfMonitorsStr.split(","); for (String val : values) { val = val.trim(); if (Integer.valueOf(val) > max) { max = Integer.valueOf(val); } } return max; } /** * Returns the vm's active snapshot, or null if one doesn't exist. * Note that this method takes into consideration that the vm snapshots are already loaded from DB. * @param vm The vm to get the active snapshot from. * @return the vm's active snapshot, or null if one doesn't exist. */ public static Snapshot getActiveSnapshot(VM vm) { for (Snapshot snapshot : vm.getSnapshots()) { if (snapshot.getType() == SnapshotType.ACTIVE) { return snapshot; } } return null; } public static boolean isUsbPolicyLegal(UsbPolicy usbPolicy, int osId, VDSGroup vdsGroup, List<String> messages) { boolean retVal = true; if (UsbPolicy.ENABLED_NATIVE.equals(usbPolicy)) { if (!Config.<Boolean> getValue(ConfigValues.NativeUSBEnabled, vdsGroup.getCompatibilityVersion() .getValue())) { messages.add(EngineMessage.USB_NATIVE_SUPPORT_ONLY_AVAILABLE_ON_CLUSTER_LEVEL.toString()); retVal = false; } } else if (UsbPolicy.ENABLED_LEGACY.equals(usbPolicy)) { if (osRepository.isLinux(osId)) { messages.add(EngineMessage.USB_LEGACY_NOT_SUPPORTED_ON_LINUX_VMS.toString()); retVal = false; } } return retVal; } public static void updateImportedVmUsbPolicy(VmBase vmBase) { // Enforce disabled USB policy for Linux OS with legacy policy. if (osRepository.isLinux(vmBase.getOsId()) && vmBase.getUsbPolicy().equals(UsbPolicy.ENABLED_LEGACY)) { vmBase.setUsbPolicy(UsbPolicy.DISABLED); } } public static ValidationResult canRunActionOnNonManagedVm(VM vm, VdcActionType actionType) { ValidationResult validationResult = ValidationResult.VALID; if ((vm.isHostedEngine() && !COMMANDS_ALLOWED_ON_HOSTED_ENGINE.contains(actionType)) || (vm.isExternalVm() && !COMMANDS_ALLOWED_ON_EXTERNAL_VMS.contains(actionType))) { validationResult = new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_CANNOT_RUN_ACTION_ON_NON_MANAGED_VM); } return validationResult; } private static VdsDynamicDao getVdsDynamicDao() { return DbFacade.getInstance().getVdsDynamicDao(); } public static void updateCurrentCd(Guid vdsId, VM vm, String currentCd) { VmDynamic vmDynamic = vm.getDynamicData(); vmDynamic.setCurrentCd(currentCd); Backend.getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.UpdateVmDynamicData, new UpdateVmDynamicDataVDSCommandParameters(vmDynamic)); } public static void updateDefaultTimeZone(VmBase vmBase) { if (vmBase.getTimeZone() == null) { if (osRepository.isWindows(vmBase.getOsId())) { vmBase.setTimeZone(Config.<String> getValue(ConfigValues.DefaultWindowsTimeZone)); } else { vmBase.setTimeZone(Config.<String> getValue(ConfigValues.DefaultGeneralTimeZone)); } } } public static boolean isUpdateValidForVmDevices(Guid vmId, VMStatus vmStatus, Object objectWithEditableDeviceFields) { if (objectWithEditableDeviceFields == null) { return true; } return getVmDevicesFieldsToUpdateOnNextRun(vmId, vmStatus, objectWithEditableDeviceFields).isEmpty(); } public static List<VmDeviceUpdate> getVmDevicesFieldsToUpdateOnNextRun( Guid vmId, VMStatus vmStatus, Object objectWithEditableDeviceFields) { List<VmDeviceUpdate> fieldList = new ArrayList<>(); if (objectWithEditableDeviceFields == null) { return fieldList; } List<Pair<EditableDeviceOnVmStatusField , Field>> pairList = BaseHandler.extractAnnotatedFields( EditableDeviceOnVmStatusField.class, objectWithEditableDeviceFields.getClass()); for (Pair<EditableDeviceOnVmStatusField, Field> pair : pairList) { EditableDeviceOnVmStatusField annotation = pair.getFirst(); Field field = pair.getSecond(); field.setAccessible(true); if (VmHandler.isUpdateValidForVmDevice(field.getName(), vmStatus)) { // field may be updated on the current run, so not including for the next run continue; } try { Object value = field.get(objectWithEditableDeviceFields); if (value == null) { // preserve current configuration } else if (value instanceof Boolean) { addDeviceUpdateOnNextRun(vmId, annotation, null, value, fieldList); } else if (value instanceof VmManagementParametersBase.Optional) { VmManagementParametersBase.Optional<?> optional = (VmManagementParametersBase.Optional<?>) value; if (optional.isUpdate()) { addDeviceUpdateOnNextRun(vmId, annotation, null, optional.getValue(), fieldList); } } else if (value instanceof Map) { Map<?, ?> map = (Map<?, ?>) value; for (Map.Entry<?, ?> entry : map.entrySet()) { boolean success = addDeviceUpdateOnNextRun(vmId, annotation, entry.getKey(), entry.getValue(), fieldList); if (!success) break; } } else { log.warn("getVmDevicesFieldsToUpdateOnNextRun: Unsupported field type: " + value.getClass().getName()); } } catch (IllegalAccessException | ClassCastException e) { log.warn("getVmDevicesFieldsToUpdateOnNextRun: Reflection error"); log.debug("Original exception was:", e); } } return fieldList; } private static boolean addDeviceUpdateOnNextRun(Guid vmId, EditableDeviceOnVmStatusField annotation, Object key, Object value, List<VmDeviceUpdate> updates) { return addDeviceUpdateOnNextRun(vmId, annotation.generalType(), annotation.type(), annotation.isReadOnly(), annotation.name(), key, value, updates); } private static boolean addDeviceUpdateOnNextRun(Guid vmId, VmDeviceGeneralType generalType, VmDeviceType type, boolean readOnly, String name, Object key, Object value, List<VmDeviceUpdate> updates) { if (key != null) { VmDeviceGeneralType keyGeneralType = VmDeviceGeneralType.UNKNOWN; VmDeviceType keyType = VmDeviceType.UNKNOWN; if (key instanceof VmDeviceGeneralType) { keyGeneralType = (VmDeviceGeneralType) key; } else if (key instanceof VmDeviceType) { keyType = (VmDeviceType) key; } else if (key instanceof GraphicsType) { keyType = ((GraphicsType) key).getCorrespondingDeviceType(); } else { log.warn("addDeviceUpdateOnNextRun: Unsupported map key type: " + key.getClass().getName()); return false; } if (keyGeneralType != VmDeviceGeneralType.UNKNOWN) { generalType = keyGeneralType; } if (keyType != VmDeviceType.UNKNOWN) { type = keyType; } } // if device type is set to unknown, search by general type only // because some devices have more than one type, like sound can be ac97/ich6 String typeName = type != VmDeviceType.UNKNOWN ? type.getName() : null; if (value == null) { if (VmDeviceUtils.vmDeviceChanged(vmId, generalType, typeName, false)) { updates.add(new VmDeviceUpdate(generalType, type, readOnly, name, false)); } } else if (value instanceof Boolean) { if (VmDeviceUtils.vmDeviceChanged(vmId, generalType, typeName, (Boolean) value)) { updates.add(new VmDeviceUpdate(generalType, type, readOnly, name, (Boolean) value)); } } else if (value instanceof VmDevice) { if (VmDeviceUtils.vmDeviceChanged(vmId, generalType, typeName, (VmDevice) value)) { updates.add(new VmDeviceUpdate(generalType, type, readOnly, name, (VmDevice) value)); } } else { log.warn("addDeviceUpdateOnNextRun: Unsupported value type: " + value.getClass().getName()); return false; } return true; } public static boolean isCpuSupported(int osId, Version version, String cpuName, ArrayList<String> canDoActionMessages) { String cpuId = CpuFlagsManagerHandler.getCpuId(cpuName, version); if (cpuId == null) { canDoActionMessages.add(EngineMessage.CPU_TYPE_UNKNOWN.name()); return false; } if (!osRepository.isCpuSupported( osId, version, cpuId)) { String unsupportedCpus = osRepository.getUnsupportedCpus(osId, version).toString(); canDoActionMessages.add(EngineMessage.CPU_TYPE_UNSUPPORTED_FOR_THE_GUEST_OS.name()); canDoActionMessages.add("$unsupportedCpus " + StringUtils.strip(unsupportedCpus.toString(), "[]")); return false; } return true; } public static void updateNumaNodesFromDb(VM vm){ VmNumaNodeDao dao = DbFacade.getInstance().getVmNumaNodeDao(); List<VmNumaNode> nodes = dao.getAllVmNumaNodeByVmId(vm.getId()); vm.setvNumaNodeList(nodes); } public static List<PermissionSubject> getPermissionsNeededToChangeCluster(Guid vmId, Guid clusterId) { List<PermissionSubject> permissionList = new ArrayList<>(); permissionList.add(new PermissionSubject(vmId, VdcObjectType.VM, ActionGroup.EDIT_VM_PROPERTIES)); permissionList.add(new PermissionSubject(clusterId, VdcObjectType.VdsGroups, ActionGroup.CREATE_VM)); return permissionList; } /** * Returns graphics types of devices VM/Template is supposed to have after adding/updating. * <p/> * When adding, VM/Template inherits graphics devices from the template by default. * When updating, VM/Template has already some graphics devices set. * However - these devices can be customized (overriden) in params * (i.e. params can prevent a device to be inherited from a template). * <p/> * * @return graphics types of devices VM/Template is supposed to have after adding/updating. */ public static Set<GraphicsType> getResultingVmGraphics(List<GraphicsType> srcEntityGraphics, Map<GraphicsType, GraphicsDevice> graphicsDevices) { Set<GraphicsType> result = new HashSet<>(); for (GraphicsType type : GraphicsType.values()) { if (graphicsDevices.get(type) != null) { result.add(type); } } if (result.isEmpty()) {// if graphics are set in params, do not use template graphics for (GraphicsType type : GraphicsType.values()) { if (srcEntityGraphics.contains(type) && !graphicsResetInParams(type, graphicsDevices)) { // graphics is in template and is not nulled in params result.add(type); } } } return result; } /** * Returns true if given graphics type was reset in params (that means params contain given graphics device which * is set to null). */ private static boolean graphicsResetInParams(GraphicsType type, Map<GraphicsType, GraphicsDevice> graphicsDevices) { return graphicsDevices.containsKey(type) && graphicsDevices.get(type) == null; } /** * Checks that dedicated host exists on the same cluster as the VM * * @param vm - the VM to check * @param canDoActionMessages - Action messages - used for error reporting. null value indicates that no error messages are required. * @return */ public static boolean validateDedicatedVdsExistOnSameCluster(VmBase vm, ArrayList<String> canDoActionMessages) { boolean result = true; for (Guid vdsId : vm.getDedicatedVmForVdsList()) { // get dedicated host, checks if exists and compare its cluster to the VM cluster VDS vds = DbFacade.getInstance().getVdsDao().get(vdsId); if (vds == null) { if (canDoActionMessages != null) { canDoActionMessages.add(EngineMessage.ACTION_TYPE_FAILED_DEDICATED_VDS_DOES_NOT_EXIST.toString()); } result = false; } else if (!Objects.equals(vm.getVdsGroupId(), vds.getVdsGroupId())) { if (canDoActionMessages != null) { canDoActionMessages.add(EngineMessage.ACTION_TYPE_FAILED_DEDICATED_VDS_NOT_IN_SAME_CLUSTER.toString()); } result = false; } } return result; } private static final Pattern TOOLS_PATTERN = Pattern.compile(".*rhev-tools\\s+([\\d\\.]+).*"); // FIXME: currently oVirt-ToolsSetup is not present in app_list when it does // ISO_VERSION_PATTERN should address this pattern as well as the TOOLS_PATTERN // if the name will be different. private static final Pattern ISO_VERSION_PATTERN = Pattern.compile(".*rhev-toolssetup_(\\d\\.\\d\\_\\d).*"); /** * Looking for "RHEV_Tools x.x.x" in VMs app_list if found we look if there is a newer version in the isoList - if * so we update the GuestAgentStatus of VmDynamic to UpdateNeeded * * @param poolId * storage pool id * @param isoList * list of iso file names */ public static void refreshVmsToolsVersion(Guid poolId, Set<String> isoList) { String latestVersion = getLatestGuestToolsVersion(isoList); if (latestVersion == null) { return; } List<VM> vms = DbFacade.getInstance().getVmDao().getAllForStoragePool(poolId); for (VM vm : vms) { if (vm.getAppList() != null && vm.getAppList().toLowerCase().contains("rhev-tools")) { Matcher m = TOOLS_PATTERN.matcher(vm.getAppList().toLowerCase()); if (m.matches() && m.groupCount() > 0) { String toolsVersion = m.group(1); if (toolsVersion.compareTo(latestVersion) < 0 && vm.getGuestAgentStatus() != GuestAgentStatus.UpdateNeeded) { vm.setGuestAgentStatus(GuestAgentStatus.UpdateNeeded); DbFacade.getInstance() .getVmDynamicDao() .updateGuestAgentStatus(vm.getId(), vm.getGuestAgentStatus()); } } } } } /** * iso file name that we are looking for: RHEV_toolsSetup_x.x_x.iso returning latest version only: xxx (ie 3.1.2) * * @param isoList * list of iso file names * @return latest iso version or null if no iso tools was found */ private static String getLatestGuestToolsVersion(Set<String> isoList) { String latestVersion = null; for (String iso: isoList) { if (iso.toLowerCase().contains("rhev-toolssetup")) { Matcher m = ISO_VERSION_PATTERN.matcher(iso.toLowerCase()); if (m.matches() && m.groupCount() > 0) { String isoVersion = m.group(1).replace('_', '.'); if (latestVersion == null) { latestVersion = isoVersion; } else if (latestVersion.compareTo(isoVersion) < 0) { latestVersion = isoVersion; } } } } return latestVersion; } /** * Copy fields that annotated with {@link org.ovirt.engine.core.common.businessentities.CopyOnNewVersion} from the new template version to the vm * * @param source * - template to copy data from * @param dest * - vm to copy data to */ public static boolean copyData(VmBase source, VmBase dest) { for (Field srcFld : VmBase.class.getDeclaredFields()) { try { if (srcFld.getAnnotation(CopyOnNewVersion.class) != null) { srcFld.setAccessible(true); Field dstFld = VmBase.class.getDeclaredField(srcFld.getName()); dstFld.setAccessible(true); dstFld.set(dest, srcFld.get(source)); } } catch (Exception exp) { log.error("Failed to copy field '{}' of new version to VM '{}' ({}): {}", srcFld.getName(), source.getName(), source.getId(), exp.getMessage()); log.debug("Exception", exp); return false; } } return true; } public static void autoSelectUsbPolicy(VmBase fromParams, VDSGroup cluster) { if (fromParams.getUsbPolicy() == null) { Version compatibilityVersion = cluster != null ? cluster.getCompatibilityVersion() : Version.getLast(); UsbPolicy usbPolicy = compatibilityVersion.compareTo(Version.v3_1) >= 0 ? UsbPolicy.ENABLED_NATIVE : UsbPolicy.ENABLED_LEGACY; fromParams.setUsbPolicy(usbPolicy); } } /** * Automatic selection of display type based on its graphics types in parameters. * This method preserves backward compatibility for REST API - legacy REST API doesn't allow to set display and * graphics separately. */ public static void autoSelectDefaultDisplayType(Guid srcEntityId, VmBase parametersStaticData, VDSGroup cluster, Map<GraphicsType, GraphicsDevice> graphicsDevices) { if (parametersStaticData.getOsId() == OsRepository.AUTO_SELECT_OS) { return; } List<Pair<GraphicsType, DisplayType>> graphicsAndDisplays = osRepository.getGraphicsAndDisplays( parametersStaticData.getOsId(), // cluster == null for the non cluster entities (e.g. Blank template and instance types) cluster != null ? cluster.getCompatibilityVersion() : Version.getLast()); if (parametersStaticData.getDefaultDisplayType() != null && isDisplayTypeSupported(parametersStaticData.getDefaultDisplayType(), graphicsAndDisplays)) { return; } DisplayType defaultDisplayType = null; // map holding display type -> set of supported graphics types for this display type Map<DisplayType, Set<GraphicsType>> displayGraphicsSupport = new HashMap<>(); for (Pair<GraphicsType, DisplayType> graphicsAndDisplay : graphicsAndDisplays) { DisplayType display = graphicsAndDisplay.getSecond(); if (!displayGraphicsSupport.containsKey(display)) { displayGraphicsSupport.put(display, new HashSet<GraphicsType>()); } displayGraphicsSupport.get(display).add(graphicsAndDisplay.getFirst()); } for (Map.Entry<DisplayType, Set<GraphicsType>> entry : displayGraphicsSupport.entrySet()) { if (entry.getValue().containsAll(VmHandler.getResultingVmGraphics(VmDeviceUtils.getGraphicsTypesOfEntity(srcEntityId), graphicsDevices))) { defaultDisplayType = entry.getKey(); break; } } if (defaultDisplayType == null) { if (!displayGraphicsSupport.isEmpty()) {// when not found otherwise, let's take osinfo's record as the default Map.Entry<DisplayType, Set<GraphicsType>> entry = displayGraphicsSupport.entrySet().iterator().next(); defaultDisplayType = entry.getKey(); } else {// no osinfo record defaultDisplayType = DisplayType.qxl; } } parametersStaticData.setDefaultDisplayType(defaultDisplayType); } private static boolean isDisplayTypeSupported(DisplayType displayType, List<Pair<GraphicsType, DisplayType>> graphicsAndDisplays) { for (Pair<GraphicsType, DisplayType> pair : graphicsAndDisplays) { if (displayType.equals(pair.getSecond())) { return true; } } return false; } }
package forager.client; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import java.util.logging.Logger; import forager.events.ForagerEventMap; import forager.events.TaskCompletion; import forager.events.TaskRequest; import forager.events.TaskSpec; import galileo.event.EventContext; import galileo.event.EventHandler; import galileo.event.EventReactor; import galileo.net.ClientMessageRouter; import galileo.net.NetworkDestination; public class Forager { private static final Logger logger = Logger.getLogger("forager"); private NetworkDestination server; private ClientMessageRouter messageRouter; private ForagerEventMap eventMap = new ForagerEventMap(); private EventReactor eventReactor = new EventReactor(this, eventMap); private StatusMonitor monitor; private Thread monitorThread; private int maxTasks = 0; private int activeTasks = 0; private int pendingRequests = 0; protected ExecutorService threadPool; public Forager(NetworkDestination server) { this(server, 4); } public Forager(NetworkDestination server, int threads) { this.server = server; this.maxTasks = threads; this.threadPool = Executors.newFixedThreadPool(threads); } public void start() throws Exception { messageRouter = new ClientMessageRouter(); messageRouter.addListener(eventReactor); /* Start the monitor thread */ monitor = new StatusMonitor(this); monitorThread = new Thread(monitor); monitorThread.start(); while (true) { eventReactor.processNextEvent(); } } protected synchronized void submitTaskRequest(int numTasks) throws IOException { TaskRequest tr = new TaskRequest(numTasks); pendingRequests += numTasks; messageRouter.sendMessage(server, eventReactor.wrapEvent(tr)); } protected synchronized void finalizeTask(TaskSpec task) throws IOException { System.out.println("Received task completion notification: " + task); activeTasks TaskCompletion completion = new TaskCompletion(task.taskId); messageRouter.sendMessage(server, eventReactor.wrapEvent(completion)); monitorThread.interrupt(); } protected synchronized int getNumActive() { return activeTasks; } protected synchronized int getNumPending() { return pendingRequests; } public int getMaxTasks() { return maxTasks; } @EventHandler public void processTaskSpec(TaskSpec taskSpec, EventContext context) { pendingRequests if (taskSpec.taskId == -1) { logger.log(Level.INFO, "Received idle task"); return; } logger.log(Level.INFO, "Starting task: {0}", taskSpec); activeTasks++; TaskThread thread = new TaskThread(taskSpec, this); threadPool.submit(thread); } public static void main(String[] args) throws Exception { if (args.length < 3) { System.out.println("Usage: forager.client.Forager <host> <port>"); System.exit(1); } String host = args[0]; int port = Integer.parseInt(args[1]); NetworkDestination overlord = new NetworkDestination(host, port); int threads = Integer.parseInt(args[2]); Forager forager = new Forager(overlord, threads); forager.start(); } }
package LRU_cache; import java.util.HashMap; //with HashMap and DoubleLinkedList class LRUCache { private class Node { Node prev; Node next; Integer key; Integer value; private Node() { // used only for sentinel nodes head and tail } public Node(int key, int value) { // make sure the input does not have null key and value, the null be used as // 'not found' in map this.key = key; this.value = value; this.prev = null; this.next = null; } } private class Order { // double linked list private Node old_; private Node _new; public Order() { old_ = new Node(); // care _new = new Node(); // care old_.next = _new; // care _new.prev = old_; // care } private Node rm_oldest() { Node removed = old_.next; remove(removed); return removed; } private void addNew(Node current) { Node pre = _new.prev; Node next = _new; pre.next = current; current.next = next; next.prev = current; current.prev = pre; } private void remove(Node n) { Node pre = n.prev; Node next = n.next; pre.next = next; next.prev = pre; } private void access(Node n) { remove(n); addNew(n); } } private int capacity; private HashMap<Integer, Node> map; private Order order; public LRUCache(int capacity) { this.capacity = capacity; map = new HashMap(); order = new Order(); } // get(key) - Get the value (will always be positive) of the key if the key exists in the cache, // otherwise return -1. public Integer get(int key) { Node n = map.get(key); if (n == null) { return null; // leetcode expected it to be -1, thus the value would never be -1; } order.access(n); return n.value; } // Set or insert the value if the key is not already present. // When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. public void set(int key, int value) { // set Integer v = get(key); if (get(key) != null) { // leetcode expected it to be -1, thus the value would never be -1; map.get(key).value = value; return; } // insert if (map.size() == capacity) { map.remove(order.rm_oldest().key); } Node insert = new Node(key, value); map.put(key, insert); order.addNew(insert); } } public class Leetcode146LRUCache { public static void main(String[] args) { LRUCache cache = new LRUCache(5); cache.get(1); cache.set(3, 2); } }
package fr.lip6.io; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.util.ArrayList; import java.util.List; import fr.lip6.type.TrainingSample; /** * Simple class to import data in csv format, with one sample per line:<br/> * attr1, attr2, ... , class * * position of the class label can be arbitrary * * @author picard * */ public class CsvImporter { /** * Importer with full settings. * @param filename the file containing the data * @param sep the token which separates the values * @param labelPosition the position of the class label * @return the full list of TrainingSample * @throws IOException */ public static List<TrainingSample<double[]>> importFromFile( String filename, String sep, int labelPosition) throws IOException { // the samples list List<TrainingSample<double[]>> list = new ArrayList<TrainingSample<double[]>>(); LineNumberReader line = new LineNumberReader(new FileReader(filename)); String l; // parse all lines while ((l = line.readLine()) != null) { String[] tok = l.split(","); double[] d = new double[tok.length - 1]; int y = 0; if(labelPosition == -1) { // first n-1 fields are attributes for (int i = 0; i < d.length; i++) d[i] = Double.parseDouble(tok[i]); // last field is class y = Integer.parseInt(tok[tok.length - 1]); } else if(labelPosition < d.length){ for(int i = 0 ; i < labelPosition ; i++) d[i] = Double.parseDouble(tok[i]); for(int i = labelPosition+1 ; i < d.length ; i++) d[i-1] = Double.parseDouble(tok[i]); y = Integer.parseInt(tok[labelPosition]); } TrainingSample<double[]> t = new TrainingSample<double[]>(d, y); list.add(t); } line.close(); return list; } /** * CSV import routine with delimiter set to "," * @param filename * @param labelPosition * @return The list of training samples * @throws IOException */ public static List<TrainingSample<double[]>> importFromFile( String filename, int labelPosition) throws IOException { return importFromFile(filename, ",", labelPosition); } /** * CSV import routine with label position set to the last value * @param filename * @param sep * @return The list of training samples * @throws IOException */ public static List<TrainingSample<double[]>> importFromFile( String filename, String sep) throws IOException { return importFromFile(filename, sep, -1); } /** * CSV import routine with default parameters (separator is "," and the label is the last value) * @param filename the file containing the values * @return The list of training samples * @throws IOException */ public static List<TrainingSample<double[]>> importFromFile(String filename) throws IOException { return importFromFile(filename, ",", -1); } }
package com.sequenceiq.cloudbreak.cloud.gcp; import static com.sequenceiq.cloudbreak.cloud.gcp.util.GcpStackUtil.buildCompute; import static com.sequenceiq.cloudbreak.cloud.gcp.util.GcpStackUtil.buildStorage; import static com.sequenceiq.cloudbreak.cloud.gcp.util.GcpStackUtil.getBucket; import static com.sequenceiq.cloudbreak.cloud.gcp.util.GcpStackUtil.getImageName; import static com.sequenceiq.cloudbreak.cloud.gcp.util.GcpStackUtil.getMissingServiceAccountKeyError; import static com.sequenceiq.cloudbreak.cloud.gcp.util.GcpStackUtil.getProjectId; import static com.sequenceiq.cloudbreak.cloud.gcp.util.GcpStackUtil.getTarName; import java.io.IOException; import java.util.List; import java.util.Map; import org.apache.http.HttpStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.google.api.client.auth.oauth2.TokenResponseException; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.compute.Compute; import com.google.api.services.compute.Compute.Images.Get; import com.google.api.services.compute.Compute.Images.Insert; import com.google.api.services.compute.model.GuestOsFeature; import com.google.api.services.compute.model.Image; import com.google.api.services.compute.model.Image.RawDisk; import com.google.api.services.compute.model.ImageList; import com.google.api.services.storage.Storage; import com.google.api.services.storage.Storage.Buckets; import com.google.api.services.storage.Storage.Objects.Copy; import com.google.api.services.storage.model.Bucket; import com.google.api.services.storage.model.StorageObject; import com.sequenceiq.cloudbreak.cloud.Setup; import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext; import com.sequenceiq.cloudbreak.cloud.context.CloudContext; import com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException; import com.sequenceiq.cloudbreak.cloud.gcp.util.GcpLabelUtil; import com.sequenceiq.cloudbreak.cloud.model.CloudCredential; import com.sequenceiq.cloudbreak.cloud.model.CloudStack; import com.sequenceiq.cloudbreak.cloud.model.SpiFileSystem; import com.sequenceiq.cloudbreak.cloud.notification.PersistenceNotifier; import com.sequenceiq.common.api.type.ImageStatus; import com.sequenceiq.common.api.type.ImageStatusResult; @Service public class GcpProvisionSetup implements Setup { private static final Logger LOGGER = LoggerFactory.getLogger(GcpProvisionSetup.class); private static final String READY = "READY"; @Override public void prepareImage(AuthenticatedContext authenticatedContext, CloudStack stack, com.sequenceiq.cloudbreak.cloud.model.Image image) { CloudCredential credential = authenticatedContext.getCloudCredential(); CloudContext cloudContext = authenticatedContext.getCloudContext(); try { String projectId = getProjectId(credential); String imageName = image.getImageName(); Compute compute = buildCompute(credential); ImageList list = compute.images().list(projectId).execute(); if (!containsSpecificImage(list, imageName)) { Storage storage = buildStorage(credential, cloudContext.getName()); Bucket bucket = new Bucket(); String bucketName = GcpLabelUtil.transformValue(String.format("%s-%s-%d", projectId, cloudContext.getName(), cloudContext.getId())); bucket.setName(bucketName); bucket.setStorageClass("STANDARD"); try { Buckets.Insert ins = storage.buckets().insert(projectId, bucket); ins.execute(); } catch (GoogleJsonResponseException ex) { if (ex.getStatusCode() != HttpStatus.SC_CONFLICT) { String msg = String.format("Failed to create bucket with name '%s':", bucketName); LOGGER.warn(msg, ex); throw ex; } else { LOGGER.info("No need to create bucket as it exists already with name: {}", bucketName); } } String tarName = getTarName(imageName); Copy copy = storage.objects().copy(getBucket(imageName), tarName, bucket.getName(), tarName, new StorageObject()); copy.execute(); Image gcpApiImage = new Image(); gcpApiImage.setName(getImageName(imageName)); RawDisk rawDisk = new RawDisk(); rawDisk.setSource(String.format("http://storage.googleapis.com/%s/%s", bucket.getName(), tarName)); gcpApiImage.setRawDisk(rawDisk); GuestOsFeature uefiCompatible = new GuestOsFeature().setType("UEFI_COMPATIBLE"); GuestOsFeature multiIpSubnet = new GuestOsFeature().setType("MULTI_IP_SUBNET"); gcpApiImage.setGuestOsFeatures(List.of(uefiCompatible, multiIpSubnet)); Insert ins = compute.images().insert(projectId, gcpApiImage); ins.execute(); } } catch (Exception e) { Long stackId = cloudContext.getId(); String msg = String.format("Error occurred on %s stack during the setup: %s", stackId, e.getMessage()); LOGGER.warn(msg, e); throw new CloudConnectorException(msg, e); } } @Override public ImageStatusResult checkImageStatus(AuthenticatedContext authenticatedContext, CloudStack stack, com.sequenceiq.cloudbreak.cloud.model.Image image) { CloudCredential credential = authenticatedContext.getCloudCredential(); String projectId = getProjectId(credential); String imageName = image.getImageName(); try { Image gcpApiImage = new Image(); gcpApiImage.setName(getImageName(imageName)); Compute compute = buildCompute(credential); Get getImages = compute.images().get(projectId, gcpApiImage.getName()); String status = getImages.execute().getStatus(); LOGGER.debug("Status of image {} copy: {}", gcpApiImage.getName(), status); if (READY.equals(status)) { return new ImageStatusResult(ImageStatus.CREATE_FINISHED, ImageStatusResult.COMPLETED); } } catch (TokenResponseException e) { getMissingServiceAccountKeyError(e, projectId); } catch (IOException e) { LOGGER.info("Failed to retrieve image copy status", e); return new ImageStatusResult(ImageStatus.CREATE_FAILED, 0); } return new ImageStatusResult(ImageStatus.IN_PROGRESS, ImageStatusResult.HALF); } @Override public void prerequisites(AuthenticatedContext authenticatedContext, CloudStack stack, PersistenceNotifier persistenceNotifier) { LOGGER.debug("setup has been executed"); } @Override public void validateFileSystem(CloudCredential credential, SpiFileSystem spiFileSystem) { } @Override public void validateParameters(AuthenticatedContext authenticatedContext, Map<String, String> parameters) { } @Override public void scalingPrerequisites(AuthenticatedContext authenticatedContext, CloudStack stack, boolean upscale) { } private boolean containsSpecificImage(ImageList imageList, String imageUrl) { try { for (Image image : imageList.getItems()) { if (image.getName().equals(getImageName(imageUrl))) { return true; } } } catch (NullPointerException ignored) { return false; } return false; } }
package com.zhiheng.JDBCStudy.reflection; import static java.lang.System.out; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method;; enum ClassMember {CONSTRUCTOR, FIELD, METHOD, CLASS, ALL} public class ClassSpy { private static void printMembers(Member[] mbrs, String s) { out.format("%s:%n", s); for(Member mbr : mbrs) { if(mbr instanceof Field) out.format(" %s%n", ((Field)mbr).toGenericString()); else if(mbr instanceof Constructor) out.format(" %s%n", ((Constructor)mbr).toGenericString()); else if(mbr instanceof Method) out.format(" %s%n", ((Method)mbr).toGenericString()); } } private static void printClasses(Class<?> c) { out.format("Classes:%n"); Class<?>[] clss = c.getClasses(); for (Class<?> cls : clss) { out.format(" %s%n", cls.getCanonicalName()); } if(clss.length == 0) out.format("-- No member interfaces, classes or enums --"); out.format("%n"); } public static void main(String[] args) { try { Class<?> c = Class.forName(args[0]); out.format("Class:%n %s%n%n", c.getCanonicalName()); Package p = c.getPackage(); out.format("Package:%n %s%n%n", (p != null ? p.getName() : "-- No Package --")); for (int i = 1; i < args.length; i++) { switch (ClassMember.valueOf(args[i])) { case CONSTRUCTOR: printMembers(c.getFields(), "Fields"); break; case FIELD: printMembers(c.getMethods(), "Methods"); break; case CLASS: printClasses(c); break; case ALL: break; default: assert false; break; } } } catch (Exception e) { // TODO: handle exception } } }
package com.metamatrix.common.queue; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; public class TestQueueWorkerPool { @Test public void testQueuing() throws Exception { final long SINGLE_WAIT = 50; final int WORK_ITEMS = 10; final int MAX_THREADS = 5; final WorkerPool pool = WorkerPoolFactory.newWorkerPool("test", MAX_THREADS, 120000); //$NON-NLS-1$ for(int i=0; i<WORK_ITEMS; i++) { pool.execute(new FakeWorkItem(SINGLE_WAIT)); } pool.shutdown(); pool.awaitTermination(1000, TimeUnit.MILLISECONDS); assertTrue(pool.isTerminated()); WorkerPoolStats stats = pool.getStats(); assertEquals(10, stats.totalCompleted); assertEquals("Expected threads to be maxed out", MAX_THREADS, stats.highestActiveThreads); //$NON-NLS-1$ } @Test public void testThreadReuse() throws Exception { final long SINGLE_WAIT = 50; final long NUM_THREADS = 5; final WorkerPool pool = WorkerPoolFactory.newWorkerPool("test", 5, 120000); //$NON-NLS-1$ for(int i=0; i<NUM_THREADS; i++) { pool.execute(new FakeWorkItem(SINGLE_WAIT)); try { Thread.sleep(SINGLE_WAIT*2); } catch(InterruptedException e) { } } pool.shutdown(); WorkerPoolStats stats = pool.getStats(); assertEquals("Expected 1 thread for serial execution", 1, stats.highestActiveThreads); //$NON-NLS-1$ pool.awaitTermination(1000, TimeUnit.MILLISECONDS); } @Test(expected=RejectedExecutionException.class) public void testShutdown() throws Exception { final WorkerPool pool = WorkerPoolFactory.newWorkerPool("test", 5, 120000); //$NON-NLS-1$ pool.shutdown(); pool.execute(new FakeWorkItem(1)); } @Test public void testScheduleCancel() throws Exception { final WorkerPool pool = WorkerPoolFactory.newWorkerPool("test", 5, 120000); //$NON-NLS-1$ ScheduledFuture<?> future = pool.scheduleAtFixedRate(new Runnable() { @Override public void run() { } }, 0, 5, TimeUnit.MILLISECONDS); future.cancel(true); assertFalse(future.cancel(true)); } @Test public void testSchedule() throws Exception { final WorkerPool pool = WorkerPoolFactory.newWorkerPool("test", 5, 120000); //$NON-NLS-1$ final ArrayList<String> result = new ArrayList<String>(); ScheduledFuture<?> future = pool.schedule(new Runnable() { @Override public void run() { result.add("hello"); //$NON-NLS-1$ } }, 5, TimeUnit.MILLISECONDS); future.cancel(true); Thread.sleep(10); assertEquals(0, result.size()); future = pool.schedule(new Runnable() { @Override public void run() { result.add("hello"); //$NON-NLS-1$ } }, 5, TimeUnit.MILLISECONDS); Thread.sleep(10); pool.shutdown(); pool.awaitTermination(1000, TimeUnit.MILLISECONDS); assertEquals(1, result.size()); } @Test(expected=ExecutionException.class) public void testScheduleException() throws Exception { final WorkerPool pool = WorkerPoolFactory.newWorkerPool("test", 5, 120000); //$NON-NLS-1$ ScheduledFuture<?> future = pool.schedule(new Runnable() { @Override public void run() { throw new RuntimeException(); } }, 0, TimeUnit.MILLISECONDS); future.get(); } /** * Here each execution exceeds the period */ @Test public void testScheduleRepeated() throws Exception { final WorkerPool pool = WorkerPoolFactory.newWorkerPool("test", 5, 120000); //$NON-NLS-1$ final ArrayList<String> result = new ArrayList<String>(); ScheduledFuture<?> future = pool.scheduleAtFixedRate(new Runnable() { @Override public void run() { result.add("hello"); //$NON-NLS-1$ try { Thread.sleep(75); } catch (InterruptedException e) { throw new RuntimeException(e); } } }, 0, 10, TimeUnit.MILLISECONDS); Thread.sleep(100); future.cancel(true); assertEquals(2, result.size()); } @Test public void testFailingWork() throws Exception { final WorkerPool pool = WorkerPoolFactory.newWorkerPool("test", 5, 120000); //$NON-NLS-1$ final AtomicInteger count = new AtomicInteger(); pool.execute(new Runnable() { @Override public void run() { count.getAndIncrement(); throw new RuntimeException(); } }); Thread.sleep(10); assertEquals(1, count.get()); } }
package fi.nls.oskari.control.layer; import fi.nls.oskari.analysis.AnalysisHelper; import fi.nls.oskari.annotation.OskariActionRoute; import fi.nls.oskari.control.ActionException; import fi.nls.oskari.control.ActionHandler; import fi.nls.oskari.control.ActionParameters; import fi.nls.oskari.control.ActionParamsException; import fi.nls.oskari.domain.map.analysis.Analysis; import fi.nls.oskari.map.analysis.service.AnalysisDbService; import fi.nls.oskari.map.analysis.service.AnalysisDbServiceMybatisImpl; import fi.nls.oskari.util.ConversionHelper; import fi.nls.oskari.util.JSONHelper; import fi.nls.oskari.util.ResponseHelper; import org.json.JSONArray; import org.json.JSONObject; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Returns user's analysis data as JSON. * Only for aggregate method */ @OskariActionRoute("GetAnalysisData") public class GetAnalysisDataHandler extends ActionHandler { private static final AnalysisDbService analysisService = new AnalysisDbServiceMybatisImpl(); private static final String ANALYSE_ID = "analyse_id"; private static final String JSKEY_ANALYSISDATA = "analysisdata"; @Override public void handleAction(ActionParameters params) throws ActionException { // only for logged in users! params.requireLoggedInUser(); final long id = ConversionHelper.getLong(params.getHttpParam(ANALYSE_ID), -1); if (id == -1) { throw new ActionParamsException("Parameter missing or non-numeric: " + ANALYSE_ID + "=" + params.getHttpParam(ANALYSE_ID)); } Analysis analysis; try { analysis = analysisService.getAnalysisById(id); if (analysis == null) { new ActionParamsException("Analysis not found, id: " + id); } } catch (Exception e) { throw new ActionException("Unexpected error occured trying to find analysis", e); } String select_items = AnalysisHelper.getAnalysisSelectItems(analysis); if (select_items == null) { throw new ActionException("Unable to retrieve Analysis data, " + "this Analysis is not stored correctly, id:" + id); } List<HashMap<String, Object>> list; try { String uid = params.getUser().getUuid(); list = analysisService.getAnalysisDataByIdUid(id, uid, select_items); if (list.isEmpty()) { throw new ActionException("Could not find analysis data"); } } catch (Exception e) { throw new ActionException("Unexpected error occured trying to find analysis data", e); } final JSONArray rows = new JSONArray(); for (HashMap<String, Object> analysisData : list) { final JSONObject row = convertToOldResultJSON(analysisData, select_items); if (row != null) { rows.put(row); } } final JSONObject response = new JSONObject(); JSONHelper.putValue(response, JSKEY_ANALYSISDATA, rows); JSONHelper.putValue(response, ANALYSE_ID, id); ResponseHelper.writeResponse(params, response); } /** * Converts aggregate analysis result to old result syntax for multiselect on client side * and returns a JSONObject as aggregate results of one property * * @param analysisData * @return JSONObject {property:{aggregate value1, aggregate value2,..}} */ private JSONObject convertToOldResultJSON(HashMap<String, Object> analysisData, String selectColumns) { if (analysisData == null) { return null; } final JSONObject row = new JSONObject(); String columnName = null; for (Map.Entry<String, Object> entry : analysisData.entrySet()) { final Object value = entry.getValue(); final String key = entry.getKey(); if (selectColumns.indexOf("As " + key) != -1) { columnName = value.toString(); continue; } // try to map as JSON JSONHelper.putValue(row, key, value); } return (columnName != null) ? JSONHelper.createJSONObject(columnName, row) : null; } }
package com.yahoo.vespa.hosted.controller; import com.google.common.collect.ImmutableMap; import com.yahoo.component.Version; import com.yahoo.config.application.api.DeploymentSpec; import com.yahoo.config.application.api.ValidationOverrides; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.Environment; import com.yahoo.vespa.hosted.controller.api.integration.MetricsService.ApplicationMetrics; import com.yahoo.vespa.hosted.controller.api.integration.organization.IssueId; import com.yahoo.vespa.hosted.controller.api.integration.zone.ZoneId; import com.yahoo.vespa.hosted.controller.application.ApplicationRotation; import com.yahoo.vespa.hosted.controller.application.ApplicationVersion; import com.yahoo.vespa.hosted.controller.application.Change; import com.yahoo.vespa.hosted.controller.application.Deployment; import com.yahoo.vespa.hosted.controller.application.DeploymentJobs; import com.yahoo.vespa.hosted.controller.rotation.RotationId; import java.time.Instant; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; /** * An instance of an application. * * This is immutable. * * @author bratseth */ public class Application { private final ApplicationId id; private final DeploymentSpec deploymentSpec; private final ValidationOverrides validationOverrides; private final Map<ZoneId, Deployment> deployments; private final DeploymentJobs deploymentJobs; private final Change change; private final Change outstandingChange; private final Optional<IssueId> ownershipIssueId; private final ApplicationMetrics metrics; private final Optional<RotationId> rotation; /** Creates an empty application */ public Application(ApplicationId id) { this(id, DeploymentSpec.empty, ValidationOverrides.empty, Collections.emptyMap(), new DeploymentJobs(Optional.empty(), Collections.emptyList(), Optional.empty()), Change.empty(), Change.empty(), Optional.empty(), new ApplicationMetrics(0, 0), Optional.empty()); } /** Used from persistence layer: Do not use */ public Application(ApplicationId id, DeploymentSpec deploymentSpec, ValidationOverrides validationOverrides, List<Deployment> deployments, DeploymentJobs deploymentJobs, Change change, Change outstandingChange, Optional<IssueId> ownershipIssueId, ApplicationMetrics metrics, Optional<RotationId> rotation) { this(id, deploymentSpec, validationOverrides, deployments.stream().collect(Collectors.toMap(Deployment::zone, d -> d)), deploymentJobs, change, outstandingChange, ownershipIssueId, metrics, rotation); } Application(ApplicationId id, DeploymentSpec deploymentSpec, ValidationOverrides validationOverrides, Map<ZoneId, Deployment> deployments, DeploymentJobs deploymentJobs, Change change, Change outstandingChange, Optional<IssueId> ownershipIssueId, ApplicationMetrics metrics, Optional<RotationId> rotation) { Objects.requireNonNull(id, "id cannot be null"); Objects.requireNonNull(deploymentSpec, "deploymentSpec cannot be null"); Objects.requireNonNull(validationOverrides, "validationOverrides cannot be null"); Objects.requireNonNull(deployments, "deployments cannot be null"); Objects.requireNonNull(deploymentJobs, "deploymentJobs cannot be null"); Objects.requireNonNull(change, "change cannot be null"); Objects.requireNonNull(metrics, "metrics cannot be null"); Objects.requireNonNull(rotation, "rotation cannot be null"); this.id = id; this.deploymentSpec = deploymentSpec; this.validationOverrides = validationOverrides; this.deployments = ImmutableMap.copyOf(deployments); this.deploymentJobs = deploymentJobs; this.change = change; this.outstandingChange = outstandingChange; this.ownershipIssueId = ownershipIssueId; this.metrics = metrics; this.rotation = rotation; } public ApplicationId id() { return id; } /** * Returns the last deployed deployment spec of this application, * or the empty deployment spec if it has never been deployed */ public DeploymentSpec deploymentSpec() { return deploymentSpec; } /** * Returns the last deployed validation overrides of this application, * or the empty validation overrides if it has never been deployed * (or was deployed with an empty/missing validation overrides) */ public ValidationOverrides validationOverrides() { return validationOverrides; } /** Returns an immutable map of the current deployments of this */ public Map<ZoneId, Deployment> deployments() { return deployments; } /** * Returns an immutable map of the current *production* deployments of this * (deployments also includes manually deployed environments) */ public Map<ZoneId, Deployment> productionDeployments() { return ImmutableMap.copyOf(deployments.values().stream() .filter(deployment -> deployment.zone().environment() == Environment.prod) .collect(Collectors.toMap(Deployment::zone, Function.identity()))); } public DeploymentJobs deploymentJobs() { return deploymentJobs; } /** * Returns the change that should currently be deployed for this application, * which is empty when no change is in progress. */ public Change change() { return change; } /** * Returns whether this has an outstanding change (in the source repository), which * has currently not started deploying (because a deployment is (or was) already in progress */ public Change outstandingChange() { return outstandingChange; } public Optional<IssueId> ownershipIssueId() { return ownershipIssueId; } public ApplicationMetrics metrics() { return metrics; } /** * Returns the oldest version this has deployed in a permanent zone (not test or staging), * or empty version if it is not deployed anywhere */ public Optional<Version> oldestDeployedVersion() { return productionDeployments().values().stream() .map(Deployment::version) .min(Comparator.naturalOrder()); } /** Returns the version a new deployment to this zone should use for this application */ public Version deployVersionIn(ZoneId zone, Controller controller) { return change.platform().orElse(versionIn(zone, controller)); } /** Returns the current version this application has, or if none; should use, in the given zone */ public Version versionIn(ZoneId zone, Controller controller) { return Optional.ofNullable(deployments().get(zone)).map(Deployment::version) // Already deployed in this zone: Use that version .orElse(oldestDeployedVersion().orElse(controller.systemVersion())); } /** Returns the Vespa version to use for the given job */ public Version deployVersionFor(DeploymentJobs.JobType jobType, Controller controller) { return jobType == DeploymentJobs.JobType.component ? controller.systemVersion() : deployVersionIn(jobType.zone(controller.system()).get(), controller); } /** * Returns the application version to use for the given job. * * If no version is specified by the application's {@link Change}, or by {@code currentVersion}, * returns the currently deployed application version, or the last successfully deployed one. */ public Optional<ApplicationVersion> deployApplicationVersionFor(DeploymentJobs.JobType jobType, Controller controller, boolean currentVersion) { if (jobType == DeploymentJobs.JobType.component) return Optional.empty(); if (currentVersion || ! change().application().isPresent()) { Deployment deployment = deployments().get(jobType.zone(controller.system()).get()); if (deployment != null) return Optional.of(deployment.applicationVersion()); if (deploymentJobs().lastSuccessfulApplicationVersionFor(jobType).isPresent()) return deploymentJobs().lastSuccessfulApplicationVersionFor(jobType); } return change().application(); } /** Returns the global rotation of this, if present */ public Optional<ApplicationRotation> rotation() { return rotation.map(rotation -> new ApplicationRotation(id, rotation)); } @Override public boolean equals(Object o) { if (this == o) return true; if (! (o instanceof Application)) return false; Application that = (Application) o; return id.equals(that.id); } @Override public int hashCode() { return id.hashCode(); } @Override public String toString() { return "application '" + id + "'"; } /** Returns whether changes to this are blocked in the given instant */ public boolean isBlocked(Instant instant) { return ! deploymentSpec().canUpgradeAt(instant) || ! deploymentSpec().canChangeRevisionAt(instant); } }
package org.apereo.cas.util; import lombok.SneakyThrows; import lombok.experimental.UtilityClass; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.ReaderInputStream; import org.apache.commons.lang3.StringUtils; import org.springframework.core.io.AbstractResource; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.UrlResource; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Enumeration; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import static org.springframework.util.ResourceUtils.CLASSPATH_URL_PREFIX; import static org.springframework.util.ResourceUtils.FILE_URL_PREFIX; /** * Utility class to assist with resource operations. * * @author Misagh Moayyed * @since 5.0.0 */ @Slf4j @UtilityClass public class ResourceUtils { private static final String HTTP_URL_PREFIX = "http"; /** * Gets resource from a String location. * * @param location the metadata location * @return the resource from * @throws IOException the exception */ public static AbstractResource getRawResourceFrom(final String location) throws IOException { if (StringUtils.isBlank(location)) { throw new IllegalArgumentException("Provided location does not exist and is empty"); } final AbstractResource res; if (location.toLowerCase().startsWith(HTTP_URL_PREFIX)) { res = new UrlResource(location); } else if (location.toLowerCase().startsWith(CLASSPATH_URL_PREFIX)) { res = new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length())); } else { res = new FileSystemResource(StringUtils.remove(location, FILE_URL_PREFIX)); } return res; } /** * Does resource exist? * * @param resource the resource * @param resourceLoader the resource loader * @return the boolean */ public static boolean doesResourceExist(final String resource, final ResourceLoader resourceLoader) { try { if (StringUtils.isNotBlank(resource)) { final var res = resourceLoader.getResource(resource); return doesResourceExist(res); } } catch (final Exception e) { LOGGER.warn(e.getMessage(), e); } return false; } /** * Does resource exist? * * @param res the res * @return the boolean */ public static boolean doesResourceExist(final Resource res) { if (res != null) { try { IOUtils.read(res.getInputStream(), new byte[1]); return res.contentLength() > 0; } catch (final Exception e) { LOGGER.trace(e.getMessage(), e); return false; } } return false; } /** * Does resource exist? * * @param location the resource * @return the boolean */ public static boolean doesResourceExist(final String location) { try { return getResourceFrom(location) != null; } catch (final Exception e) { LOGGER.trace(e.getMessage(), e); } return false; } /** * Gets resource from a String location. * * @param location the metadata location * @return the resource from * @throws IOException the exception */ public static AbstractResource getResourceFrom(final String location) throws IOException { final var metadataLocationResource = getRawResourceFrom(location); if (!metadataLocationResource.exists() || !metadataLocationResource.isReadable()) { throw new FileNotFoundException("Resource " + location + " does not exist or is unreadable"); } return metadataLocationResource; } /** * Prepare classpath resource if needed file. * * @param resource the resource * @return the file */ public static Resource prepareClasspathResourceIfNeeded(final Resource resource) { if (resource == null) { LOGGER.debug("No resource defined to prepare. Returning null"); return null; } return prepareClasspathResourceIfNeeded(resource, false, resource.getFilename()); } /** * If the provided resource is a classpath resource, running inside an embedded container, * and if the container is running in a non-exploded form, classpath resources become non-accessible. * So, this method will attempt to move resources out of classpath and onto a physical location * outside the context, typically in the "cas" directory of the temp system folder. * * @param resource the resource * @param isDirectory the if the resource is a directory, in which case entries will be copied over. * @param containsName the resource name pattern * @return the file */ @SneakyThrows public static Resource prepareClasspathResourceIfNeeded(final Resource resource, final boolean isDirectory, final String containsName) { if (resource == null) { LOGGER.debug("No resource defined to prepare. Returning null"); return null; } if (resource instanceof ClassPathResource) { return resource; } if (org.springframework.util.ResourceUtils.isFileURL(resource.getURL())) { return resource; } final var url = org.springframework.util.ResourceUtils.extractArchiveURL(resource.getURL()); final var file = org.springframework.util.ResourceUtils.getFile(url); final var casDirectory = new File(FileUtils.getTempDirectory(), "cas"); final var destination = new File(casDirectory, resource.getFilename()); if (isDirectory) { FileUtils.forceMkdir(destination); FileUtils.cleanDirectory(destination); } else if (destination.exists()) { FileUtils.forceDelete(destination); } try (var jFile = new JarFile(file)) { final Enumeration e = jFile.entries(); while (e.hasMoreElements()) { final var entry = (ZipEntry) e.nextElement(); if (entry.getName().contains(resource.getFilename()) && entry.getName().contains(containsName)) { try (var stream = jFile.getInputStream(entry)) { var copyDestination = destination; if (isDirectory) { final var entryFileName = new File(entry.getName()); copyDestination = new File(destination, entryFileName.getName()); } try (var writer = Files.newBufferedWriter(copyDestination.toPath(), StandardCharsets.UTF_8)) { IOUtils.copy(stream, writer, StandardCharsets.UTF_8); } } } } } return new FileSystemResource(destination); } /** * Build input stream resource from string value. * * @param value the value * @param description the description * @return the input stream resource */ public static InputStreamResource buildInputStreamResourceFrom(final String value, final String description) { final var reader = new StringReader(value); final InputStream is = new ReaderInputStream(reader, StandardCharsets.UTF_8); return new InputStreamResource(is, description); } /** * Is the resource a file? * * @param resource the resource * @return the boolean */ public static boolean isFile(final String resource) { return StringUtils.isNotBlank(resource) && resource.startsWith(FILE_URL_PREFIX); } }
package org.onetwo.common.apiclient; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.onetwo.common.apiclient.ApiClientMethod.ApiClientMethodParameter; import org.onetwo.common.apiclient.ApiErrorHandler.DefaultErrorHandler; import org.onetwo.common.apiclient.CustomResponseHandler.NullHandler; import org.onetwo.common.apiclient.annotation.InjectProperties; import org.onetwo.common.apiclient.annotation.ResponseHandler; import org.onetwo.common.apiclient.utils.ApiClientConstants.ApiClientErrors; import org.onetwo.common.apiclient.utils.ApiClientUtils; import org.onetwo.common.exception.ApiClientException; import org.onetwo.common.exception.BaseException; import org.onetwo.common.proxy.AbstractMethodResolver; import org.onetwo.common.proxy.BaseMethodParameter; import org.onetwo.common.reflect.BeanToMapConvertor; import org.onetwo.common.reflect.BeanToMapConvertor.BeanToMapBuilder; import org.onetwo.common.reflect.ReflectUtils; import org.onetwo.common.spring.SpringUtils; import org.onetwo.common.spring.Springs; import org.onetwo.common.spring.rest.RestUtils; import org.onetwo.common.utils.FieldName; import org.onetwo.common.utils.LangUtils; import org.slf4j.Logger; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ValueConstants; import org.springframework.web.client.RestClientException; import org.springframework.web.multipart.MultipartFile; /** * @PathVariable @RequestBody @RequestParam * @PathVariable * @RequestBodybodyjson requestbody * @RequestParamqueryString * getqueryString@RequestParam * postMaprequestBody * * requestBodyrequestBody * * @RequestParammap * * * getrequestBody * posturlrequestBody * * consumes -> contentTypeconvertorHttpEntityRequestCallback * produces -> acceptHeaderaccept headerresponsecontentTypeconvertorResponseEntityResponseExtractor * * ValueConvertor * HttpEntityRequestCallback * * @author wayshall * <br/> */ public class ApiClientMethod extends AbstractMethodResolver<ApiClientMethodParameter> { public static BeanToMapConvertor getBeanToMapConvertor() { return beanToMapConvertor; } final static private BeanToMapConvertor beanToMapConvertor = BeanToMapBuilder.newBuilder() .enableFieldNameAnnotation() .valueConvertor(new ValueConvertor()) .flatableObject(obj->{ boolean flatable = BeanToMapConvertor.DEFAULT_FLATABLE.apply(obj); return flatable && !Resource.class.isInstance(obj) && !byte[].class.isInstance(obj) && !MultipartFile.class.isInstance(obj); }) .build(); // final private AnnotationAttributes requestMappingAttributes; private RequestMethod requestMethod; private String path; private Class<?> componentType; private Optional<String> acceptHeader; /*** * resttemplatecontentTypeconsumeshttpMessageConvertor * HttpEntityRequestCallback#doWithRequest -> requestContentType */ private Optional<String> contentType; private String[] headers; private int apiHeaderCallbackIndex = -1; private int headerParameterIndex = -1; private CustomResponseHandler<?> customResponseHandler; private ApiErrorHandler apiErrorHandler; public ApiClientMethod(Method method) { super(method); componentType = ReflectUtils.getGenricType(method.getGenericReturnType(), 0, null); } public void initialize(){ if(!ApiClientUtils.isRequestMappingPresent()){ throw new ApiClientException(ApiClientErrors.REQUEST_MAPPING_NOT_FOUND); } Optional<AnnotationAttributes> requestMapping = SpringUtils.getAnnotationAttributes(method, RequestMapping.class); if(!requestMapping.isPresent()){ throw new ApiClientException(ApiClientErrors.REQUEST_MAPPING_NOT_FOUND, method, null); } AnnotationAttributes reqestMappingAttrs = requestMapping.get(); //SpringMvcContract#parseAndValidateMetadata this.acceptHeader = LangUtils.getFirstOptional(reqestMappingAttrs.getStringArray("produces")); this.contentType = LangUtils.getFirstOptional(reqestMappingAttrs.getStringArray("consumes")); this.headers = reqestMappingAttrs.getStringArray("headers"); String[] paths = reqestMappingAttrs.getStringArray("value"); path = LangUtils.isEmpty(paths)?"":paths[0]; RequestMethod[] methods = (RequestMethod[])reqestMappingAttrs.get("method"); requestMethod = LangUtils.isEmpty(methods)?RequestMethod.GET:methods[0]; findParameterByType(ApiHeaderCallback.class).ifPresent(p->{ this.apiHeaderCallbackIndex = p.getParameterIndex(); }); findParameterByType(HttpHeaders.class).ifPresent(p->{ this.headerParameterIndex = p.getParameterIndex(); }); ResponseHandler resHandler = AnnotatedElementUtils.getMergedAnnotation(getMethod(), ResponseHandler.class); if (resHandler==null){ resHandler = AnnotatedElementUtils.getMergedAnnotation(getDeclaringClass(), ResponseHandler.class); } if (resHandler!=null){ Class<? extends CustomResponseHandler<?>> handlerClass = resHandler.value(); if (handlerClass!=NullHandler.class) { CustomResponseHandler<?> customHandler = createAndInitComponent(resHandler.value()); this.customResponseHandler = customHandler; } Class<? extends ApiErrorHandler> errorHandlerClass = resHandler.errorHandler(); if (errorHandlerClass==DefaultErrorHandler.class) { this.apiErrorHandler = obtainDefaultApiErrorHandler(); } else { this.apiErrorHandler = createAndInitComponent(errorHandlerClass); } } else { this.apiErrorHandler = obtainDefaultApiErrorHandler(); } } protected ApiErrorHandler obtainDefaultApiErrorHandler() { return ApiErrorHandler.DEFAULT; } private <T> T createAndInitComponent(Class<T> clazz) { T component = null; if (Springs.getInstance().isInitialized()){ component = Springs.getInstance().getBean(clazz); if (component==null) { component = ReflectUtils.newInstance(clazz); SpringUtils.injectAndInitialize(Springs.getInstance().getAppContext(), component); } } else { Logger logger = ApiClientUtils.getApiclientlogger(); if (logger.isWarnEnabled()) { logger.warn("spring application not initialized, use reflection to create component: {}", clazz); } component = ReflectUtils.newInstance(clazz); } return component; } public CustomResponseHandler<?> getCustomResponseHandler() { return customResponseHandler; } public ApiErrorHandler getApiErrorHandler() { return apiErrorHandler; } public Optional<ApiHeaderCallback> getApiHeaderCallback(Object[] args){ return apiHeaderCallbackIndex<0?Optional.empty():Optional.ofNullable((ApiHeaderCallback)args[apiHeaderCallbackIndex]); } public Optional<HttpHeaders> getHttpHeaders(Object[] args){ return headerParameterIndex<0?Optional.empty():Optional.ofNullable((HttpHeaders)args[headerParameterIndex]); } public String[] getHeaders() { return headers; } public Optional<String> getAcceptHeader() { return acceptHeader; } public Optional<String> getContentType() { return contentType; } public Map<String, Object> getUriVariables(Object[] args){ if(LangUtils.isEmpty(args)){ return Collections.emptyMap(); } List<ApiClientMethodParameter> urlVariableParameters = parameters.stream() .filter(p->{ return isUriVariables(p); }) .collect(Collectors.toList()); // boolean parameterNameAsPrefix = urlVariableParameters.size()>1; Map<String, Object> values = toMap(urlVariableParameters, args).toSingleValueMap(); return values; } public Map<String, ?> getQueryStringParameters(Object[] args){ if(LangUtils.isEmpty(args)){ return Collections.emptyMap(); } List<ApiClientMethodParameter> queryParameters = parameters.stream() .filter(p->isQueryStringParameters(p)) .collect(Collectors.toList()); boolean parameterNameAsPrefix = queryParameters.size()>1; Map<String, ?> values = toMap(queryParameters, args, parameterNameAsPrefix).toSingleValueMap(); return values; } protected boolean isQueryStringParameters(ApiClientMethodParameter p){ if(requestMethod==RequestMethod.POST || requestMethod==RequestMethod.PATCH){ //postRequestParamqueryString return p.hasParameterAnnotation(RequestParam.class); } return !isUriVariables(p) && !isSpecalPemerater(p); } protected boolean isUriVariables(ApiClientMethodParameter p){ return p.hasParameterAnnotation(PathVariable.class); } public Map<String, ?> getPathVariables(Object[] args){ if(LangUtils.isEmpty(args)){ return Collections.emptyMap(); } List<ApiClientMethodParameter> pathVariables = parameters.stream() .filter(p->{ return p.hasParameterAnnotation(PathVariable.class); }) .collect(Collectors.toList()); /*Object pvalue = null; for(ApiClientMethodParameter parameter : pathVariables){ pvalue = args[parameter.getParameterIndex()]; handleArg(values, parameter, pvalue); }*/ Map<String, ?> values = toMap(pathVariables, args).toSingleValueMap(); return values; } public Object getRequestBody(Object[] args){ if(!RestUtils.isRequestBodySupportedMethod(requestMethod)){ throw new RestClientException("unsupported request body method: " + method); } List<ApiClientMethodParameter> requestBodyParameters = parameters.stream() .filter(p->{ return p.hasParameterAnnotation(RequestBody.class); }) .collect(Collectors.toList()); if(requestBodyParameters.isEmpty()){ //RequestBody // Object values = toMap(parameters, args); Object values = null; if(LangUtils.isEmpty(args)){ return null; } //requestBodyrequestBody List<ApiClientMethodParameter> bodyableParameters = parameters.stream() .filter(p->!isSpecalPemerater(p) && !isQueryStringParameters(p)) .collect(Collectors.toList()); // List<ApiClientMethodParameter> bodyableParameters = parameters; if(LangUtils.isEmpty(bodyableParameters)){ return null; } // boolean parameterNameAsPrefix = bodyableParameters.size()>1; // boolean parameterNameAsPrefix = false; //requestBodycontentType if(getContentType().isPresent()){ String contentType = getContentType().get(); MediaType consumerMediaType = MediaType.parseMediaType(contentType); if(MediaType.APPLICATION_FORM_URLENCODED.equals(consumerMediaType) || MediaType.MULTIPART_FORM_DATA.equals(consumerMediaType)){ //formmultipleMap values = toMap(bodyableParameters, args, parameterNameAsPrefix); }else{ //contentTypejsonmap // values = args.length==1?args[0]:toMap(parameters, args).toSingleValueMap(); values = args.length==1?args[0]:toMap(bodyableParameters, args, parameterNameAsPrefix).toSingleValueMap(); // values = args.length==1?args[0]:toMap(parameters, args); // values = toMap(parameters, args); } }else{ //form values = toMap(bodyableParameters, args, parameterNameAsPrefix); } return values; }else if(requestBodyParameters.size()==1){ return args[requestBodyParameters.get(0).getParameterIndex()]; }else{ throw new ApiClientException(ApiClientErrors.REQUEST_BODY_ONLY_ONCE, method, null); } /*if(requestBodyParameter.isPresent()){ return args[requestBodyParameter.get().getParameterIndex()]; } return null;*/ } protected MultiValueMap<String, Object> toMap(List<ApiClientMethodParameter> methodParameters, Object[] args){ return toMap(methodParameters, args, true); } protected MultiValueMap<String, Object> toMap(List<ApiClientMethodParameter> methodParameters, Object[] args, boolean parameterNameAsPrefix){ MultiValueMap<String, Object> values = new LinkedMultiValueMap<>(methodParameters.size()); for(ApiClientMethodParameter parameter : methodParameters){ if(isSpecalPemerater(parameter)){ continue; } Object pvalue = args[parameter.getParameterIndex()]; handleArg(values, parameter, pvalue, parameterNameAsPrefix); } return values; } protected boolean isSpecalPemerater(ApiClientMethodParameter parameter){ return parameter.getParameterIndex()==apiHeaderCallbackIndex || parameter.getParameterIndex()==headerParameterIndex; } protected void handleArg(MultiValueMap<String, Object> values, ApiClientMethodParameter mp, final Object pvalue, boolean parameterNameAsPrefix){ if(pvalue instanceof ApiArgumentTransformer){ Object val = ((ApiArgumentTransformer)pvalue).asApiValue(); values.add(mp.getParameterName(), val); return ; } String prefix = ""; Object paramValue = pvalue; if(mp.hasParameterAnnotation(RequestParam.class)){ RequestParam params = mp.getParameterAnnotation(RequestParam.class); if(pvalue==null && params.required() && (paramValue=params.defaultValue())==ValueConstants.DEFAULT_NONE){ throw new BaseException("parameter["+params.name()+"] must be required : " + mp.getParameterName()); } parameterNameAsPrefix = true; }else if(isUriVariables(mp) || mp.hasParameterAnnotation(FieldName.class)){ parameterNameAsPrefix = true; }else if(beanToMapConvertor.isMappableValue(pvalue)){ parameterNameAsPrefix = true; } if(parameterNameAsPrefix){ prefix = mp.getParameterName(); } beanToMapConvertor.flatObject(prefix, paramValue, (k, v, ctx)->{ values.add(k, v); }); /*if(falatable){ // beanToMapConvertor.flatObject(mp.getParameterName(), paramValue, (k, v, ctx)->{ beanToMapConvertor.flatObject(mp.getParameterName(), paramValue, (k, v, ctx)->{ if(v instanceof Enum){ Enum<?> e = (Enum<?>)v; if(e instanceof ValueEnum){ v = ((ValueEnum<?>)e).getValue(); }else{//name v = e.name(); } }else if(v instanceof Resource){ //ignorestring }else{ v = v.toString(); } if(ctx!=null){ // System.out.println("ctx.getName():"+ctx.getName()); values.add(ctx.getName(), v); }else{ values.add(k, v); } // values.add(k, v); }); }else{ values.add(mp.getParameterName(), pvalue); }*/ } public String getPath() { return path; } public RequestMethod getRequestMethod() { return requestMethod; } public Class<?> getComponentType() { return componentType; } @Override protected ApiClientMethodParameter createMethodParameter(Method method, int parameterIndex, Parameter parameter) { return new ApiClientMethodParameter(method, parameter, parameterIndex); } public static class ApiClientMethodParameter extends BaseMethodParameter { private boolean injectProperties; public ApiClientMethodParameter(Method method, Parameter parameter, int parameterIndex) { super(method, parameter, parameterIndex); this.injectProperties = parameter.isAnnotationPresent(InjectProperties.class); } @Override public String obtainParameterName() { /*String pname = super.getParameterName(); if(StringUtils.isNotBlank(pname)){ return pname; }*/ String pname = getOptionalParameterAnnotation(RequestParam.class).map(rp->rp.value()).orElseGet(()->{ // return getOptionalParameterAnnotation(PathVariable.class).map(pv->pv.value()).orElse(null); return getOptionalParameterAnnotation(PathVariable.class).map(pv->pv.value()).orElseGet(()->{ return getOptionalParameterAnnotation(FieldName.class).map(fn->fn.value()).orElse(null); }); }); if(StringUtils.isBlank(pname)){ /*pname = getOptionalParameterAnnotation(PathVariable.class).map(pv->pv.value()).orElse(null); if(StringUtils.isNotBlank(pname)){ return pname; }*/ if(parameter!=null && parameter.isNamePresent()){ pname = parameter.getName(); }else{ pname = String.valueOf(getParameterIndex()); } } // this.setParameterName(pname); return pname; } public boolean isInjectProperties() { return injectProperties; } } }
package com.sequenceiq.cloudbreak.converter; import static com.sequenceiq.cloudbreak.service.network.ExposedService.SHIPYARD; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import org.apache.commons.lang3.BooleanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; import com.google.api.client.repackaged.com.google.common.base.Strings; import com.google.common.base.Optional; import com.sequenceiq.ambari.client.AmbariClient; import com.sequenceiq.cloudbreak.api.model.AmbariStackDetailsJson; import com.sequenceiq.cloudbreak.api.model.ClusterResponse; import com.sequenceiq.cloudbreak.api.model.HostGroupJson; import com.sequenceiq.cloudbreak.controller.validation.blueprint.BlueprintValidator; import com.sequenceiq.cloudbreak.controller.validation.blueprint.StackServiceComponentDescriptor; import com.sequenceiq.cloudbreak.controller.validation.blueprint.StackServiceComponentDescriptors; import com.sequenceiq.cloudbreak.core.CloudbreakSecuritySetupException; import com.sequenceiq.cloudbreak.domain.AmbariStackDetails; import com.sequenceiq.cloudbreak.domain.Blueprint; import com.sequenceiq.cloudbreak.domain.Cluster; import com.sequenceiq.cloudbreak.domain.HostGroup; import com.sequenceiq.cloudbreak.domain.InstanceMetaData; import com.sequenceiq.cloudbreak.domain.RDSConfig; import com.sequenceiq.cloudbreak.domain.Stack; import com.sequenceiq.cloudbreak.service.TlsSecurityService; import com.sequenceiq.cloudbreak.service.cluster.AmbariClientProvider; import com.sequenceiq.cloudbreak.service.cluster.flow.AmbariViewProvider; import com.sequenceiq.cloudbreak.service.network.NetworkUtils; import com.sequenceiq.cloudbreak.service.network.Port; import com.sequenceiq.cloudbreak.service.stack.flow.HttpClientConfig; @Component public class ClusterToJsonConverter extends AbstractConversionServiceAwareConverter<Cluster, ClusterResponse> { private static final Logger LOGGER = LoggerFactory.getLogger(ClusterToJsonConverter.class); private static final int SECONDS_PER_MINUTE = 60; private static final int MILLIS_PER_SECOND = 1000; @Inject private BlueprintValidator blueprintValidator; @Inject private StackServiceComponentDescriptors stackServiceComponentDescs; @Inject private TlsSecurityService tlsSecurityService; @Inject private AmbariClientProvider ambariClientProvider; @Inject private AmbariViewProvider ambariViewProvider; @Override public ClusterResponse convert(Cluster source) { ClusterResponse clusterResponse = new ClusterResponse(); clusterResponse.setId(source.getId()); clusterResponse.setName(source.getName()); clusterResponse.setStatus(source.getStatus().name()); clusterResponse.setStatusReason(source.getStatusReason()); if (source.getBlueprint() != null) { clusterResponse.setBlueprintId(source.getBlueprint().getId()); } if (source.getUpSince() != null && source.isAvailable()) { long now = new Date().getTime(); long uptime = now - source.getUpSince(); int minutes = (int) ((uptime / (MILLIS_PER_SECOND * SECONDS_PER_MINUTE)) % SECONDS_PER_MINUTE); int hours = (int) (uptime / (MILLIS_PER_SECOND * SECONDS_PER_MINUTE * SECONDS_PER_MINUTE)); clusterResponse.setHoursUp(hours); clusterResponse.setMinutesUp(minutes); } else { clusterResponse.setHoursUp(0); clusterResponse.setMinutesUp(0); } clusterResponse.setLdapRequired(source.isLdapRequired()); if (source.getSssdConfig() != null) { clusterResponse.setSssdConfigId(source.getSssdConfig().getId()); } AmbariStackDetails ambariStackDetails = source.getAmbariStackDetails(); if (ambariStackDetails != null) { clusterResponse.setAmbariStackDetails(getConversionService().convert(ambariStackDetails, AmbariStackDetailsJson.class)); } RDSConfig rdsConfig = source.getRdsConfig(); if (rdsConfig != null) { clusterResponse.setRdsConfigId(rdsConfig.getId()); } source = provideViewDefinitions(source); if (source.getAttributes() != null) { clusterResponse.setAttributes(source.getAttributes().getMap()); } clusterResponse.setAmbariServerIp(source.getAmbariIp()); clusterResponse.setUserName(source.getUserName()); clusterResponse.setPassword(source.getPassword()); clusterResponse.setDescription(source.getDescription() == null ? "" : source.getDescription()); clusterResponse.setHostGroups(convertHostGroupsToJson(source.getHostGroups())); clusterResponse.setServiceEndPoints(prepareServiceEndpointsMap(source.getHostGroups(), source.getBlueprint(), source.getAmbariIp(), source.getEnableShipyard())); clusterResponse.setEnableShipyard(source.getEnableShipyard()); clusterResponse.setConfigStrategy(source.getConfigStrategy()); return clusterResponse; } private Cluster provideViewDefinitions(Cluster source) { if ((source.getAttributes().getValue() == null || ambariViewProvider.isViewDefinitionNotProvided(source)) && !Strings.isNullOrEmpty(source.getAmbariIp())) { try { HttpClientConfig clientConfig = tlsSecurityService.buildTLSClientConfig(source.getStack().getId(), source.getAmbariIp()); AmbariClient ambariClient = ambariClientProvider.getAmbariClient(clientConfig, source.getStack().getGatewayPort(), source.getUserName(), source.getPassword()); return ambariViewProvider.provideViewInformation(ambariClient, source); } catch (CloudbreakSecuritySetupException e) { LOGGER.error("Unable to setup ambari client tls configs: ", e); } } return source; } private Set<HostGroupJson> convertHostGroupsToJson(Set<HostGroup> hostGroups) { Set<HostGroupJson> jsons = new HashSet<>(); for (HostGroup hostGroup : hostGroups) { jsons.add(getConversionService().convert(hostGroup, HostGroupJson.class)); } return jsons; } private Map<String, String> prepareServiceEndpointsMap(Set<HostGroup> hostGroups, Blueprint blueprint, String ambariIp, Boolean shipyardEnabled) { Map<String, String> result = new HashMap<>(); List<Port> ports = NetworkUtils.getPorts(Optional.<Stack>absent()); collectPortsOfAdditionalServices(result, ambariIp, shipyardEnabled); try { JsonNode hostGroupsNode = blueprintValidator.getHostGroupNode(blueprint); Map<String, HostGroup> hostGroupMap = blueprintValidator.createHostGroupMap(hostGroups); for (JsonNode hostGroupNode : hostGroupsNode) { String hostGroupName = blueprintValidator.getHostGroupName(hostGroupNode); JsonNode componentsNode = blueprintValidator.getComponentsNode(hostGroupNode); HostGroup actualHostgroup = hostGroupMap.get(hostGroupName); String serviceAddress; if (actualHostgroup.getConstraint().getInstanceGroup() != null) { InstanceMetaData next = actualHostgroup.getConstraint().getInstanceGroup().getInstanceMetaData().iterator().next(); serviceAddress = next.getPublicIpWrapper(); } else { serviceAddress = actualHostgroup.getHostMetadata().iterator().next().getHostName(); } for (JsonNode componentNode : componentsNode) { String componentName = componentNode.get("name").asText(); StackServiceComponentDescriptor componentDescriptor = stackServiceComponentDescs.get(componentName); collectServicePorts(result, ports, serviceAddress, componentDescriptor); } } } catch (Exception ex) { return result; } return result; } private void collectPortsOfAdditionalServices(Map<String, String> result, String ambariIp, Boolean shipyardEnabled) { if (BooleanUtils.isTrue(shipyardEnabled)) { Port shipyardPort = NetworkUtils.getPortByServiceName(SHIPYARD); result.put(shipyardPort.getName(), String.format("%s:%s%s", ambariIp, shipyardPort.getPort(), shipyardPort.getExposedService().getPostFix())); } } private void collectServicePorts(Map<String, String> result, List<Port> ports, String address, StackServiceComponentDescriptor componentDescriptor) { if (componentDescriptor != null && componentDescriptor.isMaster()) { for (Port port : ports) { if (port.getExposedService().getServiceName().equals(componentDescriptor.getName())) { result.put(port.getExposedService().getPortName(), String.format("%s:%s%s", address, port.getPort(), port.getExposedService().getPostFix())); } } } } }
package dk.netarkivet.harvester.scheduler; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import dk.netarkivet.common.lifecycle.ComponentLifeCycle; import dk.netarkivet.common.lifecycle.PeriodicTaskExecutor; import dk.netarkivet.common.utils.NotificationType; import dk.netarkivet.common.utils.NotificationsFactory; import dk.netarkivet.common.utils.Settings; import dk.netarkivet.harvester.HarvesterSettings; import dk.netarkivet.harvester.datamodel.HarvestDefinition; import dk.netarkivet.harvester.datamodel.HarvestDefinitionDAO; import dk.netarkivet.harvester.scheduler.jobgen.JobGenerator; import dk.netarkivet.harvester.scheduler.jobgen.JobGeneratorFactory; /** * Handles the generation of new jobs based on the harvest definitions in * persistent storage. The <code>HarvestJobGenerator</code> continuously scans * the harvest definition database for harvest which should be run now. If a HD * defines a harvest which should be run, a Harvest Job is created in the * harvest job database. */ public class HarvestJobGenerator implements ComponentLifeCycle { /** The set of HDs (or rather their OIDs) that are currently being * scheduled in a separate thread. * This set is a SynchronizedSet */ protected static Set<Long> harvestDefinitionsBeingScheduled = Collections.synchronizedSet(new HashSet<Long>()); /** Used the store the currenttimeMillis when the scheduling of * a particular harvestdefinition # started or when last * a warning was issued. */ protected static Map<Long, Long> schedulingStartedMap = Collections.synchronizedMap(new HashMap<Long, Long>()); /** The class logger. */ private static final Log log = LogFactory.getLog(HarvestJobGenerator.class.getName()); /** The executor used to schedule the generator jobs. */ private PeriodicTaskExecutor genExec; /** The HarvestDefinitionDAO used by the HarvestJobGenerator. */ private static final HarvestDefinitionDAO haDefinitionDAO = HarvestDefinitionDAO.getInstance(); /** * Starts the job generation scheduler. */ @Override public void start() { genExec = new PeriodicTaskExecutor( "JobGeneratorTask", new JobGeneratorTask(), 0, Settings.getInt(HarvesterSettings.GENERATE_JOBS_PERIOD)); } @Override public void shutdown() { if (genExec != null) { genExec.shutdown(); } } /** * Contains the functionality for the individual JobGenerations. */ static class JobGeneratorTask implements Runnable { @Override public synchronized void run() { try { generateJobs(new Date()); } catch (Exception e) { log.info("Exception caught at fault barrier while generating jobs.", e); } } /** * Check if jobs should be generated for any ready harvest definitions * for the specified time. * @param timeToGenerateJobsFor Jobs will be generated which should be * run at this time. * Note: In a production system the provided time will normally be * current time, but during testing we need to simulated other * points-in-time */ static void generateJobs(Date timeToGenerateJobsFor) { final Iterable<Long> readyHarvestDefinitions = haDefinitionDAO.getReadyHarvestDefinitions( timeToGenerateJobsFor); for (final Long id : readyHarvestDefinitions) { // Make every HD run in its own thread, but at most once. if (harvestDefinitionsBeingScheduled.contains(id)) { if (takesSuspiciouslyLongToSchedule(id)) { String harvestName = haDefinitionDAO.getHarvestName(id); String errMsg = "Not creating jobs for harvestdefinition + id + " (" + harvestName + ")" + " as the previous scheduling is still running"; if (haDefinitionDAO.isSnapshot(id)) { // Log only at level debug if the ID represents // is a snapshot harvestdefinition, which are only run // once anyway log.debug(errMsg); } else { // Log at level WARN, and send a notification, if it is time log.warn(errMsg); NotificationsFactory.getInstance().notify(errMsg, NotificationType.WARNING); } } continue; } final HarvestDefinition harvestDefinition = haDefinitionDAO.read(id); harvestDefinitionsBeingScheduled.add(id); schedulingStartedMap.put(id, System.currentTimeMillis()); if (!harvestDefinition.runNow(timeToGenerateJobsFor)) { log.trace("The harvestdefinition + harvestDefinition.getName() + "' should not run now."); log.trace("numEvents: " + harvestDefinition.getNumEvents()); continue; } log.info("Starting to create jobs for harvest definition + harvestDefinition.getName() + ")"); new Thread("JobGeneratorTask-" + id) { public void run() { try { JobGenerator jobGen = JobGeneratorFactory.getInstance(); int jobsMade = jobGen.generateJobs(harvestDefinition); if (jobsMade > 0) { log.info("Created " + jobsMade + " jobs for harvest definition (" + harvestDefinition.getName() + ")"); } else { String msg = "No jobs created for harvest definition '" + harvestDefinition.getName() + "'. Probable cause: " + "harvest tries to continue harvest that is already finished "; log.warn(msg); NotificationsFactory.getInstance().notify(msg, NotificationType.WARNING); } haDefinitionDAO.update(harvestDefinition); } catch (Throwable e) { try { HarvestDefinition hd = haDefinitionDAO.read( harvestDefinition.getOid()); hd.setActive(false); haDefinitionDAO.update(hd); String errMsg = "Exception while scheduling" + "harvestdefinition + harvestDefinition.getName() + "). The " + "harvestdefinition has been deactivated!"; log.warn(errMsg, e); NotificationsFactory.getInstance(). notify(errMsg, NotificationType.ERROR, e); } catch (Exception e1) { String errMsg = "Exception while scheduling" + "harvestdefinition + harvestDefinition.getName() + "). The harvestdefinition couldn't be " + "deactivated!"; log.warn(errMsg, e); log.warn("Unable to deactivate", e1); NotificationsFactory.getInstance(). notify(errMsg, NotificationType.ERROR, e); } } finally { harvestDefinitionsBeingScheduled. remove(id); schedulingStartedMap.remove(id); log.debug("Removed HD #" + id + "(" + harvestDefinition.getName() + ") from list of harvestdefinitions to be " + "scheduled. Harvestdefinitions still to " + "be scheduled: " + harvestDefinitionsBeingScheduled); } } }.start(); } } /** * Find out if a scheduling takes more than is acceptable * currently 5 minutes. * @param harvestId A given harvestId * @return true, if a scheduling of the given harvestId has taken more * than 5 minutes, or false, if not or no scheduling for this harvestId * is underway */ private static boolean takesSuspiciouslyLongToSchedule(Long harvestId) { // acceptable delay before issuing warning is currently hard-wired to // 5 minutes (5 * 60 * 1000 milliseconds) final long acceptableDelay = 5 * 60 * 1000; Long timewhenscheduled = schedulingStartedMap.get(harvestId); if (timewhenscheduled == null) { return false; } else { long now = System.currentTimeMillis(); if (timewhenscheduled + acceptableDelay < now) { // updates the schedulingStartedMap with currenttime for //the given harvestID when returning true schedulingStartedMap.put(harvestId, now); return true; } else { return false; } } } } //Hack, used by test static void clearGeneratingJobs() { harvestDefinitionsBeingScheduled.clear(); } }
package edu.stanford.nlp.naturalli.entail; import com.google.gson.Gson; import edu.stanford.nlp.classify.Classifier; import edu.stanford.nlp.classify.LinearClassifier; import edu.stanford.nlp.io.IOUtils; import edu.stanford.nlp.naturalli.ProcessPremise; import edu.stanford.nlp.naturalli.ProcessQuery; import edu.stanford.nlp.naturalli.QRewrite; import edu.stanford.nlp.naturalli.SentenceFragment; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.simple.Sentence; import edu.stanford.nlp.stats.Counter; import edu.stanford.nlp.util.*; import java.io.*; import java.util.*; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static edu.stanford.nlp.util.logging.Redwood.Util.*; /** * An interface for calling NaturalLI in alignment mode. * * @author Gabor Angeli */ public class NaturalLIClassifier implements EntailmentClassifier { @Execution.Option(name="naturalli.use", gloss="If true, incorporate input from NaturalLI") private static boolean USE_NATURALLI = true; @Execution.Option(name="naturalli.weight", gloss="The weight to incorporate NaturalLI with") private static double ALIGNMENT_WEIGHT = 0.00; @Execution.Option(name="naturalli.incache", gloss="The cache to read from") private static String NATURALLI_INCACHE = "tmp/naturalli.cache"; @Execution.Option(name="naturalli.outcache", gloss="The cache to write from") private static String NATURALLI_OUTCACHE = "tmp/naturalli.cacheout"; static final String COUNT_ALIGNED = "count_aligned"; static final String COUNT_ALIGNABLE = "count_alignable"; static final String COUNT_UNALIGNED = "count_unaligned"; static final String COUNT_UNALIGNABLE_PREMISE = "count_unalignable_premise"; static final String COUNT_UNALIGNABLE_CONCLUSION = "count_unalignable_conclusion"; static final String COUNT_UNALIGNABLE_JOINT = "count_unalignable_joint"; static final String COUNT_PREMISE = "count_premise"; static final String COUNT_CONCLUSkION = "count_conclusion"; static final String PERCENT_ALIGNABLE_PREMISE = "percent_alignable_premise"; static final String PERCENT_ALIGNABLE_CONCLUSION = "percent_alignable_conclusion"; static final String PERCENT_ALIGNABLE_JOINT = "percent_alignable_joint"; static final String PERCENT_ALIGNED_PREMISE = "percent_aligned_premise"; static final String PERCENT_ALIGNED_CONCLUSION = "percent_aligned_conclusion"; static final String PERCENT_ALIGNED_JOINT = "percent_aligned_joint"; static final String PERCENT_UNALIGNED_PREMISE = "percent_unaligned_premise"; static final String PERCENT_UNALIGNED_CONCLUSION = "percent_unaligned_conclusion"; static final String PERCENT_UNALIGNED_JOINT = "percent_unaligned_joint"; static final String PERCENT_UNALIGNABLE_PREMISE = "percent_unalignable_premise"; static final String PERCENT_UNALIGNABLE_CONCLUSION = "percent_unalignable_conclusion"; static final String PERCENT_UNALIGNABLE_JOINT = "percent_unalignable_joint"; private static final Pattern truthPattern = Pattern.compile("\"truth\": *([0-9\\.]+)"); private static final Pattern alignmentIndexPattern = Pattern.compile("\"closestSoftAlignment\": *([0-9]+)"); private static final Pattern alignmentScoresPattern = Pattern.compile("\"closestSoftAlignmentScores\": *\\[ *((:?-?(:?[0-9\\.]+|inf), *)*-?(:?[0-9\\.]+|inf)) *\\]"); private static final Pattern hardGuessPattern = Pattern.compile("\"hardGuess\": \"(true|false|uknown)\""); private static final Pattern softGuessPattern = Pattern.compile("\"softGuess\": \"(true|false|uknown)\""); /** * A query to NaturalLI. Serialized with GSON. */ private static final class NaturalLIQuery { public String[] premises; public String hypothesis; public NaturalLIQuery(List<String> premises, String hypothesis) { this.premises = premises.toArray(new String[premises.size()]); } } /** * A response to a NaturalLI query. Populated with GSON. */ private static final class NaturalLIResponse { public int numResults; public int totalTicks; public String hardGuess; public String softGuess; public String query; public String bestPremise; public boolean success; public int closestSoftAlignment; public double[] closestSoftAlignmentScores; public double[] closestSoftAlignmentSearchCosts; } private static final class NaturalLIPair { public NaturalLIQuery query; public NaturalLIResponse response; } public final String searchProgram; public final Classifier<Trilean, String> impl; public final EntailmentFeaturizer featurizer; private BufferedReader fromNaturalLI; private OutputStreamWriter toNaturalLI; private final Counter<String> weights; private final Lazy<StanfordCoreNLP> pipeline = Lazy.of(() -> ProcessPremise.constructPipeline("depparse") ); private final Map<NaturalLIQuery, NaturalLIResponse> naturalliCache = new HashMap<>(); private PrintWriter naturalliWriteCache; NaturalLIClassifier(String naturalliSearch, EntailmentFeaturizer featurizer, Classifier<Trilean, String> impl) { this.searchProgram = naturalliSearch; this.impl = impl; this.featurizer = featurizer; this.weights = ((LinearClassifier<Trilean,String>) impl).weightsAsMapOfCounters().get(Trilean.TRUE); init(); } NaturalLIClassifier(String naturalliSearch, EntailmentClassifier underlyingImpl) { this.searchProgram = naturalliSearch; if (underlyingImpl instanceof SimpleEntailmentClassifier) { this.impl = ((SimpleEntailmentClassifier) underlyingImpl).impl; this.featurizer = ((SimpleEntailmentClassifier) underlyingImpl).featurizer; } else { throw new IllegalArgumentException("Cannot create NaturalLI classifier from " + underlyingImpl.getClass()); } this.weights = ((LinearClassifier<Trilean,String>) impl).weightsAsMapOfCounters().get(Trilean.TRUE); init(); } /** * Initialize the pipe to NaturalLI. */ private synchronized void init() { try { Gson gson = new Gson(); if (new File(NATURALLI_INCACHE).exists()) { FileReader reader = new FileReader(NATURALLI_INCACHE); NaturalLIPair entry; while ((entry = gson.fromJson(reader, NaturalLIPair.class)) != null) { naturalliCache.put(entry.query, entry.response); } } naturalliWriteCache = new PrintWriter(new FileWriter(NATURALLI_OUTCACHE)); forceTrack("Creating connection to NaturalLI"); ProcessBuilder searcherBuilder = new ProcessBuilder(searchProgram); final Process searcher = searcherBuilder.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { searcher.destroy(); } }); // Gobble naturalli.stderr to real stderr Writer errWriter = new BufferedWriter(new FileWriter(new File("/dev/null"))); // Writer errWriter = new BufferedWriter(new OutputStreamWriter(System.err)); StreamGobbler errGobbler = new StreamGobbler(searcher.getErrorStream(), errWriter); errGobbler.start(); // Create the pipe fromNaturalLI = new BufferedReader(new InputStreamReader(searcher.getInputStream())); toNaturalLI = new OutputStreamWriter(new BufferedOutputStream(searcher.getOutputStream())); // Set some parameters toNaturalLI.write("%defaultCosts = true\n"); // toNaturalLI.write("%skipNegationSearch=true\n"); toNaturalLI.write("%maxTicks=500000\n"); toNaturalLI.flush(); endTrack("Creating connection to NaturalLI"); } catch (IOException e) { throw new RuntimeException(e); } } /** Convert a plain-text string to a CoNLL parse tree that can be fed into NaturalLI */ private String toParseTree(String text) { Pointer<String> debug = new Pointer<>(); try { String annotated = ProcessQuery.annotate(QRewrite.FOR_PREMISE, text, pipeline.get(), debug, true); return annotated; } catch (AssertionError e) { err("Assertion error when processing sentence: " + text); return "cats\t0\troot\t0"; } } /** Convert a comma-separated list to a list of doubles */ private List<Double> parseDoubleList(String list) { return Arrays.stream(list.split(" *, *")).map(x -> {switch (x) { case "-inf": return Double.NEGATIVE_INFINITY; case "inf": return Double.POSITIVE_INFINITY; default: return Double.parseDouble(x); }}).collect(Collectors.toList()); } /** * Get the best alignment score between the hypothesis and the best premise. * @param premises The premises to possibly align to. * @param hypothesis The hypothesis we are testing. * @return A triple: the truth of the hypothesis, the best alignment, and the best soft alignment scores. * @throws IOException Thrown if the pipe to NaturalLI is broken. */ private synchronized NaturalLIResponse queryNaturalLI(List<String> premises, String hypothesis) throws IOException { NaturalLIQuery query = new NaturalLIQuery(premises, hypothesis); if (naturalliCache.containsKey(query)) { return naturalliCache.get(query); } // Write the premises // Note: we write all the premises first so that the index of the costs // matches the index of the premise. Also, so we don't overflow the soft match buffer // with entailments from the first premise. for (String premise : premises) { try { String tree = toParseTree(premise); if (tree.split("\n").length > 30) { // Tree is too long; don't write it or else the program will crash toNaturalLI.write(toParseTree("cats have tails")); } else { toNaturalLI.write(tree); } toNaturalLI.write("\n"); } catch (Exception e) { err("Caught exception: " + e.getClass().getSimpleName() + ": " + e.getMessage()); } } // Write entailments for (String premise : premises) { for (SentenceFragment entailment : ProcessPremise.forwardEntailments(premise, pipeline.get())) { if (!entailment.toString().equals(premise)) { try { String tree = ProcessQuery.conllDump(entailment.parseTree, false, true); if (tree.split("\n").length > 30) { // Tree is too long; don't write it or else the program will crash toNaturalLI.write(toParseTree("cats have tails")); } else { toNaturalLI.write(tree); } toNaturalLI.write("\n"); } catch (Exception e) { err("Caught exception: " + e.getClass().getSimpleName() + ": " + e.getMessage()); } } } } // Write the query toNaturalLI.write(toParseTree(hypothesis)); // Start the search toNaturalLI.write("\n\n"); toNaturalLI.flush(); // Read the result Matcher matcher; String json = fromNaturalLI.readLine(); Gson gson = new Gson(); NaturalLIResponse response = gson.fromJson(json, NaturalLIResponse.class); naturalliWriteCache.println(gson.toJson(response)); naturalliWriteCache.flush(); return response; } private double scoreBeforeNaturalli(Counter<String> features) { double sum = 0.0; for (Map.Entry<String, Double> entry : features.entrySet()) { switch (entry.getKey()) { case COUNT_ALIGNED: // this is the one that gets changed most case PERCENT_ALIGNED_PREMISE: case PERCENT_ALIGNED_CONCLUSION: case PERCENT_ALIGNED_JOINT: break; default: sum += weights.getCount(entry.getKey()) * features.getCount(entry.getKey()); } } return sum; } private double scoreAlignmentSimple(Counter<String> features) { double sum = 0.0; for (Map.Entry<String, Double> entry : features.entrySet()) { switch(entry.getKey()) { case COUNT_ALIGNED: case PERCENT_ALIGNED_PREMISE: case PERCENT_ALIGNED_CONCLUSION: case PERCENT_ALIGNED_JOINT: sum += weights.getCount(entry.getKey()) * features.getCount(entry.getKey()); break; default: // do nothing } } return sum; } @Override public Pair<Sentence, Double> bestScore(List<String> premisesText, String hypothesisText, Optional<String> focus, Optional<List<Double>> luceneScores, Function<Integer, Double> decay) { double max = Double.NEGATIVE_INFINITY; int argmax = -1; Sentence hypothesis = new Sentence(hypothesisText); List<Sentence> premises = premisesText.stream().map(Sentence::new).collect(Collectors.toList()); // Query NaturalLI NaturalLIResponse bestNaturalLIScores; try { bestNaturalLIScores = queryNaturalLI(premisesText, hypothesisText); } catch (IOException e) { throw new RuntimeException(e); } for (int i = 0; i < premises.size(); ++i) { // Featurize the pair Sentence premise = premises.get(i); Optional<Double> luceneScore = luceneScores.isPresent() ? Optional.of(luceneScores.get().get(i)) : Optional.empty(); Counter<String> features = featurizer.featurize(new EntailmentPair(Trilean.UNKNOWN, premise, hypothesis, focus, luceneScore), Optional.empty()); // Get the raw score double score = scoreBeforeNaturalli(features); double naturalLIScore = 0.0; if (USE_NATURALLI) { naturalLIScore = bestNaturalLIScores.closestSoftAlignmentScores[i]; } else { // double naturalLIScore = scoreAlignmentSimple(features); } score += naturalLIScore * ALIGNMENT_WEIGHT; assert !Double.isNaN(score); assert Double.isFinite(score); // Computer the probability double prob = 1.0 / (1.0 + Math.exp(-score)); // Discount the score if the focus is not present if (focus.isPresent()) { if (focus.get().contains(" ")) { if (!premise.text().toLowerCase().replaceAll("\\s+", " ").contains(focus.get().toLowerCase().replaceAll("\\s+", " "))) { prob *= 0.75; // Slight penalty for not matching a long focus } } else { if (!premise.text().toLowerCase().replaceAll("\\s+", " ").contains(focus.get().toLowerCase().replaceAll("\\s+", " "))) { prob *= 0.25; // Big penalty for not matching a short focus. } } } // Discount the score if NaturalLI thinks this conclusion is false if (USE_NATURALLI) { if (Trilean.fromString(bestNaturalLIScores.hardGuess).isFalse()) { prob *= 0.1; } else if (Trilean.fromString(bestNaturalLIScores.softGuess).isFalse()) { prob *= 0.5; } } // Take the argmax if (prob > max) { max = prob; argmax = i; } } return Pair.makePair(premises.get(argmax), max); } @Override public double truthScore(Sentence premise, Sentence hypothesis, Optional<String> focus, Optional<Double> luceneScore) { return bestScore(Collections.singletonList(premise.text()), hypothesis.text(), focus, luceneScore.isPresent() ? Optional.of(Collections.singletonList(luceneScore.get())) : Optional.empty(), i -> 1.0).second; } @Override public Trilean classify(Sentence premise, Sentence hypothesis, Optional<String> focus, Optional<Double> luceneScore) { return truthScore(premise, hypothesis, focus, luceneScore) >= 0.5 ? Trilean.TRUE : Trilean.FALSE; } @Override public Object serialize() { return Triple.makeTriple(searchProgram, featurizer, impl); } @SuppressWarnings("unchecked") public static NaturalLIClassifier deserialize(Object model) { Triple<String, EntailmentFeaturizer, Classifier<Trilean, String>> data = (Triple) model; return new NaturalLIClassifier(data.first, data.second, data.third()); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.uprm.gaming.graphic.nifty; //import com.sun.org.apache.bcel.internal.generic.IFEQ; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.NiftyEventSubscriber; import de.lessvoid.nifty.builder.PanelBuilder; import de.lessvoid.nifty.controls.Button; import de.lessvoid.nifty.controls.ButtonClickedEvent; import de.lessvoid.nifty.controls.CheckBox; import de.lessvoid.nifty.controls.CheckBoxStateChangedEvent; import de.lessvoid.nifty.controls.Label; import de.lessvoid.nifty.effects.EffectEventId; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.input.NiftyInputEvent; import de.lessvoid.nifty.screen.KeyInputHandler; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.screen.ScreenController; import de.lessvoid.nifty.controls.ListBox; import de.lessvoid.nifty.controls.Slider; import de.lessvoid.nifty.controls.SliderChangedEvent; import de.lessvoid.nifty.controls.button.builder.ButtonBuilder; import de.lessvoid.nifty.controls.checkbox.builder.CheckboxBuilder; import de.lessvoid.nifty.controls.label.builder.LabelBuilder; import de.lessvoid.nifty.controls.slider.builder.SliderBuilder; import de.lessvoid.nifty.elements.render.ImageRenderer; import de.lessvoid.nifty.render.NiftyImage; import de.lessvoid.nifty.tools.Color; import de.lessvoid.nifty.tools.SizeValue; import de.lessvoid.xml.xpp3.Attributes; import edu.uprm.gaming.GameEngine; import edu.uprm.gaming.entity.E_Machine; import edu.uprm.gaming.entity.E_Operation; import edu.uprm.gaming.entity.E_Operator; import edu.uprm.gaming.entity.E_Part; import edu.uprm.gaming.entity.E_Purchase; import edu.uprm.gaming.entity.E_Station; import edu.uprm.gaming.entity.E_Supplier; import edu.uprm.gaming.entity.E_TransportStore; import edu.uprm.gaming.graphic.nifty.controls.ActivityControl; import edu.uprm.gaming.graphic.nifty.controls.AssignOperatorControl; import edu.uprm.gaming.graphic.nifty.controls.CharactersControl; import edu.uprm.gaming.graphic.nifty.controls.FlowChartControl; import edu.uprm.gaming.graphic.nifty.controls.GameLogControl; import edu.uprm.gaming.graphic.nifty.controls.GameSetupControl; import edu.uprm.gaming.graphic.nifty.controls.MachineControl; import edu.uprm.gaming.graphic.nifty.controls.OperatorControl; import edu.uprm.gaming.graphic.nifty.controls.OrderControl; import edu.uprm.gaming.graphic.nifty.controls.OverallControl; import edu.uprm.gaming.graphic.nifty.controls.PartControl; import edu.uprm.gaming.graphic.nifty.controls.PriorityControl; import edu.uprm.gaming.graphic.nifty.controls.StationControl; import edu.uprm.gaming.graphic.nifty.controls.StorageCostControl; import edu.uprm.gaming.graphic.nifty.controls.StorageStationControl; import edu.uprm.gaming.graphic.nifty.controls.SupplierControl; import edu.uprm.gaming.graphic.nifty.controls.UnitLoadControl; import edu.uprm.gaming.utils.MessageType; import edu.uprm.gaming.utils.Messages; import edu.uprm.gaming.utils.ObjectState; import edu.uprm.gaming.utils.OperatorCategory; import edu.uprm.gaming.utils.Params; import edu.uprm.gaming.utils.Sounds; import edu.uprm.gaming.utils.StationType; import edu.uprm.gaming.utils.Status; import edu.uprm.gaming.utils.TypeActivity; import edu.uprm.gaming.utils.Utils; import java.util.HashMap; import java.util.Map; import javax.swing.JOptionPane; /** * * @author David */ public class GeneralScreenController implements ScreenController, KeyInputHandler { private Nifty nifty; private Screen screen; private Label labelCurrentGameTime; private Label labelDueDateNextOrder; private Label labelPurchaseDueDate; private float currentTimeFactor; private Label labelCurrentTimeFactor; // private Label labelPeopleBusy; // private Label labelPeopleIdle; // private Label labelCurrentMoney; private GameEngine gameEngine; private Slider sliderTimeFactor; private boolean isGamePlaying; private String currentOptionselected = ""; private String currentDynamicButtonSelected = ""; private String currentDynamicSubLevelButtonSelected = ""; private boolean isVisibleWindowOverall = true; private boolean isVisibleWindowOrder = true; private boolean isVisibleWindowGameLog = true; private boolean isVisibleWindowGameSetup = true; private boolean isVisibleWindowFlowChart = true; private Map<String, Integer> arrActivitiesId; private NiftyImage imagePlayRed; private NiftyImage imagePlayGreen; private NiftyImage imagePauseRed; private NiftyImage imagePauseGreen; private String buttonSelectedFirstLevel = ""; private String buttonSelectedSecondLevel = ""; private String buttonSelectedThirdLevel = ""; private String buttonActive = "Textures/azul.png"; private String buttonInactive = "Textures/anaranjado.png"; private Element quitPopup; private boolean callOnceMoneyWarning = true; private boolean callOnceNoMoney = true; private boolean isVolumeManage = false; private float oldVolumeMusic = 100.f; private float oldVolumeSFX = 100.f; private boolean isEnableVolumeMusic = true; private boolean isEnableVolumeSFX = true; final CommonBuilders common = new CommonBuilders(); public String getButtonSelectedSecondLevel() { return buttonSelectedSecondLevel; } public void setButtonSelectedSecondLevel(String buttonSelectedSecondLevel) { this.buttonSelectedSecondLevel = buttonSelectedSecondLevel; } public String getCurrentOptionselected() { return currentOptionselected; } public void setCurrentOptionselected(String currentOptionselected) { this.currentOptionselected = currentOptionselected; } public GameEngine getGameEngine() { return gameEngine; } public void setGameEngine(GameEngine gameEngine) { this.gameEngine = gameEngine; } public GeneralScreenController(){ arrActivitiesId = new HashMap<String, Integer>(); } @Override public void bind(final Nifty nifty, final Screen screen) { this.nifty = nifty; this.screen = screen; this.labelCurrentGameTime = screen.findNiftyControl("labelCurrentGameTime", Label.class); this.labelDueDateNextOrder = screen.findNiftyControl("labelDueDateNextOrder", Label.class); this.labelPurchaseDueDate = screen.findNiftyControl("labelPurchaseDueDate", Label.class); this.labelCurrentTimeFactor = screen.findNiftyControl("labelSliderTime", Label.class); // this.labelPeopleBusy = screen.findNiftyControl("peopleBusy", Label.class); // this.labelPeopleIdle = screen.findNiftyControl("peopleIdle", Label.class); // this.labelCurrentMoney = screen.findNiftyControl("currentMoney", Label.class); Attributes x = new Attributes(); x.set("hideOnClose", "true"); this.sliderTimeFactor = screen.findNiftyControl("sliderTime", Slider.class); this.isGamePlaying = true; imagePlayGreen = nifty.createImage("Interface/button_play_green.png", false); imagePlayRed = nifty.createImage("Interface/button_play_red.png", false); imagePauseGreen = nifty.createImage("Interface/button_pause_green.png", false); imagePauseRed = nifty.createImage("Interface/button_pause_red.png", false); quitPopup = nifty.createPopup("quitPopup"); } @NiftyEventSubscriber(id="gameClosingContinue") public void onGameClosingContinueButtonClicked(final String id, final ButtonClickedEvent event) { gameEngine.stopClosingGame(); } @NiftyEventSubscriber(id="gameClosingExit") public void onGameClosingExitButtonClicked(final String id, final ButtonClickedEvent event) { nifty.showPopup(screen, quitPopup.getId(), null); } @NiftyEventSubscriber(pattern="quitPopup.*") public void onGameClosingQuitPopupButtonClicked(final String id, final ButtonClickedEvent event) { if (id.equals("quitPopupYes")){ gameEngine.getGameData().logoutPlayer(); gameEngine.app.stop(); System.exit(0); }else{ nifty.closePopup(quitPopup.getId()); } } @SuppressWarnings("unchecked") private ListBox<ListBoxMessages> getListBox(final String name) { return (ListBox<ListBoxMessages>) screen.findNiftyControl(name, ListBox.class); } @Override public void onStartScreen() { // ((Slider) screen.findNiftyControl("sliderTime", Slider.class)).setup(1.f, 8.f, 4.f, 1.f, 1.f); // showHideDynamicButtons(0); // showHideDynamicSubLevelButtons(0); } @Override public void onEndScreen() { } @Override public boolean keyEvent(final NiftyInputEvent inputEvent) { return false; } @NiftyEventSubscriber(id="sliderTime") public void onAlphaSliderChange(final String id, final SliderChangedEvent event) { gameEngine.updateLastActivitySystemTime(); String strTimeFactor = ""; //The TIME_FACTOR has been changed only this part, in order to not change others things in the code. //Becareful in case somebody change it int selectedValue = 0; switch ((int)event.getValue()){ case 1: strTimeFactor = "1/8x"; selectedValue = 8; break; case 2: strTimeFactor = "1/4x"; selectedValue = 7; break; case 3: strTimeFactor = "1/2x"; selectedValue = 6; break; case 4: strTimeFactor = "1x"; selectedValue = 5; break; case 5: strTimeFactor = "2x"; selectedValue = 4; break; case 6: strTimeFactor = "4x"; selectedValue = 3; break; case 7: strTimeFactor = "8x"; selectedValue = 2; break; case 8: strTimeFactor = "16x"; selectedValue = 1; break; } currentTimeFactor = 0.0625f; for(int i=1; i<selectedValue; i++){ currentTimeFactor = currentTimeFactor * 2; } labelCurrentTimeFactor.setText(strTimeFactor); GameLogControl.addMessage(MessageType.Info, Messages.timeFactor.replace(Messages.wildCard, strTimeFactor)); gameEngine.getGameData().updateSpeedElements(); gameEngine.updateEventsTime(); } public float getTimeFactor(){ return this.currentTimeFactor; } public float getTimeFactorForSpeed(){ return 1/getTimeFactor(); } public void setTimeFactor(float timeFactor){ float newTimeFactor = 1; switch ((int)(timeFactor/0.0625)){ case 1: newTimeFactor = 8; break; case 2: newTimeFactor = 7; break; case 4: newTimeFactor = 6; break; case 8: newTimeFactor = 5; break; case 16: newTimeFactor = 4; break; case 32: newTimeFactor = 3; break; case 64: newTimeFactor = 2; break; case 128: newTimeFactor = 1; break; } sliderTimeFactor.setValue(newTimeFactor); } public void updateStartScreen(){ ((Slider) screen.findNiftyControl("sliderTime", Slider.class)).setup(1.f, 8.f, 4.f, 1.f, 1.f); showHideDynamicButtons(0); showHideDynamicSubLevelButtons(0); currentOptionselected = ""; currentDynamicButtonSelected = ""; currentDynamicSubLevelButtonSelected = ""; } public void setCurrentGameTime(String time){ labelCurrentGameTime.setText(time); } public void setNextDueDate(String time){ labelDueDateNextOrder.setText("NextOrder Due: " + time); } public void setNextPurchaseDueDate(String time){ labelPurchaseDueDate.setText("NextPurchase: " + time); } // public void updateQuantityPeopleStatus(int noPeopleBusy, int noPeopleIdle){ // this.labelPeopleBusy.setText(noPeopleBusy + " Busy"); // this.labelPeopleIdle.setText(noPeopleIdle + " Idle"); public void updateQuantityCurrentMoney(double currentMoney){ // this.labelCurrentMoney.setText(Params.moneySign + " " + Utils.formatValue2DecToString(currentMoney)); if (currentMoney < 1000 && currentMoney > 980){ GameLogControl.addMessage(MessageType.Notification, Messages.moneyBetween1000and980); if (callOnceMoneyWarning){ gameEngine.getGameSounds().playSound(Sounds.GameWarningMoney); callOnceMoneyWarning = false; } } if (currentMoney < 100){ GameLogControl.addMessage(MessageType.Error, Messages.moneyLessThan100); if (callOnceNoMoney){ gameEngine.getGameSounds().playSound(Sounds.GameNoMoney); callOnceNoMoney = false; } } if (currentMoney > 1000) callOnceMoneyWarning = true; if (currentMoney > 100) callOnceNoMoney = true; } public void setGameNamePrincipal(String newGameName){ ((Label)screen.findNiftyControl("gameNamePrincipal", Label.class)).setText(" Game: " + newGameName); } public void setGamePrincipalStatus(String principalStatus){ ((Label)screen.findNiftyControl("gamePrincipalStatus", Label.class)).setText(principalStatus); } public void playGameValidated(){ gameEngine.updateLastActivitySystemTime(); if (nifty.getScreen("layerScreen").findElementByName("winGSC_Element").getControl(GameSetupControl.class).isIsReadyToStart()){ playGame(); }else{ GameLogControl.addMessage(MessageType.Notification, Messages.gameSetup); } // nifty.gotoScreen("initialMenu"); } public void playGame(){ gameEngine.updateLastActivitySystemTime(); if (!isGamePlaying){ screen.findElementByName("imagePlay").getRenderer(ImageRenderer.class).setImage(imagePlayGreen); // screen.findElementByName("imagePause").getRenderer(ImageRenderer.class).setImage(imagePauseRed); isGamePlaying = true; playPauseGame(); GameLogControl.addMessage(MessageType.Info, Messages.gamePlay); setGamePrincipalStatus(" (Playing)"); gameEngine.getGameSounds().playSound(Sounds.PlayPause); gameEngine.getGameSounds().playSound(Sounds.Background); gameEngine.updateGameSounds(true); sliderTimeFactor.enable(); }else{ forcePauseGame(); } } public void pauseGame(){ gameEngine.updateLastActivitySystemTime(); if (isGamePlaying){ forcePauseGame(); } } public void forcePauseGame(){ isGamePlaying = false; playPauseGame(); GameLogControl.addMessage(MessageType.Info, Messages.gamePause); setGamePrincipalStatus(" (Paused)"); screen.findElementByName("imagePlay").getRenderer(ImageRenderer.class).setImage(imagePauseRed); // screen.findElementByName("imagePlay").getRenderer(ImageRenderer.class).setImage(imagePlayRed); // screen.findElementByName("imagePause").getRenderer(ImageRenderer.class).setImage(imagePauseGreen); gameEngine.getGameSounds().playSound(Sounds.PlayPause); gameEngine.getGameSounds().pauseSound(Sounds.Background); gameEngine.updateGameSounds(false); sliderTimeFactor.disable(); for (E_Operator op: this.gameEngine.getGameData().getMapUserOperator().values()){ op.playStopAnimation(false); if (op.getMotionControl()!=null) op.getMotionControl().pause(); } } public void manageGameVolume(){ if (isVolumeManage){ //hide isEnableVolumeMusic = screen.findElementByName("controlVolumeMusic_MGV").isEnabled(); isEnableVolumeSFX = screen.findElementByName("controlVolumeSFX_MGV").isEnabled(); oldVolumeMusic = ((Slider) screen.findNiftyControl("controlVolumeMusic_MGV", Slider.class)).getValue(); oldVolumeSFX = ((Slider) screen.findNiftyControl("controlVolumeSFX_MGV", Slider.class)).getValue(); if (screen.findElementByName("container_MGV") != null) screen.findElementByName("container_MGV").markForRemoval(); nifty.executeEndOfFrameElementActions(); }else{//show new PanelBuilder("container_MGV"){{ backgroundImage("Interface/panel2.png"); childLayoutVertical(); panel(new PanelBuilder(){{ childLayoutHorizontal(); panel(common.hspacer("5px")); control(new LabelBuilder("labelMusic_MGV", "Music :"){{ textHAlignLeft(); }}); panel(common.hspacer("5px")); control(new LabelBuilder("labelMusicValue_MGV", "0%"){{ textHAlignLeft(); width("60px"); }}); }}); panel(new PanelBuilder(){{ childLayoutHorizontal(); panel(common.hspacer("5px")); control(new CheckboxBuilder("enableMusic_MGV")); panel(common.hspacer("5px")); control(new SliderBuilder("controlVolumeMusic_MGV", false){{ width("110px"); }}); }}); panel(common.vspacer("10px")); panel(new PanelBuilder(){{ childLayoutHorizontal(); panel(common.hspacer("5px")); control(new LabelBuilder("labelSFX_MGV", "SFX :"){{ textHAlignLeft(); }}); panel(common.hspacer("5px")); control(new LabelBuilder("labelSFXValue_MGV", "0%"){{ textHAlignLeft(); width("60px"); }}); }}); panel(new PanelBuilder(){{ childLayoutHorizontal(); panel(common.hspacer("5px")); control(new CheckboxBuilder("enableSFX_MGV")); panel(common.hspacer("5px")); control(new SliderBuilder("controlVolumeSFX_MGV", false){{ width("110px"); }}); }}); width("150"); height("110"); }}.build(nifty, screen, screen.findElementByName("parent_MGV")); nifty.executeEndOfFrameElementActions(); ((Slider) screen.findNiftyControl("controlVolumeMusic_MGV", Slider.class)).setup(0.f, 100.f, oldVolumeMusic, 1.f, 1.f); ((Slider) screen.findNiftyControl("controlVolumeSFX_MGV", Slider.class)).setup(0.f, 100.f, oldVolumeSFX, 1.f, 1.f); if (isEnableVolumeMusic){ ((CheckBox) screen.findNiftyControl("enableMusic_MGV", CheckBox.class)).check(); screen.findElementByName("controlVolumeMusic_MGV").enable(); }else{ ((CheckBox) screen.findNiftyControl("enableMusic_MGV", CheckBox.class)).uncheck(); screen.findElementByName("controlVolumeMusic_MGV").disable(); } if (isEnableVolumeSFX){ ((CheckBox) screen.findNiftyControl("enableSFX_MGV", CheckBox.class)).check(); screen.findElementByName("controlVolumeSFX_MGV").enable(); }else{ ((CheckBox) screen.findNiftyControl("enableSFX_MGV", CheckBox.class)).uncheck(); screen.findElementByName("controlVolumeSFX_MGV").disable(); } } isVolumeManage = !isVolumeManage; } @NiftyEventSubscriber(pattern="enable.*") public void onEnableControlsClicked(final String id, final CheckBoxStateChangedEvent event) { if (id.equals("enableMusic_MGV")){ if (event.isChecked()){ screen.findElementByName("controlVolumeMusic_MGV").enable(); gameEngine.getGameSounds().setVolumeMusic(((Slider) screen.findNiftyControl("controlVolumeMusic_MGV", Slider.class)).getValue()/100.f); }else{ screen.findElementByName("controlVolumeMusic_MGV").disable(); gameEngine.getGameSounds().setVolumeMusic(0); } }else if (id.equals("enableSFX_MGV")){ if (event.isChecked()){ screen.findElementByName("controlVolumeSFX_MGV").enable(); gameEngine.getGameSounds().setVolumeSFX(((Slider) screen.findNiftyControl("controlVolumeSFX_MGV", Slider.class)).getValue()/100.f,gameEngine); }else{ screen.findElementByName("controlVolumeSFX_MGV").disable(); gameEngine.getGameSounds().setVolumeSFX(0,gameEngine); } } } @NiftyEventSubscriber(pattern="controlVolume.*") public void onControlVolumeSliderChange(final String id, final SliderChangedEvent event) { if (id.equals("controlVolumeMusic_MGV")){ ((Label)screen.findNiftyControl("labelMusicValue_MGV", Label.class)).setText((int)event.getValue() + "%"); if(((CheckBox) screen.findNiftyControl("enableMusic_MGV", CheckBox.class)).isChecked()) gameEngine.getGameSounds().setVolumeMusic(((Slider) screen.findNiftyControl("controlVolumeMusic_MGV", Slider.class)).getValue()/100.f); }else if (id.equals("controlVolumeSFX_MGV")){ ((Label)screen.findNiftyControl("labelSFXValue_MGV", Label.class)).setText((int)event.getValue() + "%"); if(((CheckBox) screen.findNiftyControl("enableSFX_MGV", CheckBox.class)).isChecked()) gameEngine.getGameSounds().setVolumeSFX(((Slider) screen.findNiftyControl("controlVolumeSFX_MGV", Slider.class)).getValue()/100.f,gameEngine); } } private void playPauseGame(){ if (isGamePlaying){//PLAY gameEngine.setCurrentSystemStatus(Status.Busy); gameEngine.getGameData().playPauseElements(Status.Busy); gameEngine.updateAnimations(); }else{//PAUSE gameEngine.setCurrentSystemStatus(Status.Idle); gameEngine.simpleUpdateLocal(); gameEngine.getGameData().playPauseElements(Status.Idle); } } public void showHideDynamicButtons(int numberButtonsVisible){ showHideDynamicButtons(numberButtonsVisible, "98%"); } private void showHideDynamicButtons(int numberButtonsVisible, String sizeWidth){ Element dynamicPanel = nifty.getScreen("layerScreen").findElementByName("dynamicButtons"); int i=0; for (Element element : dynamicPanel.getElements()){ if (element.getId() != null){ i++; element.setVisible(i <= numberButtonsVisible ? true : false); ((Button)screen.findNiftyControl(element.getId(), Button.class)).setWidth(new SizeValue(sizeWidth)); } } screen.findElementByName("dynamicButtons").layoutElements(); } public void showHideDynamicSubLevelButtons(int numberButtonsVisible){ showHideDynamicSubLevelButtons(numberButtonsVisible, "98%"); } private void showHideDynamicSubLevelButtons(int numberButtonsVisible, String sizeWidth){ Element dynamicPanel = nifty.getScreen("layerScreen").findElementByName("dynamicSubLevelButtons"); int i=0; for (Element element : dynamicPanel.getElements()){ if (element.getId() != null){ i++; element.setVisible(i <= numberButtonsVisible ? true : false); ((Button)screen.findNiftyControl(element.getId(), Button.class)).setWidth(new SizeValue(sizeWidth)); } } screen.findElementByName("dynamicSubLevelButtons").layoutElements(); } private void changeBackgroundButtonActiveInactiveFirst(String nameButton){ if (nameButton.equals("")) return; if (buttonSelectedFirstLevel.equals("")){ screen.findElementByName(nameButton).getRenderer(ImageRenderer.class).setImage(nifty.createImage(buttonActive, false)); buttonSelectedFirstLevel = nameButton; }else{ if (buttonSelectedFirstLevel.equals(nameButton)){ screen.findElementByName(nameButton).getRenderer(ImageRenderer.class).setImage(nifty.createImage(buttonInactive, false)); buttonSelectedFirstLevel = ""; }else{ screen.findElementByName(buttonSelectedFirstLevel).getRenderer(ImageRenderer.class).setImage(nifty.createImage(buttonInactive, false)); screen.findElementByName(nameButton).getRenderer(ImageRenderer.class).setImage(nifty.createImage(buttonActive, false)); buttonSelectedFirstLevel = nameButton; } changeBackgroundButtonActiveInactiveSecond(buttonSelectedSecondLevel); } } private void changeBackgroundButtonActiveInactiveSecond(String nameButton){ if (nameButton.equals("")) return; if (buttonSelectedSecondLevel.equals("")){ screen.findElementByName(nameButton).getRenderer(ImageRenderer.class).setImage(nifty.createImage(buttonActive, false)); buttonSelectedSecondLevel = nameButton; }else{ if (buttonSelectedSecondLevel.equals(nameButton)){ screen.findElementByName(nameButton).getRenderer(ImageRenderer.class).setImage(nifty.createImage(buttonInactive, false)); buttonSelectedSecondLevel = ""; }else{ screen.findElementByName(buttonSelectedSecondLevel).getRenderer(ImageRenderer.class).setImage(nifty.createImage(buttonInactive, false)); screen.findElementByName(nameButton).getRenderer(ImageRenderer.class).setImage(nifty.createImage(buttonActive, false)); buttonSelectedSecondLevel = nameButton; } changeBackgroundButtonActiveInactiveThird(buttonSelectedThirdLevel); } } private void changeBackgroundButtonActiveInactiveThird(String nameButton){ if (nameButton.equals("")) return; if (buttonSelectedThirdLevel.equals("")){ screen.findElementByName(nameButton).getRenderer(ImageRenderer.class).setImage(nifty.createImage(buttonActive, false)); buttonSelectedThirdLevel = nameButton; }else if (buttonSelectedThirdLevel.equals(nameButton)){ screen.findElementByName(nameButton).getRenderer(ImageRenderer.class).setImage(nifty.createImage(buttonInactive, false)); buttonSelectedThirdLevel = ""; }else{ screen.findElementByName(buttonSelectedThirdLevel).getRenderer(ImageRenderer.class).setImage(nifty.createImage(buttonInactive, false)); screen.findElementByName(nameButton).getRenderer(ImageRenderer.class).setImage(nifty.createImage(buttonActive, false)); buttonSelectedThirdLevel = nameButton; } } public void hideCurrentControlsWindow(){ if (currentOptionselected.equals("buttonOptionControls")){ if (currentDynamicButtonSelected.contains("Resources")){ screen.findElementByName("winChC_Element").getControl(CharactersControl.class).loadWindowControl(gameEngine, -1, null); }else if (currentDynamicButtonSelected.contains("PriorityActivities")){ screen.findElementByName("winPrC_Element").getControl(PriorityControl.class).loadWindowControl(gameEngine, -1, null); }else if (currentDynamicButtonSelected.contains("AssignOperators")){ screen.findElementByName("winAsOpC_Element").getControl(AssignOperatorControl.class).loadWindowControl(gameEngine, -1, null); }else if (currentDynamicButtonSelected.contains("UnitLoad")){ screen.findElementByName("winULC_Element").getControl(UnitLoadControl.class).loadWindowControl(gameEngine, -1, null); }else if (currentDynamicButtonSelected.contains("AllocateStorages")){ screen.findElementByName("winASCC_Element").getControl(StorageCostControl.class).loadWindowControl(gameEngine, -1, null); } }else if (currentOptionselected.equals("buttonOptionActivities")){ screen.findElementByName("winAC_Element").getControl(ActivityControl.class).loadWindowControl(gameEngine, -1, TypeActivity.None, null); }else if (currentOptionselected.equals("buttonOptionUtilities")){ if (currentDynamicButtonSelected.contains("Station")){ screen.findElementByName("winSSC_Element").getControl(StorageStationControl.class).loadWindowControl(gameEngine,-1,null); // screen.findElementByName("winSC_Element").getControl(StationControl.class).loadWindowControl(gameEngine, -1, null); }else if (currentDynamicButtonSelected.contains("Machine") || currentDynamicButtonSelected.contains("Equipment")){ screen.findElementByName("winMC_Element").getControl(MachineControl.class).loadWindowControl(gameEngine, -1, null); }else if (currentDynamicButtonSelected.contains("Operator")){ screen.findElementByName("winOC_Element").getControl(OperatorControl.class).loadWindowControl(gameEngine, -1, null); }else if (currentDynamicButtonSelected.contains("Part")){ screen.findElementByName("winPC_Element").getControl(PartControl.class).loadWindowControl(gameEngine, -1, null); }else if (currentDynamicButtonSelected.contains("Supplier")){ screen.findElementByName("winSuC_Element").getControl(SupplierControl.class).loadWindowControl(gameEngine, -1, null); } }else if (currentOptionselected.equals("windowOperator")){ screen.findElementByName("winOC_Element").getControl(OperatorControl.class).loadWindowControl(gameEngine, -1, null); }else if (currentOptionselected.equals("windowPart")){ screen.findElementByName("winPC_Element").getControl(PartControl.class).loadWindowControl(gameEngine, -1, null); }else if (currentOptionselected.equals("windowStorageStation")){ screen.findElementByName("winSSC_Element").getControl(StorageStationControl.class).loadWindowControl(gameEngine,-1,null); }else // if (currentOptionselected.equals("windowStation")){ // screen.findElementByName("winSC_Element").getControl(StationControl.class).loadWindowControl(gameEngine, -1, null); // }else if (currentOptionselected.equals("windowMachine")){ screen.findElementByName("winMC_Element").getControl(MachineControl.class).loadWindowControl(gameEngine, -1, null); } } @NiftyEventSubscriber(pattern="dynSubLevelBut.*") public void onDynamicSubLevelButtonClicked(final String id, final ButtonClickedEvent event) { gameEngine.updateLastActivitySystemTime(); changeBackgroundButtonActiveInactiveThird(id); hideCurrentControlsWindow(); if (currentDynamicSubLevelButtonSelected.equals(((Button)nifty.getScreen("layerScreen").findNiftyControl(id, Button.class)).getText())){ hideCurrentControlsWindow(); currentDynamicSubLevelButtonSelected = ""; return; } currentDynamicSubLevelButtonSelected = ((Button)nifty.getScreen("layerScreen").findNiftyControl(id, Button.class)).getText(); // if (currentDynamicButtonSelected.contains(TypeActivity.Operation.toString()) || currentDynamicButtonSelected.contains(TypeActivity.Purchase.toString()) || currentDynamicButtonSelected.contains(TypeActivity.Transport.toString())){ // TypeActivity tempActivityType = TypeActivity.None; // int tempIdActivity = arrActivitiesId.get(currentDynamicSubLevelButtonSelected); // if (currentDynamicButtonSelected.contains(TypeActivity.Operation.toString())){ // tempActivityType = TypeActivity.Operation; // }else // if (currentDynamicButtonSelected.contains(TypeActivity.Purchase.toString())){ // tempActivityType = TypeActivity.Purchase; // }else // if (currentDynamicButtonSelected.contains(TypeActivity.Transport.toString())){ // tempActivityType = TypeActivity.Transport; // screen.findElementByName("winAC_Element").getControl(ActivityControl.class).loadWindowControl(gameEngine, tempIdActivity, tempActivityType, null); // }else // if (currentDynamicButtonSelected.contains("Station")){ // for (E_Station temp : gameEngine.getGameData().getMapUserStation().values()){ // if (temp.getStationDescription().equals(currentDynamicSubLevelButtonSelected)){ // if (temp.getStationType().equals(StationType.StorageFG) || // temp.getStationType().equals(StationType.StorageIG) || // temp.getStationType().equals(StationType.StorageRM)) // screen.findElementByName("winSSC_Element").getControl(StorageStationControl.class).loadWindowControl(gameEngine,temp.getIdStation(),null); // else // screen.findElementByName("winSC_Element").getControl(StationControl.class).loadWindowControl(gameEngine,temp.getIdStation(),null); // }//else // if (currentDynamicButtonSelected.contains("Machine")){ // screen.findElementByName("winMC_Element").getControl(MachineControl.class).loadWindowControl(gameEngine, Integer.valueOf(currentDynamicSubLevelButtonSelected.replace(" ", "").replace("Machine", "").replace("(", "").replace(")", "").replace(Params.active, "").replace(Params.inactive, "")), null); // screen.findElementByName("winMC_Element").getControl(MachineControl.class).setIdButton(id); // }else // if (currentDynamicButtonSelected.contains("Equipment")){ // screen.findElementByName("winMC_Element").getControl(MachineControl.class).loadWindowControl(gameEngine, Integer.valueOf(currentDynamicSubLevelButtonSelected.replace(" ", "").replace("Equipment", "").replace("(", "").replace(")", "").replace(Params.active, "").replace(Params.inactive, "")), null); // screen.findElementByName("winMC_Element").getControl(MachineControl.class).setIdButton(id); // }else // if (currentDynamicButtonSelected.contains("Operator")){ // screen.findElementByName("winOC_Element").getControl(OperatorControl.class).loadWindowControl(gameEngine, Integer.valueOf(currentDynamicSubLevelButtonSelected.replace(" ", "").replace("(", "").replace(")", "").replace("Operator", "").replace("Material", "").replace("Handler", "").replace("Ope", "").replace(Params.opeActive, "").replace(Params.opeInactive, "").replace(OperatorCategory.Versatile.toString(), "")), null); // screen.findElementByName("winOC_Element").getControl(OperatorControl.class).setIdButton(id); // }else // if (currentDynamicButtonSelected.contains("Part")){ // screen.findElementByName("winPC_Element").getControl(PartControl.class).loadWindowControl(gameEngine, Integer.valueOf(currentDynamicSubLevelButtonSelected.replace(" ", "").replace("Part", "")), null); // }else // if (currentDynamicButtonSelected.contains("Supplier")){ // screen.findElementByName("winSuC_Element").getControl(SupplierControl.class).loadWindowControl(gameEngine, Integer.valueOf(currentDynamicSubLevelButtonSelected.replace(" ", "").replace("Supplier", "")), null); } public void onDynamicButtonClicked(String id){ changeBackgroundButtonActiveInactiveSecond(id); showHideDynamicSubLevelButtons(0); hideCurrentControlsWindow(); if (currentDynamicButtonSelected.equals(((Button)nifty.getScreen("layerScreen").findNiftyControl(id, Button.class)).getText().replace(" ", ""))){ // if (currentOptionselected.equals("buttonOptionInformation")){ // if (currentDynamicButtonSelected.contains("Overall")){ // screen.findElementByName("winOvC_Element").getControl(OverallControl.class).loadWindowControl(gameEngine, -1, null); // }else // if (currentDynamicButtonSelected.contains("Order")){ // screen.findElementByName("winOrC_Element").getControl(OrderControl.class).loadWindowControl(gameEngine, -1, null); // }else // if (currentDynamicButtonSelected.contains("FlowChart")){ // screen.findElementByName("winFCC_Element").getControl(FlowChartControl.class).loadWindowControl(gameEngine, -1, null); currentDynamicButtonSelected = ""; return; } //load appropriate action currentDynamicButtonSelected = ((Button)nifty.getScreen("layerScreen").findNiftyControl(id, Button.class)).getText().replace(" ", ""); // if (currentOptionselected.equals("buttonOptionInformation")){ // if (currentDynamicButtonSelected.contains("Overall")){ // screen.findElementByName("winOvC_Element").getControl(OverallControl.class).loadWindowControl(gameEngine, 0, null); // }else // if (currentDynamicButtonSelected.contains("Order")){ // screen.findElementByName("winOrC_Element").getControl(OrderControl.class).loadWindowControl(gameEngine, 0, null); // }else // if (currentDynamicButtonSelected.contains("FlowChart")){ // screen.findElementByName("winFCC_Element").getControl(FlowChartControl.class).loadWindowControl(gameEngine, 0, null); // }else if (currentOptionselected.equals("buttonOptionControls")){ if (currentDynamicButtonSelected.contains("Resources")){ screen.findElementByName("winChC_Element").getControl(CharactersControl.class).loadWindowControl(gameEngine, 0, null); }else if (currentDynamicButtonSelected.contains("PriorityActivities")){ screen.findElementByName("winPrC_Element").getControl(PriorityControl.class).loadWindowControl(gameEngine, 0, null); }else if (currentDynamicButtonSelected.contains("AssignOperators")){ screen.findElementByName("winAsOpC_Element").getControl(AssignOperatorControl.class).loadWindowControl(gameEngine, 0, null); }else if (currentDynamicButtonSelected.contains("UnitLoad")){ screen.findElementByName("winULC_Element").getControl(UnitLoadControl.class).loadWindowControl(gameEngine, 0, null); }else if (currentDynamicButtonSelected.contains("AllocateStorages")){ screen.findElementByName("winASCC_Element").getControl(StorageCostControl.class).loadWindowControl(gameEngine, 0, null); } }else if (currentOptionselected.equals("buttonOptionActivities")){ TypeActivity tempActivityType = TypeActivity.None; Button dynamicButton; int position = 0; Screen screenButton = nifty.getScreen("layerScreen"); arrActivitiesId.clear(); if (currentDynamicButtonSelected.contains(TypeActivity.Operation.toString())){ tempActivityType = TypeActivity.Operation; // showHideDynamicSubLevelButtons(gameEngine.getGameData().getMapOperation().size()); // for (E_Operation temp : gameEngine.getGameData().getMapOperation().values()){ // dynamicButton = screenButton.findNiftyControl("dynSubLevelBut" + position, Button.class); // dynamicButton.setText(temp.getActivityDescription()); // arrActivitiesId.put(temp.getActivityDescription(), temp.getIdActivity()); // position++; }else if (currentDynamicButtonSelected.contains(TypeActivity.Purchase.toString())){ tempActivityType = TypeActivity.Purchase; // showHideDynamicSubLevelButtons(gameEngine.getGameData().getMapPurchase().size()); // for (E_Purchase temp : gameEngine.getGameData().getMapPurchase().values()){ // dynamicButton = screenButton.findNiftyControl("dynSubLevelBut" + position, Button.class); // dynamicButton.setText(temp.getActivityDescription()); // arrActivitiesId.put(temp.getActivityDescription(), temp.getIdActivity()); // position++; }else if (currentDynamicButtonSelected.contains(TypeActivity.Transport.toString())){ tempActivityType = TypeActivity.Transport; // showHideDynamicSubLevelButtons(gameEngine.getGameData().getMapTransport().size(),"180%"); // for (E_TransportStore temp : gameEngine.getGameData().getMapTransport().values()){ // dynamicButton = screenButton.findNiftyControl("dynSubLevelBut" + position, Button.class)manageSo // dynamicButton.setText(temp.getActivityDescription()); // arrActivitiesId.put(temp.getActivityDescription(), temp.getIdActivity()); // position++; } screen.findElementByName("winAC_Element").getControl(ActivityControl.class).loadWindowControl(gameEngine, 0, tempActivityType, null); }else if (currentOptionselected.equals("buttonOptionUtilities")){ // Button dynamicButton; // int position = 0; // Screen screenButton = nifty.getScreen("layerScreen"); if (currentDynamicButtonSelected.contains("Station")){ // showHideDynamicSubLevelButtons(gameEngine.getGameData().getMapUserStation().size()-2,"120%"); // for (E_Station temp : gameEngine.getGameData().getMapUserStation().values()){ // if (!(temp.getStationType().equals(StationType.MachineZone) || temp.getStationType().equals(StationType.StaffZone))){ // dynamicButton = screenButton.findNiftyControl("dynSubLevelBut" + position, Button.class); // dynamicButton.setText(temp.getStationDescription()); // position++; screen.findElementByName("winSSC_Element").getControl(StorageStationControl.class).loadWindowControl(gameEngine,Params.stationList,null); }else if (currentDynamicButtonSelected.contains("Machine")){ // showHideDynamicSubLevelButtons(gameEngine.getGameData().getMapUserMachineByOperation().size()); // for (E_Machine temp : gameEngine.getGameData().getMapUserMachineByOperation().values()){ // dynamicButton = screenButton.findNiftyControl("dynSubLevelBut" + position, Button.class); // dynamicButton.setText("Machine " +temp.getIdMachine() + " (" + (temp.getMachineState().equals(ObjectState.Inactive) ? Params.inactive : Params.active) + ")"); // position++; screen.findElementByName("winMC_Element").getControl(MachineControl.class).loadWindowControl(gameEngine, Params.machineList, null); screen.findElementByName("winMC_Element").getControl(MachineControl.class).setIdButton(id); }else if (currentDynamicButtonSelected.contains("Equipment")){ // showHideDynamicSubLevelButtons(gameEngine.getGameData().getMapUserMachineByTransport().size()); // for (E_Machine temp : gameEngine.getGameData().getMapUserMachineByTransport().values()){ // dynamicButton = screenButton.findNiftyControl("dynSubLevelBut" + position, Button.class); // dynamicButton.setText("Equipment " +temp.getIdMachine() + " (" + (temp.getMachineState().equals(ObjectState.Inactive) ? Params.inactive : Params.active) + ")"); // position++; screen.findElementByName("winMC_Element").getControl(MachineControl.class).loadWindowControl(gameEngine, Params.equipmentList, null); screen.findElementByName("winMC_Element").getControl(MachineControl.class).setIdButton(id); }else if (currentDynamicButtonSelected.contains("Operator")){ // showHideDynamicSubLevelButtons(gameEngine.getGameData().getMapUserOperator().size(),"140%"); // for (E_Operator temp : gameEngine.getGameData().getMapUserOperator().values()){ // dynamicButton = screenButton.findNiftyControl("dynSubLevelBut" + position, Button.class); // dynamicButton.setText("Ope" + temp.getIdOperator() + " ( " + (temp.getState().equals(ObjectState.Inactive) ? Params.opeInactive : Params.opeActive) + " ) " + (temp.getCategory().equals(OperatorCategory.Assembler) ? "Operator" : (temp.getCategory().equals(OperatorCategory.Carrier) ? "Material Handler" : OperatorCategory.Versatile.toString()))); // position++; screen.findElementByName("winOC_Element").getControl(OperatorControl.class).loadWindowControl(gameEngine, Params.operatorList, null); screen.findElementByName("winOC_Element").getControl(OperatorControl.class).setIdButton(id); }else if (currentDynamicButtonSelected.contains("Part")){ // showHideDynamicSubLevelButtons(gameEngine.getGameData().getMapUserPart().size()); // for (E_Part temp : gameEngine.getGameData().getMapUserPart().values()){ // dynamicButton = screenButton.findNiftyControl("dynSubLevelBut" + position, Button.class); // dynamicButton.setText("Part " + temp.getIdPart()); // position++; screen.findElementByName("winPC_Element").getControl(PartControl.class).loadWindowControl(gameEngine, Params.partList, null); }else if (currentDynamicButtonSelected.contains("Supplier")){ // showHideDynamicSubLevelButtons(gameEngine.getGameData().getMapGameSupplier().size()); // for (E_Supplier temp : gameEngine.getGameData().getMapGameSupplier().values()){ // dynamicButton = screenButton.findNiftyControl("dynSubLevelBut" + position, Button.class); // dynamicButton.setText("Supplier " + temp.getIdSupplier()); // position++; screen.findElementByName("winSuC_Element").getControl(SupplierControl.class).loadWindowControl(gameEngine, Params.supplierList, null); } } } @NiftyEventSubscriber(pattern="dynBut.*") public void onDynamicButtonClicked(final String id, final ButtonClickedEvent event) { gameEngine.updateLastActivitySystemTime(); onDynamicButtonClicked(id); } @NiftyEventSubscriber(pattern="buttonStaticOption.*") public void onOptionStaticButtonClicked(final String id, final ButtonClickedEvent event) { gameEngine.updateLastActivitySystemTime(); // if (id.equals("buttonStaticOptionGameLog")){ //showGAMELOG window // if (isVisibleWindowGameLog) // screen.findElementByName("winGLC_Element").getControl(GameLogControl.class).loadWindowControl(gameEngine, -1, null); // else // screen.findElementByName("winGLC_Element").getControl(GameLogControl.class).loadWindowControl(gameEngine, 0, null); // isVisibleWindowGameLog = !isVisibleWindowGameLog; // }else if (id.equals("buttonStaticOptionFlowChart")){ if (isVisibleWindowFlowChart) screen.findElementByName("winFCC_Element").getControl(FlowChartControl.class).loadWindowControl(gameEngine, -1, null); else screen.findElementByName("winFCC_Element").getControl(FlowChartControl.class).loadWindowControl(gameEngine, 0, null); isVisibleWindowFlowChart = !isVisibleWindowFlowChart; }else if (id.equals("buttonStaticOptionReturnToMenu")){ pauseGame(); ((MenuScreenController)nifty.getScreen("initialMenu").getScreenController()).setDefaultStart(false); nifty.gotoScreen("initialMenu"); (nifty.getScreen("initialMenu").findElementByName("dialogNewGameStage1Menu")).hide(); (nifty.getScreen("initialMenu").findElementByName("dialogInitialMenu")).hide(); Element nextElement = nifty.getScreen("initialMenu").findElementByName("dialogMainMenu"); MainMenuController mainMenu = nextElement.getControl(MainMenuController.class); mainMenu.updateControls(); nextElement.show(); nifty.getScreen("initialMenu").findElementByName("dialogNewGameStage1Menu").stopEffect(EffectEventId.onCustom); nifty.getScreen("initialMenu").findElementByName("dialogInitialMenu").stopEffect(EffectEventId.onCustom); nifty.getScreen("initialMenu").findElementByName("dialogMainMenu").startEffect(EffectEventId.onCustom, null, "selected"); gameEngine.getGameData().updatePlayerLog(); }else if (id.equals("buttonStaticOptionGameSetup")){ //showGAMESETUP window if (isVisibleWindowGameSetup) screen.findElementByName("winGSC_Element").getControl(GameSetupControl.class).loadWindowControl(gameEngine, -1, null); else screen.findElementByName("winGSC_Element").getControl(GameSetupControl.class).loadWindowControl(gameEngine, 0, null); isVisibleWindowGameSetup = !isVisibleWindowGameSetup; } } @NiftyEventSubscriber(pattern="buttonOption.*") public void onOptionButtonClicked(final String id, final ButtonClickedEvent event) { gameEngine.updateLastActivitySystemTime(); optionButtonClicked(id); } public void optionButtonClicked(String id){ changeBackgroundButtonActiveInactiveFirst(id); showHideDynamicSubLevelButtons(0); hideCurrentControlsWindow(); if (id.equals(currentOptionselected)){ showHideDynamicButtons(0); currentOptionselected = ""; return; } Screen screenButton = nifty.getScreen("layerScreen"); Button dynamicButton; int position = 0; // if (id.equals("buttonOptionMenu")){ // showHideDynamicButtons(0); // pauseGame(); // ((MenuScreenController)nifty.getScreen("initialMenu").getScreenController()).setDefaultStart(false); // nifty.gotoScreen("initialMenu"); // (nifty.getScreen("initialMenu").findElementByName("dialogNewGameStage1Menu")).hide(); // (nifty.getScreen("initialMenu").findElementByName("dialogInitialMenu")).hide(); // Element nextElement = nifty.getScreen("initialMenu").findElementByName("dialogMainMenu"); // MainMenuController mainMenu = nextElement.getControl(MainMenuController.class); // mainMenu.updateControls(); // nextElement.show(); // nifty.getScreen("initialMenu").findElementByName("dialogNewGameStage1Menu").stopEffect(EffectEventId.onCustom); // nifty.getScreen("initialMenu").findElementByName("dialogInitialMenu").stopEffect(EffectEventId.onCustom); // nifty.getScreen("initialMenu").findElementByName("dialogMainMenu").startEffect(EffectEventId.onCustom, null, "selected"); // gameEngine.getGameData().updatePlayerLog(); // }else // if (id.equals("buttonOptionInformation")){ // showHideDynamicButtons(3); // dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Overall"); position++; // dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Order"); position++; // dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Process Flow Chart"); position++; // }else if (id.equals("buttonOptionControls")){ showHideDynamicButtons(5); dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Allocate Storages"); position++; dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Assign Operators"); position++; dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Priority Activities"); position++; dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Resources"); position++; dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Unit Load"); position++; }else if (id.equals("buttonOptionActivities")){ showHideDynamicButtons(3); dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText(TypeActivity.Operation.toString() + " (" + gameEngine.getGameData().getMapOperation().size() + ")"); position++; dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText(TypeActivity.Purchase.toString() + " (" + gameEngine.getGameData().getMapPurchase().size() + ")"); position++; dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText(TypeActivity.Transport.toString() + " (" + gameEngine.getGameData().getMapTransport().size() + ")"); position++; }else if (id.equals("buttonOptionUtilities")){ showHideDynamicButtons(6); dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Station (" + (gameEngine.getGameData().getMapUserStation().size()-2) + ")"); position++; dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Machine (" + gameEngine.getGameData().getMapUserMachineByOperation().size() + ")"); position++; dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Equipment (" + gameEngine.getGameData().getMapUserMachineByTransport().size() + ")"); position++; dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Operator (" + gameEngine.getGameData().getMapUserOperator().size() + ")"); position++; dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Part (" + gameEngine.getGameData().getMapUserPart().size() + ")"); position++; dynamicButton = screenButton.findNiftyControl("dynBut" + position, Button.class); dynamicButton.setText("Supplier(" + gameEngine.getGameData().getMapGameSupplier().size() + ")"); position++; } currentOptionselected = id; } public void updateSubLevelButtonText(String idButton, String newText){ nifty.getScreen("layerScreen").findNiftyControl(idButton, Button.class).setText(newText); } public boolean getPauseStatus() { return this.isGamePlaying; } public void notifySound() { if(screen.findElementByName("controlVolumeMusic_MGV")!=null) { if(!screen.findElementByName("controlVolumeMusic_MGV").isEnabled()) gameEngine.getGameSounds().setVolumeSFX(0,gameEngine); else gameEngine.getGameSounds().setVolumeSFX(((Slider) screen.findNiftyControl("controlVolumeSFX_MGV", Slider.class)).getValue()/100.f,gameEngine); } } }
package edu.washington.escience.myriad.parallel; import java.nio.channels.ClosedChannelException; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandler.Sharable; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.DownstreamChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.channel.UpstreamChannelStateEvent; import edu.washington.escience.myriad.proto.TransportProto.TransportMessage; @Sharable public class IPCInputGuard extends SimpleChannelHandler { private static final Logger logger = Logger.getLogger(IPCInputGuard.class.getName()); /** * constructor. * */ IPCInputGuard() { } @Override public void handleUpstream(final ChannelHandlerContext ctx, final ChannelEvent e) throws Exception { if (e instanceof UpstreamChannelStateEvent) { UpstreamChannelStateEvent ee = (UpstreamChannelStateEvent) e; switch (ee.getState()) { case OPEN: case BOUND: break; case CONNECTED: logger.info("Connection from remote. " + e.toString()); break; } } super.handleUpstream(ctx, e); } @Override public void handleDownstream(final ChannelHandlerContext ctx, final ChannelEvent e) throws Exception { if (e instanceof DownstreamChannelStateEvent) { DownstreamChannelStateEvent ee = (DownstreamChannelStateEvent) e; switch (ee.getState()) { case OPEN: case BOUND: break; case CONNECTED: logger.info("Connection to remote. " + e.toString()); break; } } super.handleDownstream(ctx, e); } @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) { Object message = e.getMessage(); if (!(message instanceof TransportMessage)) { throw new RuntimeException("Non-TransportMessage received: \n" + "\tfrom " + e.getRemoteAddress() + "\n" + "\tmessage: " + message); } ctx.sendUpstream(e); } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent e) { Channel c = e.getChannel(); Throwable cause = e.getCause(); String errorMessage = cause.getMessage(); if (errorMessage == null) { errorMessage = ""; } if (cause instanceof java.nio.channels.NotYetConnectedException) { logger.log(Level.WARNING, "Channel " + c + ": not yet connected. " + errorMessage, cause); } else if (cause instanceof java.net.ConnectException) { logger.log(Level.WARNING, "Channel " + c + ": Connection failed: " + errorMessage, cause); } else if (cause instanceof java.io.IOException && errorMessage.contains("reset by peer")) { logger.log(Level.WARNING, "Channel " + c + ": Connection reset by peer: " + c.getRemoteAddress() + " " + errorMessage, cause); } else if (cause instanceof ClosedChannelException) { logger.log(Level.WARNING, "Channel " + c + ": Connection reset by peer: " + c.getRemoteAddress() + " " + errorMessage, cause); } else { logger.log(Level.WARNING, "Channel " + c + ": Unexpected exception from downstream.", cause); } if (c != null) { c.close(); } } }
package gov.nih.nci.cananolab.ui.sample; import gov.nih.nci.cananolab.dto.common.FileBean; import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.dto.particle.SampleBean; import gov.nih.nci.cananolab.dto.particle.composition.CompositionBean; import gov.nih.nci.cananolab.exception.SecurityException; import gov.nih.nci.cananolab.service.common.FileService; import gov.nih.nci.cananolab.service.common.impl.FileServiceLocalImpl; import gov.nih.nci.cananolab.service.common.impl.FileServiceRemoteImpl; import gov.nih.nci.cananolab.service.sample.CompositionService; import gov.nih.nci.cananolab.service.sample.SampleService; import gov.nih.nci.cananolab.service.sample.impl.CompositionServiceLocalImpl; import gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl; import gov.nih.nci.cananolab.service.security.AuthorizationService; import gov.nih.nci.cananolab.ui.core.InitSetup; import gov.nih.nci.cananolab.ui.security.InitSecuritySetup; import gov.nih.nci.cananolab.util.Constants; import gov.nih.nci.cananolab.util.StringUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; /** * This class allows users to submit composition files under sample composition. * * @author pansu */ public class CompositionFileAction extends CompositionAction { public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CompositionBean comp = (CompositionBean) theForm.get("comp"); FileBean theFile = comp.getTheFile(); SampleService sampleService=new SampleServiceLocalImpl(); String sampleId=theForm.getString("sampleId"); //need to load the full sample to save composition because of unidirectional relationship //between composition and file SampleBean sampleBean=sampleService.findFullSampleById(sampleId); UserBean user = (UserBean) request.getSession().getAttribute("user"); String internalUriPath = Constants.FOLDER_PARTICLE + "/" + sampleBean.getDomain().getName() + "/" + StringUtils .getOneWordLowerCaseFirstLetter("Composition File"); theFile.setupDomainFile(internalUriPath, user.getLoginName(), 0); CompositionService service = new CompositionServiceLocalImpl(); service.saveCompositionFile(sampleBean.getDomain(), theFile .getDomainFile()); // save to the file system FileService fileService = new FileServiceLocalImpl(); fileService .writeFile(theFile.getDomainFile(), theFile.getNewFileData()); // set visibility AuthorizationService authService = new AuthorizationService( Constants.CSM_APP_NAME); authService.assignVisibility( theFile.getDomainFile().getId().toString(), theFile .getVisibilityGroups(), null); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.addCompositionFile", theFile.getDomainFile().getTitle()); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); request.setAttribute("location", "local"); return summaryEdit(mapping, form, request, response); } private void setLookups(HttpServletRequest request) throws Exception { InitSampleSetup.getInstance().setSharedDropdowns(request); InitSecuritySetup.getInstance().getAllVisibilityGroups(request); } public ActionForward setupNew(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { request.getSession().removeAttribute("compositionForm"); setLookups(request); DynaValidatorForm theForm = (DynaValidatorForm) form; setupSample(theForm, request, "local"); return mapping.getInputForward(); } public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String fileId = request.getParameter("dataId"); UserBean user = (UserBean) request.getSession().getAttribute("user"); FileService fileService = new FileServiceLocalImpl(); FileBean fileBean = fileService.findFileById(fileId); fileService.retrieveVisibility(fileBean, user); CompositionBean compBean=(CompositionBean)theForm.get("comp"); compBean.setTheFile(fileBean); setLookups(request); setupSample(theForm, request, "local"); ActionForward forward = mapping.getInputForward(); return forward; } public ActionForward setupView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String location = request.getParameter("location"); String fileId = request.getParameter("dataId"); UserBean user = (UserBean) request.getSession().getAttribute("user"); FileService fileService = null; if (location.equals("local")) { fileService = new FileServiceLocalImpl(); } else { String serviceUrl = InitSetup.getInstance().getGridServiceUrl( request, location); fileService = new FileServiceRemoteImpl(serviceUrl); } FileBean fileBean = fileService.findFileById(fileId); if (location.equals("local")) { fileService.retrieveVisibility(fileBean, user); } theForm.set("compFile", fileBean); setupSample(theForm, request, location); ActionForward forward = mapping.getInputForward(); return forward; } public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; FileBean fileBean = (FileBean) theForm.get("compFile"); SampleBean sampleBean = setupSample(theForm, request, "local"); CompositionService compService = new CompositionServiceLocalImpl(); compService.deleteCompositionFile(sampleBean.getDomain(), fileBean .getDomainFile()); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.deleteCompositionFile"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); ActionForward forward = mapping.findForward("success"); return forward; } public ActionForward deleteAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String submitType = request.getParameter("submitType"); SampleBean sampleBean = setupSample(theForm, request, "local"); CompositionService compService = new CompositionServiceLocalImpl(); String[] dataIds = (String[]) theForm.get("idsToDelete"); FileService fileService = new FileServiceLocalImpl(); for (String id : dataIds) { FileBean fileBean = fileService.findFileById(id); compService.deleteCompositionFile(sampleBean.getDomain(), fileBean .getDomainFile()); } ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.deleteAnnotations", submitType); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); ActionForward forward = mapping.findForward("success"); return forward; } public boolean loginRequired() { return true; } public boolean canUserExecute(UserBean user) throws SecurityException { return InitSecuritySetup.getInstance().userHasCreatePrivilege(user, Constants.CSM_PG_PARTICLE); } }
package org.postgresql.jdbc1; // IMPORTANT NOTE: This file implements the JDBC 1 version of the driver. // If you make any modifications to this file, you must make sure that the // changes are also made (if relevent) to the related JDBC 2 class in the // org.postgresql.jdbc2 package. import java.sql.*; import java.util.*; import org.postgresql.Field; /** * This class provides information about the database as a whole. * * <p>Many of the methods here return lists of information in ResultSets. You * can use the normal ResultSet methods such as getString and getInt to * retrieve the data from these ResultSets. If a given form of metadata is * not available, these methods should throw a SQLException. * * <p>Some of these methods take arguments that are String patterns. These * arguments all have names such as fooPattern. Within a pattern String, * "%" means match any substring of 0 or more characters, and "_" means * match any one character. Only metadata entries matching the search * pattern are returned. if a search pattern argument is set to a null * ref, it means that argument's criteria should be dropped from the * search. * * <p>A SQLException will be throws if a driver does not support a meta * data method. In the case of methods that return a ResultSet, either * a ResultSet (which may be empty) is returned or a SQLException is * thrown. * * @see java.sql.DatabaseMetaData */ public class DatabaseMetaData implements java.sql.DatabaseMetaData { Connection connection; // The connection association // These define various OID's. Hopefully they will stay constant. static final int iVarcharOid = 1043; // OID for varchar static final int iBoolOid = 16; // OID for bool static final int iInt2Oid = 21; // OID for int2 static final int iInt4Oid = 23; // OID for int4 static final int VARHDRSZ = 4; // length for int4 // This is a default value for remarks private static final byte defaultRemarks[]="no remarks".getBytes(); public DatabaseMetaData(Connection conn) { this.connection = conn; } /** * Can all the procedures returned by getProcedures be called * by the current user? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean allProceduresAreCallable() throws SQLException { return true; // For now... } /** * Can all the tables returned by getTable be SELECTed by * the current user? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean allTablesAreSelectable() throws SQLException { return true; // For now... } /** * What is the URL for this database? * * @return the url or null if it cannott be generated * @exception SQLException if a database access error occurs */ public String getURL() throws SQLException { return connection.getURL(); } /** * What is our user name as known to the database? * * @return our database user name * @exception SQLException if a database access error occurs */ public String getUserName() throws SQLException { return connection.getUserName(); } /** * Is the database in read-only mode? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean isReadOnly() throws SQLException { return connection.isReadOnly(); } /** * Are NULL values sorted high? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean nullsAreSortedHigh() throws SQLException { return false; } /** * Are NULL values sorted low? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean nullsAreSortedLow() throws SQLException { return false; } /** * Are NULL values sorted at the start regardless of sort order? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean nullsAreSortedAtStart() throws SQLException { return false; } /** * Are NULL values sorted at the end regardless of sort order? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean nullsAreSortedAtEnd() throws SQLException { return true; } /** * What is the name of this database product - we hope that it is * PostgreSQL, so we return that explicitly. * * @return the database product name * @exception SQLException if a database access error occurs */ public String getDatabaseProductName() throws SQLException { return "PostgreSQL"; } /** * What is the version of this database product. * * @return the database version * @exception SQLException if a database access error occurs */ public String getDatabaseProductVersion() throws SQLException { java.sql.ResultSet resultSet = connection.ExecSQL("select version()"); resultSet.next(); StringTokenizer versionParts = new StringTokenizer(resultSet.getString(1)); versionParts.nextToken(); /* "PostgreSQL" */ String versionNumber = versionParts.nextToken(); /* "X.Y.Z" */ return versionNumber; } /** * What is the name of this JDBC driver? If we don't know this * we are doing something wrong! * * @return the JDBC driver name * @exception SQLException why? */ public String getDriverName() throws SQLException { return "PostgreSQL Native Driver"; } /** * What is the version string of this JDBC driver? Again, this is * static. * * @return the JDBC driver name. * @exception SQLException why? */ public String getDriverVersion() throws SQLException { return connection.this_driver.getVersion(); } /** * What is this JDBC driver's major version number? * * @return the JDBC driver major version */ public int getDriverMajorVersion() { return connection.this_driver.getMajorVersion(); } /** * What is this JDBC driver's minor version number? * * @return the JDBC driver minor version */ public int getDriverMinorVersion() { return connection.this_driver.getMinorVersion(); } /** * Does the database store tables in a local file? No - it * stores them in a file on the server. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean usesLocalFiles() throws SQLException { return false; } /** * Does the database use a file for each table? Well, not really, * since it doesnt use local files. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean usesLocalFilePerTable() throws SQLException { return false; } /** * Does the database treat mixed case unquoted SQL identifiers * as case sensitive and as a result store them in mixed case? * A JDBC-Compliant driver will always return false. * * <p>Predicament - what do they mean by "SQL identifiers" - if it * means the names of the tables and columns, then the answers * given below are correct - otherwise I don't know. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsMixedCaseIdentifiers() throws SQLException { return false; } /** * Does the database treat mixed case unquoted SQL identifiers as * case insensitive and store them in upper case? * * @return true if so */ public boolean storesUpperCaseIdentifiers() throws SQLException { return false; } /** * Does the database treat mixed case unquoted SQL identifiers as * case insensitive and store them in lower case? * * @return true if so */ public boolean storesLowerCaseIdentifiers() throws SQLException { return true; } /** * Does the database treat mixed case unquoted SQL identifiers as * case insensitive and store them in mixed case? * * @return true if so */ public boolean storesMixedCaseIdentifiers() throws SQLException { return false; } /** * Does the database treat mixed case quoted SQL identifiers as * case sensitive and as a result store them in mixed case? A * JDBC compliant driver will always return true. * * <p>Predicament - what do they mean by "SQL identifiers" - if it * means the names of the tables and columns, then the answers * given below are correct - otherwise I don't know. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { return true; } /** * Does the database treat mixed case quoted SQL identifiers as * case insensitive and store them in upper case? * * @return true if so */ public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { return false; } /** * Does the database treat mixed case quoted SQL identifiers as case * insensitive and store them in lower case? * * @return true if so */ public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { return false; } /** * Does the database treat mixed case quoted SQL identifiers as case * insensitive and store them in mixed case? * * @return true if so */ public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { return false; } /** * What is the string used to quote SQL identifiers? This returns * a space if identifier quoting isn't supported. A JDBC Compliant * driver will always use a double quote character. * * <p>If an SQL identifier is a table name, column name, etc. then * we do not support it. * * @return the quoting string * @exception SQLException if a database access error occurs */ public String getIdentifierQuoteString() throws SQLException { return "\""; } public String getSQLKeywords() throws SQLException { return "abort,acl,add,aggregate,append,archive,arch_store,backward,binary,change,cluster,copy,database,delimiters,do,extend,explain,forward,heavy,index,inherits,isnull,light,listen,load,merge,nothing,notify,notnull,oids,purge,rename,replace,retrieve,returns,rule,recipe,setof,stdin,stdout,store,vacuum,verbose,version"; } public String getNumericFunctions() throws SQLException { // XXX-Not Implemented return ""; } public String getStringFunctions() throws SQLException { // XXX-Not Implemented return ""; } public String getSystemFunctions() throws SQLException { // XXX-Not Implemented return ""; } public String getTimeDateFunctions() throws SQLException { // XXX-Not Implemented return ""; } /** * This is the string that can be used to escape '_' and '%' in * a search string pattern style catalog search parameters * * @return the string used to escape wildcard characters * @exception SQLException if a database access error occurs */ public String getSearchStringEscape() throws SQLException { return "\\"; } /** * Get all the "extra" characters that can bew used in unquoted * identifier names (those beyond a-zA-Z0-9 and _) * * <p>From the file src/backend/parser/scan.l, an identifier is * {letter}{letter_or_digit} which makes it just those listed * above. * * @return a string containing the extra characters * @exception SQLException if a database access error occurs */ public String getExtraNameCharacters() throws SQLException { return ""; } /** * Is "ALTER TABLE" with an add column supported? * Yes for PostgreSQL 6.1 * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsAlterTableWithAddColumn() throws SQLException { return true; } /** * Is "ALTER TABLE" with a drop column supported? * Peter 10/10/2000 This was set to true, but 7.1devel doesn't support it! * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsAlterTableWithDropColumn() throws SQLException { return false; } public boolean supportsColumnAliasing() throws SQLException { return true; } /** * Are concatenations between NULL and non-NULL values NULL? A * JDBC Compliant driver always returns true * * @return true if so * @exception SQLException if a database access error occurs */ public boolean nullPlusNonNullIsNull() throws SQLException { return true; } public boolean supportsConvert() throws SQLException { // XXX-Not Implemented return false; } public boolean supportsConvert(int fromType, int toType) throws SQLException { // XXX-Not Implemented return false; } public boolean supportsTableCorrelationNames() throws SQLException { // XXX-Not Implemented return false; } public boolean supportsDifferentTableCorrelationNames() throws SQLException { // XXX-Not Implemented return false; } /** * Are expressions in "ORCER BY" lists supported? * * <br>e.g. select * from t order by a + b; * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsExpressionsInOrderBy() throws SQLException { return true; } /** * Can an "ORDER BY" clause use columns not in the SELECT? * I checked it, and you can't. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsOrderByUnrelated() throws SQLException { return false; } /** * Is some form of "GROUP BY" clause supported? * I checked it, and yes it is. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsGroupBy() throws SQLException { return true; } /** * Can a "GROUP BY" clause use columns not in the SELECT? * I checked it - it seems to allow it * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsGroupByUnrelated() throws SQLException { return true; } /** * Can a "GROUP BY" clause add columns not in the SELECT provided * it specifies all the columns in the SELECT? Does anyone actually * understand what they mean here? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsGroupByBeyondSelect() throws SQLException { return true; // For now... } /** * Is the escape character in "LIKE" clauses supported? A * JDBC compliant driver always returns true. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsLikeEscapeClause() throws SQLException { return true; } /** * Are multiple ResultSets from a single execute supported? * Well, I implemented it, but I dont think this is possible from * the back ends point of view. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsMultipleResultSets() throws SQLException { return false; } /** * Can we have multiple transactions open at once (on different * connections?) * I guess we can have, since Im relying on it. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsMultipleTransactions() throws SQLException { return true; } /** * Can columns be defined as non-nullable. A JDBC Compliant driver * always returns true. * * <p>This changed from false to true in v6.2 of the driver, as this * support was added to the backend. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsNonNullableColumns() throws SQLException { return true; } public boolean supportsMinimumSQLGrammar() throws SQLException { return true; } /** * Does this driver support the Core ODBC SQL grammar. We need * SQL-92 conformance for this. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsCoreSQLGrammar() throws SQLException { return false; } /** * Does this driver support the Extended (Level 2) ODBC SQL * grammar. We don't conform to the Core (Level 1), so we can't * conform to the Extended SQL Grammar. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsExtendedSQLGrammar() throws SQLException { return false; } /** * Does this driver support the ANSI-92 entry level SQL grammar? * All JDBC Compliant drivers must return true. I think we have * to support outer joins for this to be true. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsANSI92EntryLevelSQL() throws SQLException { return false; } /** * Does this driver support the ANSI-92 intermediate level SQL * grammar? Anyone who does not support Entry level cannot support * Intermediate level. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsANSI92IntermediateSQL() throws SQLException { return false; } /** * Does this driver support the ANSI-92 full SQL grammar? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsANSI92FullSQL() throws SQLException { return false; } /** * Is the SQL Integrity Enhancement Facility supported? * I haven't seen this mentioned anywhere, so I guess not * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsIntegrityEnhancementFacility() throws SQLException { return false; } /** * Is some form of outer join supported? From my knowledge, nope. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsOuterJoins() throws SQLException { return false; } /** * Are full nexted outer joins supported? Well, we dont support any * form of outer join, so this is no as well * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsFullOuterJoins() throws SQLException { return false; } /** * Is there limited support for outer joins? (This will be true if * supportFullOuterJoins is true) * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsLimitedOuterJoins() throws SQLException { return false; } /** * What is the database vendor's preferred term for "schema" - well, * we do not provide support for schemas, so lets just use that * term. * * @return the vendor term * @exception SQLException if a database access error occurs */ public String getSchemaTerm() throws SQLException { return "Schema"; } /** * What is the database vendor's preferred term for "procedure" - * I kind of like "Procedure" myself. * * @return the vendor term * @exception SQLException if a database access error occurs */ public String getProcedureTerm() throws SQLException { return "Procedure"; } /** * What is the database vendor's preferred term for "catalog"? - * we dont have a preferred term, so just use Catalog * * @return the vendor term * @exception SQLException if a database access error occurs */ public String getCatalogTerm() throws SQLException { return "Catalog"; } /** * Does a catalog appear at the start of a qualified table name? * (Otherwise it appears at the end). * * @return true if so * @exception SQLException if a database access error occurs */ public boolean isCatalogAtStart() throws SQLException { return false; } /** * What is the Catalog separator. Hmmm....well, I kind of like * a period (so we get catalog.table definitions). - I don't think * PostgreSQL supports catalogs anyhow, so it makes no difference. * * @return the catalog separator string * @exception SQLException if a database access error occurs */ public String getCatalogSeparator() throws SQLException { // PM Sep 29 97 - changed from "." as we don't support catalogs. return ""; } /** * Can a schema name be used in a data manipulation statement? Nope. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsSchemasInDataManipulation() throws SQLException { return false; } /** * Can a schema name be used in a procedure call statement? Nope. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsSchemasInProcedureCalls() throws SQLException { return false; } /** * Can a schema be used in a table definition statement? Nope. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsSchemasInTableDefinitions() throws SQLException { return false; } /** * Can a schema name be used in an index definition statement? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsSchemasInIndexDefinitions() throws SQLException { return false; } /** * Can a schema name be used in a privilege definition statement? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { return false; } /** * Can a catalog name be used in a data manipulation statement? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsCatalogsInDataManipulation() throws SQLException { return false; } /** * Can a catalog name be used in a procedure call statement? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsCatalogsInProcedureCalls() throws SQLException { return false; } /** * Can a catalog name be used in a table definition statement? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsCatalogsInTableDefinitions() throws SQLException { return false; } /** * Can a catalog name be used in an index definition? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsCatalogsInIndexDefinitions() throws SQLException { return false; } /** * Can a catalog name be used in a privilege definition statement? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { return false; } /** * We support cursors for gets only it seems. I dont see a method * to get a positioned delete. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsPositionedDelete() throws SQLException { return false; // For now... } /** * Is positioned UPDATE supported? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsPositionedUpdate() throws SQLException { return false; // For now... } public boolean supportsSelectForUpdate() throws SQLException { // XXX-Not Implemented return false; } public boolean supportsStoredProcedures() throws SQLException { // XXX-Not Implemented return false; } public boolean supportsSubqueriesInComparisons() throws SQLException { // XXX-Not Implemented return false; } public boolean supportsSubqueriesInExists() throws SQLException { // XXX-Not Implemented return false; } public boolean supportsSubqueriesInIns() throws SQLException { // XXX-Not Implemented return false; } public boolean supportsSubqueriesInQuantifieds() throws SQLException { // XXX-Not Implemented return false; } public boolean supportsCorrelatedSubqueries() throws SQLException { // XXX-Not Implemented return false; } /** * Is SQL UNION supported? Nope. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsUnion() throws SQLException { return false; } /** * Is SQL UNION ALL supported? Nope. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsUnionAll() throws SQLException { return false; } /** * In PostgreSQL, Cursors are only open within transactions. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsOpenCursorsAcrossCommit() throws SQLException { return false; } /** * Do we support open cursors across multiple transactions? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsOpenCursorsAcrossRollback() throws SQLException { return false; } /** * Can statements remain open across commits? They may, but * this driver cannot guarentee that. In further reflection. * we are talking a Statement object jere, so the answer is * yes, since the Statement is only a vehicle to ExecSQL() * * @return true if they always remain open; false otherwise * @exception SQLException if a database access error occurs */ public boolean supportsOpenStatementsAcrossCommit() throws SQLException { return true; } /** * Can statements remain open across rollbacks? They may, but * this driver cannot guarentee that. In further contemplation, * we are talking a Statement object here, so the answer is yes, * since the Statement is only a vehicle to ExecSQL() in Connection * * @return true if they always remain open; false otherwise * @exception SQLException if a database access error occurs */ public boolean supportsOpenStatementsAcrossRollback() throws SQLException { return true; } /** * How many hex characters can you have in an inline binary literal * * @return the max literal length * @exception SQLException if a database access error occurs */ public int getMaxBinaryLiteralLength() throws SQLException { return 0; // For now... } /** * What is the maximum length for a character literal * I suppose it is 8190 (8192 - 2 for the quotes) * * @return the max literal length * @exception SQLException if a database access error occurs */ public int getMaxCharLiteralLength() throws SQLException { return 65535; } /** * Whats the limit on column name length. The description of * pg_class would say '32' (length of pg_class.relname) - we * should probably do a query for this....but.... * * @return the maximum column name length * @exception SQLException if a database access error occurs */ public int getMaxColumnNameLength() throws SQLException { return 32; } /** * What is the maximum number of columns in a "GROUP BY" clause? * * @return the max number of columns * @exception SQLException if a database access error occurs */ public int getMaxColumnsInGroupBy() throws SQLException { return getMaxColumnsInTable(); } /** * What's the maximum number of columns allowed in an index? * 6.0 only allowed one column, but 6.1 introduced multi-column * indices, so, theoretically, its all of them. * * @return max number of columns * @exception SQLException if a database access error occurs */ public int getMaxColumnsInIndex() throws SQLException { return getMaxColumnsInTable(); } /** * What's the maximum number of columns in an "ORDER BY clause? * Theoretically, all of them! * * @return the max columns * @exception SQLException if a database access error occurs */ public int getMaxColumnsInOrderBy() throws SQLException { return getMaxColumnsInTable(); } /** * What is the maximum number of columns in a "SELECT" list? * Theoretically, all of them! * * @return the max columns * @exception SQLException if a database access error occurs */ public int getMaxColumnsInSelect() throws SQLException { return getMaxColumnsInTable(); } /** * What is the maximum number of columns in a table? From the * create_table(l) manual page... * * <p>"The new class is created as a heap with no initial data. A * class can have no more than 1600 attributes (realistically, * this is limited by the fact that tuple sizes must be less than * 8192 bytes)..." * * @return the max columns * @exception SQLException if a database access error occurs */ public int getMaxColumnsInTable() throws SQLException { return 1600; } /** * How many active connection can we have at a time to this * database? Well, since it depends on postmaster, which just * does a listen() followed by an accept() and fork(), its * basically very high. Unless the system runs out of processes, * it can be 65535 (the number of aux. ports on a TCP/IP system). * I will return 8192 since that is what even the largest system * can realistically handle, * * @return the maximum number of connections * @exception SQLException if a database access error occurs */ public int getMaxConnections() throws SQLException { return 8192; } public int getMaxCursorNameLength() throws SQLException { return 32; } /** * What is the maximum length of an index (in bytes)? Now, does * the spec. mean name of an index (in which case its 32, the * same as a table) or does it mean length of an index element * (in which case its 8192, the size of a row) or does it mean * the number of rows it can access (in which case it 2^32 - * a 4 byte OID number)? I think its the length of an index * element, personally, so Im setting it to 65535. * * @return max index length in bytes * @exception SQLException if a database access error occurs */ public int getMaxIndexLength() throws SQLException { return 65535; } public int getMaxSchemaNameLength() throws SQLException { // XXX-Not Implemented return 0; } /** * What is the maximum length of a procedure name? * (length of pg_proc.proname used) - again, I really * should do a query here to get it. * * @return the max name length in bytes * @exception SQLException if a database access error occurs */ public int getMaxProcedureNameLength() throws SQLException { return 32; } public int getMaxCatalogNameLength() throws SQLException { // XXX-Not Implemented return 0; } /** * What is the maximum length of a single row? (not including * blobs). 65535 is defined in PostgreSQL. * * @return max row size in bytes * @exception SQLException if a database access error occurs */ public int getMaxRowSize() throws SQLException { return 65535; } /** * Did getMaxRowSize() include LONGVARCHAR and LONGVARBINARY * blobs? We don't handle blobs yet * * @return true if so * @exception SQLException if a database access error occurs */ public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { return false; } /** * What is the maximum length of a SQL statement? * * @return max length in bytes * @exception SQLException if a database access error occurs */ public int getMaxStatementLength() throws SQLException { return 65535; } /** * How many active statements can we have open at one time to * this database? Basically, since each Statement downloads * the results as the query is executed, we can have many. However, * we can only really have one statement per connection going * at once (since they are executed serially) - so we return * one. * * @return the maximum * @exception SQLException if a database access error occurs */ public int getMaxStatements() throws SQLException { return 1; } /** * What is the maximum length of a table name? This was found * from pg_class.relname length * * @return max name length in bytes * @exception SQLException if a database access error occurs */ public int getMaxTableNameLength() throws SQLException { return 32; } /** * What is the maximum number of tables that can be specified * in a SELECT? Theoretically, this is the same number as the * number of tables allowable. In practice tho, it is much smaller * since the number of tables is limited by the statement, we * return 1024 here - this is just a number I came up with (being * the number of tables roughly of three characters each that you * can fit inside a 65535 character buffer with comma separators). * * @return the maximum * @exception SQLException if a database access error occurs */ public int getMaxTablesInSelect() throws SQLException { return 1024; } /** * What is the maximum length of a user name? Well, we generally * use UNIX like user names in PostgreSQL, so I think this would * be 8. However, showing the schema for pg_user shows a length * for username of 32. * * @return the max name length in bytes * @exception SQLException if a database access error occurs */ public int getMaxUserNameLength() throws SQLException { return 32; } /** * What is the database's default transaction isolation level? We * do not support this, so all transactions are SERIALIZABLE. * * @return the default isolation level * @exception SQLException if a database access error occurs * @see Connection */ public int getDefaultTransactionIsolation() throws SQLException { return Connection.TRANSACTION_READ_COMMITTED; } /** * Are transactions supported? If not, commit and rollback are noops * and the isolation level is TRANSACTION_NONE. We do support * transactions. * * @return true if transactions are supported * @exception SQLException if a database access error occurs */ public boolean supportsTransactions() throws SQLException { return true; } /** * Does the database support the given transaction isolation level? * We only support TRANSACTION_SERIALIZABLE and TRANSACTION_READ_COMMITTED * * @param level the values are defined in java.sql.Connection * @return true if so * @exception SQLException if a database access error occurs * @see Connection */ public boolean supportsTransactionIsolationLevel(int level) throws SQLException { if (level == Connection.TRANSACTION_SERIALIZABLE || level == Connection.TRANSACTION_READ_COMMITTED) return true; else return false; } /** * Are both data definition and data manipulation transactions * supported? I checked it, and could not do a CREATE TABLE * within a transaction, so I am assuming that we don't * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { return false; } /** * Are only data manipulation statements withing a transaction * supported? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsDataManipulationTransactionsOnly() throws SQLException { return true; } /** * Does a data definition statement within a transaction force * the transaction to commit? I think this means something like: * * <p><pre> * CREATE TABLE T (A INT); * INSERT INTO T (A) VALUES (2); * BEGIN; * UPDATE T SET A = A + 1; * CREATE TABLE X (A INT); * SELECT A FROM T INTO X; * COMMIT; * </pre><p> * * does the CREATE TABLE call cause a commit? The answer is no. * * @return true if so * @exception SQLException if a database access error occurs */ public boolean dataDefinitionCausesTransactionCommit() throws SQLException { return false; } /** * Is a data definition statement within a transaction ignored? * It seems to be (from experiment in previous method) * * @return true if so * @exception SQLException if a database access error occurs */ public boolean dataDefinitionIgnoredInTransactions() throws SQLException { return true; } /** * Get a description of stored procedures available in a catalog * * <p>Only procedure descriptions matching the schema and procedure * name criteria are returned. They are ordered by PROCEDURE_SCHEM * and PROCEDURE_NAME * * <p>Each procedure description has the following columns: * <ol> * <li><b>PROCEDURE_CAT</b> String => procedure catalog (may be null) * <li><b>PROCEDURE_SCHEM</b> String => procedure schema (may be null) * <li><b>PROCEDURE_NAME</b> String => procedure name * <li><b>Field 4</b> reserved (make it null) * <li><b>Field 5</b> reserved (make it null) * <li><b>Field 6</b> reserved (make it null) * <li><b>REMARKS</b> String => explanatory comment on the procedure * <li><b>PROCEDURE_TYPE</b> short => kind of procedure * <ul> * <li> procedureResultUnknown - May return a result * <li> procedureNoResult - Does not return a result * <li> procedureReturnsResult - Returns a result * </ul> * </ol> * * @param catalog - a catalog name; "" retrieves those without a * catalog; null means drop catalog name from criteria * @param schemaParrern - a schema name pattern; "" retrieves those * without a schema - we ignore this parameter * @param procedureNamePattern - a procedure name pattern * @return ResultSet - each row is a procedure description * @exception SQLException if a database access error occurs */ public java.sql.ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException { // the field descriptors for the new ResultSet Field f[] = new Field[8]; java.sql.ResultSet r; // ResultSet for the SQL query that we need to do Vector v = new Vector(); // The new ResultSet tuple stuff byte remarks[] = defaultRemarks; f[0] = new Field(connection, "PROCEDURE_CAT", iVarcharOid, 32); f[1] = new Field(connection, "PROCEDURE_SCHEM", iVarcharOid, 32); f[2] = new Field(connection, "PROCEDURE_NAME", iVarcharOid, 32); f[3] = f[4] = f[5] = null; // reserved, must be null for now f[6] = new Field(connection, "REMARKS", iVarcharOid, 8192); f[7] = new Field(connection, "PROCEDURE_TYPE", iInt2Oid, 2); // If the pattern is null, then set it to the default if(procedureNamePattern==null) procedureNamePattern="%"; r = connection.ExecSQL("select proname, proretset from pg_proc where proname like '"+procedureNamePattern.toLowerCase()+"' order by proname"); while (r.next()) { byte[][] tuple = new byte[8][0]; tuple[0] = null; // Catalog name tuple[1] = null; // Schema name tuple[2] = r.getBytes(1); // Procedure name tuple[3] = tuple[4] = tuple[5] = null; // Reserved tuple[6] = remarks; // Remarks if (r.getBoolean(2)) tuple[7] = Integer.toString(java.sql.DatabaseMetaData.procedureReturnsResult).getBytes(); else tuple[7] = Integer.toString(java.sql.DatabaseMetaData.procedureNoResult).getBytes(); v.addElement(tuple); } return new ResultSet(connection, f, v, "OK", 1); } /** * Get a description of a catalog's stored procedure parameters * and result columns. * * <p>Only descriptions matching the schema, procedure and parameter * name criteria are returned. They are ordered by PROCEDURE_SCHEM * and PROCEDURE_NAME. Within this, the return value, if any, is * first. Next are the parameter descriptions in call order. The * column descriptions follow in column number order. * * <p>Each row in the ResultSet is a parameter description or column * description with the following fields: * <ol> * <li><b>PROCEDURE_CAT</b> String => procedure catalog (may be null) * <li><b>PROCEDURE_SCHE</b>M String => procedure schema (may be null) * <li><b>PROCEDURE_NAME</b> String => procedure name * <li><b>COLUMN_NAME</b> String => column/parameter name * <li><b>COLUMN_TYPE</b> Short => kind of column/parameter: * <ul><li>procedureColumnUnknown - nobody knows * <li>procedureColumnIn - IN parameter * <li>procedureColumnInOut - INOUT parameter * <li>procedureColumnOut - OUT parameter * <li>procedureColumnReturn - procedure return value * <li>procedureColumnResult - result column in ResultSet * </ul> * <li><b>DATA_TYPE</b> short => SQL type from java.sql.Types * <li><b>TYPE_NAME</b> String => SQL type name * <li><b>PRECISION</b> int => precision * <li><b>LENGTH</b> int => length in bytes of data * <li><b>SCALE</b> short => scale * <li><b>RADIX</b> short => radix * <li><b>NULLABLE</b> short => can it contain NULL? * <ul><li>procedureNoNulls - does not allow NULL values * <li>procedureNullable - allows NULL values * <li>procedureNullableUnknown - nullability unknown * <li><b>REMARKS</b> String => comment describing parameter/column * </ol> * @param catalog This is ignored in org.postgresql, advise this is set to null * @param schemaPattern This is ignored in org.postgresql, advise this is set to null * @param procedureNamePattern a procedure name pattern * @param columnNamePattern a column name pattern * @return each row is a stored procedure parameter or column description * @exception SQLException if a database-access error occurs * @see #getSearchStringEscape */ // Implementation note: This is required for Borland's JBuilder to work public java.sql.ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { if(procedureNamePattern==null) procedureNamePattern="%"; if(columnNamePattern==null) columnNamePattern="%"; // for now, this returns an empty result set. Field f[] = new Field[13]; ResultSet r; // ResultSet for the SQL query that we need to do Vector v = new Vector(); // The new ResultSet tuple stuff f[0] = new Field(connection, "PROCEDURE_CAT", iVarcharOid, 32); f[1] = new Field(connection, "PROCEDURE_SCHEM", iVarcharOid, 32); f[2] = new Field(connection, "PROCEDURE_NAME", iVarcharOid, 32); f[3] = new Field(connection, "COLUMN_NAME", iVarcharOid, 32); f[4] = new Field(connection, "COLUMN_TYPE", iInt2Oid, 2); f[5] = new Field(connection, "DATA_TYPE", iInt2Oid, 2); f[6] = new Field(connection, "TYPE_NAME", iVarcharOid, 32); f[7] = new Field(connection, "PRECISION", iInt4Oid, 4); f[8] = new Field(connection, "LENGTH", iInt4Oid, 4); f[9] = new Field(connection, "SCALE", iInt2Oid, 2); f[10] = new Field(connection, "RADIX", iInt2Oid, 2); f[11] = new Field(connection, "NULLABLE", iInt2Oid, 2); f[12] = new Field(connection, "REMARKS", iVarcharOid, 32); // add query loop here return new ResultSet(connection, f, v, "OK", 1); } /** * Get a description of tables available in a catalog. * * <p>Only table descriptions matching the catalog, schema, table * name and type criteria are returned. They are ordered by * TABLE_TYPE, TABLE_SCHEM and TABLE_NAME. * * <p>Each table description has the following columns: * * <ol> * <li><b>TABLE_CAT</b> String => table catalog (may be null) * <li><b>TABLE_SCHEM</b> String => table schema (may be null) * <li><b>TABLE_NAME</b> String => table name * <li><b>TABLE_TYPE</b> String => table type. Typical types are "TABLE", * "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL * TEMPORARY", "ALIAS", "SYNONYM". * <li><b>REMARKS</b> String => explanatory comment on the table * </ol> * * <p>The valid values for the types parameter are: * "TABLE", "INDEX", "SEQUENCE", "SYSTEM TABLE" and "SYSTEM INDEX" * * @param catalog a catalog name; For org.postgresql, this is ignored, and * should be set to null * @param schemaPattern a schema name pattern; For org.postgresql, this is ignored, and * should be set to null * @param tableNamePattern a table name pattern. For all tables this should be "%" * @param types a list of table types to include; null returns * all types * @return each row is a table description * @exception SQLException if a database-access error occurs. */ public java.sql.ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[]) throws SQLException { // Handle default value for types if(types==null) types = defaultTableTypes; if(tableNamePattern==null) tableNamePattern="%"; // the field descriptors for the new ResultSet Field f[] = new Field[5]; java.sql.ResultSet r; // ResultSet for the SQL query that we need to do Vector v = new Vector(); // The new ResultSet tuple stuff f[0] = new Field(connection, "TABLE_CAT", iVarcharOid, 32); f[1] = new Field(connection, "TABLE_SCHEM", iVarcharOid, 32); f[2] = new Field(connection, "TABLE_NAME", iVarcharOid, 32); f[3] = new Field(connection, "TABLE_TYPE", iVarcharOid, 32); f[4] = new Field(connection, "REMARKS", iVarcharOid, 32); // Now form the query StringBuffer sql = new StringBuffer("select relname,oid,relkind from pg_class where ("); boolean notFirst=false; for(int i=0;i<types.length;i++) { for(int j=0;j<getTableTypes.length;j++) if(getTableTypes[j][0].equals(types[i])) { if(notFirst) sql.append(" or "); sql.append(getTableTypes[j][1]); notFirst=true; } } // Added by Stefan Andreasen <stefan@linux.kapow.dk> // Now take the pattern into account sql.append(") and relname like '"); sql.append(tableNamePattern.toLowerCase()); sql.append("' order by relkind, relname"); // Now run the query r = connection.ExecSQL(sql.toString()); byte remarks[]; while (r.next()) { byte[][] tuple = new byte[5][0]; // Fetch the description for the table (if any) java.sql.ResultSet dr = connection.ExecSQL("select description from pg_description where objoid="+r.getInt(2)); if(((org.postgresql.ResultSet)dr).getTupleCount()==1) { dr.next(); remarks = dr.getBytes(1); } else remarks = defaultRemarks; dr.close(); String relKind; switch (r.getBytes(3)[0]) { case 'r': relKind = "TABLE"; break; case 'i': relKind = "INDEX"; break; case 'S': relKind = "SEQUENCE"; break; default: relKind = null; } tuple[0] = null; // Catalog name tuple[1] = null; // Schema name tuple[2] = r.getBytes(1); // Table name tuple[3] = relKind.getBytes(); // Table type tuple[4] = remarks; // Remarks v.addElement(tuple); } r.close(); return new ResultSet(connection, f, v, "OK", 1); } // This array contains the valid values for the types argument // in getTables(). // Each supported type consists of it's name, and the sql where // clause to retrieve that value. // IMPORTANT: the query must be enclosed in ( ) private static final String getTableTypes[][] = { {"TABLE", "(relkind='r' and relhasrules='f' and relname !~ '^pg_')"}, {"VIEW", "(relkind='v' and relname !~ '^pg_')"}, {"INDEX", "(relkind='i' and relname !~ '^pg_')"}, {"SEQUENCE", "(relkind='S' and relname !~ '^pg_')"}, {"SYSTEM TABLE", "(relkind='r' and relname ~ '^pg_')"}, {"SYSTEM INDEX", "(relkind='i' and relname ~ '^pg_')"} }; // These are the default tables, used when NULL is passed to getTables // The choice of these provide the same behaviour as psql's \d private static final String defaultTableTypes[] = { "TABLE","VIEW","INDEX","SEQUENCE" }; /** * Get the schema names available in this database. The results * are ordered by schema name. * * <P>The schema column is: * <OL> * <LI><B>TABLE_SCHEM</B> String => schema name * </OL> * * @return ResultSet each row has a single String column that is a * schema name */ public java.sql.ResultSet getSchemas() throws SQLException { // We don't use schemas, so we simply return a single schema name "". Field f[] = new Field[1]; Vector v = new Vector(); byte[][] tuple = new byte[1][0]; f[0] = new Field(connection,"TABLE_SCHEM",iVarcharOid,32); tuple[0] = "".getBytes(); v.addElement(tuple); return new ResultSet(connection,f,v,"OK",1); } /** * Get the catalog names available in this database. The results * are ordered by catalog name. * * <P>The catalog column is: * <OL> * <LI><B>TABLE_CAT</B> String => catalog name * </OL> * * @return ResultSet each row has a single String column that is a * catalog name */ public java.sql.ResultSet getCatalogs() throws SQLException { // We don't use catalogs, so we simply return a single catalog name "". Field f[] = new Field[1]; Vector v = new Vector(); byte[][] tuple = new byte[1][0]; f[0] = new Field(connection,"TABLE_CAT",iVarcharOid,32); tuple[0] = "".getBytes(); v.addElement(tuple); return new ResultSet(connection,f,v,"OK",1); } /** * Get the table types available in this database. The results * are ordered by table type. * * <P>The table type is: * <OL> * <LI><B>TABLE_TYPE</B> String => table type. Typical types are "TABLE", * "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", * "LOCAL TEMPORARY", "ALIAS", "SYNONYM". * </OL> * * @return ResultSet each row has a single String column that is a * table type */ public java.sql.ResultSet getTableTypes() throws SQLException { Field f[] = new Field[1]; Vector v = new Vector(); f[0] = new Field(connection,new String("TABLE_TYPE"),iVarcharOid,32); for(int i=0;i<getTableTypes.length;i++) { byte[][] tuple = new byte[1][0]; tuple[0] = getTableTypes[i][0].getBytes(); v.addElement(tuple); } return new ResultSet(connection,f,v,"OK",1); } /** * Get a description of table columns available in a catalog. * * <P>Only column descriptions matching the catalog, schema, table * and column name criteria are returned. They are ordered by * TABLE_SCHEM, TABLE_NAME and ORDINAL_POSITION. * * <P>Each column description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>DATA_TYPE</B> short => SQL type from java.sql.Types * <LI><B>TYPE_NAME</B> String => Data source dependent type name * <LI><B>COLUMN_SIZE</B> int => column size. For char or date * types this is the maximum number of characters, for numeric or * decimal types this is precision. * <LI><B>BUFFER_LENGTH</B> is not used. * <LI><B>DECIMAL_DIGITS</B> int => the number of fractional digits * <LI><B>NUM_PREC_RADIX</B> int => Radix (typically either 10 or 2) * <LI><B>NULLABLE</B> int => is NULL allowed? * <UL> * <LI> columnNoNulls - might not allow NULL values * <LI> columnNullable - definitely allows NULL values * <LI> columnNullableUnknown - nullability unknown * </UL> * <LI><B>REMARKS</B> String => comment describing column (may be null) * <LI><B>COLUMN_DEF</B> String => default value (may be null) * <LI><B>SQL_DATA_TYPE</B> int => unused * <LI><B>SQL_DATETIME_SUB</B> int => unused * <LI><B>CHAR_OCTET_LENGTH</B> int => for char types the * maximum number of bytes in the column * <LI><B>ORDINAL_POSITION</B> int => index of column in table * (starting at 1) * <LI><B>IS_NULLABLE</B> String => "NO" means column definitely * does not allow NULL values; "YES" means the column might * allow NULL values. An empty string means nobody knows. * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schemaPattern a schema name pattern; "" retrieves those * without a schema * @param tableNamePattern a table name pattern * @param columnNamePattern a column name pattern * @return ResultSet each row is a column description * @see #getSearchStringEscape */ public java.sql.ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { // the field descriptors for the new ResultSet Field f[] = new Field[18]; java.sql.ResultSet r; // ResultSet for the SQL query that we need to do Vector v = new Vector(); // The new ResultSet tuple stuff f[0] = new Field(connection, "TABLE_CAT", iVarcharOid, 32); f[1] = new Field(connection, "TABLE_SCHEM", iVarcharOid, 32); f[2] = new Field(connection, "TABLE_NAME", iVarcharOid, 32); f[3] = new Field(connection, "COLUMN_NAME", iVarcharOid, 32); f[4] = new Field(connection, "DATA_TYPE", iInt2Oid, 2); f[5] = new Field(connection, "TYPE_NAME", iVarcharOid, 32); f[6] = new Field(connection, "COLUMN_SIZE", iInt4Oid, 4); f[7] = new Field(connection, "BUFFER_LENGTH", iVarcharOid, 32); f[8] = new Field(connection, "DECIMAL_DIGITS", iInt4Oid, 4); f[9] = new Field(connection, "NUM_PREC_RADIX", iInt4Oid, 4); f[10] = new Field(connection, "NULLABLE", iInt4Oid, 4); f[11] = new Field(connection, "REMARKS", iVarcharOid, 32); f[12] = new Field(connection, "COLUMN_DEF", iVarcharOid, 32); f[13] = new Field(connection, "SQL_DATA_TYPE", iInt4Oid, 4); f[14] = new Field(connection, "SQL_DATETIME_SUB", iInt4Oid, 4); f[15] = new Field(connection, "CHAR_OCTET_LENGTH", iVarcharOid, 32); f[16] = new Field(connection, "ORDINAL_POSITION", iInt4Oid,4); f[17] = new Field(connection, "IS_NULLABLE", iVarcharOid, 32); // Added by Stefan Andreasen <stefan@linux.kapow.dk> // If the pattern are null then set them to % if (tableNamePattern == null) tableNamePattern="%"; if (columnNamePattern == null) columnNamePattern="%"; // Now form the query r = connection.ExecSQL("select a.oid,c.relname,a.attname,a.atttypid,a.attnum,a.attnotnull,a.attlen,a.atttypmod from pg_class c, pg_attribute a where a.attrelid=c.oid and c.relname like '"+tableNamePattern.toLowerCase()+"' and a.attname like '"+columnNamePattern.toLowerCase()+"' and a.attnum>0 order by c.relname,a.attnum"); byte remarks[]; while(r.next()) { byte[][] tuple = new byte[18][0]; // Fetch the description for the table (if any) java.sql.ResultSet dr = connection.ExecSQL("select description from pg_description where objoid="+r.getInt(1)); if(((org.postgresql.ResultSet)dr).getTupleCount()==1) { dr.next(); tuple[11] = dr.getBytes(1); } else tuple[11] = defaultRemarks; dr.close(); tuple[0] = "".getBytes(); // Catalog name tuple[1] = "".getBytes(); // Schema name tuple[2] = r.getBytes(2); // Table name tuple[3] = r.getBytes(3); // Column name dr = connection.ExecSQL("select typname from pg_type where oid = "+r.getString(4)); dr.next(); String typname=dr.getString(1); dr.close(); tuple[4] = Integer.toString(Field.getSQLType(typname)).getBytes(); // Data type tuple[5] = typname.getBytes(); // Type name // Column size // Looking at the psql source, // I think the length of a varchar as specified when the table was created // should be extracted from atttypmod which contains this length + sizeof(int32) if (typname.equals("bpchar") || typname.equals("varchar")) { int atttypmod = r.getInt(8); tuple[6] = Integer.toString(atttypmod != -1 ? atttypmod - VARHDRSZ : 0).getBytes(); } else tuple[6] = r.getBytes(7); tuple[7] = null; // Buffer length tuple[8] = "0".getBytes(); // Decimal Digits - how to get this? tuple[9] = "10".getBytes(); // Num Prec Radix - assume decimal // tuple[10] is below // tuple[11] is above tuple[12] = null; // column default tuple[13] = null; // sql data type (unused) tuple[14] = null; // sql datetime sub (unused) tuple[15] = tuple[6]; // char octet length tuple[16] = r.getBytes(5); // ordinal position String nullFlag = r.getString(6); tuple[10] = Integer.toString(nullFlag.equals("f")?java.sql.DatabaseMetaData.columnNullable:java.sql.DatabaseMetaData.columnNoNulls).getBytes(); // Nullable tuple[17] = (nullFlag.equals("f")?"YES":"NO").getBytes(); // is nullable v.addElement(tuple); } r.close(); return new ResultSet(connection, f, v, "OK", 1); } /** * Get a description of the access rights for a table's columns. * * <P>Only privileges matching the column name criteria are * returned. They are ordered by COLUMN_NAME and PRIVILEGE. * * <P>Each privilige description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>GRANTOR</B> => grantor of access (may be null) * <LI><B>GRANTEE</B> String => grantee of access * <LI><B>PRIVILEGE</B> String => name of access (SELECT, * INSERT, UPDATE, REFRENCES, ...) * <LI><B>IS_GRANTABLE</B> String => "YES" if grantee is permitted * to grant to others; "NO" if not; null if unknown * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name; "" retrieves those without a schema * @param table a table name * @param columnNamePattern a column name pattern * @return ResultSet each row is a column privilege description * @see #getSearchStringEscape */ public java.sql.ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException { Field f[] = new Field[8]; Vector v = new Vector(); if(table==null) table="%"; if(columnNamePattern==null) columnNamePattern="%"; else columnNamePattern=columnNamePattern.toLowerCase(); f[0] = new Field(connection,"TABLE_CAT",iVarcharOid,32); f[1] = new Field(connection,"TABLE_SCHEM",iVarcharOid,32); f[2] = new Field(connection,"TABLE_NAME",iVarcharOid,32); f[3] = new Field(connection,"COLUMN_NAME",iVarcharOid,32); f[4] = new Field(connection,"GRANTOR",iVarcharOid,32); f[5] = new Field(connection,"GRANTEE",iVarcharOid,32); f[6] = new Field(connection,"PRIVILEGE",iVarcharOid,32); f[7] = new Field(connection,"IS_GRANTABLE",iVarcharOid,32); // This is taken direct from the psql source java.sql.ResultSet r = connection.ExecSQL("SELECT relname, relacl FROM pg_class, pg_user WHERE ( relkind = 'r' OR relkind = 'i') and relname !~ '^pg_' and relname !~ '^xin[vx][0-9]+' and usesysid = relowner and relname like '"+table.toLowerCase()+"' ORDER BY relname"); while(r.next()) { byte[][] tuple = new byte[8][0]; tuple[0] = tuple[1]= "".getBytes(); DriverManager.println("relname=\""+r.getString(1)+"\" relacl=\""+r.getString(2)+"\""); // For now, don't add to the result as relacl needs to be processed. //v.addElement(tuple); } return new ResultSet(connection,f,v,"OK",1); } /** * Get a description of the access rights for each table available * in a catalog. * * <P>Only privileges matching the schema and table name * criteria are returned. They are ordered by TABLE_SCHEM, * TABLE_NAME, and PRIVILEGE. * * <P>Each privilige description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>GRANTOR</B> => grantor of access (may be null) * <LI><B>GRANTEE</B> String => grantee of access * <LI><B>PRIVILEGE</B> String => name of access (SELECT, * INSERT, UPDATE, REFRENCES, ...) * <LI><B>IS_GRANTABLE</B> String => "YES" if grantee is permitted * to grant to others; "NO" if not; null if unknown * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schemaPattern a schema name pattern; "" retrieves those * without a schema * @param tableNamePattern a table name pattern * @return ResultSet each row is a table privilege description * @see #getSearchStringEscape */ public java.sql.ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { // XXX-Not Implemented return null; } /** * Get a description of a table's optimal set of columns that * uniquely identifies a row. They are ordered by SCOPE. * * <P>Each column description has the following columns: * <OL> * <LI><B>SCOPE</B> short => actual scope of result * <UL> * <LI> bestRowTemporary - very temporary, while using row * <LI> bestRowTransaction - valid for remainder of current transaction * <LI> bestRowSession - valid for remainder of current session * </UL> * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>DATA_TYPE</B> short => SQL data type from java.sql.Types * <LI><B>TYPE_NAME</B> String => Data source dependent type name * <LI><B>COLUMN_SIZE</B> int => precision * <LI><B>BUFFER_LENGTH</B> int => not used * <LI><B>DECIMAL_DIGITS</B> short => scale * <LI><B>PSEUDO_COLUMN</B> short => is this a pseudo column * like an Oracle ROWID * <UL> * <LI> bestRowUnknown - may or may not be pseudo column * <LI> bestRowNotPseudo - is NOT a pseudo column * <LI> bestRowPseudo - is a pseudo column * </UL> * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name; "" retrieves those without a schema * @param table a table name * @param scope the scope of interest; use same values as SCOPE * @param nullable include columns that are nullable? * @return ResultSet each row is a column description */ // Implementation note: This is required for Borland's JBuilder to work public java.sql.ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) throws SQLException { // for now, this returns an empty result set. Field f[] = new Field[8]; ResultSet r; // ResultSet for the SQL query that we need to do Vector v = new Vector(); // The new ResultSet tuple stuff f[0] = new Field(connection, "SCOPE", iInt2Oid, 2); f[1] = new Field(connection, "COLUMN_NAME", iVarcharOid, 32); f[2] = new Field(connection, "DATA_TYPE", iInt2Oid, 2); f[3] = new Field(connection, "TYPE_NAME", iVarcharOid, 32); f[4] = new Field(connection, "COLUMN_SIZE", iInt4Oid, 4); f[5] = new Field(connection, "BUFFER_LENGTH", iInt4Oid, 4); f[6] = new Field(connection, "DECIMAL_DIGITS", iInt2Oid, 2); f[7] = new Field(connection, "PSEUDO_COLUMN", iInt2Oid, 2); return new ResultSet(connection, f, v, "OK", 1); } /** * Get a description of a table's columns that are automatically * updated when any value in a row is updated. They are * unordered. * * <P>Each column description has the following columns: * <OL> * <LI><B>SCOPE</B> short => is not used * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>DATA_TYPE</B> short => SQL data type from java.sql.Types * <LI><B>TYPE_NAME</B> String => Data source dependent type name * <LI><B>COLUMN_SIZE</B> int => precision * <LI><B>BUFFER_LENGTH</B> int => length of column value in bytes * <LI><B>DECIMAL_DIGITS</B> short => scale * <LI><B>PSEUDO_COLUMN</B> short => is this a pseudo column * like an Oracle ROWID * <UL> * <LI> versionColumnUnknown - may or may not be pseudo column * <LI> versionColumnNotPseudo - is NOT a pseudo column * <LI> versionColumnPseudo - is a pseudo column * </UL> * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name; "" retrieves those without a schema * @param table a table name * @return ResultSet each row is a column description */ public java.sql.ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { // XXX-Not Implemented return null; } /** * Get a description of a table's primary key columns. They * are ordered by COLUMN_NAME. * * <P>Each column description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>KEY_SEQ</B> short => sequence number within primary key * <LI><B>PK_NAME</B> String => primary key name (may be null) * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name pattern; "" retrieves those * without a schema * @param table a table name * @return ResultSet each row is a primary key column description */ public java.sql.ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { return connection.createStatement().executeQuery("SELECT " + "'' as TABLE_CAT," + "'' AS TABLE_SCHEM," + "bc.relname AS TABLE_NAME," + "a.attname AS COLUMN_NAME," + "a.attnum as KEY_SEQ,"+ "ic.relname as PK_NAME " + " FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a" + " WHERE bc.relkind = 'r' " + // -- not indices " and upper(bc.relname) = upper('"+table+"')" + " and i.indrelid = bc.oid" + " and i.indexrelid = ic.oid" + " and ic.oid = a.attrelid" + " and i.indisprimary='t' " + " ORDER BY table_name, pk_name, key_seq" ); } /** * Get a description of the primary key columns that are * referenced by a table's foreign key columns (the primary keys * imported by a table). They are ordered by PKTABLE_CAT, * PKTABLE_SCHEM, PKTABLE_NAME, and KEY_SEQ. * * <P>Each primary key column description has the following columns: * <OL> * <LI><B>PKTABLE_CAT</B> String => primary key table catalog * being imported (may be null) * <LI><B>PKTABLE_SCHEM</B> String => primary key table schema * being imported (may be null) * <LI><B>PKTABLE_NAME</B> String => primary key table name * being imported * <LI><B>PKCOLUMN_NAME</B> String => primary key column name * being imported * <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null) * <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null) * <LI><B>FKTABLE_NAME</B> String => foreign key table name * <LI><B>FKCOLUMN_NAME</B> String => foreign key column name * <LI><B>KEY_SEQ</B> short => sequence number within foreign key * <LI><B>UPDATE_RULE</B> short => What happens to * foreign key when primary is updated: * <UL> * <LI> importedKeyCascade - change imported key to agree * with primary key update * <LI> importedKeyRestrict - do not allow update of primary * key if it has been imported * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been updated * </UL> * <LI><B>DELETE_RULE</B> short => What happens to * the foreign key when primary is deleted. * <UL> * <LI> importedKeyCascade - delete rows that import a deleted key * <LI> importedKeyRestrict - do not allow delete of primary * key if it has been imported * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been deleted * </UL> * <LI><B>FK_NAME</B> String => foreign key name (may be null) * <LI><B>PK_NAME</B> String => primary key name (may be null) * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name pattern; "" retrieves those * without a schema * @param table a table name * @return ResultSet each row is a primary key column description * @see #getExportedKeys */ public java.sql.ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { // XXX-Not Implemented return null; } /** * Get a description of a foreign key columns that reference a * table's primary key columns (the foreign keys exported by a * table). They are ordered by FKTABLE_CAT, FKTABLE_SCHEM, * FKTABLE_NAME, and KEY_SEQ. * * <P>Each foreign key column description has the following columns: * <OL> * <LI><B>PKTABLE_CAT</B> String => primary key table catalog (may be null) * <LI><B>PKTABLE_SCHEM</B> String => primary key table schema (may be null) * <LI><B>PKTABLE_NAME</B> String => primary key table name * <LI><B>PKCOLUMN_NAME</B> String => primary key column name * <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null) * being exported (may be null) * <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null) * being exported (may be null) * <LI><B>FKTABLE_NAME</B> String => foreign key table name * being exported * <LI><B>FKCOLUMN_NAME</B> String => foreign key column name * being exported * <LI><B>KEY_SEQ</B> short => sequence number within foreign key * <LI><B>UPDATE_RULE</B> short => What happens to * foreign key when primary is updated: * <UL> * <LI> importedKeyCascade - change imported key to agree * with primary key update * <LI> importedKeyRestrict - do not allow update of primary * key if it has been imported * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been updated * </UL> * <LI><B>DELETE_RULE</B> short => What happens to * the foreign key when primary is deleted. * <UL> * <LI> importedKeyCascade - delete rows that import a deleted key * <LI> importedKeyRestrict - do not allow delete of primary * key if it has been imported * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been deleted * </UL> * <LI><B>FK_NAME</B> String => foreign key identifier (may be null) * <LI><B>PK_NAME</B> String => primary key identifier (may be null) * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name pattern; "" retrieves those * without a schema * @param table a table name * @return ResultSet each row is a foreign key column description * @see #getImportedKeys */ public java.sql.ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { // XXX-Not Implemented return null; } /** * Get a description of the foreign key columns in the foreign key * table that reference the primary key columns of the primary key * table (describe how one table imports another's key.) This * should normally return a single foreign key/primary key pair * (most tables only import a foreign key from a table once.) They * are ordered by FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME, and * KEY_SEQ. * * <P>Each foreign key column description has the following columns: * <OL> * <LI><B>PKTABLE_CAT</B> String => primary key table catalog (may be null) * <LI><B>PKTABLE_SCHEM</B> String => primary key table schema (may be null) * <LI><B>PKTABLE_NAME</B> String => primary key table name * <LI><B>PKCOLUMN_NAME</B> String => primary key column name * <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null) * being exported (may be null) * <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null) * being exported (may be null) * <LI><B>FKTABLE_NAME</B> String => foreign key table name * being exported * <LI><B>FKCOLUMN_NAME</B> String => foreign key column name * being exported * <LI><B>KEY_SEQ</B> short => sequence number within foreign key * <LI><B>UPDATE_RULE</B> short => What happens to * foreign key when primary is updated: * <UL> * <LI> importedKeyCascade - change imported key to agree * with primary key update * <LI> importedKeyRestrict - do not allow update of primary * key if it has been imported * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been updated * </UL> * <LI><B>DELETE_RULE</B> short => What happens to * the foreign key when primary is deleted. * <UL> * <LI> importedKeyCascade - delete rows that import a deleted key * <LI> importedKeyRestrict - do not allow delete of primary * key if it has been imported * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been deleted * </UL> * <LI><B>FK_NAME</B> String => foreign key identifier (may be null) * <LI><B>PK_NAME</B> String => primary key identifier (may be null) * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name pattern; "" retrieves those * without a schema * @param table a table name * @return ResultSet each row is a foreign key column description * @see #getImportedKeys */ public java.sql.ResultSet getCrossReference(String primaryCatalog, String primarySchema, String primaryTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException { // XXX-Not Implemented return null; } /** * Get a description of all the standard SQL types supported by * this database. They are ordered by DATA_TYPE and then by how * closely the data type maps to the corresponding JDBC SQL type. * * <P>Each type description has the following columns: * <OL> * <LI><B>TYPE_NAME</B> String => Type name * <LI><B>DATA_TYPE</B> short => SQL data type from java.sql.Types * <LI><B>PRECISION</B> int => maximum precision * <LI><B>LITERAL_PREFIX</B> String => prefix used to quote a literal * (may be null) * <LI><B>LITERAL_SUFFIX</B> String => suffix used to quote a literal (may be null) * <LI><B>CREATE_PARAMS</B> String => parameters used in creating * the type (may be null) * <LI><B>NULLABLE</B> short => can you use NULL for this type? * <UL> * <LI> typeNoNulls - does not allow NULL values * <LI> typeNullable - allows NULL values * <LI> typeNullableUnknown - nullability unknown * </UL> * <LI><B>CASE_SENSITIVE</B> boolean=> is it case sensitive? * <LI><B>SEARCHABLE</B> short => can you use "WHERE" based on this type: * <UL> * <LI> typePredNone - No support * <LI> typePredChar - Only supported with WHERE .. LIKE * <LI> typePredBasic - Supported except for WHERE .. LIKE * <LI> typeSearchable - Supported for all WHERE .. * </UL> * <LI><B>UNSIGNED_ATTRIBUTE</B> boolean => is it unsigned? * <LI><B>FIXED_PREC_SCALE</B> boolean => can it be a money value? * <LI><B>AUTO_INCREMENT</B> boolean => can it be used for an * auto-increment value? * <LI><B>LOCAL_TYPE_NAME</B> String => localized version of type name * (may be null) * <LI><B>MINIMUM_SCALE</B> short => minimum scale supported * <LI><B>MAXIMUM_SCALE</B> short => maximum scale supported * <LI><B>SQL_DATA_TYPE</B> int => unused * <LI><B>SQL_DATETIME_SUB</B> int => unused * <LI><B>NUM_PREC_RADIX</B> int => usually 2 or 10 * </OL> * * @return ResultSet each row is a SQL type description */ public java.sql.ResultSet getTypeInfo() throws SQLException { java.sql.ResultSet rs = connection.ExecSQL("select typname from pg_type"); if(rs!=null) { Field f[] = new Field[18]; ResultSet r; // ResultSet for the SQL query that we need to do Vector v = new Vector(); // The new ResultSet tuple stuff f[0] = new Field(connection, "TYPE_NAME", iVarcharOid, 32); f[1] = new Field(connection, "DATA_TYPE", iInt2Oid, 2); f[2] = new Field(connection, "PRECISION", iInt4Oid, 4); f[3] = new Field(connection, "LITERAL_PREFIX", iVarcharOid, 32); f[4] = new Field(connection, "LITERAL_SUFFIX", iVarcharOid, 32); f[5] = new Field(connection, "CREATE_PARAMS", iVarcharOid, 32); f[6] = new Field(connection, "NULLABLE", iInt2Oid, 2); f[7] = new Field(connection, "CASE_SENSITIVE", iBoolOid, 1); f[8] = new Field(connection, "SEARCHABLE", iInt2Oid, 2); f[9] = new Field(connection, "UNSIGNED_ATTRIBUTE", iBoolOid, 1); f[10] = new Field(connection, "FIXED_PREC_SCALE", iBoolOid, 1); f[11] = new Field(connection, "AUTO_INCREMENT", iBoolOid, 1); f[12] = new Field(connection, "LOCAL_TYPE_NAME", iVarcharOid, 32); f[13] = new Field(connection, "MINIMUM_SCALE", iInt2Oid, 2); f[14] = new Field(connection, "MAXIMUM_SCALE", iInt2Oid, 2); f[15] = new Field(connection, "SQL_DATA_TYPE", iInt4Oid, 4); f[16] = new Field(connection, "SQL_DATETIME_SUB", iInt4Oid, 4); f[17] = new Field(connection, "NUM_PREC_RADIX", iInt4Oid, 4); // cache some results, this will keep memory useage down, and speed // things up a little. byte b9[] = "9".getBytes(); byte b10[] = "10".getBytes(); byte bf[] = "f".getBytes(); byte bnn[] = Integer.toString(typeNoNulls).getBytes(); byte bts[] = Integer.toString(typeSearchable).getBytes(); while(rs.next()) { byte[][] tuple = new byte[18][]; String typname=rs.getString(1); tuple[0] = typname.getBytes(); tuple[1] = Integer.toString(Field.getSQLType(typname)).getBytes(); tuple[2] = b9; // for now tuple[6] = bnn; // for now tuple[7] = bf; // false for now - not case sensitive tuple[8] = bts; tuple[9] = bf; // false for now - it's signed tuple[10] = bf; // false for now - must handle money tuple[11] = bf; // false for now - handle autoincrement // 12 - LOCAL_TYPE_NAME is null // 13 & 14 ? // 15 & 16 are unused so we return null tuple[17] = b10; // everything is base 10 v.addElement(tuple); } rs.close(); return new ResultSet(connection, f, v, "OK", 1); } return null; } /** * Get a description of a table's indices and statistics. They are * ordered by NON_UNIQUE, TYPE, INDEX_NAME, and ORDINAL_POSITION. * * <P>Each index column description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>NON_UNIQUE</B> boolean => Can index values be non-unique? * false when TYPE is tableIndexStatistic * <LI><B>INDEX_QUALIFIER</B> String => index catalog (may be null); * null when TYPE is tableIndexStatistic * <LI><B>INDEX_NAME</B> String => index name; null when TYPE is * tableIndexStatistic * <LI><B>TYPE</B> short => index type: * <UL> * <LI> tableIndexStatistic - this identifies table statistics that are * returned in conjuction with a table's index descriptions * <LI> tableIndexClustered - this is a clustered index * <LI> tableIndexHashed - this is a hashed index * <LI> tableIndexOther - this is some other style of index * </UL> * <LI><B>ORDINAL_POSITION</B> short => column sequence number * within index; zero when TYPE is tableIndexStatistic * <LI><B>COLUMN_NAME</B> String => column name; null when TYPE is * tableIndexStatistic * <LI><B>ASC_OR_DESC</B> String => column sort sequence, "A" => ascending * "D" => descending, may be null if sort sequence is not supported; * null when TYPE is tableIndexStatistic * <LI><B>CARDINALITY</B> int => When TYPE is tableIndexStatisic then * this is the number of rows in the table; otherwise it is the * number of unique values in the index. * <LI><B>PAGES</B> int => When TYPE is tableIndexStatisic then * this is the number of pages used for the table, otherwise it * is the number of pages used for the current index. * <LI><B>FILTER_CONDITION</B> String => Filter condition, if any. * (may be null) * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name pattern; "" retrieves those without a schema * @param table a table name * @param unique when true, return only indices for unique values; * when false, return indices regardless of whether unique or not * @param approximate when true, result is allowed to reflect approximate * or out of data values; when false, results are requested to be * accurate * @return ResultSet each row is an index column description */ // Implementation note: This is required for Borland's JBuilder to work public java.sql.ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { // for now, this returns an empty result set. Field f[] = new Field[13]; ResultSet r; // ResultSet for the SQL query that we need to do Vector v = new Vector(); // The new ResultSet tuple stuff f[0] = new Field(connection, "TABLE_CAT", iVarcharOid, 32); f[1] = new Field(connection, "TABLE_SCHEM", iVarcharOid, 32); f[2] = new Field(connection, "TABLE_NAME", iVarcharOid, 32); f[3] = new Field(connection, "NON_UNIQUE", iBoolOid, 1); f[4] = new Field(connection, "INDEX_QUALIFIER", iVarcharOid, 32); f[5] = new Field(connection, "INDEX_NAME", iVarcharOid, 32); f[6] = new Field(connection, "TYPE", iInt2Oid, 2); f[7] = new Field(connection, "ORDINAL_POSITION", iInt2Oid, 2); f[8] = new Field(connection, "COLUMN_NAME", iVarcharOid, 32); f[9] = new Field(connection, "ASC_OR_DESC", iVarcharOid, 32); f[10] = new Field(connection, "CARDINALITY", iInt4Oid, 4); f[11] = new Field(connection, "PAGES", iInt4Oid, 4); f[12] = new Field(connection, "FILTER_CONDITION", iVarcharOid, 32); return new ResultSet(connection, f, v, "OK", 1); } }
package org.broadinstitute.variant.variantcontext; import net.sf.samtools.util.StringUtil; import java.util.Arrays; import java.util.Collection; /** * Immutable representation of an allele * * Types of alleles: * * Ref: a t C g a // C is the reference base * * : a t G g a // C base is a G in some individuals * * : a t - g a // C base is deleted w.r.t. the reference * * : a t CAg a // A base is inserted w.r.t. the reference sequence * * In these cases, where are the alleles? * * SNP polymorphism of C/G -> { C , G } -> C is the reference allele * 1 base deletion of C -> { C , - } -> C is the reference allele * 1 base insertion of A -> { - ; A } -> Null is the reference allele * * Suppose I see a the following in the population: * * Ref: a t C g a // C is the reference base * : a t G g a // C base is a G in some individuals * : a t - g a // C base is deleted w.r.t. the reference * * How do I represent this? There are three segregating alleles: * * { C , G , - } * * Now suppose I have this more complex example: * * Ref: a t C g a // C is the reference base * : a t - g a * : a t - - a * : a t CAg a * * There are actually four segregating alleles: * * { C g , - g, - -, and CAg } over bases 2-4 * * However, the molecular equivalence explicitly listed above is usually discarded, so the actual * segregating alleles are: * * { C g, g, -, C a g } * * Critically, it should be possible to apply an allele to a reference sequence to create the * correct haplotype sequence: * * Allele + reference => haplotype * * For convenience, we are going to create Alleles where the GenomeLoc of the allele is stored outside of the * Allele object itself. So there's an idea of an A/C polymorphism independent of it's surrounding context. * * Given list of alleles it's possible to determine the "type" of the variation * * A / C @ loc => SNP with * - / A => INDEL * * If you know where allele is the reference, you can determine whether the variant is an insertion or deletion. * * Alelle also supports is concept of a NO_CALL allele. This Allele represents a haplotype that couldn't be * determined. This is usually represented by a '.' allele. * * Note that Alleles store all bases as bytes, in **UPPER CASE**. So 'atc' == 'ATC' from the perspective of an * Allele. * @author ebanks, depristo */ public class Allele implements Comparable<Allele> { private static final byte[] EMPTY_ALLELE_BASES = new byte[0]; private boolean isRef = false; private boolean isNoCall = false; private boolean isSymbolic = false; private byte[] bases = null; public final static String NO_CALL_STRING = "."; /** A generic static NO_CALL allele for use */ // no public way to create an allele protected Allele(byte[] bases, boolean isRef) { // null alleles are no longer allowed if ( wouldBeNullAllele(bases) ) { throw new IllegalArgumentException("Null alleles are not supported"); } // no-calls are represented as no bases if ( wouldBeNoCallAllele(bases) ) { this.bases = EMPTY_ALLELE_BASES; isNoCall = true; if ( isRef ) throw new IllegalArgumentException("Cannot tag a NoCall allele as the reference allele"); return; } if ( wouldBeSymbolicAllele(bases) ) { isSymbolic = true; if ( isRef ) throw new IllegalArgumentException("Cannot tag a symbolic allele as the reference allele"); } else { StringUtil.toUpperCase(bases); } this.isRef = isRef; this.bases = bases; if ( ! acceptableAlleleBases(bases) ) throw new IllegalArgumentException("Unexpected base in allele bases \'" + new String(bases)+"\'"); } protected Allele(String bases, boolean isRef) { this(bases.getBytes(), isRef); } /** * Creates a new allele based on the provided one. Ref state will be copied unless ignoreRefState is true * (in which case the returned allele will be non-Ref). * * This method is efficient because it can skip the validation of the bases (since the original allele was already validated) * * @param allele the allele from which to copy the bases * @param ignoreRefState should we ignore the reference state of the input allele and use the default ref state? */ protected Allele(final Allele allele, final boolean ignoreRefState) { this.bases = allele.bases; this.isRef = ignoreRefState ? false : allele.isRef; this.isNoCall = allele.isNoCall; this.isSymbolic = allele.isSymbolic; } private final static Allele REF_A = new Allele("A", true); private final static Allele ALT_A = new Allele("A", false); private final static Allele REF_C = new Allele("C", true); private final static Allele ALT_C = new Allele("C", false); private final static Allele REF_G = new Allele("G", true); private final static Allele ALT_G = new Allele("G", false); private final static Allele REF_T = new Allele("T", true); private final static Allele ALT_T = new Allele("T", false); private final static Allele REF_N = new Allele("N", true); private final static Allele ALT_N = new Allele("N", false); public final static Allele NO_CALL = new Allele(NO_CALL_STRING, false); // creation routines public static Allele create(byte[] bases, boolean isRef) { if ( bases == null ) throw new IllegalArgumentException("create: the Allele base string cannot be null; use new Allele() or new Allele(\"\") to create a Null allele"); if ( bases.length == 1 ) { // optimization to return a static constant Allele for each single base object switch (bases[0]) { case '.': if ( isRef ) throw new IllegalArgumentException("Cannot tag a NoCall allele as the reference allele"); return NO_CALL; case 'A': case 'a' : return isRef ? REF_A : ALT_A; case 'C': case 'c' : return isRef ? REF_C : ALT_C; case 'G': case 'g' : return isRef ? REF_G : ALT_G; case 'T': case 't' : return isRef ? REF_T : ALT_T; case 'N': case 'n' : return isRef ? REF_N : ALT_N; default: throw new IllegalArgumentException("Illegal base [" + (char)bases[0] + "] seen in the allele"); } } else { return new Allele(bases, isRef); } } public static Allele create(byte base, boolean isRef) { return create( new byte[]{ base }, isRef); } public static Allele create(byte base) { return create( base, false ); } public static Allele extend(Allele left, byte[] right) { if (left.isSymbolic()) throw new IllegalArgumentException("Cannot extend a symbolic allele"); byte[] bases = new byte[left.length() + right.length]; System.arraycopy(left.getBases(), 0, bases, 0, left.length()); System.arraycopy(right, 0, bases, left.length(), right.length); return create(bases, left.isReference()); } /** * @param bases bases representing an allele * @return true if the bases represent the null allele */ public static boolean wouldBeNullAllele(byte[] bases) { return (bases.length == 1 && bases[0] == '-') || bases.length == 0; } /** * @param bases bases representing an allele * @return true if the bases represent the NO_CALL allele */ public static boolean wouldBeNoCallAllele(byte[] bases) { return bases.length == 1 && bases[0] == '.'; } /** * @param bases bases representing an allele * @return true if the bases represent a symbolic allele */ public static boolean wouldBeSymbolicAllele(byte[] bases) { if ( bases.length <= 2 ) return false; else { final String strBases = new String(bases); return (bases[0] == '<' && bases[bases.length-1] == '>') || (strBases.contains("[") || strBases.contains("]")); } } /** * @param bases bases representing an allele * @return true if the bases represent the well formatted allele */ public static boolean acceptableAlleleBases(String bases) { return acceptableAlleleBases(bases.getBytes(), true); } public static boolean acceptableAlleleBases(String bases, boolean allowNsAsAcceptable) { return acceptableAlleleBases(bases.getBytes(), allowNsAsAcceptable); } /** * @param bases bases representing an allele * @return true if the bases represent the well formatted allele */ public static boolean acceptableAlleleBases(byte[] bases) { return acceptableAlleleBases(bases, true); // default: N bases are acceptable } public static boolean acceptableAlleleBases(byte[] bases, boolean allowNsAsAcceptable) { if ( wouldBeNullAllele(bases) ) return false; if ( wouldBeNoCallAllele(bases) || wouldBeSymbolicAllele(bases) ) return true; for (byte base : bases ) { switch (base) { case 'A': case 'C': case 'G': case 'T': case 'a': case 'c': case 'g': case 't': break; case 'N' : case 'n' : if (allowNsAsAcceptable) break; else return false; default: return false; } } return true; } /** * @see Allele(byte[], boolean) * * @param bases bases representing an allele * @param isRef is this the reference allele? */ public static Allele create(String bases, boolean isRef) { return create(bases.getBytes(), isRef); } /** * Creates a non-Ref allele. @see Allele(byte[], boolean) for full information * * @param bases bases representing an allele */ public static Allele create(String bases) { return create(bases, false); } /** * Creates a non-Ref allele. @see Allele(byte[], boolean) for full information * * @param bases bases representing an allele */ public static Allele create(byte[] bases) { return create(bases, false); } /** * Creates a new allele based on the provided one. Ref state will be copied unless ignoreRefState is true * (in which case the returned allele will be non-Ref). * * This method is efficient because it can skip the validation of the bases (since the original allele was already validated) * * @param allele the allele from which to copy the bases * @param ignoreRefState should we ignore the reference state of the input allele and use the default ref state? */ public static Allele create(final Allele allele, final boolean ignoreRefState) { return new Allele(allele, ignoreRefState); } // accessor routines // Returns true if this is the NO_CALL allele public boolean isNoCall() { return isNoCall; } // Returns true if this is not the NO_CALL allele public boolean isCalled() { return ! isNoCall(); } // Returns true if this Allele is the reference allele public boolean isReference() { return isRef; } // Returns true if this Allele is not the reference allele public boolean isNonReference() { return ! isReference(); } // Returns true if this Allele is symbolic (i.e. no well-defined base sequence) public boolean isSymbolic() { return isSymbolic; } // Returns a nice string representation of this object public String toString() { return ( isNoCall() ? NO_CALL_STRING : getDisplayString() ) + (isReference() ? "*" : ""); } /** * Return the DNA bases segregating in this allele. Note this isn't reference polarized, * so the Null allele is represented by a vector of length 0 * * @return the segregating bases */ public byte[] getBases() { return isSymbolic ? EMPTY_ALLELE_BASES : bases; } /** * Return the DNA bases segregating in this allele in String format. * This is useful, because toString() adds a '*' to reference alleles and getBases() returns garbage when you call toString() on it. * * @return the segregating bases */ public String getBaseString() { return isNoCall() ? NO_CALL_STRING : new String(getBases()); } /** * Return the printed representation of this allele. * Same as getBaseString(), except for symbolic alleles. * For symbolic alleles, the base string is empty while the display string contains <TAG>. * * @return the allele string representation */ public String getDisplayString() { return new String(bases); } /** * Same as #getDisplayString() but returns the result as byte[]. * * Slightly faster then getDisplayString() * * @return the allele string representation */ public byte[] getDisplayBases() { return bases; } /** * @param other the other allele * * @return true if these alleles are equal */ public boolean equals(Object other) { return ( ! (other instanceof Allele) ? false : equals((Allele)other, false) ); } /** * @return hash code */ public int hashCode() { int hash = 1; for (int i = 0; i < bases.length; i++) hash += (i+1) * bases[i]; return hash; } /** * Returns true if this and other are equal. If ignoreRefState is true, then doesn't require both alleles has the * same ref tag * * @param other allele to compare to * @param ignoreRefState if true, ignore ref state in comparison * @return true if this and other are equal */ public boolean equals(Allele other, boolean ignoreRefState) { return this == other || (isRef == other.isRef || ignoreRefState) && isNoCall == other.isNoCall && (bases == other.bases || Arrays.equals(bases, other.bases)); } /** * @param test bases to test against * * @return true if this Allele contains the same bases as test, regardless of its reference status; handles Null and NO_CALL alleles */ public boolean basesMatch(byte[] test) { return !isSymbolic && (bases == test || Arrays.equals(bases, test)); } /** * @param test bases to test against * * @return true if this Allele contains the same bases as test, regardless of its reference status; handles Null and NO_CALL alleles */ public boolean basesMatch(String test) { return basesMatch(test.toUpperCase().getBytes()); } /** * @param test allele to test against * * @return true if this Allele contains the same bases as test, regardless of its reference status; handles Null and NO_CALL alleles */ public boolean basesMatch(Allele test) { return basesMatch(test.getBases()); } /** * @return the length of this allele. Null and NO_CALL alleles have 0 length. */ public int length() { return isSymbolic ? 0 : bases.length; } // useful static functions public static Allele getMatchingAllele(Collection<Allele> allAlleles, byte[] alleleBases) { for ( Allele a : allAlleles ) { if ( a.basesMatch(alleleBases) ) { return a; } } if ( wouldBeNoCallAllele(alleleBases) ) return NO_CALL; else return null; // couldn't find anything } public int compareTo(Allele other) { if ( isReference() && other.isNonReference() ) return -1; else if ( isNonReference() && other.isReference() ) return 1; else return getBaseString().compareTo(other.getBaseString()); // todo -- potential performance issue } public static boolean oneIsPrefixOfOther(Allele a1, Allele a2) { if ( a2.length() >= a1.length() ) return firstIsPrefixOfSecond(a1, a2); else return firstIsPrefixOfSecond(a2, a1); } private static boolean firstIsPrefixOfSecond(Allele a1, Allele a2) { String a1String = a1.getBaseString(); return a2.getBaseString().substring(0, a1String.length()).equals(a1String); } }