Example usage for org.eclipse.jdt.core IJavaElement getResource

List of usage examples for org.eclipse.jdt.core IJavaElement getResource

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaElement getResource.

Prototype

IResource getResource();

Source Link

Document

Returns the innermost resource enclosing this element.

Usage

From source file:edu.wpi.cs.jburge.SEURAT.actions.RestoreAssociations.java

License:Open Source License

/**
 * This is where the action takes place when the restore is invoked from the SEURAT pull-down menu.
 *///from   w w  w  .  j a  v a2 s.c o  m
public void run() {
    //find all our resources
    RationaleDB d = RationaleDB.getHandle();
    Vector<Association> ourResources = d.getAssociations();
    Iterator<Association> resI = ourResources.iterator();
    try {

        while (resI.hasNext()) {
            cstart = 0;
            ourAssoc = (Association) resI.next();
            String ourArtifact = ourAssoc.getArtifact();

            //System.out.println(ourArtifact);
            //System.out.println(ourAssoc.getResource());
            try {
                // We create the java element from its artifact that is stored in the DB
                // and then search through the resource to find out where the marker needs to be placed.
                IJavaElement ourEle = JavaCore.create(ourArtifact);
                //System.out.println(ourEle.getElementName() + " " + ourEle.getElementType());

                if (ourEle.getElementType() == IJavaElement.COMPILATION_UNIT) {
                    ourRes = ourEle.getCorrespondingResource();
                } else {
                    ourRes = ourEle.getUnderlyingResource();
                    if (ourRes != null) {
                        //                     ***                        System.out.println("this one wasn't null?");
                    }
                    //find the enclosing class file
                    IJavaElement nextE = ourEle.getParent();
                    while ((nextE != null) && (nextE.getElementType() != IJavaElement.COMPILATION_UNIT)) {
                        //                     ***                        System.out.println("Name = " + nextE.getElementName());
                        //                     ***                     System.out.println("Type = " + nextE.getElementType());
                        nextE = nextE.getParent();
                    }
                    try {
                        //                     ***                     System.out.println("getting our resource");
                        //                  ourRes = nextE.getUnderlyingResource();
                        ourRes = nextE.getCorrespondingResource();
                        ourRes = nextE.getResource();
                    } catch (JavaModelException ex) {
                        System.out.println("exception getting resource?");
                    }
                    //                  ***                     System.out.println("Final name = " + nextE.getElementName());
                    //                  ***                     System.out.println("Final type = " + nextE.getElementType());
                    if (ourRes == null) {
                        //                     ***                        System.out.println("see if there's a working copy");
                        IJavaElement original = nextE.getPrimaryElement();
                        //see if we can get the element from the working copy
                        //                     IJavaElement original = ((IWorkingCopy) ((ICompilationUnit) nextE).getWorkingCopy()).getOriginalElement();
                        ourRes = original.getCorrespondingResource();
                    }
                }
                //                  ourRes = navigatorSelection.getUnderlyingResource();
                if (ourRes == null) {
                    //                  ***                     System.out.println("why would our resource be null?");
                }
                //               ***                  System.out.println("FullPath = " + ourRes.getFullPath().toString());
                //               ***                  System.out.println("now checking file extension?");
                if (ourRes.getFullPath().getFileExtension().compareTo("java") == 0) {
                    //                  ***                     System.out.println("creating our file?");
                    IJavaElement myJavaElement = JavaCore.create((IFile) ourRes);
                    //                  ***                  System.out.println("created an element?");
                    if (myJavaElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                        //                     ***                     System.out.println("Compilation Unit");
                        ICompilationUnit myCompilationUnit = (ICompilationUnit) myJavaElement;

                        IType[] myTypes = myCompilationUnit.getTypes();
                        boolean found = false;
                        int i = 0;
                        while ((!found) && i < myTypes.length) {
                            //selected item was the class itself
                            if (ourEle.getElementType() == IJavaElement.COMPILATION_UNIT) {
                                //                           ***                            System.out.println("found the class");
                                if (myTypes[i].isClass()) {
                                    found = true;
                                    cstart = myTypes[i].getNameRange().getOffset();
                                }
                            } else if (ourEle.getElementType() == IJavaElement.FIELD) {
                                //                           ***                            System.out.println("looking for types");
                                IField[] myFields = myTypes[i].getFields();
                                for (int j = 0; j < myFields.length; j++) {
                                    if (myFields[j].getElementName().compareTo(ourEle.getElementName()) == 0) {
                                        //                                 ***                               System.out.println("found a type");
                                        found = true;
                                        cstart = myFields[j].getNameRange().getOffset();
                                    }
                                }

                            } else if (ourEle.getElementType() == IJavaElement.METHOD) {
                                //                           ***                            System.out.println("looking for a method");
                                IMethod[] myMethods = myTypes[i].getMethods();
                                for (int j = 0; j < myMethods.length; j++) {
                                    if (myMethods[j].getElementName().compareTo(ourEle.getElementName()) == 0) {
                                        //                                 ***                         System.out.println("found a method");
                                        found = true;
                                        cstart = myMethods[j].getNameRange().getOffset();
                                    }
                                }
                            }
                            //don't forget to increment!
                            i++;
                        } //end while

                    } else {
                        //                     ***                      System.out.println("not a compilation unit?");
                        System.out.println(myJavaElement.getElementType());
                    }
                    //ok... now what type is our selected item? 
                    System.out.println("got the resource?");
                    if (ourRes == null) {
                        //                     ***                     System.out.println("null resource???");
                    }
                } else {
                    //                  ***                     System.out.println("not a java file?");
                }
                //               from the newsgroup - in a runnable?                  
                ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
                    public void run(IProgressMonitor monitor) {
                        try {
                            //                        ***                  System.out.println("line number = " + new Integer(lineNumber).toString());
                            IMarker ratM = ourRes.createMarker("SEURAT.ratmarker");
                            String markD = ourAssoc.getMsg();
                            ratM.setAttribute(IMarker.MESSAGE, markD);
                            ratM.setAttribute(IMarker.CHAR_START, cstart);
                            ratM.setAttribute(IMarker.CHAR_END, cstart + 1);
                            ratM.setAttribute(IMarker.SEVERITY, 0);
                            System.out.println(cstart);
                            Alternative ourAlt = (Alternative) RationaleDB
                                    .getRationaleElement(ourAssoc.getAlt(), RationaleElementType.ALTERNATIVE);
                            ratM.setAttribute("alternative", ourAlt.getName());
                            SEURATResourcePropertiesManager.addPersistentProperty(ourRes, "Rat", "true");

                        } catch (CoreException e) {
                            e.printStackTrace();
                        }
                    }
                }, null);
                //               ***                  System.out.println("adding persistent property");

                SEURATDecoratorManager.addSuccessResources(ourRes);
                //               ***                  System.out.println("added our property");  
                // Refresh the label decorations... Change it to DemoDecoratorWithImageCaching if image caching should be used
                //               ((TreeParent) obj).setStatus(RationaleErrorLevel.ERROR);
                //              viewer.update((TreeParent) obj, null);
                //for some reason the next line is giving us an exception - ???
                //it doesn't seem to be needed - the decorator appears.
                //         SEURATLightWeightDecorator.getRatDecorator().refresh();
                //               ***                  System.out.println("refresh");

            } catch (Exception e) {
                System.out.println("couldn't create our element " + ourArtifact);
            }

        }
    } catch (Exception ex) {
        System.out.println("exception while trying to add associations");
    }

}

From source file:edu.wpi.cs.jburge.SEURAT.SEURATElementChangedManager.java

License:Open Source License

/**
 * Determines whether a change occurred to an associated artifact, and if it did,
 * handles the change.  It basically works by saving the first element it gets and
 * mapping it to a corresponding element later on (provided that the elements are actually
 * associated with some alternative).  Two exceptions come up: one, if it's a compilation unit,
 * we just use the getMovedToElement() method to take care of the mapping for us (we don't have
 * access to this for single methods due to the confusing/arcane way they decided to code
 * java element changes).  The other exception is also for compilation units- we have to manually check
 * the java elements attached to it such as methods and fields to see if any of those are associated
 * and handle the changes if they are, because we don't get deltas for them.
 * /*from w  w w .j  a va 2  s  . c om*/
 * @param change - the possible change, an IJavaElementDelta
 */
private void handleChange(IJavaElementDelta change) {
    System.out
            .println("HandleChange: " + change.getElement() + " " + change.toString() + " " + change.getKind());
    //System.out.println("Saved Delta: " + savedDelta.getElement() + " " + savedDelta.toString() + " " + savedDelta.getKind());
    IJavaElement movedTo = change.getMovedToElement();
    if (change.getKind() == IJavaElementDelta.ADDED || change.getKind() == IJavaElementDelta.REMOVED) {
        if (change.getKind() == IJavaElementDelta.REMOVED && savedDelta == null && movedTo == null) {
            checkDeltaAndSave(change);
        } else if (change.getKind() == IJavaElementDelta.ADDED && savedDelta == null && movedTo == null) {
            // always save this kind of delta, can't check if in DB without reference to removed delta
            savedDelta = change;
            System.out.println("Saved a delta");
        } else {
            IJavaElement oldElt = null;
            IJavaElement newElt = null;
            if (change.getKind() == IJavaElementDelta.ADDED) {
                // get the saved added delta
                oldElt = savedDelta.getElement();
                newElt = change.getElement();
            } else { // change.getKind() == IJavaElementDelta.REMOVED
                if (movedTo != null) {
                    // process the move
                    checkDeltaAndSave(change); // in this case we're not really saving, just checking
                    newElt = movedTo;
                    oldElt = change.getElement();
                } else {
                    // check the removed delta, then get the saved added delta
                    checkDeltaAndSave(change);
                    if (savedDelta != null) { // sanity check
                        newElt = savedDelta.getElement();
                        oldElt = change.getElement();
                    }
                }
            }
            // Get the saved association and the old artName
            Association ourAssoc = savedAssoc;
            String oldArtName = oldElt.getElementName();
            // Reset the saved delta and association
            savedDelta = null;
            savedAssoc = null;

            // Make sure the association is in the database
            if (ourAssoc != null && ourAssoc.getAlt() != -1) {
                // Find the artifact itself
                IResource newResource = null;
                int cstart = 0;
                IField[] fields = null;
                IMethod[] methods = null;
                try {
                    ICompilationUnit compUnit = null;
                    if (newElt.getElementType() != IJavaElement.COMPILATION_UNIT) {
                        newResource = newElt.getUnderlyingResource();
                        compUnit = (ICompilationUnit) newElt.getAncestor(IJavaElement.COMPILATION_UNIT);
                    } else {
                        newResource = newElt.getCorrespondingResource();
                        compUnit = (ICompilationUnit) newElt;
                    }
                    IType[] myTypes = compUnit.getTypes();
                    boolean found = false;
                    int i = 0;
                    while ((!found) && i < myTypes.length) {
                        //selected item was the class itself
                        if (newElt.getElementType() == IJavaElement.COMPILATION_UNIT) {
                            if (myTypes[i].isClass()) {
                                found = true;
                                cstart = myTypes[i].getNameRange().getOffset();
                                fields = myTypes[i].getFields();
                                methods = myTypes[i].getMethods();
                            }
                        } else if (newElt.getElementType() == IJavaElement.FIELD) {
                            IField[] myFields = myTypes[i].getFields();
                            for (int j = 0; j < myFields.length; j++) {
                                if (myFields[j].getElementName().compareTo(newElt.getElementName()) == 0) {
                                    found = true;
                                    cstart = myFields[j].getNameRange().getOffset();
                                }
                            }
                        } else if (newElt.getElementType() == IJavaElement.METHOD) {
                            IMethod[] myMethods = myTypes[i].getMethods();
                            for (int j = 0; j < myMethods.length; j++) {
                                if (myMethods[j].getElementName().compareTo(newElt.getElementName()) == 0) {
                                    found = true;
                                    cstart = myMethods[j].getNameRange().getOffset();
                                }
                            }
                        }
                        i++;
                    } //end while
                } catch (JavaModelException jme) {
                    System.err.println(jme.toString());
                }
                System.out.println("DEBUG: newresource " + newResource.getName() + " cstart " + cstart);

                // Get new values for association data
                String newRes = newResource.getName();
                String newArtName = newElt.getElementName();
                String newArt = newElt.getHandleIdentifier();

                IResource oldResource = null;
                // Now, the time-consuming part.  If this is a compilation unit, we need to go through
                // all of its fields and methods and if they have associations, update them.
                if (newElt.getElementType() == IJavaElement.COMPILATION_UNIT) {
                    for (int i = 0; i < fields.length; i++) {
                        checkAssocAndUpdate(fields[i], newRes, null);
                    }
                    for (int i = 0; i < methods.length; i++) {
                        String oldSubArtName = methods[i].getElementName();
                        String oldSubArtNameJava = oldSubArtName + ".java";
                        if ((oldSubArtName == oldArtName || oldSubArtNameJava == oldArtName)
                                && oldArtName != newArtName) {
                            // Names of old comp unit and old method are same; this is a constructor, and its name has changed
                            checkAssocAndUpdate(methods[i], newRes, oldSubArtName);
                        } else {
                            checkAssocAndUpdate(methods[i], newRes, null);
                        }
                    }
                }
                // If we're not dealing with a compilation unit, a single method/field was renamed or moved.
                // If it was moved we need to know the old resource to change resource properties (it might not
                // have rationale anymore) so we save that now.
                else {
                    oldResource = oldElt.getResource();
                }

                // Update them
                ourAssoc.setArtifact(newArt);
                ourAssoc.setResource(newRes);
                ourAssoc.setArtName(newArtName);

                System.out.println("oldArt became " + newArt);
                System.out.println("oldRes became " + newRes);
                System.out.println(oldArtName + " became " + newArtName);

                // Send the update to the DB
                ourAssoc.toDatabase(oldArtName);

                // Update the marker- this will sometimes give us "resource tree locked" exceptions.
                // However, in the cases where it does, we're making changes to a compilation unit
                // and the markers will stay where they are.
                try {
                    IMarker ratM = newResource.createMarker("SEURAT.ratmarker");
                    String markD = ourAssoc.getMsg();
                    ratM.setAttribute(IMarker.MESSAGE, markD);
                    ratM.setAttribute(IMarker.CHAR_START, cstart);
                    ratM.setAttribute(IMarker.CHAR_END, cstart + 1);
                    ratM.setAttribute(IMarker.SEVERITY, 0);
                    System.out.println(cstart);
                    Alternative ourAlt = (Alternative) RationaleDB.getRationaleElement(ourAssoc.getAlt(),
                            RationaleElementType.ALTERNATIVE);
                    ratM.setAttribute("alternative", ourAlt.getName());
                } catch (CoreException e) {
                    System.err.println(e.toString());
                }

                // If the element was moved, remove the persistent property from the old resource.
                // This is a hack, because if there is associated rationale remaining in the old resource
                // it still removes the decorator, but the next time restoreAssociations is called it will
                // be back.  I couldn't see a better way to do it short of rewriting the decorator and/or resource properties manager.
                if (oldResource != null) { // it will be null for a compilation unit because we didn't set it
                    SEURATResourcePropertiesManager.addPersistentProperty(oldResource, "Rat", "false");
                    SEURATDecoratorManager.addSuccessResources(oldResource);
                }
                // add property for the new resource in all cases
                SEURATResourcePropertiesManager.addPersistentProperty(newResource, "Rat", "true");
                SEURATDecoratorManager.addSuccessResources(newResource);
            }
        }
    }
}

From source file:edu.wpi.cs.jburge.SEURAT.views.RationaleExplorer.java

License:Open Source License

/**
 * This method is used to associate the java file with alternative in the ratinale 
 * explore in the java direction//from  w ww. j av a2s . c  o m
 */
public void associateAlternative(RationaleUpdateEvent e)

{
    //get the Java element selected in the Package Explorer from the RationaleUpdateEvent
    navigatorSelection = e.getIJavaElement();

    if (navigatorSelection != null) {

        ISelection selection = viewer.getSelection();

        obj = ((IStructuredSelection) selection).getFirstElement();

        //whether an alternative is selected?
        if (obj != null && ((TreeParent) obj).getType() == RationaleElementType.ALTERNATIVE) {
            alternativeName = ((TreeParent) obj).getName();
        }
        //if there is no alternative selected, provide a select items of alternative
        else {
            SelectItem selectItem = new SelectItem(ourDisplay, RationaleElementType.fromString("Alternative"));
            //DEBUG: Is this where the infinite loop is? (YQ)
            if (selectItem == null) {
                System.out.println("NULL selectItem at line 2098");
            }
            if (selectItem.getNewItem() == null) {
                System.out.println("NULL Pointer at line 2099 in RationaleExplorer.java Expect Crashes");
            }
            alternativeName = selectItem.getNewItem().getName();
        }

        String assQ = "Associate '" + alternativeName + "' with " + navigatorSelection.getElementName() + "?";

        boolean selOk = showQuestion(assQ);
        if (selOk) {
            cstart = 0;

            ourRes = null;
            try {

                if (navigatorSelection.getElementType() == IJavaElement.COMPILATION_UNIT) {
                    ourRes = navigatorSelection.getCorrespondingResource();
                } else {
                    ourRes = navigatorSelection.getUnderlyingResource();
                    if (ourRes != null) {
                        //                     ***                        System.out.println("this one wasn't null?");
                    }
                    //find the enclosing class file
                    IJavaElement nextE = navigatorSelection.getParent();
                    while ((nextE != null) && (nextE.getElementType() != IJavaElement.COMPILATION_UNIT)) {
                        //                     ***                        System.out.println("Name = " + nextE.getElementName());
                        //                     ***                     System.out.println("Type = " + nextE.getElementType());
                        nextE = nextE.getParent();
                    }
                    try {
                        //                     ***                     System.out.println("getting our resource");
                        //                  ourRes = nextE.getUnderlyingResource();
                        ourRes = nextE.getCorrespondingResource();
                        ourRes = nextE.getResource();
                    } catch (JavaModelException ex) {
                        System.out.println("exception getting resource?");
                    }
                    //                  ***                     System.out.println("Final name = " + nextE.getElementName());
                    //                  ***                     System.out.println("Final type = " + nextE.getElementType());
                    if (ourRes == null) {
                        //see if we can get the element from the working copy
                        IJavaElement original = nextE.getPrimaryElement();
                        //                     Get working copy has been deprecated
                        //                     IJavaElement original = ((ICompilationUnit) ((ICompilationUnit) nextE).getWorkingCopy()).getOriginalElement();
                        ourRes = original.getCorrespondingResource();

                    }
                }
                //                  ourRes = navigatorSelection.getUnderlyingResource();
                if (ourRes == null) {
                    //                  ***                     System.out.println("why would our resource be null?");
                }
                //               ***                  System.out.println("FullPath = " + ourRes.getFullPath().toString());
                //               ***                  System.out.println("now checking file extension?");
                if (ourRes.getFullPath().getFileExtension().compareTo("java") == 0) {
                    //                  ***                     System.out.println("creating our file?");
                    IJavaElement myJavaElement = JavaCore.create((IFile) ourRes);
                    //                  ***                  System.out.println("created an element?");
                    if (myJavaElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                        //                     ***                     System.out.println("Compilation Unit");
                        ICompilationUnit myCompilationUnit = (ICompilationUnit) myJavaElement;

                        IType[] myTypes = myCompilationUnit.getTypes();
                        boolean found = false;
                        int i = 0;
                        while ((!found) && i < myTypes.length) {
                            //selected item was the class itself
                            if (navigatorSelection.getElementType() == IJavaElement.COMPILATION_UNIT) {
                                //                           ***                            System.out.println("found the class");
                                if (myTypes[i].isClass()) {
                                    found = true;
                                    cstart = myTypes[i].getNameRange().getOffset();
                                }
                            } else if (navigatorSelection.getElementType() == IJavaElement.FIELD) {
                                //                           ***                            System.out.println("looking for types");
                                IField[] myFields = myTypes[i].getFields();
                                for (int j = 0; j < myFields.length; j++) {
                                    if (myFields[j].getElementName()
                                            .compareTo(navigatorSelection.getElementName()) == 0) {
                                        //                                 ***                               System.out.println("found a type");
                                        found = true;
                                        cstart = myFields[j].getNameRange().getOffset();
                                    }
                                }

                            } else if (navigatorSelection.getElementType() == IJavaElement.METHOD) {
                                //                           ***                            System.out.println("looking for a method");
                                IMethod[] myMethods = myTypes[i].getMethods();
                                for (int j = 0; j < myMethods.length; j++) {
                                    if (myMethods[j].getElementName()
                                            .compareTo(navigatorSelection.getElementName()) == 0) {
                                        //                                 ***                               System.out.println("found a method");
                                        found = true;
                                        cstart = myMethods[j].getNameRange().getOffset();
                                    }
                                }
                            }
                            //don't forget to increment!
                            i++;
                        } //end while
                    } else {
                        //                     ***                      System.out.println("not a compilation unit?");
                        System.out.println(myJavaElement.getElementType());
                    }
                    //ok... now what type is our selected item? 
                    System.out.println("got the resource?");
                    if (ourRes == null) {
                        System.out.println("null resource???");
                    }
                } else {
                    System.out.println("not a java file?");
                }
                //               from the newsgroup - in a runnable?                  
                ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
                    public void run(IProgressMonitor monitor) {
                        try {
                            //                        ***                  System.out.println("line number = " + new Integer(lineNumber).toString());
                            IMarker ratM = ourRes.createMarker("SEURAT.ratmarker");
                            String dbname = RationaleDB.getDbName();
                            String markD = "Alt: '" + alternativeName + "'   Rationale DB: '" + dbname + "'";
                            ratM.setAttribute(IMarker.MESSAGE, markD);
                            ratM.setAttribute(IMarker.CHAR_START, cstart);
                            ratM.setAttribute(IMarker.CHAR_END, cstart + 1);
                            ratM.setAttribute(IMarker.SEVERITY, 0);
                            //                        ratM.setAttribute(IMarker.LINE_NUMBER, lineNumber);
                            String artName = navigatorSelection.getElementName();
                            ratM.setAttribute("alternative", alternativeName);
                            SEURATResourcePropertiesManager.addPersistentProperty(ourRes, "Rat", "true");
                            RationaleDB d = RationaleDB.getHandle();
                            d.associateAlternative(alternativeName, navigatorSelection.getHandleIdentifier(),
                                    ourRes.getName(), artName, markD);

                        } catch (CoreException e) {
                            e.printStackTrace();
                        }
                    }
                }, null);
                //               ***                  System.out.println("adding persistent property");

                SEURATDecoratorManager.addSuccessResources(ourRes);
                //               ***                  System.out.println("added our property");  
                // Refresh the label decorations... Change it to DemoDecoratorWithImageCaching if image caching should be used
                //               ((TreeParent) obj).setStatus(RationaleErrorLevel.ERROR);
                //Is this the inf loop? (YQ)
                if (obj == null) {
                    System.out.println("CRITICAL ERROR: Obj is null at RationaleExplorer.java, line 2280");
                }
                if (viewer == null) {
                    System.out.println("Viewer is null at RationaleExplorer.java line 2283");
                }
                viewer.update((TreeParent) obj, null);
                SEURATLightWeightDecorator.getRatDecorator().refresh();
                //               ***                  System.out.println("refresh");

            } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("an exception occured in AssociateArtifactAction");
            }

        } else {
            System.out.println("selection rejected");
        }
    }

    else {
        System.out.println("No java element selected...");
    }

}

From source file:ewicket.wizard.EWicketNewPanelWizard.java

License:Apache License

@Override
public boolean performFinish() {
    final boolean finished = super.performFinish();
    if (finished) {
        final IJavaElement ce = getCreatedElement();
        final IPath p = ce.getResource().getProjectRelativePath().removeFileExtension().addFileExtension("html")
                .makeAbsolute();//  ww w . jav a  2s  .co m
        try {
            WizardPage nhtwp = (WizardPage) htmlWiz.getPage("NewHTMLTemplatesWizardPage");
            IFile file = ce.getJavaProject().getProject().getFile(p);

            // this is evil, but the NewHTMLTemplatesWizardPage doesn't allow to get the selected template
            final Method m = nhtwp.getClass().getDeclaredMethod("getTemplateString", (Class<?>[]) null);
            m.setAccessible(true);
            final String templateString = (String) m.invoke(nhtwp, (Object[]) null);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            outputStreamWriter.write(templateString);
            outputStreamWriter.flush();
            outputStreamWriter.close();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            if (!file.exists()) {
                file.create(inputStream, true, null);
            }
            inputStream.close();
        } catch (Exception e) {
            Logger.log(202, "Could not create contents for new html file", e);
        }
    }
    return finished;
}

From source file:ewicket.wizard.EWicketNewWebPageWizard.java

License:Apache License

@Override
public boolean performFinish() {
    final boolean finished = super.performFinish();
    if (finished) {
        final IJavaElement ce = getCreatedElement();
        final IPath p = ce.getResource().getProjectRelativePath().removeFileExtension().addFileExtension("html")
                .makeAbsolute();//from w w  w.j a  va  2  s  .c  o  m
        final IPath pathP = ce.getResource().getProjectRelativePath().removeFileExtension()
                .addFileExtension("properties").makeAbsolute();
        try {
            WizardPage nhtwp = (WizardPage) htmlWiz.getPage("NewHTMLTemplatesWizardPage");
            IFile file = ce.getJavaProject().getProject().getFile(p);
            IFile file_p = ce.getJavaProject().getProject().getFile(pathP);

            final Method m = nhtwp.getClass().getDeclaredMethod("getTemplateString", (Class<?>[]) null);
            m.setAccessible(true);
            final String templateString = (String) m.invoke(nhtwp, (Object[]) null);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            outputStreamWriter.write(templateString);
            outputStreamWriter.flush();
            outputStreamWriter.close();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            if (!file.exists()) {
                System.out.println("creo il file properties");
                file.create(inputStream, true, null);
            }
            inputStream.close();

            ByteArrayInputStream inputStream_p = new ByteArrayInputStream(
                    new ByteArrayOutputStream().toByteArray());
            if (!file_p.exists()) {
                System.out.println("creo il file properties");
                file_p.create(inputStream_p, true, null);
            }
            inputStream_p.close();

        } catch (Exception e) {
            Logger.log(202, "Could not create contents for new html file", e);
        }
    }
    return finished;
}

From source file:fr.imag.adele.cadse.cadseg.eclipse.RenameJavaClassMappingOperartion.java

License:Apache License

protected void refactoringRename(String id, String... params) {
    try {/*from ww w .  ja  va2s. c o m*/
        IJavaElement oldElement = getJavaElement(_oldcontext);
        IJavaElement newElement = getJavaElement(_newcontext);

        Map<String, String> arguments = new HashMap<String, String>();
        for (int i = 0; i < params.length;) {
            String k = params[i++];
            String v = params[i++];
            arguments.put(k, v);
        }
        arguments.put("name", newElement.getElementName());
        arguments.put("input", oldElement.getHandleIdentifier());

        RenameJavaElementDescriptor javaElementDescriptor = new RenameJavaElementDescriptor(id,
                id == IJavaRefactorings.RENAME_JAVA_PROJECT ? null
                        : oldElement.getResource().getProject().getName(),
                _desc, _desc, arguments, 0);
        javaElementDescriptor.setJavaElement(oldElement);
        javaElementDescriptor.setNewName(newElement.getElementName());

        int type = oldElement.getElementType();
        switch (type) {
        case IJavaElement.PACKAGE_FRAGMENT:
        case IJavaElement.TYPE:
            javaElementDescriptor.setUpdateQualifiedNames(true);
            break;
        default:
        }
        if (oldElement.getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT) {
            javaElementDescriptor.setUpdateReferences(true);
        }

        RenameSupport renameSupport = RenameSupport.create(javaElementDescriptor);
        Shell parent = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
        renameSupport.perform(parent, new ProgressMonitorDialog(parent));

    } catch (CoreException e1) {
        e1.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:in.cypal.studio.gwt.core.common.Util.java

License:Apache License

public static List findRemoteServices(IJavaProject javaProject) throws CoreException {

    List remoteServiceFiles = new ArrayList();

    IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots();
    for (int i = 0; i < packageFragmentRoots.length; i++) {
        IPackageFragmentRoot aRoot = packageFragmentRoots[i];
        // check only in source folders. Skip others
        if (aRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
            continue;
        }/*from  ww w.  j a  v a2  s. co  m*/

        IJavaElement[] children = aRoot.getChildren();
        for (int j = 0; j < children.length; j++) {

            IJavaElement aPackage = children[j];
            // look only for packages. Skip others
            if (!(aPackage instanceof IPackageFragment)) {
                continue;
            }

            ICompilationUnit[] compilationUnits = ((IPackageFragment) aPackage).getCompilationUnits();
            for (int k = 0; k < compilationUnits.length; k++) {

                ICompilationUnit cu = compilationUnits[k];

                IResource resource = cu.getCorrespondingResource();
                if (aPackage.getResource().getName().equals(Constants.CLIENT_PACKAGE)
                        && resource instanceof IFile && resource.getName().endsWith(".java")) {//$NON-NLS-1$
                    // java file. Check whether its a remote service ...

                    // for every type declared in the java file
                    IType[] types = cu.getTypes();
                    for (int l = 0; l < types.length; l++) {
                        IType someType = types[l];
                        // for every interface implemented by that type

                        String[] superInterfaceNames = someType.getSuperInterfaceNames();
                        for (int m = 0; m < superInterfaceNames.length; m++) {
                            String aSuperInterface = superInterfaceNames[m];
                            if (aSuperInterface.equals(Constants.REMOTE_SERVICE_CLASS)) {
                                remoteServiceFiles.add(resource);
                            }
                        }
                    }
                }
            }
        }
    }
    return remoteServiceFiles;
}

From source file:net.sf.wickedshell.jdt.action.ChangeToFolderInShellAction.java

License:Open Source License

/**
 * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction,
 *      org.eclipse.jface.viewers.ISelection)
 *///from  w  w w.  jav a 2 s.  c  o m
@SuppressWarnings("null")
public void selectionChanged(IAction action, ISelection selection) {
    IStructuredSelection structuredSelection = (IStructuredSelection) selection;
    if (!structuredSelection.isEmpty()) {
        Object selectedElement = structuredSelection.getFirstElement();
        if (selectedElement instanceof IJavaElement) {
            IJavaElement currentJavaElement = (IJavaElement) selectedElement;
            if (currentJavaElement != null) {
                currentResource = currentJavaElement.getResource();
            } else {
                currentResource = null;
            }
            action.setEnabled(currentResource != null && currentResource.exists());
        } else {
            action.setEnabled(false);
        }
    }
}

From source file:org.caesarj.launching.CaesarLaunchShortcut.java

License:Open Source License

/**
 * If the given java element contains a main type, the return value is the full
 * qualified type name, otherwise it is null.
 * /*from w  ww. j  av a2s.  co m*/
 * @param je   the java root element to search for a main type
 * @return      the full qualified type name or null
 */
protected String findRunnableType(IJavaElement je) {
    IResource res = je.getResource();
    if (res == null) {
        return null;
    }
    String filename = res.getLocation().toFile().getAbsolutePath();
    IProject project = res.getProject();
    ProjectProperties properties = ProjectProperties.create(project);
    IProgramElement pe = findSourceFileNode(properties.getAsmManager().getHierarchy().getRoot(), filename);

    Object current = null;
    CaesarProgramElement currentCe = null;
    boolean foundRunnable = false;
    for (Iterator it = pe.getChildren().iterator(); it.hasNext() && !foundRunnable;) {
        current = it.next();
        if (current instanceof CaesarProgramElement) {
            currentCe = (CaesarProgramElement) current;
            if (currentCe.getCaesarKind().isType()) {
                foundRunnable = isTypeNodeRunnable(currentCe);
            }
        }
    }
    if (foundRunnable) {
        return currentCe.getPackageName() + "." + currentCe.getName();
    }
    return null;
}

From source file:org.caesarj.ui.views.CaesarHierarchyView.java

License:Open Source License

/**
 * Refreshes the view./*from  w w w  .  j  a  va  2  s.  c  o m*/
 * 
 * Checks if the properties have an ASM. If not, just print messages in the view.
 * 
 * If yes, create new input objects for the treeviewer and list viewer. If error occurs,
 * set the messages is the view.
 * 
 * @param properties
 * @param file
 */
public void refresh(ProjectProperties properties, IJavaElement file) {
    // Enable the buttons
    filterButton.setEnabled(true);
    toolButton.setEnabled(true);

    // Check if we already have an ASM for the project. If we don't have,
    // just call the update method with empty nodes (to show a message) and return
    if (properties == null || properties.getAsmManager() == null) {
        treeViewer.setInput(new RootNode(HierarchyNode.EMPTY));
        listViewer.setInput(new LinearNode(HierarchyNode.EMPTY));
        // Disable the buttons, since we don't have input
        filterButton.setEnabled(false);
        toolButton.setEnabled(false);
        return;
    }

    try {
        // Gets the absolute path for the project output directory
        String outputdir = properties.getProjectLocation() + properties.getOutputPath();

        // Gets the filename for the input element
        String filename = file.getResource().getName();

        // Try to get the class string, which is the packages + the file name
        String path = file.getResource().getProjectRelativePath().removeFileExtension().toOSString();
        IPackageFragmentRoot[] roots = file.getJavaProject().getAllPackageFragmentRoots();
        String clazz = null;
        for (int i = 0; i < roots.length; i++) {
            if (path.lastIndexOf(roots[i].getElementName()) != -1) {
                clazz = path.substring(roots[i].getElementName().length() + 1);
            }
        }

        // Create the input nodes with the factory
        RootNode rootNode = HierarchyModelFactory.createHierarchyTreeModel(
                properties.getAsmManager().getHierarchy(), filename, outputdir, implicitFilter, superView);
        LinearNode linearNode = HierarchyModelFactory.createHierarchyListModel(clazz, outputdir);

        // If the root node is EMPTY or if it doesn't have children, disable the buttons
        if (rootNode.getKind().equals(HierarchyNode.EMPTY) || rootNode.getChildren().length == 0) {
            // Disable the buttons, since we don't have input
            filterButton.setEnabled(false);
            toolButton.setEnabled(false);
        }

        // Set the input for the viewers
        treeViewer.setInput(rootNode);
        listViewer.setInput(linearNode);

        // Show 5 levels on the treeViewer
        treeViewer.expandToLevel(5);

    } catch (Exception e) {
        // If we have an error, set the messages in the view
        treeViewer.setInput(new RootNode(HierarchyNode.EMPTY));
        listViewer.setInput(new LinearNode(HierarchyNode.EMPTY));
        // Disable the buttons, since we don't have input
        filterButton.setEnabled(false);
        toolButton.setEnabled(false);
    }
}