Example usage for org.eclipse.jdt.core IType createField

List of usage examples for org.eclipse.jdt.core IType createField

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IType createField.

Prototype

IField createField(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor)
        throws JavaModelException;

Source Link

Document

Creates and returns a field in this type with the given contents.

Usage

From source file:at.bestsolution.efxclipse.tooling.fxgraph.ui.quickfix.FXGraphQuickfixProvider.java

License:Open Source License

@Fix(FXGraphJavaValidator.UNKNOWN_CONTROLLER_FIELD)
public void fixAddControllerField(final Issue issue, IssueResolutionAcceptor acceptor) {
    acceptor.accept(issue, "Add controller field",
            "Add a field of '" + issue.getData()[0] + "' to the controller '" + issue.getData()[1] + "'", null,
            new IModification() {

                @Override//  ww w.  j  av a2 s. co m
                public void apply(IModificationContext context) throws Exception {
                    IJavaProject p = context.getXtextDocument()
                            .readOnly(new IUnitOfWork<IJavaProject, XtextResource>() {

                                @Override
                                public IJavaProject exec(XtextResource state) throws Exception {
                                    return provider.getJavaProject(state.getResourceSet());
                                }

                            });

                    IType type = p.findType(issue.getData()[1]);

                    String[][] resolvedType = type.resolveType("FXML");

                    if (resolvedType == null) {
                        type.getCompilationUnit().createImport("javafx.fxml.FXML", null,
                                new NullProgressMonitor());
                    }

                    resolvedType = type.resolveType(Signature.getSimpleName(issue.getData()[2]));

                    if (resolvedType == null) {
                        type.getCompilationUnit().createImport(issue.getData()[2], null,
                                new NullProgressMonitor());
                    }

                    type.createField("@FXML " + Signature.getSimpleName(issue.getData()[2]) + " "
                            + issue.getData()[0] + ";", null, true, new NullProgressMonitor());
                }
            });
    acceptor.accept(issue, "Remove id field", "Remove the id field from the element", null,
            new IModification() {

                @Override
                public void apply(IModificationContext context) throws Exception {
                    IXtextDocument xtextDocument = context.getXtextDocument();
                    StringBuilder b = new StringBuilder();
                    int start = issue.getOffset();
                    while (!b.toString().startsWith("id")) {
                        b.insert(0, xtextDocument.getChar(--start));
                    }

                    xtextDocument.replace(start, (b + issue.getData()[0]).length(), "");
                }
            });
}

From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java

License:Apache License

public static void merge(IType type, String authority, String dbName, List<String> tableCreators,
        List<String> tables) throws Exception {
    type.createField("public static final String AUTH=\"" + authority + "\";", null, true, null);
    type.createField("public static final Uri URI=Uri.parse(\"content://\" + AUTH);", null, true, null);

    type.createField("private SQLiteOpenHelper mOpenHelper;", null, true, null);

    type.createField("private static Session session;", null, true, null);

    type.createMethod("public static Session getSession(){" + "return session;" + "}", null, true, null);
    IMethod onCreate = type.getMethod("onCreate", null);
    // String doc = onCreate.getAttachedJavadoc(null);
    StringBuilder sb = new StringBuilder(onCreate.getSource());
    int start = sb.indexOf("{") + 1;
    int end = sb.indexOf("}");
    sb.delete(start, end);/*from www  .j av a2s .  co m*/

    StringBuilder sb2 = new StringBuilder();
    sb2.append("mOpenHelper=new SQLiteOpenHelper(this.getContext(),\"");
    sb2.append(dbName);
    sb2.append("\",null,1){");
    sb2.append("public void onCreate(SQLiteDatabase db){");
    //        sb2.append(" String sql=\"\";");
    //        for (String creator : tableCreators) {
    //            String[] lines = creator.split(SourceAnalysis.LF);
    //            for (int i = 0; i < lines.length; i++) {
    //                if (i == 0) {
    //                    sb2.append("sql=\"");
    //                } else {
    //                    sb2.append("sql+=\"");
    //                }
    //                sb2.append(lines[i]);
    //                sb2.append("\";");
    //            }
    //            sb2.append("db.execSQL(sql);");
    //        }
    for (String table : tables) {
        sb2.append(table);
    }
    sb2.append("}");
    sb2.append("public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){");
    sb2.append("");
    sb2.append("}};");
    sb2.append("session = new Session(mOpenHelper, getContext().getContentResolver());");
    sb2.append("return true;");
    sb.insert(start, sb2);

    onCreate.delete(true, null);
    type.createMethod(sb.toString(), null, true, null);

}

From source file:cn.ieclipse.adt.ext.wizards.NewProviderWizardPage.java

License:Apache License

@Override
protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor)
        throws CoreException {
    super.createTypeMembers(newType, imports, monitor);

    try {//  w w  w. java  2  s. c o  m
        // imports.addImport("android.database.sqlite.SQLiteDatabase");
        imports.addImport("android.database.sqlite.SQLiteOpenHelper");
        // imports.addImport("android.content.UriMatcher");
        // imports.addImport("android.content.ContentValues");
        newType.createField("public static final String AUTH=\"" + authority + "\";", null, true, null);
        newType.createField("public static final Uri URI=Uri.parse(\"content://\" + AUTH);", null, true, null);

        newType.createField("private SQLiteOpenHelper mOpenHelper;", null, true, null);
    } catch (Exception e) {
        e.printStackTrace();
        Status status = new Status();
        status.setError("error in generate code : " + e.getMessage());
        throw new CoreException(status);
    }
}

From source file:cn.ieclipse.aorm.eclipse.jdt.SourceGenerator.java

License:Apache License

public static void merge(IType type, String authority, String dbName, List<String> tableCreators)
        throws Exception {
    type.createField("public static final String AUTH=\"" + authority + "\";", null, true, null);
    type.createField("public static final Uri URI=Uri.parse(\"content://\" + AUTH);", null, true, null);

    type.createField("private SQLiteOpenHelper mOpenHelper;", null, true, null);

    type.createField("private static Session session;", null, true, null);

    type.createMethod("public static Session getSession(){" + "return session;" + "}", null, true, null);
    IMethod onCreate = type.getMethod("onCreate", null);
    // String doc = onCreate.getAttachedJavadoc(null);
    StringBuilder sb = new StringBuilder(onCreate.getSource());
    int start = sb.indexOf("{") + 1;
    int end = sb.indexOf("}");
    sb.delete(start, end);/*from  w ww  .j ava 2s.com*/

    StringBuilder sb2 = new StringBuilder();
    sb2.append("mOpenHelper=new SQLiteOpenHelper(this.getContext(),\"");
    sb2.append(dbName);
    sb2.append("\",null,1){");
    sb2.append("public void onCreate(SQLiteDatabase db){");
    sb2.append(" String sql=\"\";");
    for (String creator : tableCreators) {
        String[] lines = creator.split(SourceAnalysis.LF);
        for (int i = 0; i < lines.length; i++) {
            if (i == 0) {
                sb2.append("sql=\"");
            } else {
                sb2.append("sql+=\"");
            }
            sb2.append(lines[i]);
            sb2.append("\";");
        }
        sb2.append("db.execSQL(sql);");
    }
    sb2.append("}");
    sb2.append("public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){");
    sb2.append("");
    sb2.append("}};");
    sb2.append("session = new Session(mOpenHelper, getContext().getContentResolver());");
    sb2.append("return true;");
    sb.insert(start, sb2);

    onCreate.delete(true, null);
    type.createMethod(sb.toString(), null, true, null);

}

From source file:com.google.gwt.eclipse.core.uibinder.resources.HtmlBasedUiBinderResourceCreator.java

License:Open Source License

@Override
public void createOwnerClassMembers(IType ownerClass, ImportsManager imports, boolean addComments,
        boolean addSampleContent, IProgressMonitor monitor) throws JavaModelException {
    String uiBinderDecl = createUiBinderSubtype(ownerClass, "com.google.gwt.dom.client.Element", imports);
    ownerClass.createType(uiBinderDecl, null, false, monitor);

    String uiBinderField = createUiBinderStaticField(ownerClass, imports);
    ownerClass.createField(uiBinderField, null, false, monitor);

    String ctorSrc = createCtor(ownerClass, addSampleContent, addComments);
    IMethod ctor = ownerClass.createMethod(ctorSrc, null, false, monitor);

    if (addSampleContent) {
        String uiField = createUiField("com.google.gwt.dom.client.SpanElement", "nameSpan", imports);
        ownerClass.createField(uiField, ctor, false, monitor);
    }//from  w w w .ja va  2s.c o  m
}

From source file:com.google.gwt.eclipse.core.uibinder.resources.WidgetBasedUiBinderResourceCreator.java

License:Open Source License

@Override
public void createOwnerClassMembers(IType ownerClass, ImportsManager imports, boolean addComments,
        boolean addSampleContent, IProgressMonitor monitor) throws JavaModelException {
    String uiBinderDecl = createUiBinderSubtype(ownerClass, "com.google.gwt.user.client.ui.Widget", imports);
    ownerClass.createType(uiBinderDecl, null, false, monitor);

    String uiBinderField = createUiBinderStaticField(ownerClass, imports);
    ownerClass.createField(uiBinderField, null, false, monitor);

    String defaultCtorSrc = createDefaultCtor(ownerClass, addComments);
    ownerClass.createMethod(defaultCtorSrc, null, false, monitor);

    if (addSampleContent) {
        String ctorSrc = createCtor(ownerClass, addSampleContent, addComments);
        IMethod ctor = ownerClass.createMethod(ctorSrc, null, false, monitor);

        String uiField = createUiField("com.google.gwt.user.client.ui.Button", "button", imports);
        ownerClass.createField(uiField, ctor, false, monitor);

        String eventHandler = createEventHandler(imports);
        ownerClass.createMethod(eventHandler, null, false, monitor);

        String getterSrc = createGetter(ownerClass);
        ownerClass.createMethod(getterSrc, null, false, monitor);

        String setterSrc = createSetter(ownerClass, addComments);
        ownerClass.createMethod(setterSrc, null, false, monitor);
    }//from w w  w.  ja  v  a 2  s . c  om
}

From source file:com.sun.codemodel.ClassGenerator.java

License:Apache License

private ICompilationUnit addClass(ElementClass ec, ICompilationUnit of, IProgressMonitor pm)
        throws JavaModelException {
    JDefinedClass c = ec.getjDefClass();
    IImportDeclaration imp = of.getImport("javax.xml.namespace.QName");
    if (imp == null || (!imp.exists())) {
        of.createImport("javax.xml.namespace.QName", null, Flags.AccDefault, pm);
    }//from w w w  . j av  a 2  s  . c o m
    imp = of.getImport("javax.xml.bind.annotation.XmlElementDecl");
    if (imp == null || (!imp.exists())) {
        of.createImport("javax.xml.bind.annotation.XmlElementDecl", null, Flags.AccDefault, pm);
    }
    imp = of.getImport("javax.xml.bind.JAXBElement");
    if (imp == null || (!imp.exists())) {
        of.createImport("javax.xml.bind.JAXBElement", null, Flags.AccDefault, pm);
    }
    IType t = of.getType("ObjectFactory");
    if (t != null && t.exists()) {
        String lineDelimiter = StubUtility.getLineDelimiterUsed(project);
        t.createField("private final static QName _" + c.name() + "_QNAME= new QName(\""
                + ec.getElementType().getNamespaceURI() + "\", \"" + ec.getElementType().getLocalPart() + "\");"
                + lineDelimiter, null, false, pm);

        t.createMethod(generateFirstMethod(c, lineDelimiter), null, false, pm);
        t.createMethod(generateSecondMethod(ec, lineDelimiter), null, false, pm);
    } else
        throw new JavaModelException(
                new Exception("Error ObjectFactory class does not exists in compilation unit"),
                JavaModelStatus.ERROR);

    return of;
}

From source file:in.cypal.studio.gwt.ui.wizards.NewGwtRemoteServiceWizardPage.java

License:Apache License

protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor)
        throws CoreException {

    imports.addImport("com.google.gwt.core.client.GWT");
    imports.addImport("com.google.gwt.user.client.rpc.ServiceDefTarget");
    newType.createField("public static final String SERVICE_URI = \"" + serviceUri + "\";", null, true, //$NON-NLS-1$//$NON-NLS-2$
            monitor);/*  www  .j  a v  a 2  s  .c  o m*/
    newType.createType(getUtilClassContents(), null, true, monitor);
    super.createTypeMembers(newType, imports, monitor);
}

From source file:org.bonitasoft.studio.common.repository.ClassGenerator.java

License:Open Source License

private static void createAbstractClassContent(IType classType, ConnectorDefinition definition,
        String className, IProgressMonitor monitor) throws Exception {

    for (Input input : definition.getInput()) {
        String fieldName = NamingUtils.toJavaIdentifier(input.getName().toUpperCase(), true)
                + "_INPUT_PARAMETER";
        IField field = classType.getField(fieldName);

        /*check a field with this name not already exist*/
        if (field != null && field.exists()) {
            field.delete(true, monitor);
        }//from   w  ww . j  a va2 s .  c  o m

        String fieldDefinition = "protected final static String " + fieldName + " = \"" + input.getName()
                + "\" ;";
        classType.createField(fieldDefinition, null, true, null);

        final String getterName = "get" + NamingUtils.toJavaIdentifier(input.getName(), true);
        IMethod getterMethod = classType.getMethod(getterName, null);
        if (getterMethod != null && getterMethod.exists()) { //Regenerate method
            getterMethod.delete(true, monitor);
        }

        classType.createMethod(
                "protected final " + input.getType() + " " + getterName + "() {\n" + "\t return ("
                        + input.getType() + ") getInputParameter(" + fieldName + ");\n" + "}",
                null, true, null);

    }

    for (Output output : definition.getOutput()) {
        String fieldName = NamingUtils.toJavaIdentifier(output.getName().toUpperCase(), true)
                + "_OUTPUT_PARAMETER";
        IField field = classType.getField(fieldName);

        /*check a field with this name not already exist*/
        if (field != null && field.exists()) {
            field.delete(true, monitor);
        }

        String fieldDefinition = "protected final String " + fieldName + " = \"" + output.getName() + "\" ;";
        classType.createField(fieldDefinition, null, true, null);

        final String setterName = "set" + NamingUtils.toJavaIdentifier(output.getName(), true);

        String inputName = NamingUtils.toJavaIdentifier(output.getName(), false);
        classType.createMethod(
                "protected final void " + setterName + "(" + output.getType() + " " + inputName + ") {\n"
                        + "\t setOutputParameter(" + fieldName + " , " + inputName + " );\n" + "}\n",
                null, true, null);
    }

    IMethod validateMethod = classType.getMethod("validateInputParameters", null);
    if (validateMethod != null && validateMethod.exists()) {
        validateMethod.delete(true, monitor);
    }

    StringBuilder validateMethodContent = new StringBuilder(
            "@Override\npublic void validateInputParameters() throws ConnectorValidationException{\n\t");

    for (Input input : definition.getInput()) {
        String getterName = "get" + NamingUtils.toJavaIdentifier(input.getName(), true);
        validateMethodContent.append("try{ \n\t" + getterName + "();\n"
                + " }catch (ClassCastException cce) {\n\t" + " throw new ConnectorValidationException(\""
                + input.getName() + " type is invalid\") ;\n\t" + "  }\n");

    }

    validateMethodContent.append("\n\t}");
    classType.createMethod(validateMethodContent.toString(), null, true, null);
    classType.getCompilationUnit().createImport(CONNECTOR_VALIDATION_EXCEPTION_QUALIFIED_NAME, null, monitor);

}

From source file:org.datanucleus.ide.eclipse.wizard.createappid.JDOApplicationIdWizardMainPage.java

License:Open Source License

protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor)
        throws CoreException {
    List selectedFields = getSelectedFields();
    String TYPE_STRING = "java.lang.String";
    imports.addImport(TYPE_STRING);//  ww  w  . j  a va 2s . c  o m
    for (int i = 0; i < selectedFields.size(); i++) {
        IField field = ((IField) selectedFields.get(i));
        String fieldGenerated = "public " + Signature.toString(field.getTypeSignature()) + " "
                + field.getElementName() + ";";
        newType.createField(fieldGenerated, null, false, null);
    }
    String method = "public " + newType.getElementName() + "() {} ";
    newType.createMethod(method, null, false, null);

    method = "public " + newType.getElementName() + "(" + TYPE_STRING + " str) { ";
    method = method + "java.util.StringTokenizer token = new java.util.StringTokenizer(str, \"::\");";
    for (int i = 0; i < selectedFields.size(); i++) {
        IField field = ((IField) selectedFields.get(i));
        method = method + "this." + field.getElementName() + " = "
                + CodeGenerationUtil.convert("token.nextToken()", field.getTypeSignature()) + ";";
    }
    method = method + " } ";
    newType.createMethod(method, null, false, null);

    method = "public " + TYPE_STRING + " toString() { ";
    method = method + "java.lang.String str = \"\"; ";
    for (int i = 0; i < selectedFields.size(); i++) {
        IField field = ((IField) selectedFields.get(i));
        method = method + "str += java.lang.String.valueOf(this." + field.getElementName() + ")";
        if (i < selectedFields.size()) {
            method = method + "+\"::\"";
        }
        method = method + ";";
    }
    method = method + " return str;";
    method = method + " } ";
    newType.createMethod(method, null, false, null);
    newType.createMethod(CodeGenerationUtil.createEqualsMethod(newType.getElementName(), newType), null, false,
            null);
}