text:
package org.apache.catalina.deploy;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import javax.naming.NamingException;

import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.Server;
import org.apache.catalina.mbeans.MBeanUtils;
import org.apache.catalina.util.Introspection;
import org.apache.catalina.util.LifecycleMBeanBase;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.naming.ContextBindings;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.res.StringManager;

/**
 * Holds and manages the naming resources defined in the J2EE Enterprise
 * Naming Context and their associated JNDI context.
 *
 * @author Remy Maucherat
 */
public class NamingResources extends LifecycleMBeanBase implements Serializable {

    private static final long serialVersionUID = 1L;

    private static final Log log = LogFactory.getLog(NamingResources.class);

    private static final StringManager sm =
        StringManager.getManager(Constants.Package);

    private volatile boolean resourceRequireExplicitRegistration = false;

    // ----------------------------------------------------------- Constructors

    /**
     * Create a new NamingResources instance.
     */
    public NamingResources() {
        // NOOP
    }

    // ----------------------------------------------------- Instance Variables

    /**
     * Associated container object.
     */
    private Object container = null;

    /**
     * Set of naming entries, keyed by name.
     */
    private Set<String> entries = new HashSet<String>();

    /**
     * The EJB resource references for this web application, keyed by name.
     */
    private HashMap<String, ContextEjb> ejbs =
        new HashMap<String, ContextEjb>();

    /**
     * The environment entries for this web application, keyed by name.
     */
    private HashMap<String, ContextEnvironment> envs =
        new HashMap<String, ContextEnvironment>();

    /**
     * The local  EJB resource references for this web application, keyed by
     * name.
     */
    private HashMap<String, ContextLocalEjb> localEjbs =
        new HashMap<String, ContextLocalEjb>();

    /**
     * The message destination referencess for this web application,
     * keyed by name.
     */
    private HashMap<String, MessageDestinationRef> mdrs =
        new HashMap<String, MessageDestinationRef>();

    /**
     * The resource environment references for this web application,
     * keyed by name.
     */
    private HashMap<String, ContextResourceEnvRef> resourceEnvRefs =
        new HashMap<String, ContextResourceEnvRef>();

    /**
     * The resource references for this web application, keyed by name.
     */
    private HashMap<String, ContextResource> resources =
        new HashMap<String, ContextResource>();

    /**
     * The resource links for this web application, keyed by name.
     */
    private HashMap<String, ContextResourceLink> resourceLinks =
        new HashMap<String, ContextResourceLink>();

    /**
     * The web service references for this web application, keyed by name.
     */
    private HashMap<String, ContextService> services =
        new HashMap<String, ContextService>();

    /**
     * The transaction for this webapp.
     */
    private ContextTransaction transaction = null;

    /**
     * The property change support for this component.
     */
    protected PropertyChangeSupport support = new PropertyChangeSupport(this);

    // ------------------------------------------------------------- Properties

    /**
     * Get the container with which the naming resources are associated.
     */
    public Object getContainer() {
        return container;
    }

    /**
     * Set the container with which the naming resources are associated.
     */
    public void setContainer(Object container) {
        this.container = container;
    }

    /**
     * Set the transaction object.
     */
    public void setTransaction(ContextTransaction transaction) {
        this.transaction = transaction;
    }

    /**
     * Get the transaction object.
     */
    public ContextTransaction getTransaction() {
        return transaction;
    }

    /**
     * Add an EJB resource reference for this web application.
     *
     * @param ejb New EJB resource reference
     */
    public void addEjb(ContextEjb ejb) {

        if (entries.contains(ejb.getName())) {
            return;
        } else {
            entries.add(ejb.getName());
        }

        synchronized (ejbs) {
            ejb.setNamingResources(this);
            ejbs.put(ejb.getName(), ejb);
        }
        support.firePropertyChange("ejb", null, ejb);

    }

    /**
     * Add an environment entry for this web application.
     *
     * @param environment New environment entry
     */
    public void addEnvironment(ContextEnvironment environment) {

        if (entries.contains(environment.getName())) {
            ContextEnvironment ce = findEnvironment(environment.getName());
            ContextResourceLink rl = findResourceLink(environment.getName());
            if (ce != null) {
                if (ce.getOverride()) {
                    removeEnvironment(environment.getName());
                } else {
                    return;
                }
            } else if (rl != null) {
                // Link. Need to look at the global resources
                NamingResources global = getServer().getGlobalNamingResources();
                if (global.findEnvironment(rl.getGlobal()) != null) {
                    if (global.findEnvironment(rl.getGlobal()).getOverride()) {
                        removeResourceLink(environment.getName());
                    } else {
                        return;
                    }
                }
            } else {
                // It exists but it isn't an env or a res link...
                return;
            }
        }

        if (!checkResourceType(environment)) {
            throw new IllegalArgumentException(sm.getString(
                    "namingResources.resourceTypeFail", environment.getName(),
                    environment.getType()));
        }

        entries.add(environment.getName());

        synchronized (envs) {
            environment.setNamingResources(this);
            envs.put(environment.getName(), environment);
        }
        support.firePropertyChange("environment", null, environment);

        // Register with JMX
        if (resourceRequireExplicitRegistration) {
            try {
                MBeanUtils.createMBean(environment);
            } catch (Exception e) {
                log.warn(sm.getString("namingResources.mbeanCreateFail",
                        environment.getName()), e);
            }
        }
    }

    // Container should be an instance of Server or Context. If it is anything
    // else, return null which will trigger a NPE.
    private Server getServer() {
        if (container instanceof Server) {
            return (Server) container;
        }
        if (container instanceof Context) {
            // Could do this in one go. Lots of casts so split out for clarity
            Engine engine =
                (Engine) ((Context) container).getParent().getParent();
            return engine.getService().getServer();
        }
        return null;
    }

    /**
     * Add a local EJB resource reference for this web application.
     *
     * @param ejb New EJB resource reference
     */
    public void addLocalEjb(ContextLocalEjb ejb) {

        if (entries.contains(ejb.getName())) {
            return;
        } else {
            entries.add(ejb.getName());
        }

        synchronized (localEjbs) {
            ejb.setNamingResources(this);
            localEjbs.put(ejb.getName(), ejb);
        }
        support.firePropertyChange("localEjb", null, ejb);

    }

    /**
     * Add a message destination reference for this web application.
     *
     * @param mdr New message destination reference
     */
    public void addMessageDestinationRef(MessageDestinationRef mdr) {

        if (entries.contains(mdr.getName())) {
            return;
        } else {
            if (!checkResourceType(mdr)) {
                throw new IllegalArgumentException(sm.getString(
                        "namingResources.resourceTypeFail", mdr.getName(),
                        mdr.getType()));
            }
            entries.add(mdr.getName());
        }

        synchronized (mdrs) {
            mdr.setNamingResources(this);
            mdrs.put(mdr.getName(), mdr);
        }
        support.firePropertyChange("messageDestinationRef", null, mdr);

    }

    /**
     * Add a property change listener to this component.
     *
     * @param listener The listener to add
     */
    public void addPropertyChangeListener(PropertyChangeListener listener) {

        support.addPropertyChangeListener(listener);

    }

    /**
     * Add a resource reference for this web application.
     *
     * @param resource New resource reference
     */
    public void addResource(ContextResource resource) {

        if (entries.contains(resource.getName())) {
            return;
        } else {
            if (!checkResourceType(resource)) {
                throw new IllegalArgumentException(sm.getString(
                        "namingResources.resourceTypeFail", resource.getName(),
                        resource.getType()));
            }
            entries.add(resource.getName());
        }

        synchronized (resources) {
            resource.setNamingResources(this);
            resources.put(resource.getName(), resource);
        }
        support.firePropertyChange("resource", null, resource);

        // Register with JMX
        if (resourceRequireExplicitRegistration) {
            try {
                MBeanUtils.createMBean(resource);
            } catch (Exception e) {
                log.warn(sm.getString("namingResources.mbeanCreateFail",
                        resource.getName()), e);
            }
        }
    }

    /**
     * Add a resource environment reference for this web application.
     *
     * @param resource The resource
     */
    public void addResourceEnvRef(ContextResourceEnvRef resource) {

        if (entries.contains(resource.getName())) {
            return;
        } else {
            if (!checkResourceType(resource)) {
                throw new IllegalArgumentException(sm.getString(
                        "namingResources.resourceTypeFail", resource.getName(),
                        resource.getType()));
            }
            entries.add(resource.getName());
        }

        synchronized (resourceEnvRefs) {
            resource.setNamingResources(this);
            resourceEnvRefs.put(resource.getName(), resource);
        }
        support.firePropertyChange("resourceEnvRef", null, resource);

    }

    /**
     * Add a resource link for this web application.
     *
     * @param resourceLink New resource link
     */
    public void addResourceLink(ContextResourceLink resourceLink) {

        if (entries.contains(resourceLink.getName())) {
            return;
        } else {
            entries.add(resourceLink.getName());
        }

        synchronized (resourceLinks) {
            resourceLink.setNamingResources(this);
            resourceLinks.put(resourceLink.getName(), resourceLink);
        }
        support.firePropertyChange("resourceLink", null, resourceLink);

        // Register with JMX
        if (resourceRequireExplicitRegistration) {
            try {
                MBeanUtils.createMBean(resourceLink);
            } catch (Exception e) {
                log.warn(sm.getString("namingResources.mbeanCreateFail",
                        resourceLink.getName()), e);
            }
        }
    }

    /**
     * Add a web service reference for this web application.
     *
     * @param service New web service reference
     */
    public void addService(ContextService service) {

        if (entries.contains(service.getName())) {
            return;
        } else {
            entries.add(service.getName());
        }

        synchronized (services) {
            service.setNamingResources(this);
            services.put(service.getName(), service);
        }
        support.firePropertyChange("service", null, service);

    }

    /**
     * Return the EJB resource reference with the specified name, if any;
     * otherwise, return null.
     *
     * @param name Name of the desired EJB resource reference
     */
    public ContextEjb findEjb(String name) {

        synchronized (ejbs) {
            return ejbs.get(name);
        }

    }

    /**
     * Return the defined EJB resource references for this application.
     * If there are none, a zero-length array is returned.
     */
    public ContextEjb[] findEjbs() {

        synchronized (ejbs) {
            ContextEjb results[] = new ContextEjb[ejbs.size()];
            return ejbs.values().toArray(results);
        }

    }

    /**
     * Return the environment entry with the specified name, if any;
     * otherwise, return null.
     *
     * @param name Name of the desired environment entry
     */
    public ContextEnvironment findEnvironment(String name) {

        synchronized (envs) {
            return envs.get(name);
        }

    }

    /**
     * Return the set of defined environment entries for this web
     * application.  If none have been defined, a zero-length array
     * is returned.
     */
    public ContextEnvironment[] findEnvironments() {

        synchronized (envs) {
            ContextEnvironment results[] = new ContextEnvironment[envs.size()];
            return envs.values().toArray(results);
        }

    }

    /**
     * Return the local EJB resource reference with the specified name, if any;
     * otherwise, return null.
     *
     * @param name Name of the desired EJB resource reference
     */
    public ContextLocalEjb findLocalEjb(String name) {

        synchronized (localEjbs) {
            return localEjbs.get(name);
        }

    }

    /**
     * Return the defined local EJB resource references for this application.
     * If there are none, a zero-length array is returned.
     */
    public ContextLocalEjb[] findLocalEjbs() {

        synchronized (localEjbs) {
            ContextLocalEjb results[] = new ContextLocalEjb[localEjbs.size()];
            return localEjbs.values().toArray(results);
        }

    }

    /**
     * Return the message destination reference with the specified name,
     * if any; otherwise, return null.
     *
     * @param name Name of the desired message destination reference
     */
    public MessageDestinationRef findMessageDestinationRef(String name) {

        synchronized (mdrs) {
            return mdrs.get(name);
        }

    }

    /**
     * Return the defined message destination references for this application.
     * If there are none, a zero-length array is returned.
     */
    public MessageDestinationRef[] findMessageDestinationRefs() {

        synchronized (mdrs) {
            MessageDestinationRef results[] =
                new MessageDestinationRef[mdrs.size()];
            return mdrs.values().toArray(results);
        }

    }

    /**
     * Return the resource reference with the specified name, if any;
     * otherwise return null.
     *
     * @param name Name of the desired resource reference
     */
    public ContextResource findResource(String name) {

        synchronized (resources) {
            return resources.get(name);
        }

    }

    /**
     * Return the resource link with the specified name, if any;
     * otherwise return null.
     *
     * @param name Name of the desired resource link
     */
    public ContextResourceLink findResourceLink(String name) {

        synchronized (resourceLinks) {
            return resourceLinks.get(name);
        }

    }

    /**
     * Return the defined resource links for this application.  If
     * none have been defined, a zero-length array is returned.
     */
    public ContextResourceLink[] findResourceLinks() {

        synchronized (resourceLinks) {
            ContextResourceLink results[] =
                new ContextResourceLink[resourceLinks.size()];
            return resourceLinks.values().toArray(results);
        }

    }

    /**
     * Return the defined resource references for this application.  If
     * none have been defined, a zero-length array is returned.
     */
    public ContextResource[] findResources() {

        synchronized (resources) {
            ContextResource results[] = new ContextResource[resources.size()];
            return resources.values().toArray(results);
        }

    }

    /**
     * Return the resource environment reference type for the specified
     * name, if any; otherwise return null.
     *
     * @param name Name of the desired resource environment reference
     */
    public ContextResourceEnvRef findResourceEnvRef(String name) {

        synchronized (resourceEnvRefs) {
            return resourceEnvRefs.get(name);
        }

    }

    /**
     * Return the set of resource environment reference names for this
     * web application.  If none have been specified, a zero-length
     * array is returned.
     */
    public ContextResourceEnvRef[] findResourceEnvRefs() {

        synchronized (resourceEnvRefs) {
            ContextResourceEnvRef results[] = new ContextResourceEnvRef[resourceEnvRefs.size()];
            return resourceEnvRefs.values().toArray(results);
        }

    }

    /**
     * Return the web service reference for the specified
     * name, if any; otherwise return null.
     *
     * @param name Name of the desired web service
     */
    public ContextService findService(String name) {

        synchronized (services) {
            return services.get(name);
        }

    }

    /**
     * Return the defined web service references for this application.  If
     * none have been defined, a zero-length array is returned.
     */
    public ContextService[] findServices() {

        synchronized (services) {
            ContextService results[] = new ContextService[services.size()];
            return services.values().toArray(results);
        }

    }

    /**
     * Return true if the name specified already exists.
     */
    @Deprecated
    public boolean exists(String name) {

        return (entries.contains(name));

    }

    /**
     * Remove any EJB resource reference with the specified name.
     *
     * @param name Name of the EJB resource reference to remove
     */
    public void removeEjb(String name) {

        entries.remove(name);

        ContextEjb ejb = null;
        synchronized (ejbs) {
            ejb = ejbs.remove(name);
        }
        if (ejb != null) {
            support.firePropertyChange("ejb", ejb, null);
            ejb.setNamingResources(null);
        }

    }

    /**
     * Remove any environment entry with the specified name.
     *
     * @param name Name of the environment entry to remove
     */
    public void removeEnvironment(String name) {

        entries.remove(name);

        ContextEnvironment environment = null;
        synchronized (envs) {
            environment = envs.remove(name);
        }
        if (environment != null) {
            support.firePropertyChange("environment", environment, null);
            // De-register with JMX
            if (resourceRequireExplicitRegistration) {
                try {
                    MBeanUtils.destroyMBean(environment);
                } catch (Exception e) {
                    log.warn(sm.getString("namingResources.mbeanDestroyFail",
                            environment.getName()), e);
                }
            }
            environment.setNamingResources(null);
        }
    }

    /**
     * Remove any local EJB resource reference with the specified name.
     *
     * @param name Name of the EJB resource reference to remove
     */
    public void removeLocalEjb(String name) {

        entries.remove(name);

        ContextLocalEjb localEjb = null;
        synchronized (localEjbs) {
            localEjb = localEjbs.remove(name);
        }
        if (localEjb != null) {
            support.firePropertyChange("localEjb", localEjb, null);
            localEjb.setNamingResources(null);
        }

    }

    /**
     * Remove any message destination reference with the specified name.
     *
     * @param name Name of the message destination resource reference to remove
     */
    public void removeMessageDestinationRef(String name) {

        entries.remove(name);

        MessageDestinationRef mdr = null;
        synchronized (mdrs) {
            mdr = mdrs.remove(name);
        }
        if (mdr != null) {
            support.firePropertyChange("messageDestinationRef",
                                       mdr, null);
            mdr.setNamingResources(null);
        }

    }

    /**
     * Remove a property change listener from this component.
     *
     * @param listener The listener to remove
     */
    public void removePropertyChangeListener(PropertyChangeListener listener) {

        support.removePropertyChangeListener(listener);

    }

    /**
     * Remove any resource reference with the specified name.
     *
     * @param name Name of the resource reference to remove
     */
    public void removeResource(String name) {

        entries.remove(name);

        ContextResource resource = null;
        synchronized (resources) {
            resource = resources.remove(name);
        }
        if (resource != null) {
            support.firePropertyChange("resource", resource, null);
            // De-register with JMX
            if (resourceRequireExplicitRegistration) {
                try {
                    MBeanUtils.destroyMBean(resource);
                } catch (Exception e) {
                    log.warn(sm.getString("namingResources.mbeanDestroyFail",
                            resource.getName()), e);
                }
            }
            resource.setNamingResources(null);
        }
    }

    /**
     * Remove any resource environment reference with the specified name.
     *
     * @param name Name of the resource environment reference to remove
     */
    public void removeResourceEnvRef(String name) {

        entries.remove(name);

        ContextResourceEnvRef resourceEnvRef = null;
        synchronized (resourceEnvRefs) {
            resourceEnvRef =
                resourceEnvRefs.remove(name);
        }
        if (resourceEnvRef != null) {
            support.firePropertyChange("resourceEnvRef", resourceEnvRef, null);
            resourceEnvRef.setNamingResources(null);
        }

    }

    /**
     * Remove any resource link with the specified name.
     *
     * @param name Name of the resource link to remove
     */
    public void removeResourceLink(String name) {

        entries.remove(name);

        ContextResourceLink resourceLink = null;
        synchronized (resourceLinks) {
            resourceLink = resourceLinks.remove(name);
        }
        if (resourceLink != null) {
            support.firePropertyChange("resourceLink", resourceLink, null);
            // De-register with JMX
            if (resourceRequireExplicitRegistration) {
                try {
                    MBeanUtils.destroyMBean(resourceLink);
                } catch (Exception e) {
                    log.warn(sm.getString("namingResources.mbeanDestroyFail",
                            resourceLink.getName()), e);
                }
            }
            resourceLink.setNamingResources(null);
        }
    }

    /**
     * Remove any web service reference with the specified name.
     *
     * @param name Name of the web service reference to remove
     */
    public void removeService(String name) {

        entries.remove(name);

        ContextService service = null;
        synchronized (services) {
            service = services.remove(name);
        }
        if (service != null) {
            support.firePropertyChange("service", service, null);
            service.setNamingResources(null);
        }

    }

    // ------------------------------------------------------- Lifecycle methods

    @Override
    protected void initInternal() throws LifecycleException {
        super.initInternal();

        // Set this before we register currently known naming resources to avoid
        // timing issues. Duplication registration is not an issue.
        resourceRequireExplicitRegistration = true;

        for (ContextResource cr : resources.values()) {
            try {
                MBeanUtils.createMBean(cr);
            } catch (Exception e) {
                log.warn(sm.getString(
                        "namingResources.mbeanCreateFail", cr.getName()), e);
            }
        }

        for (ContextEnvironment ce : envs.values()) {
            try {
                MBeanUtils.createMBean(ce);
            } catch (Exception e) {
                log.warn(sm.getString(
                        "namingResources.mbeanCreateFail", ce.getName()), e);
            }
        }

        for (ContextResourceLink crl : resourceLinks.values()) {
            try {
                MBeanUtils.createMBean(crl);
            } catch (Exception e) {
                log.warn(sm.getString(
                        "namingResources.mbeanCreateFail", crl.getName()), e);
            }
        }
    }

    @Override
    protected void startInternal() throws LifecycleException {
        fireLifecycleEvent(CONFIGURE_START_EVENT, null);
        setState(LifecycleState.STARTING);
    }

    @Override
    protected void stopInternal() throws LifecycleException {
        cleanUp();
        setState(LifecycleState.STOPPING);
        fireLifecycleEvent(CONFIGURE_STOP_EVENT, null);
    }

    /**
     * Close those resources that an explicit close may help clean-up faster.
     */
    private void cleanUp() {
        if (resources.size() == 0) {
            return;
        }
        javax.naming.Context ctxt;
        try {
            if (container instanceof Server) {
                ctxt = ((Server) container).getGlobalNamingContext();
            } else {
                ctxt = ContextBindings.getClassLoader();
                ctxt = (javax.naming.Context) ctxt.lookup("comp/env");
            }
        } catch (NamingException e) {
            log.warn(sm.getString("namingResources.cleanupNoContext",
                    container), e);
            return;
        }
        for (ContextResource cr: resources.values()) {
            if (cr.getSingleton()) {
                String closeMethod = cr.getCloseMethod();
                if (closeMethod != null && closeMethod.length() > 0) {
                    String name = cr.getName();
                    Object resource;
                    try {
                         resource = ctxt.lookup(name);
                    } catch (NamingException e) {
                        log.warn(sm.getString(
                                "namingResources.cleanupNoResource",
                                cr.getName(), container), e);
                        continue;
                    }
                    cleanUp(resource, name, closeMethod);
                }
            }
        }
    }

    /**
     * Clean up a resource by calling the defined close method. For example,
     * closing a database connection pool will close it's open connections. This
     * will happen on GC but that leaves db connections open that may cause
     * issues.
     *
     * @param resource  The resource to close.
     */
    private void cleanUp(Object resource, String name, String closeMethod) {
        // Look for a zero-arg close() method
        Method m = null;
        try {
            m = resource.getClass().getMethod(closeMethod, (Class<?>[]) null);
        } catch (SecurityException e) {
            log.debug(sm.getString("namingResources.cleanupCloseSecurity",
                    closeMethod, name, container));
            return;
        } catch (NoSuchMethodException e) {
            log.debug(sm.getString("namingResources.cleanupNoClose",
                    name, container, closeMethod));
            return;
        }
        try {
            m.invoke(resource, (Object[]) null);
        } catch (IllegalArgumentException e) {
            log.warn(sm.getString("namingResources.cleanupCloseFailed",
                    closeMethod, name, container), e);
        } catch (IllegalAccessException e) {
            log.warn(sm.getString("namingResources.cleanupCloseFailed",
                    closeMethod, name, container), e);
        } catch (InvocationTargetException e) {
            Throwable t = ExceptionUtils.unwrapInvocationTargetException(e);
            ExceptionUtils.handleThrowable(t);
            log.warn(sm.getString("namingResources.cleanupCloseFailed",
                    closeMethod, name, container), t);
        }
    }

    @Override
    protected void destroyInternal() throws LifecycleException {

        // Set this before we de-register currently known naming resources to
        // avoid timing issues. Duplication de-registration is not an issue.
        resourceRequireExplicitRegistration = false;

        // Destroy in reverse order to create, although it should not matter
        for (ContextResourceLink crl : resourceLinks.values()) {
            try {
                MBeanUtils.destroyMBean(crl);
            } catch (Exception e) {
                log.warn(sm.getString(
                        "namingResources.mbeanDestroyFail", crl.getName()), e);
            }
        }

        for (ContextEnvironment ce : envs.values()) {
            try {
                MBeanUtils.destroyMBean(ce);
            } catch (Exception e) {
                log.warn(sm.getString(
                        "namingResources.mbeanDestroyFail", ce.getName()), e);
            }
        }

        for (ContextResource cr : resources.values()) {
            try {
                MBeanUtils.destroyMBean(cr);
            } catch (Exception e) {
                log.warn(sm.getString(
                        "namingResources.mbeanDestroyFail", cr.getName()), e);
            }
        }

        super.destroyInternal();
    }

    @Override
    protected String getDomainInternal() {
        // Use the same domain as our associated container if we have one
        Object c = getContainer();

        if (c instanceof LifecycleMBeanBase) {
            return ((LifecycleMBeanBase) c).getDomain();
        }

        return null;
    }

    @Override
    protected String getObjectNameKeyProperties() {
        Object c = getContainer();
        if (c instanceof Container) {
            return "type=NamingResources" +
                    MBeanUtils.getContainerKeyProperties((Container) c);
        }
        // Server or just unknown
        return "type=NamingResources";
    }

    /**
     * Checks that the configuration of the type for the specified resource is
     * consistent with any injection targets and if the type is not specified,
     * tries to configure the type based on the injection targets
     *
     * @param resource  The resource to check
     *
     * @return  true if the type for the resource is now valid (if
     *          previously null this means it is now set) or
     *          false if the current resource type is inconsistent
     *          with the injection targets and/or cannot be determined
     */
    private boolean checkResourceType(ResourceBase resource) {
        if (!(container instanceof Context)) {
            // Only Context's will have injection targets
            return true;
        }

        if (resource.getInjectionTargets() == null ||
                resource.getInjectionTargets().size() == 0) {
            // No injection targets so use the defined type for the resource
            return true;
        }

        Context context = (Context) container;

        String typeName = resource.getType();
        Class<?> typeClass = null;
        if (typeName != null) {
            typeClass = Introspection.loadClass(context, typeName);
            if (typeClass == null) {
                // Can't load the type - will trigger a failure later so don't
                // fail here
                return true;
            }
        }

        Class<?> compatibleClass =
                getCompatibleType(context, resource, typeClass);
        if (compatibleClass == null) {
            // Indicates that a compatible type could not be identified that
            // worked for all injection targets
            return false;
        }

        resource.setType(compatibleClass.getCanonicalName());
        return true;
    }

    private Class<?> getCompatibleType(Context context,
            ResourceBase resource, Class<?> typeClass) {

        Class<?> result = null;

        for (InjectionTarget injectionTarget : resource.getInjectionTargets()) {
            Class<?> clazz = Introspection.loadClass(
                    context, injectionTarget.getTargetClass());
            if (clazz == null) {
                // Can't load class - therefore ignore this target
                continue;
            }

            // Look for a match
            String targetName = injectionTarget.getTargetName();
            // Look for a setter match first
            Class<?> targetType = getSetterType(clazz, targetName);
            if (targetType == null) {
                // Try a field match if no setter match
                targetType = getFieldType(clazz,targetName);
            }
            if (targetType == null) {
                // No match - ignore this injection target
                continue;
            }
            targetType = Introspection.convertPrimitiveType(targetType);

            if (typeClass == null) {
                // Need to find a common type amongst the injection targets
                if (result == null) {
                    result = targetType;
                } else if (targetType.isAssignableFrom(result)) {
                    // NO-OP - This will work
                } else if (result.isAssignableFrom(targetType)) {
                    // Need to use more specific type
                    result = targetType;
                } else {
                    // Incompatible types
                    return null;
                }
            } else {
                // Each injection target needs to be consistent with the defined
                // type
                if (targetType.isAssignableFrom(typeClass)) {
                    result = typeClass;
                } else {
                    // Incompatible types
                    return null;
                }
            }
        }
        return result;
    }

    private Class<?> getSetterType(Class<?> clazz, String name) {
        Method[] methods = Introspection.getDeclaredMethods(clazz);
        if (methods != null && methods.length > 0) {
            for (Method method : methods) {
                if (Introspection.isValidSetter(method) &&
                        Introspection.getPropertyName(method).equals(name)) {
                    return method.getParameterTypes()[0];
                }
            }
        }
        return null;
    }

    private Class<?> getFieldType(Class<?> clazz, String name) {
        Field[] fields = Introspection.getDeclaredFields(clazz);
        if (fields != null && fields.length > 0) {
            for (Field field : fields) {
                if (field.getName().equals(name)) {
                    return field.getType();
                }
            }
        }
        return null;
    }
}


text:
package de.perdian.ant.webstart.elements;

import org.w3c.dom.Element;

import de.perdian.ant.webstart.JnlpTask;

public class PackageElement implements ConfigurationElement {

  private String myName = null;
  private String myPart = null;
  private Boolean myRecursive = null;

  @Override
  public void appendXml(JnlpTask task, Element parentElement) {
    Element packageElement = ConfigurationHelper.appendElement(parentElement, "package");
    ConfigurationHelper.appendAttributeIfNotNull(packageElement, "name", this.getName());
    ConfigurationHelper.appendAttributeIfNotNull(packageElement, "part", this.getPart());
    ConfigurationHelper.appendAttributeIfNotNull(packageElement, "recursive", this.getRecursive());
  }

  // ---------------------------------------------------------------------------
  // --- Property access methods -----------------------------------------------
  // ---------------------------------------------------------------------------

  public String getName() {
    return this.myName;
  }
  public void setName(String name) {
    this.myName = name;
  }

  public String getPart() {
    return this.myPart;
  }
  public void setPart(String part) {
    this.myPart = part;
  }

  public Boolean getRecursive() {
    return this.myRecursive;
  }
  public void setRecursive(Boolean recursive) {
    this.myRecursive = recursive;
  }

}

redpajama_set_name: RedPajamaGithub


text:
<title>Learning WebGL — lesson 4</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">

    << Back to Lesson 4

    <canvas id="lesson04-canvas" style="border: none;" width="500" height="500"></canvas>

    << Back to Lesson 4


text:
<?php

/**
 * Created by PhpStorm.
 * User: ford
 * Date: 2017/3/30
 * Time: 21:04
 */
namespace Waters\WebChatApi\Msg;

abstract class WxRespMessage
{

    protected $ToUserName;
    protected $FromUserName;
    protected $CreateTime;
    protected $MsgType;

    function __construct()
    {
        $this->CreateTime = time();
    }

    public abstract function output();

}


text:
require 'fileutils'
require 'shellwords'

#  This script will find out the timestamps stored by the camera and print them
#  out along with the filenames. If the camera used some weird format to a legible
# time format , for example my Cybershot stores timestamps as 2013.04.12 15:39:38,
# they are be converted to 2013-04-12 15:39:38
directory = Dir.new(Dir.pwd)
puts "Building manifest..."
manifest = "[" + directory.entries.select { |file| file.match(/JPG$/) }.map do |photo_filename|
  timestamp = `identify -format "%[exif:DateTimeOriginal]" #{Shellwords.escape photo_filename}`
  timestamp.gsub! /([0-9]{4}).([0-9]{2}).([0-9]{2})/, '\1-\2-\3'
  "{ :filename => \"#{photo_filename}\", :timestamp => \"#{ timestamp }\" }"
end.join(", ") + "]"
puts manifest


text:
import { UNKNOWN_RESPONSE, FILE_NOT_FOUND } from './error-types'
import { errorFactory } from '../request/factory'
import { requiredParam, requiredTypes } from '../utils'
import command from '../command'

/** @ignore */
function parse (response) {
  let text = response.text.trim()
  let lines = text.split('\n')
  let header = lines.shift()
  let footer = lines.pop()
  let configText = lines.join('\n').trim()
  if (!header.startsWith('Loading config override file: ')) {
    throw new Error(`Undefined response header`)
  }
  if (!footer.startsWith('config override file executed')) {
    throw new Error(`Undefined response footer`)
  }
  let config = []
  let description = []
  lines.forEach(line => {
    line = line.trim()
    if (line.startsWith(';')) {
      description.push(line.slice(1).trim().replace(/:$/, ''))
    } else {
      config.push({
        gcode: line,
        description: description.join('\n')
      })
      description = []
    }
    console.log(line)
  })
  return { file: header.slice(30, -3), configText, config }
}

/**
 * Send [ load <file> ] command.
 *
 * - See {@link post}, {@link request} and {@link command} for more details.
 *
 * @param {Object} params               - Params...
 * @param {String} params.address       - Board address without protocol
 * @param {String} [params.file = null] - File path (default '/sd/config-override')
 * @param {...any} ...rest              - Optional params passed to {@link command} request
 *
 * @return {Promise<responsePayload|RequestError>}
 *
 * @throws {RequestError} {@link FILE_NOT_FOUND}
 * @throws {RequestError} {@link UNKNOWN_RESPONSE}
 *
 * @see https://github.com/Smoothieware/Smoothieware/blob/9e5477518b1c85498a68e81be894faea45d6edca/src/modules/utils/simpleshell/SimpleShell.cpp#L533
 *
 * @example
 * [EXAMPLE ../../examples/loadConfig.js]
 */
export default function loadConfig ({
  address = requiredParam('address'),
  file = null,
  ...rest
} = {}) {
  requiredTypes('address', address, ['string'])
  requiredTypes('file', file, ['null', 'string'])
  const params = {
    ...rest,
    address,
    file,
    command: `load ${file || ''}`
  }
  return command(params).then(response => {
    let text = response.text.trim()
    if (text.startsWith('File not found: ')) {
      throw errorFactory({
        ...response,
        type: FILE_NOT_FOUND,
        message: `File not found [ ${file} ]`
      })
    }
    try {
      response.data = parse(response)
    } catch (error) {
      throw errorFactory({
        ...response,
        type: UNKNOWN_RESPONSE,
        message: error.message
      })
    }
    // allaways return the response
    return response
  })
}


text:
package solidserver

import (
	"encoding/json"
	"fmt"
	"github.com/hashicorp/terraform/helper/schema"
	"log"
	"net/url"
	"strings"
)

func resourceapplication() *schema.Resource {
	return &schema.Resource{
		Create: resourceapplicationCreate,
		Read:   resourceapplicationRead,
		Update: resourceapplicationUpdate,
		Delete: resourceapplicationDelete,
		Exists: resourceapplicationExists,
		Importer: &schema.ResourceImporter{
			State: resourceapplicationImportState,
		},

		Schema: map[string]*schema.Schema{
			"name": {
				Type:        schema.TypeString,
				Description: "The name of the application to create.",
				Required:    true,
				ForceNew:    true,
			},
			"fqdn": {
				Type:        schema.TypeString,
				Description: "The Fully Qualified Domain Name of the application to create.",
				Required:    true,
				ForceNew:    true,
			},
			"gslb_members": {
				Type:        schema.TypeList,
				Description: "The names of the GSLB servers applying the application traffic policy.",
				Required:    true,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
			},
			"class": {
				Type:        schema.TypeString,
				Description: "The class associated to the application.",
				Optional:    true,
				ForceNew:    false,
				Default:     "",
			},
			"class_parameters": {
				Type:        schema.TypeMap,
				Description: "The class parameters associated to application.",
				Optional:    true,
				ForceNew:    false,
				Default:     map[string]string{},
			},
		},
	}
}

func resourceapplicationExists(d *schema.ResourceData, meta interface{}) (bool, error) {
	s := meta.(*SOLIDserver)

	// Building parameters
	parameters := url.Values{}
	parameters.Add("appapplication_id", d.Id())

	if s.Version < 710 {
		// Reporting a failure
		return false, fmt.Errorf("SOLIDServer - Object not supported in this SOLIDserver version")
	}

	log.Printf("[DEBUG] Checking existence of application (oid): %s\n", d.Id())

	// Sending read request
	resp, body, err := s.Request("get", "rest/app_application_info", &parameters)

	if err == nil {
		var buf [](map[string]interface{})
		json.Unmarshal([]byte(body), &buf)

		// Checking answer
		if (resp.StatusCode == 200 || resp.StatusCode == 201) && len(buf) > 0 {
			return true, nil
		}

		if len(buf) > 0 {
			if errMsg, errExist := buf[0]["errmsg"].(string); errExist {
				log.Printf("[DEBUG] SOLIDServer - Unable to find application (oid): %s (%s)\n", d.Id(), errMsg)
			}
		} else {
			log.Printf("[DEBUG] SOLIDServer - Unable to find application (oid): %s\n", d.Id())
		}

		// Unset local ID
		d.SetId("")
	}

	// Reporting a failure
	return false, err
}

func resourceapplicationCreate(d *schema.ResourceData, meta interface{}) error {
	s := meta.(*SOLIDserver)

	// Building parameters
	parameters := url.Values{}
	parameters.Add("add_flag", "new_only")
	parameters.Add("name", d.Get("name").(string))
	parameters.Add("fqdn", d.Get("fqdn").(string))
	parameters.Add("appapplication_class_name", d.Get("class").(string))
	parameters.Add("appapplication_class_parameters", urlfromclassparams(d.Get("class_parameters")).Encode())

	// Building GSLB server list
	GSLBList := ""
	for _, GSLB := range toStringArray(d.Get("gslb_members").([]interface{})) {
		GSLBList += GSLB + ";"
	}
	parameters.Add("gslbserver_list", GSLBList)

	if s.Version < 710 {
		// Reporting a failure
		return fmt.Errorf("SOLIDServer - Object not supported in this SOLIDserver version")
	}

	// Sending creation request
	resp, body, err := s.Request("post", "rest/app_application_add", &parameters)

	if err == nil {
		var buf [](map[string]interface{})
		json.Unmarshal([]byte(body), &buf)

		// Checking the answer
		if (resp.StatusCode == 200 || resp.StatusCode == 201) && len(buf) > 0 {
			if oid, oidExist := buf[0]["ret_oid"].(string); oidExist {
				log.Printf("[DEBUG] SOLIDServer - Created application (oid): %s\n", oid)
				d.SetId(oid)
				return nil
			}
		}

		// Reporting a failure
		if len(buf) > 0 {
			if errMsg, errExist := buf[0]["errmsg"].(string); errExist {
				return fmt.Errorf("SOLIDServer - Unable to create application: %s (%s)", d.Get("name").(string), errMsg)
			}
		}

		return fmt.Errorf("SOLIDServer - Unable to create application: %s\n", d.Get("name").(string))
	}

	// Reporting a failure
	return err
}

func resourceapplicationUpdate(d *schema.ResourceData, meta interface{}) error {
	s := meta.(*SOLIDserver)

	// Building parameters
	parameters := url.Values{}
	parameters.Add("appapplication_id", d.Id())
	parameters.Add("add_flag", "edit_only")
	parameters.Add("name", d.Get("name").(string))
	parameters.Add("fqdn", d.Get("fqdn").(string))
	parameters.Add("appapplication_class_name", d.Get("class").(string))
	parameters.Add("appapplication_class_parameters", urlfromclassparams(d.Get("class_parameters")).Encode())

	// Building GSLB server list
	GSLBList := ""
	for _, GSLB := range toStringArray(d.Get("gslb_members").([]interface{})) {
		GSLBList += GSLB + ";"
	}
	parameters.Add("gslbserver_list", GSLBList)

	if s.Version < 710 {
		// Reporting a failure
		return fmt.Errorf("SOLIDServer - Object not supported in this SOLIDserver version")
	}

	// Sending the update request
	resp, body, err := s.Request("put", "rest/app_application_add", &parameters)

	if err == nil {
		var buf [](map[string]interface{})
		json.Unmarshal([]byte(body), &buf)

		// Checking the answer
		if (resp.StatusCode == 200 || resp.StatusCode == 201) && len(buf) > 0 {
			if oid, oidExist := buf[0]["ret_oid"].(string); oidExist {
				log.Printf("[DEBUG] SOLIDServer - Updated application (oid): %s\n", oid)
				d.SetId(oid)
				return nil
			}
		}

		// Reporting a failure
		if len(buf) > 0 {
			if errMsg, errExist := buf[0]["errmsg"].(string); errExist {
				return fmt.Errorf("SOLIDServer - Unable to update application: %s (%s)", d.Get("name").(string), errMsg)
			}
		}

		return fmt.Errorf("SOLIDServer - Unable to update application: %s\n", d.Get("name").(string))
	}

	// Reporting a failure
	return err
}

func resourceapplicationDelete(d *schema.ResourceData, meta interface{}) error {
	s := meta.(*SOLIDserver)

	// Building parameters
	parameters := url.Values{}
	parameters.Add("appapplication_id", d.Id())

	if s.Version < 710 {
		// Reporting a failure
		return fmt.Errorf("SOLIDServer - Object not supported in this SOLIDserver version")
	}

	// Sending the deletion request
	resp, body, err := s.Request("delete", "rest/app_application_delete", &parameters)

	if err == nil {
		var buf [](map[string]interface{})
		json.Unmarshal([]byte(body), &buf)

		// Checking the answer
		if resp.StatusCode != 200 && resp.StatusCode != 204 {
			// Reporting a failure
			if len(buf) > 0 {
				if errMsg, errExist := buf[0]["errmsg"].(string); errExist {
					return fmt.Errorf("SOLIDServer - Unable to delete application: %s (%s)", d.Get("name").(string), errMsg)
				}
			}

			return fmt.Errorf("SOLIDServer - Unable to delete application: %s", d.Get("name").(string))
		}

		// Log deletion
		log.Printf("[DEBUG] SOLIDServer - Deleted application (oid): %s\n", d.Id())

		// Unset local ID
		d.SetId("")

		// Reporting a success
		return nil
	}

	// Reporting a failure
	return err
}

func resourceapplicationRead(d *schema.ResourceData, meta interface{}) error {
	s := meta.(*SOLIDserver)

	// Building parameters
	parameters := url.Values{}
	parameters.Add("appapplication_id", d.Id())

	if s.Version < 710 {
		// Reporting a failure
		return fmt.Errorf("SOLIDServer - Object not supported in this SOLIDserver version")
	}

	// Sending the read request
	resp, body, err := s.Request("get", "rest/app_application_info", &parameters)

	if err == nil {
		var buf [](map[string]interface{})
		json.Unmarshal([]byte(body), &buf)

		// Checking the answer
		if resp.StatusCode == 200 && len(buf) > 0 {
			d.Set("name", buf[0]["appapplication_name"].(string))
			d.Set("fqdn", buf[0]["appapplication_fqdn"].(string))
			d.Set("class", buf[0]["appapplication_class_name"].(string))

			// Updating gslb_members information
			if buf[0]["appapplication_gslbserver_list"].(string) != "" {
				d.Set("gslb_members", toStringArrayInterface(strings.Split(strings.TrimSuffix(buf[0]["appapplication_gslbserver_list"].(string), ","), ",")))
			}

			// Updating local class_parameters
			currentClassParameters := d.Get("class_parameters").(map[string]interface{})
			retrievedClassParameters, _ := url.ParseQuery(buf[0]["appapplication_class_parameters"].(string))
			computedClassParameters := map[string]string{}

			for ck := range currentClassParameters {
				if rv, rvExist := retrievedClassParameters[ck]; rvExist {
					computedClassParameters[ck] = rv[0]
				} else {
					computedClassParameters[ck] = ""
				}
			}

			d.Set("class_parameters", computedClassParameters)

			return nil
		}

		if len(buf) > 0 {
			if errMsg, errExist := buf[0]["errmsg"].(string); errExist {
				// Log the error
				log.Printf("[DEBUG] SOLIDServer - Unable to find application: %s (%s)\n", d.Get("name"), errMsg)
			}
		} else {
			// Log the error
			log.Printf("[DEBUG] SOLIDServer - Unable to find application (oid): %s\n", d.Id())
		}

		// Do not unset the local ID to avoid inconsistency

		// Reporting a failure
		return fmt.Errorf("SOLIDServer - Unable to find application: %s\n", d.Get("name").(string))
	}

	// Reporting a failure
	return err
}

func resourceapplicationImportState(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
	s := meta.(*SOLIDserver)

	// Building parameters
	parameters := url.Values{}
	parameters.Add("appapplication_id", d.Id())

	if s.Version < 710 {
		// Reporting a failure
		return nil, fmt.Errorf("SOLIDServer - Object not supported in this SOLIDserver version")
	}

	// Sending the read request
	resp, body, err := s.Request("get", "rest/app_application_info", &parameters)

	if err == nil {
		var buf [](map[string]interface{})
		json.Unmarshal([]byte(body), &buf)

		// Checking the answer
		if resp.StatusCode == 200 && len(buf) > 0 {
			d.Set("name", buf[0]["appapplication_name"].(string))
			d.Set("fqdn", buf[0]["appapplication_fqdn"].(string))
			d.Set("class", buf[0]["appapplication_class_name"].(string))

			// Updating gslb_members information
			if buf[0]["appapplication_gslbserver_list"].(string) != "" {
				d.Set("gslb_members", toStringArrayInterface(strings.Split(strings.TrimSuffix(buf[0]["appapplication_gslbserver_list"].(string), ","), ",")))
			}

			// Updating local class_parameters
			currentClassParameters := d.Get("class_parameters").(map[string]interface{})
			retrievedClassParameters, _ := url.ParseQuery(buf[0]["appapplication_class_parameters"].(string))
			computedClassParameters := map[string]string{}

			for ck := range currentClassParameters {
				if rv, rvExist := retrievedClassParameters[ck]; rvExist {
					computedClassParameters[ck] = rv[0]
				} else {
					computedClassParameters[ck] = ""
				}
			}

			d.Set("class_parameters", computedClassParameters)

			return []*schema.ResourceData{d}, nil
		}

		if len(buf) > 0 {
			if errMsg, errExist := buf[0]["errmsg"].(string); errExist {
				log.Printf("[DEBUG] SOLIDServer - Unable to import application(oid): %s (%s)\n", d.Id(), errMsg)
			}
		} else {
			log.Printf("[DEBUG] SOLIDServer - Unable to find and import application (oid): %s\n", d.Id())
		}

		// Reporting a failure
		return nil, fmt.Errorf("SOLIDServer - Unable to find and import application (oid): %s\n", d.Id())
	}

	// Reporting a failure
	return nil, err
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>vial-parent</artifactId>
        <groupId>io.machinecode.vial</groupId>
        <version>0.0.2-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>vial-build-plugin</artifactId>
    <packaging>maven-plugin</packaging>

    <dependencies>
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>ST4</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugin-tools</groupId>
            <artifactId>maven-plugin-annotations</artifactId>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-plugin-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>default-descriptor</id>
                            <phase>none</phase>
                            <goals>
                                <goal>descriptor</goal>
                            </goals>
                            <configuration>
                                <goalPrefix>vial-build</goalPrefix>
                            </configuration>
                        </execution>
                        <execution>
                            <id>generate-helpmojo</id>
                            <phase>none</phase>
                            <goals>
                                <goal>helpmojo</goal>
                            </goals>
                            <configuration>
                                <helpPackageName>io.machinecode.vial.build</helpPackageName>
                                <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.plexus</groupId>
                    <artifactId>plexus-component-metadata</artifactId>
                    <executions>
                        <execution>
                            <id>generate-metadata</id>
                            <phase>none</phase>
                            <goals>
                                <goal>generate-metadata</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-javadoc-plugin</artifactId>
                    <configuration>
                        <additionalparam>-Xdoclint:none</additionalparam>
                        <tagletArtifacts>
                            <tagletArtifact>
                                <groupId>org.apache.maven.plugin-tools</groupId>
                                <artifactId>maven-plugin-tools-javadoc</artifactId>
                                <version>${version.org.apache.maven.plugin-tools.maven-plugin-tools-javadoc}</version>
                            </tagletArtifact>
                            <tagletArtifact>
                                <groupId>org.codehaus.plexus</groupId>
                                <artifactId>plexus-component-javadoc</artifactId>
                                <version>${version.org.codehaus.plexus.plexus-component-javadoc}</version>
                            </tagletArtifact>
                        </tagletArtifacts>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-plugin-plugin</artifactId>
                <executions>
                    <execution>
                        <id>default-descriptor</id>
                        <phase>process-classes</phase>
                    </execution>
                    <execution>
                        <id>generate-helpmojo</id>
                        <phase>process-classes</phase>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.plexus</groupId>
                <artifactId>plexus-component-metadata</artifactId>
                <executions>
                    <execution>
                        <id>generate-metadata</id>
                        <phase>process-classes</phase>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Web.Script.Serialization;
using System.Xml.Serialization;
using DodoNet.Utility;

namespace DodoNet
{
	/// <summary>
	/// Descripción breve de Serialization.
	/// </summary>
	public class Serialization
	{
		public static BinaryFormatter formatter = new BinaryFormatter();

		/// <summary>
		/// serializar un objeto
		/// </summary>
		/// <param name="o"></param>
		/// <returns></returns>
		public static Stream Serialize(object o)
		{
			try
			{
				MemoryStream ret = new MemoryStream();
				formatter.Serialize(ret, o);
				return ret;
			}
			catch ( Exception err )
			{
				throw err;
			}
		}

		/// <summary>
		/// deserializar el objeto
		/// </summary>
		/// <param name="__s"></param>
		/// <returns></returns>
		public static object Deserialize(Stream __s)
		{
			try
			{
				__s.Position = 0;
				return formatter.Deserialize(__s);
			}
			catch ( Exception err )
			{
				throw err;
			}
		}

        public static JavaScriptSerializer Json()
        {
            return new JavaScriptSerializer(new GenericResolver());
        }
	}
}


text:
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Android.App;
using Android.Content;
using Android.OS;
using Sensus.Callbacks;
using System.Threading.Tasks;
using Sensus.Extensions;
using Sensus.Notifications;

namespace Sensus.Android.Callbacks
{
    public class AndroidCallbackScheduler : CallbackScheduler
    {
        private AndroidSensusService _service;

        public AndroidCallbackScheduler(AndroidSensusService service)
        {
            _service = service;
        }

        protected override Task RequestLocalInvocationAsync(ScheduledCallback callback)
        {
            Intent callbackIntent = CreateCallbackIntent(callback);
            PendingIntent callbackPendingIntent = CreateCallbackPendingIntent(callbackIntent);
            ScheduleCallbackAlarm(callback, callbackPendingIntent);
            SensusServiceHelper.Get().Logger.Log("Callback " + callback.Id + " scheduled for " + callback.NextExecution + " " + (callback.RepeatDelay.HasValue ? "(repeating)" : "(one-time)") + ".", LoggingLevel.Normal, GetType());
            return Task.CompletedTask;
        }

        private Intent CreateCallbackIntent(ScheduledCallback callback)
        {
            Intent callbackIntent = new Intent(_service, typeof(AndroidSensusService));
            callbackIntent.SetAction(callback.Id);
            callbackIntent.PutExtra(SENSUS_CALLBACK_KEY, true);
            callbackIntent.PutExtra(SENSUS_CALLBACK_INVOCATION_ID_KEY, callback.InvocationId);
            return callbackIntent;
        }

        private PendingIntent CreateCallbackPendingIntent(Intent callbackIntent)
        {
            // intent extras are not considered when checking equality. thus, the only way we'll get equal pending intents is
            // if the intent action (i.e., callback id) is the same. this should not happen, but if it does we should probably
            // cancel the previously issued (current) intent with the one we are here constructing and are about to pass to the
            // alarm manager. see the following for more information:
            //
            // https://developer.android.com/reference/android/app/PendingIntent.html
            //
            return PendingIntent.GetService(_service, 0, callbackIntent, PendingIntentFlags.CancelCurrent);
        }

        private void ScheduleCallbackAlarm(ScheduledCallback callback, PendingIntent callbackPendingIntent)
        {
            AlarmManager alarmManager = _service.GetSystemService(global::Android.Content.Context.AlarmService) as AlarmManager;

            // cancel the current alarm for this callback id. this deals with the situations where (1) sensus schedules callbacks
            // and is subsequently restarted, or (2) a probe is restarted after scheduling callbacks (e.g., script runner). in
            // these situations, the originally scheduled callbacks will remain in the alarm manager, and we'll begin piling up
            // additional, duplicate alarms. we need to be careful to avoid duplicate alarms, and this is how we manage it.
            alarmManager.Cancel(callbackPendingIntent);

            long callbackTimeMS = callback.NextExecution.Value.ToJavaCurrentTimeMillis();

            // see the Backwards Compatibility article for more information
#if __ANDROID_23__
            if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent);  // API level 23 added "while idle" option, making things even tighter.
            }
            else if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
            {
                alarmManager.SetExact(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent);  // API level 19 differentiated Set (loose) from SetExact (tight)
            }
            else
#endif
            {
                alarmManager.Set(AlarmType.RtcWakeup, callbackTimeMS, callbackPendingIntent);  // API 1-18 treats Set as a tight alarm
            }

            SensusServiceHelper.Get().Logger.Log("Alarm scheduled for callback " + callback.Id + " at " + callback.NextExecution.Value + ".", LoggingLevel.Normal, GetType());
        }

        public ScheduledCallback TryGetCallback(Intent intent)
        {
            if (IsCallback(intent))
            {
                return TryGetCallback(intent.Action);
            }
            else
            {
                return null;
            }
        }

        public bool IsCallback(Intent intent)
        {
            return intent.GetBooleanExtra(SENSUS_CALLBACK_KEY, false);
        }

        public async Task RaiseCallbackAsync(Intent intent)
        {
            ScheduledCallback callback = TryGetCallback(intent.Action);

            if (callback == null)
            {
                return;
            }

            SensusServiceHelper serviceHelper = SensusServiceHelper.Get();

            // if the user removes the main activity from the switcher, the service's process will be killed and restarted without notice, and
            // we'll have no opportunity to unschedule repeating callbacks. when the service is restarted we'll reinitialize the service
            // helper, restart the repeating callbacks, and we'll then have duplicate repeating callbacks. handle the invalid callbacks below.
            // if the callback is present, it's fine. if it's not, then unschedule it.
            if (ContainsCallback(callback))
            {
                string invocationId = intent.GetStringExtra(SENSUS_CALLBACK_INVOCATION_ID_KEY);

                await RaiseCallbackAsync(callback, invocationId);
            }
            else
            {
                await UnscheduleCallbackAsync(callback);
            }
        }

        protected override void CancelLocalInvocation(ScheduledCallback callback)
        {
            // we don't need a reference to the original pending intent in order to cancel the alarm. we just need a pending intent
            // with the same request code and underlying intent with the same action. extras are not considered, and we don't use
            // the other intent fields (data, categories, etc.). see the following for more information:
            //
            // https://developer.android.com/reference/android/app/PendingIntent.html
            //
            Intent callbackIntent = CreateCallbackIntent(callback);
            PendingIntent callbackPendingIntent = CreateCallbackPendingIntent(callbackIntent);
            AlarmManager alarmManager = _service.GetSystemService(global::Android.Content.Context.AlarmService) as AlarmManager;
            alarmManager.Cancel(callbackPendingIntent);
            SensusServiceHelper.Get().Logger.Log("Unscheduled alarm for callback " + callback.Id + ".", LoggingLevel.Normal, GetType());
        }
    }
}


text:
$(function(){
	$("#frm-shell").submit(function(event){

		event.preventDefault();

		var input = $(this).find("input");

		var shell = $(this).parent().parent().parent();
		var data = $(this).serializeArray();

		$.ajax({
			url: "adapter.php",
			type: 'post',
			data: data,
			dataType: 'json',
			error: function(a,b,c) {
				alert(b);
			},
			beforeSend: function() {
				input.attr("readonly", "readonly");
			},
			success: function(response)
			{
				shell.children(".body").append("
$: " + input.val() + "
");
				shell.children(".body").append("
" + response["message"] + "
");
				input.val(""); $("#prompt").text(response["path"]+"#");
				$('.shell')[0].scrollTop = 9999999;
			},
			complete: function() {
				input.removeAttr("readonly");
			}
		});

	});
});


text:
        <!--Import User stylesheets -->
        <?php
            echo link_tag('public/css/custombuilder.css');
        ?>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Tetraria bachmannii Kük.

### Remarks
null


text:
namespace StraightSql
{
	using Npgsql;
	using System;

	public interface IQueryParameterBuilder
	{
		IQuery Build();
		IQueryParameterBuilder SetLiteral(String name, String value);
		IQueryParameterBuilder SetParameter(NpgsqlParameter npgsqlParameter);
	}
}


text:
#include <spatialite_private.h>

/* declaring prototypes */
SPATIALITE_PRIVATE void initialize_epsg_00 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_01 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_02 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_03 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_04 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_05 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_06 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_07 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_08 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_09 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_10 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_11 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_12 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_13 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_14 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_15 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_16 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_17 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_18 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_19 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_20 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_21 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_22 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_23 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_24 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_25 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_26 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_27 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_28 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_29 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_30 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_31 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_32 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_33 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_34 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_35 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_36 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_37 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_38 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_39 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_40 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_wgs84_00 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_wgs84_01 (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_prussian (
	int filter, struct epsg_defs **first, struct epsg_defs **last);
SPATIALITE_PRIVATE void initialize_epsg_extra (
	int filter, struct epsg_defs **first, struct epsg_defs **last);

SPATIALITE_PRIVATE void
initialize_epsg_extra (int filter, struct epsg_defs **first, struct epsg_defs **last)

{
/* initializing the EPSG defs list [EXTRA] */
    struct epsg_defs *p;
    p = add_epsg_def (filter, first, last, 40000, "gfoss.it", 1,
        "Italy mainland zone 1 GB Roma40");
    add_proj4text (p, 0,
        "+proj=tmerc+lat_0=0 +lon_0=9  +k=0.9996 +x_0=1500000 +y_");
    add_proj4text (p, 1,
        "0=0 +ellps=intl +units=m +towgs84=-104.1,-49.1,-9.9,0.97");
    add_proj4text (p, 2, "1,-2.917,0.714,-11.68 +no_defs");
    add_srs_wkt (p, 0, "");
    p = add_epsg_def (filter, first, last, 40001, "gfoss.it", 2,
        "Italy mainland zone 2 GB Roma40");
    add_proj4text (p, 0,
        "+proj=tmerc +lat_0=0 +lon_0=15 +k=0.9996 +x_0=2520000 +y");
    add_proj4text (p, 1,
        "_0=0 +ellps=intl +units=m +towgs84=-104.1,-49.1,-9.9,0.9");
    add_proj4text (p, 2, "71,-2.917,0.714,-11.68 +no_defs");
    add_srs_wkt (p, 0, "");
    p = add_epsg_def (filter, first, last, 40002, "gfoss.it", 3,
        "Italy Sardinia GB Roma40");
    add_proj4text (p, 0,
        "+proj=tmerc +lat_0=0 +lon_0=9  +k=0.9996 +x_0=1500000 +y");
    add_proj4text (p, 1,
        "_0=0 +ellps=intl +units=m +towgs84=-168.6,-34.0,38.6,-0.");
    add_proj4text (p, 2, "374,-0.679,-1.379,-9.48 +no_defs");
    add_srs_wkt (p, 0, "");
    p = add_epsg_def (filter, first, last, 40003, "gfoss.it", 4,
        "Italy Sicily GB Roma40");
    add_proj4text (p, 0,
        "+proj=tmerc +lat_0=0 +lon_0=9  +k=0.9996 +x_0=1500000 +y");
    add_proj4text (p, 1,
        "_0=0 +ellps=intl +units=m +towgs84=-50.2,-50.4,84.8,-0.6");
    add_proj4text (p, 2, "90,-2.012,0.459,-28.08  +no_defs");
    add_srs_wkt (p, 0, "");
}

SPATIALITE_PRIVATE void
initialize_epsg (int filter, struct epsg_defs **first, struct epsg_defs **last)
{
/* initializing the EPSG defs list */
    struct epsg_defs *p;
 /* initializing the EPSG UNKNOWN def [-1] */
    p = add_epsg_def (filter, first, last, -1, "NONE", -1, "Undefined - Cartesian");
    add_proj4text (p, 0, "");
    add_srs_wkt (p, 0, "");
    p = add_epsg_def (filter, first, last, 0, "NONE", 0, "Undefined - Geographic Long/Lat");
    add_proj4text (p, 0, "");
    add_srs_wkt (p, 0, "");

    if (filter != GAIA_EPSG_WGS84_ONLY)
    {
#ifndef OMIT_EPSG    /* full EPSG initialization enabled */
        initialize_epsg_00 (filter, first, last);
        initialize_epsg_01 (filter, first, last);
        initialize_epsg_02 (filter, first, last);
        initialize_epsg_03 (filter, first, last);
        initialize_epsg_04 (filter, first, last);
        initialize_epsg_05 (filter, first, last);
        initialize_epsg_06 (filter, first, last);
        initialize_epsg_07 (filter, first, last);
        initialize_epsg_08 (filter, first, last);
        initialize_epsg_09 (filter, first, last);
        initialize_epsg_10 (filter, first, last);
        initialize_epsg_11 (filter, first, last);
        initialize_epsg_12 (filter, first, last);
        initialize_epsg_13 (filter, first, last);
        initialize_epsg_14 (filter, first, last);
        initialize_epsg_15 (filter, first, last);
        initialize_epsg_16 (filter, first, last);
        initialize_epsg_17 (filter, first, last);
        initialize_epsg_18 (filter, first, last);
        initialize_epsg_19 (filter, first, last);
        initialize_epsg_20 (filter, first, last);
        initialize_epsg_21 (filter, first, last);
        initialize_epsg_22 (filter, first, last);
        initialize_epsg_23 (filter, first, last);
        initialize_epsg_24 (filter, first, last);
        initialize_epsg_25 (filter, first, last);
        initialize_epsg_26 (filter, first, last);
        initialize_epsg_27 (filter, first, last);
        initialize_epsg_28 (filter, first, last);
        initialize_epsg_29 (filter, first, last);
        initialize_epsg_30 (filter, first, last);
        initialize_epsg_31 (filter, first, last);
        initialize_epsg_32 (filter, first, last);
        initialize_epsg_33 (filter, first, last);
        initialize_epsg_34 (filter, first, last);
        initialize_epsg_35 (filter, first, last);
        initialize_epsg_36 (filter, first, last);
        initialize_epsg_37 (filter, first, last);
        initialize_epsg_38 (filter, first, last);
        initialize_epsg_39 (filter, first, last);
        initialize_epsg_40 (filter, first, last);
        initialize_epsg_prussian (filter, first, last);
        initialize_epsg_extra (filter, first, last);
#endif /* full EPSG initialization enabled/disabled */
    }
    initialize_epsg_wgs84_00 (filter, first, last);
    initialize_epsg_wgs84_01 (filter, first, last);
}


text:
package ru.yandex.qatools.allure.data;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import ru.yandex.qatools.allure.data.io.ReportWriter;
import ru.yandex.qatools.allure.data.plugins.PluginManager;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static ru.yandex.qatools.matchers.nio.PathMatchers.contains;
import static ru.yandex.qatools.matchers.nio.PathMatchers.hasFilesCount;

/**
 * @author Dmitry Baev charlie@yandex-team.ru
 *         Date: 19.02.15
 */
public class AllureReportGeneratorTest {

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    @Test
    public void shouldGenerateWithoutFailures() throws Exception {
        AllureReportGenerator generator = new AllureReportGenerator(new File("target/allure-results"));
        File outputDirectory = folder.newFolder();
        generator.generate(outputDirectory);

        Path dataDirectory = outputDirectory.toPath().resolve(ReportWriter.DATA_DIRECTORY_NAME);
        assertTrue("Data directory should be created", Files.exists(dataDirectory));

        assertThat(dataDirectory, contains("xunit.json"));
        assertThat(dataDirectory, contains("timeline.json"));
        assertThat(dataDirectory, contains("behaviors.json"));
        assertThat(dataDirectory, contains("defects.json"));
        assertThat(dataDirectory, contains("graph.json"));
        assertThat(dataDirectory, contains(PluginManager.WIDGETS_JSON));
        assertThat(dataDirectory, contains(ReportWriter.REPORT_JSON));

        assertThat(dataDirectory, hasFilesCount(15, "*-attachment*"));
        assertThat(dataDirectory, hasFilesCount(321, "*-testcase.json"));
    }

    @Test(expected = ReportGenerationException.class)
    public void shouldFailIfNoResults() throws Exception {
        AllureReportGenerator generator = new AllureReportGenerator(folder.newFolder());
        generator.generate(folder.newFolder());
    }

    @Test(expected = ReportGenerationException.class)
    public void shouldFailIfNoResultsDirectory() throws Exception {
        AllureReportGenerator generator = new AllureReportGenerator(
                new File(folder.newFolder(), "unknown-directory"));
        generator.generate(folder.newFolder());
    }
}


text:
using namespace std;

namespace
{
  ///////////////////////// map_key_to_button ///////////////////////////////
  HandmadePlatform::GameButton *map_key_to_button(HandmadePlatform::GameController &input, int key)
  {
    switch (key)
    {
      case 0x01000012:
        return &input.move_left;

      case 0x01000013:
        return &input.move_up;

      case 0x01000014:
        return &input.move_right;

      case 0x01000015:
        return &input.move_down;

      default:
        return nullptr;
    }
  }
}

namespace HandmadePlatform
{

  //|---------------------- GameMemory --------------------------------------
  //|------------------------------------------------------------------------

  ///////////////////////// GameMemory::initialise ////////////////////////////
  void gamememory_initialise(GameMemory &pool, void *data, size_t capacity)
  {
    pool.size = 0;
    pool.data = data;
    pool.capacity = capacity;

    std::align(alignof(max_align_t), 0, pool.data, pool.capacity);
  }

  //|---------------------- Input Buffer ------------------------------------
  //|------------------------------------------------------------------------

  ///////////////////////// InputBuffer::Constructor ////////////////////////
  InputBuffer::InputBuffer()
  {
    m_input = {};
  }

  ///////////////////////// InputBuffer::register_mousemove /////////////////
  void InputBuffer::register_mousemove(int x, int y)
  {
    lock_guard<mutex> lock(m_mutex);

    m_events.push_back({ EventType::MouseMoveX, x });
    m_events.push_back({ EventType::MouseMoveY, y });
  }

  ///////////////////////// InputBuffer::register_keydown ///////////////////
  void InputBuffer::register_keydown(int key)
  {
    lock_guard<mutex> lock(m_mutex);

    m_events.push_back({ EventType::KeyDown, key });
  }

  ///////////////////////// InputBuffer::register_keyup /////////////////////
  void InputBuffer::register_keyup(int key)
  {
    lock_guard<mutex> lock(m_mutex);

    m_events.push_back({ EventType::KeyUp, key });
  }

  ///////////////////////// InputBuffer::grab ///////////////////////////////
  GameInput InputBuffer::grab()
  {
    lock_guard<mutex> lock(m_mutex);

    // Keyboard
    m_input.controllers[0].move_up.transitions = 0;
    m_input.controllers[0].move_down.transitions = 0;
    m_input.controllers[0].move_left.transitions = 0;
    m_input.controllers[0].move_right.transitions = 0;

    for(auto &evt : m_events)
    {
      switch(evt.type)
      {
        case EventType::KeyDown:
          {
            auto button = map_key_to_button(m_input.controllers[0], evt.data);

            if (button)
            {
              button->state = true;
              button->transitions += 1;
            }

            break;
          }

        case EventType::KeyUp:
          {
            auto button = map_key_to_button(m_input.controllers[0], evt.data);

            if (button)
            {
              button->state = false;
              button->transitions += 1;
            }

            break;
          }

        case EventType::MouseMoveX:
          m_input.mousex = evt.data;
          break;

        case EventType::MouseMoveY:
          m_input.mousey = evt.data;
          break;

        case EventType::MouseMoveZ:
          m_input.mousez = evt.data;
          break;

        case EventType::MousePress:
          break;

        case EventType::MouseRelease:
          break;
      }
    }

    m_events.clear();

    return m_input;
  }

  //|---------------------- WorkQueue ---------------------------------------
  //|------------------------------------------------------------------------

  ///////////////////////// WorkQueue::Constructor //////////////////////////
  WorkQueue::WorkQueue(int threads)
  {
    m_done = false;

    for(int i = 0; i < threads; ++i)
    {
      m_threads.push_back(std::thread([=]() {

        while (!m_done)
        {
          std::function<void()> work;

          {
            unique_lock<std::mutex> lock(m_mutex);

            while (m_queue.empty())
            {
              m_signal.wait(lock);
            }

            work = std::move(m_queue.front());

            m_queue.pop_front();
          }

          work();
        }

      }));
    }
  }

  ///////////////////////// WorkQueue::Destructor ///////////////////////////
  WorkQueue::~WorkQueue()
  {
    for(size_t i = 0; i < m_threads.size(); ++i)
      push([=]() { m_done = true; });

    for(auto &thread : m_threads)
      thread.join();
  }

  //|---------------------- PlatformCore ------------------------------------
  //|------------------------------------------------------------------------

  ///////////////////////// PlatformCore::Constructor ///////////////////////
  PlatformCore::PlatformCore()
  {
    m_terminaterequested = false;
  }

  ///////////////////////// PlatformCore::initialise ////////////////////////
  void PlatformCore::initialise(std::size_t gamememorysize)
  {
    m_gamememory.reserve(gamememorysize);
    m_gamescratchmemory.reserve(256*1024*1024);
    m_renderscratchmemory.reserve(256*1024*1024);

    gamememory_initialise(gamememory, m_gamememory.data(), m_gamememory.capacity());

    gamememory_initialise(gamescratchmemory, m_gamescratchmemory.data(), m_gamescratchmemory.capacity());

    gamememory_initialise(renderscratchmemory, m_renderscratchmemory.data(), m_renderscratchmemory.capacity());
  }

  ///////////////////////// PlatformCore::read_handle ///////////////////////
  void PlatformCore::read_handle(PlatformInterface::handle_t handle, uint64_t position, void *buffer, size_t n)
  {
    auto file = static_cast<platform_handle_t*>(handle);

    lock_guard<mutex> lock(file->lock);

    file->fio.seekg(position);

    file->fio.read((char*)buffer, n);

    if (!file->fio)
      throw runtime_error("Data Read Error");
  }

  ///////////////////////// PlatformCore::close_handle //////////////////////
  void PlatformCore::close_handle(PlatformInterface::handle_t handle)
  {
    delete static_cast<platform_handle_t*>(handle);
  }

  ///////////////////////// PlatformCore::open_type_enumerator //////////////
  PlatformInterface::type_enumerator PlatformCore::open_type_enumerator(const char *type)
  {
    auto directory = new platform_type_enumerator;

    directory->type = string(".") + string(type);
    directory->iterator = filesystem::directory_iterator(".");

    return directory;
  }

  ///////////////////////// PlatformCore::iterate_type_enumerator ///////////
  PlatformInterface::handle_t PlatformCore::iterate_type_enumerator(PlatformInterface::type_enumerator enumerator)
  {
    auto directory = static_cast<platform_type_enumerator*>(enumerator);

    platform_handle_t *handle = nullptr;

    while (!handle && directory->iterator != filesystem::directory_iterator())
    {
      if (directory->iterator->extention() == directory->type)
      {
        handle = new platform_handle_t;

        handle->fio.open(directory->iterator->string(), ios::in | ios::binary);
      }

      ++directory->iterator;
    }

    return handle;
  }

  ///////////////////////// PlatformCore::close_type_enumerator /////////////
  void PlatformCore::close_type_enumerator(PlatformInterface::type_enumerator enumerator)
  {
    delete static_cast<platform_type_enumerator*>(enumerator);
  }

  ///////////////////////// PlatformCore::submit_work ///////////////////////
  void PlatformCore::submit_work(void (*func)(PlatformInterface &, void*, void*), void *ldata, void *rdata)
  {
    m_workqueue.push([=]() { func(*this, ldata, rdata); });
  }

  ///////////////////////// PlatformCore::terminate /////////////////////////
  void PlatformCore::terminate()
  {
    m_terminaterequested = true;
  }

} // namespace


text:
var Matcher = require('minimatch').Minimatch;
var SEP = require('path').sep;
var chalk = require('chalk');

const DEFAULT_EXCLUDES = '**/{.git,.hg,.svn,.DS_Store,*.pem}';

var Filter = function(excludeGlob) {
    excludeGlob = excludeGlob || DEFAULT_EXCLUDES;
    var matcher = new Matcher(excludeGlob);

    return function(path) {
        var stdPath = path.replace(SEP, '/');

        var skip = matcher.match(stdPath);
        if (skip) {
            console.log(chalk.yellow('Skipping', path));
        }

        return !skip;
    };
};

module.exports = Filter;


text:
<!DOCTYPE html>

<title>Classe QInputContextFactory</title>

Classe QInputContextFactory

Derivada de

Classes derivadas:

Módulo QtGui

Método estático: QInputContextFactory():create(QString, QObject * ) -> QInputContext *

Método estático: QInputContextFactory():description(QString ) -> QString

Método estático: QInputContextFactory():displayName(QString ) -> QString

Método estático: QInputContextFactory():keys( ) -> QStringList

Método estático: QInputContextFactory():languages(QString ) -> QStringList


text:
/**
 *
 */
package org.ops4j.pax.wicket.samples.ds.internal;

import org.ops4j.pax.wicket.api.WebApplicationFactory;

/**
 * @author Christoph Läubrich
 */
public class WicketWebApplicationFactory implements WebApplicationFactory<WicketApplication> {

	{
		System.err.println("### INIT " + WicketWebApplicationFactory.class.getName());
	}

    /* (non-Javadoc)
     * @see org.ops4j.pax.wicket.api.WebApplicationFactory#getWebApplicationClass()
     */
    public Class<WicketApplication> getWebApplicationClass() {
        return WicketApplication.class;
    }

    /* (non-Javadoc)
     * @see org.ops4j.pax.wicket.api.WebApplicationFactory#onInstantiation(org.apache.wicket.protocol.http.WebApplication)
     */
    public void onInstantiation(WicketApplication application) {
        //Nothing to do here...
		System.err.println("### INIT " + application );
    }

}