Example usage for java.util LinkedList size

List of usage examples for java.util LinkedList size

Introduction

In this page you can find the example usage for java.util LinkedList size.

Prototype

int size

To view the source code for java.util LinkedList size.

Click Source Link

Usage

From source file:com.epam.dlab.mongo.DlabResourceTypeDAO.java

/**
 * Update exploratory cost in Mongo DB./*from w  w  w  .ja  v  a 2  s .c o  m*/
 *
 * @param user            the name of user.
 * @param exploratoryName id of exploratory.
 */
private void updateExploratoryCost(String user, String exploratoryName) {
    LOGGER.debug("Update explorartory {} cost for user {}", exploratoryName, user);
    List<? extends Bson> pipeline = Arrays.asList(
            match(and(eq(FIELD_USER, user), eq(FIELD_EXPLORATORY_NAME, exploratoryName))),
            group(getGrouppingFields(FIELD_DLAB_RESOURCE_ID, ReportLine.FIELD_PRODUCT,
                    ReportLine.FIELD_RESOURCE_TYPE, ReportLine.FIELD_CURRENCY_CODE),
                    sum(ReportLine.FIELD_COST, "$" + ReportLine.FIELD_COST),
                    min(FIELD_USAGE_DATE_START, "$" + ReportLine.FIELD_USAGE_DATE),
                    max(FIELD_USAGE_DATE_END, "$" + ReportLine.FIELD_USAGE_DATE)),
            sort(new Document(FIELD_ID + "." + FIELD_DLAB_RESOURCE_ID, 1)
                    .append(FIELD_ID + "." + ReportLine.FIELD_PRODUCT, 1)));
    AggregateIterable<Document> docs = connection.getCollection(COLLECTION_BILLING).aggregate(pipeline);
    LinkedList<Document> billing = new LinkedList<>();
    ResourceItemList resources = getResourceList();
    Double costTotal = null;
    String currencyCode = null;
    for (Document d : docs) {
        Document id = (Document) d.get(FIELD_ID);
        double cost = BillingCalculationUtils.round(d.getDouble(ReportLine.FIELD_COST), 2);
        costTotal = (costTotal == null ? cost : costTotal + cost);
        if (currencyCode == null) {
            currencyCode = id.getString(ReportLine.FIELD_CURRENCY_CODE);
        }

        Document total = new Document()
                .append(FIELD_RESOURCE_NAME,
                        resources.getById(id.getString(FIELD_DLAB_RESOURCE_ID)).getResourceName())
                .append(ReportLine.FIELD_PRODUCT, id.getString(ReportLine.FIELD_PRODUCT))
                .append(ReportLine.FIELD_RESOURCE_TYPE, id.getString(ReportLine.FIELD_RESOURCE_TYPE))
                .append(ReportLine.FIELD_COST, BillingCalculationUtils.formatDouble(cost))
                .append(ReportLine.FIELD_CURRENCY_CODE, id.getString(ReportLine.FIELD_CURRENCY_CODE))
                .append(FIELD_USAGE_DATE_START, d.getString(FIELD_USAGE_DATE_START))
                .append(FIELD_USAGE_DATE_END, d.getString(FIELD_USAGE_DATE_END));
        billing.add(total);
    }

    LOGGER.debug("Total explorartory {} cost for user {} is {} {}, detail count is {}", exploratoryName, user,
            costTotal, currencyCode, billing.size());
    billing.sort(new BillingComparator());

    MongoCollection<Document> cExploratory = connection.getCollection(COLLECTION_USER_INSTANCES);
    Bson values = Updates.combine(
            Updates.set(ReportLine.FIELD_COST, BillingCalculationUtils.formatDouble(costTotal)),
            Updates.set(FIELD_CURRENCY_CODE, currencyCode),
            Updates.set(COLLECTION_BILLING, (!billing.isEmpty() ? billing : null)));
    cExploratory.updateOne(and(and(eq(FIELD_USER, user), eq(FIELD_EXPLORATORY_NAME, exploratoryName))), values);
}

From source file:edu.cornell.med.icb.clustering.QTClusterer.java

/**
 * Groups instances into clusters. Returns the indices of the instances
 * that belong to a cluster as an int array in the list result.
 *
 * @param calculator       The//from   w w w .  j ava 2s .co m
 *                         {@link edu.cornell.med.icb.clustering.SimilarityDistanceCalculator}
 *                         that should be used when clustering
 * @param qualityThreshold The QT clustering algorithm quality threshold (d)
 * @return The list of clusters.
 */
public List<int[]> cluster(final SimilarityDistanceCalculator calculator, final double qualityThreshold) {
    final ProgressLogger clusterProgressLogger = new ProgressLogger(LOGGER, logInterval, "instances clustered");
    clusterProgressLogger.displayFreeMemory = true;
    clusterProgressLogger.expectedUpdates = instanceCount;
    clusterProgressLogger.start("Starting to cluster " + instanceCount + " instances using "
            + parallelTeam.getThreadCount() + " threads.");

    // reset cluster results
    clusterCount = 0;
    // instanceList is the set "G" to cluster
    final LinkedList<Integer> instanceList = new LinkedList<Integer>();
    for (int i = 0; i < instanceCount; i++) {
        clusters[i].clear();

        // set each node in the instance list to it's
        // original position in the source data array
        instanceList.add(i);
    }

    final double ignoreDistance = calculator.getIgnoreDistance();

    // eliminate any instances that will never cluster with anything else
    final IntList singletonClusters = identifySingletonClusters(calculator, qualityThreshold, instanceList,
            clusterProgressLogger);

    final ProgressLogger innerLoopProgressLogger = new ProgressLogger(LOGGER, logInterval,
            "inner loop iterations");
    innerLoopProgressLogger.displayFreeMemory = false;

    final ProgressLogger outerLoopProgressLogger = new ProgressLogger(LOGGER, logInterval,
            "outer loop iterations");
    outerLoopProgressLogger.displayFreeMemory = true;

    try {
        // loop over instances until they have all been added to a cluster
        while (!instanceList.isEmpty()) {
            // cluster remaining instances to find the maximum cardinality
            for (int i = 0; i < instanceList.size(); i++) {
                candidateClusters[i].clear();
            }

            if (logOuterLoopProgress) {
                outerLoopProgressLogger.expectedUpdates = instanceList.size();
                outerLoopProgressLogger.start("Entering outer loop for " + instanceList.size() + " iterations");
            }

            // for each i in G (instance list)
            // find instance j such that distance i,j minimum
            parallelTeam.execute(new ParallelRegion() { // NOPMD

                @Override
                public void run() throws Exception { // NOPMD
                    // each thread will populate a different portion of the "candidateCluster"
                    // array so we shouldn't need to worry about concurrent access
                    execute(0, instanceList.size() - 1, new IntegerForLoop() {
                        @Override
                        public void run(final int first, final int last) {
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("first = " + first + ", last = " + last);
                            }
                            for (int i = first; i <= last; i++) {
                                @SuppressWarnings("unchecked")
                                final LinkedList<Integer> notClustered = (LinkedList<Integer>) instanceList
                                        .clone();

                                // add the first instance to the next candidate cluster
                                final IntArrayList candidateCluster = candidateClusters[i];
                                candidateCluster.add(notClustered.remove(i));

                                if (logInnerLoopProgress) {
                                    innerLoopProgressLogger.expectedUpdates = notClustered.size();
                                    innerLoopProgressLogger.start(
                                            "Entering inner loop for " + notClustered.size() + " iterations");
                                }

                                // cluster the remaining instances to find the maximum
                                // cardinality find instance j such that distance i,j minimum
                                boolean done = false;
                                while (!done && !notClustered.isEmpty()) {
                                    // find the node that has minimum distance between the
                                    // current cluster and the instances that have not yet
                                    // been clustered.
                                    double minDistance = Double.POSITIVE_INFINITY;
                                    int minDistanceInstanceIndex = 0;
                                    int instanceIndex = 0;
                                    for (final int instance : notClustered) {
                                        double newDistance = ignoreDistance;

                                        final int[] cluster = candidateCluster.elements();
                                        for (int instanceInCluster = 0; instanceInCluster < candidateCluster
                                                .size(); instanceInCluster++) {
                                            final double a = calculator.distance(cluster[instanceInCluster],
                                                    instance);
                                            // if the distance of the instance will force the candidate cluster
                                            // to be larger than the cutoff value, we can stop here
                                            // because we know that this candidate cluster will be too large
                                            if (a >= minDistance) {
                                                newDistance = ignoreDistance;
                                                break;
                                            }
                                            final double b = newDistance;

                                            // This code is inlined from java.lang.Math.max(a, b)
                                            if (a != a) { // a is NaN
                                                newDistance = a;
                                            } else if (a == 0.0d && b == 0.0d
                                                    && Double.doubleToLongBits(a) == negativeZeroDoubleBits) {
                                                newDistance = b;
                                            } else if (a >= b) {
                                                newDistance = a;
                                            } else {
                                                newDistance = b;
                                            }
                                        }

                                        if (newDistance != ignoreDistance && newDistance < minDistance) {
                                            minDistance = newDistance;
                                            minDistanceInstanceIndex = instanceIndex;
                                        }
                                        instanceIndex++;
                                    }
                                    // grow clusters until min distance between new instance
                                    // and cluster reaches quality threshold
                                    // if (diameter(Ai U {j}) > d)
                                    if (minDistance > qualityThreshold) {
                                        done = true;
                                    } else {
                                        // remove the instance from the ones to be considered
                                        final int instance = notClustered.remove(minDistanceInstanceIndex);
                                        // and add it to the newly formed cluster
                                        candidateCluster.add(instance);
                                    }
                                    if (logInnerLoopProgress) {
                                        innerLoopProgressLogger.update();
                                    }
                                }
                                if (logInnerLoopProgress) {
                                    innerLoopProgressLogger.stop("Inner loop completed.");
                                }
                                if (logOuterLoopProgress) {
                                    outerLoopProgressLogger.update();
                                }
                            }
                        }
                    });
                }
            });

            if (logOuterLoopProgress) {
                outerLoopProgressLogger.stop("Outer loop completed.");
            }

            // identify cluster (set C) with maximum cardinality
            int maxCardinality = 0;
            int selectedClusterIndex = -1;
            for (int i = 0; i < instanceList.size(); i++) {
                final int size = candidateClusters[i].size();
                if (LOGGER.isTraceEnabled() && size > 0) {
                    LOGGER.trace("potential cluster " + i + ": " + ArrayUtils.toString(candidateClusters[i]));
                }
                if (size > maxCardinality) {
                    maxCardinality = size;
                    selectedClusterIndex = i;
                }
            }

            final IntArrayList selectedCluster = candidateClusters[selectedClusterIndex];

            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("adding " + selectedCluster.size() + " instances to cluster " + clusterCount);
            }
            // and add that cluster to the final result
            clusters[clusterCount].addAll(selectedCluster);

            // remove instances in cluster C so they are no longer considered
            instanceList.removeAll(selectedCluster);

            if (logClusterProgress) {
                final int selectedClusterSize = selectedCluster.size();
                int i = 0;
                while (i < selectedClusterSize - 1) {
                    clusterProgressLogger.lightUpdate();
                    i++;
                }
                // make sure there is at least one "full" update per loop
                if (i < selectedClusterSize) {
                    clusterProgressLogger.update();
                }
            }

            // we just created a new cluster
            clusterCount++;

            // next iteration is over (G - C)
        }
    } catch (RuntimeException e) {
        LOGGER.error("Caught runtime exception - rethrowing", e);
        throw e;
    } catch (Exception e) {
        LOGGER.error("Caught exception - rethrowing as ClusteringException", e);
        throw new ClusteringException(e);
    }

    // add singleton clusters to the end so the largest clusters are at the start of the list
    for (final int singleton : singletonClusters) {
        clusters[clusterCount].add(singleton);
        clusterCount++;
    }

    clusterProgressLogger.stop("Clustering completed.");
    return getClusters();
}

From source file:mergedoc.core.Comment.java

/**
 * JDK1.5  API ???? pre HTML ??/*  w ww. ja v a 2 s . c o m*/
 * ???????????Java ?????
 * ????pre ????????????? API ?
 * ???
 */
private void replacePreBody() {

    // pre ??????????
    if (!docBody.contains("<pre>")) {
        return;
    }

    // Java ? pre ??
    LinkedList<String> pres = null;
    String commentBody = FastStringUtils.replaceAll(srcBody, "(?m)^\\s*\\*( |)", "");
    Pattern pat = PatternCache.getPattern("(?s)(<pre>\n)(.+?)(\n</pre>)");
    Matcher mat = pat.matcher(commentBody);
    while (mat.find()) {
        if (pres == null) {
            pres = new LinkedList<String>();
        }
        pres.add(mat.group(2));
    }
    if (pres == null) {
        return;
    }

    // API ? pre ?? Java ???
    Matcher descMatcher = pat.matcher(docBody);
    StringBuffer sb = new StringBuffer();
    while (descMatcher.find()) {

        // pre ??????????
        if (pres.size() == 0) {
            return;
        }
        String value = FastStringUtils.quoteReplacement(pres.removeFirst());
        descMatcher.appendReplacement(sb, "$1" + value + "$3");
    }
    descMatcher.appendTail(sb);

    // pre ????????
    if (pres.size() == 0) {
        docBody = sb.toString();
    }
}

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.mqo.PiggybackingWorker.java

/**
 * /*from w  w  w.  j  a v a  2 s  . c  o  m*/
 * @param workingSet
 * @return
 * @throws IllegalAccessException 
 */
protected LinkedList<MergedMRJobInstruction> mergeMRJobInstructions(
        LinkedList<Pair<Long, MRJobInstruction>> workingSet) throws IllegalAccessException {
    LinkedList<MergedMRJobInstruction> ret = new LinkedList<MergedMRJobInstruction>();
    Timing time = new Timing(true);

    //NOTE currently all merged into one (might be invalid due to memory constraints)
    MergedMRJobInstruction minst = new MergedMRJobInstruction();
    for (Pair<Long, MRJobInstruction> inst : workingSet) {
        long instID = inst.getKey();
        MRJobInstruction instVal = inst.getValue();
        int numOutputs = instVal.getOutputs().length;

        //append to current merged instruction
        if (minst.inst == null) {
            //deep copy first instruction
            minst.inst = new MRJobInstruction(instVal);
            minst.addInstructionMetaData(instID, 0, numOutputs);
        } else {
            //merge other instructions
            if (minst.inst.isMergableMRJobInstruction(instVal)) {
                //add instruction to open merged instruction
                int offOutputs = minst.inst.getOutputs().length; //before merge
                minst.inst.mergeMRJobInstruction(instVal);
                minst.addInstructionMetaData(instID, offOutputs, numOutputs);
            } else {
                //close current merged instruction
                ret.add(minst);
                //open new merged instruction
                minst = new MergedMRJobInstruction();
                minst.inst = new MRJobInstruction(instVal);
                minst.addInstructionMetaData(instID, 0, numOutputs);
            }
        }
    }
    //close last open merged instruction
    ret.add(minst);

    //output log info for better understandability for users
    LOG.info("Merged MR-Job instructions: " + workingSet.size() + " --> " + ret.size() + " in " + time.stop()
            + "ms.");

    return ret;
}

From source file:com.nhncorp.lucy.security.xss.XssSaxFilter.java

/**
 * @param stackForObjectTag// w ww .j  a  v  a2s. c o m
 * @param stackForAllowNetworkingValue
 * @param element
 */
private void doObjectParamStartTagProcess(LinkedList<Element> stackForObjectTag,
        LinkedList<String> stackForAllowNetworkingValue, Element element) {

    if ("object".equalsIgnoreCase(element.getName())) {
        stackForObjectTag.push(element);
        boolean isDataWhiteUrl = false;

        Attribute dataUrl = element.getAttribute("data");

        if (dataUrl != null) { // data ??  ?
            String dataUrlStr = dataUrl.getValue();
            isDataWhiteUrl = this.isWhiteUrl(dataUrlStr);

            // URL MIME ?
            boolean isVulnerable = SecurityUtils.checkVulnerable(element, dataUrlStr, isDataWhiteUrl);

            if (isVulnerable) {
                element.setEnabled(false);
                return;
            }
        }

        if (isDataWhiteUrl) {
            stackForAllowNetworkingValue.push("\"all\""); // data?? url ? white url? allowNetworking ? ? all
        } else {
            stackForAllowNetworkingValue.push("\"internal\""); // allowNetworking ? ? internal
        }
    } else if (stackForObjectTag.size() > 0 && "param".equalsIgnoreCase(element.getName())) {
        Attribute nameAttr = element.getAttribute("name");
        Attribute valueAttr = element.getAttribute("value");

        if (nameAttr != null && valueAttr != null) {
            stackForObjectTag.push(element);
            if (containsURLName(nameAttr.getValue())) {
                stackForAllowNetworkingValue.pop();
                boolean whiteUrl = isWhiteUrl(valueAttr.getValue());

                if (whiteUrl) {
                    stackForAllowNetworkingValue.push("\"all\""); // whiteUrl ?  allowNetworking ? all  
                } else {
                    stackForAllowNetworkingValue.push("\"internal\""); // whiteUrl ? ?  allowNetworking ? internal  
                }
            }
        }
    }
}

From source file:org.gephi.statistics.plugin.ConnectedComponents.java

public void weaklyConnected(HierarchicalUndirectedGraph hgraph, AttributeModel attributeModel) {
    isCanceled = false;/*from  ww w  .j a v a 2s .c  o m*/
    componentCount = 0;
    AttributeTable nodeTable = attributeModel.getNodeTable();
    AttributeColumn componentCol = nodeTable.getColumn(WEAKLY);
    if (componentCol == null) {
        componentCol = nodeTable.addColumn(WEAKLY, "Component ID", AttributeType.INT, AttributeOrigin.COMPUTED,
                new Integer(0));
    }

    List<Integer> sizeList = new ArrayList<Integer>();

    hgraph.readLock();

    HashMap<Node, Integer> indicies = new HashMap<Node, Integer>();
    int index = 0;
    for (Node s : hgraph.getNodes()) {
        indicies.put(s, index);
        index++;
    }

    int N = hgraph.getNodeCount();

    //Keep track of which nodes have been seen
    int[] color = new int[N];

    Progress.start(progress, hgraph.getNodeCount());
    int seenCount = 0;
    while (seenCount < N) {
        //The search Q
        LinkedList<Node> Q = new LinkedList<Node>();
        //The component-list
        LinkedList<Node> component = new LinkedList<Node>();

        //Seed the seach Q
        NodeIterable iter = hgraph.getNodes();
        for (Node first : iter) {
            if (color[indicies.get(first)] == 0) {
                Q.add(first);
                iter.doBreak();
                break;
            }
        }

        //While there are more nodes to search
        while (!Q.isEmpty()) {
            if (isCanceled) {
                hgraph.readUnlock();
                return;
            }
            //Get the next Node and add it to the component list
            Node u = Q.removeFirst();
            component.add(u);

            //Iterate over all of u's neighbors
            EdgeIterable edgeIter = hgraph.getEdgesAndMetaEdges(u);

            //For each neighbor
            for (Edge edge : edgeIter) {
                Node reachable = hgraph.getOpposite(u, edge);
                int id = indicies.get(reachable);
                //If this neighbor is unvisited
                if (color[id] == 0) {
                    color[id] = 1;
                    //Add it to the search Q
                    Q.addLast(reachable);
                    //Mark it as used 

                    Progress.progress(progress, seenCount);
                }
            }
            color[indicies.get(u)] = 2;
            seenCount++;
        }
        for (Node s : component) {
            AttributeRow row = (AttributeRow) s.getNodeData().getAttributes();
            row.setValue(componentCol, componentCount);
        }
        sizeList.add(component.size());
        componentCount++;
    }
    hgraph.readUnlock();

    componentsSize = new int[sizeList.size()];
    for (int i = 0; i < sizeList.size(); i++) {
        componentsSize[i] = sizeList.get(i);
    }
}

From source file:de.tobiasroeser.maven.featurebuilder.FeatureBuilder.java

public List<Bundle> scanBundlesAtDir(final String scanJarsAtDir) {
    final File file = new File(scanJarsAtDir);

    final LinkedList<Bundle> bundles = new LinkedList<Bundle>();

    if (!file.exists() || !file.isDirectory()) {
        log.error("Directory '" + file.getAbsolutePath() + "' does not exists.");
        return bundles;
    }// w ww  .  java  2 s.c  o  m

    for (final File jar : file.listFiles()) {
        if (jar.isFile() && jar.getName().toLowerCase().endsWith(".jar")) {
            try {
                final JarInputStream jarStream = new JarInputStream(
                        new BufferedInputStream(new FileInputStream(jar)));
                final Manifest manifest = jarStream.getManifest();
                String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
                final String version = manifest.getMainAttributes().getValue("Bundle-Version");
                if (symbolicName != null && version != null) {
                    symbolicName = symbolicName.split(";")[0].trim();
                    final Bundle bundle = new Bundle(symbolicName, version, jar.length(), jar);
                    bundles.add(bundle);
                } else {
                    log.warn("jar '" + jar.getAbsolutePath() + "' is not an OSGi bundle.");
                }

            } catch (final FileNotFoundException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            } catch (final IOException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            }

        }
    }
    log.info("Found " + bundles.size() + " bundles in scanned directory: " + file.getAbsolutePath());

    Collections.sort(bundles);
    return bundles;
}

From source file:com.cablelabs.sim.PCSim2.java

/**
 * This method determines whether the global presence server needs to be started
 * //from  ww  w  .j  a  v  a  2 s . c  o  m
 */
private boolean configPresenceServer() {
    presenceServerEnabled = SystemSettings.getBooleanSetting("Presence Server");
    if (presenceServerEnabled) {
        Properties platform = SystemSettings.getSettings(SettingConstants.PLATFORM);
        String psName = platform.getProperty(SettingConstants.PRESENCE_SERVER_FSM);
        if (presenceServerFile == null) {
            presenceServerFile = psName;
        } else if (presenceServerFile.equals(psName)) {
            return true;
        } else {
            if (stacks != null)
                stacks.shutdownPresenceServer();
            presenceServerFile = psName;
        }
        if (presenceServerFile != null) {
            File ps = new File(presenceServerFile);
            if (ps != null && ps.exists() && ps.canRead() && ps.isFile()) {
                TSParser tsp = new TSParser(false);
                try {
                    logger.info(PC2LogCategory.Parser, subCat,
                            "Parsing document " + presenceServerFile + " for PresenceServer processing.");
                    TSDocument psDoc = tsp.parse(presenceServerFile);
                    LinkedList<FSM> fsms = psDoc.getFsms();
                    if (fsms.size() == 1) {
                        FSM f = fsms.getFirst();
                        if (f.getModel() instanceof PresenceModel) {
                            PresenceModel model = (PresenceModel) f.getModel();
                            // Initialize the settings that can be overwritten from
                            // within the document 
                            setExtensions(fsms);
                            PresenceServer server = PresenceServer.getInstance(f, model.getElements());
                            if (server != null) {
                                Stacks.setPresenceServer(server);
                                server.init();
                                return true;
                            }
                        }

                    }
                } catch (PC2XMLException pe) {
                    String err = "\n** Parsing error in file \n    " + pe.getFileName() + " at line "
                            + pe.getLineNumber();
                    if (pe.getSystemId() != null) {
                        err += ", uri " + pe.getSystemId();
                    }
                    if (pe.getPublicId() != null) {
                        err += ", public " + pe.getPublicId();
                    }
                    err += "\n";

                    logger.fatal(PC2LogCategory.Parser, subCat, err, pe);
                } catch (SAXParseException spe) {
                    String err = "\n** Parsing error in file \n    " + presenceServerFile + " at line "
                            + spe.getLineNumber();
                    if (spe.getSystemId() != null) {
                        err += ", uri " + spe.getSystemId();
                    }
                    if (spe.getPublicId() != null) {
                        err += ", public " + spe.getPublicId();
                    }
                    err += "\n";

                    logger.fatal(PC2LogCategory.Parser, subCat, err, spe);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                //               if (ps == null) {
                //                  logger.fatal(PC2LogCategory.Parser, subCat,
                //                        "The platform configuration file doesn't appear to have a " 
                //                        + "value for the \"Presence Server FSM\" setting.");
                //               }
                if (!ps.exists()) {
                    logger.fatal(PC2LogCategory.Parser, subCat, "The \"Presence Server FSM\" setting=[" + ps
                            + "] doesn't appear to define a valid path or file name.");
                }
                if (!ps.canRead()) {
                    logger.fatal(PC2LogCategory.Parser, subCat,
                            "The \"Presence Server FSM\" setting=[" + ps + "] can not be read by the system.");
                }
                if (!ps.isFile()) {
                    logger.fatal(PC2LogCategory.Parser, subCat, "The \"Presence Server FSM\" setting=[" + ps
                            + "] doesn't appear to define a file.");
                }
            }
        }
    }
    return false;
}

From source file:com.cablelabs.sim.PCSim2.java

/**
 * This method determines whether the global registration needs to be started
 * /*from w  w  w. ja  v a 2s  . com*/
 */
private boolean configGlobalRegistrar() {
    globalRegEnabled = SystemSettings.getBooleanSetting("Global Registrar");
    if (globalRegEnabled) {
        Properties platform = SystemSettings.getSettings(SettingConstants.PLATFORM);
        String grName = platform.getProperty(SettingConstants.GLOBAL_REGISTRAR_FSM);
        if (globalRegFile == null) {
            globalRegFile = grName;
        } else if (globalRegFile.equals(grName)) {
            return true;
        } else {
            if (stacks != null)
                stacks.shutdownGlobalRegistrars();
            globalRegFile = grName;
        }
        if (globalRegFile != null) {
            File gr = new File(globalRegFile);
            if (gr != null && gr.exists() && gr.canRead() && gr.isFile()) {
                TSParser tsp = new TSParser(false);
                try {
                    logger.info(PC2LogCategory.Parser, subCat,
                            "Parsing document " + globalRegFile + " for GlobalRegistrar processing.");
                    TSDocument grDoc = tsp.parse(globalRegFile);
                    LinkedList<FSM> fsms = grDoc.getFsms();
                    if (fsms.size() == 1) {
                        // Initialize the settings that can be overwritten from
                        // within the document 
                        setExtensions(fsms);
                        FSM grFsm = fsms.getFirst();
                        String transport = grFsm.getModel().getProperty(SettingConstants.TRANSPORT_PROTOCOL);
                        Transport t = Transport.UDP;
                        if (transport != null) {
                            if (transport.equals(Transport.UDP.toString()))
                                t = Transport.UDP;
                            else if (transport.equals(Transport.TCP.toString()))
                                t = Transport.TCP;
                            else if (transport.equals(Transport.TLS.toString()))
                                t = Transport.TLS;
                        } else {
                            if (platform != null) {
                                transport = platform.getProperty(SettingConstants.SIP_DEF_TRANPORT_PROTOCOL);
                                if (transport != null) {
                                    if (transport.equals(Transport.UDP.toString()))
                                        t = Transport.UDP;
                                    else if (transport.equals(Transport.TCP.toString()))
                                        t = Transport.TCP;
                                    else if (transport.equals(Transport.TLS.toString()))
                                        t = Transport.TLS;
                                }
                            }
                        }
                        GlobalRegistrar.setMasterFSM(grFsm, t);

                        return true;

                    }
                } catch (PC2XMLException pe) {
                    String err = "\n** Parsing error in file \n    " + pe.getFileName() + " at line "
                            + pe.getLineNumber();
                    if (pe.getSystemId() != null) {
                        err += ", uri " + pe.getSystemId();
                    }
                    if (pe.getPublicId() != null) {
                        err += ", public " + pe.getPublicId();
                    }
                    err += "\n";

                    logger.fatal(PC2LogCategory.Parser, subCat, err, pe);
                } catch (SAXParseException spe) {
                    String err = "\n** Parsing error in file \n    " + globalRegFile + " at line "
                            + spe.getLineNumber();
                    if (spe.getSystemId() != null) {
                        err += ", uri " + spe.getSystemId();
                    }
                    if (spe.getPublicId() != null) {
                        err += ", public " + spe.getPublicId();
                    }
                    err += "\n";

                    logger.fatal(PC2LogCategory.Parser, subCat, err, spe);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                //               if (gr == null) {
                //                  logger.fatal(PC2LogCategory.Parser, subCat,
                //                        "The platform configuration file doesn't appear to have a " 
                //                        + "value for the \"Global Registrar FSM\" setting.");
                //               }
                if (!gr.exists()) {
                    logger.fatal(PC2LogCategory.Parser, subCat, "The \"Global Registrar FSM\" setting=[" + gr
                            + "] doesn't appear to define a valid path or file name.");
                }
                if (!gr.canRead()) {
                    logger.fatal(PC2LogCategory.Parser, subCat,
                            "The \"Global Registrar FSM\" setting=[" + gr + "] can not be read by the system.");
                }
                if (!gr.isFile()) {
                    logger.fatal(PC2LogCategory.Parser, subCat, "The \"Global Registrar FSM\" setting=[" + gr
                            + "] doesn't appear to define a file.");
                }
            }

        }
    }
    return false;
}

From source file:com.opengamma.util.db.management.AbstractDbManagement.java

@Override
public void clearTables(String catalog, String schema, Collection<String> ignoredTables) {
    LinkedList<String> script = new LinkedList<String>();
    Connection conn = null;/*from   w w w. j a  v a2 s  .  c om*/
    try {
        if (!getCatalogCreationStrategy().catalogExists(catalog)) {
            return; // nothing to clear
        }

        conn = connect(catalog);
        setActiveSchema(conn, schema);
        Statement statement = conn.createStatement();

        // Clear tables SQL
        List<String> tablesToClear = new ArrayList<String>();
        for (String name : getAllTables(catalog, schema, statement)) {
            if (!ignoredTables.contains(name.toLowerCase())) {
                tablesToClear.add(name);
            }
        }
        List<String> clearTablesCommands = getClearTablesCommand(schema, tablesToClear);
        script.addAll(clearTablesCommands);
        for (String name : tablesToClear) {
            Table table = new Table(name);
            if (matches(table.getName().toLowerCase(), Pattern.compile(".*?hibernate_sequence"))) { // if it's a sequence table, reset it 
                script.add("INSERT INTO " + table.getQualifiedName(getHibernateDialect(), null, schema)
                        + " values ( 1 )");
            }
        }

        // Now execute it all. Constraints are taken into account by retrying the failed statement after all 
        // dependent tables have been cleared first.
        int i = 0;
        int maxAttempts = script.size() * 3; // make sure the loop eventually terminates. Important if there's a cycle in the table dependency graph
        SQLException latestException = null;
        while (i < maxAttempts && !script.isEmpty()) {
            String sql = script.remove();
            try {
                statement.executeUpdate(sql);
            } catch (SQLException e) {
                // assume it failed because of a constraint violation
                // try deleting other tables first - make this the new last statement
                latestException = e;
                script.add(sql);
            }
            i++;
        }
        statement.close();

        if (i == maxAttempts && !script.isEmpty()) {
            throw new OpenGammaRuntimeException(
                    "Failed to clear tables - is there a cycle in the table dependency graph?",
                    latestException);
        }

    } catch (SQLException e) {
        throw new OpenGammaRuntimeException("Failed to clear tables", e);
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
        }
    }
}