Example usage for java.util Set clear

List of usage examples for java.util Set clear

Introduction

In this page you can find the example usage for java.util Set clear.

Prototype

void clear();

Source Link

Document

Removes all of the elements from this set (optional operation).

Usage

From source file:com.google.code.facebook.graph.sna.applet.VertexCollapseDemo.java

public VertexCollapseDemo() {

    // create a simple graph for the demo
    graph = TestGraphs.getOneComponentGraph();
    collapser = new GraphCollapser(graph);

    layout = new FRLayout(graph);

    Dimension preferredSize = new Dimension(400, 400);
    final VisualizationModel visualizationModel = new DefaultVisualizationModel(layout, preferredSize);
    vv = new VisualizationViewer(visualizationModel, preferredSize);

    vv.getRenderContext().setVertexShapeTransformer(new ClusterVertexShapeFunction());

    final PredicatedParallelEdgeIndexFunction eif = PredicatedParallelEdgeIndexFunction.getInstance();
    final Set exclusions = new HashSet();
    eif.setPredicate(new Predicate() {

        public boolean evaluate(Object e) {

            return exclusions.contains(e);
        }/*from  ww w.j  a  v a 2 s  . c  om*/
    });

    vv.getRenderContext().setParallelEdgeIndexFunction(eif);

    vv.setBackground(Color.white);

    // add a listener for ToolTips
    vv.setVertexToolTipTransformer(new ToStringLabeller() {

        /* (non-Javadoc)
         * @see edu.uci.ics.jung.visualization.decorators.DefaultToolTipFunction#getToolTipText(java.lang.Object)
         */
        @Override
        public String transform(Object v) {
            if (v instanceof Graph) {
                return ((Graph) v).getVertices().toString();
            }
            return super.transform(v);
        }
    });

    /**
     * the regular graph mouse for the normal view
     */
    final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();

    vv.setGraphMouse(graphMouse);

    Container content = getContentPane();
    GraphZoomScrollPane gzsp = new GraphZoomScrollPane(vv);
    content.add(gzsp);

    JComboBox modeBox = graphMouse.getModeComboBox();
    modeBox.addItemListener(graphMouse.getModeListener());
    graphMouse.setMode(ModalGraphMouse.Mode.PICKING);

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JButton collapse = new JButton("Collapse");
    collapse.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Collection picked = new HashSet(vv.getPickedVertexState().getPicked());
            if (picked.size() > 1) {
                Graph inGraph = layout.getGraph();
                Graph clusterGraph = collapser.getClusterGraph(inGraph, picked);

                Graph g = collapser.collapse(layout.getGraph(), clusterGraph);
                double sumx = 0;
                double sumy = 0;
                for (Object v : picked) {
                    Point2D p = (Point2D) layout.transform(v);
                    sumx += p.getX();
                    sumy += p.getY();
                }
                Point2D cp = new Point2D.Double(sumx / picked.size(), sumy / picked.size());
                vv.getRenderContext().getParallelEdgeIndexFunction().reset();
                layout.setGraph(g);
                layout.setLocation(clusterGraph, cp);
                vv.getPickedVertexState().clear();
                vv.repaint();
            }
        }
    });

    JButton compressEdges = new JButton("Compress Edges");
    compressEdges.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Collection picked = vv.getPickedVertexState().getPicked();
            if (picked.size() == 2) {
                Pair pair = new Pair(picked);
                Graph graph = layout.getGraph();
                Collection edges = new HashSet(graph.getIncidentEdges(pair.getFirst()));
                edges.retainAll(graph.getIncidentEdges(pair.getSecond()));
                exclusions.addAll(edges);
                vv.repaint();
            }

        }
    });

    JButton expandEdges = new JButton("Expand Edges");
    expandEdges.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Collection picked = vv.getPickedVertexState().getPicked();
            if (picked.size() == 2) {
                Pair pair = new Pair(picked);
                Graph graph = layout.getGraph();
                Collection edges = new HashSet(graph.getIncidentEdges(pair.getFirst()));
                edges.retainAll(graph.getIncidentEdges(pair.getSecond()));
                exclusions.removeAll(edges);
                vv.repaint();
            }

        }
    });

    JButton expand = new JButton("Expand");
    expand.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Collection picked = new HashSet(vv.getPickedVertexState().getPicked());
            for (Object v : picked) {
                if (v instanceof Graph) {

                    Graph g = collapser.expand(layout.getGraph(), (Graph) v);
                    vv.getRenderContext().getParallelEdgeIndexFunction().reset();
                    layout.setGraph(g);
                }
                vv.getPickedVertexState().clear();
                vv.repaint();
            }
        }
    });

    JButton reset = new JButton("Reset");
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            layout.setGraph(graph);
            exclusions.clear();
            vv.repaint();
        }
    });

    JButton help = new JButton("Help");
    help.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog((JComponent) e.getSource(), instructions, "Help",
                    JOptionPane.PLAIN_MESSAGE);
        }
    });

    JPanel controls = new JPanel();
    JPanel zoomControls = new JPanel(new GridLayout(2, 1));
    zoomControls.setBorder(BorderFactory.createTitledBorder("Zoom"));
    zoomControls.add(plus);
    zoomControls.add(minus);
    controls.add(zoomControls);
    JPanel collapseControls = new JPanel(new GridLayout(3, 1));
    collapseControls.setBorder(BorderFactory.createTitledBorder("Picked"));
    collapseControls.add(collapse);
    collapseControls.add(expand);
    collapseControls.add(compressEdges);
    collapseControls.add(expandEdges);
    collapseControls.add(reset);
    controls.add(collapseControls);
    controls.add(modeBox);
    controls.add(help);
    content.add(controls, BorderLayout.SOUTH);
}

From source file:com.clustercontrol.monitor.run.factory.RunMonitor.java

/**
 * FacilityId????????/*from   ww  w.  java 2  s.  c o  m*/
 * 
 * @return ??????</code> true </code>
 * @throws FacilityNotFound
 * @throws MonitorNotFound
 * @throws InvalidRole
 * @throws EntityExistsException
 * @throws HinemosUnknown
 *
 */
private boolean runMonitorInfoAggregateByNode()
        throws FacilityNotFound, MonitorNotFound, InvalidRole, EntityExistsException, HinemosUnknown {

    if (!m_isMonitorJob) {
        // ?????????????????
        final RepositoryControllerBean repository = new RepositoryControllerBean();
        final NodeInfo targetNode = repository.getNode(m_facilityId);
        final Set<Integer> currentTask = NodeMonitorPollerController
                .calcCurrentExecMonitorIntervals(targetNode);

        final Set<Integer> plannedTask = getPlannedTasksForNodeAggregateMonitor(m_monitorTypeId, m_facilityId);
        synchronized (plannedTask) {
            plannedTask.addAll(currentTask);
        }

        final NodeToMonitorCache node2monitor = NodeToMonitorCache.getInstance(m_monitorTypeId);
        final Semaphore execSingleThreadSemaphore = getSemaphoreForNodeAggregateMonitor(m_monitorTypeId,
                m_facilityId);

        // ?try???????????1??????????
        // Semaphore??????????????????????
        // ?????????
        if (execSingleThreadSemaphore.tryAcquire() == false) {
            for (Map.Entry<Integer, Set<MonitorInfo>> entry : node2monitor
                    .getMonitorsWithCalendar(m_facilityId, currentTask).entrySet()) {

                // ??????????
                final Set<MonitorInfo> monitors = entry.getValue();
                for (MonitorInfo monitor : monitors) {
                    String notifyGroupId = monitor.getNotifyGroupId();

                    // 
                    OutputBasicInfo notifyInfo = new OutputBasicInfo();
                    notifyInfo.setPluginId(m_monitorTypeId);
                    notifyInfo.setMonitorId(monitor.getMonitorId());
                    notifyInfo.setApplication(monitor.getApplication());

                    String facilityPath = new RepositoryControllerBean().getFacilityPath(m_facilityId, null);
                    notifyInfo.setFacilityId(m_facilityId);
                    notifyInfo.setScopeText(facilityPath);

                    // ????
                    int priority = PriorityConstant.TYPE_UNKNOWN;

                    String message = MessageConstant.MESSAGE_MONITOR_UNCOMPLETED.getMessage();
                    String messageOrg = MessageConstant.MESSAGE_MONITOR_UNCOMPLETED.getMessage();
                    notifyInfo.setPriority(priority);
                    notifyInfo.setMessage(message);
                    notifyInfo.setMessageOrg(messageOrg);
                    notifyInfo.setGenerationDate(m_now.getTime());

                    // for debug
                    if (m_log.isDebugEnabled()) {
                        m_log.debug("notify() priority = " + priority + " , message = " + message
                                + " , messageOrg = " + messageOrg + ", generationDate = " + m_now);
                    }

                    // ?
                    if (m_log.isDebugEnabled()) {
                        m_log.debug("sending message" + " : priority=" + notifyInfo.getPriority()
                                + " generationDate=" + notifyInfo.getGenerationDate() + " pluginId="
                                + notifyInfo.getPluginId() + " monitorId=" + notifyInfo.getMonitorId()
                                + " facilityId=" + notifyInfo.getFacilityId() + " subKey="
                                + notifyInfo.getSubKey() + ")");
                    }

                    new NotifyControllerBean().notify(notifyInfo, notifyGroupId);
                }
            }

            // ?????????????????????true?
            return true;
        }

        // ?????1??????Semaphore???
        try {
            // ???????????????
            Set<Integer> execTargetInterval = null;
            synchronized (plannedTask) {
                execTargetInterval = new HashSet<>(plannedTask);
                plannedTask.clear();
            }

            // ??????preCollect???????????????preCollect????????
            final Object preCollectData = preCollect(execTargetInterval);

            // ??????RunMonitor???runMonitorList???????
            final List<RunMonitor> runMonitorList = new ArrayList<>();
            Set<MonitorInfo> monitorInfos = new HashSet<>();
            for (Set<MonitorInfo> addMonitors : node2monitor
                    .getMonitorsWithCalendar(m_facilityId, execTargetInterval).values()) {
                monitorInfos.addAll(addMonitors);
            }
            // ????????FacilityId????Map???????????1?????
            final Map<String, NodeInfo> nodeinfoMap = new HashMap<>();
            nodeinfoMap.put(m_facilityId, targetNode);
            for (final MonitorInfo monitorInfo : monitorInfos) {
                // ID?runMonitor?????
                RunMonitor runMonitor = this.createMonitorInstance();
                runMonitor.m_monitorTypeId = m_monitorTypeId;
                runMonitor.m_monitorId = monitorInfo.getMonitorId();
                runMonitor.m_now = m_now;
                if (runMonitor.setMonitorInfo(m_monitorTypeId, monitorInfo.getMonitorId())) {
                    runMonitorList.add(runMonitor);

                    // setMonitorInfo?????FacilityId???
                    // ??????????????????????
                    runMonitor.m_facilityId = m_facilityId;

                    // ????runMonitor?????runMonitorInfo??????
                    // TODO ?? m_priorityMap ???????????????????
                    runMonitor.setJudgementInfo();
                    runMonitor.nodeInfo = nodeinfoMap;
                    runMonitor.setCheckInfo();
                    runMonitor.m_isNode = true;
                }
            }

            // ??????
            checkMultiMonitorInfoData(preCollectData, runMonitorList);
        } finally {
            execSingleThreadSemaphore.release();
        }
    } else {
        // ?????
        final Object preCollectData = preCollect(null);

        // ID?runMonitor?????
        setJudgementInfo();
        final RepositoryControllerBean repository = new RepositoryControllerBean();
        final NodeInfo targetNode = repository.getNode(m_facilityId);
        final Map<String, NodeInfo> nodeinfoMap = new HashMap<>();
        nodeinfoMap.put(m_facilityId, targetNode);
        nodeInfo = nodeinfoMap;
        setCheckInfo();
        m_isNode = true;

        // ??????
        checkMultiMonitorInfoData(preCollectData, Arrays.asList(this));
    }
    return true;
}

From source file:com.mirth.connect.client.ui.Frame.java

public void doRefreshStatuses(boolean queue) {
    QueuingSwingWorkerTask<Void, DashboardStatus> task = new QueuingSwingWorkerTask<Void, DashboardStatus>(
            "doRefreshStatuses", "Loading statistics...") {
        @Override/* w ww. j a va  2s.co  m*/
        public Void doInBackground() {
            try {
                channelPanel.retrieveGroups();
                channelPanel.retrieveDependencies();

                for (DashboardColumnPlugin plugin : LoadedExtensions.getInstance().getDashboardColumnPlugins()
                        .values()) {
                    plugin.tableUpdate(status);
                }

                DashboardChannelInfo dashboardStatusList = mirthClient
                        .getDashboardChannelInfo(REFRESH_BLOCK_SIZE);
                status = dashboardStatusList.getDashboardStatuses();
                Set<String> remainingIds = dashboardStatusList.getRemainingChannelIds();

                if (status != null) {
                    publish(status.toArray(new DashboardStatus[status.size()]));

                    if (CollectionUtils.isNotEmpty(remainingIds)) {
                        Set<String> statusChannelIds = new HashSet<String>(
                                Math.min(remainingIds.size(), REFRESH_BLOCK_SIZE));

                        for (Iterator<String> it = remainingIds.iterator(); it.hasNext();) {
                            statusChannelIds.add(it.next());

                            if (!it.hasNext() || statusChannelIds.size() == REFRESH_BLOCK_SIZE) {
                                // Processing a new block, retrieve dashboard statuses from server
                                List<DashboardStatus> intermediateStatusList = mirthClient
                                        .getChannelStatusList(statusChannelIds);
                                // Publish the intermediate statuses
                                publish(intermediateStatusList
                                        .toArray(new DashboardStatus[intermediateStatusList.size()]));
                                // Add the statuses to the master list
                                status.addAll(intermediateStatusList);
                                // Clear the set of channel IDs
                                statusChannelIds.clear();
                            }
                        }
                    }
                }
            } catch (ClientException e) {
                status = null;
                alertThrowable(PlatformUI.MIRTH_FRAME, e, e.getMessage(), false,
                        TaskConstants.DASHBOARD_REFRESH);
            }

            return null;
        }

        @Override
        public void process(List<DashboardStatus> chunks) {
            logger.debug("Processing chunk: " + (chunks != null ? chunks.size() : "null"));
            if (chunks != null) {
                TableState tableState = dashboardPanel.getCurrentTableState();
                dashboardPanel.updateTableChannelNodes(chunks);
                dashboardPanel.updateTableState(tableState);
            }
        }

        @Override
        public void done() {
            if (status != null) {
                TableState tableState = dashboardPanel.getCurrentTableState();
                updateChannelTags(true);
                dashboardPanel.finishUpdatingTable(status, channelPanel.getCachedGroupStatuses().values());
                dashboardPanel.updateTableState(tableState);
            }
        }
    };

    new QueuingSwingWorker<Void, DashboardStatus>(task, queue).executeDelegate();
}

From source file:com.google.code.facebook.graph.sna.applet.VertexCollapseDemoWithLayouts.java

public VertexCollapseDemoWithLayouts() {

    // create a simple graph for the demo
    graph = TestGraphs.getOneComponentGraph();
    collapsedGraph = graph;/*from  w  ww  .ja v  a  2 s  .  c  om*/
    collapser = new GraphCollapser(graph);

    layout = new FRLayout(graph);

    Dimension preferredSize = new Dimension(400, 400);
    final VisualizationModel visualizationModel = new DefaultVisualizationModel(layout, preferredSize);
    vv = new VisualizationViewer(visualizationModel, preferredSize);

    vv.getRenderContext().setVertexShapeTransformer(new ClusterVertexShapeFunction());

    final PredicatedParallelEdgeIndexFunction eif = PredicatedParallelEdgeIndexFunction.getInstance();
    final Set exclusions = new HashSet();
    eif.setPredicate(new Predicate() {

        public boolean evaluate(Object e) {

            return exclusions.contains(e);
        }
    });

    vv.getRenderContext().setParallelEdgeIndexFunction(eif);

    vv.setBackground(Color.white);

    // add a listener for ToolTips
    vv.setVertexToolTipTransformer(new ToStringLabeller() {

        /* (non-Javadoc)
         * @see edu.uci.ics.jung.visualization.decorators.DefaultToolTipFunction#getToolTipText(java.lang.Object)
         */
        @Override
        public String transform(Object v) {
            if (v instanceof Graph) {
                return ((Graph) v).getVertices().toString();
            }
            return super.transform(v);
        }
    });

    /**
     * the regular graph mouse for the normal view
     */
    final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();

    vv.setGraphMouse(graphMouse);

    Container content = getContentPane();
    GraphZoomScrollPane gzsp = new GraphZoomScrollPane(vv);
    content.add(gzsp);

    JComboBox modeBox = graphMouse.getModeComboBox();
    modeBox.addItemListener(graphMouse.getModeListener());
    graphMouse.setMode(ModalGraphMouse.Mode.PICKING);

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JButton collapse = new JButton("Collapse");
    collapse.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Collection picked = new HashSet(vv.getPickedVertexState().getPicked());
            if (picked.size() > 1) {
                Graph inGraph = layout.getGraph();
                Graph clusterGraph = collapser.getClusterGraph(inGraph, picked);

                Graph g = collapser.collapse(layout.getGraph(), clusterGraph);
                collapsedGraph = g;
                double sumx = 0;
                double sumy = 0;
                for (Object v : picked) {
                    Point2D p = (Point2D) layout.transform(v);
                    sumx += p.getX();
                    sumy += p.getY();
                }
                Point2D cp = new Point2D.Double(sumx / picked.size(), sumy / picked.size());
                vv.getRenderContext().getParallelEdgeIndexFunction().reset();
                layout.setGraph(g);
                layout.setLocation(clusterGraph, cp);
                vv.getPickedVertexState().clear();
                vv.repaint();
            }
        }
    });

    JButton compressEdges = new JButton("Compress Edges");
    compressEdges.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Collection picked = vv.getPickedVertexState().getPicked();
            if (picked.size() == 2) {
                Pair pair = new Pair(picked);
                Graph graph = layout.getGraph();
                Collection edges = new HashSet(graph.getIncidentEdges(pair.getFirst()));
                edges.retainAll(graph.getIncidentEdges(pair.getSecond()));
                exclusions.addAll(edges);
                vv.repaint();
            }

        }
    });

    JButton expandEdges = new JButton("Expand Edges");
    expandEdges.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Collection picked = vv.getPickedVertexState().getPicked();
            if (picked.size() == 2) {
                Pair pair = new Pair(picked);
                Graph graph = layout.getGraph();
                Collection edges = new HashSet(graph.getIncidentEdges(pair.getFirst()));
                edges.retainAll(graph.getIncidentEdges(pair.getSecond()));
                exclusions.removeAll(edges);
                vv.repaint();
            }

        }
    });

    JButton expand = new JButton("Expand");
    expand.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Collection picked = new HashSet(vv.getPickedVertexState().getPicked());
            for (Object v : picked) {
                if (v instanceof Graph) {

                    Graph g = collapser.expand(layout.getGraph(), (Graph) v);
                    vv.getRenderContext().getParallelEdgeIndexFunction().reset();
                    layout.setGraph(g);
                }
                vv.getPickedVertexState().clear();
                vv.repaint();
            }
        }
    });

    JButton reset = new JButton("Reset");
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            layout.setGraph(graph);
            exclusions.clear();
            vv.repaint();
        }
    });

    JButton help = new JButton("Help");
    help.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog((JComponent) e.getSource(), instructions, "Help",
                    JOptionPane.PLAIN_MESSAGE);
        }
    });
    Class[] combos = getCombos();
    final JComboBox jcb = new JComboBox(combos);
    // use a renderer to shorten the layout name presentation
    jcb.setRenderer(new DefaultListCellRenderer() {
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            String valueString = value.toString();
            valueString = valueString.substring(valueString.lastIndexOf('.') + 1);
            return super.getListCellRendererComponent(list, valueString, index, isSelected, cellHasFocus);
        }
    });
    jcb.addActionListener(new LayoutChooser(jcb, vv));
    jcb.setSelectedItem(FRLayout.class);

    JPanel controls = new JPanel();
    JPanel zoomControls = new JPanel(new GridLayout(2, 1));
    zoomControls.setBorder(BorderFactory.createTitledBorder("Zoom"));
    zoomControls.add(plus);
    zoomControls.add(minus);
    controls.add(zoomControls);
    JPanel collapseControls = new JPanel(new GridLayout(3, 1));
    collapseControls.setBorder(BorderFactory.createTitledBorder("Picked"));
    collapseControls.add(collapse);
    collapseControls.add(expand);
    collapseControls.add(compressEdges);
    collapseControls.add(expandEdges);
    collapseControls.add(reset);
    controls.add(collapseControls);
    controls.add(modeBox);
    controls.add(help);
    controls.add(jcb);
    content.add(controls, BorderLayout.SOUTH);
}

From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java

private/* synchronized */Set<String> pauseLogIndex(Map<String, LogIndex> toCommit) {
    if (isClosed())
        return null;
    if (!USE_CHECKPOINTS_AS_PAUSE_TABLE)
        return this.pauseLogIndexIndividually(toCommit);
    String updateCmd = "update " + (USE_CHECKPOINTS_AS_PAUSE_TABLE ? getCTable() : getPTable())
            + " set logindex=? where  paxos_id=?";

    PreparedStatement pstmt = null;
    Connection conn = null;/*from   w w w  .  j  a va  2 s. c o  m*/
    Set<String> paused = new HashSet<String>();
    Set<String> batch = new HashSet<String>();
    synchronized (this.messageLog) {
        try {
            int i = 0;
            for (String paxosID : toCommit.keySet()) {
                LogIndex logIndex = toCommit.get(paxosID);
                if (conn == null) {
                    conn = this.getDefaultConn();
                    conn.setAutoCommit(false);
                    pstmt = conn.prepareStatement(updateCmd);
                }

                byte[] logIndexBytes = logIndex != null ? deflate(logIndex.toString().getBytes(CHARSET)) : null;
                if (logIndexBytes != null && ENABLE_INSTRUMENTATION && Util.oneIn(Integer.MAX_VALUE))
                    DelayProfiler.updateMovAvg("logindex_size", logIndexBytes.length);
                Blob blob = conn.createBlob();
                if (logIndexBytes != null)
                    blob.setBytes(1, logIndexBytes);
                pstmt.setBlob(1, logIndexBytes != null ? blob : null);
                pstmt.setString(2, paxosID);
                pstmt.addBatch();
                batch.add(paxosID);
                if ((i + 1) % MAX_DB_BATCH_SIZE == 0 || (i + 1) == toCommit.size()) {
                    pstmt.executeBatch();
                    conn.commit();
                    pstmt.clearBatch();
                    paused.addAll(batch);

                    log.log(Level.FINE, "{0} paused logIndex batch {1}",
                            new Object[] { this, Util.truncatedLog(batch, 16) });
                    batch.clear();
                }
                i++;
            }
        } catch (SQLException | IOException sqle) {
            log.severe(this + " failed to pause logIndex batch");
            sqle.printStackTrace();
        } finally {
            cleanup(pstmt);
            cleanup(conn);
        }
        // free up memory
        for (String paxosID : paused)
            this.messageLog.uncache(paxosID);
    }
    if (paused.size() != toCommit.size())
        paused.addAll(this.pauseLogIndexIndividually(diffLI(toCommit, paused)));
    return paused;
}

From source file:esg.node.components.registry.ESGFRegistry.java

Set<Node> mergeNodes(Registration myRegistration, Registration otherRegistration) {
    log.trace("merging registrations...");

    List<Node> myList = myRegistration.getNode();
    List<Node> otherList = otherRegistration.getNode();

    try {/*from  w  w  w  . j a  va 2 s .c  om*/
        log.trace("mylist = [" + myList + "] - size (" + myList.size() + ") " + myList.get(0).getHostname());
        log.trace("otherList = [" + otherList + "] - size (" + otherList.size() + ") "
                + otherList.get(0).getHostname());
    } catch (Throwable t) {
        log.error(t);
        log.trace("Malformed Registration: hostname field not set!!!!");
    }
    Long removedNodeTimeStamp = null;
    String removedNodeHostname = null;

    //Sort lists by hostname (natural) ascending order a -> z
    //where a compareTo z is < 0 iff a is before z
    //This algorithm is not in-place, uses terciary list.
    Collections.sort(myList, nodecomp);
    Collections.sort(otherList, nodecomp);

    Set<Node> newNodes = new TreeSet<Node>(nodecomp);
    Set<Node> updatedNodes = new HashSet<Node>();

    int i = 0;
    int j = 0;
    while ((i < myList.size()) && (j < otherList.size())) {
        try {
            if ((nodecomp.compare(myList.get(i), otherList.get(j))) == 0) {
                if ((myList.get(i)).getTimeStamp() >= (otherList.get(j)).getTimeStamp()) {
                    newNodes.add(myList.get(i));
                    log.trace("-- Keeping local entry for (=) " + (myList.get(i)).getHostname());
                } else {
                    if (peerFilter.isInNetwork(otherList.get(j))
                            && !exList.isExcluded((otherList.get(j)).getHostname())) {
                        newNodes.add(otherList.get(j));
                        updatedNodes.add(otherList.get(j));
                        log.trace("-- Updating with remote entry for (=) " + (myList.get(j)).getHostname());
                    } else {
                        log.trace("   Skipping, Not in our peer network (=) [" + (myList.get(j)).getHostname()
                                + "]");
                        //just skip what's in the entry in the
                        //otherList but leave us at the same position
                        //in myList to do the next comparison
                        //(I could have also done j++; continue;)
                        i--;
                    }
                }
                i++;
                j++;
            } else if ((nodecomp.compare(myList.get(i), otherList.get(j))) < 0) {
                newNodes.add(myList.get(i));
                log.trace("-  Keeping local entry for " + (myList.get(i)).getHostname());
                i++;
            } else {
                if ((null == (removedNodeTimeStamp = removedMap
                        .get(removedNodeHostname = otherList.get(j).getHostname())))
                        || (removedNodeTimeStamp < otherRegistration.getTimeStamp())) {
                    removedMap.remove(removedNodeHostname);
                    if (peerFilter.isInNetwork(otherList.get(j))
                            && !exList.isExcluded((otherList.get(j)).getHostname())) {
                        newNodes.add(otherList.get(j));
                        updatedNodes.add(otherList.get(j));
                        log.trace("-  Accepting new(er) remote entry for (+) "
                                + (otherList.get(j)).getHostname());
                    } else {
                        log.trace("   Skipping " + (otherList.get(j)).getHostname()
                                + ", Not in our peer network (+)");
                    }
                } else {
                    log.debug("   NOT accepting older candidate remote entry, ["
                            + (otherList.get(j)).getHostname() + "], have more recent knowledge of removal by ["
                            + (removedNodeTimeStamp > otherRegistration.getTimeStamp())
                            + "]ms than candidate entry (+)");
                }
                j++;
            }
        } catch (Throwable t) {
            log.error(t);
            log.warn("[=+] Skipping MALFORMED Node Entry...(i=" + (i) + ") (j=" + (j) + ")");
            j++;
            continue;
        }
    }

    while (i < myList.size()) {
        newNodes.add(myList.get(i));
        log.trace("   Keeping local entry for " + myList.get(i).getHostname());
        i++;
    }

    while (j < otherList.size()) {
        try {
            if ((null == (removedNodeTimeStamp = removedMap
                    .get(removedNodeHostname = otherList.get(j).getHostname())))
                    || (removedNodeTimeStamp < otherRegistration.getTimeStamp())) {
                removedMap.remove(removedNodeHostname);
                if (peerFilter.isInNetwork(otherList.get(j))
                        && !exList.isExcluded((otherList.get(j)).getHostname())) {
                    newNodes.add(otherList.get(j));
                    updatedNodes.add(otherList.get(j));
                    log.trace("   Adding new(er) remote entry for (++) " + (otherList.get(j)).getHostname());
                } else {
                    log.trace("   Skipping " + (otherList.get(j)).getHostname()
                            + ", Not in our peer network (++)");
                }
            } else {
                log.debug("   NOT accepting older candidate remote entry, [" + (otherList.get(j)).getHostname()
                        + "], have more recent knowledge of removal by ["
                        + (removedNodeTimeStamp > otherRegistration.getTimeStamp())
                        + "]ms than candidate entry (++)");
            }
        } catch (Throwable t) {
            log.error(t);
            log.warn("Skipping MALFORMED Node Entry... (j=" + (j) + ")");
            j++;
            continue;
        }
        j++;
    }

    log.trace("updatedNodes: (" + updatedNodes.size() + ")");
    for (Node n : updatedNodes) {
        log.debug("updating registry with info on: " + n.getHostname());
    }

    myList.clear();
    myList.addAll(newNodes); //because using set they are
    newNodes.clear();

    return updatedNodes;
}

From source file:com.hrbb.loan.pos.biz.backstage.inter.impl.LoanPosCreditApplyBackStageBizImpl.java

@Override
    public boolean uploadPosSerial(File file, String posChannel, String posType, String loanId) throws Exception {
        try {/*from   w  w  w .  j a  va 2  s.  c  o m*/
            // Workbook wb = PoiUtil.read(file);
            // Sheet sheet1 = wb.getSheetAt(0);
            // //POS?
            Set<String> uniquePOSKey = Sets.newHashSet();

            String channelBiz = posChannel + posType;
            switch (channelBiz) {
            // ?
            case BusinessDictionaryConstants.BIZ_CHANNEL_KQ + BusinessDictionaryConstants.POS_TYPE_DAY: {
                List<Map<String, Object>> insertList = Lists.newArrayList();
                // for (Row row : sheet1) {
                // if (row.getRowNum() != 0) {
                // // ??
                // Map<String, Object> insertMap = Maps.newHashMap();
                // insertMap.put(LOAN_ID, loanId);
                // insertMap.put(POS_CHANNEL, posChannel);
                // insertMap.put(POS_KIND, posType);
                // insertMap.put(MERCHANT_NAME, row.getCell(3)
                // .getStringCellValue());
                // insertMap.put(TRADE_DATE, DateUtil.parDate(
                // DateUtil.sdf1, DateUtil.sdf9, row.getCell(4)
                // .getStringCellValue()));
                // insertMap.put(TRADE_AMT, row.getCell(5)
                // .getStringCellValue());
                // insertList.add(insertMap);
                // if(insertList.size() == batchNum){
                // loanPosCreditApplyService.insertPosSerialSelectiveMapBatch(insertList);
                // insertList.clear();
                // }
                //
                // }
                // }

                POSRowReader reader = new KQDRowReader(loanId, posType);
                reader.addHandleList(insertList);
                reader.addService(loanPosCreditApplyService);
                reader.addUniqueKey(uniquePOSKey);
                ExcelReaderUtil.readExcel(reader, file.getAbsolutePath());

                if (reader.fireTrigger())
                    return false;

                if (ListUtil.isNotEmpty(insertList)) {
                    loanPosCreditApplyService.insertPosSerialSelectiveMapBatch(insertList);
                    insertList.clear();
                    uniquePOSKey.clear();
                }
                return true;
            }
            // ?
            case BusinessDictionaryConstants.BIZ_CHANNEL_YB + BusinessDictionaryConstants.POS_TYPE_DAY: {
                List<Map<String, Object>> insertList = Lists.newArrayList();
                // for (Row row : sheet1) {
                // if (row.getRowNum() != 0) {
                // Map<String, Object> insertMap = Maps.newHashMap();
                // insertMap.put(LOAN_ID, loanId);
                // insertMap.put(POS_CHANNEL, posChannel);
                // insertMap.put(POS_KIND, posType);
                // insertMap.put(MERCHANT_NAME, row.getCell(0)
                // .getStringCellValue());
                // insertMap.put(MERCHANT_ID, row.getCell(1)
                // .getStringCellValue());
                // insertMap.put(TRADE_DATE, row.getCell(2)
                // .getStringCellValue().trim().substring(0, 10));
                // insertMap.put(TRADE_TIME, row.getCell(2)
                // .getStringCellValue().trim().substring(12));
                // insertMap.put(TRADE_AMT, row.getCell(3)
                // .getStringCellValue());
                // insertMap.put(TRADE_LAST_FOUR_STATE, row.getCell(4)
                // .getStringCellValue());
                // insertMap.put(TRADE_CARD_KIND, row.getCell(5)
                // .getStringCellValue());
                // insertMap.put(TRADE_TYPE, row.getCell(6)
                // .getStringCellValue());
                // insertList.add(insertMap);
                // if(insertList.size() == batchNum){
                // loanPosCreditApplyService.insertPosSerialSelectiveMapBatch(insertList);
                // insertList.clear();
                // }
                //
                // }
                // }

                POSRowReader reader = new YBDRowReader(loanId, posType);
                reader.addHandleList(insertList);
                reader.addService(loanPosCreditApplyService);
                reader.addUniqueKey(uniquePOSKey);
                ExcelReaderUtil.readExcel(reader, file.getAbsolutePath());

                if (reader.fireTrigger())
                    return false;

                if (ListUtil.isNotEmpty(insertList)) {
                    loanPosCreditApplyService.insertPosSerialSelectiveMapBatch(insertList);
                    insertList.clear();
                    uniquePOSKey.clear();
                }
                return true;
            }
            // ?
            case BusinessDictionaryConstants.BIZ_CHANNEL_UP + BusinessDictionaryConstants.POS_TYPE_DAY: {
                List<Map<String, Object>> insertList = Lists.newArrayList();
                // for (Row row : sheet1) {
                // if (row.getRowNum() != 0) {
                // Map<String, Object> insertMap = Maps.newHashMap();
                // insertMap.put(LOAN_ID, loanId);
                // insertMap.put(POS_CHANNEL, posChannel);
                // insertMap.put(POS_KIND, posType);
                // insertMap.put(MERCHANT_NAME, row.getCell(0)
                // .getStringCellValue());
                // insertMap.put(MERCHANT_ID, row.getCell(1)
                // .getStringCellValue());
                // insertMap.put(MERCHANT_TYPE_CODE, row.getCell(2)
                // .getStringCellValue());
                // insertMap.put(TRADE_DATE, DateUtil.parDate(
                // DateUtil.sdf1, DateUtil.sdf9,
                // row.getCell(3).getStringCellValue().trim()
                // .substring(0, 8)));
                // insertMap.put(TRADE_TIME, DateUtil.parDate(
                // DateUtil.sdf8, DateUtil.sdf7,
                // row.getCell(3).getStringCellValue().trim()
                // .substring(8)));
                // insertMap.put(TRADE_AMT, row.getCell(4)
                // .getStringCellValue());
                // insertMap.put(TRADE_CARD_NO, row.getCell(5)
                // .getStringCellValue());
                // insertMap.put(TRADE_CARD_KIND, row.getCell(6)
                // .getStringCellValue());
                // insertMap.put(TRADE_TYPE, row.getCell(7)
                // .getStringCellValue());
                // insertList.add(insertMap);
                // if(insertList.size() == batchNum){
                // loanPosCreditApplyService.insertPosSerialSelectiveMapBatch(insertList);
                // insertList.clear();
                // }
                //
                // }
                // }

                POSRowReader reader = new UPDRowReader(loanId, posType);
                reader.addHandleList(insertList);
                reader.addService(loanPosCreditApplyService);
                reader.addUniqueKey(uniquePOSKey);
                ExcelReaderUtil.readExcel(reader, file.getAbsolutePath());

                if (reader.fireTrigger())
                    return false;

                if (ListUtil.isNotEmpty(insertList)) {
                    loanPosCreditApplyService.insertPosSerialSelectiveMapBatch(insertList);
                    insertList.clear();
                    uniquePOSKey.clear();
                }
                return true;
            }

            // ?
            case BusinessDictionaryConstants.BIZ_CHANNEL_UP + BusinessDictionaryConstants.POS_TYPE_WEEK_COLLECT:
                // ?
            case BusinessDictionaryConstants.BIZ_CHANNEL_UP + BusinessDictionaryConstants.POS_TYPE_MONTH_COLLECT:
                // ?
            case BusinessDictionaryConstants.BIZ_CHANNEL_UP + BusinessDictionaryConstants.POS_TYPE_DAY_COLLECT: {
                List<Map<String, Object>> insertList = Lists.newArrayList();
                // for (Row row : sheet1) {
                // if (row.getRowNum() != 0) {
                // Map<String, Object> insertMap = Maps.newHashMap();
                // insertMap.put(LOAN_ID, loanId);
                // insertMap.put(POS_CHANNEL, posChannel);
                // insertMap.put(POS_KIND, posType);
                // insertMap.put(TRADE_DATE, row.getCell(0)
                // .getStringCellValue());
                // insertMap.put(MERCHANT_NAME, row.getCell(1)
                // .getStringCellValue());
                // insertMap.put(MERCHANT_ID, row.getCell(2)
                // .getStringCellValue());
                // insertMap.put(TRADE_NUM, row.getCell(3)
                // .getStringCellValue());
                // insertMap.put(TRADE_AMT, row.getCell(4)
                // .getStringCellValue());
                // insertList.add(insertMap);
                // if(insertList.size() == batchNum){
                // loanPosCreditApplyService.insertPosSerialSelectiveMapBatch(insertList);
                // insertList.clear();
                // }
                //
                // }
                // }

                POSRowReader reader = new UPMRowReader(loanId, posType);
                reader.addHandleList(insertList);
                reader.addService(loanPosCreditApplyService);
                reader.addUniqueKey(uniquePOSKey);
                ExcelReaderUtil.readExcel(reader, file.getAbsolutePath());

                if (reader.fireTrigger())
                    return false;

                if (ListUtil.isNotEmpty(insertList)) {
                    loanPosCreditApplyService.insertPosSerialSelectiveMapBatch(insertList);
                    insertList.clear();
                    uniquePOSKey.clear();
                }
                return true;
            }
            // 
            case BusinessDictionaryConstants.BIZ_CHANNEL_UM + BusinessDictionaryConstants.POS_TYPE_MONTH_COLLECT: {
                List<Map<String, Object>> insertList = Lists.newArrayList();
                // for (Row row : sheet1) {
                // if (row.getRowNum() != 0) {
                // Map<String, Object> insertMap = Maps.newHashMap();
                // insertMap.put(LOAN_ID, loanId);
                // insertMap.put(POS_CHANNEL, posChannel);
                // insertMap.put(POS_KIND, posType);
                // insertMap.put(TRADE_AMT, row.getCell(6)
                // .getStringCellValue());
                // insertMap.put(TRADE_NUM, row.getCell(7)
                // .getStringCellValue());
                // insertMap.put(REG_TIME_TRADE_AMT, row.getCell(8)
                // .getStringCellValue());
                // insertMap.put(REG_TIME_TRADE_NUM, row.getCell(9)
                // .getStringCellValue());
                // insertMap.put(MAX_TRADE_AMT_PER_MONTH, row.getCell(10)
                // .getStringCellValue());
                // insertMap.put(CREDIT_CARD_TRADE_AMT_RADE, row.getCell(11)
                // .getStringCellValue());
                // insertMap.put(CREDIT_CARD_TRADE_NUM_RATE, row.getCell(12)
                // .getStringCellValue());
                // insertMap.put(DIFFERENT_CARD_NO_NUM, row.getCell(13)
                // .getStringCellValue());
                // insertList.add(insertMap);
                // if(insertList.size() == batchNum){
                // loanPosCreditApplyService.insertPosSerialSelectiveMapBatch(insertList);
                // insertList.clear();
                // }
                //
                // }
                // }

                POSRowReader reader = new UMMRowReader(loanId, posType);
                reader.addHandleList(insertList);
                reader.addService(loanPosCreditApplyService);
                reader.addUniqueKey(uniquePOSKey);
                ExcelReaderUtil.readExcel(reader, file.getAbsolutePath());

                if (reader.fireTrigger())
                    return false;

                if (ListUtil.isNotEmpty(insertList)) {
                    loanPosCreditApplyService.insertPosSerialSelectiveMapBatch(insertList);
                    insertList.clear();
                    uniquePOSKey.clear();
                }
                return true;
            }
            // ??
            case BusinessDictionaryConstants.BIZ_CHANNEL_CY + BusinessDictionaryConstants.POS_TYPE_DAY: {

                List<Map<String, Object>> insertList = Lists.newArrayList();

                POSRowReader reader = new CYRowReader(loanId, posType);
                reader.addHandleList(insertList);
                reader.addService(loanPosCreditApplyService);
                reader.addUniqueKey(uniquePOSKey);
                ExcelReaderUtil.readExcel(reader, file.getAbsolutePath());

                if (reader.fireTrigger())
                    return false;

                if (ListUtil.isNotEmpty(insertList)) {
                    loanPosCreditApplyService.insertPosSerialSelectiveMapBatch(insertList);
                    insertList.clear();
                    uniquePOSKey.clear();
                }
                return true;
            }
            default:
                return false;
            }
        } catch (Exception e) {
            logger.error("pos?:[]", e.getMessage());
            return false;
        }

    }

From source file:gov.nih.nci.security.dao.AuthorizationDAOImpl.java

public Set getPrivileges(String roleId) throws CSObjectNotFoundException {
    Session s = null;/*w  ww . ja  v  a2  s  .c o  m*/
    Set result = new HashSet();
    try {
        s = HibernateSessionFactoryHelper.getAuditSession(sf);
        Role role = (Role) this.getObjectByPrimaryKey(s, Role.class, new Long(roleId));
        result = role.getPrivileges();

        List list = new ArrayList();
        Iterator toSortIterator = result.iterator();
        while (toSortIterator.hasNext()) {
            list.add(toSortIterator.next());
        }
        Collections.sort(list);
        result.clear();
        result.addAll(list);

        log.debug("The result size is: " + result.size());
    } catch (Exception ex) {
        if (log.isDebugEnabled())
            log.debug("Authorization|||getPrivileges|Failure|Error obtaining Associated Privileges for Role id "
                    + roleId + "|" + ex.getMessage());
        throw new CSObjectNotFoundException(
                "An error occured in obtaining associated Privileges for the given Role\n" + ex.getMessage(),
                ex);
    } finally {
        try {
            s.close();
        } catch (Exception ex2) {
            if (log.isDebugEnabled())
                log.debug("Authorization|||assignGroupRoleToProtectionGroup|Failure|Error in Closing Session |"
                        + ex2.getMessage());
        }
    }
    if (log.isDebugEnabled())
        log.debug(
                "Authorization|||getPrivileges|Success|Successful in obtaining Associated Privileges for Role id "
                        + roleId + "|");
    return result;
}

From source file:gov.nih.nci.security.dao.AuthorizationDAOImpl.java

public Set getProtectionElements(String protectionGroupId) throws CSObjectNotFoundException {
    Session s = null;//from w  w  w  .  ja v  a  2 s.  c  om
    Set result = new HashSet();
    try {
        s = HibernateSessionFactoryHelper.getAuditSession(sf);
        ProtectionGroup protectionGroup = (ProtectionGroup) this.getObjectByPrimaryKey(s, ProtectionGroup.class,
                new Long(protectionGroupId));
        result = protectionGroup.getProtectionElements();

        List list = new ArrayList();
        Iterator toSortIterator = result.iterator();
        while (toSortIterator.hasNext()) {
            list.add(toSortIterator.next());
        }
        Collections.sort(list);
        result.clear();
        result.addAll(list);

        log.debug("The result size is: " + result.size());

    } catch (Exception ex) {
        if (log.isDebugEnabled())
            log.debug(
                    "Authorization|||getProtectionElements|Failure|Error in obtaining Protection Elements for Protection Group Id "
                            + protectionGroupId + "|" + ex.getMessage());
        throw new CSObjectNotFoundException(
                "An error occurred while obtaining Associated Protection Elements for the Protection Group\n"
                        + ex.getMessage(),
                ex);
    } finally {
        try {
            s.close();
        } catch (Exception ex2) {
            if (log.isDebugEnabled())
                log.debug("Authorization|||getProtectionElements|Failure|Error in Closing Session |"
                        + ex2.getMessage());
        }
    }
    if (log.isDebugEnabled())
        log.debug(
                "Authorization|||getProtectionElements|Success|Succesful in obtaining Protection Elements for Protection Group Id "
                        + protectionGroupId + "|");
    return result;
}

From source file:com.zimbra.cs.account.ProvUtil.java

private void dumpComboRight(ComboRight comboRight, boolean expandComboRight, String indent, Set<String> seen) {
    // safety check, should not happen,
    // detect circular combo rights
    if (seen.contains(comboRight.getName())) {
        console.println("Circular combo right: " + comboRight.getName() + " !!");
        return;/*from  ww  w .j ava  2 s.c  om*/
    }

    String indent2 = indent + indent;

    for (Right r : comboRight.getRights()) {
        String tt = r.getTargetTypeStr();
        tt = tt == null ? "" : " (" + tt + ")";
        // console.format("%s%10.10s: %s %s\n", indent2, r.getRightType().name(), r.getName(), tt);
        console.format("%s %s: %s %s\n", indent2, r.getRightType().name(), r.getName(), tt);

        seen.add(comboRight.getName());

        if (r.isComboRight() && expandComboRight) {
            dumpComboRight((ComboRight) r, expandComboRight, indent2, seen);
        }

        seen.clear();
    }
}