Example usage for org.apache.commons.collections BinaryHeap size

List of usage examples for org.apache.commons.collections BinaryHeap size

Introduction

In this page you can find the example usage for org.apache.commons.collections BinaryHeap size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this heap.

Usage

From source file:com.silverwrist.dynamo.app.ApplicationContainer.java

/**
 * Creates the application container./*w ww.j a  va  2  s.co m*/
 *
 * @param config_file A reference to the Dynamo XML configuration file.
 * @param substrate A reference to the {@link com.silverwrist.dynamo.iface.ApplicationSubstrate ApplicationSubstrate}
 *                  object, which provides certain services and object references to the
 *                  <CODE>ApplicationContainer</CODE>.  (Usually, this will be specific to the Dynamo application
 *                  type, for example, Web application.)
 * @exception com.silverwrist.dynamo.except.ConfigException If there is an error in the configuration which will
 *            not allow Dynamo to be initialized.
 */
public ApplicationContainer(File config_file, ApplicationSubstrate substrate) throws ConfigException {
    if (logger.isDebugEnabled())
        logger.debug("new ApplicationContainer - config file is " + config_file.getAbsolutePath());
    substrate.initialize();
    m_substrate = substrate;
    m_refs = 1;
    m_app_sm = new ApplicationServiceManager();
    m_pss = new PropertySerializationSupport();
    m_known_sessions = Collections.synchronizedSet(new HashSet());
    XMLLoader loader = XMLLoader.get();

    // Initialize the init services and runtime services with defaults.
    m_app_sm.addInitService(ResourceProvider.class, (ResourceProvider) this);
    m_app_sm.addInitService(ResourceProviderManager.class, (ResourceProviderManager) this);
    m_app_sm.addInitService(RendererRegistration.class, (RendererRegistration) this);
    m_app_sm.addInitService(ObjectProvider.class, (ObjectProvider) this);
    m_app_sm.addInitService(EventListenerRegistration.class, (EventListenerRegistration) this);
    m_app_sm.addInitService(OutputObjectFilterRegistration.class, (OutputObjectFilterRegistration) this);
    m_app_sm.addInitService(PropertySerializer.class, (PropertySerializer) m_pss);
    m_app_sm.addInitService(PropertySerializerRegistration.class, (PropertySerializerRegistration) m_pss);
    m_app_sm.addInitService(PostDynamicUpdate.class, (PostDynamicUpdate) this);
    m_app_sm.addInitService(RequestPreprocessorRegistration.class, (RequestPreprocessorRegistration) this);
    m_app_sm.addInitService(ExceptionTranslatorRegistration.class, (ExceptionTranslatorRegistration) this);
    m_app_sm.addInitService(FinalStageRegistration.class, (FinalStageRegistration) this);

    m_app_sm.addRuntimeService(ResourceProvider.class, (ResourceProvider) this);
    m_app_sm.addRuntimeService(ObjectProvider.class, (ObjectProvider) this);
    m_app_sm.addRuntimeService(EventListenerRegistration.class, (EventListenerRegistration) this);
    m_app_sm.addRuntimeService(PropertySerializer.class, (PropertySerializer) m_pss);
    m_app_sm.addRuntimeService(PostDynamicUpdate.class, (PostDynamicUpdate) this);
    m_app_sm.addRuntimeService(RenderImmediate.class, (RenderImmediate) this);

    m_app_sm.addOutputService(ResourceProvider.class, (ResourceProvider) this);
    m_app_sm.addOutputService(ObjectProvider.class, (ObjectProvider) this);
    m_app_sm.addOutputService(QueryRenderer.class, (QueryRenderer) this);

    // Create initialization services interface object.
    ServiceProvider init_svcs = m_app_sm.createInitServices();

    try { // load the configuration file
        Document config_doc = loader.load(config_file, false);
        Element root = loader.getRootElement(config_doc, "configuration");

        // get the <control/> element and process it
        Element control = loader.getSubElement(root, "control");
        processControlSection(control);
        m_shutdown_list.addFirst(m_background);
        m_app_sm.addInitService(BackgroundScheduler.class, m_background);
        m_app_sm.addRuntimeService(BackgroundScheduler.class, m_background);

        // initialize some default renderers
        m_shutdown_list.addFirst(registerRenderer(DataItem.class, new DataItemRenderer()));
        m_shutdown_list.addFirst(registerRenderer(java.util.List.class, new ListRenderer()));

        // initialize the scripting engine
        m_script_ctrl = new ScriptController();
        m_script_ctrl.initialize(control, init_svcs);
        m_shutdown_list.addFirst(m_script_ctrl);

        // add the scripting engine's services so they can be used by external components
        m_app_sm.addInitService(ScriptEngineConfig.class, m_script_ctrl);
        m_app_sm.addRuntimeService(ScriptExecute.class, m_script_ctrl);

        // get all database connection configurations
        List l = loader.getMatchingSubElements(root, "dbconnection");
        Iterator it = l.iterator();
        Element elt;
        while (it.hasNext()) { // get each element in turn
            elt = (Element) (it.next());
            DBConnectionPool pool = (DBConnectionPool) createNamedObject(elt, init_svcs, DBConnectionPool.class,
                    "no.notDBPool");
            m_connections.put(pool.getName(), pool);

        } // end while

        m_app_sm.addInitService(HookServiceProviders.class, m_app_sm);

        // Sort the "object" definitions by priority order to determine in what order to instantiate them.
        l = loader.getMatchingSubElements(root, "object");
        if (!(l.isEmpty())) { // copy elements into binary heap 
            it = l.iterator();
            BinaryHeap prioheap = new BinaryHeap(l.size());
            while (it.hasNext()) { // sort elements by priority 
                elt = (Element) (it.next());
                prioheap.insert(new HeapContents(elt));

            } // end while

            while (prioheap.size() > 0) { // now remove and instantiate the elements
                HeapContents hc = (HeapContents) (prioheap.remove());
                NamedObject nobj = createNamedObject(hc.getElement(), init_svcs, null, null);
                m_objects.put(nobj.getName(), nobj);

            } // end while

        } // end if

        // Find the application definition and initialize the application.
        elt = loader.getSubElement(root, "application");
        m_application = (Application) createNamedObject(elt, init_svcs, Application.class, "no.notApp");

    } // end try
    catch (IOException e) { // unable to read config file - send back a ConfigException
        logger.fatal("ApplicationContainer config read failed", e);
        ConfigException ce = new ConfigException(ApplicationContainer.class, "ApplicationContainerMessages",
                "creation.ioError", e);
        ce.setParameter(0, config_file.getAbsolutePath());
        throw ce;

    } // end catch
    catch (XMLLoadException e) { // XML loader failed - send back a ConfigException
        logger.fatal("ApplicationContainer config load failed", e);
        throw new ConfigException(e);

    } // end catch

    // Create the "server identity" string.
    StringBuffer buf = new StringBuffer();
    String app_id = m_application.getIdentity();
    if (app_id != null)
        buf.append(app_id).append(' ');
    buf.append("Dynamo/").append(DynamoVersion.VERSION);
    m_identity = buf.toString();
    logger.info("Server: " + m_identity);

    try { // Call the "final stage" initialization hooks.
        logger.info(m_final_stage_inits.size() + " final-stage init hook(s) to call");
        while (!(m_final_stage_inits.isEmpty())) { // call the hooks in FIFO order
            FinalStageInitHook hook = (FinalStageInitHook) (m_final_stage_inits.removeFirst());
            hook.initialize(m_application, init_svcs);

        } // end while

        m_final_stage_inits = null; // done with this list

    } // end try
    catch (DynamoException e) { // final-stage initialization failed - post an error
        ConfigException ce = new ConfigException(ApplicationContainer.class, "ApplicationContainerMessages",
                "finalinit.fail", e);
        ce.setParameter(0, e.getMessage());
        throw ce;

    } // end catch

    // Fire the "application initialized" events.
    ApplicationListener[] listeners = (ApplicationListener[]) (m_application_listeners
            .toArray(APP_LISTENER_TEMPLATE));
    if (listeners.length > 0) { // call the event handlers...
        if (logger.isDebugEnabled())
            logger.debug("ApplicationContainer: " + listeners.length + " init handler(s) to call");
        ApplicationEventRequest req = new ApplicationEventRequest(m_app_sm.createRuntimeServices(), true);
        ApplicationEvent evt = new ApplicationEvent(req, m_application);
        for (int i = 0; i < listeners.length; i++)
            listeners[i].applicationInitialized(evt);

    } // end if

    if (logger.isDebugEnabled())
        logger.debug("ApplicationContainer initialization done");

}

From source file:com.opendoorlogistics.core.scripts.formulae.FmLookupNearest.java

@Override
public Object execute(FunctionParameters parameters) {
    TableParameters tp = (TableParameters) parameters;
    ODLTableReadOnly table = (ODLTableReadOnly) tp.getTableById(refs.datastoreIndx, refs.tableId);

    if (type == LCType.LL) {
        return executeLL(parameters, table);
    }//from  w  w  w. ja  v a 2s  .c o m

    CachedProcessedGeom searchObject = getSearchGeom(parameters);
    if (searchObject == null || searchObject.geometry == null) {
        return Functions.EXECUTION_ERROR;
    }

    class RowElement implements Comparable<RowElement> {
        int row;
        CachedProcessedGeom geom;
        double minDistance;

        @Override
        public int compareTo(RowElement o) {
            int ret = Double.compare(minDistance, o.minDistance);
            if (ret == 0) {
                ret = Integer.compare(row, o.row);
            }
            return ret;
        }
    }

    // Get all geometries, transformed into the coord system and with bounding circles.
    // Place them in a binary heap, sorted by their minimum possible distance according to bounding circle
    int nr = table.getRowCount();
    BinaryHeap sortedHeap = new BinaryHeap();
    for (int row = 0; row < nr; row++) {
        CachedProcessedGeom otherGeom = null;
        switch (type) {
        case GL:
            Pair<LatLong, Boolean> result = getLatLongFromRow(table, row);
            if (result.getSecond() == false) {
                // critical error
                return Functions.EXECUTION_ERROR;
            } else if (result.getFirst() != null) {

                LatLong ll = result.getFirst();

                // put into our comparison object and convert
                otherGeom = new CachedProcessedGeom(ll, transform);
            }
            break;

        case GG:
        case LG: {
            Object val = table.getValueAt(row, refs.columnIndices[0]);
            if (val != null) {

                ODLGeomImpl odlGeom = (ODLGeomImpl) ColumnValueProcessor.convertToMe(ODLColumnType.GEOM, val);
                if (odlGeom == null) {
                    // critical error
                    return Functions.EXECUTION_ERROR;
                }

                otherGeom = toCoordSystem(odlGeom);
                if (otherGeom == null || otherGeom.geometry == null) {
                    // critical error
                    return Functions.EXECUTION_ERROR;
                }
            }
        }
        default:
            break;
        }

        if (otherGeom != null) {
            RowElement rowElement = new RowElement();
            rowElement.row = row;
            rowElement.minDistance = searchObject.boundingCircle.minimumSeparation(otherGeom.boundingCircle);
            rowElement.geom = otherGeom;
            sortedHeap.add(rowElement);
        }
    }

    // loop over the table
    RowElement closest = null;
    double closestDistance = Double.MAX_VALUE;
    while (sortedHeap.size() > 0) {
        RowElement row = (RowElement) sortedHeap.pop();
        if (row.minDistance > closestDistance) {
            // We can stop searching now as the minimum possible distance is greater than our closest
            break;
        }

        // Explicitly get the distance
        double distance = searchObject.geometry.distance(row.geom.geometry);
        if (distance < closestDistance) {
            closestDistance = distance;
            closest = row;
        }
    }

    if (closest != null) {
        return getReturnObject(table, closest.row);
    }

    return null;
}