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

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

Introduction

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

Prototype

ICompilationUnit getCompilationUnit();

Source Link

Document

Returns the compilation unit in which this member is declared, or null if this member is not declared in a compilation unit (for example, a binary type).

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// w  w  w.  j a  v a  2s . 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:at.bestsolution.efxclipse.tooling.fxgraph.ui.quickfix.FXGraphQuickfixProvider.java

License:Open Source License

@Fix(FXGraphJavaValidator.UNKNOWN_CONTROLLER_METHOD)
public void fixAddControllerMethod(final Issue issue, IssueResolutionAcceptor acceptor) {
    final String methodName = issue.getData()[0];
    final String controllerClass = issue.getData()[1];
    final String argType = issue.getData()[2];
    final String simpleArgType = Signature.getSimpleName(argType);
    acceptor.accept(issue, "Add controller method " + methodName + "(" + simpleArgType + ")",
            "Add a controller method '" + methodName + "(" + simpleArgType + ")' to controller '"
                    + controllerClass + "'",
            null, new IModification() {

                @Override//ww  w.  ja  v  a 2s . c  o  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(controllerClass);

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

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

                    resolvedType = type.resolveType(simpleArgType);

                    if (resolvedType == null) {
                        type.getCompilationUnit().createImport(argType, null, new NullProgressMonitor());
                    }

                    type.createMethod("@FXML public void " + methodName + "(" + simpleArgType + " event) {}",
                            null, true, new NullProgressMonitor());
                }
            });
    acceptor.accept(issue, "Add controller method " + methodName + "()",
            "Add a controller method '" + methodName + "()' to controller '" + controllerClass + "'", null,
            new IModification() {

                @Override
                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(controllerClass);

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

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

                    type.createMethod("@FXML public void " + methodName + "() {}", null, true,
                            new NullProgressMonitor());
                }
            });
}

From source file:at.bestsolution.efxclipse.tooling.fxml.compile.FxmlAnnotationCompilationParticipant.java

License:Open Source License

private int getMethodLineNumber(final IType type, final IMethod method) throws JavaModelException {
    String source = type.getCompilationUnit().getSource();
    String sourceUpToMethod = source.substring(0, method.getSourceRange().getOffset());
    Pattern lineEnd = Pattern.compile("$", Pattern.MULTILINE | Pattern.DOTALL); //$NON-NLS-1$
    return lineEnd.split(sourceUpToMethod).length;
}

From source file:ca.uvic.chisel.diver.sequencediagrams.sc.java.model.ASTUTils.java

License:Open Source License

public static ASTNode getASTFor(IType type) {
    try {/*  www . j av a2 s. c om*/
        ICompilationUnit unit = type.getCompilationUnit();
        if (unit != null) {
            return getASTFor(unit);
        }
        IClassFile classFile = type.getClassFile();
        if (classFile != null) {
            return getASTFor(classFile);
        }
    } catch (Exception e) {
    }
    return null;
}

From source file:ca.uvic.chisel.javasketch.internal.ast.ASTUTils.java

License:Open Source License

public static ASTNode getASTFor(IType type) {
    try {//  ww  w .j a  v  a 2 s .c  om
        synchronized (cache) {
            if (cache.containsKey(type)) {
                WeakReference<ASTNode> ref = cache.get(type);
                if (!(ref.isEnqueued() || ref.get() == null)) {
                    return ref.get();
                } else {
                    cache.remove(type);
                }
            }
            ICompilationUnit unit = type.getCompilationUnit();
            ASTNode node = null;
            if (unit != null) {
                node = getASTFor(unit);
            }
            IClassFile classFile = type.getClassFile();
            if (classFile != null) {
                node = getASTFor(classFile);
            }
            if (node != null) {
                cache.put(type, new WeakReference<ASTNode>(node));
            }
            return node;
        }
    } catch (Exception e) {
    }
    return null;
}

From source file:ca.uvic.chisel.javasketch.ui.internal.MarkTypeJob.java

License:Open Source License

@Override
public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
    try {/*from   w ww  .  j a v a 2s.  c  om*/
        monitor.beginTask("Marking Touched Locations", IProgressMonitor.UNKNOWN);

        IResource resource = typeRoot.getCorrespondingResource();
        if (resource == null) {
            IType type = typeRoot.findPrimaryType();
            if (type != null) {
                ICompilationUnit unit = type.getCompilationUnit();
                if (unit != null) {
                    resource = unit.getResource();
                }
            }
        }
        if (resource == null) {
            resource = ResourcesPlugin.getWorkspace().getRoot();
        }
        deleteMarkers(resource, typeRoot);

        IProgramSketch active = SketchPlugin.getDefault().getActiveSketch();
        if (active == null) {
            return Status.OK_STATUS;
        }

        if (resource.getLocalTimeStamp() > active.getTraceData().getTraceTime().getTime()) {
            //no point in trying to look it up if it has changed recently.
            return Status.OK_STATUS;
        }
        PreparedStatement s = active.getPortal().prepareStatement(
                "SELECT * FROM Activation LEFT OUTER JOIN Message ON Message.activation_id = Activation.model_id WHERE Activation.type_name LIKE ? AND "
                        + "(Message.kind IN ('CALL', 'REPLY', 'THROW'))");
        for (IJavaElement child : typeRoot.getChildren()) {
            if (!(child instanceof IType)) {
                continue;
            }
            IType type = (IType) child;
            String qualifiedName = type.getFullyQualifiedName() + '%';
            s.setString(1, qualifiedName);
            ResultSet results = s.executeQuery();
            TreeSet<Integer> codeLines = new TreeSet<Integer>();
            while (results.next()) {
                //create a new marker
                Object codeLine = results.getObject("CODE_LINE");
                if (codeLine instanceof Integer) {
                    codeLines.add((Integer) codeLine);
                }

            }
            for (Integer line : codeLines) {
                if (line > 0) {
                    Map<Object, Object> attributes = new HashMap<Object, Object>();
                    JavaCore.addJavaElementMarkerAttributes(attributes, typeRoot);
                    attributes.put(IMarker.LINE_NUMBER, line);
                    MarkerUtilities.createMarker(resource, attributes,
                            "ca.uvic.chisel.javasketch.markers.touched");
                }
            }
        }
    } catch (Exception e) {
        SketchPlugin.getDefault().log(e);
        return SketchPlugin.getDefault().createStatus(e);

    } finally {
        monitor.done();
    }
    return Status.OK_STATUS;
}

From source file:ch.powerunit.poweruniteclipse.PowerunitlaunchConfigurationShortcut.java

License:Open Source License

@Override
protected ILaunchConfiguration createConfiguration(IType type) {
    ILaunchConfiguration config = null;/*from ww w . j  a va2  s  . c om*/
    ILaunchConfigurationWorkingCopy wc = null;
    try {
        ILaunchConfigurationType configType = getConfigurationType();
        wc = configType.newInstance(null,
                getLaunchManager().generateLaunchConfigurationName(type.getTypeQualifiedName('.')));
        wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
                type.getCompilationUnit().getJavaProject().getElementName());
        wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, type.getFullyQualifiedName());
        config = wc.doSave();
    } catch (CoreException exception) {
        MessageDialog.openError(JDIDebugUIPlugin.getActiveWorkbenchShell(),
                LauncherMessages.JavaLaunchShortcut_3, exception.getStatus().getMessage());
    }
    return config;
}

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

License:Apache License

private void generateOnCreate(IType type, ImportsManager imports) throws CoreException, JavaModelException {
    StringBuilder buf = new StringBuilder();
    final String lineDelim = "\n"; // OK, since content is formatted afterwards //$NON-NLS-1$
    buf.append("/* (non-Javadoc)").append(lineDelim);
    buf.append("* @see android.app.Activity#onCreate(android.os.Bundle)").append(lineDelim);
    buf.append("*/").append(lineDelim);
    buf.append("@Override");
    buf.append(lineDelim);/*from  w  w w  . jav a2  s .c o  m*/
    buf.append("public void onCreate("); //$NON-NLS-1$
    buf.append(imports.addImport("android.os.Bundle")); //$NON-NLS-1$
    buf.append(" savedInstanceState) {"); //$NON-NLS-1$
    buf.append(lineDelim);
    buf.append("super.onCreate(savedInstanceState);");
    buf.append(lineDelim);
    final String content = CodeGeneration.getMethodBodyContent(type.getCompilationUnit(),
            type.getTypeQualifiedName('.'), "onCreate", false, "", lineDelim); //$NON-NLS-1$ //$NON-NLS-2$
    if (content != null && content.length() != 0)
        buf.append(content);
    buf.append(lineDelim);
    buf.append("}"); //$NON-NLS-1$
    type.createMethod(buf.toString(), null, false, null);
}

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

License:Apache License

private void generateOnStartCommand(IType type, ImportsManager imports)
        throws CoreException, JavaModelException {
    StringBuilder buf = new StringBuilder();
    final String lineDelim = "\n"; // OK, since content is formatted afterwards //$NON-NLS-1$
    buf.append("/* (non-Javadoc)").append(lineDelim);
    buf.append("* @see android.app.Service#onStartCommand(android.content.Intent, int, int)").append(lineDelim);
    buf.append("*/").append(lineDelim);
    buf.append("@Override");
    buf.append(lineDelim);//  ww  w. j  a v a  2 s  . com
    buf.append("public int onStartCommand("); //$NON-NLS-1$
    buf.append(imports.addImport("android.content.Intent")); //$NON-NLS-1$
    buf.append(" intent, int flags, int startId) {"); //$NON-NLS-1$
    buf.append(lineDelim);

    final String content = CodeGeneration.getMethodBodyContent(type.getCompilationUnit(),
            type.getTypeQualifiedName('.'), "super.onStartCommand", false, "", lineDelim); //$NON-NLS-1$ //$NON-NLS-2$
    if (content != null && content.length() != 0)
        buf.append(content);
    buf.append(lineDelim);
    buf.append("return super.onStartCommand(intent, flags, startId);");
    buf.append(lineDelim);
    buf.append("}"); //$NON-NLS-1$
    type.createMethod(buf.toString(), null, false, null);

}

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

License:Apache License

private void generateStub(String method, IType type, ImportsManager imports)
        throws CoreException, JavaModelException {
    List<String> supers = ProjectHelper.getSuperTypeName(getJavaProject(), getSuperClass(), false);
    if (supers.contains(AdtConstants.ACTIVITY_QNAME) && "onCreate".equals(method)) {
        generateOnCreate(type, imports);
        return;/*from  ww  w  .  ja va2  s  .  c  om*/
    } else if (supers.contains(AdtConstants.SERVICE_QNAME) && "onStartCommand".equals(method)) {
        generateOnStartCommand(type, imports);
        return;
    }
    StringBuilder buf = new StringBuilder();
    final String lineDelim = "\n"; // OK, since content is formatted afterwards //$NON-NLS-1$
    buf.append("/* (non-Javadoc)").append(lineDelim);
    buf.append("* @see " + getSuperClass() + "#" + method + "()").append(lineDelim);
    buf.append("*/").append(lineDelim);
    buf.append("@Override");
    buf.append(lineDelim);
    buf.append("public void " + method + "(){"); //$NON-NLS-1$
    //

    buf.append(lineDelim);
    buf.append("super." + method + "();");
    buf.append(lineDelim);

    final String content = CodeGeneration.getMethodBodyContent(type.getCompilationUnit(),
            type.getTypeQualifiedName('.'), method, false, "", lineDelim); //$NON-NLS-1$ //$NON-NLS-2$
    if (content != null && content.length() != 0)
        buf.append(content);
    buf.append(lineDelim);
    buf.append("}"); //$NON-NLS-1$
    type.createMethod(buf.toString(), null, false, null);
}