Example usage for org.eclipse.jdt.core.dom SimpleName toString

List of usage examples for org.eclipse.jdt.core.dom SimpleName toString

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom SimpleName toString.

Prototype

@Override
public final String toString() 

Source Link

Document

Returns a string representation of this node suitable for debugging purposes only.

Usage

From source file:ast.StructureParse.java

private void enclose(String body, DefaultMutableTreeNode parentNode) {
    ASTParser parser = ASTParser.newParser(AST.JLS2);
    /*/*  www .  j  a  v  a  2s  .  co m*/
     * make parse result into OPP structure, because AST wanna be that.
    */
    String setClass = "class fo{\nvoid foo(){ \n" + body + "\n}\n}";
    parser.setSource(setClass.toCharArray());
    //parser.setSource("/*abc*/".toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    //ASTNode node = parser.createAST(null);
    parser.setResolveBindings(true);

    try {
        final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

        cu.accept(new ASTVisitor() {
            Set names2 = new HashSet();

            @Override
            public boolean visit(SimpleName node) {
                if (this.names2.contains(node.getIdentifier())) {
                    parentNode.add(new DefaultMutableTreeNode(node.toString()));
                    System.out.println("SimpleNode : " + node.toString());
                }
                return true;
            }

            @Override
            public boolean visit(EnhancedForStatement node) {
                _for = new DefaultMutableTreeNode(
                        "for (" + node.getParameter() + " : " + node.getExpression() + ")");
                parentNode.add(_for);
                System.out.println("for (" + node.getParameter() + " : " + node.getExpression() + ")");
                enclose(node.getBody().toString(), _for);
                return false;
            }

            @Override
            public boolean visit(ForStatement node) {
                /*
                 * because initial may more than 1.
                */
                String initial = "";
                for (int i = 0; i < node.initializers().size(); i++) {
                    initial += node.initializers().get(i);
                    if (node.initializers().size() - 1 != i)
                        initial += ", ";
                }

                /*
                 * because increment may more than 1
                */
                String inc = "";
                for (int i = 0; i < node.updaters().size(); i++) {
                    inc += node.updaters().get(i);
                    if (node.updaters().size() - 1 != i)
                        inc += ", ";
                }

                _for = new DefaultMutableTreeNode(
                        "for (" + initial + "; " + node.getExpression() + "; " + inc + ")");
                parentNode.add(_for);
                System.out.println("for (" + initial + "; " + node.getExpression() + "; " + inc + ")");
                enclose(node.getBody().toString(), _for);
                return false;
            }

            @Override
            public boolean visit(IfStatement node) {
                String elseExist = "";
                _if = new DefaultMutableTreeNode("if (" + node.getExpression() + ")");
                System.out.println("if (+" + node.getExpression() + ")");
                parentNode.add(_if);
                enclose(node.getThenStatement().toString(), _if);
                elseExist = node.getElseStatement() + "";
                if (!(elseExist.equals("") || (elseExist.equals("null")))) {
                    _else = new DefaultMutableTreeNode("else");
                    System.out.println("else");
                    parentNode.add(_else);
                    enclose(node.getElseStatement().toString(), _else);
                }
                return false;
            }

            @Override
            public boolean visit(VariableDeclarationFragment node) {
                if (node.getParent() instanceof FieldDeclaration) {
                    FieldDeclaration declaration = ((FieldDeclaration) node.getParent());
                    _class.add(new DefaultMutableTreeNode(declaration.getType().toString()));
                } else {
                    System.out.println("VariableDeclarationFragment : " + node.toString());
                    parentNode.add(new DefaultMutableTreeNode(node.toString()));
                }
                return false; // do not continue to avoid usage info
            }

            @Override
            public boolean visit(ReturnStatement node) {
                parentNode.add(new DefaultMutableTreeNode(node.toString()));
                System.out.println("Return : " + node.toString());
                return false;
            }

            @Override
            public boolean visit(SuperConstructorInvocation node) {
                _constructorCall = new DefaultMutableTreeNode(node);
                parentNode.add(_constructorCall);
                System.out.println("SuperConstructorInvocation : " + node);
                return false;
            }

            @Override
            public boolean visit(MethodInvocation node) {
                _methodCall = new DefaultMutableTreeNode(node);
                parentNode.add(_methodCall);
                System.out.println("MethodInvocation : " + node);
                return true;
            }

            @Override
            public boolean visit(SuperMethodInvocation node) {
                _methodCall = new DefaultMutableTreeNode(node);
                parentNode.add(_methodCall);
                System.out.println("SuperMethodInvocation : " + node);
                return false;
            }

            @Override
            public boolean visit(WhileStatement node) {
                _while = new DefaultMutableTreeNode("while " + node.getExpression());
                parentNode.add(_while);
                System.out.println("WhileStatement : " + node.getExpression());
                enclose(node.getBody().toString(), _while);
                return false;
            }

            @Override
            public boolean visit(DoStatement node) {
                _do = new DefaultMutableTreeNode("do");
                parentNode.add(_do);
                System.out.println("do");
                enclose(node.getBody().toString(), _do);
                _while = new DefaultMutableTreeNode("while(" + node.getExpression() + ")");
                parentNode.add(_while);
                return false;
            }

            @Override
            public boolean visit(TryStatement node) {
                String ada = "";
                _try = new DefaultMutableTreeNode("try");
                parentNode.add(_try);
                System.out.println("try");
                enclose(node.getBody().toString(), _try);
                ada = node.getFinally() + "";
                if (!(ada.equals("") || (ada.equals("null")))) {
                    _final = new DefaultMutableTreeNode("finally");
                    parentNode.add(_final);
                    System.out.println("finally");
                    enclose(node.getFinally().toString(), _final);
                }
                return false;
            }

            @Override
            public boolean visit(CatchClause node) {
                _catch = new DefaultMutableTreeNode("catch (" + node.getException() + ")");
                parentNode.add(_catch);
                System.out.println("catch : " + node.getException());
                enclose(node.getBody().toString(), _catch);
                return false;
            }

            @Override
            public boolean visit(Assignment node) {
                _assignment = new DefaultMutableTreeNode(node.toString());
                parentNode.add(_assignment);
                System.out.println("Assignment : " + node.toString());
                return false;
            }

            @Override
            public boolean visit(ConstructorInvocation node) {
                _constructorCall = new DefaultMutableTreeNode(node.toString());
                parentNode.add(_constructorCall);
                System.out.println(node.toString());
                return false;
            }

            @Override
            public boolean visit(AnonymousClassDeclaration node) {
                _constructorCall = new DefaultMutableTreeNode(node.toString());
                parentNode.add(_constructorCall);
                System.out.println("AnonymousClassDeclaration : " + node.toString());
                return false;
            }

            @Override
            public boolean visit(ArrayAccess node) {
                _class = new DefaultMutableTreeNode(node.toString());
                parentNode.add(_class);
                System.out.println("AbstrackTypeDeclaration : " + node.toString());
                return false;
            }

            @Override
            public boolean visit(ArrayCreation node) {
                _array = new DefaultMutableTreeNode(node.toString());
                _method.add(_array);
                System.out.println("ArrayCreation : " + node.toString());
                return false;
            }

            @Override
            public boolean visit(ArrayInitializer node) {
                _array = new DefaultMutableTreeNode(node.toString());
                System.out.println("ArrayInitialize : " + node.toString());
                parentNode.add(_array);
                return false;
            }

            @Override
            public boolean visit(AssertStatement node) {
                _statement = new DefaultMutableTreeNode(node.toString());
                System.out.println("AssertStatement : " + node.toString());
                parentNode.add(_statement);
                return false;
            }

            @Override
            public boolean visit(ContinueStatement node) {
                _statement = new DefaultMutableTreeNode(node.toString());
                System.out.println("ContinueStatement : " + node.toString());
                parentNode.add(_statement);
                return false;
            }

            @Override
            public boolean visit(SwitchStatement node) {
                _switch = new DefaultMutableTreeNode("switch (" + node.getExpression() + ")");
                System.out.println("switch (" + node.getExpression() + ")");
                parentNode.add(_switch);
                List getStatement = node.statements();
                for (Object st : getStatement) {
                    Matcher _caseMatch = Pattern.compile("^case\\s+.+\\:").matcher(st.toString());
                    if (_caseMatch.find()) {
                        _case = new DefaultMutableTreeNode(_caseMatch.group());
                        _switch.add(_case);
                    }

                    enclose(st.toString(), _case);

                    Matcher _breakMatch = Pattern.compile("^break\\s*.*;").matcher(st.toString());
                    if (_breakMatch.find()) {
                        _break = new DefaultMutableTreeNode(_breakMatch.group());
                        _case.add(_break);
                    }
                }
                return false;
            }

            @Override
            public boolean visit(ClassInstanceCreation node) {
                _constructorCall = new DefaultMutableTreeNode(node.toString());
                System.out.println("ClassInstanceCreation : " + node.toString());
                parentNode.add(_constructorCall);
                return false;
            }
        });
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.reverse.ReversePackage_JavaTypes.java

License:Open Source License

/**
 * @throws CodeSyncException //from ww w  .  java2s .  c  o m
 * @flowerModelElementId _IFwlserfEd6QaI9daHlzjA
 */
@SuppressWarnings("unchecked")
@Override
protected ReverseStatus reverseElement(Type modelElement, FileAndAST<CompilationUnit> astElement)
        throws CodeSyncException {
    ReverseStatus status = new ReverseStatus();
    TypeDeclaration typeDeclaration = JavaSyncUtils.getMasterClass(astElement.getAstElement());

    getFullyQualifiedImports().clear();
    for (ImportDeclaration id : (List<ImportDeclaration>) astElement.getAstElement().imports()) {
        Name importedName = id.getName();
        SimpleName name;
        if (importedName.isQualifiedName()) {
            name = ((QualifiedName) importedName).getName();
        } else {
            name = (SimpleName) importedName;
        }
        getFullyQualifiedImports().put(name.toString(), importedName.getFullyQualifiedName());
    }

    if (typeDeclaration.isInterface()) {
        reverseJavaInterface.currentElement = modelElement;
        status.applyOr(reverseJavaInterface.reverse((Interface) modelElement, astElement.getAstElement()));
        reverseJavaInterface.currentElement = null;
    } else {
        reverseJavaClass.currentElement = modelElement;
        status.applyOr(reverseJavaClass.reverse((org.eclipse.uml2.uml.Class) modelElement,
                astElement.getAstElement()));
        reverseJavaClass.currentElement = null;
    }

    updateSynchronizationTimeStamp(modelElement, astElement);
    return status;
}

From source file:com.flamefire.importsmalinames.astutils.RenameVariablesVisitor.java

License:Open Source License

@Override
public boolean visit(SimpleName node) {
    // We have to be inside a method
    if (curMethod == null)
        return false;
    // Only replace variables
    IBinding binding = node.resolveBinding();
    if (binding == null) {
        if ((node.getParent() instanceof LabeledStatement)
                && ((LabeledStatement) node.getParent()).getLabel().equals(node))
            return false;
        if ((node.getParent() instanceof BreakStatement)
                && ((BreakStatement) node.getParent()).getLabel().equals(node))
            return false;
        if (node.getParent() instanceof QualifiedName)
            return false;
        // This may happen
        System.err.println("Detected SimpleName without binding: " + node + "; Parent:" + node.getParent()
                + "\nThis may happen if there are compile errors");
        // return false;
    } else if (binding.getKind() != IBinding.VARIABLE)
        return false;
    // Check if we need to add a "this"
    // Do this if current node is a field and we may replace a variable with
    // its name//from   w  w w  .  j  a  va 2 s  . co  m
    AST ast = node.getAST();
    IVariableBinding vBinding = (IVariableBinding) binding;
    // Check for field acceses
    if (vBinding != null && vBinding.isField()) {
        // Add this if necessary
        if (renaming.containsValue(node.toString()) && !(node.getParent() instanceof FieldAccess)
                && !(node.getParent() instanceof QualifiedName)) {
            FieldAccess fa = ast.newFieldAccess();
            fa.setExpression(ast.newThisExpression());
            fa.setName(ast.newSimpleName(node.toString()));
            astRewrite.replace(node, fa, null);
        }
        return false;
    }
    String newName = renaming.get(node.toString());
    if (newName == null || newName == "")
        return false;
    astRewrite.replace(node, ast.newSimpleName(newName), null);
    return false;
}

From source file:com.kodebeagle.javaparser.MethodInvocationResolver.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override//from w  w  w .j  a v  a2 s .  c om
public boolean visit(MethodInvocation node) {
    SimpleName methodName = node.getName();

    List args = node.arguments();
    Expression expression = node.getExpression();
    Map<String, Integer> scopeBindings = getNodeScopes().get(node);
    String target = getTarget(expression);

    String targetType = translateTargetToType(target, scopeBindings);
    // Add only if you could guess the type of target, else ignore.
    // TODO: In case of a method in super type, this will still infer it as in "this".
    if (!targetType.isEmpty()) {
        List<String> argTypes = translateArgsToTypes(args, scopeBindings);
        if (!methodStack.empty()) {
            MethodDeclaration currentMethod = methodStack.peek();
            MethodDecl methodDecl = getMethodDecl(currentMethod);
            List<MethodInvokRef> invoks = methodInvoks.get(methodDecl);
            if (invoks == null) {
                invoks = new ArrayList<>();
                methodInvoks.put(methodDecl, invoks);
            }
            MethodInvokRef methodInvokRef = new MethodInvokRef(methodName.toString(), targetType, target,
                    args.size(), node.getName().getStartPosition(), argTypes, methodName.getLength(), false,
                    getReturnType(node));
            invoks.add(methodInvokRef);
        }
    }
    return true;
}

From source file:com.kodebeagle.javaparser.MethodInvocationResolver.java

License:Apache License

private MethodDecl getMethodDecl(MethodDeclaration node) {
    String qualifiedTypeName = currentPackage + "." + Joiner.on(".").skipNulls().join(typesInFile);
    SimpleName nameNode = node.getName();
    String methodName = nameNode.toString();
    String returnType = "";
    if (node.getReturnType2() != null) {
        returnType = getNameOfType(node.getReturnType2());
    }/*from  w  w  w .  j  a v a2  s.  co m*/

    Map<String, String> params = new HashMap<>();
    for (Object p : node.parameters()) {
        String typeName = OBJECT_TYPE;
        if (p instanceof SingleVariableDeclaration) {

            SingleVariableDeclaration svd = (SingleVariableDeclaration) p;
            String varName = svd.getName().toString();
            Type type = svd.getType();
            typeName = getNameOfType(type);

            params.put(varName, typeName);
        } else {
            System.err.println("Unxepected AST node type for param - " + p);
        }

    }
    return new MethodDecl(methodName, qualifiedTypeName, returnType, nameNode.getStartPosition(), params);
}

From source file:lang.java.jdt.internal.FullyQualifyTypeNames.java

License:Open Source License

@Override
public boolean visit(SimpleType node) {
    ITypeBinding tb = node.resolveBinding();
    if (tb != null) {
        IPackageBinding pb = tb.getPackage();
        if (pb != null && !pb.isUnnamed()) {
            String qualifiedTypeName = "";
            if (tb.isNested()) {
                ITypeBinding parent = tb.getDeclaringClass();
                String parentString = parent.getName();
                while (parent != null && parent.isNested()) {
                    parent = parent.getDeclaringClass();
                    parentString = parent.getName() + "." + parentString;
                }/*from ww  w . ja v a  2  s  . c o m*/
                qualifiedTypeName = pb.getName() + "." + parentString + ".";
            } else {
                qualifiedTypeName = pb.getName() + ".";
            }
            Name stName = node.getName();
            if (stName.isQualifiedName()) {
                QualifiedName qn = (QualifiedName) stName;
                qualifiedTypeName = qualifiedTypeName + qn.getName().toString();
            } else {
                SimpleName sn = (SimpleName) stName;
                qualifiedTypeName = qualifiedTypeName + sn.toString();
            }
            SimpleType st = node.getAST().newSimpleType(node.getAST().newName(qualifiedTypeName));
            rewriter.replace(node, st, null);
        }
    }
    return true;
}

From source file:lang.java.jdt.internal.FullyQualifyTypeNames.java

License:Open Source License

@Override
public boolean visit(FieldAccess node) {
    Expression exp = node.getExpression();
    if (exp instanceof SimpleName) {
        SimpleName sn = (SimpleName) exp;
        ITypeBinding tb = sn.resolveTypeBinding();
        if (tb != null && (tb.isClass() || tb.isInterface())) {
            IPackageBinding pb = tb.getPackage();
            if (pb != null && !pb.isUnnamed()) {
                String qualifiedTypeName = "";
                if (tb.isNested()) {
                    ITypeBinding parent = tb.getDeclaringClass();
                    String parentString = parent.getName();
                    while (parent != null && parent.isNested()) {
                        parent = parent.getDeclaringClass();
                        parentString = parent.getName() + "." + parentString;
                    }/*from  www  .  j  av a 2 s .co  m*/
                    qualifiedTypeName = pb.getName() + "." + parentString + ".";
                } else {
                    qualifiedTypeName = pb.getName() + ".";
                }
                qualifiedTypeName = qualifiedTypeName + sn.toString();
                Name n = node.getAST().newName(qualifiedTypeName);
                rewriter.replace(exp, n, null);
            }
        }
    }
    return true;
}

From source file:lang.java.jdt.internal.FullyQualifyTypeNames.java

License:Open Source License

@Override
public boolean visit(MethodInvocation node) {
    Expression exp = node.getExpression();
    if (exp instanceof SimpleName) {
        SimpleName sn = (SimpleName) exp;
        IBinding b = sn.resolveBinding();
        if (b.getKind() == IBinding.TYPE) {
            ITypeBinding tb = sn.resolveTypeBinding();
            if (tb != null && (tb.isClass() || tb.isInterface())) {
                IPackageBinding pb = tb.getPackage();
                if (pb != null && !pb.isUnnamed()) {
                    String qualifiedTypeName = "";
                    if (tb.isNested()) {
                        ITypeBinding parent = tb.getDeclaringClass();
                        String parentString = parent.getName();
                        while (parent != null && parent.isNested()) {
                            parent = parent.getDeclaringClass();
                            parentString = parent.getName() + "." + parentString;
                        }//from w  ww.j  ava 2  s  .c  o  m
                        qualifiedTypeName = pb.getName() + "." + parentString + ".";
                    } else {
                        qualifiedTypeName = pb.getName() + ".";
                    }
                    qualifiedTypeName = qualifiedTypeName + sn.toString();
                    Name n = node.getAST().newName(qualifiedTypeName);
                    rewriter.replace(exp, n, null);
                }
            }
        }
    }
    return true;
}

From source file:logic.Translator.java

License:Open Source License

/** This method translates the node passed as parameter to use
 * the variable object of the method passed as parameter or of the root.
 * @param node the node to translate./* ww  w .j  a  va2 s.c om*/
 * @param method the method.
 */
private String translateVars(ASTNode node, MethodDeclaration method) {
    //Metodo che permette di tradurre il nodo passato come parametro
    //in modo da usare l'oggetto variabili necessario
    //(ad esempio: l'istruzione "i = x + y;" deve essere tradotta in
    //"OGG_VAR.i = OGG_VAR.x + OGG_VAR.y", dove "OGG_VAR" rappresenta
    //l'oggetto variabili da utilizzare).
    //Il parametro "MethodDeclaration" indica che bisogna usare l'oggetto
    //variabili di questo metodo o quello della root (non quello di qualche
    //altro metodo).

    //troviamo tutti i "SimpleName" del nodo passato come parametro
    ArrayList<SimpleName> simpleNamesList = null;
    if (node instanceof SimpleName) {
        simpleNamesList = new ArrayList<SimpleName>();
        simpleNamesList.add((SimpleName) node);
    } else {
        //utilizziamo l'apposito visitor per trovare tutti i "SimpleName"
        //del nodo passato come parametro e dei suoi sotto-nodi
        SimpleNameVisitor visitor = new SimpleNameVisitor();
        node.accept(visitor);
        simpleNamesList = visitor.getSimpleNamesList();
    }

    //ricaviamo l'istruzione da tradurre
    String istruzione = "";
    if (node instanceof VariableDeclarationStatement) {
        //se il nodo passato come parametro rappresenta la dichiarazione
        //di una variabile, dobbiamo eliminare il tipo della variabile a
        //sinistra dell'istruzione; ad esempio, se abbiamo questa istruzione:
        // int x = y + z;
        //eliminiamo "int" dalla parte sinistra e l'istruzione diventa:
        // OGG_VAR.x = OGG_VAR.y + OGG_VAR.z;
        VariableDeclarationStatement vd = (VariableDeclarationStatement) node;
        for (int i = 0; i < vd.fragments().size(); i++) {
            if (vd.fragments().get(i) instanceof VariableDeclarationFragment) {
                VariableDeclarationFragment v = (VariableDeclarationFragment) vd.fragments().get(i);
                if (v.getInitializer() != null) {
                    //le dichiarazioni di variabili senza assegnazione di valore
                    //(cio, quelle che hanno "getInitializer() = null", come ad
                    //esempio: "int x;") non vanno tradotte; traduciamo solo
                    //quelle che assegnano un valore alle variabili (es.: "int x = 1;")
                    istruzione += v.toString() + ";";
                }
            }
        }
    } else {
        istruzione = node.toString(); //contiene l'istruzione rappresentata dal nodo passato come parametro
    }

    if (istruzione.equals("") == false) {
        //prima di manipolare la stringa che rappresenta l'istruzione,
        //sostituiamo il testo tra virgolette (che non deve essere
        //modificato) con il carattere speciale "@"; poi, al termine
        //delle modifiche, ogni carattere speciale "@" verr sostituito
        //con il testo tra virgolette originale
        ArrayList<String> stringheTraVirgolette = new ArrayList<String>();
        ArrayList<Integer> indiciVirgolette = new ArrayList<Integer>();

        for (int i = 0; i < istruzione.length(); i++) {
            char carattereCorr = istruzione.charAt(i);
            if (((i == 0) && (carattereCorr == '\"'))
                    || ((i > 0) && (carattereCorr == '\"') && (istruzione.charAt(i - 1) != '\\'))) {
                //se abbiamo trovato il carattere " e questo carattere
                //non  preceduto dal carattere \ (per ignorare la rappresentazione
                //di una virgoletta all'interno di un testo tra virgolette),
                //memorizziamo l'indice attuale
                indiciVirgolette.add(i);
            }
        }

        //memorizziamo il testo tra virgolette
        int k = 0;
        while (k < (indiciVirgolette.size() - 1)) {
            String sottostringa = istruzione.substring(indiciVirgolette.get(k),
                    indiciVirgolette.get(k + 1) + 1);
            stringheTraVirgolette.add(sottostringa);
            k = k + 2;
        }

        //sostituiamo il testo tra virgolette con il carattere
        //speciale "@" seguito da un numero che permette di identificare
        //successivamente quale sottostringa  stata sostituita
        for (int i = 0; i < stringheTraVirgolette.size(); i++) {
            istruzione = istruzione.replace(stringheTraVirgolette.get(i), "@" + i);
        }

        //separiamo con il carattere speciale "#" i vari componenti dell'istruzione
        //per effettuare successivamente in maniera corretta la sostituzione
        //dei nomi delle variabili (ogni nome di variabile  preceduto e seguito
        //dal carattere speciale "#" o da uno spazio vuoto)
        istruzione = "#" + istruzione + "#";
        istruzione = istruzione.replace("+", "#+#");
        istruzione = istruzione.replace("-", "#-#");
        istruzione = istruzione.replace("~", "#~#");
        istruzione = istruzione.replace("!", "#!#");
        istruzione = istruzione.replace("*", "#*#");
        istruzione = istruzione.replace("/", "#/#");
        istruzione = istruzione.replace("%", "#%#");
        istruzione = istruzione.replace("<", "#<#");
        istruzione = istruzione.replace(">", "#>#");
        istruzione = istruzione.replace("=", "#=#");
        istruzione = istruzione.replace("&", "#&#");
        istruzione = istruzione.replace("^", "#^#");
        istruzione = istruzione.replace("|", "#|#");
        istruzione = istruzione.replace("?", "#?#");
        istruzione = istruzione.replace(":", "#:#");
        istruzione = istruzione.replace("(", "#(#");
        istruzione = istruzione.replace(")", "#)#");
        istruzione = istruzione.replace("[", "#[#");
        istruzione = istruzione.replace("]", "#]#");
        istruzione = istruzione.replace("{", "#{#");
        istruzione = istruzione.replace("}", "#}#");
        istruzione = istruzione.replace(",", "#,#");
        istruzione = istruzione.replace(".", "#.#");
        istruzione = istruzione.replace(";", "#;#");

        //per ogni "SimpleName" trovato, vediamo quale variabile rappresenta
        //e scegliamo di conseguenza l'oggetto variabili da utilizzare.
        //NOTA: per l'oggetto variabili della root utilizziamo il nome "varRoot",
        //mentre per gli oggetti variabili degli stati composti utilizziamo il
        //formato "varXxx", dove "xxx"  il nome del metodo
        for (int i = 0; i < simpleNamesList.size(); i++) {
            SimpleName sn = simpleNamesList.get(i);

            //cerchiamo la variabile con il nome corrente
            //e riceviamo l'oggetto variabili da utilizzare
            String oggVar = Util.findVar(sn, method, this.unit);

            if (oggVar != null) {
                //se "oggVar"  diverso da NULL, significa che la
                //variabile  stata trovata, quindi anteponiamo il
                //nome dell'oggetto variabili al nome della variabile
                //all'interno dell'istruzione
                istruzione = istruzione.replace("#" + sn.toString() + "#",
                        "#" + oggVar + "." + sn.toString() + "#");
                istruzione = istruzione.replace("#" + sn.toString() + " ",
                        "#" + oggVar + "." + sn.toString() + " ");
                istruzione = istruzione.replace(" " + sn.toString() + "#",
                        " " + oggVar + "." + sn.toString() + "#");
                istruzione = istruzione.replace(" " + sn.toString() + " ",
                        " " + oggVar + "." + sn.toString() + " ");
            }
        }

        //eliminiamo i caratteri speciali "#"
        istruzione = istruzione.replace("#", "");

        //eliminiamo i caratteri speciali "@", sostituendo ad
        //ogni carattere "@" il testo tra virgolette originale
        for (int i = 0; i < stringheTraVirgolette.size(); i++) {
            istruzione = istruzione.replace("@" + i, stringheTraVirgolette.get(i));
        }
    }

    return istruzione;
}

From source file:logic.Util.java

License:Open Source License

/** This method searches the variable name passed as parameter in the method
 * passed as parameter or in the root.//from   w w w  .j a v a2s . c  om
 * @param name the name of the searched variable.
 * @param method the method.
 * @param unit the CompilationUnit.
 * @return a string that represents the variable object to use or null.
 */
public static String findVar(SimpleName name, MethodDeclaration method, CompilationUnit unit) {
    //trova la variabile che ha un nome uguale a quello passato come parametro
    //e restituisce l'oggetto variabili da utilizzare (quello del metodo passato
    //come parametro o quello della root)

    //cerchiamo la variabile nel metodo passato come parametro:

    //cerchiamo nei parametri del metodo corrente
    for (int j = 0; j < method.parameters().size(); j++) {
        if (method.parameters().get(j) instanceof SingleVariableDeclaration) {
            SingleVariableDeclaration par = (SingleVariableDeclaration) method.parameters().get(j);
            if ((par.getName().toString()).equals(name.toString())) {
                return "var" + Util.firstToUpper(method.getName().toString()); //restituiamo l'oggetto variabili del metodo corrente (nel formato "varXxx", dove "xxx"  il nome del metodo)
            }
        }
    }

    //cerchiamo nelle variabili contenute nel corpo del metodo corrente
    Block body = method.getBody();
    for (int j = 0; j < body.statements().size(); j++) {
        if (body.statements().get(j) instanceof VariableDeclarationStatement) {
            VariableDeclarationStatement vd = (VariableDeclarationStatement) body.statements().get(j);
            for (int z = 0; z < vd.fragments().size(); z++) {
                if (vd.fragments().get(z) instanceof VariableDeclarationFragment) {
                    VariableDeclarationFragment v = (VariableDeclarationFragment) vd.fragments().get(z);
                    if ((v.getName().toString()).equals(name.toString())) {
                        return "var" + Util.firstToUpper(method.getName().toString()); //restituiamo l'oggetto variabili del metodo corrente (nel formato "varXxx", dove "xxx"  il nome del metodo)
                    }
                }
            }
        }
    }

    //cerchiamo la variabile nella root:
    List classComponents = ((TypeDeclaration) unit.types().get(0)).bodyDeclarations();
    for (int i = 0; i < classComponents.size(); i++) {
        if (classComponents.get(i) instanceof FieldDeclaration) {
            FieldDeclaration fd = (FieldDeclaration) classComponents.get(i);
            for (int j = 0; j < fd.fragments().size(); j++) {
                if (fd.fragments().get(j) instanceof VariableDeclarationFragment) {
                    VariableDeclarationFragment v = (VariableDeclarationFragment) fd.fragments().get(j);
                    if ((v.getName().toString()).equals(name.toString())) {
                        return "varRoot"; //restituiamo l'oggetto variabili della root
                    }
                }
            }
        }
    }

    //se non abbiamo trovato la variabile, restituiamo NULL
    return null;
}