Example usage for java.util Vector lastElement

List of usage examples for java.util Vector lastElement

Introduction

In this page you can find the example usage for java.util Vector lastElement.

Prototype

public synchronized E lastElement() 

Source Link

Document

Returns the last component of the vector.

Usage

From source file:padl.creator.classfile.relationship.RelationshipAnalyzer.java

private List analyseDeepMethodInvocations(final IFirstClassEntity currentEntity,
        final ExtendedMethodInfo methodInfo) {

    final IOperation currentMethod = (IOperation) currentEntity
            .getConstituentFromID(Utils.computeSignature(methodInfo));
    final DeepMethodInvocationAnalyzer analyzer = DeepMethodInvocationAnalyzer.getUniqueInstance();
    final List couplesOfUsedAttributes = analyzer.analyzeMethod(methodInfo);

    final List methodInvocations = new ArrayList();
    boolean foundArrayStaticOrNot = false;
    Vector foundFieldStaticOrNot = null;
    IFirstClassEntity foundEntityDeclaringField = null;
    boolean foundArrayLoad = false;
    final Iterator iterAttributes = couplesOfUsedAttributes.iterator();
    while (iterAttributes.hasNext()) {
        final String[] nextCouple = (String[]) iterAttributes.next();
        final boolean isFieldEmpty = Utils.isMemberNameEmptyOrEqual(nextCouple[0]);
        final boolean isMethodEmpty = Utils.isMemberNameEmpty(nextCouple[1]);

        final IFirstClassEntity entityDeclaringField;
        final IFirstClassEntity entityDeclaringMethod;
        final Vector callingFields;
        final IOperation calledMethod;
        ExtendedMethodInvocation methodInvocation = null;

        // Yann 2012/02/02: Dealing with static arrays!
        // The idea is to remember if a static array is
        // used just before an instance method invocation,
        // then a dedicated IMetodInvocation is created.
        if (nextCouple[1] != null && nextCouple[1].endsWith(":" + JVMConstants.AALOAD)) {

            foundArrayLoad = true;/* w  ww.  j  a v  a2  s . c o  m*/
        }

        if (!isFieldEmpty && !isMethodEmpty && !Utils.isAnonymousOrLocalEntity(
                nextCouple[0].substring(0, nextCouple[0].indexOf(" ")).toCharArray())) {

            callingFields = this.createFieldsFromFieldInfos(nextCouple[0]);

            // Yann 2004/06/02: Field assignment!
            // I want to know when a field is assigned to
            // distinguish data type from ordanary class.
            if (nextCouple[1].equals(String.valueOf(RelationshipAnalyzer.EQUAL_SIGN))) {

                calledMethod = RelationshipAnalyzer.ASSIGNMENT_METHOD;
            } else {
                calledMethod = this.createOperation(nextCouple[1]);
            }
            entityDeclaringField = Utils.getEntityOrCreateGhost(this.codeLevelModel,
                    nextCouple[0].substring(0, nextCouple[0].indexOf(" ")).toCharArray(),
                    RelationshipAnalyzer.MapOfIDsEntities);
            if (nextCouple[1].equals(String.valueOf(RelationshipAnalyzer.EQUAL_SIGN))) {

                entityDeclaringMethod = null;
            } else {
                final String fieldNameAndType = nextCouple[0].substring(nextCouple[0].indexOf(" ") + 1);

                String fieldType = fieldNameAndType.substring(fieldNameAndType.indexOf('.') + 1);
                final int hashCharPos = fieldType.indexOf('#');
                if (hashCharPos > 0) {
                    fieldType = fieldType.substring(0, hashCharPos);
                }

                entityDeclaringMethod = Utils.getEntityOrCreateGhost(this.codeLevelModel,
                        fieldType.toCharArray(), RelationshipAnalyzer.MapOfIDsEntities);
            }
            methodInvocation = new ExtendedMethodInvocation(this.codeLevelModel.getFactory(), currentEntity,
                    currentMethod,
                    // Yann 2012/02/02: Not sure!
                    // I believe that we should use the commented code
                    // instead of the uncommented code. However, the
                    // commented code leads to the creation of more
                    // aggregation relationships than expected, see
                    // for example the test
                    //   padl.creator.test.classfile.example.CreationLink_INSTANCE_CREATION_3
                    RelationshipAnalyzer.computeMethodInvocationTypeThroughField(
                            (IField) callingFields.lastElement(), calledMethod),
                    ((IField) callingFields.lastElement()).getCardinality(), entityDeclaringMethod,
                    entityDeclaringField);
            methodInvocation.setCallingField(callingFields);
            methodInvocation.setCalledMethod(calledMethod);
            methodInvocations.add(methodInvocation);
        } else if (!isFieldEmpty && isMethodEmpty && !Utils.isAnonymousOrLocalEntity(
                nextCouple[0].substring(0, nextCouple[0].indexOf(" ")).toCharArray())) {

            callingFields = this.createFieldsFromFieldInfos(nextCouple[0]);
            // Yann 2007/01/24: Unneeded test
            // The test of the callingFields being null
            // is only needed because of the bug documented
            // in method extractFieldName()!
            if (callingFields.get(0) == null) {
                break;
            }
            entityDeclaringField = Utils.getEntityOrCreateGhost(this.codeLevelModel,
                    nextCouple[0].substring(0, nextCouple[0].indexOf(" ")).toCharArray(),
                    RelationshipAnalyzer.MapOfIDsEntities);
            // Yann 2012/02/02: Null Object!
            // The use of the "null" value below is really ugly
            // and suggest misadapted interface: at least a Null
            // Object should be used in this code.
            // TODO: Remove the use of "null"
            methodInvocation = new ExtendedMethodInvocation(this.codeLevelModel.getFactory(), currentEntity,
                    currentMethod, IMethodInvocation.OTHER,
                    ((IField) callingFields.lastElement()).getCardinality(), null, entityDeclaringField);
            methodInvocation.setCallingField(callingFields);
            methodInvocations.add(methodInvocation);

            // Yann 2012/02/02: Dealing with static arrays!
            // The idea is to remember if a static array is
            // used just before an instance method invocation,
            // then a dedicated IMetodInvocation is created.
            if (((IField) callingFields.lastElement()).getCardinality() == Constants.CARDINALITY_MANY) {
                foundArrayStaticOrNot = true;
                foundFieldStaticOrNot = callingFields;
                foundEntityDeclaringField = entityDeclaringField;
            }
        } else if (isFieldEmpty && !isMethodEmpty && !Utils.isAnonymousOrLocalEntity(
                nextCouple[1].substring(0, nextCouple[1].indexOf(" ")).toCharArray())) {

            calledMethod = this.createOperation(nextCouple[1]);
            entityDeclaringMethod = Utils.getEntityOrCreateGhost(this.codeLevelModel,
                    nextCouple[1].substring(0, nextCouple[1].indexOf(" ")).toCharArray(),
                    RelationshipAnalyzer.MapOfIDsEntities);

            // Yann 2012/03/23: New case!
            // Sgla found out that in Lucene Core v3.0.3, the callee is
            // actually "long[]", which leads to entityDeclaringMethod being
            // null and thus break the code below...
            if (entityDeclaringMethod != null) {

                // Yann 2012/02/02: Dealing with static arrays!
                // The idea is to remember if a static array is
                // used just before an instance method invocation,
                // then a dedicated IMetodInvocation is created.
                if (foundArrayStaticOrNot && foundArrayLoad) {
                    methodInvocation = new ExtendedMethodInvocation(this.codeLevelModel.getFactory(),
                            currentEntity, currentMethod,
                            RelationshipAnalyzer.computeMethodInvocationTypeThroughField(
                                    (IField) foundFieldStaticOrNot.lastElement(), calledMethod),
                            ((IField) foundFieldStaticOrNot.lastElement()).getCardinality(),
                            entityDeclaringMethod, foundEntityDeclaringField);
                    methodInvocation.setCallingField(foundFieldStaticOrNot);
                    methodInvocation.setCalledMethod(calledMethod);
                    methodInvocations.add(methodInvocation);

                    foundArrayStaticOrNot = false;
                    foundFieldStaticOrNot = null;
                    foundEntityDeclaringField = null;
                    foundArrayLoad = false;
                } else {
                    // Yann 2012/02/21: Cardinality
                    // Thanks to Aminata, we have now clear test about
                    // method invocations and we unify the created MIs
                    // between the JavaFile Creator and the ClassFile 
                    // Creator. From now on, cardinality also matters
                    // in the following...

                    final int cardinality;
                    // I must use getID because I need the package name, not just the simple name.
                    if (Util.isArrayOrCollection(entityDeclaringMethod.getID()) || foundArrayLoad) {

                        cardinality = Constants.CARDINALITY_MANY;
                    } else {
                        cardinality = Constants.CARDINALITY_ONE;
                    }

                    methodInvocation = new ExtendedMethodInvocation(this.codeLevelModel.getFactory(),
                            currentEntity, currentMethod,
                            RelationshipAnalyzer.computeMethodInvocationTypeDirect(currentMethod, calledMethod),
                            cardinality, entityDeclaringMethod);
                    methodInvocation.setCalledMethod(calledMethod);
                    methodInvocations.add(methodInvocation);
                }
            }
        }

        if (this.storeMethodInvocation && methodInvocation != null) {
            currentMethod.addConstituent(methodInvocation.getMethodInvocation());
        }
    }

    return methodInvocations;
}

From source file:org.ohmage.db.DbHelper.java

/**
 * Utility method that populates the Survey and SurveyPrompt tables for the
 * campaign identified by campaignUrn and containing the given xml as
 * campaignXML./*from  w w w.java2  s. c om*/
 * 
 * Note that this method takes a db handle so that it can be used in a
 * transaction.
 * 
 * @param db
 *            a handle to an existing writable db
 * @param campaignUrn
 *            the urn of the campaign for which we're populating subtables
 * @param campaignXML
 *            the XML for the campaign (not validated by this method)
 * @return
 * 
 */
public boolean populateSurveysFromCampaignXML(SQLiteDatabase db, String campaignUrn, String campaignXML) {
    try {
        // dump all the surveys (and consequently survey prompts) before we
        // do anything
        // this is (perhaps surprisingly) desired behavior, as the surveys +
        // survey prompts
        // should always reflect the state of the campaign XML, valid or not
        db.delete(Tables.SURVEYS, Surveys.CAMPAIGN_URN + "=?", new String[] { campaignUrn });

        // do a pass over the XML to gather surveys and survey prompts
        XmlPullParser xpp = Xml.newPullParser();
        xpp.setInput(new ByteArrayInputStream(campaignXML.getBytes("UTF-8")), "UTF-8");
        int eventType = xpp.getEventType();
        String tagName;

        // various stacks to maintain state while walking through the xml
        // tree
        Stack<String> tagStack = new Stack<String>();
        Survey curSurvey = null; // valid only within a survey, null
        // otherwise
        Vector<SurveyPrompt> prompts = new Vector<SurveyPrompt>(); // valid
        // only
        // within
        // a
        // survey,
        // empty
        // otherwise
        Vector<JSONObject> properties = new Vector<JSONObject>(); // valid
        // only
        // within
        // a
        // prompt,
        // empty
        // otherwise

        // iterate through the xml, paying attention only to surveys and
        // prompts
        // note that this does no validation outside of preventing itself
        // from crashing catastrophically
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {
                tagName = xpp.getName();
                tagStack.push(tagName);

                if (tagName.equalsIgnoreCase("survey")) {
                    if (curSurvey != null)
                        throw new XmlPullParserException("encountered a survey tag inside another survey tag");

                    curSurvey = new Survey();
                    curSurvey.mCampaignUrn = campaignUrn;

                } else if (tagName.equalsIgnoreCase("prompt")) {
                    SurveyPrompt sp = new SurveyPrompt();
                    // FIXME: add the campaign + survey ID to make lookups
                    // easier?
                    prompts.add(sp);
                } else if (tagName.equalsIgnoreCase("property")) {
                    properties.add(new JSONObject());
                }
            } else if (eventType == XmlPullParser.TEXT) {
                if (tagStack.size() >= 2) {
                    // we may be in an entity>property situation, so check
                    // and assign accordingly
                    if (tagStack.get(tagStack.size() - 2).equalsIgnoreCase("survey")) {
                        // populating the current survey object with its
                        // properties here
                        if (tagStack.peek().equalsIgnoreCase("id"))
                            curSurvey.mSurveyID = xpp.getText();
                        else if (tagStack.peek().equalsIgnoreCase("title"))
                            curSurvey.mTitle = xpp.getText();
                        else if (tagStack.peek().equalsIgnoreCase("description"))
                            curSurvey.mDescription = xpp.getText();
                        else if (tagStack.peek().equalsIgnoreCase("submitText"))
                            curSurvey.mSubmitText = xpp.getText();
                        else if (tagStack.peek().equalsIgnoreCase("showSummary"))
                            curSurvey.mShowSummary = xpp.getText().equals("true") ? true : false;
                        else if (tagStack.peek().equalsIgnoreCase("editSummary"))
                            curSurvey.mEditSummary = xpp.getText().equals("true") ? true : false;
                        else if (tagStack.peek().equalsIgnoreCase("summaryText"))
                            curSurvey.mSummaryText = xpp.getText();
                        else if (tagStack.peek().equalsIgnoreCase("introText"))
                            curSurvey.mIntroText = xpp.getText();
                        else if (tagStack.peek().equalsIgnoreCase("anytime"))
                            curSurvey.mAnytime = xpp.getText().equals("true") ? true : false;
                    } else if (tagStack.get(tagStack.size() - 2).equalsIgnoreCase("prompt")) {
                        SurveyPrompt sp = prompts.lastElement();

                        // populating the last encountered survey prompt
                        // with its properties here
                        if (tagStack.peek().equalsIgnoreCase("id"))
                            sp.mPromptID = xpp.getText();
                        else if (tagStack.peek().equalsIgnoreCase("promptText"))
                            sp.mPromptText = xpp.getText();
                        else if (tagStack.peek().equalsIgnoreCase("promptType"))
                            sp.mPromptType = xpp.getText();
                    } else if (tagStack.get(tagStack.size() - 2).equalsIgnoreCase("property")) {
                        JSONObject curProperty = properties.lastElement();

                        // populating the last encountered property
                        if (tagStack.peek().equalsIgnoreCase("key"))
                            curProperty.put("key", xpp.getText());
                        else if (tagStack.peek().equalsIgnoreCase("label"))
                            curProperty.put("label", xpp.getText());
                        else if (tagStack.peek().equalsIgnoreCase("value"))
                            curProperty.put("value", xpp.getText());
                    }
                }
            } else if (eventType == XmlPullParser.END_TAG) {
                tagName = xpp.getName();
                tagStack.pop();

                if (tagName.equalsIgnoreCase("survey")) {
                    // store the current survey to the database
                    long surveyPID = db.insert(Tables.SURVEYS, null, curSurvey.toCV());

                    // also store all the prompts we accumulated for it
                    for (SurveyPrompt sp : prompts) {
                        sp.mSurveyID = curSurvey.mSurveyID;
                        sp.mSurveyPID = surveyPID;
                        sp.mCompositeID = curSurvey.mCampaignUrn + ":" + curSurvey.mSurveyID;
                        db.insert(Tables.SURVEY_PROMPTS, null, sp.toCV());
                    }

                    // flush the prompts we've stored up so far
                    prompts.clear();

                    // Create Streams here
                    OhmagePDVManager.getInstance().createStreamForSurvey(campaignUrn, curSurvey.mSurveyID);
                    // and clear us from being in any survey
                    curSurvey = null;
                } else if (tagName.equalsIgnoreCase("prompt")) {
                    SurveyPrompt sp = prompts.lastElement();

                    // update the current prompt with the collected
                    // properties
                    JSONArray propertyArray = new JSONArray();

                    for (JSONObject property : properties)
                        propertyArray.put(property);

                    // encode it as json and stuff it in the surveyprompt
                    sp.mProperties = propertyArray.toString();

                    // and wipe the properties
                    properties.clear();
                }
            }

            eventType = xpp.next();
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (XmlPullParserException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.codecover.eclipse.views.CoverageGraphView.java

private edu.uci.ics.jung.graph.Graph<CoverageGraphNode, CoverageGraphLink> createGraph(String Criterion,
        String SUTLevel, String TestLevel, Boolean ShowOnlyCovered, Boolean CompleteName) {
    edu.uci.ics.jung.graph.Graph<CoverageGraphNode, CoverageGraphLink> graph = new SparseMultigraph<CoverageGraphNode, CoverageGraphLink>();
    try {/* w ww.  ja  va 2s . c o  m*/
        Set<CoverableItem> coverableItemSet = CreateCoverableItemSet(Criterion);
        Vector<CoverageGraphNode> SUTItems = new Vector<CoverageGraphNode>();
        Vector<String> SUTItemsId = new Vector<String>();
        Vector<CoverageGraphNode> TestItems = new Vector<CoverageGraphNode>();
        Vector<String> TestItemsId = new Vector<String>();
        int NumOfSUTNodes = 0;
        int NumOfTestNodes = 0;
        if (selectedTestCases.size() != 0) {
            CoverageGraphNode SUTNode;
            CoverageGraphNode TestNode;
            List<CoverableItem> SUTItemList = new ArrayList<CoverableItem>(coverableItemSet);
            List<CoverableItem> CoveredItemList;

            //Adding all of the SUT Nodes to the graph:
            //-----------------------------------------
            for (int j = 0; j < SUTItemList.size(); j++) {
                boolean ex = false;
                HierarchyLevel methodLevel = null;
                try {
                    methodLevel = getSUTItemMethod(SUTItemList.get(j));
                } catch (IllegalArgumentException e1) {
                    // the item is a condition, it is not possible to get the parent statement in the tree (it's parent is null)
                    ex = true;
                } catch (Exception e2) {
                    ex = true;
                }

                if (methodLevel != null && !ex) {
                    String PackageName = getSUTItemPackage(getSUTItemClass(methodLevel));
                    String ClassName = getSUTItemClass(methodLevel).getName();
                    String MethodName = methodLevel.getName();

                    String ItemName = getSUTItemId(SUTItemList.get(j).getId());
                    String nodeName = getNodeLable(SUTLevel, PackageName, ClassName, MethodName, ItemName);
                    if (!SUTItemsId.contains(nodeName)) {
                        SUTNode = new CoverageGraphNode("SUT", SUTLevel, PackageName, ClassName,
                                getSUTItemClass(methodLevel).getLocation().getLocations().get(0), MethodName,
                                methodLevel.getLocation().getLocations().get(0), ItemName, loc, StContent,
                                methodLevel, CompleteName);
                        SUTItemsId.add(SUTNode.getLable());
                        SUTItems.add(SUTNode);
                        NumOfSUTNodes++;
                        if (!ShowOnlyCovered)
                            graph.addVertex(SUTNode);
                    }
                }
            }

            Set<CoverableItem> coveredItemSet;
            int testsize = 0;
            if (!selectedTestCases.equals(null))
                testsize = selectedTestCases.size();
            for (int i = 0; i < testsize; i++) {

                //Adding Test Nodes to the graph:
                //-------------------------------
                TestCase tc = (TestCase) selectedTestCases.get(i);
                TestNode = new CoverageGraphNode("Test", TestLevel, getTestNodeName(tc.getName(), "Package"),
                        getTestNodeName(tc.getName(), "Class"), getTestNodeName(tc.getName(), "Method"),
                        CompleteName);
                String testNodeName = TestNode.getLable();
                if (!TestItemsId.contains(testNodeName)) {
                    TestItemsId.add(TestNode.getLable());
                    TestItems.add(TestNode);
                    graph.addVertex(TestNode);
                    TestNode.Testcases.add(tc);
                    NumOfTestNodes++;
                } else {
                    for (int k = 0; k < NumOfTestNodes; k++)
                        if (TestItems.get(k).getLable().compareTo(testNodeName) == 0)
                            TestNode = TestItems.get(k);
                    TestNode.Testcases.add(tc);
                }

                Map<CoverableItem, Long> CoveredItemMap = tc.getCoverageData();
                coveredItemSet = new HashSet<CoverableItem>();
                for (int j = 0; j < SUTItemList.size(); j++) {
                    coveredItemSet.add(SUTItemList.get(j));
                }
                coveredItemSet.retainAll(CoveredItemMap.keySet());
                CoveredItemList = new ArrayList<CoverableItem>(coveredItemSet);

                String nodeName = "";
                for (int j = 0; j < CoveredItemList.size(); j++) {
                    boolean ex = false;
                    HierarchyLevel methodLevel = null;
                    HierarchyLevel currentlevel = null;
                    try {
                        methodLevel = getSUTItemMethod(CoveredItemList.get(j));
                    } catch (Exception ec) {
                        ex = true;
                    }

                    if (methodLevel != null && !ex) {
                        String PackageName = getSUTItemPackage(getSUTItemClass(methodLevel));
                        String ClassName = getSUTItemClass(methodLevel).getName();
                        String MethodName = methodLevel.getName();
                        String ItemName = getSUTItemId(CoveredItemList.get(j).getId());
                        nodeName = getNodeLable(SUTLevel, PackageName, ClassName, MethodName, ItemName);
                        //Adding Edges to the graph:
                        //--------------------------
                        Integer id = graph.getEdgeCount() + 1;
                        CoverageGraphLink CoverageLink = graph.findEdge(TestItems.lastElement(),
                                SUTItems.elementAt(SUTItemsId.indexOf(nodeName)));
                        if (CoverageLink == null) {
                            CoverageLink = new CoverageGraphLink(id);
                            CoverageLink.SUTLevel = SUTLevel;
                        } else
                            graph.removeEdge(CoverageLink);
                        CoverageLink.times++;

                        CoverageGraphNode CurrentNode = new CoverageGraphNode();
                        for (int k = 0; k < NumOfSUTNodes; k++)
                            if (SUTItems.get(k).getLable().compareTo(nodeName) == 0)
                                CurrentNode = SUTItems.get(k);
                        if (CurrentNode != null) {
                            if (ShowOnlyCovered)
                                graph.addVertex(CurrentNode);

                            //For calculating Ratio:
                            if (SUTLevel.compareTo("Method") == 0)
                                currentlevel = methodLevel;
                            else if (SUTLevel.compareTo("Class") == 0)
                                currentlevel = topLevel.getParent(methodLevel);
                            else if (SUTLevel.compareTo("Package") == 0) {
                                currentlevel = topLevel.getParent(methodLevel);
                                currentlevel = topLevel.getParent(currentlevel);
                            }
                            if (currentlevel != null) {
                                CoverageResult coverageResult = null;
                                if (Criterion.compareTo("Statement") == 0) {
                                    StatementCoverage coverageMetric = StatementCoverage.getInstance();
                                    coverageResult = coverageMetric.getCoverage(TestNode.Testcases,
                                            currentlevel);
                                } else if (Criterion.compareTo("Branch") == 0) {
                                    BranchCoverage coverageMetric = BranchCoverage.getInstance();
                                    coverageResult = coverageMetric.getCoverage(TestNode.Testcases,
                                            currentlevel);
                                } else if (Criterion.compareTo("Loop") == 0) {
                                    LoopCoverage coverageMetric = LoopCoverage.getInstance();
                                    coverageResult = coverageMetric.getCoverage(TestNode.Testcases,
                                            currentlevel);
                                } else if (Criterion.compareTo("Term") == 0) {
                                    TermCoverage coverageMetric = TermCoverage.getInstance();
                                    coverageResult = coverageMetric.getCoverage(TestNode.Testcases,
                                            currentlevel);
                                }
                                if (coverageResult != null) {
                                    float coverage = 0f;
                                    if (coverageResult.getTotalItems() > 0) {
                                        coverage = ((float) coverageResult.getCoveredItems()
                                                / coverageResult.getTotalItems());
                                    }
                                    CoverageLink.ratio = coverage;
                                }
                            } else
                                CoverageLink.ratio = 2;
                            graph.addEdge(CoverageLink, TestItems.lastElement(), CurrentNode,
                                    EdgeType.DIRECTED);
                        }
                    }
                }
                coveredItemSet.clear();
            }
        }
    } catch (Exception ex) {
        return null;
    }
    return graph;
}