text:
package org.kaazing.gateway.bridge;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.kaazing.gateway.bridge.XoaEvent.XoaEventKind;
import org.kaazing.gateway.client.transport.AuthenticateEvent;
import org.kaazing.gateway.client.transport.BridgeDelegate;
import org.kaazing.gateway.client.transport.CloseEvent;
import org.kaazing.gateway.client.transport.ErrorEvent;
import org.kaazing.gateway.client.transport.LoadEvent;
import org.kaazing.gateway.client.transport.MessageEvent;
import org.kaazing.gateway.client.transport.OpenEvent;
import org.kaazing.gateway.client.transport.ProgressEvent;
import org.kaazing.gateway.client.transport.ReadyStateChangedEvent;
import org.kaazing.gateway.client.transport.RedirectEvent;
import org.kaazing.gateway.client.transport.http.HttpRequestDelegate;
import org.kaazing.gateway.client.transport.http.HttpRequestDelegateFactory;
import org.kaazing.gateway.client.transport.http.HttpRequestDelegateImpl;
import org.kaazing.gateway.client.transport.http.HttpRequestDelegateListener;
import org.kaazing.gateway.client.transport.ws.WebSocketDelegate;
import org.kaazing.gateway.client.transport.ws.WebSocketDelegateFactory;
import org.kaazing.gateway.client.transport.ws.WebSocketDelegateImpl;
import org.kaazing.gateway.client.transport.ws.WebSocketDelegateListener;

public class CrossOriginProxy extends PropertyChangeSupport implements XoaEventListener {
    private static final String CLASS_NAME = CrossOriginProxy.class.getName();

    static final Logger LOG = Logger.getLogger(CLASS_NAME);

    private static final String SOA_MESSAGE = "soaMessage";
    private static final String XOP_MESSAGE = "xopMessage";
    private static final String OBJECT_TYPE_HTTPREQUEST = "HTTPREQUEST";
    private static final String OBJECT_TYPE_WEBSOCKET = "WEBSOCKET";
    private static final String[] EMPTY_ARGS = new String[] {};
    private static final long serialVersionUID = -3694699522384518136L;

    private XoaEventProcessor xoaEventProcessor = new XoaEventProcessor(this);
    private Map<Integer, BridgeDelegate> xoaObjectMap = new ConcurrentHashMap<Integer, BridgeDelegate>();

    private boolean soaValidated = false;
    private boolean rejectFurtherMessages = false;

    private String xOrigin = null;

    WebSocketDelegateFactory WEB_SOCKET_DELEGATE_FACTORY = new WebSocketDelegateFactory() {
        @Override
        public WebSocketDelegate createWebSocketDelegate(URI xoaUrl, URI originUrl, String wsProtocols) {
            return new WebSocketDelegateImpl(xoaUrl, originUrl, wsProtocols == null ? null : wsProtocols.split(","), 0);
        }
    };

    HttpRequestDelegateFactory HTTP_REQUEST_DELEGATE_FACTORY = new HttpRequestDelegateFactory() {
        @Override
        public HttpRequestDelegate createHttpRequestDelegate() {
            return new HttpRequestDelegateImpl();
        }
    };

    public CrossOriginProxy() {
        super("null");
        LOG.entering(CLASS_NAME, "<init>");

        this.addPropertyChangeListener(SOA_MESSAGE, new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                LOG.entering(CLASS_NAME, "propertyChange");

                /**
                 * Process an event from Source Origin to WebSocket or HttpRequest delegates
                 * @param event
                 */
                Object[] eventParts = (Object[])evt.getNewValue();
                if (eventParts == null) {
                    LOG.severe("Event value is null");
                    return;
                }
                else if (eventParts.length == 0) {
                    LOG.severe("Event value has no parameters");
                    return;
                }

                Integer handlerId = (Integer)eventParts[0];

                // if at first message we do not validate the same origin - it may be an attack
                // so prevent further messages from getting processed at all
                if (rejectFurtherMessages) {
                    dispatchEvent(XoaEvent.createErrorEvent(handlerId));
                    return;
                }

                if (!soaValidated) {
                    if (!validateSameOrigin((String[]) eventParts[2])) {
                        rejectFurtherMessages = true;
                        dispatchEvent(XoaEvent.createErrorEvent(handlerId));
                        return;
                    }
                    soaValidated = true;
                }

                XoaEventKind eventName = XoaEventKind.getName((String) eventParts[1]);
                Object[] params = (Object[]) eventParts[2];

                XoaEvent event = new XoaEvent(handlerId, eventName, params);
                xoaEventProcessor.offer(event);
            }
        });
    }

    /**
     * Dispatch an event to Source Origin
     * @param event
     */
    private void dispatchEvent(XoaEvent event) {
        LOG.entering(CLASS_NAME, "dispatchEvent", event);

        try {
            Integer handlerId = event.getHandlerId();

            XoaEventKind eventKind = event.getEvent();
            if (LOG.isLoggable(Level.FINEST)) {
                LOG.finest("XOA --> SOA: " + handlerId  + " event: " + eventKind.name());
            }

            BridgeDelegate handler = xoaObjectMap.get(handlerId);
            if (handler == null) {
                if (LOG.isLoggable(Level.FINEST)) {
                    LOG.finest("No handler for handler id: " + handlerId);
                }
                return;
            }

            /* Allow only one bridge crossing per handler at a time */
            synchronized (handler) {
                // dispatch to SOA
                Object[] args = { handlerId, eventKind.toString(), event.getParams() };
                firePropertyChange(XOP_MESSAGE, null, args);
            }

        } catch (Exception e) {
            LOG.log(Level.FINE, "While dispatching event: "+e.getMessage(), e);
            throw new IllegalStateException("Unable to dispatch an event from the cross origin proxy", e);
        }

    }

    HttpRequestDelegate createHttpRequestDelegate(final Integer id) {
        LOG.entering(CLASS_NAME, "createHttpRequestDelegate", id);

        // There is a race here if processing is not serialized for a handler!
        HttpRequestDelegate reqDelegate = HTTP_REQUEST_DELEGATE_FACTORY.createHttpRequestDelegate();
        reqDelegate.setListener(new HttpRequestDelegateListener() {

            @Override
            public void opened(OpenEvent event) {
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.fine("HttpRequestDelegateListener opened: "+id);
                }
                dispatchEvent(new XoaEvent(id, XoaEventKind.OPEN, event.getParams()));
            }

            @Override
            public void readyStateChanged(ReadyStateChangedEvent event) {
                if (LOG.isLoggable(Level.FINER)) {
                    LOG.finer("HttpRequestDelegateListener readyStateChanged: "+id);
                }
                dispatchEvent(new XoaEvent(id, XoaEventKind.READYSTATECHANGE, event.getParams()));
            }

            @Override
            public void progressed(ProgressEvent progressEvent) {
                if (LOG.isLoggable(Level.FINEST)) {
                    LOG.finest("HttpRequestDelegateListener progressed: "+id);
                }
                ByteBuffer payload = progressEvent.getPayload();
                dispatchEvent(new XoaEvent(id, XoaEventKind.PROGRESS, new Object[] { payload }));
            }

            @Override
            public void loaded(LoadEvent event) {
                if (LOG.isLoggable(Level.FINER)) {
                    LOG.finer("HttpRequestDelegateListener loaded: "+id);
                }
                ByteBuffer responseBuffer = (ByteBuffer)event.getResponseBuffer();
                dispatchEvent(new XoaEvent(id, XoaEventKind.LOAD, new Object[] { responseBuffer }));
            }

            @Override
            public void closed(CloseEvent event) {
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.fine("HttpRequestDelegateListener closed: "+id);
                }
                try {
                    dispatchEvent(new XoaEvent(id, XoaEventKind.CLOSED, EMPTY_ARGS));
                }
                finally {
                    removeHandler(id);
                }
            }

            @Override
            public void errorOccurred(ErrorEvent event) {
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.fine("HttpRequestDelegateListener errorOccurred");
                }
                try {
                    dispatchEvent(XoaEvent.createErrorEvent(id));
                }
                finally {
                    removeHandler(id);
                }
            }
        });

        return reqDelegate;
    }

    private WebSocketDelegate createWebSocketDelegate(final Integer id, String xoaUrlStr, String wsProtocols) {
        LOG.entering(CLASS_NAME, "createWebSocketDelegate", id);
        URI originUrl;
        try {
            // add version string
            xoaUrlStr += ((xoaUrlStr.indexOf("?") == -1) ? "?" : "&") + ".kv=10.05";

            URI xoaUrl = new URI(xoaUrlStr);
            originUrl = new URI(xOrigin);

            WebSocketDelegate wsDelegate = WEB_SOCKET_DELEGATE_FACTORY.createWebSocketDelegate(xoaUrl, originUrl, wsProtocols);
            wsDelegate.setListener(new WebSocketDelegateListener() {

                @Override
                public void authenticationRequested(AuthenticateEvent authenticateEvent) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("WebSocketDelegateListener authenticationRequested: "+id);
                    }
                    String authenticate = authenticateEvent.getChallenge();
                    dispatchEvent(new XoaEvent(id, XoaEventKind.AUTHENTICATE, new String[] { authenticate }));
                }

                @Override
                public void opened(OpenEvent event) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("WebSocketDelegateListener opened: "+id);
                    }
                    String protocol = event.getProtocol();
                    dispatchEvent(new XoaEvent(id, XoaEventKind.OPEN, new String[] { protocol }));
                }

                @Override
                public void redirected(RedirectEvent redirectEvent) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("WebSocketDelegateListener redirected: "+id);
                    }
                    String location = redirectEvent.getLocation();
                    dispatchEvent(new XoaEvent(id, XoaEventKind.REDIRECT, new String[] { location }));
                }

                @Override
                public void messageReceived(MessageEvent messageEvent) {
                    if (LOG.isLoggable(Level.FINEST)) {
                        LOG.finest("WebSocketDelegateListener messageReceived: "+id);
                    }
                    ByteBuffer message = messageEvent.getData();
                    dispatchEvent(new XoaEvent(id, XoaEventKind.MESSAGE, new Object[] { message, messageEvent.getMessageType() }));
                }

                @Override
                public void closed(CloseEvent event) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("WebSocketDelegateListener closed: "+id);
                    }
                    try {
                        dispatchEvent(new XoaEvent(id, XoaEventKind.CLOSED, EMPTY_ARGS));
                    }
                    finally {
                        removeHandler(id);
                    }
                }

                @Override
                public void errorOccurred(ErrorEvent event) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("WebSocketDelegateListener errorOccurred: "+id);
                    }
                    try {
                        dispatchEvent(XoaEvent.createErrorEvent(id));
                    }
                    finally {
                        removeHandler(id);
                    }
                }
            });

            return wsDelegate;

        } catch (Exception e) {
            LOG.log(Level.FINE, "While processing the Java client bridge event queue: "+e.getMessage(), e);
            throw new RuntimeException("While processing the Java client bridge event queue: " + e);
        }
    }

    protected URL getCallerUrl() {
        return this.getClass().getResource("ValidateOrigin.class");
    }

    private boolean validateSameOrigin(String[] params) {
        LOG.entering(CLASS_NAME, "validateSameOrigin", (Object) params);

        try {
            Class<?> validationClass = this.getClass().getClassLoader().loadClass("org.kaazing.gateway.bridge.ValidateOrigin");
            int modifiers = validationClass.getModifiers();
            if (Modifier.isFinal(modifiers) && Modifier.isPrivate(modifiers)) {
                LOG.finest("Invalid modifiers");
                return false;
            }

            URL callerUrl = getCallerUrl();

            // jar:http://localhost:8000/demo/stomp.jar!/org/kaazing/gateway/bridge/ValidateOrigin.class
            String origin = callerUrl.toString();
            LOG.finest("Caller origin: " + origin);

            if (origin.startsWith("jar:")) {
                // URL like jar:http://www.foo.com/bar/baz.jar!/COM/foo/Quux.class
                origin = origin.substring(4, origin.indexOf("!"));
                URI originUri = new URI(origin);
                if (originUri.getScheme().equals("file")) {
                    origin = originUri.getScheme() + "://" + originUri.getAuthority();
                }
                else {
                    origin = originUri.getScheme() + "://" + getCanonicalHostPort(originUri);
                }
            }

            if (origin.startsWith("http:") || origin.startsWith("https:")) {
                // URL like [scheme:][//authority][path][?query][#fragment]
                URI originUri = new URI(origin);
                xOrigin = originUri.getScheme() + "://" + getCanonicalHostPort(originUri);
            }
            else if (origin.startsWith("file:") ||
                     origin.startsWith("bundleresource:") ||   // Felix/Equinox
                     origin.startsWith("bundle:") ||           // Felix/Equinox
                     origin.startsWith("code-source:") ||      // OC4J
                     origin.startsWith("zip:") ||              // WebLogic
                     origin.startsWith("vfszip:") ||           // JBoss5
                     origin.startsWith("vfs:") ||              // JBoss6
                     origin.startsWith("vfsfile:") ||          // JBoss6
                     origin.startsWith("wsjar:")) {            // WebSphere
                try {
                    this.getClass().getClassLoader().getParent();
                    URI targetURI = new URI(params[1]);
                    xOrigin = "privileged://" + getCanonicalHostPort(targetURI);
                } catch (Exception e) {
                    LOG.log(Level.FINE, "Unable to determine source origin: "+e.getMessage(), e);
                    xOrigin = "null";
                }
            }
            else {
                LOG.severe("Unable to locate the origin of the parent class loader");
                throw new IllegalArgumentException("Unable to locate the origin of the parent class loader");
            }
            LOG.finest("Bridge: xOrigin: " + xOrigin);
        } catch (Exception e) {
            LOG.log(Level.FINE, "Unable to locate the origin validation class: "+e.getMessage(), e);
            return false;
        }

        // Start the event handler thread that processes all messages from the
        // same origin code
        xoaEventProcessor.start();
        return true;
    }

    private String getCanonicalHostPort(URI uri) {
        int port = uri.getPort();
        if (port == -1) {
            String scheme = uri.getScheme();
            if (scheme.equals("https") || scheme.equals("wss") || scheme.equals("wse+ssl")) {
                port = 443;
            }
            else {
                port = 80;
            }
        }
        return uri.getHost()+":"+port;
    }

    private void removeHandler(Integer handlerId) {
        if (xoaObjectMap.remove(handlerId) != null) {
            LOG.fine("Removed handler: "+handlerId);

            // If no more handlers are available in the object map, then stop the
            // event handler thread.
            if (xoaObjectMap.size() == 0) {
                LOG.fine("Stopping xoaEventProcessor");
                xoaEventProcessor.stop();
            }
        }
    }

    @Override
    public void handleEvent(XoaEvent ev) {
        LOG.entering(CLASS_NAME, "handleEvent", ev);

        if (ev.getEvent() == XoaEventKind.CREATE) {
            try {
                processCreateEvent(ev);
            } catch (Exception e) {
                LOG.log(Level.SEVERE, "While processing create event: "+e.getMessage(), e);
                throw new RuntimeException("While processing create event: "+e);
            }
        }
        else {
            Integer handlerId = ev.getHandlerId();
            BridgeDelegate delegate = xoaObjectMap.get(handlerId);

            if (delegate == null) {
                throw new IllegalArgumentException("Unable to locate delegate: " + handlerId);
            }
            else if (delegate instanceof WebSocketDelegate) {
                processEvent((WebSocketDelegate)delegate, ev);
            }
            else if (delegate instanceof HttpRequestDelegate) {
                processEvent((HttpRequestDelegate)delegate, ev);
            }
            else {
                String reason = "Unknown delegate: "+handlerId+" type: "+delegate.getClass().getName();
                LOG.severe(reason);
                throw new IllegalArgumentException(reason);
            }
        }
    }

    private void processCreateEvent(XoaEvent ev) throws Exception {
        Object[] params = ev.getParams();
        final Integer handlerId = ev.getHandlerId();
        String type = (String)params[0];

        if (type.equals(OBJECT_TYPE_WEBSOCKET)) {
            LOG.fine("Creating WebSocketDelegate: HandlerID: "+handlerId);

            String xoaUrlStr = (String) params[1];
            String wsProtocols = (params.length > 3) ? (String)params[2] : null;

            WebSocketDelegate wsDelegate = createWebSocketDelegate(handlerId, xoaUrlStr, wsProtocols == null? null: wsProtocols);
            xoaObjectMap.put(handlerId, wsDelegate);

            wsDelegate.processOpen();
        }
        else if (type.equals(OBJECT_TYPE_HTTPREQUEST)) {
            LOG.fine("Creating HttpRequestDelegate: HandlerID: "+handlerId);

            String xoaUrlStr = (String) params[1];
            String method = (String) params[2];
            String asyncText = (String) params[3];
            boolean async = asyncText.equals("Y");

            // add version string
            LOG.finest("xoaUrlStr = " + xoaUrlStr);
            xoaUrlStr += ((xoaUrlStr.indexOf("?") == -1) ? "?" : "&") + ".kv=10.05";

            validateUrl(xoaUrlStr);

            HttpRequestDelegate req = createHttpRequestDelegate(handlerId);
            xoaObjectMap.put(handlerId, req);

            req.processOpen(method, new URL(xoaUrlStr), xOrigin, async, 0);
        }
        else {
            LOG.severe("Unknown type " + type);
            throw new IllegalArgumentException("Unknown type : " + type + " passed to CrossOriginProxy");
        }
    }

    private void processEvent(WebSocketDelegate wsDelegate, XoaEvent ev) {
        LOG.entering(CLASS_NAME, "handleWebSocketEvent", ev);

        try {
            Object[] params = ev.getParams();

            switch (ev.getEvent()) {
            case AUTHORIZE:
                wsDelegate.processAuthorize((String) params[0]);
                break;

            case POSTMESSAGE:
                if (params[0] instanceof String) {
                    wsDelegate.processSend((String)params[0]);
                }
                else {
                    wsDelegate.processSend((ByteBuffer)params[0]);
                }
                break;

            case DISCONNECT:
                wsDelegate.processDisconnect();
                break;

            default:
                LOG.severe("Unknown event: "+ev.getEvent().toString());
                throw new IllegalArgumentException("Unknown event: "+ev.getEvent().toString());
            }
        }
        catch (IOException e) {
            LOG.severe(e.toString());
            throw new RuntimeException("While dispatching event "+ev.getEvent().name+" to WebsocketDelegate: " + e.getMessage(), e);
        }
    }

    private void processEvent(HttpRequestDelegate reqDelegate, XoaEvent ev) {
        LOG.entering(CLASS_NAME, "handleHttpRequestEvent", ev);

        try {
            Object[] params = ev.getParams();

            switch (ev.getEvent()) {
            case SETREQUESTHEADER:
                reqDelegate.setRequestHeader((String) params[0], (String) params[1]);
                break;

            case SEND:
                reqDelegate.processSend((ByteBuffer) params[0]);
                break;

            case ABORT:
                try {
                    reqDelegate.processAbort();
                }
                finally {
                    removeHandler(ev.getHandlerId());
                }
                break;

            default:
                LOG.severe("Unknown event: "+ev.getEvent().toString());
                throw new IllegalArgumentException("Unknown event: "+ev.getEvent().toString());
            }
        }
        catch (Exception e) {
            LOG.severe(e.toString());
            throw new RuntimeException("While dispatching event "+ev.getEvent().name+" to HttpRequestDelegate: " + e.getMessage(), e);
        }
    }

    private void validateUrl(String xoaUrlStr) throws URISyntaxException {
        URI xoaUri = new URI(xoaUrlStr);
        String scheme = xoaUri.getScheme();
        if (!scheme.equals("http") && !scheme.equals("https")) {
            LOG.severe("Invalid scheme: "+scheme);
            throw new IllegalArgumentException("Invalid scheme: "+scheme);
        }
    }
}


text:
package org.apache.calcite.sql.type;

import org.apache.calcite.avatica.util.TimeUnit;
import org.apache.calcite.sql.SqlLiteral;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.util.DateString;
import org.apache.calcite.util.TimeString;
import org.apache.calcite.util.TimestampString;
import org.apache.calcite.util.Util;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;

import org.checkerframework.checker.nullness.qual.Nullable;

import java.math.BigDecimal;
import java.sql.Types;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Enumeration of the type names which can be used to construct a SQL type.
 * Rationale for this class's existence (instead of just using the standard
 * java.sql.Type ordinals):
 *
 *

 *
{@link java.sql.Types} does not include all SQL2003 data-types;
 *
SqlTypeName provides a type-safe enumeration;
 *
SqlTypeName provides a place to hang extra information such as whether
 * the type carries precision and scale.
 *

 */
public enum SqlTypeName {
  BOOLEAN(PrecScale.NO_NO, false, Types.BOOLEAN, SqlTypeFamily.BOOLEAN),
  TINYINT(PrecScale.NO_NO, false, Types.TINYINT, SqlTypeFamily.NUMERIC),
  SMALLINT(PrecScale.NO_NO, false, Types.SMALLINT, SqlTypeFamily.NUMERIC),
  INTEGER(PrecScale.NO_NO, false, Types.INTEGER, SqlTypeFamily.NUMERIC),
  BIGINT(PrecScale.NO_NO, false, Types.BIGINT, SqlTypeFamily.NUMERIC),
  DECIMAL(PrecScale.NO_NO | PrecScale.YES_NO | PrecScale.YES_YES, false,
      Types.DECIMAL, SqlTypeFamily.NUMERIC),
  FLOAT(PrecScale.NO_NO, false, Types.FLOAT, SqlTypeFamily.NUMERIC),
  REAL(PrecScale.NO_NO, false, Types.REAL, SqlTypeFamily.NUMERIC),
  DOUBLE(PrecScale.NO_NO, false, Types.DOUBLE, SqlTypeFamily.NUMERIC),
  DATE(PrecScale.NO_NO, false, Types.DATE, SqlTypeFamily.DATE),
  TIME(PrecScale.NO_NO | PrecScale.YES_NO, false, Types.TIME,
      SqlTypeFamily.TIME),
  TIME_WITH_LOCAL_TIME_ZONE(PrecScale.NO_NO | PrecScale.YES_NO, false, Types.OTHER,
      SqlTypeFamily.TIME),
  TIMESTAMP(PrecScale.NO_NO | PrecScale.YES_NO, false, Types.TIMESTAMP,
      SqlTypeFamily.TIMESTAMP),
  TIMESTAMP_WITH_LOCAL_TIME_ZONE(PrecScale.NO_NO | PrecScale.YES_NO, false, Types.OTHER,
      SqlTypeFamily.TIMESTAMP),
  INTERVAL_YEAR(PrecScale.NO_NO, false, Types.OTHER,
      SqlTypeFamily.INTERVAL_YEAR_MONTH),
  INTERVAL_YEAR_MONTH(PrecScale.NO_NO, false, Types.OTHER,
      SqlTypeFamily.INTERVAL_YEAR_MONTH),
  INTERVAL_MONTH(PrecScale.NO_NO, false, Types.OTHER,
      SqlTypeFamily.INTERVAL_YEAR_MONTH),
  INTERVAL_DAY(PrecScale.NO_NO | PrecScale.YES_NO | PrecScale.YES_YES,
      false, Types.OTHER, SqlTypeFamily.INTERVAL_DAY_TIME),
  INTERVAL_DAY_HOUR(PrecScale.NO_NO | PrecScale.YES_NO | PrecScale.YES_YES,
      false, Types.OTHER, SqlTypeFamily.INTERVAL_DAY_TIME),
  INTERVAL_DAY_MINUTE(PrecScale.NO_NO | PrecScale.YES_NO | PrecScale.YES_YES,
      false, Types.OTHER, SqlTypeFamily.INTERVAL_DAY_TIME),
  INTERVAL_DAY_SECOND(PrecScale.NO_NO | PrecScale.YES_NO | PrecScale.YES_YES,
      false, Types.OTHER, SqlTypeFamily.INTERVAL_DAY_TIME),
  INTERVAL_HOUR(PrecScale.NO_NO | PrecScale.YES_NO | PrecScale.YES_YES,
      false, Types.OTHER, SqlTypeFamily.INTERVAL_DAY_TIME),
  INTERVAL_HOUR_MINUTE(PrecScale.NO_NO | PrecScale.YES_NO | PrecScale.YES_YES,
      false, Types.OTHER, SqlTypeFamily.INTERVAL_DAY_TIME),
  INTERVAL_HOUR_SECOND(PrecScale.NO_NO | PrecScale.YES_NO | PrecScale.YES_YES,
      false, Types.OTHER, SqlTypeFamily.INTERVAL_DAY_TIME),
  INTERVAL_MINUTE(PrecScale.NO_NO | PrecScale.YES_NO | PrecScale.YES_YES,
      false, Types.OTHER, SqlTypeFamily.INTERVAL_DAY_TIME),
  INTERVAL_MINUTE_SECOND(PrecScale.NO_NO | PrecScale.YES_NO | PrecScale.YES_YES,
      false, Types.OTHER, SqlTypeFamily.INTERVAL_DAY_TIME),
  INTERVAL_SECOND(PrecScale.NO_NO | PrecScale.YES_NO | PrecScale.YES_YES,
      false, Types.OTHER, SqlTypeFamily.INTERVAL_DAY_TIME),
  CHAR(PrecScale.NO_NO | PrecScale.YES_NO, false, Types.CHAR,
      SqlTypeFamily.CHARACTER),
  VARCHAR(PrecScale.NO_NO | PrecScale.YES_NO, false, Types.VARCHAR,
      SqlTypeFamily.CHARACTER),
  BINARY(PrecScale.NO_NO | PrecScale.YES_NO, false, Types.BINARY,
      SqlTypeFamily.BINARY),
  VARBINARY(PrecScale.NO_NO | PrecScale.YES_NO, false, Types.VARBINARY,
      SqlTypeFamily.BINARY),
  NULL(PrecScale.NO_NO, true, Types.NULL, SqlTypeFamily.NULL),
  ANY(PrecScale.NO_NO | PrecScale.YES_NO | PrecScale.YES_YES, true,
      Types.JAVA_OBJECT, SqlTypeFamily.ANY),
  SYMBOL(PrecScale.NO_NO, true, Types.OTHER, null),
  MULTISET(PrecScale.NO_NO, false, Types.ARRAY, SqlTypeFamily.MULTISET),
  ARRAY(PrecScale.NO_NO, false, Types.ARRAY, SqlTypeFamily.ARRAY),
  MAP(PrecScale.NO_NO, false, Types.OTHER, SqlTypeFamily.MAP),
  DISTINCT(PrecScale.NO_NO, false, Types.DISTINCT, null),
  STRUCTURED(PrecScale.NO_NO, false, Types.STRUCT, null),
  ROW(PrecScale.NO_NO, false, Types.STRUCT, null),
  OTHER(PrecScale.NO_NO, false, Types.OTHER, null),
  CURSOR(PrecScale.NO_NO, false, ExtraSqlTypes.REF_CURSOR,
      SqlTypeFamily.CURSOR),
  COLUMN_LIST(PrecScale.NO_NO, false, Types.OTHER + 2,
      SqlTypeFamily.COLUMN_LIST),
  DYNAMIC_STAR(PrecScale.NO_NO | PrecScale.YES_NO | PrecScale.YES_YES, true,
      Types.JAVA_OBJECT, SqlTypeFamily.ANY),
  /** Spatial type. Though not standard, it is common to several DBs, so we
   * do not flag it 'special' (internal). */
  GEOMETRY(PrecScale.NO_NO, false, ExtraSqlTypes.GEOMETRY, SqlTypeFamily.GEO),
  SARG(PrecScale.NO_NO, true, Types.OTHER, SqlTypeFamily.ANY);

  public static final int MAX_DATETIME_PRECISION = 3;

  // Minimum and default interval precisions are  defined by SQL2003
  // Maximum interval precisions are implementation dependent,
  //  but must be at least the default value
  public static final int DEFAULT_INTERVAL_START_PRECISION = 2;
  public static final int DEFAULT_INTERVAL_FRACTIONAL_SECOND_PRECISION = 6;
  public static final int MIN_INTERVAL_START_PRECISION = 1;
  public static final int MIN_INTERVAL_FRACTIONAL_SECOND_PRECISION = 1;
  public static final int MAX_INTERVAL_START_PRECISION = 10;
  public static final int MAX_INTERVAL_FRACTIONAL_SECOND_PRECISION = 9;

  // Cached map of enum values
  private static final Map<String, SqlTypeName> VALUES_MAP =
      Util.enumConstants(SqlTypeName.class);

  // categorizations used by SqlTypeFamily definitions

  // you probably want to use JDK 1.5 support for treating enumeration
  // as collection instead; this is only here to support
  // SqlTypeFamily.ANY
  public static final List<SqlTypeName> ALL_TYPES =
      ImmutableList.of(
          BOOLEAN, INTEGER, VARCHAR, DATE, TIME, TIMESTAMP, NULL, DECIMAL,
          ANY, CHAR, BINARY, VARBINARY, TINYINT, SMALLINT, BIGINT, REAL,
          DOUBLE, SYMBOL, INTERVAL_YEAR, INTERVAL_YEAR_MONTH, INTERVAL_MONTH,
          INTERVAL_DAY, INTERVAL_DAY_HOUR, INTERVAL_DAY_MINUTE,
          INTERVAL_DAY_SECOND, INTERVAL_HOUR, INTERVAL_HOUR_MINUTE,
          INTERVAL_HOUR_SECOND, INTERVAL_MINUTE, INTERVAL_MINUTE_SECOND,
          INTERVAL_SECOND, TIME_WITH_LOCAL_TIME_ZONE, TIMESTAMP_WITH_LOCAL_TIME_ZONE,
          FLOAT, MULTISET, DISTINCT, STRUCTURED, ROW, CURSOR, COLUMN_LIST);

  public static final List<SqlTypeName> BOOLEAN_TYPES =
      ImmutableList.of(BOOLEAN);

  public static final List<SqlTypeName> BINARY_TYPES =
      ImmutableList.of(BINARY, VARBINARY);

  public static final List<SqlTypeName> INT_TYPES =
      ImmutableList.of(TINYINT, SMALLINT, INTEGER, BIGINT);

  public static final List<SqlTypeName> EXACT_TYPES =
      combine(INT_TYPES, ImmutableList.of(DECIMAL));

  public static final List<SqlTypeName> APPROX_TYPES =
      ImmutableList.of(FLOAT, REAL, DOUBLE);

  public static final List<SqlTypeName> NUMERIC_TYPES =
      combine(EXACT_TYPES, APPROX_TYPES);

  public static final List<SqlTypeName> FRACTIONAL_TYPES =
      combine(APPROX_TYPES, ImmutableList.of(DECIMAL));

  public static final List<SqlTypeName> CHAR_TYPES =
      ImmutableList.of(CHAR, VARCHAR);

  public static final List<SqlTypeName> STRING_TYPES =
      combine(CHAR_TYPES, BINARY_TYPES);

  public static final List<SqlTypeName> DATETIME_TYPES =
      ImmutableList.of(DATE, TIME, TIME_WITH_LOCAL_TIME_ZONE,
          TIMESTAMP, TIMESTAMP_WITH_LOCAL_TIME_ZONE);

  public static final Set<SqlTypeName> YEAR_INTERVAL_TYPES =
      Sets.immutableEnumSet(SqlTypeName.INTERVAL_YEAR,
          SqlTypeName.INTERVAL_YEAR_MONTH,
          SqlTypeName.INTERVAL_MONTH);

  public static final Set<SqlTypeName> DAY_INTERVAL_TYPES =
      Sets.immutableEnumSet(SqlTypeName.INTERVAL_DAY,
          SqlTypeName.INTERVAL_DAY_HOUR,
          SqlTypeName.INTERVAL_DAY_MINUTE,
          SqlTypeName.INTERVAL_DAY_SECOND,
          SqlTypeName.INTERVAL_HOUR,
          SqlTypeName.INTERVAL_HOUR_MINUTE,
          SqlTypeName.INTERVAL_HOUR_SECOND,
          SqlTypeName.INTERVAL_MINUTE,
          SqlTypeName.INTERVAL_MINUTE_SECOND,
          SqlTypeName.INTERVAL_SECOND);

  public static final Set<SqlTypeName> INTERVAL_TYPES =
      Sets.immutableEnumSet(
          Iterables.concat(YEAR_INTERVAL_TYPES, DAY_INTERVAL_TYPES));

  private static final Map<Integer, SqlTypeName> JDBC_TYPE_TO_NAME =
      ImmutableMap.<Integer, SqlTypeName>builder()
          .put(Types.TINYINT, TINYINT)
          .put(Types.SMALLINT, SMALLINT)
          .put(Types.BIGINT, BIGINT)
          .put(Types.INTEGER, INTEGER)
          .put(Types.NUMERIC, DECIMAL) // REVIEW
          .put(Types.DECIMAL, DECIMAL)

          .put(Types.FLOAT, FLOAT)
          .put(Types.REAL, REAL)
          .put(Types.DOUBLE, DOUBLE)

          .put(Types.CHAR, CHAR)
          .put(Types.VARCHAR, VARCHAR)

              // TODO: provide real support for these eventually
          .put(ExtraSqlTypes.NCHAR, CHAR)
          .put(ExtraSqlTypes.NVARCHAR, VARCHAR)

              // TODO: additional types not yet supported. See ExtraSqlTypes.
              // .put(Types.LONGVARCHAR, Longvarchar)
              // .put(Types.CLOB, Clob)
              // .put(Types.LONGVARBINARY, Longvarbinary)
              // .put(Types.BLOB, Blob)
              // .put(Types.LONGNVARCHAR, Longnvarchar)
              // .put(Types.NCLOB, Nclob)
              // .put(Types.ROWID, Rowid)
              // .put(Types.SQLXML, Sqlxml)

          .put(Types.BINARY, BINARY)
          .put(Types.VARBINARY, VARBINARY)

          .put(Types.DATE, DATE)
          .put(Types.TIME, TIME)
          .put(Types.TIMESTAMP, TIMESTAMP)
          .put(Types.BIT, BOOLEAN)
          .put(Types.BOOLEAN, BOOLEAN)
          .put(Types.DISTINCT, DISTINCT)
          .put(Types.STRUCT, STRUCTURED)
          .put(Types.ARRAY, ARRAY)
          .build();

  /**
   * Bitwise-or of flags indicating allowable precision/scale combinations.
   */
  private final int signatures;

  /**
   * Returns true if not of a "pure" standard sql type. "Inpure" types are
   * {@link #ANY}, {@link #NULL} and {@link #SYMBOL}
   */
  private final boolean special;
  private final int jdbcOrdinal;
  private final @Nullable SqlTypeFamily family;

  SqlTypeName(int signatures, boolean special, int jdbcType,
      @Nullable SqlTypeFamily family) {
    this.signatures = signatures;
    this.special = special;
    this.jdbcOrdinal = jdbcType;
    this.family = family;
  }

  /**
   * Looks up a type name from its name.
   *
   * @return Type name, or null if not found
   */
  public static @Nullable SqlTypeName get(String name) {
    if (false) {
      // The following code works OK, but the spurious exceptions are
      // annoying.
      try {
        return SqlTypeName.valueOf(name);
      } catch (IllegalArgumentException e) {
        return null;
      }
    }
    return VALUES_MAP.get(name);
  }

  public boolean allowsNoPrecNoScale() {
    return (signatures & PrecScale.NO_NO) != 0;
  }

  public boolean allowsPrecNoScale() {
    return (signatures & PrecScale.YES_NO) != 0;
  }

  public boolean allowsPrec() {
    return allowsPrecScale(true, true)
        || allowsPrecScale(true, false);
  }

  public boolean allowsScale() {
    return allowsPrecScale(true, true);
  }

  /**
   * Returns whether this type can be specified with a given combination of
   * precision and scale. For example,
   *
   *

   *
Varchar.allowsPrecScale(true, false) returns
   * true, because the VARCHAR type allows a precision parameter, as in
   * VARCHAR(10).

   *
Varchar.allowsPrecScale(true, true) returns
   * true, because the VARCHAR type does not allow a precision and a
   * scale parameter, as in VARCHAR(10, 4).

   *
allowsPrecScale(false, true) returns false
   * for every type.

   *

   *
   * @param precision Whether the precision/length field is part of the type
   *                  specification
   * @param scale     Whether the scale field is part of the type specification
   * @return Whether this combination of precision/scale is valid
   */
  public boolean allowsPrecScale(
      boolean precision,
      boolean scale) {
    int mask =
        precision ? (scale ? PrecScale.YES_YES : PrecScale.YES_NO)
            : (scale ? 0 : PrecScale.NO_NO);
    return (signatures & mask) != 0;
  }

  public boolean isSpecial() {
    return special;
  }

  /** Returns the ordinal from {@link java.sql.Types} corresponding to this
   * SqlTypeName. */
  public int getJdbcOrdinal() {
    return jdbcOrdinal;
  }

  private static List<SqlTypeName> combine(
      List<SqlTypeName> list0,
      List<SqlTypeName> list1) {
    return ImmutableList.<SqlTypeName>builder()
        .addAll(list0)
        .addAll(list1)
        .build();
  }

  /** Returns the default scale for this type if supported, otherwise -1 if
   * scale is either unsupported or must be specified explicitly. */
  public int getDefaultScale() {
    switch (this) {
    case DECIMAL:
      return 0;
    case INTERVAL_YEAR:
    case INTERVAL_YEAR_MONTH:
    case INTERVAL_MONTH:
    case INTERVAL_DAY:
    case INTERVAL_DAY_HOUR:
    case INTERVAL_DAY_MINUTE:
    case INTERVAL_DAY_SECOND:
    case INTERVAL_HOUR:
    case INTERVAL_HOUR_MINUTE:
    case INTERVAL_HOUR_SECOND:
    case INTERVAL_MINUTE:
    case INTERVAL_MINUTE_SECOND:
    case INTERVAL_SECOND:
      return DEFAULT_INTERVAL_FRACTIONAL_SECOND_PRECISION;
    default:
      return -1;
    }
  }

  /**
   * Gets the SqlTypeFamily containing this SqlTypeName.
   *
   * @return containing family, or null for none (SYMBOL, DISTINCT, STRUCTURED, ROW, OTHER)
   */
  public @Nullable SqlTypeFamily getFamily() {
    return family;
  }

  /**
   * Gets the SqlTypeName corresponding to a JDBC type.
   *
   * @param jdbcType the JDBC type of interest
   * @return corresponding SqlTypeName, or null if the type is not known
   */
  public static @Nullable SqlTypeName getNameForJdbcType(int jdbcType) {
    return JDBC_TYPE_TO_NAME.get(jdbcType);
  }

  /**
   * Returns the limit of this datatype. For example,
   *
   *

   *
Datatype limits

   *

   * Datatype
   * sign
   * limit
   * beyond
   * precision
   * scale
   * Returns
   *

   *

   * Integer
   * true
   * true
   * false
   * -1
   * -1
   * 2147483647 (2 ^ 31 -1 = MAXINT)
   *

   *

   * Integer
   * true
   * true
   * true
   * -1
   * -1
   * 2147483648 (2 ^ 31 = MAXINT + 1)
   *

   *

   * Integer
   * false
   * true
   * false
   * -1
   * -1
   * -2147483648 (-2 ^ 31 = MININT)
   *

   *

   * Boolean
   * true
   * true
   * false
   * -1
   * -1
   * TRUE
   *

   *

   * Varchar
   * true
   * true
   * false
   * 10
   * -1
   * 'ZZZZZZZZZZ'
   *

   *

   *
   * @param sign      If true, returns upper limit, otherwise lower limit
   * @param limit     If true, returns value at or near to overflow; otherwise
   *                  value at or near to underflow
   * @param beyond    If true, returns the value just beyond the limit,
   *                  otherwise the value at the limit
   * @param precision Precision, or -1 if not applicable
   * @param scale     Scale, or -1 if not applicable
   * @return Limit value
   */
  public @Nullable Object getLimit(
      boolean sign,
      Limit limit,
      boolean beyond,
      int precision,
      int scale) {
    assert allowsPrecScale(precision != -1, scale != -1) : this;
    if (limit == Limit.ZERO) {
      if (beyond) {
        return null;
      }
      sign = true;
    }
    Calendar calendar;

    switch (this) {
    case BOOLEAN:
      switch (limit) {
      case ZERO:
        return false;
      case UNDERFLOW:
        return null;
      case OVERFLOW:
        if (beyond || !sign) {
          return null;
        } else {
          return true;
        }
      default:
        throw Util.unexpected(limit);
      }

    case TINYINT:
      return getNumericLimit(2, 8, sign, limit, beyond);

    case SMALLINT:
      return getNumericLimit(2, 16, sign, limit, beyond);

    case INTEGER:
      return getNumericLimit(2, 32, sign, limit, beyond);

    case BIGINT:
      return getNumericLimit(2, 64, sign, limit, beyond);

    case DECIMAL:
      BigDecimal decimal =
          getNumericLimit(10, precision, sign, limit, beyond);
      if (decimal == null) {
        return null;
      }

      // Decimal values must fit into 64 bits. So, the maximum value of
      // a DECIMAL(19, 0) is 2^63 - 1, not 10^19 - 1.
      switch (limit) {
      case OVERFLOW:
        final BigDecimal other =
            (BigDecimal) BIGINT.getLimit(sign, limit, beyond, -1, -1);
        if (other != null && decimal.compareTo(other) == (sign ? 1 : -1)) {
          decimal = other;
        }
        break;
      default:
        break;
      }

      // Apply scale.
      if (scale == 0) {
        // do nothing
      } else if (scale > 0) {
        decimal = decimal.divide(BigDecimal.TEN.pow(scale));
      } else {
        decimal = decimal.multiply(BigDecimal.TEN.pow(-scale));
      }
      return decimal;

    case CHAR:
    case VARCHAR:
      if (!sign) {
        return null; // this type does not have negative values
      }
      StringBuilder buf = new StringBuilder();
      switch (limit) {
      case ZERO:
        break;
      case UNDERFLOW:
        if (beyond) {
          // There is no value between the empty string and the
          // smallest non-empty string.
          return null;
        }
        buf.append("a");
        break;
      case OVERFLOW:
        for (int i = 0; i < precision; ++i) {
          buf.append("Z");
        }
        if (beyond) {
          buf.append("Z");
        }
        break;
      default:
        break;
      }
      return buf.toString();

    case BINARY:
    case VARBINARY:
      if (!sign) {
        return null; // this type does not have negative values
      }
      byte[] bytes;
      switch (limit) {
      case ZERO:
        bytes = new byte[0];
        break;
      case UNDERFLOW:
        if (beyond) {
          // There is no value between the empty string and the
          // smallest value.
          return null;
        }
        bytes = new byte[]{0x00};
        break;
      case OVERFLOW:
        bytes = new byte[precision + (beyond ? 1 : 0)];
        Arrays.fill(bytes, (byte) 0xff);
        break;
      default:
        throw Util.unexpected(limit);
      }
      return bytes;

    case DATE:
      calendar = Util.calendar();
      switch (limit) {
      case ZERO:
        // The epoch.
        calendar.set(Calendar.YEAR, 1970);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        break;
      case UNDERFLOW:
        return null;
      case OVERFLOW:
        if (beyond) {
          // It is impossible to represent an invalid year as a date
          // literal. SQL dates are represented as 'yyyy-mm-dd', and
          // 1 <= yyyy <= 9999 is valid. There is no year 0: the year
          // before 1AD is 1BC, so SimpleDateFormat renders the day
          // before 0001-01-01 (AD) as 0001-12-31 (BC), which looks
          // like a valid date.
          return null;
        }

        // "SQL:2003 6.1 <data type> Access Rules 6" says that year is
        // between 1 and 9999, and days/months are the valid Gregorian
        // calendar values for these years.
        if (sign) {
          calendar.set(Calendar.YEAR, 9999);
          calendar.set(Calendar.MONTH, 11);
          calendar.set(Calendar.DAY_OF_MONTH, 31);
        } else {
          calendar.set(Calendar.YEAR, 1);
          calendar.set(Calendar.MONTH, 0);
          calendar.set(Calendar.DAY_OF_MONTH, 1);
        }
        break;
      default:
        break;
      }
      calendar.set(Calendar.HOUR_OF_DAY, 0);
      calendar.set(Calendar.MINUTE, 0);
      calendar.set(Calendar.SECOND, 0);
      return calendar;

    case TIME:
      if (!sign) {
        return null; // this type does not have negative values
      }
      if (beyond) {
        return null; // invalid values are impossible to represent
      }
      calendar = Util.calendar();
      switch (limit) {
      case ZERO:

        // The epoch.
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        break;
      case UNDERFLOW:
        return null;
      case OVERFLOW:
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        int millis =
            (precision >= 3) ? 999
                : ((precision == 2) ? 990 : ((precision == 1) ? 900 : 0));
        calendar.set(Calendar.MILLISECOND, millis);
        break;
      default:
        break;
      }
      return calendar;

    case TIMESTAMP:
      calendar = Util.calendar();
      switch (limit) {
      case ZERO:
        // The epoch.
        calendar.set(Calendar.YEAR, 1970);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        break;
      case UNDERFLOW:
        return null;
      case OVERFLOW:
        if (beyond) {
          // It is impossible to represent an invalid year as a date
          // literal. SQL dates are represented as 'yyyy-mm-dd', and
          // 1 <= yyyy <= 9999 is valid. There is no year 0: the year
          // before 1AD is 1BC, so SimpleDateFormat renders the day
          // before 0001-01-01 (AD) as 0001-12-31 (BC), which looks
          // like a valid date.
          return null;
        }

        // "SQL:2003 6.1 <data type> Access Rules 6" says that year is
        // between 1 and 9999, and days/months are the valid Gregorian
        // calendar values for these years.
        if (sign) {
          calendar.set(Calendar.YEAR, 9999);
          calendar.set(Calendar.MONTH, 11);
          calendar.set(Calendar.DAY_OF_MONTH, 31);
          calendar.set(Calendar.HOUR_OF_DAY, 23);
          calendar.set(Calendar.MINUTE, 59);
          calendar.set(Calendar.SECOND, 59);
          int millis =
              (precision >= 3) ? 999
                  : ((precision == 2) ? 990
                      : ((precision == 1) ? 900 : 0));
          calendar.set(Calendar.MILLISECOND, millis);
        } else {
          calendar.set(Calendar.YEAR, 1);
          calendar.set(Calendar.MONTH, 0);
          calendar.set(Calendar.DAY_OF_MONTH, 1);
          calendar.set(Calendar.HOUR_OF_DAY, 0);
          calendar.set(Calendar.MINUTE, 0);
          calendar.set(Calendar.SECOND, 0);
          calendar.set(Calendar.MILLISECOND, 0);
        }
        break;
      default:
        break;
      }
      return calendar;

    default:
      throw Util.unexpected(this);
    }
  }

  /**
   * Returns the minimum precision (or length) allowed for this type, or -1 if
   * precision/length are not applicable for this type.
   *
   * @return Minimum allowed precision
   */
  public int getMinPrecision() {
    switch (this) {
    case DECIMAL:
    case VARCHAR:
    case CHAR:
    case VARBINARY:
    case BINARY:
    case TIME:
    case TIME_WITH_LOCAL_TIME_ZONE:
    case TIMESTAMP:
    case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
      return 1;
    case INTERVAL_YEAR:
    case INTERVAL_YEAR_MONTH:
    case INTERVAL_MONTH:
    case INTERVAL_DAY:
    case INTERVAL_DAY_HOUR:
    case INTERVAL_DAY_MINUTE:
    case INTERVAL_DAY_SECOND:
    case INTERVAL_HOUR:
    case INTERVAL_HOUR_MINUTE:
    case INTERVAL_HOUR_SECOND:
    case INTERVAL_MINUTE:
    case INTERVAL_MINUTE_SECOND:
    case INTERVAL_SECOND:
      return MIN_INTERVAL_START_PRECISION;
    default:
      return -1;
    }
  }

  /**
   * Returns the minimum scale (or fractional second precision in the case of
   * intervals) allowed for this type, or -1 if precision/length are not
   * applicable for this type.
   *
   * @return Minimum allowed scale
   */
  public int getMinScale() {
    switch (this) {
    // TODO: Minimum numeric scale for decimal
    case INTERVAL_YEAR:
    case INTERVAL_YEAR_MONTH:
    case INTERVAL_MONTH:
    case INTERVAL_DAY:
    case INTERVAL_DAY_HOUR:
    case INTERVAL_DAY_MINUTE:
    case INTERVAL_DAY_SECOND:
    case INTERVAL_HOUR:
    case INTERVAL_HOUR_MINUTE:
    case INTERVAL_HOUR_SECOND:
    case INTERVAL_MINUTE:
    case INTERVAL_MINUTE_SECOND:
    case INTERVAL_SECOND:
      return MIN_INTERVAL_FRACTIONAL_SECOND_PRECISION;
    default:
      return -1;
    }
  }

  /** Returns {@code HOUR} for {@code HOUR TO SECOND} and
   * {@code HOUR}, {@code SECOND} for {@code SECOND}. */
  public TimeUnit getStartUnit() {
    switch (this) {
    case INTERVAL_YEAR:
    case INTERVAL_YEAR_MONTH:
      return TimeUnit.YEAR;
    case INTERVAL_MONTH:
      return TimeUnit.MONTH;
    case INTERVAL_DAY:
    case INTERVAL_DAY_HOUR:
    case INTERVAL_DAY_MINUTE:
    case INTERVAL_DAY_SECOND:
      return TimeUnit.DAY;
    case INTERVAL_HOUR:
    case INTERVAL_HOUR_MINUTE:
    case INTERVAL_HOUR_SECOND:
      return TimeUnit.HOUR;
    case INTERVAL_MINUTE:
    case INTERVAL_MINUTE_SECOND:
      return TimeUnit.MINUTE;
    case INTERVAL_SECOND:
      return TimeUnit.SECOND;
    default:
      throw new AssertionError(this);
    }
  }

  /** Returns {@code SECOND} for both {@code HOUR TO SECOND} and
   * {@code SECOND}. */
  public TimeUnit getEndUnit() {
    switch (this) {
    case INTERVAL_YEAR:
      return TimeUnit.YEAR;
    case INTERVAL_YEAR_MONTH:
    case INTERVAL_MONTH:
      return TimeUnit.MONTH;
    case INTERVAL_DAY:
      return TimeUnit.DAY;
    case INTERVAL_DAY_HOUR:
    case INTERVAL_HOUR:
      return TimeUnit.HOUR;
    case INTERVAL_DAY_MINUTE:
    case INTERVAL_HOUR_MINUTE:
    case INTERVAL_MINUTE:
      return TimeUnit.MINUTE;
    case INTERVAL_DAY_SECOND:
    case INTERVAL_HOUR_SECOND:
    case INTERVAL_MINUTE_SECOND:
    case INTERVAL_SECOND:
      return TimeUnit.SECOND;
    default:
      throw new AssertionError(this);
    }
  }

  public boolean isYearMonth() {
    switch (this) {
    case INTERVAL_YEAR:
    case INTERVAL_YEAR_MONTH:
    case INTERVAL_MONTH:
      return true;
    default:
      return false;
    }
  }

  /** Limit. */
  public enum Limit {
    ZERO, UNDERFLOW, OVERFLOW
  }

  private static @Nullable BigDecimal getNumericLimit(
      int radix,
      int exponent,
      boolean sign,
      Limit limit,
      boolean beyond) {
    switch (limit) {
    case OVERFLOW:

      // 2-based schemes run from -2^(N-1) to 2^(N-1)-1 e.g. -128 to +127
      // 10-based schemas run from -(10^N-1) to 10^N-1 e.g. -99 to +99
      final BigDecimal bigRadix = BigDecimal.valueOf(radix);
      if (radix == 2) {
        --exponent;
      }
      BigDecimal decimal = bigRadix.pow(exponent);
      if (sign || (radix != 2)) {
        decimal = decimal.subtract(BigDecimal.ONE);
      }
      if (beyond) {
        decimal = decimal.add(BigDecimal.ONE);
      }
      if (!sign) {
        decimal = decimal.negate();
      }
      return decimal;
    case UNDERFLOW:
      return beyond ? null
          : (sign ? BigDecimal.ONE : BigDecimal.ONE.negate());
    case ZERO:
      return BigDecimal.ZERO;
    default:
      throw Util.unexpected(limit);
    }
  }

  public SqlLiteral createLiteral(Object o, SqlParserPos pos) {
    switch (this) {
    case BOOLEAN:
      return SqlLiteral.createBoolean((Boolean) o, pos);
    case TINYINT:
    case SMALLINT:
    case INTEGER:
    case BIGINT:
    case DECIMAL:
      return SqlLiteral.createExactNumeric(o.toString(), pos);
    case VARCHAR:
    case CHAR:
      return SqlLiteral.createCharString((String) o, pos);
    case VARBINARY:
    case BINARY:
      return SqlLiteral.createBinaryString((byte[]) o, pos);
    case DATE:
      return SqlLiteral.createDate(o instanceof Calendar
          ? DateString.fromCalendarFields((Calendar) o)
          : (DateString) o, pos);
    case TIME:
      return SqlLiteral.createTime(o instanceof Calendar
          ? TimeString.fromCalendarFields((Calendar) o)
          : (TimeString) o, 0 /* todo */, pos);
    case TIMESTAMP:
      return SqlLiteral.createTimestamp(o instanceof Calendar
          ? TimestampString.fromCalendarFields((Calendar) o)
          : (TimestampString) o, 0 /* todo */, pos);
    default:
      throw Util.unexpected(this);
    }
  }

  /** Returns the name of this type. */
  public String getName() {
    return toString();
  }

  /**
   * Flags indicating precision/scale combinations.
   *
   *
Note: for intervals:
   *
   *

   *
precision = start (leading field) precision

   *
scale = fractional second precision

   *

   */
  private interface PrecScale {
    int NO_NO = 1;
    int YES_NO = 2;
    int YES_YES = 4;
  }
}

redpajama_set_name: RedPajamaGithub


text:
import React from "react";
import { Room } from "matrix-js-sdk/src/models/room";
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { User } from "matrix-js-sdk/src/models/user";
import { logger } from "matrix-js-sdk/src/logger";
import { EventType } from "matrix-js-sdk/src/@types/event";

import { MatrixClientPeg } from './MatrixClientPeg';
import MultiInviter, { CompletionStates } from './utils/MultiInviter';
import Modal from './Modal';
import { _t } from './languageHandler';
import InviteDialog from "./components/views/dialogs/InviteDialog";
import BaseAvatar from "./components/views/avatars/BaseAvatar";
import { mediaFromMxc } from "./customisations/Media";
import ErrorDialog from "./components/views/dialogs/ErrorDialog";
import { KIND_DM, KIND_INVITE } from "./components/views/dialogs/InviteDialogTypes";
import { Member } from "./utils/direct-messages";

export interface IInviteResult {
    states: CompletionStates;
    inviter: MultiInviter;
}

/**
 * Invites multiple addresses to a room
 * Simpler interface to utils/MultiInviter but with
 * no option to cancel.
 *
 * @param {string} roomId The ID of the room to invite to
 * @param {string[]} addresses Array of strings of addresses to invite. May be matrix IDs or 3pids.
 * @param {boolean} sendSharedHistoryKeys whether to share e2ee keys with the invitees if applicable.
 * @param {function} progressCallback optional callback, fired after each invite.
 * @returns {Promise} Promise
 */
export function inviteMultipleToRoom(
    roomId: string,
    addresses: string[],
    sendSharedHistoryKeys = false,
    progressCallback?: () => void,
): Promise<IInviteResult> {
    const inviter = new MultiInviter(roomId, progressCallback);
    return inviter.invite(addresses, undefined, sendSharedHistoryKeys)
        .then(states => Promise.resolve({ states, inviter }));
}

export function showStartChatInviteDialog(initialText = ""): void {
    // This dialog handles the room creation internally - we don't need to worry about it.
    Modal.createDialog(
        InviteDialog, { kind: KIND_DM, initialText },
        /*className=*/"mx_InviteDialog_flexWrapper", /*isPriority=*/false, /*isStatic=*/true,
    );
}

export function showRoomInviteDialog(roomId: string, initialText = ""): void {
    // This dialog handles the room creation internally - we don't need to worry about it.
    Modal.createDialog(
        InviteDialog, {
            kind: KIND_INVITE,
            initialText,
            roomId,
        },
        /*className=*/"mx_InviteDialog_flexWrapper", /*isPriority=*/false, /*isStatic=*/true,
    );
}

/**
 * Checks if the given MatrixEvent is a valid 3rd party user invite.
 * @param {MatrixEvent} event The event to check
 * @returns {boolean} True if valid, false otherwise
 */
export function isValid3pidInvite(event: MatrixEvent): boolean {
    if (!event || event.getType() !== EventType.RoomThirdPartyInvite) return false;

    // any events without these keys are not valid 3pid invites, so we ignore them
    const requiredKeys = ['key_validity_url', 'public_key', 'display_name'];
    if (requiredKeys.some(key => !event.getContent()[key])) {
        return false;
    }

    // Valid enough by our standards
    return true;
}

export function inviteUsersToRoom(
    roomId: string,
    userIds: string[],
    sendSharedHistoryKeys = false,
    progressCallback?: () => void,
): Promise<void> {
    return inviteMultipleToRoom(roomId, userIds, sendSharedHistoryKeys, progressCallback).then((result) => {
        const room = MatrixClientPeg.get().getRoom(roomId);
        showAnyInviteErrors(result.states, room, result.inviter);
    }).catch((err) => {
        logger.error(err.stack);
        Modal.createDialog(ErrorDialog, {
            title: _t("Failed to invite"),
            description: ((err && err.message) ? err.message : _t("Operation failed")),
        });
    });
}

export function showAnyInviteErrors(
    states: CompletionStates,
    room: Room,
    inviter: MultiInviter,
    userMap?: Map<string, Member>,
): boolean {
    // Show user any errors
    const failedUsers = Object.keys(states).filter(a => states[a] === 'error');
    if (failedUsers.length === 1 && inviter.fatal) {
        // Just get the first message because there was a fatal problem on the first
        // user. This usually means that no other users were attempted, making it
        // pointless for us to list who failed exactly.
        Modal.createDialog(ErrorDialog, {
            title: _t("Failed to invite users to %(roomName)s", { roomName: room.name }),
            description: inviter.getErrorText(failedUsers[0]),
        });
        return false;
    } else {
        const errorList = [];
        for (const addr of failedUsers) {
            if (states[addr] === "error") {
                const reason = inviter.getErrorText(addr);
                errorList.push(addr + ": " + reason);
            }
        }

        const cli = MatrixClientPeg.get();
        if (errorList.length > 0) {
            // React 16 doesn't let us use `errorList.join(<br />)` anymore, so this is our solution
            const description =

{ _t("We sent the others, but the below people couldn't be invited to <RoomName/>", {}, {
                    RoomName: () => { room.name },
                }) }

                    { failedUsers.map(addr => {
                        const user = userMap?.get(addr) || cli.getUser(addr);
                        const name = (user as Member).name || (user as User).rawDisplayName;
                        const avatarUrl = (user as Member).getMxcAvatarUrl?.() || (user as User).avatarUrl;
                        return

                                <BaseAvatar
                                    url={avatarUrl ? mediaFromMxc(avatarUrl).getSquareThumbnailHttp(24) : null}
                                    name={name}
                                    idName={user.userId}
                                    width={36}
                                    height={36}
                                />

                                { name }
                                { user.userId }

                                { inviter.getErrorText(addr) }

;
                    }) }

;

            Modal.createDialog(ErrorDialog, {
                title: _t("Some invites couldn't be sent"),
                description,
            });
            return false;
        }
    }

    return true;
}


text:
layout: default
description: Description of the oasisctl delete role command
title: Oasisctl Delete Role
---
# Oasisctl Delete Role

Delete a role the authenticated user has access to

## Synopsis

Delete a role the authenticated user has access to

```
oasisctl delete role [flags]
```

## Options

```
  -h, --help                     help for role
  -o, --organization-id string   Identifier of the organization
  -r, --role-id string           Identifier of the role
```

## Options inherited from parent commands

```
      --endpoint string   API endpoint of the ArangoDB Oasis (default "api.cloud.arangodb.com")
      --format string     Output format (table|json) (default "table")
      --token string      Token used to authenticate at ArangoDB Oasis
```

## See also

* [oasisctl delete](oasisctl-delete.html)	 - Delete resources


text:
describe('UnicodeMapper', function () {
    var str = '', map = {'!':'exclamation'};

    it('can translate a character into a word', function () {
        str = UnicodeMapper.translate('☃');
        expect(str).toEqual('snowman');
    });

    it('can clean a string', function () {
        str = UnicodeMapper.clean(' snowman   heart ');
        expect(str).toEqual('snowman heart');
    });

    it('can get the character for a word', function () {
        str = UnicodeMapper.getChar('snowman');
        expect(str).toEqual('☃');
    });

    it('can encode a string', function () {
        str = UnicodeMapper.encode('snowman heart');
        expect(str).toEqual('☃♥');
    });

    it('can decode a string', function () {
        str = UnicodeMapper.decode('☃♥');
        expect(str).toEqual('snowman heart');
    });

    it('can check if character is a punctuation', function () {
        str = UnicodeMapper.ispunct('!');
        expect(str).toEqual(true);
    });

    it('can set a map', function () {
        UnicodeMapper.setMap(map);
        expect(UnicodeMapper.getMap()).toEqual(map);
    });

    it('can get a map', function () {
        var newmap = UnicodeMapper.getMap();
        expect(newmap).toEqual(map);
    });

});


text:
import datetime

from django.core.urlresolvers import reverse  # noqa
from django import http
from django.utils import timezone

from mox import IsA  # noqa

from horizon.templatetags import sizeformat

from openstack_dashboard import api
from openstack_dashboard.test import helpers as test
from openstack_dashboard import usage

INDEX_URL = reverse('horizon:project:overview:index')

class UsageViewTests(test.BaseAdminViewTests):

    @test.create_stubs({api.nova: ('usage_list', 'tenant_absolute_limits', ),
                        api.keystone: ('tenant_list',),
                        api.network: ('tenant_floating_ip_list',)})
    def test_usage(self):
        now = timezone.now()
        usage_obj = api.nova.NovaUsage(self.usages.first())
        api.keystone.tenant_list(IsA(http.HttpRequest)) \
                    .AndReturn([self.tenants.list(), False])
        api.nova.usage_list(IsA(http.HttpRequest),
                            datetime.datetime(now.year,
                                              now.month,
                                              now.day, 0, 0, 0, 0),
                            datetime.datetime(now.year,
                                              now.month,
                                              now.day, 23, 59, 59, 0)) \
                                              .AndReturn([usage_obj])
        api.nova.tenant_absolute_limits(IsA(http.HttpRequest)) \
            .AndReturn(self.limits['absolute'])
        api.network.tenant_floating_ip_list(IsA(http.HttpRequest)) \
                           .AndReturn(self.floating_ips.list())
        self.mox.ReplayAll()

        res = self.client.get(reverse('horizon:admin:overview:index'))
        self.assertTemplateUsed(res, 'admin/overview/usage.html')
        self.assertTrue(isinstance(res.context['usage'], usage.GlobalUsage))
        self.assertContains(res,
                            'test_tenant'
                            '	'
                            '%s	'
                            '%s	'
                            '%s	'
                            '%.2f	'
                            '%.2f	' %
                            (usage_obj.vcpus,
                             usage_obj.disk_gb_hours,
                             sizeformat.mbformat(usage_obj.memory_mb),
                             usage_obj.vcpu_hours,
                             usage_obj.total_local_gb_usage))

    @test.create_stubs({api.nova: ('usage_list', 'tenant_absolute_limits', ),
                        api.keystone: ('tenant_list',),
                        api.network: ('tenant_floating_ip_list',)})
    def test_usage_csv(self):
        now = timezone.now()
        usage_obj = [api.nova.NovaUsage(u) for u in self.usages.list()]
        api.keystone.tenant_list(IsA(http.HttpRequest)) \
                    .AndReturn([self.tenants.list(), False])
        api.nova.usage_list(IsA(http.HttpRequest),
                            datetime.datetime(now.year,
                                              now.month,
                                              now.day, 0, 0, 0, 0),
                            datetime.datetime(now.year,
                                              now.month,
                                              now.day, 23, 59, 59, 0)) \
                                              .AndReturn(usage_obj)
        api.nova.tenant_absolute_limits(IsA(http.HttpRequest))\
            .AndReturn(self.limits['absolute'])
        api.network.tenant_floating_ip_list(IsA(http.HttpRequest)) \
                           .AndReturn(self.floating_ips.list())
        self.mox.ReplayAll()

        csv_url = reverse('horizon:admin:overview:index') + "?format=csv"
        res = self.client.get(csv_url)
        self.assertTemplateUsed(res, 'admin/overview/usage.csv')
        self.assertTrue(isinstance(res.context['usage'], usage.GlobalUsage))
        hdr = 'Project Name,VCPUs,Ram (MB),Disk (GB),Usage (Hours)'
        self.assertContains(res, '%s\r\n' % (hdr))
        for obj in usage_obj:
            row = u'{0},{1},{2},{3},{4:.2f}\r\n'.format(obj.project_name,
                                                        obj.vcpus,
                                                        obj.memory_mb,
                                                        obj.disk_gb_hours,
                                                        obj.vcpu_hours)
        self.assertContains(res, row)


text:
namespace Tests
{
    class TestGame : public NinjaParty::Game
    {
    public:
        TestGame(int screenWidth, int screenHeight)
			: NinjaParty::Game(screenWidth, screenHeight)
        {
        }

        void Update(float deltaSeconds)
        {
        }

        void Draw()
        {
			if(facebookManager.IsLoggedIn())
			   ClearScreen(NinjaParty::Color::CornflowerBlue);
			else
			   ClearScreen(NinjaParty::Color::Red);
        }

		void TouchBegan(void *touchHandle, int tapCount, int x, int y)
		{
			if(x < GetScreenWidth() / 2)
			{
				if(facebookManager.IsLoggedIn())
					facebookManager.RequestInfo();
				else
					facebookManager.Login();
			}
			else
			{
				if(facebookManager.IsLoggedIn())
					facebookManager.Logout();
				else
					facebookManager.Login();
			}
		}

		void FacebookLogin(bool success, const std::string &accessToken)
		{
			facebookManager.InjectLogin(success, accessToken);
		}

		void FacebookLogout()
		{
			facebookManager.InjectLogout();
		}

	private:
		NinjaParty::FacebookManager facebookManager;
    };
}


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateTunjangansTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('tunjangans', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string(' kd_absen');
			$table->string('kd_tunjangan');
			$table->integer('ttl_tun_kes');
			$table->integer('ttl_tun_makan');
			$table->integer('ttl_tun_transport');
			$table->integer ('ttl_tun');
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('tunjangans');
	}

}


text:
.class Lcom/google/common/collect/Synchronized$SynchronizedRandomAccessList;
.super Lcom/google/common/collect/Synchronized$SynchronizedList;
.source "Synchronized.java"

# interfaces
.implements Ljava/util/RandomAccess;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/google/common/collect/Synchronized;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "SynchronizedRandomAccessList"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "<E:",
        "Ljava/lang/Object;",
        ">",
        "Lcom/google/common/collect/Synchronized$SynchronizedList",
        "<TE;>;",
        "Ljava/util/RandomAccess;"
    }
.end annotation

# static fields
.field private static final serialVersionUID:J

# direct methods
.method constructor <init>(Ljava/util/List;Ljava/lang/Object;)V
    .locals 0
    .param p2, "mutex"    # Ljava/lang/Object;
        .annotation runtime Ljavax/annotation/Nullable;
        .end annotation
    .end param
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/util/List",
            "<TE;>;",
            "Ljava/lang/Object;",
            ")V"
        }
    .end annotation

    .prologue
    .line 400
    .local p0, "this":Lcom/google/common/collect/Synchronized$SynchronizedRandomAccessList;, "Lcom/google/common/collect/Synchronized$SynchronizedRandomAccessList<TE;>;"
    .local p1, "list":Ljava/util/List;, "Ljava/util/List<TE;>;"
    invoke-direct {p0, p1, p2}, Lcom/google/common/collect/Synchronized$SynchronizedList;-><init>(Ljava/util/List;Ljava/lang/Object;)V

    .line 401
    return-void
.end method


text:
//! \file

#ifndef TRITON_AARCH64CPU_HPP
#define TRITON_AARCH64CPU_HPP

#include <set>
#include <string>
#include <unordered_map>
#include <vector>

#include <triton/aarch64Specifications.hpp>
#include <triton/archEnums.hpp>
#include <triton/callbacks.hpp>
#include <triton/cpuInterface.hpp>
#include <triton/dllexport.hpp>
#include <triton/instruction.hpp>
#include <triton/memoryAccess.hpp>
#include <triton/register.hpp>
#include <triton/tritonTypes.hpp>

//! The Triton namespace
namespace triton {
/*!
 *  \addtogroup triton
 *  @{
 */

  //! The Architecture namespace
  namespace arch {
  /*!
   *  \ingroup triton
   *  \addtogroup arch
   *  @{
   */

    //! The ARM namespace
    namespace arm {
    /*!
     *  \ingroup arch
     *  \addtogroup arm
     *  @{
     */

      //! The aarch64 namespace
      namespace aarch64 {
      /*!
       *  \ingroup arm
       *  \addtogroup aarch64
       *  @{
       */

        //! \class AArch64Cpu
        /*! \brief This class is used to describe the ARM (64-bits) spec. */
        class AArch64Cpu : public CpuInterface, public AArch64Specifications {

          static const triton::arch::register_e pcId = triton::arch::ID_REG_AARCH64_PC;
          static const triton::arch::register_e spId = triton::arch::ID_REG_AARCH64_SP;

          private:
            //! Callbacks API
            triton::callbacks::Callbacks* callbacks;

            //! Exclusive memory tags. Each address in this std::set is tagged as exclusive.
            std::set<triton::uint64> exclusiveMemoryTags;

            //! Capstone context
            std::size_t handle;

            //! Copies a AArch64Cpu class.
            void copy(const AArch64Cpu& other);

            //! Initializes the disassembler
            inline void disassInit(void);

          protected:
            /*! \brief map of address -> concrete value
             *
             * \details
             *
             * **item1**: memory address<br>
             * **item2**: concrete value
             */
            std::unordered_map<triton::uint64, triton::uint8, IdentityHash<triton::uint64>> memory;

            //! Concrete value of x0
            triton::uint8 x0[triton::size::qword];
            //! Concrete value of x1
            triton::uint8 x1[triton::size::qword];
            //! Concrete value of x2
            triton::uint8 x2[triton::size::qword];
            //! Concrete value of x3
            triton::uint8 x3[triton::size::qword];
            //! Concrete value of x4
            triton::uint8 x4[triton::size::qword];
            //! Concrete value of x5
            triton::uint8 x5[triton::size::qword];
            //! Concrete value of x6
            triton::uint8 x6[triton::size::qword];
            //! Concrete value of x7
            triton::uint8 x7[triton::size::qword];
            //! Concrete value of x8
            triton::uint8 x8[triton::size::qword];
            //! Concrete value of x9
            triton::uint8 x9[triton::size::qword];
            //! Concrete value of x10
            triton::uint8 x10[triton::size::qword];
            //! Concrete value of x11
            triton::uint8 x11[triton::size::qword];
            //! Concrete value of x12
            triton::uint8 x12[triton::size::qword];
            //! Concrete value of x13
            triton::uint8 x13[triton::size::qword];
            //! Concrete value of x14
            triton::uint8 x14[triton::size::qword];
            //! Concrete value of x15
            triton::uint8 x15[triton::size::qword];
            //! Concrete value of x16
            triton::uint8 x16[triton::size::qword];
            //! Concrete value of x17
            triton::uint8 x17[triton::size::qword];
            //! Concrete value of x18
            triton::uint8 x18[triton::size::qword];
            //! Concrete value of x19
            triton::uint8 x19[triton::size::qword];
            //! Concrete value of x20
            triton::uint8 x20[triton::size::qword];
            //! Concrete value of x21
            triton::uint8 x21[triton::size::qword];
            //! Concrete value of x22
            triton::uint8 x22[triton::size::qword];
            //! Concrete value of x23
            triton::uint8 x23[triton::size::qword];
            //! Concrete value of x24
            triton::uint8 x24[triton::size::qword];
            //! Concrete value of x25
            triton::uint8 x25[triton::size::qword];
            //! Concrete value of x26
            triton::uint8 x26[triton::size::qword];
            //! Concrete value of x27
            triton::uint8 x27[triton::size::qword];
            //! Concrete value of x28
            triton::uint8 x28[triton::size::qword];
            //! Concrete value of x29
            triton::uint8 x29[triton::size::qword];
            //! Concrete value of x30
            triton::uint8 x30[triton::size::qword];
            //! Concrete value of q0
            triton::uint8 q0[triton::size::dqword];
            //! Concrete value of q1
            triton::uint8 q1[triton::size::dqword];
            //! Concrete value of q2
            triton::uint8 q2[triton::size::dqword];
            //! Concrete value of q3
            triton::uint8 q3[triton::size::dqword];
            //! Concrete value of q4
            triton::uint8 q4[triton::size::dqword];
            //! Concrete value of q5
            triton::uint8 q5[triton::size::dqword];
            //! Concrete value of q6
            triton::uint8 q6[triton::size::dqword];
            //! Concrete value of q7
            triton::uint8 q7[triton::size::dqword];
            //! Concrete value of q8
            triton::uint8 q8[triton::size::dqword];
            //! Concrete value of q9
            triton::uint8 q9[triton::size::dqword];
            //! Concrete value of q10
            triton::uint8 q10[triton::size::dqword];
            //! Concrete value of q11
            triton::uint8 q11[triton::size::dqword];
            //! Concrete value of q12
            triton::uint8 q12[triton::size::dqword];
            //! Concrete value of q13
            triton::uint8 q13[triton::size::dqword];
            //! Concrete value of q14
            triton::uint8 q14[triton::size::dqword];
            //! Concrete value of q15
            triton::uint8 q15[triton::size::dqword];
            //! Concrete value of q16
            triton::uint8 q16[triton::size::dqword];
            //! Concrete value of q17
            triton::uint8 q17[triton::size::dqword];
            //! Concrete value of q18
            triton::uint8 q18[triton::size::dqword];
            //! Concrete value of q19
            triton::uint8 q19[triton::size::dqword];
            //! Concrete value of q20
            triton::uint8 q20[triton::size::dqword];
            //! Concrete value of q21
            triton::uint8 q21[triton::size::dqword];
            //! Concrete value of q22
            triton::uint8 q22[triton::size::dqword];
            //! Concrete value of q23
            triton::uint8 q23[triton::size::dqword];
            //! Concrete value of q24
            triton::uint8 q24[triton::size::dqword];
            //! Concrete value of q25
            triton::uint8 q25[triton::size::dqword];
            //! Concrete value of q26
            triton::uint8 q26[triton::size::dqword];
            //! Concrete value of q27
            triton::uint8 q27[triton::size::dqword];
            //! Concrete value of q28
            triton::uint8 q28[triton::size::dqword];
            //! Concrete value of q29
            triton::uint8 q29[triton::size::dqword];
            //! Concrete value of q30
            triton::uint8 q30[triton::size::dqword];
            //! Concrete value of q31
            triton::uint8 q31[triton::size::dqword];
            //! Concrete value of sp
            triton::uint8 sp[triton::size::qword];
            //! Concrete value of pc
            triton::uint8 pc[triton::size::qword];
            //! Concrete value of spsr
            triton::uint8 spsr[triton::size::dword];

            //! System registers
            #define SYS_REG_SPEC(_, LOWER_NAME, _2, _3, _4, _5) \
            triton::uint8 LOWER_NAME[triton::size::qword];
            #define REG_SPEC(_1, _2, _3, _4, _5, _6)
            #define REG_SPEC_NO_CAPSTONE(_1, _2, _3, _4, _5, _6)
            #include "triton/aarch64.spec"

          public:
            //! Constructor.
            TRITON_EXPORT AArch64Cpu(triton::callbacks::Callbacks* callbacks=nullptr);

            //! Constructor
            TRITON_EXPORT AArch64Cpu(const AArch64Cpu& other);

            //! Destructor.
            TRITON_EXPORT virtual ~AArch64Cpu();

            //! Copies a AArch64Cpu class.
            TRITON_EXPORT AArch64Cpu& operator=(const AArch64Cpu& other);

            //! Returns true if regId is a GRP.
            TRITON_EXPORT bool isGPR(triton::arch::register_e regId) const;

            //! Returns true if regId is a scalar register.
            TRITON_EXPORT bool isScalarRegister(triton::arch::register_e regId) const;

            //! Returns true if regId is a vector register.
            TRITON_EXPORT bool isVectorRegister(triton::arch::register_e regId) const;

            //! Returns true if regId is a system register.
            TRITON_EXPORT bool isSystemRegister(triton::arch::register_e regId) const;

            /* Virtual pure inheritance ================================================= */
            TRITON_EXPORT bool isFlag(triton::arch::register_e regId) const;
            TRITON_EXPORT bool isRegister(triton::arch::register_e regId) const;
            TRITON_EXPORT bool isRegisterValid(triton::arch::register_e regId) const;
            TRITON_EXPORT bool isThumb(void) const;
            TRITON_EXPORT bool isMemoryExclusive(const triton::arch::MemoryAccess& mem) const;
            TRITON_EXPORT const std::unordered_map<triton::arch::register_e, const triton::arch::Register>& getAllRegisters(void) const;
            TRITON_EXPORT const triton::arch::Register& getParentRegister(const triton::arch::Register& reg) const;
            TRITON_EXPORT const triton::arch::Register& getParentRegister(triton::arch::register_e id) const;
            TRITON_EXPORT const triton::arch::Register& getProgramCounter(void) const;
            TRITON_EXPORT const triton::arch::Register& getRegister(triton::arch::register_e id) const;
            TRITON_EXPORT const triton::arch::Register& getRegister(const std::string& name) const;
            TRITON_EXPORT const triton::arch::Register& getStackPointer(void) const;
            TRITON_EXPORT std::set<const triton::arch::Register*> getParentRegisters(void) const;
            TRITON_EXPORT std::vector<triton::uint8> getConcreteMemoryAreaValue(triton::uint64 baseAddr, triton::usize size, bool execCallbacks=true) const;
            TRITON_EXPORT triton::arch::endianness_e getEndianness(void) const;
            TRITON_EXPORT triton::uint32 gprBitSize(void) const;
            TRITON_EXPORT triton::uint32 gprSize(void) const;
            TRITON_EXPORT triton::uint32 numberOfRegisters(void) const;
            TRITON_EXPORT triton::uint512 getConcreteMemoryValue(const triton::arch::MemoryAccess& mem, bool execCallbacks=true) const;
            TRITON_EXPORT triton::uint512 getConcreteRegisterValue(const triton::arch::Register& reg, bool execCallbacks=true) const;
            TRITON_EXPORT triton::uint8 getConcreteMemoryValue(triton::uint64 addr, bool execCallbacks=true) const;
            TRITON_EXPORT void clear(void);
            TRITON_EXPORT void disassembly(triton::arch::Instruction& inst);
            TRITON_EXPORT void setConcreteMemoryAreaValue(triton::uint64 baseAddr, const std::vector<triton::uint8>& values, bool execCallbacks=true);
            TRITON_EXPORT void setConcreteMemoryAreaValue(triton::uint64 baseAddr, const void* area, triton::usize size, bool execCallbacks=true);
            TRITON_EXPORT void setConcreteMemoryValue(const triton::arch::MemoryAccess& mem, const triton::uint512& value, bool execCallbacks=true);
            TRITON_EXPORT void setConcreteMemoryValue(triton::uint64 addr, triton::uint8 value, bool execCallbacks=true);
            TRITON_EXPORT void setConcreteRegisterValue(const triton::arch::Register& reg, const triton::uint512& value, bool execCallbacks=true);
            TRITON_EXPORT void setThumb(bool state);
            TRITON_EXPORT void setMemoryExclusiveTag(const triton::arch::MemoryAccess& mem, bool tag);
            TRITON_EXPORT bool isConcreteMemoryValueDefined(const triton::arch::MemoryAccess& mem) const;
            TRITON_EXPORT bool isConcreteMemoryValueDefined(triton::uint64 baseAddr, triton::usize size=1) const;
            TRITON_EXPORT void clearConcreteMemoryValue(const triton::arch::MemoryAccess& mem);
            TRITON_EXPORT void clearConcreteMemoryValue(triton::uint64 baseAddr, triton::usize size=1);
            /* End of virtual pure inheritance ========================================== */
        };

      /*! @} End of aarch64 namespace */
      };
    /*! @} End of arm namespace */
    };
  /*! @} End of arch namespace */
  };
/*! @} End of triton namespace */
};

#endif /* TRITON_AARCH64CPU_HPP */


text:
require 'ansible/ruby/modules/base'

module Ansible
  module Ruby
    module Modules
      # Get facts for all virtual machines of a resource group.
      class Azure_rm_virtualmachine_facts < Base
        # @return [String, nil] Name of the resource group containing the virtual machines (required when filtering by vm name).
        attribute :resource_group
        validates :resource_group, type: String

        # @return [String, nil] Name of the virtual machine.
        attribute :name
        validates :name, type: String

        # @return [Array<String>, String, nil] Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.
        attribute :tags
        validates :tags, type: TypeGeneric.new(String)
      end
    end
  end
end


text:
#!/bin/sh

# Clean up the results directory
rm -rf results
mkdir results

#Synthesize the Wrapper Files

echo 'Synthesizing example design with XST';
xst -ifn xst.scr
cp Instruct_Memory_exdes.ngc ./results/

# Copy the netlist generated by Coregen
echo 'Copying files from the netlist directory to the results directory'
cp ../../Instruct_Memory.ngc results/

#  Copy the constraints files generated by Coregen
echo 'Copying files from constraints directory to results directory'
cp ../example_design/Instruct_Memory_exdes.ucf results/

cd results

echo 'Running ngdbuild'
ngdbuild -p xc3s500e-fg320-4 Instruct_Memory_exdes

echo 'Running map'
map Instruct_Memory_exdes -o mapped.ncd -pr i

echo 'Running par'
par mapped.ncd routed.ncd

echo 'Running trce'
trce -e 10 routed.ncd mapped.pcf -o routed

echo 'Running design through bitgen'
bitgen -w routed

echo 'Running netgen to create gate level VHDL model'
netgen -ofmt vhdl -sim -tm Instruct_Memory_exdes -pcf mapped.pcf -w routed.ncd routed.vhd


text:
export class Entity {
  id: string;
  applicationId: string;
  parentId?: string;
  name: string;
  type: string;
  iconUrl?: string;
  serviceUp: boolean;
  serviceState: string;
  children?: Application[];
}

export class Application extends Entity {
  applicationId: string;
}

class Location {
  id: string;
}

export class Effector {
  name: string;
  description: string;
  returnType: string;
  parameters: EffectorParameter[] = [];
}

export class EffectorParameter {
  name: string;
  type: string;
  description: string;
  defaultValue?: any;
  shouldSanitize?: boolean;
}

export class Policy {
  id: string;
  name: string;
  catalogItemId: string;
  state: string;
}

export class PolicyConfig {
  name: string;
  type: string;
  description: string;
  defaultValue: any;
  reconfigurable: boolean;
}


text:
package com.sixt.service.framework.kafka.messaging;

import com.google.protobuf.Parser;
import com.sixt.service.framework.OrangeContext;
import com.sixt.service.framework.metrics.MetricBuilderFactory;
import io.opentracing.Tracer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.TopicPartition;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static junit.framework.TestCase.*;

public class PartitionProcessorTest {

    private static final String TOPIC = "aTopic";
    private static final int PARTITION = 42;
    private static final String KEY = "aKey";

    static class TestHandler implements MessageHandler {

        final AtomicInteger nbHandlerInvokations = new AtomicInteger(0);
        final CountDownLatch onMessageCalled = new CountDownLatch(1);
        final CountDownLatch blockReturnFromOnMessage = new CountDownLatch(1);
        final CountDownLatch handlerReturnedNormally = new CountDownLatch(1);

        final List<Message> handledMessages = Collections.synchronizedList(new ArrayList<>());
        volatile Message lastMessage = null;
        volatile OrangeContext lastContext = null;
        volatile RuntimeException exceptionToBeThrown = null;
        volatile boolean resetExceptionToNull = true;

        @Override
        public void onMessage(Message msg, OrangeContext context) {
            nbHandlerInvokations.incrementAndGet();

            handledMessages.add(msg);

            lastMessage = msg;
            lastContext = context;

            onMessageCalled.countDown();

            if (exceptionToBeThrown != null) {
                RuntimeException boom = exceptionToBeThrown;
                if (resetExceptionToNull) {
                    exceptionToBeThrown = null;
                }
                throw boom;
            }

            try {
                blockReturnFromOnMessage.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            handlerReturnedNormally.countDown();
        }
    }

    static class TestTypeDictionary extends TypeDictionary {

        TestHandler handler = new TestHandler();

        public TestTypeDictionary() {
            super(new HashMap<>(), new HashMap<>());
        }

        @Override
        public MessageHandler messageHandlerFor(MessageType type) {
            return handler;
        }

        @Override
        public Parser parserFor(MessageType type) {
            return EmptyMessage.parser();
        }
    }

    private PartitionProcessor givenAPartionProcessor() {
        TopicPartition topicKey = new TopicPartition(TOPIC, PARTITION);

        TypeDictionary typeDictionary = new TestTypeDictionary();
        FailedMessageProcessor failedMessageProcessor = new DiscardFailedMessages();

        MetricBuilderFactory metricsBuilderFactory = null;
        Tracer tracer = null;

        return new PartitionProcessor(topicKey, typeDictionary, failedMessageProcessor, tracer, metricsBuilderFactory);
    }

    private ConsumerRecord<String, byte[]> testRecordWithOffset(long offset) {
        Envelope.Builder envelope = Envelope.newBuilder();
        envelope.setMessageId("cruft");

        return new ConsumerRecord<String, byte[]>(TOPIC, PARTITION, offset, KEY, envelope.build().toByteArray());
    }

    private ConsumerRecord<String, byte[]> simulateKafkaInTheLoop(Message message, long offset) {
        Envelope envelope = Messages.toKafka(message);
        return new ConsumerRecord<String, byte[]>(message.getMetadata().getTopic().toString(), PARTITION, offset, message.getMetadata().getPartitioningKey(), envelope.toByteArray());
    }

    private void shortSleep() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ignored) {

        }
    }

    private TestHandler getTestHandler(PartitionProcessor processor) {
        return (TestHandler) processor.getTypeDictionary().messageHandlerFor(null);
    }

    @Test
    public void basicLifecycle() throws InterruptedException {
        PartitionProcessor processor = givenAPartionProcessor();
        assertFalse(processor.isTerminated());

        assertFalse(processor.isPaused());
        assertTrue(processor.shouldResume());

        assertEquals(0, processor.numberOfUnprocessedMessages());
        assertFalse(processor.hasUncommittedMessages());
        assertEquals(-1, processor.getCommitOffsetAndClear());

        processor.waitForHandlersToTerminate(1);
        assertTrue(processor.isTerminated());

        assertEquals(0, processor.numberOfUnprocessedMessages());
        assertFalse(processor.hasUncommittedMessages());
        assertEquals(-1, processor.getCommitOffsetAndClear());
    }

    @Test
    public void consumeOneMessage() throws InterruptedException {
        PartitionProcessor processor = givenAPartionProcessor();

        ConsumerRecord<String, byte[]> record = testRecordWithOffset(999);
        processor.enqueue(record);

        (getTestHandler(processor)).onMessageCalled.await();

        // message not yet marked as consumed
        assertEquals(0, processor.numberOfUnprocessedMessages());
        assertFalse(processor.hasUncommittedMessages());
        assertEquals(-1, processor.getCommitOffsetAndClear());

        (getTestHandler(processor)).blockReturnFromOnMessage.countDown();
        Thread.sleep(1000); // allow handler to continue

        assertTrue(processor.hasUncommittedMessages());
        assertEquals(1000, processor.getCommitOffsetAndClear());

        // getCommitOffsetAndClear clears hasUncommittedMessages
        assertFalse(processor.hasUncommittedMessages());
        assertEquals(1000, processor.getCommitOffsetAndClear());

        processor.waitForHandlersToTerminate(50);
    }

    @Test
    public void pauseProcessorIfBacklogOfUnconsumedMessagesToBig() throws InterruptedException {
        PartitionProcessor processor = givenAPartionProcessor();

        for (int i = 1; i <= PartitionProcessor.MAX_MESSAGES_IN_FLIGHT + 2; i++) {
            ConsumerRecord<String, byte[]> record = testRecordWithOffset(i);
            processor.enqueue(record);
        }

        while (processor.numberOfUnprocessedMessages() < PartitionProcessor.MAX_MESSAGES_IN_FLIGHT + 1) {
            shortSleep(); // allow to fill queue
        }

        assertEquals(PartitionProcessor.MAX_MESSAGES_IN_FLIGHT + 1, processor.numberOfUnprocessedMessages()); // 1 message currently in handler
        assertTrue(processor.isPaused()); // should throttle
        assertFalse(processor.shouldResume());

        (getTestHandler(processor)).onMessageCalled.await();
        (getTestHandler(processor)).blockReturnFromOnMessage.countDown();

        shortSleep(); // allow handler to continue

        assertTrue(processor.hasUncommittedMessages());
        assertEquals(PartitionProcessor.MAX_MESSAGES_IN_FLIGHT + 3, processor.getCommitOffsetAndClear());

        assertFalse(processor.isPaused()); // after emptying the queue, processor should resume
        assertTrue(processor.shouldResume());

        processor.waitForHandlersToTerminate(50);
    }

    @Test
    public void shutDownEvenIfHandlerIsStillActive() throws InterruptedException {
        PartitionProcessor processor = givenAPartionProcessor();

        ConsumerRecord<String, byte[]> record = testRecordWithOffset(999);
        processor.enqueue(record);
        (getTestHandler(processor)).onMessageCalled.await();

        processor.stopProcessing();
        assertFalse(processor.isTerminated());

        processor.waitForHandlersToTerminate(10); // should log a warn about still running handlers
        assertTrue(processor.isTerminated());
        assertFalse(processor.hasUncommittedMessages());

        // If handler finishes, it will mark message as committable, but at this time, the processor is probably already removed.
        (getTestHandler(processor)).blockReturnFromOnMessage.countDown();
        shortSleep(); // allow handler to continue
        assertTrue(processor.hasUncommittedMessages());
    }

    @Test
    public void afterProcesserIsStoppedMessagesToBeEnqueuedWillBeIgnored() throws InterruptedException {
        PartitionProcessor processor = givenAPartionProcessor();
        processor.stopProcessing();

        ConsumerRecord<String, byte[]> record = testRecordWithOffset(999);
        processor.enqueue(record); // should log a message that messages are ignored (and never committed to Kafka)

        // assert handler not called
        assertFalse((getTestHandler(processor)).onMessageCalled.await(100, TimeUnit.MILLISECONDS));

        processor.waitForHandlersToTerminate(1);
    }

    @Test
    public void requestResponseCylce() throws InterruptedException {
        PartitionProcessor processor = givenAPartionProcessor();

        EmptyMessage payload = EmptyMessage.getDefaultInstance();
        OrangeContext context = new OrangeContext();

        ConsumerRecord<String, byte[]> aRecord;

        Message sentRequest = Messages.requestFor(Topic.defaultServiceInbox("com.sixt.service.cruft"), Topic.serviceInbox("com.sixt.service.cruft", "trashcan"), "requestKey", payload, context);
        aRecord = simulateKafkaInTheLoop(sentRequest, 10);
        processor.enqueue(aRecord);

        getTestHandler(processor).onMessageCalled.await();
        Message receivedRequest = getTestHandler(processor).lastMessage;
        OrangeContext receivedContext = getTestHandler(processor).lastContext;

        Message sentReply = Messages.replyTo(receivedRequest, payload, receivedContext);
        aRecord = simulateKafkaInTheLoop(sentReply, 20);
        processor.enqueue(aRecord);

        getTestHandler(processor).blockReturnFromOnMessage.countDown();
        shortSleep(); // for the reply handling

        Message receivedReply = getTestHandler(processor).lastMessage;
        assertEquals(2, getTestHandler(processor).handledMessages.size());

        assertEquals(sentRequest.getMetadata().getReplyTo(), receivedReply.getMetadata().getTopic());
        assertEquals(sentRequest.getMetadata().getMessageId(), receivedReply.getMetadata().getRequestCorrelationId());
        assertEquals(context.getCorrelationId(), receivedReply.getMetadata().getCorrelationId());

        processor.waitForHandlersToTerminate(1);
    }

    @Test
    public void exceptionInHandlerShouldConsumeMessage() throws InterruptedException {
        PartitionProcessor processor = givenAPartionProcessor();
        processor.enqueue(testRecordWithOffset(42));

        getTestHandler(processor).exceptionToBeThrown = new RuntimeException("BOOM");
        getTestHandler(processor).onMessageCalled.await();
        shortSleep();

        assertTrue(processor.hasUncommittedMessages());
        assertEquals(43, processor.getCommitOffsetAndClear());

        processor.waitForHandlersToTerminate(1);
    }

    @Test
    public void retryFailedMessages() throws InterruptedException {
        TopicPartition topicKey = new TopicPartition(TOPIC, PARTITION);
        TypeDictionary typeDictionary = new TestTypeDictionary();

        class RetryableTestException extends RuntimeException {

        }

        class RetryTestFailureHandler extends DelayAndRetryOnRecoverableErrors {

            public RetryTestFailureHandler(FailedMessageProcessor fallbackStrategy, RetryDelayer retryStrategy) {
                super(fallbackStrategy, retryStrategy);
            }

            @Override
            protected boolean isRecoverable(Throwable failureCause) {

                if (failureCause instanceof RetryableTestException) {
                    return true;
                }

                return super.isRecoverable(failureCause);
            }
        }

        FailedMessageProcessor failedMessageProcessor = new RetryTestFailureHandler(new DiscardFailedMessages(), new SimpleRetryDelayer(10, 100));
        PartitionProcessor processor = new PartitionProcessor(topicKey, typeDictionary, failedMessageProcessor, null, null);

        getTestHandler(processor).exceptionToBeThrown = new RetryableTestException();
        processor.enqueue(testRecordWithOffset(42));

        getTestHandler(processor).blockReturnFromOnMessage.countDown();
        getTestHandler(processor).handlerReturnedNormally.await();

        processor.waitForHandlersToTerminate(100);

        assertEquals(2, getTestHandler(processor).nbHandlerInvokations.get());
        assertTrue(processor.hasUncommittedMessages());
        assertEquals(43, processor.getCommitOffsetAndClear());
    }

    @Test
    public void retryFailedMessagesHitsRetryLimit() throws InterruptedException {
        TopicPartition topicKey = new TopicPartition(TOPIC, PARTITION);
        TypeDictionary typeDictionary = new TestTypeDictionary();

        class RetryableTestException extends RuntimeException {

        }

        class RetryTestFailureHandler extends DelayAndRetryOnRecoverableErrors {

            public RetryTestFailureHandler(FailedMessageProcessor fallbackStrategy, RetryDelayer retryStrategy) {
                super(fallbackStrategy, retryStrategy);
            }

            @Override
            protected boolean isRecoverable(Throwable failureCause) {

                if (failureCause instanceof RetryableTestException) {
                    return true;
                }

                return super.isRecoverable(failureCause);
            }
        }

        FailedMessageProcessor failedMessageProcessor = new RetryTestFailureHandler(new DiscardFailedMessages(), new SimpleRetryDelayer(10, 200));
        PartitionProcessor processor = new PartitionProcessor(topicKey, typeDictionary, failedMessageProcessor, null, null);

        getTestHandler(processor).exceptionToBeThrown = new RetryableTestException();
        getTestHandler(processor).resetExceptionToNull = false; // Never terminate normally

        processor.enqueue(testRecordWithOffset(42));

        assertFalse(getTestHandler(processor).handlerReturnedNormally.await(2, TimeUnit.SECONDS));

        // new SimpleRetryDelayer(10, 200) -> 20 retries
        // timing of retry delays manually checked by timestamps in log output -> is OK
        assertEquals(20, getTestHandler(processor).nbHandlerInvokations.get());

        assertTrue(processor.hasUncommittedMessages());
        assertEquals(43, processor.getCommitOffsetAndClear());
        processor.waitForHandlersToTerminate(1);
    }

}