try {
            data = Os.capget(header);
        } catch (ErrnoException ex) {
            throw new RuntimeException("Failed to capget()", ex);
        }

package com.android.internal.os;

import static android.system.OsConstants.S_IRWXG;
import static android.system.OsConstants.S_IRWXO;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.icu.impl.CacheValue;
import android.icu.text.DecimalFormatSymbols;
import android.icu.util.ULocale;
import android.opengl.EGL14;
import android.os.Build;
import android.os.Environment;
import android.os.IInstalld;
import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.ServiceSpecificException;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.Trace;
import android.os.UserHandle;
import android.os.ZygoteProcess;
import android.os.storage.StorageManager;
import android.security.keystore.AndroidKeyStoreProvider;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
import android.system.StructCapUserData;
import android.system.StructCapUserHeader;
import android.text.Hyphenator;
import android.util.EventLog;
import android.util.Log;
import android.util.Slog;
import android.util.TimingsTraceLog;
import android.webkit.WebViewFactory;
import android.widget.TextView;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.util.Preconditions;
import dalvik.system.DexFile;
import dalvik.system.VMRuntime;
import dalvik.system.ZygoteHooks;
import libcore.io.IoUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.Provider;
import java.security.Security;

/**
 * Startup class for the zygote process.
 *
 * Pre-initializes some classes, and then waits for commands on a UNIX domain
 * socket. Based on these commands, forks off child processes that inherit
 * the initial state of the VM.
 *
 * Please see {@link ZygoteConnection.Arguments} for documentation on the
 * client protocol.
 *
 * @hide
 */
public class ZygoteInit {

    private static final String TAG = "Zygote";

    private static final String PROPERTY_DISABLE_OPENGL_PRELOADING = "ro.zygote.disable_gl_preload";

    private static final String PROPERTY_GFX_DRIVER = "ro.gfx.driver.0";

    private static final int LOG_BOOT_PROGRESS_PRELOAD_START = 3020;

    private static final int LOG_BOOT_PROGRESS_PRELOAD_END = 3030;

    /**
     * when preloading, GC after allocating this many bytes
     */
    private static final int PRELOAD_GC_THRESHOLD = 50000;

    private static final String ABI_LIST_ARG = "--abi-list=";

    private static final String SOCKET_NAME_ARG = "--socket-name=";

    /**
     * Used to pre-load resources.
     */
    private static Resources mResources;

    /**
     * The path of a file that contains classes to preload.
     */
    private static final String PRELOADED_CLASSES = "/system/etc/preloaded-classes";

    /**
     * Controls whether we should preload resources during zygote init.
     */
    public static final boolean PRELOAD_RESOURCES = true;

    private static final int UNPRIVILEGED_UID = 9999;

    private static final int UNPRIVILEGED_GID = 9999;

    private static final int ROOT_UID = 0;

    private static final int ROOT_GID = 0;

    private static boolean sPreloadComplete;

    static void preload(TimingsTraceLog bootTimingsTraceLog) {
        Log.d(TAG, "begin preload");
        bootTimingsTraceLog.traceBegin("BeginIcuCachePinning");
        beginIcuCachePinning();
        // BeginIcuCachePinning
        bootTimingsTraceLog.traceEnd();
        bootTimingsTraceLog.traceBegin("PreloadClasses");
        preloadClasses();
        // PreloadClasses
        bootTimingsTraceLog.traceEnd();
        bootTimingsTraceLog.traceBegin("PreloadResources");
        preloadResources();
        // PreloadResources
        bootTimingsTraceLog.traceEnd();
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadAppProcessHALs");
        nativePreloadAppProcessHALs();
        Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadOpenGL");
        preloadOpenGL();
        Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
        preloadSharedLibraries();
        preloadTextResources();
        // Ask the WebViewFactory to do any initialization that must run in the zygote process,
        // for memory sharing purposes.
        WebViewFactory.prepareWebViewInZygote();
        endIcuCachePinning();
        warmUpJcaProviders();
        Log.d(TAG, "end preload");
        sPreloadComplete = true;
    }

    public static void lazyPreload() {
        Preconditions.checkState(!sPreloadComplete);
        Log.i(TAG, "Lazily preloading resources.");
        preload(new TimingsTraceLog("ZygoteInitTiming_lazy", Trace.TRACE_TAG_DALVIK));
    }

    private static void beginIcuCachePinning() {
        // Pin ICU data in memory from this point that would normally be held by soft references.
        // Without this, any references created immediately below or during class preloading
        // would be collected when the Zygote GC runs in gcAndFinalize().
        Log.i(TAG, "Installing ICU cache reference pinning...");
        CacheValue.setStrength(CacheValue.Strength.STRONG);
        Log.i(TAG, "Preloading ICU data...");
        // Explicitly exercise code to cache data apps are likely to need.
        ULocale[] localesToPin = { ULocale.ROOT, ULocale.US, ULocale.getDefault() };
        for (ULocale uLocale : localesToPin) {
            new DecimalFormatSymbols(uLocale);
        }
    }

    private static void endIcuCachePinning() {
        // All cache references created by ICU from this point will be soft.
        CacheValue.setStrength(CacheValue.Strength.SOFT);
        Log.i(TAG, "Uninstalled ICU cache reference pinning...");
    }

    private static void preloadSharedLibraries() {
        Log.i(TAG, "Preloading shared libraries...");
        System.loadLibrary("android");
        System.loadLibrary("compiler_rt");
        System.loadLibrary("jnigraphics");
    }

    native private static void nativePreloadAppProcessHALs();

    private static void preloadOpenGL() {
        String driverPackageName = SystemProperties.get(PROPERTY_GFX_DRIVER);
        if (!SystemProperties.getBoolean(PROPERTY_DISABLE_OPENGL_PRELOADING, false) && (driverPackageName == null || driverPackageName.isEmpty())) {
            EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
        }
    }

    private static void preloadTextResources() {
        Hyphenator.init();
        TextView.preloadFontCache();
    }

    /**
     * Register AndroidKeyStoreProvider and warm up the providers that are already registered.
     *
     * By doing it here we avoid that each app does it when requesting a service from the
     * provider for the first time.
     */
    private static void warmUpJcaProviders() {
        long startTime = SystemClock.uptimeMillis();
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "Starting installation of AndroidKeyStoreProvider");
        // AndroidKeyStoreProvider.install() manipulates the list of JCA providers to insert
        // preferred providers. Note this is not done via security.properties as the JCA providers
        // are not on the classpath in the case of, for example, raw dalvikvm runtimes.
        AndroidKeyStoreProvider.install();
        Log.i(TAG, "Installed AndroidKeyStoreProvider in " + (SystemClock.uptimeMillis() - startTime) + "ms.");
        Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
        startTime = SystemClock.uptimeMillis();
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "Starting warm up of JCA providers");
        for (Provider p : Security.getProviders()) {
            p.warmUpServiceProvision();
        }
        Log.i(TAG, "Warmed up JCA providers in " + (SystemClock.uptimeMillis() - startTime) + "ms.");
        Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
    }

    /**
     * Performs Zygote process initialization. Loads and initializes
     * commonly used classes.
     *
     * Most classes only cause a few hundred bytes to be allocated, but
     * a few will allocate a dozen Kbytes (in one case, 500+K).
     */
    private static void preloadClasses() {
        final VMRuntime runtime = VMRuntime.getRuntime();
        InputStream is;
        try {
            is = new FileInputStream(PRELOADED_CLASSES);
        } catch (FileNotFoundException e) {
            Log.e(TAG, "Couldn't find " + PRELOADED_CLASSES + ".");
            return;
        }
        Log.i(TAG, "Preloading classes...");
        long startTime = SystemClock.uptimeMillis();
        // Drop root perms while running static initializers.
        final int reuid = Os.getuid();
        final int regid = Os.getgid();
        // We need to drop root perms only if we're already root. In the case of "wrapped"
        // processes (see WrapperInit), this function is called from an unprivileged uid
        // and gid.
        boolean droppedPriviliges = false;
        if (reuid == ROOT_UID && regid == ROOT_GID) {
            try {
                Os.setregid(ROOT_GID, UNPRIVILEGED_GID);
                Os.setreuid(ROOT_UID, UNPRIVILEGED_UID);
            } catch (ErrnoException ex) {
                throw new RuntimeException("Failed to drop root", ex);
            }
            droppedPriviliges = true;
        }
        // Alter the target heap utilization.  With explicit GCs this
        // is not likely to have any effect.
        float defaultUtilization = runtime.getTargetHeapUtilization();
        runtime.setTargetHeapUtilization(0.8f);
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is), 256);
            int count = 0;
            String line;
            while ((line = br.readLine()) != null) {
                // Skip comments and blank lines.
                line = line.trim();
                if (line.startsWith("#") || line.equals("")) {
                    continue;
                }
                Trace.traceBegin(Trace.TRACE_TAG_DALVIK, line);
                try {
                    if (false) {
                        Log.v(TAG, "Preloading " + line + "...");
                    }
                    // Load and explicitly initialize the given class. Use
                    // Class.forName(String, boolean, ClassLoader) to avoid repeated stack lookups
                    // (to derive the caller's class-loader). Use true to force initialization, and
                    // null for the boot classpath class-loader (could as well cache the
                    // class-loader of this class in a variable).
                    Class.forName(line, true, null);
                    count++;
                } catch (ClassNotFoundException e) {
                    Log.w(TAG, "Class not found for preloading: " + line);
                } catch (UnsatisfiedLinkError e) {
                    Log.w(TAG, "Problem preloading " + line + ": " + e);
                } catch (Throwable t) {
                    Log.e(TAG, "Error preloading " + line + ".", t);
                    if (t instanceof Error) {
                        throw (Error) t;
                    }
                    if (t instanceof RuntimeException) {
                        throw (RuntimeException) t;
                    }
                    throw new RuntimeException(t);
                }
                Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
            }
            Log.i(TAG, "...preloaded " + count + " classes in " + (SystemClock.uptimeMillis() - startTime) + "ms.");
        } catch (IOException e) {
            Log.e(TAG, "Error reading " + PRELOADED_CLASSES + ".", e);
        } finally {
            IoUtils.closeQuietly(is);
            runtime.setTargetHeapUtilization(defaultUtilization);
            // Fill in dex caches with classes, fields, and methods brought in by preloading.
            Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadDexCaches");
            runtime.preloadDexCaches();
            Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
            // Bring back root. We'll need it later if we're in the zygote.
            if (droppedPriviliges) {
                try {
                    Os.setreuid(ROOT_UID, ROOT_UID);
                    Os.setregid(ROOT_GID, ROOT_GID);
                } catch (ErrnoException ex) {
                    throw new RuntimeException("Failed to restore root", ex);
                }
            }
        }
    }

    /**
     * Load in commonly used resources, so they can be shared across
     * processes.
     *
     * These tend to be a few Kbytes, but are frequently in the 20-40K
     * range, and occasionally even larger.
     */
    private static void preloadResources() {
        final VMRuntime runtime = VMRuntime.getRuntime();
        try {
            mResources = Resources.getSystem();
            mResources.startPreloading();
            if (PRELOAD_RESOURCES) {
                Log.i(TAG, "Preloading resources...");
                long startTime = SystemClock.uptimeMillis();
                TypedArray ar = mResources.obtainTypedArray(com.android.internal.R.array.preloaded_drawables);
                int N = preloadDrawables(ar);
                ar.recycle();
                Log.i(TAG, "...preloaded " + N + " resources in " + (SystemClock.uptimeMillis() - startTime) + "ms.");
                startTime = SystemClock.uptimeMillis();
                ar = mResources.obtainTypedArray(com.android.internal.R.array.preloaded_color_state_lists);
                N = preloadColorStateLists(ar);
                ar.recycle();
                Log.i(TAG, "...preloaded " + N + " resources in " + (SystemClock.uptimeMillis() - startTime) + "ms.");
                if (mResources.getBoolean(com.android.internal.R.bool.config_freeformWindowManagement)) {
                    startTime = SystemClock.uptimeMillis();
                    ar = mResources.obtainTypedArray(com.android.internal.R.array.preloaded_freeform_multi_window_drawables);
                    N = preloadDrawables(ar);
                    ar.recycle();
                    Log.i(TAG, "...preloaded " + N + " resource in " + (SystemClock.uptimeMillis() - startTime) + "ms.");
                }
            }
            mResources.finishPreloading();
        } catch (RuntimeException e) {
            Log.w(TAG, "Failure preloading resources", e);
        }
    }

    private static int preloadColorStateLists(TypedArray ar) {
        int N = ar.length();
        for (int i = 0; i < N; i++) {
            int id = ar.getResourceId(i, 0);
            if (false) {
                Log.v(TAG, "Preloading resource #" + Integer.toHexString(id));
            }
            if (id != 0) {
                if (mResources.getColorStateList(id, null) == null) {
                    throw new IllegalArgumentException("Unable to find preloaded color resource #0x" + Integer.toHexString(id) + " (" + ar.getString(i) + ")");
                }
            }
        }
        return N;
    }

    private static int preloadDrawables(TypedArray ar) {
        int N = ar.length();
        for (int i = 0; i < N; i++) {
            int id = ar.getResourceId(i, 0);
            if (false) {
                Log.v(TAG, "Preloading resource #" + Integer.toHexString(id));
            }
            if (id != 0) {
                if (mResources.getDrawable(id, null) == null) {
                    throw new IllegalArgumentException("Unable to find preloaded drawable resource #0x" + Integer.toHexString(id) + " (" + ar.getString(i) + ")");
                }
            }
        }
        return N;
    }

    /**
     * Runs several special GCs to try to clean up a few generations of
     * softly- and final-reachable objects, along with any other garbage.
     * This is only useful just before a fork().
     */
    static void gcAndFinalize() {
        final VMRuntime runtime = VMRuntime.getRuntime();
        /* runFinalizationSync() lets finalizers be called in Zygote,
         * which doesn't have a HeapWorker thread.
         */
        System.gc();
        runtime.runFinalizationSync();
        System.gc();
    }

    /**
     * Finish remaining work for the newly forked system server process.
     */
    private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) {
        // set umask to 0077 so new files and directories will default to owner-only permissions.
        Os.umask(S_IRWXG | S_IRWXO);
        if (parsedArgs.niceName != null) {
            Process.setArgV0(parsedArgs.niceName);
        }
        final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
        if (systemServerClasspath != null) {
            performSystemServerDexOpt(systemServerClasspath);
            // Capturing profiles is only supported for debug or eng builds since selinux normally
            // prevents it.
            boolean profileSystemServer = SystemProperties.getBoolean("dalvik.vm.profilesystemserver", false);
            if (profileSystemServer && (Build.IS_USERDEBUG || Build.IS_ENG)) {
                try {
                    prepareSystemServerProfile(systemServerClasspath);
                } catch (Exception e) {
                    Log.wtf(TAG, "Failed to set up system server profile", e);
                }
            }
        }
        if (parsedArgs.invokeWith != null) {
            String[] args = parsedArgs.remainingArgs;
            // If we have a non-null system server class path, we'll have to duplicate the
            // existing arguments and append the classpath to it. ART will handle the classpath
            // correctly when we exec a new process.
            if (systemServerClasspath != null) {
                String[] amendedArgs = new String[args.length + 2];
                amendedArgs[0] = "-cp";
                amendedArgs[1] = systemServerClasspath;
                System.arraycopy(args, 0, amendedArgs, 2, args.length);
                args = amendedArgs;
            }
            WrapperInit.execApplication(parsedArgs.invokeWith, parsedArgs.niceName, parsedArgs.targetSdkVersion, VMRuntime.getCurrentInstructionSet(), null, args);
            throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
        } else {
            ClassLoader cl = null;
            if (systemServerClasspath != null) {
                cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);
                Thread.currentThread().setContextClassLoader(cl);
            }
            /*
             * Pass the remaining arguments to SystemServer.
             */
            return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
        }
        /* should never reach here */
    }

    /**
     * Note that preparing the profiles for system server does not require special
     * selinux permissions. From the installer perspective the system server is a regular package
     * which can capture profile information.
     */
    private static void prepareSystemServerProfile(String systemServerClasspath) throws RemoteException {
        if (systemServerClasspath.isEmpty()) {
            return;
        }
        String[] codePaths = systemServerClasspath.split(":");
        final IInstalld installd = IInstalld.Stub.asInterface(ServiceManager.getService("installd"));
        String systemServerPackageName = "android";
        String systemServerProfileName = "primary.prof";
        installd.prepareAppProfile(systemServerPackageName, UserHandle.USER_SYSTEM, UserHandle.getAppId(Process.SYSTEM_UID), systemServerProfileName, codePaths[0], /*dexMetadata*/
        null);
        File profileDir = Environment.getDataProfilesDePackageDirectory(UserHandle.USER_SYSTEM, systemServerPackageName);
        String profilePath = new File(profileDir, systemServerProfileName).getAbsolutePath();
        VMRuntime.registerAppInfo(profilePath, codePaths);
    }

    public static void setApiBlacklistExemptions(String[] exemptions) {
        VMRuntime.getRuntime().setHiddenApiExemptions(exemptions);
    }

    public static void setHiddenApiAccessLogSampleRate(int percent) {
        VMRuntime.getRuntime().setHiddenApiAccessLogSamplingRate(percent);
    }

    /**
     * Creates a PathClassLoader for the given class path that is associated with a shared
     * namespace, i.e., this classloader can access platform-private native libraries. The
     * classloader will use java.library.path as the native library path.
     */
    static ClassLoader createPathClassLoader(String classPath, int targetSdkVersion) {
        String libraryPath = System.getProperty("java.library.path");
        return ClassLoaderFactory.createClassLoader(classPath, libraryPath, libraryPath, ClassLoader.getSystemClassLoader(), targetSdkVersion, true, /* isNamespaceShared */
        null);
    }

    /**
     * Performs dex-opt on the elements of {@code classPath}, if needed. We
     * choose the instruction set of the current runtime.
     */
    private static void performSystemServerDexOpt(String classPath) {
        final String[] classPathElements = classPath.split(":");
        final IInstalld installd = IInstalld.Stub.asInterface(ServiceManager.getService("installd"));
        final String instructionSet = VMRuntime.getRuntime().vmInstructionSet();
        String classPathForElement = "";
        for (String classPathElement : classPathElements) {
            // System server is fully AOTed and never profiled
            // for profile guided compilation.
            String systemServerFilter = SystemProperties.get("dalvik.vm.systemservercompilerfilter", "speed");
            int dexoptNeeded;
            try {
                dexoptNeeded = DexFile.getDexOptNeeded(classPathElement, instructionSet, systemServerFilter, null, false, false);
            } catch (FileNotFoundException ignored) {
                // Do not add to the classpath.
                Log.w(TAG, "Missing classpath element for system server: " + classPathElement);
                continue;
            } catch (IOException e) {
                // Not fully clear what to do here as we don't know the cause of the
                // IO exception. Add to the classpath to be conservative, but don't
                // attempt to compile it.
                Log.w(TAG, "Error checking classpath element for system server: " + classPathElement, e);
                dexoptNeeded = DexFile.NO_DEXOPT_NEEDED;
            }
            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
                final String packageName = "*";
                final String outputPath = null;
                final int dexFlags = 0;
                final String compilerFilter = systemServerFilter;
                final String uuid = StorageManager.UUID_PRIVATE_INTERNAL;
                final String seInfo = null;
                final String classLoaderContext = getSystemServerClassLoaderContext(classPathForElement);
                // SystemServer targets the system's SDK version
                final int targetSdkVersion = 0;
                try {
                    installd.dexopt(classPathElement, Process.SYSTEM_UID, packageName, instructionSet, dexoptNeeded, outputPath, dexFlags, compilerFilter, uuid, classLoaderContext, seInfo, false, targetSdkVersion, /*profileName*/
                    null, /*dexMetadataPath*/
                    null, "server-dexopt");
                } catch (RemoteException | ServiceSpecificException e) {
                    // Ignore (but log), we need this on the classpath for fallback mode.
                    Log.w(TAG, "Failed compiling classpath element for system server: " + classPathElement, e);
                }
            }
            classPathForElement = encodeSystemServerClassPath(classPathForElement, classPathElement);
        }
    }

    /**
     * Encodes the system server class loader context in a format that is accepted by dexopt.
     * This assumes the system server is always loaded with a {@link dalvik.system.PathClassLoader}.
     *
     * Note that ideally we would use the {@code DexoptUtils} to compute this. However we have no
     * dependency here on the server so we hard code the logic again.
     */
    private static String getSystemServerClassLoaderContext(String classPath) {
        return classPath == null ? "PCL[]" : "PCL[" + classPath + "]";
    }

    /**
     * Encodes the class path in a format accepted by dexopt.
     * @param classPath the old class path (may be empty).
     * @param newElement the new class path elements
     * @return the class path encoding resulted from appending {@code newElement} to
     * {@code classPath}.
     */
    private static String encodeSystemServerClassPath(String classPath, String newElement) {
        return (classPath == null || classPath.isEmpty()) ? newElement : classPath + ":" + newElement;
    }

    /**
     * Prepare the arguments and forks for the system server process.
     *
     * Returns an {@code Runnable} that provides an entrypoint into system_server code in the
     * child process, and {@code null} in the parent.
     */
    private static Runnable forkSystemServer(String abiList, String socketName, ZygoteServer zygoteServer) {
        long capabilities = posixCapabilitiesAsBits(OsConstants.CAP_IPC_LOCK, OsConstants.CAP_KILL, OsConstants.CAP_NET_ADMIN, OsConstants.CAP_NET_BIND_SERVICE, OsConstants.CAP_NET_BROADCAST, OsConstants.CAP_NET_RAW, OsConstants.CAP_SYS_MODULE, OsConstants.CAP_SYS_NICE, OsConstants.CAP_SYS_PTRACE, OsConstants.CAP_SYS_TIME, OsConstants.CAP_SYS_TTY_CONFIG, OsConstants.CAP_WAKE_ALARM, OsConstants.CAP_BLOCK_SUSPEND);
        /* Containers run without some capabilities, so drop any caps that are not available. */
        StructCapUserHeader header = new StructCapUserHeader(OsConstants._LINUX_CAPABILITY_VERSION_3, 0);
        StructCapUserData[] data;

capabilities &= ((long) data[0].effective) | (((long) data[1].effective) << 32);
        /* Hardcoded command line to start the system server */
        String[] args = { "--setuid=1000", "--setgid=1000", "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1024,1032,1065,3001,3002,3003,3006,3007,3009,3010", "--capabilities=" + capabilities + "," + capabilities, "--nice-name=system_server", "--runtime-args", "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT, "com.android.server.SystemServer" };
        ZygoteConnection.Arguments parsedArgs = null;
        int pid;
        try {
            parsedArgs = new ZygoteConnection.Arguments(args);
            ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
            ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
            boolean profileSystemServer = SystemProperties.getBoolean("dalvik.vm.profilesystemserver", false);
            if (profileSystemServer) {
                parsedArgs.runtimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
            }
            /* Request to fork the system server process */
            pid = Zygote.forkSystemServer(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.runtimeFlags, null, parsedArgs.permittedCapabilities, parsedArgs.effectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }
        /* For child process */
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
            zygoteServer.closeServerSocket();
            return handleSystemServerProcess(parsedArgs);
        }
        return null;
    }

    /**
     * Gets the bit array representation of the provided list of POSIX capabilities.
     */
    private static long posixCapabilitiesAsBits(int... capabilities) {
        long result = 0;
        for (int capability : capabilities) {
            if ((capability < 0) || (capability > OsConstants.CAP_LAST_CAP)) {
                throw new IllegalArgumentException(String.valueOf(capability));
            }
            result |= (1L << capability);
        }
        return result;
    }

    public static void main(String[] argv) {
        ZygoteServer zygoteServer = new ZygoteServer();
        // Mark zygote start. This ensures that thread creation will throw
        // an error.
        ZygoteHooks.startZygoteNoThreadCreation();
        // Zygote goes into its own process group.
        try {
            Os.setpgid(0, 0);
        } catch (ErrnoException ex) {
            throw new RuntimeException("Failed to setpgid(0,0)", ex);
        }
        final Runnable caller;
        try {
            // Report Zygote start time to tron unless it is a runtime restart
            if (!"1".equals(SystemProperties.get("sys.boot_completed"))) {
                MetricsLogger.histogram(null, "boot_zygote_init", (int) SystemClock.elapsedRealtime());
            }
            String bootTimeTag = Process.is64Bit() ? "Zygote64Timing" : "Zygote32Timing";
            TimingsTraceLog bootTimingsTraceLog = new TimingsTraceLog(bootTimeTag, Trace.TRACE_TAG_DALVIK);
            bootTimingsTraceLog.traceBegin("ZygoteInit");
            RuntimeInit.enableDdms();
            boolean startSystemServer = false;
            String socketName = "zygote";
            String abiList = null;
            boolean enableLazyPreload = false;
            for (int i = 1; i < argv.length; i++) {
                if ("start-system-server".equals(argv[i])) {
                    startSystemServer = true;
                } else if ("--enable-lazy-preload".equals(argv[i])) {
                    enableLazyPreload = true;
                } else if (argv[i].startsWith(ABI_LIST_ARG)) {
                    abiList = argv[i].substring(ABI_LIST_ARG.length());
                } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
                    socketName = argv[i].substring(SOCKET_NAME_ARG.length());
                } else {
                    throw new RuntimeException("Unknown command line argument: " + argv[i]);
                }
            }
            if (abiList == null) {
                throw new RuntimeException("No ABI list supplied.");
            }
            zygoteServer.registerServerSocketFromEnv(socketName);
            // In some configurations, we avoid preloading resources and classes eagerly.
            // In such cases, we will preload things prior to our first fork.
            if (!enableLazyPreload) {
                bootTimingsTraceLog.traceBegin("ZygotePreload");
                EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START, SystemClock.uptimeMillis());
                preload(bootTimingsTraceLog);
                EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END, SystemClock.uptimeMillis());
                // ZygotePreload
                bootTimingsTraceLog.traceEnd();
            } else {
                Zygote.resetNicePriority();
            }
            // Do an initial gc to clean up after startup
            bootTimingsTraceLog.traceBegin("PostZygoteInitGC");
            gcAndFinalize();
            // PostZygoteInitGC
            bootTimingsTraceLog.traceEnd();
            // ZygoteInit
            bootTimingsTraceLog.traceEnd();
            // Disable tracing so that forked processes do not inherit stale tracing tags from
            Trace.setTracingEnabled(false, 0);
            Zygote.nativeSecurityInit();
            // Zygote process unmounts root storage spaces.
            Zygote.nativeUnmountStorageOnInit();
            ZygoteHooks.stopZygoteNoThreadCreation();
            if (startSystemServer) {
                Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
                // {@code r == null} in the parent (zygote) process, and {@code r != null} in the
                if (r != null) {
                    r.run();
                    return;
                }
            }
            Log.i(TAG, "Accepting command socket connections");
            // The select loop returns early in the child process after a fork and
            // loops forever in the zygote.
            caller = zygoteServer.runSelectLoop(abiList);
        } catch (Throwable ex) {
            Log.e(TAG, "System zygote died with exception", ex);
            throw ex;
        } finally {
            zygoteServer.closeServerSocket();
        }
        // We're in the child process and have exited the select loop. Proceed to execute the
        if (caller != null) {
            caller.run();
        }
    }

    /**
     * Return {@code true} if this device configuration has another zygote.
     *
     * We determine this by comparing the device ABI list with this zygotes
     * list. If this zygote supports all ABIs this device supports, there won't
     * be another zygote.
     */
    private static boolean hasSecondZygote(String abiList) {
        return !SystemProperties.get("ro.product.cpu.abilist").equals(abiList);
    }

    private static void waitForSecondaryZygote(String socketName) {
        String otherZygoteName = Process.ZYGOTE_SOCKET.equals(socketName) ? Process.SECONDARY_ZYGOTE_SOCKET : Process.ZYGOTE_SOCKET;
        ZygoteProcess.waitForConnectionToZygote(otherZygoteName);
    }

    static boolean isPreloadComplete() {
        return sPreloadComplete;
    }

    /**
     * Class not instantiable.
     */
    private ZygoteInit() {
    }

    /**
     * The main function called when started through the zygote process. This
     * could be unified with main(), if the native code in nativeFinishInit()
     * were rationalized with Zygote startup.

     *
     * Current recognized args:
     *

     *
  [--] <start class name>  <args>
     *

     *
     * @param targetSdkVersion target SDK version
     * @param argv arg strings
     */
    public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
        if (RuntimeInit.DEBUG) {
            Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
        }
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
        RuntimeInit.redirectLogStreams();
        RuntimeInit.commonInit();
        ZygoteInit.nativeZygoteInit();
        return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
    }

    /**
     * The main function called when starting a child zygote process. This is used as an
     * alternative to zygoteInit(), which skips calling into initialization routines that
     * start the Binder threadpool.
     */
    static final Runnable childZygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
        RuntimeInit.Arguments args = new RuntimeInit.Arguments(argv);
        return RuntimeInit.findStaticMain(args.startClass, args.startArgs, classLoader);
    }

    private static final native void nativeZygoteInit();
}


try {
            InputStream inputStream = new URL(String.format(JAR_LOCATION, version)).openConnection().getInputStream();
            fromStream(inputStream, factory);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

package uk.co.thinkofdeath.thinkcraft.resources.mojang;

import uk.co.thinkofdeath.thinkcraft.resources.TextureFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class MojangResourceProvider extends ZipResourceProvider {

    private static final String JAR_LOCATION = "http://s3.amazonaws.com/Minecraft.Download/versions/%1$s/%1$s.jar";

    public MojangResourceProvider(String version, TextureFactory factory) {


try {
                dockerClient.removeImageCmd(dockerImageName + ":" + dockerImageTag).withForce(true).exec();
            } catch (NotFoundException e) {
                // just ignore if not exist
            }

package com.azure.resourcemanager.appservice.samples;

import com.azure.core.credential.TokenCredential;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.management.AzureEnvironment;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.resourcemanager.AzureResourceManager;
import com.azure.resourcemanager.appservice.models.PricingTier;
import com.azure.resourcemanager.appservice.models.WebApp;
import com.azure.resourcemanager.containerregistry.models.AccessKeyType;
import com.azure.resourcemanager.containerregistry.models.Registry;
import com.azure.resourcemanager.containerregistry.models.RegistryCredentials;
import com.azure.core.management.Region;
import com.azure.core.management.profile.AzureProfile;
import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils;
import com.azure.resourcemanager.samples.DockerUtils;
import com.azure.resourcemanager.samples.Utils;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.PullImageResultCallback;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.AuthConfig;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.core.command.PushImageResultCallback;
import java.io.IOException;
import java.time.Duration;
import java.util.Date;
import java.util.List;

/**
 * Azure App Service sample for deploying from an Azure Container Registry.
 *    - Create an Azure Container Registry to be used for holding the Docker images
 *    - If a local Docker engine cannot be found, create a Linux virtual machine that will host a Docker engine
 *        to be used for this sample
 *    - Use Docker Java to create a Docker client that will push/pull an image to/from Azure Container Registry
 *    - Pull a test image from the public Docker repo (tomcat:8-jre8) to be used as a sample for pushing/pulling
 *        to/from an Azure Container Registry
 *    - Deploys to a new web app from the Tomcat image
 */
public class ManageLinuxWebAppWithContainerRegistry {

    /**
     * Main function which runs the actual sample.
     *
     * @param azureResourceManager instance of the azure client
     * @return true if sample runs successfully
     */
    public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException, InterruptedException {
        final String rgName = Utils.randomResourceName(azureResourceManager, "rgACR", 15);
        final String acrName = Utils.randomResourceName(azureResourceManager, "acrsample", 20);
        final String appName = Utils.randomResourceName(azureResourceManager, "webapp", 20);
        final String appUrl = appName + ".azurewebsites.net";
        final Region region = Region.US_EAST;
        final String dockerImageName = "tomcat";
        final String dockerImageTag = "8-jre8";
        final String dockerContainerName = "tomcat-private";
        try {
            // Create an Azure Container Registry to store and manage private Docker container images
            System.out.println("Creating an Azure Container Registry");
            Date t1 = new Date();
            Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName).withRegion(region).withNewResourceGroup(rgName).withBasicSku().withRegistryNameAsAdminUser().create();
            Date t2 = new Date();
            System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id());
            Utils.print(azureRegistry);
            // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry
            RegistryCredentials acrCredentials = azureRegistry.getCredentials();
            DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY));
            // Pull a temp image from public Docker repo and create a temporary container from that image
            // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR
            dockerClient.pullImageCmd(dockerImageName).withTag(dockerImageTag).withAuthConfig(new AuthConfig()).exec(new PullImageResultCallback()).awaitCompletion();
            System.out.println("List local Docker images:");
            List<Image> images = dockerClient.listImagesCmd().withShowAll(true).exec();
            for (Image image : images) {
                System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId());
            }
            CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag).withName(dockerContainerName).exec();
            // Commit the new container
            String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName;
            dockerClient.commitCmd(dockerContainerInstance.getId()).withRepository(privateRepoUrl).withTag("latest").exec();
            // We can now remove the temporary container instance
            dockerClient.removeContainerCmd(dockerContainerInstance.getId()).withForce(true).exec();
            // Push the new Docker image to the Azure Container Registry
            dockerClient.pushImageCmd(privateRepoUrl).withAuthConfig(dockerClient.authConfig()).exec(new PushImageResultCallback()).awaitSuccess();
            // Remove the temp image from the local Docker host

            // Create a web app with a new app service plan
            System.out.println("Creating web app " + appName + " in resource group " + rgName + "...");
            WebApp app = azureResourceManager.webApps().define(appName).withRegion(Region.US_WEST).withExistingResourceGroup(rgName).withNewLinuxPlan(PricingTier.STANDARD_S1).withPrivateRegistryImage(privateRepoUrl + ":latest", "http://" + azureRegistry.loginServerUrl()).withCredentials(acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)).withAppSetting("PORT", "8080").create();
            System.out.println("Created web app " + app.name());
            Utils.print(app);
            // warm up
            System.out.println("Warming up " + appUrl + "...");
            Utils.sendGetRequest("http://" + appUrl);
            ResourceManagerUtils.sleep(Duration.ofSeconds(5));
            System.out.println("CURLing " + appUrl + "...");
            System.out.println(Utils.sendGetRequest("http://" + appUrl));
            return true;
        } finally {
            try {
                System.out.println("Deleting Resource Group: " + rgName);
                azureResourceManager.resourceGroups().beginDeleteByName(rgName);
                System.out.println("Deleted Resource Group: " + rgName);
            } catch (NullPointerException npe) {
                System.out.println("Did not create any resources in Azure. No clean up is necessary");
            } catch (Exception g) {
                g.printStackTrace();
            }
        }
    }

    /**
     * Main entry point.
     *
     * @param args the parameters
     */
    public static void main(String[] args) {
        try {
            // Authenticate
            final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
            final TokenCredential credential = new DefaultAzureCredentialBuilder().authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()).build();
            AzureResourceManager azureResourceManager = AzureResourceManager.configure().withLogLevel(HttpLogDetailLevel.BASIC).authenticate(credential, profile).withDefaultSubscription();
            // Print selected subscription
            System.out.println("Selected subscription: " + azureResourceManager.subscriptionId());
            runSample(azureResourceManager);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}


package me.armar.plugins.autorank.commands.conversations.prompts;

/**
 * Interface represents a callback from the {@link ConfirmPrompt}.
 */
public interface ConfirmPromptCallback {

    /**
     * The prompt has been confirmed.
     */
    void promptConfirmed();

    /**
     * The prompt has been denied.
     */


while (root != null) {
            if (p.val > root.val && q.val > root.val) {
                root = root.right;
            } else if (p.val < root.val && q.val < root.val) {
                root = root.left;
            } else {
                return root;
            }
        }

package algorithm.recursion;

/**
 * @author roseduan
 * @time 2020/9/24 9:11 下午
 * @description 二叉搜索树的最近公共祖先
 */
public class BstLowestCommonAncestor {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (p.val > root.val && q.val > root.val) {
            return lowestCommonAncestor(root.right, p, q);
        }
        if (p.val < root.val && q.val < root.val) {
            return lowestCommonAncestor(root.left, p, q);
        }
        return root;
    }

    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {

        return null;
    }

    public class TreeNode {

        int val;

        TreeNode left;

        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}


public boolean contains(T value) {
        if (mQuery != null) {
            Where where = new Where();
            where.setStatement(new Statement(Model.PK, value.getId()));
            SelectStatement query = new SelectStatement();
            query.from(mQuery).where(where);
            return getCount(query) != 0;
        }
        return false;
    }

package com.orm.androrm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import com.orm.androrm.field.NoSuchFieldException;
import com.orm.androrm.statement.InStatement;
import com.orm.androrm.statement.JoinStatement;
import com.orm.androrm.statement.SelectStatement;
import com.orm.androrm.statement.Statement;
import android.content.Context;
import android.database.Cursor;

/**
 * @author Philipp Giese
 */
public class QuerySet<T extends Model> implements Iterable<T> {

    private SelectStatement mQuery;

    private Class<T> mClass;

    private List<T> mItems;

    private DatabaseAdapter mAdapter;

    public QuerySet(Context context, Class<T> model) {
        mClass = model;
        mAdapter = DatabaseAdapter.getInstance(context);
    }

    public void injectQuery(SelectStatement query) {
        mQuery = query;
    }

    private Cursor getCursor(SelectStatement query) {
        mAdapter.open();
        return mAdapter.query(query);
    }

    private void closeConnection(Cursor c) {
        c.close();
        mAdapter.close();
    }

    public T get(int id) {
        Where where = new Where();
        where.setStatement(new Statement(Model.PK, id));
        if (mQuery == null) {
            mQuery = new SelectStatement();
            mQuery.from(DatabaseBuilder.getTableName(mClass));
        }
        mQuery.where(where);
        Cursor c = getCursor(mQuery);
        T object = createObject(c);
        closeConnection(c);
        return object;
    }

    public QuerySet<T> orderBy(String... columns) {
        if (mQuery != null) {
            SelectStatement query = new SelectStatement();
            query.from(mQuery).orderBy(columns);
            mQuery = query;
        }
        return this;
    }

    public QuerySet<T> distinct() {
        if (mQuery != null) {
            mQuery.distinct();
        }
        return this;
    }

    public QuerySet<T> all() {
        if (mQuery == null) {
            mQuery = new SelectStatement();
            mQuery.from(DatabaseBuilder.getTableName(mClass));
        }
        return this;
    }

    public QuerySet<T> filter(Filter filter) throws NoSuchFieldException {
        SelectStatement query = QueryBuilder.buildQuery(mClass, filter.getRules());
        if (mQuery == null) {
            mQuery = query;
        } else {
            JoinStatement join = new JoinStatement();
            join.left(mQuery, "left").right(query, "right").on(Model.PK, Model.PK);
            SelectStatement select = new SelectStatement();
            select.from(join);
            mQuery = select;
        }
        return this;
    }

    public QuerySet<T> limit(int limit) {
        return limit(new Limit(limit));
    }

    public QuerySet<T> limit(int offset, int limit) {
        return limit(new Limit(offset, limit));
    }

    public QuerySet<T> limit(Limit limit) {
        if (mQuery != null) {
            mQuery.limit(limit);
        }
        return this;
    }

    public int count() {
        if (mQuery != null) {
            return getCount(mQuery);
        }
        return all().count();
    }

    private T createObject(Cursor c) {
        T object = null;
        if (c.moveToNext()) {
            object = Model.createObject(mClass, c);
        }
        return object;
    }

    private List<T> createObjects(Cursor c) {
        List<T> items = new ArrayList<T>();
        while (c.moveToNext()) {
            T object = Model.createObject(mClass, c);
            if (object != null) {
                items.add(object);
            }
        }
        return items;
    }

    private List<T> getItems() {
        if (mItems == null) {
            mItems = new ArrayList<T>();
            if (mQuery != null) {
                Cursor c = getCursor(mQuery);
                mItems.addAll(createObjects(c));
                closeConnection(c);
            }
        }
        return mItems;
    }

    @Override
    public Iterator<T> iterator() {
        return getItems().iterator();
    }

    private int getCount(SelectStatement query) {
        SelectStatement countQuery = new SelectStatement();
        countQuery.from(query).count();
        Cursor c = getCursor(countQuery);
        int count = 0;
        if (c.moveToFirst()) {
            count = c.getInt(c.getColumnIndexOrThrow(Model.COUNT));
        }
        closeConnection(c);
        return count;
    }

    /**
     * Checks if the result of this query contains the given
     * object. Note, that this operation will execute the query
     * on the database. Use only, if you have to.
     *
     * @param value
     * @return
     */

    /**
     * See {@link QuerySet#contains}
     * @param values
     * @return
     */
    public boolean containsAll(Collection<T> values) {
        if (mQuery != null) {
            List<Object> ids = new ArrayList<Object>();
            for (T item : values) {
                ids.add(item.getId());
            }
            Where where = new Where();
            where.setStatement(new InStatement(Model.PK, ids));
            SelectStatement query = new SelectStatement();
            query.from(mQuery).where(where);
            return getCount(query) == values.size();
        }
        return false;
    }

    public boolean isEmpty() {
        return count() == 0;
    }

    public List<T> toList() {
        return getItems();
    }
}


while (c.moveToNext()) {
            T object = Model.createObject(mClass, c);
            if (object != null) {
                items.add(object);
            }
        }

package com.orm.androrm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import com.orm.androrm.field.NoSuchFieldException;
import com.orm.androrm.statement.InStatement;
import com.orm.androrm.statement.JoinStatement;
import com.orm.androrm.statement.SelectStatement;
import com.orm.androrm.statement.Statement;
import android.content.Context;
import android.database.Cursor;

/**
 * @author Philipp Giese
 */
public class QuerySet<T extends Model> implements Iterable<T> {

    private SelectStatement mQuery;

    private Class<T> mClass;

    private List<T> mItems;

    private DatabaseAdapter mAdapter;

    public QuerySet(Context context, Class<T> model) {
        mClass = model;
        mAdapter = DatabaseAdapter.getInstance(context);
    }

    public void injectQuery(SelectStatement query) {
        mQuery = query;
    }

    private Cursor getCursor(SelectStatement query) {
        mAdapter.open();
        return mAdapter.query(query);
    }

    private void closeConnection(Cursor c) {
        c.close();
        mAdapter.close();
    }

    public T get(int id) {
        Where where = new Where();
        where.setStatement(new Statement(Model.PK, id));
        if (mQuery == null) {
            mQuery = new SelectStatement();
            mQuery.from(DatabaseBuilder.getTableName(mClass));
        }
        mQuery.where(where);
        Cursor c = getCursor(mQuery);
        T object = createObject(c);
        closeConnection(c);
        return object;
    }

    public QuerySet<T> orderBy(String... columns) {
        if (mQuery != null) {
            SelectStatement query = new SelectStatement();
            query.from(mQuery).orderBy(columns);
            mQuery = query;
        }
        return this;
    }

    public QuerySet<T> distinct() {
        if (mQuery != null) {
            mQuery.distinct();
        }
        return this;
    }

    public QuerySet<T> all() {
        if (mQuery == null) {
            mQuery = new SelectStatement();
            mQuery.from(DatabaseBuilder.getTableName(mClass));
        }
        return this;
    }

    public QuerySet<T> filter(Filter filter) throws NoSuchFieldException {
        SelectStatement query = QueryBuilder.buildQuery(mClass, filter.getRules());
        if (mQuery == null) {
            mQuery = query;
        } else {
            JoinStatement join = new JoinStatement();
            join.left(mQuery, "left").right(query, "right").on(Model.PK, Model.PK);
            SelectStatement select = new SelectStatement();
            select.from(join);
            mQuery = select;
        }
        return this;
    }

    public QuerySet<T> limit(int limit) {
        return limit(new Limit(limit));
    }

    public QuerySet<T> limit(int offset, int limit) {
        return limit(new Limit(offset, limit));
    }

    public QuerySet<T> limit(Limit limit) {
        if (mQuery != null) {
            mQuery.limit(limit);
        }
        return this;
    }

    public int count() {
        if (mQuery != null) {
            return getCount(mQuery);
        }
        return all().count();
    }

    private T createObject(Cursor c) {
        T object = null;
        if (c.moveToNext()) {
            object = Model.createObject(mClass, c);
        }
        return object;
    }

    private List<T> createObjects(Cursor c) {
        List<T> items = new ArrayList<T>();

        return items;
    }

    private List<T> getItems() {
        if (mItems == null) {
            mItems = new ArrayList<T>();
            if (mQuery != null) {
                Cursor c = getCursor(mQuery);
                mItems.addAll(createObjects(c));
                closeConnection(c);
            }
        }
        return mItems;
    }

    @Override
    public Iterator<T> iterator() {
        return getItems().iterator();
    }

    private int getCount(SelectStatement query) {
        SelectStatement countQuery = new SelectStatement();
        countQuery.from(query).count();
        Cursor c = getCursor(countQuery);
        int count = 0;
        if (c.moveToFirst()) {
            count = c.getInt(c.getColumnIndexOrThrow(Model.COUNT));
        }
        closeConnection(c);
        return count;
    }

    /**
     * Checks if the result of this query contains the given
     * object. Note, that this operation will execute the query
     * on the database. Use only, if you have to.
     *
     * @param value
     * @return
     */
    public boolean contains(T value) {
        if (mQuery != null) {
            Where where = new Where();
            where.setStatement(new Statement(Model.PK, value.getId()));
            SelectStatement query = new SelectStatement();
            query.from(mQuery).where(where);
            return getCount(query) != 0;
        }
        return false;
    }

    /**
     * See {@link QuerySet#contains}
     * @param values
     * @return
     */
    public boolean containsAll(Collection<T> values) {
        if (mQuery != null) {
            List<Object> ids = new ArrayList<Object>();
            for (T item : values) {
                ids.add(item.getId());
            }
            Where where = new Where();
            where.setStatement(new InStatement(Model.PK, ids));
            SelectStatement query = new SelectStatement();
            query.from(mQuery).where(where);
            return getCount(query) == values.size();
        }
        return false;
    }

    public boolean isEmpty() {
        return count() == 0;
    }

    public List<T> toList() {
        return getItems();
    }
}


@Override
    public void reset() throws IOException {
        delegate.reset();
    }

package nu.validator.io;

import java.io.IOException;
import java.io.InputStream;

/**
 * @version $Id$
 * @author hsivonen
 */
public final class BoundedInputStream extends InputStream {

    private final InputStream delegate;

    private final String systemId;

    private long counter = 0;

    private long limit;

    /**
     * @param delegate
     * @param limit
     */
    public BoundedInputStream(InputStream delegate, long limit, String systemId) {
        this.delegate = delegate;
        this.limit = limit;
        this.systemId = systemId;
    }

    private void checkLimit() throws IOException {
        if (counter > limit) {
            throw new StreamBoundException("Stream length exceeds limit.", systemId);
        }
    }

    /**
     * @see java.io.InputStream#available()
     */
    @Override
    public int available() throws IOException {
        return delegate.available();
    }

    /**
     * @see java.io.InputStream#close()
     */
    @Override
    public void close() throws IOException {
        delegate.close();
    }

    /**
     * @see java.io.InputStream#mark(int)
     */
    @Override
    public void mark(int arg0) {
        delegate.mark(arg0);
    }

    /**
     * @see java.io.InputStream#markSupported()
     */
    @Override
    public boolean markSupported() {
        return delegate.markSupported();
    }

    /**
     * @see java.io.InputStream#read()
     */
    @Override
    public int read() throws IOException {
        this.checkLimit();
        this.counter++;
        return delegate.read();
    }

    /**
     * @see java.io.InputStream#read(byte[])
     */
    @Override
    public int read(byte[] arg0) throws IOException {
        this.checkLimit();
        int c = delegate.read(arg0);
        this.counter += c;
        return c;
    }

    /**
     * @see java.io.InputStream#read(byte[], int, int)
     */
    @Override
    public int read(byte[] arg0, int arg1, int arg2) throws IOException {
        this.checkLimit();
        int c = delegate.read(arg0, arg1, arg2);
        this.counter += c;
        return c;
    }

    /**
     * @see java.io.InputStream#reset()
     */

    /**
     * @see java.io.InputStream#skip(long)
     */
    @Override
    public long skip(long arg0) throws IOException {
        return delegate.skip(arg0);
    }
}


@Override
        public CharSequence getTextAfterCursor(int n, int flags) {
            return mTextAfter;
        }

package com.android.inputmethod.latin;

import android.content.res.Resources;
import android.inputmethodservice.InputMethodService;
import android.os.Parcel;
import android.test.AndroidTestCase;
import android.test.MoreAsserts;
import android.test.suitebuilder.annotation.SmallTest;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.SuggestionSpan;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;
import com.android.inputmethod.latin.common.Constants;
import com.android.inputmethod.latin.common.StringUtils;
import com.android.inputmethod.latin.settings.SpacingAndPunctuations;
import com.android.inputmethod.latin.utils.NgramContextUtils;
import com.android.inputmethod.latin.utils.RunInLocale;
import com.android.inputmethod.latin.utils.ScriptUtils;
import com.android.inputmethod.latin.utils.TextRange;
import java.util.Locale;

@SmallTest
public class RichInputConnectionAndTextRangeTests extends AndroidTestCase {

    // The following is meant to be a reasonable default for
    private SpacingAndPunctuations mSpacingAndPunctuations;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        final RunInLocale<SpacingAndPunctuations> job = new RunInLocale<SpacingAndPunctuations>() {

            @Override
            protected SpacingAndPunctuations job(final Resources res) {
                return new SpacingAndPunctuations(res);
            }
        };
        final Resources res = getContext().getResources();
        mSpacingAndPunctuations = job.runInLocale(res, Locale.ENGLISH);
    }

    private class MockConnection extends InputConnectionWrapper {

        final CharSequence mTextBefore;

        final CharSequence mTextAfter;

        final ExtractedText mExtractedText;

        public MockConnection(final CharSequence text, final int cursorPosition) {
            super(null, false);
            // Interaction of spans with Parcels is completely non-trivial, but in the actual case
            // the CharSequences do go through Parcels because they go through IPC. There
            // are some significant differences between the behavior of Spanned objects that
            // have and that have not gone through parceling, so it's much easier to simulate
            // the environment with Parcels than try to emulate things by hand.
            final Parcel p = Parcel.obtain();
            TextUtils.writeToParcel(text.subSequence(0, cursorPosition), p, 0);
            TextUtils.writeToParcel(text.subSequence(cursorPosition, text.length()), p, 0);
            final byte[] marshalled = p.marshall();
            p.unmarshall(marshalled, 0, marshalled.length);
            p.setDataPosition(0);
            mTextBefore = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p);
            mTextAfter = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p);
            mExtractedText = null;
            p.recycle();
        }

        public MockConnection(String textBefore, String textAfter, ExtractedText extractedText) {
            super(null, false);
            mTextBefore = textBefore;
            mTextAfter = textAfter;
            mExtractedText = extractedText;
        }

        public int cursorPos() {
            return mTextBefore.length();
        }

        /* (non-Javadoc)
         * @see android.view.inputmethod.InputConnectionWrapper#getTextBeforeCursor(int, int)
         */
        @Override
        public CharSequence getTextBeforeCursor(int n, int flags) {
            return mTextBefore;
        }

        /* (non-Javadoc)
         * @see android.view.inputmethod.InputConnectionWrapper#getTextAfterCursor(int, int)
         */

        /* (non-Javadoc)
         * @see android.view.inputmethod.InputConnectionWrapper#getExtractedText(
         *         ExtractedTextRequest, int)
         */
        @Override
        public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) {
            return mExtractedText;
        }

        @Override
        public boolean beginBatchEdit() {
            return true;
        }

        @Override
        public boolean endBatchEdit() {
            return true;
        }

        @Override
        public boolean finishComposingText() {
            return true;
        }
    }

    static class MockInputMethodService extends InputMethodService {

        private MockConnection mMockConnection;

        public void setInputConnection(final MockConnection mockConnection) {
            mMockConnection = mockConnection;
        }

        public int cursorPos() {
            return mMockConnection.cursorPos();
        }

        @Override
        public InputConnection getCurrentInputConnection() {
            return mMockConnection;
        }
    }

    /**
     * Test for getting previous word (for bigram suggestions)
     */
    public void testGetPreviousWord() {
        // If one of the following cases breaks, the bigram suggestions won't work.
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc def", mSpacingAndPunctuations, 2).getNthPrevWord(1), "abc");
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc", mSpacingAndPunctuations, 2), NgramContext.BEGINNING_OF_SENTENCE);
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc. def", mSpacingAndPunctuations, 2), NgramContext.BEGINNING_OF_SENTENCE);
        assertFalse(NgramContextUtils.getNgramContextFromNthPreviousWord("abc def", mSpacingAndPunctuations, 2).isBeginningOfSentenceContext());
        assertTrue(NgramContextUtils.getNgramContextFromNthPreviousWord("abc", mSpacingAndPunctuations, 2).isBeginningOfSentenceContext());
        // For n-gram
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc def", mSpacingAndPunctuations, 1).getNthPrevWord(1), "def");
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc def", mSpacingAndPunctuations, 1).getNthPrevWord(2), "abc");
        assertTrue(NgramContextUtils.getNgramContextFromNthPreviousWord("abc def", mSpacingAndPunctuations, 2).isNthPrevWordBeginningOfSentence(2));
        // The following tests reflect the current behavior of the function
        // TODO: However at this time, the code does never go
        // into such a path, so it should be safe to change the behavior of
        // this function if needed - especially since it does not seem very
        // logical. These tests are just there to catch any unintentional
        // changes in the behavior of the RichInputConnection#getPreviousWord method.
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc def ", mSpacingAndPunctuations, 2).getNthPrevWord(1), "abc");
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc def.", mSpacingAndPunctuations, 2).getNthPrevWord(1), "abc");
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc def .", mSpacingAndPunctuations, 2).getNthPrevWord(1), "def");
        assertTrue(NgramContextUtils.getNgramContextFromNthPreviousWord("abc ", mSpacingAndPunctuations, 2).isBeginningOfSentenceContext());
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc def", mSpacingAndPunctuations, 1).getNthPrevWord(1), "def");
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc def ", mSpacingAndPunctuations, 1).getNthPrevWord(1), "def");
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc 'def", mSpacingAndPunctuations, 1).getNthPrevWord(1), "'def");
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc def.", mSpacingAndPunctuations, 1), NgramContext.BEGINNING_OF_SENTENCE);
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc def .", mSpacingAndPunctuations, 1), NgramContext.BEGINNING_OF_SENTENCE);
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc, def", mSpacingAndPunctuations, 2), NgramContext.EMPTY_PREV_WORDS_INFO);
        // question mark is treated as the end of the sentence. Hence, beginning of the
        // sentence is expected.
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc? def", mSpacingAndPunctuations, 2), NgramContext.BEGINNING_OF_SENTENCE);
        // Exclamation mark is treated as the end of the sentence. Hence, beginning of the
        // sentence is expected.
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc! def", mSpacingAndPunctuations, 2), NgramContext.BEGINNING_OF_SENTENCE);
        assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord("abc 'def", mSpacingAndPunctuations, 2), NgramContext.EMPTY_PREV_WORDS_INFO);
    }

    public void testGetWordRangeAtCursor() {
        /**
         * Test logic in getting the word range at the cursor.
         */
        final SpacingAndPunctuations SPACE = new SpacingAndPunctuations(mSpacingAndPunctuations, new int[] { Constants.CODE_SPACE });
        final SpacingAndPunctuations TAB = new SpacingAndPunctuations(mSpacingAndPunctuations, new int[] { Constants.CODE_TAB });
        // A character that needs surrogate pair to represent its code point (U+2008A).
        final String SUPPLEMENTARY_CHAR_STRING = "\uD840\uDC8A";
        final SpacingAndPunctuations SUPPLEMENTARY_CHAR = new SpacingAndPunctuations(mSpacingAndPunctuations, StringUtils.toSortedCodePointArray(SUPPLEMENTARY_CHAR_STRING));
        final String HIRAGANA_WORD = "\u3042\u3044\u3046\u3048\u304A";
        final String GREEK_WORD = "\u03BA\u03B1\u03B9";
        ExtractedText et = new ExtractedText();
        final MockInputMethodService mockInputMethodService = new MockInputMethodService();
        final RichInputConnection ic = new RichInputConnection(mockInputMethodService);
        mockInputMethodService.setInputConnection(new MockConnection("word wo", "rd", et));
        et.startOffset = 0;
        et.selectionStart = 7;
        TextRange r;
        ic.beginBatchEdit();
        r = ic.getWordRangeAtCursor(SPACE, ScriptUtils.SCRIPT_LATIN);
        assertTrue(TextUtils.equals("word", r.mWord));
        // tab character instead of space
        mockInputMethodService.setInputConnection(new MockConnection("one\tword\two", "rd", et));
        ic.beginBatchEdit();
        r = ic.getWordRangeAtCursor(TAB, ScriptUtils.SCRIPT_LATIN);
        ic.endBatchEdit();
        assertTrue(TextUtils.equals("word", r.mWord));
        // splitting on supplementary character
        mockInputMethodService.setInputConnection(new MockConnection("one word" + SUPPLEMENTARY_CHAR_STRING + "wo", "rd", et));
        ic.beginBatchEdit();
        r = ic.getWordRangeAtCursor(SUPPLEMENTARY_CHAR, ScriptUtils.SCRIPT_LATIN);
        ic.endBatchEdit();
        assertTrue(TextUtils.equals("word", r.mWord));
        // split on chars outside the specified script
        mockInputMethodService.setInputConnection(new MockConnection(HIRAGANA_WORD + "wo", "rd" + GREEK_WORD, et));
        ic.beginBatchEdit();
        r = ic.getWordRangeAtCursor(SUPPLEMENTARY_CHAR, ScriptUtils.SCRIPT_LATIN);
        ic.endBatchEdit();
        assertTrue(TextUtils.equals("word", r.mWord));
        // likewise for greek
        mockInputMethodService.setInputConnection(new MockConnection("text" + GREEK_WORD, "text", et));
        ic.beginBatchEdit();
        r = ic.getWordRangeAtCursor(SUPPLEMENTARY_CHAR, ScriptUtils.SCRIPT_GREEK);
        ic.endBatchEdit();
        assertTrue(TextUtils.equals(GREEK_WORD, r.mWord));
    }

    /**
     * Test logic in getting the word range at the cursor.
     */
    public void testGetSuggestionSpansAtWord() {
        helpTestGetSuggestionSpansAtWord(10);
        helpTestGetSuggestionSpansAtWord(12);
        helpTestGetSuggestionSpansAtWord(15);
        helpTestGetSuggestionSpansAtWord(16);
    }

    private void helpTestGetSuggestionSpansAtWord(final int cursorPos) {
        final SpacingAndPunctuations SPACE = new SpacingAndPunctuations(mSpacingAndPunctuations, new int[] { Constants.CODE_SPACE });
        final MockInputMethodService mockInputMethodService = new MockInputMethodService();
        final RichInputConnection ic = new RichInputConnection(mockInputMethodService);
        final String[] SUGGESTIONS1 = { "swing", "strong" };
        final String[] SUGGESTIONS2 = { "storing", "strung" };
        // Test the usual case.
        SpannableString text = new SpannableString("This is a string for test");
        text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS1, 0), 10, /* start */
        16, /* end */
        0);
        mockInputMethodService.setInputConnection(new MockConnection(text, cursorPos));
        TextRange r;
        SuggestionSpan[] suggestions;
        r = ic.getWordRangeAtCursor(SPACE, ScriptUtils.SCRIPT_LATIN);
        suggestions = r.getSuggestionSpansAtWord();
        assertEquals(suggestions.length, 1);
        MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1);
        // Test the case with 2 suggestion spans in the same place.
        text = new SpannableString("This is a string for test");
        text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS1, 0), 10, /* start */
        16, /* end */
        0);
        text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS2, 0), 10, /* start */
        16, /* end */
        0);
        mockInputMethodService.setInputConnection(new MockConnection(text, cursorPos));
        r = ic.getWordRangeAtCursor(SPACE, ScriptUtils.SCRIPT_LATIN);
        suggestions = r.getSuggestionSpansAtWord();
        assertEquals(suggestions.length, 2);
        MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1);
        MoreAsserts.assertEquals(suggestions[1].getSuggestions(), SUGGESTIONS2);
        // Test a case with overlapping spans, 2nd extending past the start of the word
        text = new SpannableString("This is a string for test");
        text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS1, 0), 10, /* start */
        16, /* end */
        0);
        text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS2, 0), 5, /* start */
        16, /* end */
        0);
        mockInputMethodService.setInputConnection(new MockConnection(text, cursorPos));
        r = ic.getWordRangeAtCursor(SPACE, ScriptUtils.SCRIPT_LATIN);
        suggestions = r.getSuggestionSpansAtWord();
        assertEquals(suggestions.length, 1);
        MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1);
        // Test a case with overlapping spans, 2nd extending past the end of the word
        text = new SpannableString("This is a string for test");
        text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS1, 0), 10, /* start */
        16, /* end */
        0);
        text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS2, 0), 10, /* start */
        20, /* end */
        0);
        mockInputMethodService.setInputConnection(new MockConnection(text, cursorPos));
        r = ic.getWordRangeAtCursor(SPACE, ScriptUtils.SCRIPT_LATIN);
        suggestions = r.getSuggestionSpansAtWord();
        assertEquals(suggestions.length, 1);
        MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1);
        // Test a case with overlapping spans, 2nd extending past both ends of the word
        text = new SpannableString("This is a string for test");
        text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS1, 0), 10, /* start */
        16, /* end */
        0);
        text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS2, 0), 5, /* start */
        20, /* end */
        0);
        mockInputMethodService.setInputConnection(new MockConnection(text, cursorPos));
        r = ic.getWordRangeAtCursor(SPACE, ScriptUtils.SCRIPT_LATIN);
        suggestions = r.getSuggestionSpansAtWord();
        assertEquals(suggestions.length, 1);
        MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1);
        // Test a case with overlapping spans, none right on the word
        text = new SpannableString("This is a string for test");
        text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS1, 0), 5, /* start */
        16, /* end */
        0);
        text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS2, 0), 5, /* start */
        20, /* end */
        0);
        mockInputMethodService.setInputConnection(new MockConnection(text, cursorPos));
        r = ic.getWordRangeAtCursor(SPACE, ScriptUtils.SCRIPT_LATIN);
        suggestions = r.getSuggestionSpansAtWord();
        assertEquals(suggestions.length, 0);
    }

    public void testCursorTouchingWord() {
        final MockInputMethodService ims = new MockInputMethodService();
        final RichInputConnection ic = new RichInputConnection(ims);
        final SpacingAndPunctuations sap = mSpacingAndPunctuations;
        ims.setInputConnection(new MockConnection("users", 5));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertTrue(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection("users'", 5));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertTrue(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection("users'", 6));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertTrue(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection("'users'", 6));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertTrue(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection("'users'", 7));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertTrue(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection("users '", 6));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertFalse(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection("users '", 7));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertFalse(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection("re-", 3));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertTrue(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection("re--", 4));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertFalse(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection("-", 1));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertFalse(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection("--", 2));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertFalse(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection(" -", 2));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertFalse(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection(" --", 3));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertFalse(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection(" users '", 1));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertTrue(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection(" users '", 3));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertTrue(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection(" users '", 7));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertFalse(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection(" users are", 7));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertTrue(ic.isCursorTouchingWord(sap, true));
        ims.setInputConnection(new MockConnection(" users 'are", 7));
        ic.resetCachesUponCursorMoveAndReturnSuccess(ims.cursorPos(), ims.cursorPos(), true);
        assertFalse(ic.isCursorTouchingWord(sap, true));
    }
}


switch(method) {
            case GET:
                return get(session);
            case POST:
                return post(session);
            case PUT:
                return put(session);
            case DELETE:
                return delete(session);
            case HEAD:
                return head(session);
            case OPTIONS:
                return options(session);
        }

package com.orhanobut;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.ServerRunner;

public class TestServer extends NanoHTTPD implements HttpServer {

    public TestServer() {
        super(9095);
    }

    public static void main(String[] args) {
        ServerRunner.run(TestServer.class);
    }

    @Override
    public Response serve(IHTTPSession session) {
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Method method = session.getMethod();

        return null;
    }

    private static final String DEFAULT_RESPONSE = "{\"name\":\"wasp\"}";

    @Override
    public Response get(IHTTPSession session) {
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }

    @Override
    public Response post(IHTTPSession session) {
        Map<String, String> files = new HashMap<>();
        try {
            session.parseBody(files);
        } catch (IOException ioe) {
            return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
        } catch (ResponseException re) {
            return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
        }
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }

    @Override
    public Response put(IHTTPSession session) {
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }

    @Override
    public Response patch(IHTTPSession session) {
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }

    @Override
    public Response head(IHTTPSession session) {
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }

    @Override
    public Response delete(IHTTPSession session) {
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }

    @Override
    public Response options(IHTTPSession session) {
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }
}


try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

package com.orhanobut;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.ServerRunner;

public class TestServer extends NanoHTTPD implements HttpServer {

    public TestServer() {
        super(9095);
    }

    public static void main(String[] args) {
        ServerRunner.run(TestServer.class);
    }

    @Override
    public Response serve(IHTTPSession session) {

        Method method = session.getMethod();
        switch(method) {
            case GET:
                return get(session);
            case POST:
                return post(session);
            case PUT:
                return put(session);
            case DELETE:
                return delete(session);
            case HEAD:
                return head(session);
            case OPTIONS:
                return options(session);
        }
        return null;
    }

    private static final String DEFAULT_RESPONSE = "{\"name\":\"wasp\"}";

    @Override
    public Response get(IHTTPSession session) {
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }

    @Override
    public Response post(IHTTPSession session) {
        Map<String, String> files = new HashMap<>();
        try {
            session.parseBody(files);
        } catch (IOException ioe) {
            return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
        } catch (ResponseException re) {
            return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
        }
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }

    @Override
    public Response put(IHTTPSession session) {
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }

    @Override
    public Response patch(IHTTPSession session) {
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }

    @Override
    public Response head(IHTTPSession session) {
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }

    @Override
    public Response delete(IHTTPSession session) {
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }

    @Override
    public Response options(IHTTPSession session) {
        return new Response(Response.Status.ACCEPTED, "application/json", DEFAULT_RESPONSE);
    }
}


while (!value.compareAndSet(val, associativeAggregation.combine(val, delta))) {
            val = value.get();
        }

package com.facebook.stats;

import java.util.concurrent.atomic.AtomicLong;
import org.joda.time.Duration;
import org.joda.time.ReadableDateTime;

public class AssociativeAggregationCounter implements EventCounter {

    private final ReadableDateTime start;

    private final ReadableDateTime end;

    private final long initialValue;

    private final AssociativeAggregation associativeAggregation;

    protected final AtomicLong value;

    public AssociativeAggregationCounter(ReadableDateTime start, ReadableDateTime end, AssociativeAggregation associativeAggregation, long initialValue) {
        if (start.isAfter(end)) {
            this.start = end;
            this.end = start;
        } else {
            this.start = start;
            this.end = end;
        }
        this.initialValue = initialValue;
        this.associativeAggregation = associativeAggregation;
        this.value = new AtomicLong(initialValue);
    }

    @Override
    public void add(long delta) {
        long val = value.get();

    }

    @Override
    public long getValue() {
        return value.get();
    }

    @Override
    public ReadableDateTime getStart() {
        return start;
    }

    @Override
    public ReadableDateTime getEnd() {
        return end;
    }

    @Override
    public Duration getLength() {
        return new Duration(start, end);
    }

    @Override
    public EventCounter merge(EventCounter counter) {
        ReadableDateTime mergedStart = start;
        ReadableDateTime mergedEnd = end;
        if (counter.getStart().isBefore(mergedStart)) {
            mergedStart = counter.getStart();
        }
        if (counter.getEnd().isAfter(mergedEnd)) {
            mergedEnd = counter.getEnd();
        }
        AssociativeAggregationCounter mergedCounter = new AssociativeAggregationCounter(mergedStart, mergedEnd, associativeAggregation, initialValue);
        mergedCounter.add(associativeAggregation.combine(value.get(), counter.getValue()));
        return mergedCounter;
    }
}


public Key key() {
        return intent.key();
    }

package org.onosproject.net.intent;

import com.google.common.annotations.Beta;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Abstraction of an intent-related operation, e.g. add, remove, replace.
 */
@Beta
public final class IntentOperation {

    private final Type type;

    private final Intent intent;

    public enum Type {

        /**
         * Indicates that an intent should be added.
         */
        SUBMIT,
        /**
         * Indicates that an intent should be removed.
         */
        WITHDRAW
    }

    /**
     * Creates an intent operation.
     *
     * @param type     operation type
     * @param intent   intent subject
     */
    public IntentOperation(Type type, Intent intent) {
        this.type = checkNotNull(type);
        this.intent = intent;
    }

    /**
     * Returns the type of the operation.
     *
     * @return operation type
     */
    public Type type() {
        return type;
    }

    /**
     * Returns the identifier of the intent to which this operation applies.
     *
     * @return intent identifier
     */
    public IntentId intentId() {
        return intent.id();
    }

    /**
     * Returns the key for this intent.
     *
     * @return key value
     */

    /**
     * Returns the intent to which this operation applied. For remove,
     * this can be null.
     *
     * @return intent that is the subject of the operation; null for remove
     */
    public Intent intent() {
        return intent;
    }

    @Override
    public int hashCode() {
        return Objects.hash(type, intent);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        final IntentOperation other = (IntentOperation) obj;
        return Objects.equals(this.type, other.type) && Objects.equals(this.intent, other.intent);
    }

    @Override
    public String toString() {
        return toStringHelper(this).add("type", type).add("intent", intent).toString();
    }
}


public void validatePropsValue(FacesContext context, UIComponent toValidate, Object value) {
        FacesMessage message = new FacesMessage();
        String val = ((String) value).toUpperCase();
        if (val.isEmpty()) {
            message.setDetail("Cannot be empty");
            throw new ValidatorException(message);
        }
    }

package org.openl.rules.ui.tablewizard;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.faces.validator.ValidatorException;
import javax.validation.GroupSequence;
import org.hibernate.validator.constraints.NotBlank;
import org.openl.rules.lang.xls.XlsSheetSourceCodeModule;
import org.openl.rules.lang.xls.syntax.TableSyntaxNode;
import org.openl.rules.table.properties.ITableProperties;
import org.openl.rules.table.properties.def.TablePropertyDefinition;
import org.openl.rules.table.properties.def.TablePropertyDefinitionUtils;
import org.openl.rules.table.properties.inherit.InheritanceLevel;
import org.openl.rules.table.xls.XlsSheetGridModel;
import org.openl.rules.table.xls.builder.CreateTableException;
import org.openl.rules.table.xls.builder.PropertiesTableBuilder;
import org.openl.rules.table.xls.builder.TableBuilder;
import org.openl.rules.tableeditor.renderkit.TableProperty;
import org.openl.rules.ui.validation.StringPresentedGroup;
import org.openl.rules.ui.validation.StringValidGroup;
import org.openl.rules.ui.validation.TableNameConstraint;
import org.openl.util.StringUtils;

@GroupSequence({ PropertyTableCreationWizard.class, StringPresentedGroup.class, StringValidGroup.class })
public class PropertyTableCreationWizard extends TableCreationWizard {

    private PropertiesBean propertiesManager;

    private String scopeType;

    @NotBlank(message = "Cannot be empty", groups = StringPresentedGroup.class)
    @TableNameConstraint(groups = StringValidGroup.class)
    private String tableName;

    private String categoryName;

    private List<SelectItem> scopeTypes = new ArrayList<>(Arrays.asList(new SelectItem("Module"), new SelectItem("Category")));

    private String categoryNameSelector = "destination";

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getCategoryNameSelector() {
        return categoryNameSelector;
    }

    public void setCategoryNameSelector(String categoryNameSelector) {
        this.categoryNameSelector = categoryNameSelector;
    }

    // Not sure, probably method can be removed
    public List<SelectItem> getCategoryNamesList() {
        List<SelectItem> categoryList = new ArrayList<>();
        Set<String> categories = getAllCategories();
        for (String categoryName : categories) {
            categoryList.add(new SelectItem(// Replace new line by space
            categoryName.replaceAll("[\r\n]", " ")));
        }
        return categoryList;
    }

    // Not sure, probably method can be removed
    private Set<String> getAllCategories() {
        Set<String> categories = new TreeSet<>();
        TableSyntaxNode[] syntaxNodes = WizardUtils.getTableSyntaxNodes();
        for (TableSyntaxNode node : syntaxNodes) {
            ITableProperties tableProperties = node.getTableProperties();
            if (tableProperties != null) {
                String categoryName = tableProperties.getCategory();
                if (StringUtils.isNotBlank(categoryName)) {
                    categories.add(categoryName);
                }
            }
        }
        return categories;
    }

    public List<SelectItem> getSpecificCategoryNameList() {
        List<SelectItem> specCategoryList = new ArrayList<>();
        Set<String> categories = getAllSpecificCategories();
        for (String categoryName : categories) {
            specCategoryList.add(new SelectItem(// Replace new line by space
            categoryName.replaceAll("[\r\n]", " ")));
        }
        return specCategoryList;
    }

    private Set<String> getAllSpecificCategories() {
        Set<String> specificCategories = new TreeSet<>();
        TableSyntaxNode[] syntaxNodes = WizardUtils.getTableSyntaxNodes();
        for (TableSyntaxNode node : syntaxNodes) {
            XlsSheetSourceCodeModule tableModule = node.getXlsSheetSourceCodeModule();
            if (tableModule != null) {
                String categoryName = tableModule.getDisplayName();
                if (StringUtils.isNotBlank(categoryName)) {
                    specificCategories.add(categoryName);
                }
            }
        }
        return specificCategories;
    }

    public PropertiesBean getPropertiesManager() {
        return propertiesManager;
    }

    public List<SelectItem> getScopeTypes() {
        return scopeTypes;
    }

    public void setScopeTypes(List<SelectItem> scopeTypes) {
        this.scopeTypes = scopeTypes;
    }

    public String getScopeType() {
        return scopeType;
    }

    public void setScopeType(String scopeType) {
        this.scopeType = scopeType;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    @Override
    public String next() {
        if (getStep() == 1) {
            // After step two we create PropertiesBean according to specified scope
            propertiesManager = new PropertiesBean(getPropertyNamesList());
        }
        return super.next();
    }

    @Override
    protected void onStart() {
        reset();
        initWorkbooks();
    }

    @Override
    protected void onCancel() {
        reset();
    }

    @Override
    public String getName() {
        return "newTableProperty";
    }

    public List<String> getPropertyNamesList() {
        List<String> propertyNames = new ArrayList<>();
        TablePropertyDefinition[] propDefinitions = TablePropertyDefinitionUtils.getDefaultDefinitionsByInheritanceLevel(InheritanceLevel.valueOf(scopeType.toUpperCase()));
        for (TablePropertyDefinition propDefinition : propDefinitions) {
            String propName = propDefinition.getName();
            List<String> exceptProperties = getExceptProperties();
            if (!exceptProperties.contains(propName)) {
                propertyNames.add(propName);
            }
        }
        return propertyNames;
    }

    private List<String> getExceptProperties() {
        List<String> exceptProps = new ArrayList<>();
        exceptProps.add("scope");
        exceptProps.add("category");
        return exceptProps;
    }

    @Override
    protected void onFinish() throws Exception {
        XlsSheetSourceCodeModule sheetSourceModule = getDestinationSheet();
        String newTableUri = buildTable(sheetSourceModule);
        setNewTableURI(newTableUri);
        getModifiedWorkbooks().add(sheetSourceModule.getWorkbookSource());
        super.onFinish();
    }

    protected String buildTable(XlsSheetSourceCodeModule sourceCodeModule) throws CreateTableException {
        XlsSheetGridModel gridModel = new XlsSheetGridModel(sourceCodeModule);
        PropertiesTableBuilder builder = new PropertiesTableBuilder(gridModel);
        Map<String, Object> properties = buildProperties();
        builder.beginTable(TableBuilder.HEADER_HEIGHT + properties.size());
        builder.writeHeader(tableName);
        builder.writeBody(properties);
        String uri = gridModel.getRangeUri(builder.getTableRegion());
        builder.endTable();
        return uri;
    }

    private String buildCategoryName() {
        if (categoryNameSelector.equals("specific") && StringUtils.isNotBlank(this.categoryName)) {
            return this.categoryName;
        }
        return null;
    }

    @Override
    protected Map<String, Object> buildProperties() {
        Map<String, Object> resultProperties = new LinkedHashMap<>();
        resultProperties.put("scope", scopeType);
        if (InheritanceLevel.CATEGORY.getDisplayName().equals(scopeType)) {
            String categoryName = buildCategoryName();
            if (categoryName != null) {
                resultProperties.put("category", categoryName);
            }
        }
        for (TableProperty property : propertiesManager.getProperties()) {
            String name = property.getName();
            Object value = property.getValue();
            if (value != null && (!(value instanceof String) || StringUtils.isNotEmpty((String) value))) {
                resultProperties.put(name.trim(), value);
            }
        }
        return resultProperties;
    }

    /**
     * Validation for properties value
     */