Example usage for org.apache.commons.collections.buffer CircularFifoBuffer CircularFifoBuffer

List of usage examples for org.apache.commons.collections.buffer CircularFifoBuffer CircularFifoBuffer

Introduction

In this page you can find the example usage for org.apache.commons.collections.buffer CircularFifoBuffer CircularFifoBuffer.

Prototype

public CircularFifoBuffer(Collection coll) 

Source Link

Document

Constructor that creates a buffer from the specified collection.

Usage

From source file:com.xpn.xwiki.monitor.api.MonitorPlugin.java

public void reset(XWikiContext context) {
    timerSummaries = new HashMap();
    activeTimerDataList = new HashMap();
    duration = 0;/*from w w w. j a  v a2s  . c  o  m*/
    nbrequests = 0;
    long size = context.getWiki().ParamAsLong("xwiki.monitor.lastlistsize", 20);
    lastTimerDataList = new CircularFifoBuffer((int) size);
    lastUnfinishedTimerDataList = new CircularFifoBuffer((int) size);
}

From source file:com.neophob.sematrix.jmx.PixelControllerStatus.java

/**
 * Register the JMX Bean./*from   ww w  .java 2  s.co  m*/
 *
 * @param configuredFps the configured fps
 */
public PixelControllerStatus(int configuredFps) {
    LOG.log(Level.INFO, "Initialize the PixelControllerStatus JMX Bean");

    this.configuredFps = configuredFps;

    // initialize all buffers 
    this.timeMeasureMapGlobal = new ConcurrentHashMap<TimeMeasureItemGlobal, CircularFifoBuffer>();
    for (TimeMeasureItemGlobal timeMeasureItem : TimeMeasureItemGlobal.values()) {
        this.timeMeasureMapGlobal.put(timeMeasureItem, new CircularFifoBuffer(this.configuredFps * SECONDS));
    }
    this.timeMeasureMapOutput = new ConcurrentHashMap<Output, Map<TimeMeasureItemOutput, CircularFifoBuffer>>();
    this.outputList = new ArrayList<Output>();

    startTime = System.currentTimeMillis();

    // register MBean
    try {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = new ObjectName(JMX_BEAN_NAME);
        // check if the MBean is already registered
        if (!server.isRegistered(name)) {
            server.registerMBean(this, name);
        }
    } catch (JMException ex) {
        LOG.log(Level.WARNING, "Error while registering class as JMX Bean.", ex);
    }
}

From source file:edu.umn.msi.tropix.webgui.server.messages.MessageManager.java

public Collection<T> drainQueue() {
    final HttpSession session = httpSessionSupplier.get();
    final String sessionId = session.getId();
    final String userId = userSession.getGridId();
    final List<T> objects = Lists.newArrayList();
    if (userId == null) {
        return objects;
    }//from ww w  . j  a  v a 2  s .co  m
    CircularFifoBuffer queue;
    synchronized (userToSessionMap) {
        if (!userToSessionMap.containsEntry(userId, sessionId)) {
            final CloseWithSession finalizer = new CloseWithSession(userId, sessionId);
            session.setAttribute("messageManagerFinalizingObject", finalizer);
            userToSessionMap.put(userId, sessionId);
            sessionToUserMap.put(sessionId, userId);
        }
        if (!bufferMap.containsKey(sessionId)) {
            final CircularFifoBuffer objectBuffer = new CircularFifoBuffer(25);
            bufferMap.put(sessionId, objectBuffer);
        }
        queue = bufferMap.get(sessionId);
    }
    synchronized (queue) {
        while (!queue.isEmpty()) {
            @SuppressWarnings("unchecked")
            final T object = (T) queue.remove();
            if (object == null) {
                break;
            }
            objects.add(object);
        }
    }
    return objects;
}

From source file:com.neophob.sematrix.core.jmx.PixelControllerStatus.java

/**
 * Register the JMX Bean.//from w w  w  . j a  v a2s .c o  m
 *
 * @param configuredFps the configured fps
 */
public PixelControllerStatus(Collector col, int configuredFps) {
    LOG.log(Level.INFO, "Initialize the PixelControllerStatus JMX Bean");

    this.configuredFps = configuredFps;
    this.col = col;

    // initialize all buffers 
    this.timeMeasureMapGlobal = new ConcurrentHashMap<TimeMeasureItemGlobal, CircularFifoBuffer>();
    for (TimeMeasureItemGlobal timeMeasureItem : TimeMeasureItemGlobal.values()) {
        this.timeMeasureMapGlobal.put(timeMeasureItem, new CircularFifoBuffer(this.configuredFps * SECONDS));
    }
    this.timeMeasureMapOutput = new ConcurrentHashMap<IOutput, Map<TimeMeasureItemOutput, CircularFifoBuffer>>();
    this.outputList = new ArrayList<IOutput>();

    startTime = System.currentTimeMillis();

    // register MBean
    try {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = new ObjectName(JMX_BEAN_NAME);
        // check if the MBean is already registered
        if (!server.isRegistered(name)) {
            server.registerMBean(this, name);
        }
    } catch (JMException ex) {
        LOG.log(Level.WARNING, "Error while registering class as JMX Bean.", ex);
    }
}

From source file:de.suse.swamp.modules.screens.SWAMPScreen.java

public void provideData(RunData data, Context context) throws Exception {
    SWAMPAPI swampapi = new SWAMPAPI();
    String uname = data.getUser().getName();
    // make stuff available to all pages:
    context.put("datastates", new FieldMethodizer("de.suse.swamp.core.data.Data"));
    context.put("taskstates", new FieldMethodizer("de.suse.swamp.core.tasks.WorkflowTask"));
    // provide Bugzilla URL
    context.put("bugzilla_url", swampapi.doGetProperty("BUGZILLA_BROWSERURL", uname));
    // provide Session id:
    context.put("sessionid", data.getRequest().getRequestedSessionId());
    // pointer to Turbine configuration
    context.put("turbineconf", org.apache.turbine.Turbine.getConfiguration());
    context.put("adminEmail", swampapi.doGetProperty("POSTMASTER", uname));
    context.put("swampVersion", swampapi.doGetProperty("SWAMP_VERSION", uname));
    context.put("data", data);
    context.put("swampuser", data.getUser());
    context.put("date", new DateTool());

    // if there is a helppage available, propagade it.
    // may be overridden by special help pages, set from the templates
    ArrayList helps = new ArrayList();
    // there may already be helplinks
    if (context.get("helps") != null) {
        helps = (ArrayList) context.get("helps");
    }//from   w w  w  . j  a v  a  2  s.c om
    ContextHelp help = new DocumentationAPI().getContextHelp("help." + data.getScreen(), uname);
    if (help != null) {
        helps.add(help);
        context.put("helps", helps);
    }

    // switch for print-view
    if (data.getParameters().containsKey("printview")) {
        data.setLayoutTemplate("PrintLayout.vm");
        context.put("printview", data.getParameters().get("printview"));
    }

    // store last page parameters temporary
    CircularFifoBuffer pageBuffer = (CircularFifoBuffer) data.getUser().getTemp("pageBuffer",
            new CircularFifoBuffer(2));

    org.apache.turbine.util.parser.ParameterParser params = data.getParameters();
    SWAMPHashMap map = new SWAMPHashMap();
    for (Iterator it = params.keySet().iterator(); it.hasNext();) {
        String key = (String) it.next();
        if (!key.equals("action")) {
            map.put(key, params.getObject(key));
        }
    }
    pageBuffer.add(map);
    data.getUser().setTemp("pageBuffer", pageBuffer);

}

From source file:eu.esdihumboldt.hale.ui.service.project.internal.RecentProjectsServiceImpl.java

private CircularFifoBuffer restoreState() {
    PreferencesService prefs = OsgiUtils.getService(PreferencesService.class);

    CircularFifoBuffer buffer = new CircularFifoBuffer(MAX_FILES);
    String configString = prefs.getSystemPreferences().get(CONFIG_PROPERTY, "");

    List<String> parts = Splitter.on(' ').splitToList(configString);

    buffer.clear();//from www  .j a  va 2 s  . c  o m
    for (int i = 0; i < parts.size() - 1; i += 2) {
        try {
            String name = URLDecoder.decode(parts.get(i), ENC);
            String filename = URLDecoder.decode(parts.get(i + 1), ENC);

            Entry entry = new EntryImpl(filename, name);
            buffer.add(entry);
        } catch (UnsupportedEncodingException e) {
            log.error(ENC + "? That's supposed to be an encoding?", e);
        }
    }
    return buffer;
}

From source file:com.redhat.rhn.common.util.FileUtils.java

/**
 * Reads and returns the last n lines from a given file as string.
 * @param pathToFile path to file/*w ww  .  ja  va  2s. com*/
 * @param lines size of the tail
 * @return tail of file as string
 */
public static String getTailOfFile(String pathToFile, Integer lines) {
    InputStream fileStream = null;
    CircularFifoBuffer buffer = new CircularFifoBuffer(lines);
    try {
        fileStream = new FileInputStream(pathToFile);
        LineIterator it = org.apache.commons.io.IOUtils.lineIterator(fileStream, (String) null);
        while (it.hasNext()) {
            buffer.add(it.nextLine());
        }
    } catch (FileNotFoundException e) {
        log.error("File not found: " + pathToFile);
        throw new RuntimeException(e);
    } catch (IOException e) {
        log.error("Could not read from: " + pathToFile);
        throw new RuntimeException(e);
    } finally {
        org.apache.commons.io.IOUtils.closeQuietly(fileStream);
    }
    // Construct a string from the buffered lines
    StringBuilder sb = new StringBuilder();
    for (Object s : buffer) {
        sb.append(s);
        sb.append(System.getProperty("line.separator"));
    }
    return sb.toString();
}

From source file:com.xpn.xwiki.stats.impl.XWikiStatsServiceImpl.java

@Override
public void onEvent(Event event, Object source, Object data) {
    if (Utils.getComponent(RemoteObservationManagerContext.class).isRemoteState()) {
        // we do nothing when the event comes from remote instance since the remote instance is supposed to already
        // take care of this
        return;//from   ww w. ja  va 2s  .  c  o  m
    }

    ActionExecutedEvent actionEvent = (ActionExecutedEvent) event;
    XWikiDocument document = (XWikiDocument) source;
    XWikiContext context = (XWikiContext) data;

    // If the server is in read-only mode, forget about the statistics (since it's in read only mode we don't write
    // anything in the database)
    if (context.getWiki().isReadOnly()) {
        return;
    }

    // Initialize cookie used as unique identifier of a user visit and put it in the context
    StatsUtil.findCookie(context);

    String action = actionEvent.getActionName();

    // Let's save in the session the last elements view, saved
    synchronized (this) {
        if (!action.equals(DownloadAction.ACTION_NAME)) {
            Collection actions = StatsUtil.getRecentActionFromSessions(context, action);
            if (actions == null) {
                actions = new CircularFifoBuffer(StatsUtil.getRecentVisitSize(context));
                StatsUtil.setRecentActionsFromSession(context, action, actions);
            }

            String element = document.getPrefixedFullName();
            if (actions.contains(element)) {
                actions.remove(element);
            }
            actions.add(element);
        }
    }

    try {
        if (StatsUtil.isWikiStatsEnabled(context) && !StatsUtil.getStorageFilteredUsers(context)
                .contains(this.currentDocumentReferenceResolver.resolve(context.getUser()))) {
            this.statsRegister.addStats(document, action, context);
        }
    } catch (Exception e) {
        LOGGER.error("Faild to get filter users list", e);
    }
}

From source file:com.siemens.industrialbenchmark.dynamics.IndustrialBenchmarkDynamics.java

/**
 * initialize the industrial benchmark/*from   www.j a va2  s.  co  m*/
 * @throws PropertiesException
 */
protected void init() throws PropertiesException {

    // configure convolution variables
    CRGS = PropertiesUtil.getFloat(mProperties, "CRGS", true);
    mEmConvWeights = getFloatArray(mProperties.getProperty("ConvArray"));
    markovStateAdditionalNames = new ArrayList<String>();
    mOperationalCostsBuffer = new CircularFifoBuffer(mEmConvWeights.length);
    for (int i = 0; i < mEmConvWeights.length; i++) {
        mOperationalCostsBuffer.add(0.0d); // initialize all operationalcosts with zero
        markovStateAdditionalNames.add("OPERATIONALCOST_" + i); // add operationalcost_lag to list of convoluted markov variables
    }
    markovStateAdditionalNames.addAll(MarkovianStateDescription.getNonConvolutedInternalVariables());

    // add variables from external driver
    List<String> extNames = new ArrayList<String>();
    for (ExternalDriver d : this.externalDrivers) {
        for (String n : d.getState().getKeys()) {
            if (!extNames.contains(n)) {
                extNames.add(n);
            }
        }
    }
    markovStateAdditionalNames.addAll(extNames);
    //markovStateAdditionalNames.addAll(extDriver.getState().getKeys());       

    // instantiate markov state with additional convolution variable names
    markovState = new MarkovianState(markovStateAdditionalNames);
    mMin = new MarkovianState(markovStateAdditionalNames); // lower variable boundaries
    mMax = new MarkovianState(markovStateAdditionalNames); // upper variable boundaries

    // extract variable boundings + initial values from Properties 
    for (String v : this.markovState.getKeys()) {
        float init = PropertiesUtil.getFloat(mProperties, v + "_INIT", 0);
        float max = PropertiesUtil.getFloat(mProperties, v + "_MAX", Float.MAX_VALUE);
        float min = PropertiesUtil.getFloat(mProperties, v + "_MIN", -Float.MAX_VALUE);
        Preconditions.checkArgument(max > min, "variable=%s: max=%s must be > than min=%s", v, max, min);
        Preconditions.checkArgument(init >= min && init <= max,
                "variable=%s: init=%s must be between min=%s and max=%s", v, init, min, max);
        mMax.setValue(v, max);
        mMin.setValue(v, min);
        markovState.setValue(v, init);
    }

    // seed all random number generators for allowing to re-conduct the experiment 
    randomSeed = PropertiesUtil.getLong(mProperties, "SEED", System.currentTimeMillis());
    //mLogger.debug("init seed: " + randomSeed);
    rda.reSeed(randomSeed);

    //extDriver.setSeed(rda.nextLong(0, Long.MAX_VALUE));
    for (ExternalDriver d : this.externalDrivers) {
        d.setSeed(rda.nextLong(0, Long.MAX_VALUE));
        d.filter(markovState);
    }

    this.gsEnvironment = new GoldstoneEnvironment(24, maxRequiredStep, maxRequiredStep / 2.0);

    // set all NaN values to 0.0
    for (String key : markovState.getKeys()) {
        if (Double.isNaN(markovState.getValue(key))) {
            markovState.setValue(key, 0.0);
        }
    }

    //for (String key : markovState.getKeys()) {
    //   mLogger.debug(key  + "=" + markovState.getValue(key));
    //}
    //System.exit(-1);
    //mRewardCore.setNormal(rda);
}

From source file:com.viadeo.kasper.platform.PlatformWirer.java

public PlatformWirer(final Config config, final MetricRegistry metricRegistry, final KasperEventBus eventBus,
        final KasperCommandGateway commandGateway, final KasperQueryGateway queryGateway,
        final SagaManager sagaManager, final RepositoryManager repositoryManager, final Meta meta) {
    this(config, metricRegistry, eventBus, commandGateway, queryGateway, sagaManager, repositoryManager, meta,

            // FIXME quick and dirty fix to avoid memory leaks
            new EventStore() {

                private CircularFifoBuffer queue = new CircularFifoBuffer(10);

                @Override/* ww w. j  ava  2s.c o  m*/
                public synchronized void appendEvents(String type, DomainEventStream events) {
                    while (events.hasNext()) {
                        AggregateTypedEventMessage obj = new AggregateTypedEventMessage();
                        obj.type = type;
                        obj.eventMessage = events.next();
                        queue.add(obj);
                    }
                }

                @Override
                public synchronized DomainEventStream readEvents(String type, Object identifier) {
                    ArrayList<DomainEventMessage<?>> selection = new ArrayList<>();
                    for (Object o : queue) {
                        AggregateTypedEventMessage typedMessage = (AggregateTypedEventMessage) o;
                        if (typedMessage.type.equals(type)) {
                            DomainEventMessage<?> evMsg = typedMessage.eventMessage;
                            if (identifier.equals(evMsg.getAggregateIdentifier())) {
                                selection.add(typedMessage.eventMessage);
                            }
                        }
                    }

                    return new SimpleDomainEventStream(selection);
                }
            });
}