text:
package org.apache.felix.ipojo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.felix.ipojo.architecture.InstanceDescription;
import org.apache.felix.ipojo.metadata.Element;
import org.apache.felix.ipojo.parser.FieldMetadata;
import org.apache.felix.ipojo.parser.MethodMetadata;
import org.apache.felix.ipojo.util.Logger;
import org.osgi.framework.BundleContext;

/**
 * This class defines the container of primitive instances. It manages content initialization
 * and handlers cooperation.
 * @author Felix Project Team
 */
public class InstanceManager implements ComponentInstance, InstanceStateListener {
    /**
     * The name of the component instance.
     */
    protected String m_name;

    /**
     * The name of the component type implementation class.
     */
    protected String m_className;

    /**
     * The handler object list.
     */
    protected final HandlerManager[] m_handlers;

    /**
     * The current instance state ({@link ComponentInstance#STOPPED} at the beginning).
     * Possible value are
     *
{@link ComponentInstance#INVALID}

     *
{@link ComponentInstance#VALID}

     *
{@link ComponentInstance#DISPOSED}

     *
{@link ComponentInstance#STOPPED}

     */
    protected int m_state = STOPPED;

    /**
     * The instance state listener list.
     * @see InstanceStateListener
     */
    protected List m_listeners = null;

    /**
     * The content of the current instance.
     */
    protected List m_pojoObjects;

    /**
     * The instance factory.
     */
    private final ComponentFactory m_factory;

    /**
     * The instance logger.
     */
    private final Logger m_logger;

    /**
     * The instance description.
     */
    private final PrimitiveInstanceDescription m_description;

    /**
     * The bundle context of the instance.
     */
    private final BundleContext m_context;

    /**
     * The map [field, {@link FieldInterceptor} list] storing interceptors monitoring fields.
     * Once configured, this map can't change.
     */
    private Map m_fieldRegistration;

    /**
     * the map [method identifier, {@link MethodInterceptor} list] interested
     * by the method.
     * Once configured, this map can't change.
     */
    private Map m_methodRegistration;

    /**
     * the map (sorted by parameter index) or {@link ConstructorInjector} interested by
     * injecting constructor parameter.
     * Once configured, this list can't change.
     */
    private Map m_constructorRegistration;

    /**
     * The manipulated class.
     * Once set, this field doesn't change.
     */
    private Class m_clazz;

    /**
     * The factory method used to create content objects.
     * If null, the regular constructor is used.
     * Once set, this field is immutable.
     */
    private String m_factoryMethod = null;

    /**
     * Is the component instance state changing?
     */
    private boolean m_inTransition = false;

    /**
     * The queue of stored state changed.
     */
    private List m_stateQueue = new ArrayList();

    /**
     * The map of [field, value], storing POJO managed
     * field value.
     */
    private Map m_fields = new HashMap();

    /**
     * The Map storing the Method objects by ids.
     * [id=>{@link Method}].
     */
    private Map m_methods = new HashMap();

    /**
     * Creates a new Component Manager.
     * The instance is not initialized.
     * @param factory  the factory managing the instance manager
     * @param context  the bundle context to give to the instance
     * @param handlers handler object array
     */
    public InstanceManager(ComponentFactory factory, BundleContext context, HandlerManager[] handlers) {
        m_factory = factory;
        m_context = context;
        m_handlers = handlers;
        m_description = new PrimitiveInstanceDescription(m_factory.getComponentDescription(), this);
        m_logger = new Logger(m_context, this);
    }

    /**
     * The instance logger.
     * @return the logger
     */
    public Logger getLogger() {
        return m_logger;
    }

    /**
     * Configures the instance manager.
     * Sets the class name, and the instance name as well as the factory method.
     * Initializes handlers.
     * @param metadata the component type metadata
     * @param configuration the configuration of the instance
     * @throws ConfigurationException if the metadata are not correct
     */
    public void configure(Element metadata, Dictionary configuration) throws ConfigurationException {
        m_className = metadata.getAttribute("classname");

        // Add the name
        m_name = (String) configuration.get("instance.name");

        // Check if an object is injected in the instance
        Object obj = configuration.get("instance.object");
        if (obj != null) {
            m_pojoObjects = new ArrayList(1);
            m_pojoObjects.add(obj);
        }

        // Get the factory method if presents.
        m_factoryMethod = (String) metadata.getAttribute("factory-method");

        // Create the standard handlers and add these handlers to the list
        for (int i = 0; i < m_handlers.length; i++) {
            m_handlers[i].init(this, metadata, configuration);
        }

        // Check that the constructor parameter are continuous.
        if (m_constructorRegistration != null) {
            for (int i = 0; i < m_constructorRegistration.size(); i++) {
                if (! m_constructorRegistration.containsKey(new Integer(i))) {
                    throw new ConfigurationException("The constructor parameter " + i + " is not managed");
                }
            }
        }
    }

    /**
     * Gets the description of the current instance.
     * @return the instance description.
     * @see org.apache.felix.ipojo.ComponentInstance#getInstanceDescription()
     */
    public InstanceDescription getInstanceDescription() {
        return m_description;
    }

    /**
     * Gets the list of handlers plugged (i.e. attached) on the instance.
     * This method does not need a synchronized block as the handler set is constant.
     * @return the handler array of plugged handlers.
     */
    public Handler[] getRegistredHandlers() {
        Handler[] handler = new Handler[m_handlers.length];
        for (int i = 0; i < m_handlers.length; i++) {
            handler[i] = m_handlers[i].getHandler();
        }
        return handler;
    }

    /**
     * Returns a specified handler.
     * This method allows cross-handler interactions.
     * This must does not need a synchronized block as the handler set is constant.
     * @param name the class name of the handler to find or its qualified name (namespace:name)
     * @return the handler, or null if not found
     */
    public Handler getHandler(String name) {
        for (int i = 0; i < m_handlers.length; i++) {
            HandlerFactory fact = (HandlerFactory) m_handlers[i].getHandler().getHandlerManager().getFactory();
            if (fact.getHandlerName().equals(name)) {
                return m_handlers[i].getHandler();
            }
        }
        return null;
    }

    /**
     * Gives access to a field value of the first created pojo.
     * This method processes by analyzing both managed fields and pojo fields (by reflection).
     * If no pojo were already created try only on managed fields.
     * @param fieldName the field name.
     * @return the field value, null is returned if the value is managed and not already set.
     */
    public synchronized Object getFieldValue(String fieldName) {
        if (m_pojoObjects == null) {
            return getFieldValue(fieldName, null);
        } else {
            return getFieldValue(fieldName, m_pojoObjects.get(0)); // Use the first pojo.
        }
    }

    /**
     * Gives access to a field value to the given created pojo.
     * This method processes by analyzing both managed fields and pojo fields (by reflection).
     * If the given pojo is null, tries only on managed fields.
     * @param fieldName the field name.
     * @param pojo  the pojo on which computing field value.
     * @return the field value, null is returned if the value is managed and not already set.
     */
    public synchronized Object getFieldValue(String fieldName, Object pojo) {
        Object setByContainer = null;

        if (m_fields != null) {
            setByContainer = m_fields.get(fieldName);
        }

        if (setByContainer == null && pojo != null) { // In the case of no given pojo, return null.
            // If null either the value was not already set or has the null value.
            try {
                Field field = pojo.getClass().getDeclaredField(fieldName);
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                return field.get(pojo);
            } catch (SecurityException e) {
                m_logger.log(Logger.ERROR, "Cannot reflect on field " + fieldName + " to obtain the value : " + e.getMessage());
            } catch (NoSuchFieldException e) {
                m_logger.log(Logger.ERROR, "Cannot reflect on field " + fieldName + " to obtain the value : " + e.getMessage());
            } catch (IllegalArgumentException e) {
                m_logger.log(Logger.ERROR, "Cannot reflect on field " + fieldName + " to obtain the value : " + e.getMessage());
            } catch (IllegalAccessException e) {
                m_logger.log(Logger.ERROR, "Cannot reflect on field " + fieldName + " to obtain the value : " + e.getMessage());
            }
            return null;
        } else {
            return setByContainer;
        }
    }

    /**
     * Starts the instance manager.
     * This method activates plugged handlers,
     * and computes the initial instance state.
     */
    public void start() {
        synchronized (this) {
            if (m_state != STOPPED) { // Instance already started
                return;
            } else {
                m_state = -2; // Temporary state.
            }
        }

        // Plug handler descriptions
        Handler[] handlers = getRegistredHandlers();
        for (int i = 0; i < handlers.length; i++) {
            m_description.addHandler(handlers[i].getDescription());
        }

        for (int i = 0; i < m_handlers.length; i++) {
            m_handlers[i].addInstanceStateListener(this);
            try {
                m_handlers[i].start();
            } catch (IllegalStateException e) {
                m_logger.log(Logger.ERROR, e.getMessage());
                stop();
                throw e;
            }
        }

        // Is an object already contained (i.e. injected)
        if (m_pojoObjects != null && ! m_pojoObjects.isEmpty()) {
            managedInjectedObject();
        }

        for (int i = 0; i < m_handlers.length; i++) {
            if (m_handlers[i].getState() != VALID) {
                setState(INVALID);
                return;
            }
        }
        setState(VALID);
    }

    /**
     * Stops the instance manager.
     * This methods sets the instance state to {@link ComponentInstance#STOPPED},
     * disables attached handlers, and notifies listeners ({@link InstanceStateListener})
     * of the instance stopping process.
     */
    public void stop() {
        List listeners = null;
        synchronized (this) {
            if (m_state == STOPPED) { // Instance already stopped
                return;
            }
            m_stateQueue.clear();
            m_inTransition = false;
        }

        setState(INVALID); // Must be called outside a synchronized block.

        // Stop all the handlers
        for (int i = m_handlers.length - 1; i > -1; i--) {
            m_handlers[i].removeInstanceStateListener(this);
            m_handlers[i].stop();
        }

        synchronized (this) {
            m_state = STOPPED;
            if (m_listeners != null) {
                listeners = new ArrayList(m_listeners); // Stack confinement
            }
            m_pojoObjects = null;
        }

        if (listeners != null) {
            for (int i = 0; i < listeners.size(); i++) {
                ((InstanceStateListener) listeners.get(i)).stateChanged(this, STOPPED);
            }
        }
    }

    /**
     * Disposes the instance.
     * This method does the following process:
     *
Stop the instance is not {@link ComponentInstance#STOPPED}

     *
Notifies listeners {@link InstanceStateListener} of the destruction

     *
Disposes attached handlers

     *
Clears structures

     * @see org.apache.felix.ipojo.ComponentInstance#dispose()
     */
    public void dispose() {
        List listeners = null;
        int state = -2; // Temporary state
        synchronized (this) {
            state = m_state; // Stack confinement
            if (m_listeners != null) {
                listeners = new ArrayList(m_listeners); // Stack confinement
            }
            m_listeners = null;
        }

        if (state > STOPPED) { // Valid or invalid
            stop(); // Does not hold the lock.
        }

        synchronized (this) {
            m_state = DISPOSED;
        }

        for (int i = 0; listeners != null && i < listeners.size(); i++) {
            ((InstanceStateListener) listeners.get(i)).stateChanged(this, DISPOSED);
        }

        for (int i = m_handlers.length - 1; i > -1; i--) {
            m_handlers[i].dispose();
        }

        synchronized (this) {
            m_factory.disposed(this);
            m_clazz = null;
            // Do not clean registration map, so injection still works
            // after disposal for late callbacks.
        }
    }

    /**
     * Sets the state of the component instance.
     * If the state changes, calls the {@link PrimitiveHandler#stateChanged(int)} method on the attached handlers.
     * This method has a reentrant mechanism. If in the flow of the first call the method is called another times,
     * the second call is stored and executed after the first one finished.
     * @param state the new state
     */
    public void setState(int state) {
        int originalState = -2;
        List listeners = null;
        synchronized (this) {
            if (m_inTransition) {
                m_stateQueue.add(new Integer(state));
                return;
            }

            if (m_state != state) {
                m_inTransition = true;
                originalState = m_state; // Stack confinement.
                m_state = state;
                if (m_listeners != null) {
                    listeners = new ArrayList(m_listeners); // Stack confinement.
                }
            }
        }

        // This section can be executed only by one thread at the same time. The m_inTransition pseudo semaphore block access to this section.
        if (m_inTransition) { // Check that we are really changing.
            if (state > originalState) {
                // The state increases (Stopped = > IV, IV => V) => invoke handlers from the higher priority to the lower
                try {
                    for (int i = 0; i < m_handlers.length; i++) {
                        m_handlers[i].getHandler().stateChanged(state);
                    }
                } catch (IllegalStateException e) {
                    // When an illegal state exception happens, the instance manager must be stopped immediately.
                    stop();
                    m_logger.log(Logger.ERROR, e.getMessage(), e);
                    return;
                }
            } else {
                // The state decreases (V => IV, IV = > Stopped, Stopped => Disposed)
                try {
                    for (int i = m_handlers.length - 1; i > -1; i--) {
                        m_handlers[i].getHandler().stateChanged(state);
                    }
                } catch (IllegalStateException e) {
                    // When an illegal state exception happens, the instance manager must be stopped immediately.
                    stop();
                    m_logger.log(Logger.ERROR, e.getMessage());
                    return;
                }
            }
        }

        if (listeners != null) {
            for (int i = 0; i < listeners.size(); i++) {
                ((InstanceStateListener) listeners.get(i)).stateChanged(this, state);
            }
        }

        synchronized (this) {
            m_inTransition = false;
            if (!m_stateQueue.isEmpty()) {
                int newState = ((Integer) (m_stateQueue.remove(0))).intValue();
                setState(newState);
            }
        }
    }

    /**
     * Gets the actual state of the instance.
     * Possible values are:
     *
{@link ComponentInstance#INVALID}

     *
{@link ComponentInstance#VALID}

     *
{@link ComponentInstance#DISPOSED}

     *
{@link ComponentInstance#STOPPED}

     * @return the actual state of the component instance.
     * @see org.apache.felix.ipojo.ComponentInstance#getState()
     */
    public synchronized int getState() {
        return m_state;
    }

    /**
     * Checks if the instance is started.
     * An instance is started if the state is either
     * {@link ComponentInstance#VALID} or {@link ComponentInstance#INVALID}.
     * @return true if the instance is started.
     * @see org.apache.felix.ipojo.ComponentInstance#isStarted()
     */
    public synchronized boolean isStarted() {
        return m_state > STOPPED;
    }

    /**
     * Registers an instance state listener.
     * @param listener the listener to register.
     * @see org.apache.felix.ipojo.ComponentInstance#addInstanceStateListener(org.apache.felix.ipojo.InstanceStateListener)
     */
    public synchronized void addInstanceStateListener(InstanceStateListener listener) {
        if (m_listeners == null) {
            m_listeners = new ArrayList();
        }
        m_listeners.add(listener);
    }

    /**
     * Unregisters an instance state listener.
     * @param listener the listener to unregister.
     * @see org.apache.felix.ipojo.ComponentInstance#removeInstanceStateListener(org.apache.felix.ipojo.InstanceStateListener)
     */
    public synchronized void removeInstanceStateListener(InstanceStateListener listener) {
        if (m_listeners != null) {
            m_listeners.remove(listener);
            if (m_listeners.isEmpty()) {
                m_listeners = null;
            }
        }
    }

    /**
     * Gets the factory which has created the current instance.
     * @return the factory of the component
     * @see org.apache.felix.ipojo.ComponentInstance#getFactory()
     */
    public ComponentFactory getFactory() {
        return m_factory;
    }

    /**
     * Loads the manipulated class.
     */
    private void load() {
        try {
            m_clazz = m_factory.loadClass(m_className);
        } catch (ClassNotFoundException e) {
            m_logger.log(Logger.ERROR, "[" + m_name + "] Class not found during the loading phase : " + e.getMessage(), e);
            stop();
            return;
        }
    }

    /**
     * Gets the object array created by the instance.
     * @return the created content objects of the component instance.
     */
    public synchronized Object[] getPojoObjects() {
        if (m_pojoObjects == null) {
            return null;
        }
        return m_pojoObjects.toArray(new Object[m_pojoObjects.size()]);
    }

    /**
     * Creates a POJO objects.
     * This method is not synchronized and does not require any locks.
     * If a {@link InstanceManager#m_factoryMethod} is specified,
     * this method called this static method to creates the object.
     * Otherwise, the methods uses the regular constructor.
     * All those methods can receive the {@link BundleContext} in
     * argument.
     * @return the created object or null if an error
     * occurs during the creation.
     */
    protected Object createObject() {
        if (m_clazz == null) {
            load();
        }

        // The following code doesn't need to be synchronized as is deal only with immutable fields.
        Object instance = null;
        if (m_factoryMethod == null) {
            // No factory-method, we use the constructor.
            try {
                // Try to find the correct constructor.
                if (m_constructorRegistration != null) {
                    // Initialize the injected values and types
                    // We have the IM first.
                    Object[] values = new Object[m_constructorRegistration.size() + 1];
                    Class[] types = new Class[m_constructorRegistration.size() + 1];
                    values[0] = this;
                    types[0] = InstanceManager.class;

                    // Iterate over the constructor injector
                    for (int i = 0; i < m_constructorRegistration.size(); i++) {
                        ConstructorInjector injector = (ConstructorInjector)
                            m_constructorRegistration.get(new Integer(i));
                        Object v = injector.getConstructorParameter(i);
                        if (v != null) {
                            values[i + 1] = v;
                            Class t = injector.getConstructorParameterType(i);
                            if (t == null) {
                                t = v.getClass();
                            }
                            types[i + 1] = t;
                        }
                    }
                    // Find the constructor.
                    Constructor cst = m_clazz.getDeclaredConstructor(types);
                    if (! cst.isAccessible()) {
                        cst.setAccessible(true);
                    }
                    String methodId = MethodMetadata.computeMethodId(cst);
                    onEntry(null, methodId,  values);
                    instance = cst.newInstance(values);
                    onExit(instance, methodId, instance);
                } else {
                    // Old semantic
                    // Try to find if there is a constructor with a bundle context as parameter :
                    try {
                        Constructor cst = m_clazz.getDeclaredConstructor(new Class[] { InstanceManager.class, BundleContext.class });
                        if (! cst.isAccessible()) {
                            cst.setAccessible(true);
                        }
                        Object[] args = new Object[] { this, m_context };
                        onEntry(null, MethodMetadata.BC_CONSTRUCTOR_ID,  new Object[] {m_context});
                        instance = cst.newInstance(args);
                        onExit(instance, MethodMetadata.BC_CONSTRUCTOR_ID, instance);
                    } catch (NoSuchMethodException e) {
                        // Create an instance if no instance are already created with <init>()BundleContext
                        if (instance == null) {
                            Constructor cst = m_clazz.getDeclaredConstructor(new Class[] { InstanceManager.class });
                            if (! cst.isAccessible()) {
                                cst.setAccessible(true);
                            }
                            Object[] args = new Object[] {this};
                            onEntry(null, MethodMetadata.EMPTY_CONSTRUCTOR_ID, new Object[0]);
                            instance = cst.newInstance(args);
                            onExit(instance, MethodMetadata.EMPTY_CONSTRUCTOR_ID, instance);
                        }
                    }
                }

            } catch (IllegalAccessException e) {
                m_logger.log(Logger.ERROR,
                                          "[" + m_name + "] createInstance -> The POJO constructor is not accessible : " + e.getMessage(), e);
                stop();
                throw new RuntimeException("Cannot create a POJO instance, the POJO constructor is not accessible : " + e.getMessage());
            } catch (SecurityException e) {
                m_logger.log(
                                          Logger.ERROR,
                                          "["
                                                  + m_name
                                                  + "] createInstance -> The POJO constructor is not accessible (security reason) : "
                                                  + e.getMessage(), e);
                stop();
                throw new RuntimeException("Cannot create a POJO instance, the POJO constructor is not accessible : " + e.getMessage());
            } catch (InvocationTargetException e) {
                m_logger.log(
                                          Logger.ERROR,
                                          "["
                                                  + m_name
                                                  + "] createInstance -> Cannot invoke the constructor method - the constructor throws an exception : "
                                                  + e.getTargetException().getMessage(), e.getTargetException());
                onError(null, m_className, e.getTargetException());
                stop();
                throw new RuntimeException("Cannot create a POJO instance, the POJO constructor has thrown an exception: " + e.getTargetException().getMessage());
            } catch (NoSuchMethodException e) {
                m_logger.log(Logger.ERROR,
                                          "[" + m_name + "] createInstance -> Cannot invoke the constructor (method not found) : " + e.getMessage(), e);
                stop();
                throw new RuntimeException("Cannot create a POJO instance, the POJO constructor cannot be found : " + e.getMessage());
            } catch (Throwable e) {
                // Catch every other possible error and runtime exception.
                m_logger.log(Logger.ERROR,
                        "[" + m_name + "] createInstance -> The POJO constructor invocation failed : " + e.getMessage(), e);
                stop();
                throw new RuntimeException("Cannot create a POJO instance, the POJO constructor invocation has thrown an exception : " + e.getMessage());
            }
        } else {
            try {
                // Build the pojo object with the factory-method.
                Method factory = null;
                // Try with the bundle context
                try {
                    factory = m_clazz.getDeclaredMethod(m_factoryMethod, new Class[] { BundleContext.class });
                    if (! factory.isAccessible()) {
                        factory.setAccessible(true);
                    }
                    Object[] args = new Object[] { m_context };
                    onEntry(null, m_className, args);
                    instance = factory.invoke(null, new Object[] { m_context });
                } catch (NoSuchMethodException e1) {
                    // Try without the bundle context
                    try {
                        factory = m_clazz.getDeclaredMethod(m_factoryMethod, new Class[0]);
                        if (! factory.isAccessible()) {
                            factory.setAccessible(true);
                        }
                        Object[] args = new Object[0];
                        onEntry(null, m_className, args);
                        instance = factory.invoke(null, args);
                    } catch (NoSuchMethodException e2) {
                        // Error : factory-method not found
                        m_logger.log(
                                                  Logger.ERROR,
                                                  "["
                                                          + m_name
                                                          + "] createInstance -> Cannot invoke the factory-method (method not found) : "
                                                          + e2.getMessage(), e2);
                        stop();
                        throw new RuntimeException("Cannot create a POJO instance, the factory-method cannot be found : " + e2.getMessage());
                    }
                }

                // Now call the setInstanceManager method.
                // Find declaring super class.
                Class declaringClass = instance.getClass();
                Method method = null;
                while (declaringClass != null && method == null) {
                    try {
                        method = declaringClass.getDeclaredMethod("_setInstanceManager",
                                new Class[] { InstanceManager.class });
                    } catch (NoSuchMethodException e) {
                        //Do nothing
                    }

                    declaringClass = declaringClass.getSuperclass();
                }

                if (method == null) {
                    // Error : _setInstanceManager method is missing
                    m_logger
                            .log(
                                 Logger.ERROR,
                                 "["
                                         + m_name
                                         + "] createInstance -> Cannot invoke the factory-method (the _setInstanceManager method does not exist");
                    stop();
                    throw new RuntimeException("Cannot create a POJO instance, the factory-method cannot be found");
                }

                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                method.invoke(instance, new Object[] { this });
                onExit(null, m_className, instance);

            } catch (InvocationTargetException e) {
                // Error : invocation failed
                m_logger.log(Logger.ERROR,
                                          "[" + m_name + "] createInstance -> The factory-method throws an exception : " + e.getTargetException(), e.getTargetException());
                onError(null, m_className, e.getTargetException());
                stop();
                throw new RuntimeException("Cannot create a POJO instance, the factory-method has thrown an exception: " + e.getTargetException().getMessage());
            } catch (Throwable e) {
                // Catch every other possible error and runtime exception.
                m_logger.log(Logger.ERROR,
                        "[" + m_name + "] createInstance -> The factory-method invocation failed : " + e.getMessage(), e);
                stop();
                throw new RuntimeException("Cannot create a POJO instance, the factory-method invocation has thrown an exception : " + e.getMessage());
            }
        }
        return instance;
    }

    /**
     * Creates an instance of the content.
     * This method needs to be called once only for singleton provided service.
     * This methods call the {@link InstanceManager#createObject()} method, and adds
     * the created object to the {@link InstanceManager#m_pojoObjects} list. Then,
     * it calls the {@link PrimitiveHandler#onCreation(Object)} methods on attached
     * handlers.
     * @return a new instance or null if an error occurs during the
     * creation.
     */
    public Object createPojoObject() {
        Object instance = createObject();

        // Add the new instance in the instance list.
        synchronized (this) {
            if (m_pojoObjects == null) {
                m_pojoObjects = new ArrayList(1);
            }
            m_pojoObjects.add(instance);
        }
        // Call createInstance on Handlers :
        for (int i = 0; i < m_handlers.length; i++) {
            // This methods must be call without the monitor lock.
            ((PrimitiveHandler) m_handlers[i].getHandler()).onCreation(instance);
        }

        return instance;
    }

    /**
     * Deletes a POJO object.
     * @param pojo the pojo to remove from the list of created pojos.
     */
    public synchronized void deletePojoObject(Object pojo) {
        if (m_pojoObjects != null) {
            m_pojoObjects.remove(pojo);
        }
    }

    /**
     * Gets the first object created by the instance.
     * If no object created, creates and returns a POJO object.
     * This methods call the {@link InstanceManager#createObject()} method, and adds
     * the created object to the {@link InstanceManager#m_pojoObjects} list. Then,
     * it calls the {@link PrimitiveHandler#onCreation(Object)} methods on attached
     * handlers.
     *

     *

     * TODO this method has a potential race condition if two threads require a pojo
     * object at the same time. Only one object will be created, but the second thread
     * can receive the created object before the {@link PrimitiveHandler#onCreation(Object)}
     * calls.
     *

     * @return the pojo object of the component instance to use for singleton component
     */
    public Object getPojoObject() {
        Object pojo = null;
        boolean newPOJO = false;
        synchronized (this) {
            if (m_pojoObjects != null) {
                pojo = m_pojoObjects.get(0); // Stack confinement
            } else {
                pojo = createObject();  // Stack confinement
                if (m_pojoObjects == null) {
                    m_pojoObjects = new ArrayList(1);
                }
                m_pojoObjects.add(pojo);
                newPOJO = true;
            }
        }

        // Call createInstance on Handlers :
        for (int i = 0; newPOJO && i < m_handlers.length; i++) {
            ((PrimitiveHandler) m_handlers[i].getHandler()).onCreation(pojo);
        }
        //NOTE this method allows returning a POJO object before calling the onCreation on handler:
        // a second thread get the created object before the first one (which created the object),
        // call onCreation.

        return pojo;
    }

    /**
     * Gets the manipulated class.
     * The method does not need to be synchronized.
     * Reassigning the internal class will use the same class object.
     * @return the manipulated class
     */
    public Class getClazz() {
        if (m_clazz == null) {
            load();
        }
        return m_clazz;
    }

    /**
     * Configures an injected object in this container.
     */
    private void managedInjectedObject() {
        Object obj = m_pojoObjects.get(0); // Get first object.

        if (! (obj instanceof Pojo)) {
            // Error, the injected object is not a POJO.
            throw new RuntimeException("The injected object in " + m_name + " is not a POJO");
        }

        load(); // Load the class.

        if (! m_clazz.isInstance(obj)) {
            throw new RuntimeException("The injected object in " + m_name + " is not an instance of " + m_className);
        }

        // Call _setInstanceManager
        try {
            Method setIM = m_clazz.getDeclaredMethod("_setInstanceManager", new Class[] {this.getClass()});
            setIM.setAccessible(true); // Necessary as the method is private
            setIM.invoke(obj, new Object[] {this});
        } catch (Exception e) {
            // If anything wrong happened...
            throw new RuntimeException("Cannot attach the injected object with the container of " + m_name + " : " + e.getMessage());
        }

        // Call createInstance on Handlers :
        for (int i = 0; i < m_handlers.length; i++) {
            // This methods must be call without the monitor lock.
            ((PrimitiveHandler) m_handlers[i].getHandler()).onCreation(obj);
        }

    }

    /**
     * Registers an handler.
     * This methods is called by handler wanting to monitor
     * fields and/or methods of the implementation class.
     * @param handler the handler to register
     * @param fields the field metadata list
     * @param methods the method metadata list
     * @deprecated use {@link InstanceManager#register(FieldMetadata, FieldInterceptor)}
     * and {@link InstanceManager#register(FieldMetadata, MethodInterceptor)} instead.
     */
    public void register(PrimitiveHandler handler, FieldMetadata[] fields, MethodMetadata[] methods) {
        for (int i = 0; fields != null && i < fields.length; i++) {
            register(fields[i], handler);
        }
        for (int i = 0; methods != null && i < methods.length; i++) {
            register(methods[i], handler);
        }

    }

    /**
     * Registers a field interceptor.
     * A field interceptor will be notified of field access of the
     * implementation class. Note that handlers are field interceptors.
     * @param field the field to monitor
     * @param interceptor the field interceptor object
     */
    public void register(FieldMetadata field, FieldInterceptor interceptor) {
        if (m_fieldRegistration == null) {
            m_fieldRegistration = new HashMap();
            m_fieldRegistration.put(field.getFieldName(), new FieldInterceptor[] { interceptor });
        } else {
            FieldInterceptor[] list = (FieldInterceptor[]) m_fieldRegistration.get(field.getFieldName());
            if (list == null) {
                m_fieldRegistration.put(field.getFieldName(), new FieldInterceptor[] { interceptor });
            } else {
                for (int j = 0; j < list.length; j++) {
                    if (list[j] == interceptor) {
                        return;
                    }
                }
                FieldInterceptor[] newList = new FieldInterceptor[list.length + 1];
                System.arraycopy(list, 0, newList, 0, list.length);
                newList[list.length] = interceptor;
                m_fieldRegistration.put(field.getFieldName(), newList);
            }
        }
    }

    /**
     * Registers a method interceptor.
     * A method interceptor will be notified of method entries, exits
     * and errors. Note that handlers are method interceptors.
     * @param method the field to monitor
     * @param interceptor the field interceptor object
     */
    public void register(MethodMetadata method, MethodInterceptor interceptor) {
        if (m_methodRegistration == null) {
            m_methodRegistration = new HashMap();
            m_methodRegistration.put(method.getMethodIdentifier(), new MethodInterceptor[] { interceptor });
        } else {
            MethodInterceptor[] list = (MethodInterceptor[]) m_methodRegistration.get(method.getMethodIdentifier());
            if (list == null) {
                m_methodRegistration.put(method.getMethodIdentifier(), new MethodInterceptor[] { interceptor });
            } else {
                for (int j = 0; j < list.length; j++) {
                    if (list[j] == interceptor) {
                        return;
                    }
                }
                MethodInterceptor[] newList = new MethodInterceptor[list.length + 1];
                System.arraycopy(list, 0, newList, 0, list.length);
                newList[list.length] = interceptor;
                m_methodRegistration.put(method.getMethodIdentifier(), newList);
            }
        }
    }

    /**
     * Registers a constructor injector.
     * The constructor injector will be called when a pojo object is going to be
     * created.
     * @param index the index of the parameter. Only one injector per index can
     * be registered.
     * @param injector the injector object.
     * @throws ConfigurationException if the given index is already injected by another
     * injector
     */
    public void register(int index, ConstructorInjector injector) throws ConfigurationException {
        Integer key = new Integer(index);
        if (m_constructorRegistration == null) {
            m_constructorRegistration = new HashMap();
        }
        if (! m_constructorRegistration.containsKey(key)) {
            m_constructorRegistration.put(key, injector);
        } else {
            throw new ConfigurationException("Another constructor injector " +
                    "manages the parameter " + index);
        }
    }

    /**
     * This method is called by the manipulated class each time that a GETFIELD instruction is executed.
     * The method asks to each attached handler monitoring this field which value need
     * to be injected (i.e. returned) by invoking the {@link PrimitiveHandler#onGet(Object, String, Object)}
     * method. If the field value changes, this method call the {@link PrimitiveHandler#onSet(Object, String, Object)}
     * method on each field interceptor monitoring the field in order to advertize the new value.
     * @param pojo the pojo object on which the field was get
     * @param fieldName the field name on which the GETFIELD instruction is called
     * @return the value decided by the last asked handler (throws a warning if two fields decide two different values)
     */
    public Object  onGet(Object pojo, String fieldName) {
        Object initialValue = null;
        synchronized (this) { // Stack confinement.
            initialValue = m_fields.get(fieldName);
        }
        Object result = initialValue;
        boolean hasChanged = false;
        // Get the list of registered handlers
        FieldInterceptor[] list = (FieldInterceptor[]) m_fieldRegistration.get(fieldName); // Immutable list.
        for (int i = 0; list != null && i < list.length; i++) {
            // Call onGet outside of a synchronized block.
            Object handlerResult = list[i].onGet(null, fieldName, initialValue);
            if (handlerResult == initialValue) {
                continue; // Non-binding case (default implementation).
            } else {
                if (result != initialValue) {
                    //TODO analyze impact of removing conflict detection
                    if ((handlerResult != null && !handlerResult.equals(result)) || (result != null && handlerResult == null)) {
                        m_logger.log(
                                                  Logger.WARNING,
                                                  "A conflict was detected on the injection of "
                                                          + fieldName);
                    }
                }
                result = handlerResult;
                hasChanged = true;
            }
        }
        if (hasChanged) {
            // A change occurs => notify the change
            //TODO consider just changing the reference, however multiple thread can be an issue
            synchronized (this) {
                m_fields.put(fieldName, result);
            }
            // Call onset outside of a synchronized block.
            for (int i = 0; list != null && i < list.length; i++) {
                list[i].onSet(null, fieldName, result);
            }
        }
        return result;
    }

    /**
     * Dispatches entry method events on registered method interceptors.
     * This method calls the {@link PrimitiveHandler#onEntry(Object, Method, Object[])}
     * methods on method interceptors monitoring the method.
     * @param pojo the pojo object on which method is invoked.
     * @param methodId the method id used to compute the {@link Method} object.
     * @param args the argument array
     */
    public void onEntry(Object pojo, String methodId, Object[] args) {
        if (m_methodRegistration == null) { // Immutable field.
            return;
        }
        MethodInterceptor[] list = (MethodInterceptor[]) m_methodRegistration.get(methodId);
        Member method = getMethodById(methodId);
        // In case of a constructor, the method is null, and the list is null too.
        for (int i = 0; list != null && i < list.length; i++) {
            list[i].onEntry(pojo, method, args); // Outside a synchronized block.
        }
    }

    /**
     * Dispatches exit method events on registered method interceptors.
     * The given returned object is an instance of {@link Exception} if the method thrown an
     * exception. If the given object is null, either the method returns void,
     * or the method has returned null
     * This method calls the {@link PrimitiveHandler#onExit(Object, Method, Object[])} and the
     * {@link PrimitiveHandler#onFinally(Object, Method)} methods on method interceptors monitoring the method.
     * @param pojo the pojo object on which method was invoked.
     * @param methodId the method id used to compute the {@link Method} object.
     * @param result the returned object.
     */
    public void onExit(Object pojo, String methodId, Object result) {
        if (m_methodRegistration == null) {
            return;
        }
        MethodInterceptor[] list = (MethodInterceptor[]) m_methodRegistration.get(methodId);
        Member method = getMethodById(methodId);
        for (int i = 0; list != null && i < list.length; i++) {
            list[i].onExit(pojo, method, result);
        }
        for (int i = 0; list != null && i < list.length; i++) {
            list[i].onFinally(pojo, method);
        }
    }

    /**
     * Dispatches error method events on registered method interceptors.
     * or the method has returned null
     * This method calls the {@link PrimitiveHandler#onExit(Object, Method, Object[])} and the
     * {@link PrimitiveHandler#onFinally(Object, Method)} methods on method interceptors monitoring
     * the method.
     * @param pojo the pojo object on which the method was invoked
     * @param methodId the method id used to compute the {@link Method} object.
     * @param error the Throwable object.
     */
    public void onError(Object pojo, String methodId, Throwable error) {
        if (m_methodRegistration == null) {
            return;
        }
        MethodInterceptor[] list = (MethodInterceptor[]) m_methodRegistration.get(methodId);
        Member method = getMethodById(methodId);
        for (int i = 0; list != null && i < list.length; i++) {
            list[i].onError(pojo, method, error);
        }
        for (int i = 0; list != null && i < list.length; i++) {
            list[i].onFinally(pojo, method);
        }
    }

    /**
     * Computes the {@link Method} object from the given id.
     * Once computes, a map is used as a cache to avoid to recompute for
     * the same id.
     * @param methodId the method id
     * @return the method object or null if the method cannot be found.
     */
    private Member getMethodById(String methodId) {
        // Not necessary synchronized as recomputing the methodID will give the same Method twice.
        Member member = (Member) m_methods.get(methodId);
        if (member == null  && m_clazz != null) {

            // First try on methods.
            Method[] mets = m_clazz.getDeclaredMethods();
            for (int i = 0; i < mets.length; i++) {
                // Check if the method was not already computed. If not, compute the Id and check.
                if (!m_methods.containsValue(mets[i]) && (MethodMetadata.computeMethodId(mets[i]).equals(methodId))) {
                    // Store the new methodId
                    m_methods.put(methodId, mets[i]);
                    return mets[i];
                }
            }

            // If not found, it is a constructor, return the constructor object in this case.
            if (methodId.startsWith(MethodMetadata.CONSTRUCTOR_PREFIX)) {
                Constructor[] constructors = m_clazz.getDeclaredConstructors();
                for (int i = 0; i < constructors.length; i++) {
                    // Check if the constructor was not already computed. If not, compute the Id and check.
                    if (!m_methods.containsValue(constructors[i]) && (MethodMetadata.computeMethodId(constructors[i]).equals(methodId))) {
                        // Store the new methodId
                        m_methods.put(methodId, constructors[i]);
                        return constructors[i];
                    }
                }
            }

            // Cannot happen
            m_logger.log(Logger.INFO, "A methodID cannot be associated with a method from the POJO class: " + methodId);
            return null;
        } else {
            return member;
        }
    }

    /**
     * This method is called by the manipulated class each time that a PUTFIELD instruction is executed.
     * The method calls the {@link PrimitiveHandler#onSet(Object, String, Object)} method on each field
     * interceptors monitoring this field.
     * This method can be invoked with a null pojo argument when the changes comes from another
     * handler.
     * @param pojo the pojo object on which the field was set
     * @param fieldName the field name on which the PUTFIELD instruction is called
     * @param objectValue the new value of the field
     */
    public void onSet(final Object pojo, final String fieldName, final Object objectValue) {
        synchronized (this) {
            // First, store the new value.
            // This must be done in a synchronized block to avoid
            // concurrent modification
            m_fields.put(fieldName, objectValue);
        }
        // The registrations cannot be modified, so we can directly access
        // the interceptor list.
        FieldInterceptor[] list = (FieldInterceptor[]) m_fieldRegistration
                .get(fieldName);
        for (int i = 0; list != null && i < list.length; i++) {
             // The callback must be call outside the synchronization block.
            list[i].onSet(null, fieldName, objectValue);
        }
    }

    /**
     * Gets the bundle context used by this component instance.
     * @return the context of the component.
     * @see org.apache.felix.ipojo.ComponentInstance#getContext()
     */
    public BundleContext getContext() {
        return m_context; // Immutable
    }

    /**
     * Gets the global bundle context. This is the bundle context
     * of the bundle declaring the component type.
     * @return the bundle context of the bundle declaring the component
     * type.
     */
    public BundleContext getGlobalContext() {
        return ((IPojoContext) m_context).getGlobalContext(); // Immutable
    }

    /**
     * Gets the local service context. This service context gives
     * access to the 'local' service registry (the composite one).
     * If the instance lives in the global (i.e. OSGi) context,
     * this method returns null
     * @return the local service context or null if the
     * instance doesn't live in a composite.
     */
    public ServiceContext getLocalServiceContext() {
        return ((IPojoContext) m_context).getServiceContext(); // Immutable
    }

    /**
     * Gets the instance name.
     * @return the instance name.
     * @see org.apache.felix.ipojo.ComponentInstance#getInstanceName()
     */
    public String getInstanceName() {
        return m_name; // Immutable
    }

    /**
     * Reconfigures the current instance.
     * Reconfiguring an instance means re-injecting a new
     * instance configuration. Some properties are immutable
     * such as the instance name.
     * This methods calls the {@link PrimitiveHandler#reconfigure(Dictionary)}
     * methods on each attached handler, and then recompute the instance
     * state. Note that the reconfiguration process does not deactivate the
     * instance.
     * @param configuration the new configuration to push
     * @see org.apache.felix.ipojo.ComponentInstance#reconfigure(java.util.Dictionary)
     */
    public void reconfigure(Dictionary configuration) {
         m_logger.log(Logger.INFO, "Reconfiguring " + getInstanceName());
        for (int i = 0; i < m_handlers.length; i++) {
            m_handlers[i].getHandler().reconfigure(configuration);
        }
        // We synchronized the state computation.
        synchronized (this) {
            if (m_state == STOPPED) {
                m_logger.log(Logger.INFO, "Instance stopped during reconfiguration - Try to restart");
                start();
            } else if (m_state == INVALID) {
                m_logger.log(Logger.INFO, "Instance invalid during reconfiguration - Recompute state");
                // Try to revalidate the instance after reconfiguration
                for (int i = 0; i < m_handlers.length; i++) {
                    if (m_handlers[i].getState() != VALID) {
                        return;
                    }
                }
                setState(VALID);
            }
        }
    }

    /**
     * Gets the implementation class of the component type.
     * This method does not need to be synchronized as the
     * class name is constant once set.
     * @return the class name of the component implementation.
     */
    public String getClassName() {
        return m_className;
    }

    /**
     * State Change listener callback.
     * This method is called every time that a plugged handler becomes valid or invalid.
     * This method computes the new instance state and applies it (by calling the
     * {@link InstanceManager#setState(int)} method.
     * @param instance the handler becoming valid or invalid
     * @param newState the new state of the handler
     * @see org.apache.felix.ipojo.InstanceStateListener#stateChanged(org.apache.felix.ipojo.ComponentInstance, int)
     */
    public void stateChanged(ComponentInstance instance, int newState) {
        int state;
        synchronized (this) {
            if (m_state <= STOPPED) {
                return;
            } else {
                state = m_state; // Stack confinement
            }
        }

        // Update the component state if necessary
        if (newState == INVALID && state == VALID) {
            // Need to update the state to UNRESOLVED
            setState(INVALID);
            return;
        }
        if (newState == VALID && state == INVALID) {
            // An handler becomes valid => check if all handlers are valid
            for (int i = 0; i < m_handlers.length; i++) {
                if (m_handlers[i].getState() != VALID) {
                    return;
                }
            }
            setState(VALID);
            return;
        }
    }

    /**
     * Gets the list of registered fields (containing field names).
     * This method is invoked by the POJO itself during
     * its initialization.
     * @return the set of registered fields.
     */
    public Set getRegistredFields() {
        if (m_fieldRegistration == null) {
            return null;
        }
        return m_fieldRegistration.keySet();
    }

    /**
     * Gets the list of registered methods (containing method ids).
     * This method is invoked by the POJO itself during its
     * initialization.
     * @return the set of registered methods.
     */
    public Set getRegistredMethods() {
        if (m_methodRegistration == null) {
            return null;
        } else {
            return m_methodRegistration.keySet();
        }
    }
}


text:
package org.sakaiproject.util;

import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.w3c.dom.Element;

/**
 * <p>
 * BaseResourceProperties is the base class for ResourcePropertiesEdit implementations.
 * </p>
 */
public class BaseResourcePropertiesEdit extends BaseResourceProperties implements ResourcePropertiesEdit
{
	/**
	 * Construct.
	 */
	public BaseResourcePropertiesEdit()
	{
		super();

	} // BaseResourcePropertiesEdit

	/**
	 * Construct from XML.
	 *
	 * @param el
	 *        The XML DOM element.
	 */
	public BaseResourcePropertiesEdit(Element el)
	{
		super(el);

	} // BaseResourcePropertiesEdit

} // BaseResourcePropertiesEdit

redpajama_set_name: RedPajamaGithub


text:
package gov.hhs.fha.nhinc.patientcorrelation.nhinc.parsers.helpers;

import org.hl7.v3.II;

/**
 *
 * @author rayj
 */
public class InteractionIdHelper {

    public static II createInteractionId(String extension) {
        return IIHelper.IIFactory(Constants.HL7_OID, extension);
    }
}


text:
package io.github.charly1811.captions;

import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import io.github.charly1811.captions.io.Parser;
import io.github.charly1811.captions.io.VttParser;

public class TimedTextResource implements Serializable {

    private int parserType;
    private ArrayList<TimedText> list;
    private String name = "Unknown";

    public TimedTextResource(Map<Double, TimedText> collection) {
        list = new ArrayList<>(collection.values());
    }

    public TimedTextResource(Map<Double, TimedText> read, int parserType) {
        this(read);
        this.parserType = parserType;
    }

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

    @Override
    public String toString() {
        return toString(Parsers.getParser(parserType)).trim();
    }

    public TimedText getNextTimedText(Double position) {
        TimedText timedText = null;
        for (TimedText text : list) {
            boolean foundResource = position >= text.getPosition() && position <= text.getPosition() + text.getDuration();
            if (foundResource) {
                timedText = text;
                break;
            }
        }
        return timedText;
    }

    public String toString(Parser parser) {
        StringBuilder stringBuilder = new StringBuilder(parser.getHeader());

        for (TimedText timedText : list) {
            stringBuilder.append(timedText.toString(parser));
            stringBuilder.append("\n");
        }
        return stringBuilder.toString();
    }

    public ArrayList<TimedText> getTimedTexts() {
        return list;
    }

    public String getName() {
        return name;
    }
}


text:
class WXDLLIMPEXP_ADV wxExtHelpController : public wxHelpControllerBase
{
public:
  wxExtHelpController(wxWindow* parentWindow = NULL);
  virtual ~wxExtHelpController();
    // Set viewer: new name for SetBrowser
  void SetViewer(const wxString& viewer = wxEmptyString, long flags = wxHELP_NETSCAPE) override;
  bool Initialize(const wxString& dir, int) override
  {
    return Initialize(dir);
  }
  bool Initialize(const wxString& dir) override;
  bool LoadFile(const wxString& file = wxEmptyString) override;
  bool DisplayContents() override;
  bool DisplaySection(int sectionNo) override;
  bool DisplaySection(const wxString& section) override;
  bool DisplayBlock(long blockNo) override;
  bool KeywordSearch(const wxString& k, wxHelpSearchMode mode = wxHELP_SEARCH_ALL) override;
  bool Quit() override;
  void OnQuit() override;
  virtual bool DisplayHelp(const wxString&);
  void SetFrameParameters(const wxString&, const wxSize&, const wxPoint& = wxDefaultPosition, bool = false) override
  {
            // does nothing by default
  }
  wxFrame* GetFrameParameters(wxSize* = NULL, wxPoint* = NULL, bool* = NULL) override
  {
    return NULL;
  }
protected:
    // Filename of currently active map file.
  wxString m_helpDir;
    // How many entries do we have in the map file?
  int m_NumOfEntries;
    // A list containing all id,url,documentation triples.
  wxList* m_MapList;
private:
    // parse a single line of the map file (called by LoadFile())
    //
    // return true if the line was valid or false otherwise
  bool ParseMapFileLine(const wxString& line);
    // Deletes the list and all objects.
  void DeleteList();
    // How to call the html viewer.
  wxString m_BrowserName;
    // Is the viewer a variant of netscape?
  bool m_BrowserIsNetscape;
  wxDECLARE_CLASS(wxExtHelpController);
};
#  endif
#endif


text:
package org.kuali.rice.krad.uif.component;

/**
 * Extends Ordered interface to add setter for the order property
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public interface Ordered extends org.springframework.core.Ordered {
	public static final int INITIAL_ORDER_VALUE = 0;

	/**
	 * Setter for the order value
	 *
	 * @param order
	 * @see org.springframework.core.Ordered.getOrder()
	 */
	public void setOrder(int order);
}


text:
Inproctester provides HtmlUnit and WebDriver extensions to enable testing of a web application in-processs.
It simulates a j2ee servlet container to enable a standard j2ee web application to run within a test process.
Inproctester uses jetty behind the scenes, however it allows to dispatch requests to the web application under test directly, bypassing any socket and http layer.

# Note on jersey
Inproctester provides a jersey-client implementation that allows requests to be dispatched directly to a jersey-based web service packaged as a j2ee web application.
However jersey could also be used independently from a servlet container. E.g. it could be deployed with simpleweb [http://www.simpleframework.org].
Jersey-based web services are testable in memory out of the box, using jersey-test framework without the need to simulate a j2ee web environment [http://jersey.java.net/nonav/documentation/latest/test-framework.html].

The standard jersey-test framework does not however provide a WebDriver interface that would allow to test html if jersey is used for html generation.
The sibling jerseytester project [https://github.com/aharin/jerseytester] provides such WebDriver extensions for jersey-test framework.

## Contributors

* [http://github.com/aharin](Alex Harin)

## Binaries

The latest release of inproctester is 1.0.14, released on 29-Aug-2012. The compiled binaries are available via central maven repository.

    <dependency>
        <groupId>com.thoughtworks.inproctester</groupId>
        <artifactId>inproctester-webdriver</artifactId>
        <version>1.0.14</version>
    </dependency>

## Licence

Inprocess web application tester is distributed under the terms of Apache License, Version 2.0: [http://www.apache.org/licenses/LICENSE-2.0.html]


text:
"""Metric Utilities"""
from __future__ import print_function
import datetime
import itertools
import sys

import click

from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer import utils

# pylint: disable=unused-argument
def _validate_datetime(ctx, param, value):
    try:
        return datetime.datetime.strptime(value, "%Y-%m-%d")
    except (ValueError, TypeError):
        pass

    try:
        return datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
    except (ValueError, TypeError):
        raise click.BadParameter(
            "not in the format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'")

def _get_pooled_bandwidth(env, start, end):
    call = env.client.call('Account', 'getVirtualDedicatedRacks',
                           iter=True,
                           mask='id,name,metricTrackingObjectId')
    types = [
        {'keyName': 'PUBLICIN',
         'name': 'publicIn',
         'summaryType': 'sum'},
        {'keyName': 'PUBLICOUT',
         'name': 'publicOut',
         'summaryType': 'sum'},
        {'keyName': 'PRIVATEIN',
         'name': 'privateIn',
         'summaryType': 'sum'},
        {'keyName': 'PRIVATEOUT',
         'name': 'privateOut',
         'summaryType': 'sum'},
    ]

    with click.progressbar(list(call),
                           label='Calculating for bandwidth pools',
                           file=sys.stderr) as pools:
        for pool in pools:
            if not pool.get('metricTrackingObjectId'):
                continue

            yield {
                'id': pool['id'],
                'type': 'pool',
                'name': pool['name'],
                'data': env.client.call(
                    'Metric_Tracking_Object',
                    'getSummaryData',
                    start.strftime('%Y-%m-%d %H:%M:%S %Z'),
                    end.strftime('%Y-%m-%d %H:%M:%S %Z'),
                    types,
                    300,
                    id=pool['metricTrackingObjectId'],
                ),
            }

def _get_hardware_bandwidth(env, start, end):
    hw_call = env.client.call(
        'Account', 'getHardware',
        iter=True,
        mask='id,hostname,metricTrackingObject.id,'
             'virtualRack[id,bandwidthAllotmentTypeId]')
    types = [
        {'keyName': 'PUBLICIN',
         'name': 'publicIn',
         'summaryType': 'counter'},
        {'keyName': 'PUBLICOUT',
         'name': 'publicOut',
         'summaryType': 'counter'},
        {'keyName': 'PRIVATEIN',
         'name': 'privateIn',
         'summaryType': 'counter'},
        {'keyName': 'PRIVATEOUT',
         'name': 'privateOut',
         'summaryType': 'counter'},
    ]

    with click.progressbar(list(hw_call),
                           label='Calculating for hardware',
                           file=sys.stderr) as hws:
        for instance in hws:
            if not utils.lookup(instance, 'metricTrackingObject', 'id'):
                continue

            pool_name = None
            if utils.lookup(instance,
                            'virtualRack',
                            'bandwidthAllotmentTypeId') == 2:
                pool_name = utils.lookup(instance, 'virtualRack', 'name')

            yield {
                'id': instance['id'],
                'type': 'hardware',
                'name': instance['hostname'],
                'pool': pool_name,
                'data': env.client.call(
                    'Metric_Tracking_Object',
                    'getSummaryData',
                    start.strftime('%Y-%m-%d %H:%M:%S %Z'),
                    end.strftime('%Y-%m-%d %H:%M:%S %Z'),
                    types,
                    3600,
                    id=instance['metricTrackingObject']['id'],
                ),
            }

def _get_virtual_bandwidth(env, start, end):
    call = env.client.call(
        'Account', 'getVirtualGuests',
        iter=True,
        mask='id,hostname,metricTrackingObjectId,'
             'virtualRack[id,bandwidthAllotmentTypeId]')
    types = [
        {'keyName': 'PUBLICIN_NET_OCTET',
         'name': 'publicIn_net_octet',
         'summaryType': 'sum'},
        {'keyName': 'PUBLICOUT_NET_OCTET',
         'name': 'publicOut_net_octet',
         'summaryType': 'sum'},
        {'keyName': 'PRIVATEIN_NET_OCTET',
         'name': 'privateIn_net_octet',
         'summaryType': 'sum'},
        {'keyName': 'PRIVATEOUT_NET_OCTET',
         'name': 'privateOut_net_octet',
         'summaryType': 'sum'},
    ]

    with click.progressbar(list(call),
                           label='Calculating for virtual',
                           file=sys.stderr) as vms:
        for instance in vms:
            pool_name = None
            if utils.lookup(instance,
                            'virtualRack',
                            'bandwidthAllotmentTypeId') == 2:
                pool_name = utils.lookup(instance, 'virtualRack', 'id')

            yield {
                'id': instance['id'],
                'type': 'virtual',
                'name': instance['hostname'],
                'pool': pool_name,
                'data': env.client.call(
                    'Metric_Tracking_Object',
                    'getSummaryData',
                    start.strftime('%Y-%m-%d %H:%M:%S %Z'),
                    end.strftime('%Y-%m-%d %H:%M:%S %Z'),
                    types,
                    3600,
                    id=instance['metricTrackingObjectId'],
                ),
            }

@click.command(short_help="Bandwidth report for every pool/server")
@click.option(
    '--start',
    callback=_validate_datetime,
    default=(
        datetime.datetime.now() - datetime.timedelta(days=30)
    ).strftime('%Y-%m-%d'),
    help="datetime in the format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'")
@click.option(
    '--end',
    callback=_validate_datetime,
    default=datetime.datetime.now().strftime('%Y-%m-%d'),
    help="datetime in the format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'")
@click.option('--sortby', help='Column to sort by',
              default='hostname',
              show_default=True)
@environment.pass_env
def cli(env, start, end, sortby):
    """Bandwidth report for every pool/server.

    This reports on the total data transfered for each virtual sever, hardware
    server and bandwidth pool.
    """

    env.err('Generating bandwidth report for %s to %s' % (start, end))

    table = formatting.Table([
        'type',
        'name',
        'public_in',
        'public_out',
        'private_in',
        'private_out',
        'pool',
    ])
    table.sortby = sortby

    def f_type(key, results):
        "Filter metric data by type"
        return (result['counter'] for result in results
                if result['type'] == key)

    try:
        for item in itertools.chain(_get_pooled_bandwidth(env, start, end),
                                    _get_virtual_bandwidth(env, start, end),
                                    _get_hardware_bandwidth(env, start, end)):
            pub_in = int(sum(f_type('publicIn_net_octet', item['data'])))
            pub_out = int(sum(f_type('publicOut_net_octet', item['data'])))
            pri_in = int(sum(f_type('privateIn_net_octet', item['data'])))
            pri_out = int(sum(f_type('privateOut_net_octet', item['data'])))
            table.add_row([
                item['type'],
                item['name'],
                formatting.b_to_gb(pub_in),
                formatting.b_to_gb(pub_out),
                formatting.b_to_gb(pri_in),
                formatting.b_to_gb(pri_out),
                item.get('pool') or formatting.blank(),
            ])
    except KeyboardInterrupt:
        env.err("Printing collected results and then aborting.")

    env.out(env.fmt(table))


text: .selectors button { margin-top: 24px;}


text:
package org.orekit.propagation.conversion;

import org.orekit.frames.Frame;
import org.orekit.orbits.OrbitType;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.Propagator;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.ParameterDriversList;

/** This interface is the top-level abstraction to build propagators for conversion.
 * @author Pascal Parraud
 * @since 6.0
 */
public interface PropagatorBuilder {

    /** Build a propagator.
     * @param normalizedParameters normalized values for the selected parameters
     * @return an initialized propagator
     */
    Propagator buildPropagator(double[] normalizedParameters);

    /** Get the current value of selected normalized parameters.
     * @return current value of selected normalized parameters
     */
    double[] getSelectedNormalizedParameters();

    /** Get the orbit type expected for the 6 first parameters in
     * {@link #buildPropagator(double[])}.
     * @return orbit type to use in {@link #buildPropagator(double[])}
     * @see #buildPropagator(double[])
     * @see #getPositionAngle()
     * @since 7.1
     */
    OrbitType getOrbitType();

    /** Get the position angle type expected for the 6 first parameters in
     * {@link #buildPropagator(double[])}.
     * @return position angle type to use in {@link #buildPropagator(double[])}
     * @see #buildPropagator(double[])
     * @see #getOrbitType()
     * @since 7.1
     */
    PositionAngle getPositionAngle();

    /** Get the date of the initial orbit.
     * @return date of the initial orbit
     */
    AbsoluteDate getInitialOrbitDate();

    /** Get the frame in which the orbit is propagated.
     * @return frame in which the orbit is propagated
     */
    Frame getFrame();

    /** Get the drivers for the configurable orbital parameters.
     * @return drivers for the configurable orbital parameters
     * @since 8.0
     */
    ParameterDriversList getOrbitalParametersDrivers();

    /** Get the drivers for the configurable propagation parameters.
     * <p>
     * The parameters typically correspond to force models.
     * </p>
     * @return drivers for the configurable propagation parameters
     * @since 8.0
     */
    ParameterDriversList getPropagationParametersDrivers();

}


text:
'use strict';

/**
 * # Bind
 * Analogue of `Function::bind()`.
 *
 * ```js
 * var bind = require('fast.js').bind;
 * var bound = bind(myfunc, this, 1, 2, 3);
 *
 * bound(4);
 * ```
 *
 *
 * @param  {Function} fn          The function which should be bound.
 * @param  {Object}   thisContext The context to bind the function to.
 * @param  {mixed}    args, ...   Additional arguments to pre-bind.
 * @return {Function}             The bound function.
 */
exports.bind = function fastBind (fn, thisContext) {
  var boundLength = arguments.length - 2,
      boundArgs;

  if (boundLength > 0) {
    boundArgs = new Array(boundLength);
    for (var i = 0; i < boundLength; i++) {
      boundArgs[i] = arguments[i + 2];
    }
    return function () {
      var length = arguments.length,
          args = new Array(boundLength + length),
          i;
      for (i = 0; i < boundLength; i++) {
        args[i] = boundArgs[i];
      }
      for (i = 0; i < length; i++) {
        args[boundLength + i] = arguments[i];
      }
      return fn.apply(thisContext, args);
    };
  }
  return function () {
    return fn.apply(thisContext, arguments);
  };
};

/**
 * # Partial Application
 *
 * Partially apply a function. This is similar to `.bind()`,
 * but with one important difference - the returned function is not bound
 * to a particular context. This makes it easy to add partially
 * applied methods to objects. If you need to bind to a context,
 * use `.bind()` instead.
 *
 * > Note: This function does not support partial application for
 * constructors, for that see `partialConstructor()`
 *
 *
 * @param  {Function} fn          The function to partially apply.
 * @param  {mixed}    args, ...   Arguments to pre-bind.
 * @return {Function}             The partially applied function.
 */
exports.partial = function fastPartial (fn) {
  var boundLength = arguments.length - 1,
      boundArgs;

  boundArgs = new Array(boundLength);
  for (var i = 0; i < boundLength; i++) {
    boundArgs[i] = arguments[i + 1];
  }
  return function () {
    var length = arguments.length,
        args = new Array(boundLength + length),
        i;
    for (i = 0; i < boundLength; i++) {
      args[i] = boundArgs[i];
    }
    for (i = 0; i < length; i++) {
      args[boundLength + i] = arguments[i];
    }
    return fn.apply(this, args);
  };
};

/**
 * # Partial Constructor
 *
 * Partially apply a constructor function. The returned function
 * will work with or without the `new` keyword.
 *
 *
 * @param  {Function} fn          The constructor function to partially apply.
 * @param  {mixed}    args, ...   Arguments to pre-bind.
 * @return {Function}             The partially applied constructor.
 */
exports.partialConstructor = function fastPartialConstructor (fn) {
  var boundLength = arguments.length - 1,
      boundArgs;

  boundArgs = new Array(boundLength);
  for (var i = 0; i < boundLength; i++) {
    boundArgs[i] = arguments[i + 1];
  }
  return function partialed () {
    var length = arguments.length,
        args = new Array(boundLength + length),
        i;
    for (i = 0; i < boundLength; i++) {
      args[i] = boundArgs[i];
    }
    for (i = 0; i < length; i++) {
      args[boundLength + i] = arguments[i];
    }

    var thisContext = Object.create(fn.prototype),
        result = fn.apply(thisContext, args);

    if (result != null && (typeof result === 'object' || typeof result === 'function')) {
      return result;
    }
    else {
      return thisContext;
    }
  };
};

/**
 * # Clone
 *
 * Clone an item. Primitive values will be returned directly,
 * arrays and objects will be shallow cloned. If you know the
 * type of input you're dealing with, call `.cloneArray()` or `.cloneObject()`
 * instead.
 *
 * @param  {mixed} input The input to clone.
 * @return {mixed}       The cloned input.
 */
exports.clone = function clone (input) {
  if (!input || typeof input !== 'object') {
    return input;
  }
  else if (Array.isArray(input)) {
    return exports.cloneArray(input);
  }
  else {
    return exports.cloneObject(input);
  }
};

/**
 * # Clone Array
 *
 * Clone an array or array like object (e.g. `arguments`).
 * This is the equivalent of calling `Array.prototype.slice.call(arguments)`, but
 * significantly faster.
 *
 * @param  {Array} input The array or array-like object to clone.
 * @return {Array}       The cloned array.
 */
exports.cloneArray = function fastCloneArray (input) {
  var length = input.length,
      sliced = new Array(length),
      i;
  for (i = 0; i < length; i++) {
    sliced[i] = input[i];
  }
  return sliced;
};

/**
 * # Clone Object
 *
 * Shallow clone a simple object.
 *
 * > Note: Prototypes and non-enumerable properties will not be copied!
 *
 * @param  {Object} input The object to clone.
 * @return {Object}       The cloned object.
 */
exports.cloneObject = function fastCloneObject (input) {
  var keys = Object.keys(input),
      total = keys.length,
      cloned = {},
      i, key;

  for (i = 0; i < total; i++) {
    key = keys[i];
    cloned[key] = input[key];
  }

  return cloned;
};

/**
 * # Concat
 *
 * Concatenate multiple arrays.
 *
 * > Note: This function is effectively identical to `Array.prototype.concat()`.
 *
 *
 * @param  {Array|mixed} item, ... The item(s) to concatenate.
 * @return {Array}                 The array containing the concatenated items.
 */
exports.concat = function fastConcat () {
  var length = arguments.length,
      arr = [],
      i, item, childLength, j;

  for (i = 0; i < length; i++) {
    item = arguments[i];
    if (Array.isArray(item)) {
      childLength = item.length;
      for (j = 0; j < childLength; j++) {
        arr.push(item[j]);
      }
    }
    else {
      arr.push(item);
    }
  }
  return arr;
};

/**
 * # Map
 *
 * A fast `.map()` implementation.
 *
 * @param  {Array}    subject     The array (or array-like) to map over.
 * @param  {Function} fn          The mapper function.
 * @param  {Object}   thisContext The context for the mapper.
 * @return {Array}                The array containing the results.
 */
exports.map = function fastMap (subject, fn, thisContext) {
  var length = subject.length,
      result = new Array(length),
      i,
      iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn;
  for (i = 0; i < length; i++) {
    result[i] = iterator(subject[i], i, subject);
  }
  return result;
};

/**
 * # Filter
 *
 * A fast `.filter()` implementation.
 *
 * @param  {Array}    subject     The array (or array-like) to filter.
 * @param  {Function} fn          The filter function.
 * @param  {Object}   thisContext The context for the filter.
 * @return {Array}                The array containing the results.
 */
exports.filter = function fastFilter (subject, fn, thisContext) {
  var length = subject.length,
      result = [],
      i,
      iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn;
  for (i = 0; i < length; i++) {
    if (iterator(subject[i], i, subject)) {
      result.push(subject[i]);
    }
  }
  return result;
};

/**
 * # Reduce
 *
 * A fast `.reduce()` implementation.
 *
 * @param  {Array}    subject      The array (or array-like) to reduce.
 * @param  {Function} fn           The reducer function.
 * @param  {mixed}    initialValue The initial value for the reducer, defaults to subject[0].
 * @param  {Object}   thisContext  The context for the reducer.
 * @return {mixed}                 The final result.
 */
exports.reduce = function fastReduce (subject, fn, initialValue, thisContext) {
  var length = subject.length,
      iterator = thisContext !== undefined ? bindInternal4(fn, thisContext) : fn,
      i, result;

  if (initialValue === undefined) {
    i = 1;
    result = subject[0];
  }
  else {
    i = 0;
    result = initialValue;
  }

  for (; i < length; i++) {
    result = iterator(result, subject[i], i, subject);
  }

  return result;
};

/**
 * # For Each
 *
 * A fast `.forEach()` implementation.
 *
 * @param  {Array}    subject     The array (or array-like) to iterate over.
 * @param  {Function} fn          The visitor function.
 * @param  {Object}   thisContext The context for the visitor.
 */
exports.forEach = function fastForEach (subject, fn, thisContext) {
  var length = subject.length,
      i,
      iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn;
  for (i = 0; i < length; i++) {
    iterator(subject[i], i, subject);
  }
};

/**
 * # Index Of
 *
 * A faster `Array.prototype.indexOf()` implementation.
 *
 * @param  {Array}  subject   The array (or array-like) to search within.
 * @param  {mixed}  target    The target item to search for.
 * @param  {Number} fromIndex The position to start searching from, if known.
 * @return {Number}           The position of the target in the subject, or -1 if it does not exist.
 */
exports.indexOf = function fastIndexOf (subject, target, fromIndex) {
  var length = subject.length,
      i = 0;

  if (fromIndex !== undefined) {
    i = fromIndex >> 0;
    if (i < 0) {
      i += length;
      if (i < 0) {
        i = 0;
      }
    }
  }

  for (; i < length; i++) {
    if (subject[i] === target) {
      return i;
    }
  }
  return -1;
};

/**
 * # Last Index Of
 *
 * A faster `Array.prototype.lastIndexOf()` implementation.
 *
 * @param  {Array}  subject The array (or array-like) to search within.
 * @param  {mixed}  target  The target item to search for.
 * @param  {Number} fromIndex The position to start searching backwards from, if known.
 * @return {Number}         The last position of the target in the subject, or -1 if it does not exist.
 */
exports.lastIndexOf = function fastLastIndexOf (subject, target, fromIndex) {
  var length = subject.length,
      i = length - 1;

  if (fromIndex !== undefined) {
    i = fromIndex >> 0;
    if (i < 0) {
      i += length;
    }
  }
  for (; i >= 0; i--) {
    if (subject[i] === target) {
      return i;
    }
  }
  return -1;
};

/**
 * # Try
 *
 * Allows functions to be optimised by isolating `try {} catch (e) {}` blocks
 * outside the function declaration. Returns either the result of the function or an Error
 * object if one was thrown. The caller should then check for `result instanceof Error`.
 *
 * ```js
 * var result = fast.try(myFunction);
 * if (result instanceof Error) {
 *    console.log('something went wrong');
 * }
 * else {
 *   console.log('result:', result);
 * }
 * ```
 *
 * @param  {Function} fn The function to invoke.
 * @return {mixed}       The result of the function, or an `Error` object.
 */
exports['try'] = function fastTry (fn) {
  try {
    return fn();
  }
  catch (e) {
    if (!(e instanceof Error)) {
      return new Error(e);
    }
    else {
      return e;
    }
  }
};

// alias of `.try()` for older JS engines.
exports.attempt = exports['try'];

/**
 * # Apply
 *
 * Faster version of `Function::apply()`, optimised for 8 arguments or fewer.
 *
 *
 * @param  {Function} subject   The function to apply.
 * @param  {Object} thisContext The context for the function, set to undefined or null if no context is required.
 * @param  {Array} args         The arguments for the function.
 * @return {mixed}              The result of the function invocation.
 */
exports.apply = function fastApply (subject, thisContext, args) {
  return thisContext != null ? applyWithContext(subject, thisContext, args) : applyNoContext(subject, args);
};

/**
 * Internal helper for applying a function with a context.
 */
function applyWithContext (subject, thisContext, args) {
  switch (args.length) {
    case 0:
      return subject.call(thisContext);
    case 1:
      return subject.call(thisContext, args[0]);
    case 2:
      return subject.call(thisContext, args[0], args[1]);
    case 3:
      return subject.call(thisContext, args[0], args[1], args[2]);
    case 4:
      return subject.call(thisContext, args[0], args[1], args[2], args[3]);
    case 5:
      return subject.call(thisContext, args[0], args[1], args[2], args[3], args[4]);
    case 6:
      return subject.call(thisContext, args[0], args[1], args[2], args[3], args[4], args[5]);
    case 7:
      return subject.call(thisContext, args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
    case 8:
      return subject.call(thisContext, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
    default:
      return subject.apply(thisContext, args);
  }
}

/**
 * Internal helper for applying a function without a context.
 */
function applyNoContext (subject, args) {
  switch (args.length) {
    case 0:
      return subject();
    case 1:
      return subject(args[0]);
    case 2:
      return subject(args[0], args[1]);
    case 3:
      return subject(args[0], args[1], args[2]);
    case 4:
      return subject(args[0], args[1], args[2], args[3]);
    case 5:
      return subject(args[0], args[1], args[2], args[3], args[4]);
    case 6:
      return subject(args[0], args[1], args[2], args[3], args[4], args[5]);
    case 7:
      return subject(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
    case 8:
      return subject(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
    default:
      return subject.apply(undefined, args);
  }
}

/**
 * Internal helper to bind a function known to have 3 arguments
 * to a given context.
 */
function bindInternal3 (func, thisContext) {
  return function (a, b, c) {
    return func.call(thisContext, a, b, c);
  };
}

/**
 * Internal helper to bind a function known to have 4 arguments
 * to a given context.
 */
function bindInternal4 (func, thisContext) {
  return function (a, b, c, d) {
    return func.call(thisContext, a, b, c, d);
  };
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Gloeosporium cocculi var. ramicola Sacc.

### Remarks
null


text:
@import url("../../components/designerCommon/css/common.css");
.form-horizontal .form-group {
  margin-left: 0px;
  margin-right: 0px;
}


text:
export default Ember.ArrayController.extend({
    queryParams : ['start_date', 'end_date', 'per_page', 'page', 'sort'],
    start_date  : null,
    end_date    : null,
    per_page    : 1,
    page        : 0,
    sort        : 'DESC', // 'ASC'

    rangeOfData : function() {

      var dataPoints = this.get('model');

      var start_date = this.get('start_date');
      var end_date   = this.get('end_date');
      var per_page   = this.get('per_page');
      var page       = this.get('page');
      var sort       = this.get('sort');

      return dataPoints.filterProperty('start_date', start_date);

    }.property('start_date', 'end_date', 'per_page', 'page', 'sort', 'model'),

    totalDataPoints: function() {
      return this.get('model.length');
    }.property('@each')
  });


text:
using System;

namespace Spine {
	/// <summary>Attachment that displays a texture region.</summary>
	public class MeshAttachment : Attachment {
		internal float[] vertices, uvs, regionUVs;
		internal int[] triangles;
		internal float regionOffsetX, regionOffsetY, regionWidth, regionHeight, regionOriginalWidth, regionOriginalHeight;
		internal float r = 1, g = 1, b = 1, a = 1;

		public int HullLength { get; set; }
		public float[] Vertices { get { return vertices; } set { vertices = value; } }
		public float[] RegionUVs { get { return regionUVs; } set { regionUVs = value; } }
		public float[] UVs { get { return uvs; } set { uvs = value; } }
		public int[] Triangles { get { return triangles; } set { triangles = value; } }

		public float R { get { return r; } set { r = value; } }
		public float G { get { return g; } set { g = value; } }
		public float B { get { return b; } set { b = value; } }
		public float A { get { return a; } set { a = value; } }

		public String Path { get; set; }
		public Object RendererObject { get; set; }
		public float RegionU { get; set; }
		public float RegionV { get; set; }
		public float RegionU2 { get; set; }
		public float RegionV2 { get; set; }
		public bool RegionRotate { get; set; }
		public float RegionOffsetX { get { return regionOffsetX; } set { regionOffsetX = value; } }
		public float RegionOffsetY { get { return regionOffsetY; } set { regionOffsetY = value; } } // Pixels stripped from the bottom left, unrotated.
		public float RegionWidth { get { return regionWidth; } set { regionWidth = value; } }
		public float RegionHeight { get { return regionHeight; } set { regionHeight = value; } } // Unrotated, stripped size.
		public float RegionOriginalWidth { get { return regionOriginalWidth; } set { regionOriginalWidth = value; } }
		public float RegionOriginalHeight { get { return regionOriginalHeight; } set { regionOriginalHeight = value; } } // Unrotated, unstripped size.

		// Nonessential.
		public int[] Edges { get; set; }
		public float Width { get; set; }
		public float Height { get; set; }

		public MeshAttachment (string name)
			: base(name) {
		}

		public void UpdateUVs () {
			float u = RegionU, v = RegionV, width = RegionU2 - RegionU, height = RegionV2 - RegionV;
			float[] regionUVs = this.regionUVs;
			if (this.uvs == null || this.uvs.Length != regionUVs.Length) this.uvs = new float[regionUVs.Length];
			float[] uvs = this.uvs;
			if (RegionRotate) {
				for (int i = 0, n = uvs.Length; i < n; i += 2) {
					uvs[i] = u + regionUVs[i + 1] * width;
					uvs[i + 1] = v + height - regionUVs[i] * height;
				}
			} else {
				for (int i = 0, n = uvs.Length; i < n; i += 2) {
					uvs[i] = u + regionUVs[i] * width;
					uvs[i + 1] = v + regionUVs[i + 1] * height;
				}
			}
		}

		public void ComputeWorldVertices (Slot slot, float[] worldVertices) {
			Bone bone = slot.bone;
			float x = bone.skeleton.x + bone.worldX, y = bone.skeleton.y + bone.worldY;
			float m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11;
			float[] vertices = this.vertices;
			int verticesCount = vertices.Length;
			if (slot.attachmentVerticesCount == verticesCount) vertices = slot.AttachmentVertices;
			for (int i = 0; i < verticesCount; i += 2) {
				float vx = vertices[i];
				float vy = vertices[i + 1];
				worldVertices[i] = vx * m00 + vy * m01 + x;
				worldVertices[i + 1] = vx * m10 + vy * m11 + y;
			}
		}
	}
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle("ByteSmith.WindowsAzure.Messaging.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ByteSmith")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Sascha Dittmann")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.

[assembly: AssemblyVersion("1.0.1.*")]
[assembly: AssemblyFileVersion("1.0.1")]

// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]


text:
require 'digest'

class Account

  include Locomotive::Mongoid::Document

  # devise modules
  devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable

  # attr_accessible :email, :password, :password_confirmation # TODO

  ## attributes ##
  field :name
  field :locale, :default => 'en'
  field :switch_site_token

  ## validations ##
  validates_presence_of :name

  ## associations ##

  ## callbacks ##
  before_destroy :remove_memberships!

  ## methods ##

  def sites
    @sites ||= Site.where({ 'memberships.account_id' => self._id })
  end

  def reset_switch_site_token!
    self.switch_site_token = ActiveSupport::SecureRandom.base64(8).gsub("/", "_").gsub(/=+$/, "")
    self.save
  end

  def self.find_using_switch_site_token(token, age = 1.minute)
    return if token.blank?
    self.where(:switch_site_token => token, :updated_at.gt => age.ago.utc).first
  end

  def self.find_using_switch_site_token!(token, age = 1.minute)
    self.find_using_switch_site_token(token, age) || raise(Mongoid::Errors::DocumentNotFound.new(self, token))
  end

  protected

  def password_required?
    !persisted? || !password.blank? || !password_confirmation.blank?
  end

  def remove_memberships!
    self.sites.each do |site|
      site.memberships.delete_if { |m| m.account_id == self._id }

      if site.admin_memberships.empty?
        raise I18n.t('errors.messages.needs_admin_account')
      else
        site.save
      end
    end
  end

end


text:
package org.wso2.carbon.identity.oauth;

import org.apache.commons.io.Charsets;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xml.security.utils.Base64;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.application.common.model.User;
import org.wso2.carbon.identity.oauth.cache.CacheKey;
import org.wso2.carbon.identity.oauth.cache.OAuthCache;
import org.wso2.carbon.identity.oauth.cache.OAuthCacheKey;
import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
import org.wso2.carbon.identity.oauth2.util.OAuth2Util;
import org.wso2.carbon.registry.core.utils.UUIDGenerator;
import org.wso2.carbon.user.core.util.UserCoreUtil;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public final class OAuthUtil {

    public static final Log log = LogFactory.getLog(OAuthUtil.class);

    private OAuthUtil(){

    }

    /**
     * Generates a random number using two UUIDs and HMAC-SHA1
     *
     * @return generated secure random number
     * @throws IdentityOAuthAdminException Invalid Algorithm or Invalid Key
     */
    public static String getRandomNumber() throws IdentityOAuthAdminException {
        try {
            String secretKey = UUIDGenerator.generateUUID();
            String baseString = UUIDGenerator.generateUUID();

            SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(Charsets.UTF_8), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(key);
            byte[] rawHmac = mac.doFinal(baseString.getBytes(Charsets.UTF_8));
            String random = Base64.encode(rawHmac);
            // Registry doesn't have support for these character.
            random = random.replace("/", "_");
            random = random.replace("=", "a");
            random = random.replace("+", "f");
            return random;
        } catch (Exception e) {
            throw new IdentityOAuthAdminException("Error when generating a random number.", e);
        }
    }

    public static void clearOAuthCache(String consumerKey, User authorizedUser) {

        String user = UserCoreUtil.addDomainToName(authorizedUser.getUserName(), authorizedUser.getUserStoreDomain());
        user = UserCoreUtil.addTenantDomainToEntry(user, authorizedUser.getTenantDomain());
        clearOAuthCache(consumerKey, user);
    }

    public static void clearOAuthCache(String consumerKey, User authorizedUser, String scope) {

        String user = UserCoreUtil.addDomainToName(authorizedUser.getUserName(), authorizedUser.getUserStoreDomain());
        user = UserCoreUtil.addTenantDomainToEntry(user, authorizedUser.getTenantDomain());
        clearOAuthCache(consumerKey, user, scope);
    }

    public static void clearOAuthCache(String consumerKey, String authorizedUser) {
        boolean isUsernameCaseSensitive = OAuth2Util.isUsernameCaseSensitive(authorizedUser);
        if (!isUsernameCaseSensitive){
            authorizedUser = authorizedUser.toLowerCase();
        }
        clearOAuthCache(consumerKey + ":" + authorizedUser);
    }

    public static void clearOAuthCache(String consumerKey, String authorizedUser, String scope) {
        boolean isUsernameCaseSensitive = OAuth2Util.isUsernameCaseSensitive(authorizedUser);
        if (!isUsernameCaseSensitive){
            authorizedUser = authorizedUser.toLowerCase();
        }
        clearOAuthCache(consumerKey + ":" + authorizedUser + ":" + scope);
    }

    public static void clearOAuthCache(String oauthCacheKey) {
        OAuthCache oauthCache;
        try {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                    .getThreadLocalCarbonContext();
            carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
            carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

            CacheKey cacheKey = new OAuthCacheKey(oauthCacheKey);
            if (OAuthServerConfiguration.getInstance().isCacheEnabled()) {
                oauthCache = OAuthCache.getInstance(OAuthServerConfiguration.getInstance().getOAuthCacheTimeout());
                oauthCache.clearCacheEntry(cacheKey);
            }
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }

}


text:
ACCEPTED

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

#### Published in
null

#### Original name
Helotium chloropodium Rea & Ellis, 1911

### Remarks
null