public void testSmapGeneration1() throws JavaModelException {
    TYPENAME = "__OT__RoleA";
    _enclosingTypename = "SuperTeam";

    SmapStratum stratum_role1 = new SmapStratum(ISMAPConstants.OTJ_STRATUM_NAME);
    FileInfo fileInfo_role1 =
        stratum_role1.getOrCreateFileInfo("SuperTeam.java", "calloutOverride/SuperTeam.java");
    LineInfo lineInfo1_role1 = new LineInfo(4, 4); // RoleA is l4-15
    lineInfo1_role1.setRepeatCount(12);
    LineInfo lineInfo1_role2 =
        new LineInfo(ISMAPConstants.STEP_INTO_LINENUMBER, ISMAPConstants.STEP_INTO_LINENUMBER);
    LineInfo lineInfo1_role3 =
        new LineInfo(ISMAPConstants.STEP_OVER_LINENUMBER, ISMAPConstants.STEP_OVER_LINENUMBER);

    fileInfo_role1.addLineInfo(lineInfo1_role1);
    fileInfo_role1.addLineInfo(lineInfo1_role2);
    fileInfo_role1.addLineInfo(lineInfo1_role3);
    List<SmapStratum> strata_role1 = new ArrayList<SmapStratum>();
    strata_role1.add(stratum_role1);

    stratum_role1.optimize();

    expectedStrata.put(TYPENAME, strata_role1);

    try {
      parseAndCompile(
          new org.eclipse.jdt.core.ICompilationUnit[] {_baseClass, _superTeam, _subTeam});
    } catch (JavaModelException e) {
      fail(e.getMessage());
    }
  }
  public void testMissingType() {
    try {

      IType type = fProject.findType("tests.apiusescan.coretestproject.IConstants");
      type.rename("IConstants1", true, null);
      IProject project = fProject.getProject();
      ExternalDependencyTestUtils.waitForBuild();

      IMarker[] markers =
          project.findMarkers(
              IApiMarkerConstants.API_USESCAN_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
      assertEquals(
          "No API Use Scan problem marker found for missing type IConstants", 1, markers.length);
      String typeName = markers[0].getAttribute(IApiMarkerConstants.API_USESCAN_TYPE, null);
      assertEquals(
          "Marker for missing type IConstants not found",
          "tests.apiusescan.coretestproject.IConstants",
          typeName);

      type = fProject.findType("tests.apiusescan.coretestproject.IConstants1");
      type.rename("IConstants", true, null);
      ExternalDependencyTestUtils.waitForBuild();
      markers =
          project.findMarkers(
              IApiMarkerConstants.API_USESCAN_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
      assertEquals(
          "API Use Scan problem marker for missing type IConstants did not clear",
          0,
          markers.length);
    } catch (JavaModelException e) {
      fail(e.getMessage());
    } catch (CoreException e) {
      fail(e.getMessage());
    }
  }
 protected IPackageFragmentRoot getFragmentRoot(IJavaElement elem) {
   IPackageFragmentRoot initRoot = null;
   if (elem != null) {
     initRoot = (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
     try {
       if (initRoot == null || initRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
         IJavaProject jproject = elem.getJavaProject();
         if (jproject != null) {
           initRoot = null;
           if (jproject.exists()) {
             IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots();
             for (int i = 0; i < roots.length; i++) {
               if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                 initRoot = roots[i];
                 break;
               }
             }
           }
           if (initRoot == null) {
             initRoot = jproject.getPackageFragmentRoot(jproject.getResource());
           }
         }
       }
     } catch (JavaModelException e) {
       // TODO
       e.printStackTrace();
     }
   }
   return initRoot;
 }
  private IJavaProject chooseJavaProject() {
    IJavaProject[] projects;
    try {
      projects = JavaCore.create(getWorkspaceRoot()).getJavaProjects();
    } catch (JavaModelException e) {
      EasybLaunchActivator.getDefault().getLog().log(e.getStatus());
      projects = new IJavaProject[0];
    }

    ILabelProvider labelProvider =
        new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
    ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider);
    dialog.setTitle("Projects");
    dialog.setMessage("Please choose a project");
    dialog.setElements(projects);

    IJavaProject javaProject = getJavaProject();
    if (javaProject != null) {
      dialog.setInitialSelections(new Object[] {javaProject});
    }
    if (dialog.open() == Window.OK) {
      return (IJavaProject) dialog.getFirstResult();
    }
    return null;
  }
  /**
   * The default implementation recursively traverses the folders of the imported projects and
   * copies all contents into a feature folder with the imported projects name in {@code
   * newProject}. Can be overwritten by extending classes to accomodate {@link
   * IComposerExtensionBase Composers} needs.
   */
  protected void migrateProjects() {
    for (IProject project : projects) {
      IPath destinationPath = new Path(configurationData.sourcePath);

      assert newProject.getFolder(destinationPath).isAccessible()
          : DESTINATIONFOLDER_NOT_ACCESSIBLE_OR_WRONG_PATH;
      assert project.isOpen() : PROJECT + project.getName() + IS_NOT_OPEN_;

      IPath featureFolderPath =
          SPLMigrationUtils.setupFolder(
              newProject.getFolder(destinationPath).getFolder(project.getName()));

      try {
        migrateClassPathDependentContent(project, featureFolderPath);
      } catch (JavaModelException e) {
        e.printStackTrace();
      }

      //			try
      //			{
      //				if(project.hasNature(ANDROID_NATURE))
      //					copyProjectProperties(project, featureFolderPath);
      //			} catch (CoreException e)
      //			{
      //				e.printStackTrace();
      //			}
    }
  }
Example #6
0
  /**
   * @see
   *     edu.buffalo.cse.green.RefactorHandler#handleMove(edu.buffalo.cse.green.editor.model.RootModel,
   *     org.eclipse.jdt.core.IJavaElement, org.eclipse.jdt.core.IJavaElement)
   */
  public void handleMove(RootModel root, E sourceElement, E targetElement) {
    root.changeProjectElement(sourceElement, targetElement);

    try {
      List<IJavaElement> packages = root.getElementsOfKind(PACKAGE_FRAGMENT);

      // look through packages to match up source and destination elements
      for (IJavaElement packElement : packages) {
        IPackageFragment packFrag = (IPackageFragment) packElement;

        if (JavaModelListener.sameElements(
            packFrag.getAncestor(JAVA_PROJECT), sourceElement.getPrimaryElement())) {
          for (IPackageFragment packFrags : targetElement.getPackageFragments()) {
            // check for the same name of the two packages
            if (packFrag.getElementName().equals(packFrags.getElementName())) {
              PackageRefactorHandler.instance().handleMove(root, packFrag, packFrags);
            }
          }
        }
      }

      root.dispose();
    } catch (JavaModelException e) {
      e.printStackTrace();
    }
  }
 public ASTReader(IJavaProject iJavaProject, IProgressMonitor monitor) {
   if (monitor != null)
     monitor.beginTask("Parsing selected Java Project", getNumberOfCompilationUnits(iJavaProject));
   systemObject = new SystemObject();
   examinedProject = iJavaProject;
   try {
     IPackageFragmentRoot[] iPackageFragmentRoots = iJavaProject.getPackageFragmentRoots();
     for (IPackageFragmentRoot iPackageFragmentRoot : iPackageFragmentRoots) {
       IJavaElement[] children = iPackageFragmentRoot.getChildren();
       for (IJavaElement child : children) {
         if (child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
           IPackageFragment iPackageFragment = (IPackageFragment) child;
           ICompilationUnit[] iCompilationUnits = iPackageFragment.getCompilationUnits();
           for (ICompilationUnit iCompilationUnit : iCompilationUnits) {
             if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
             systemObject.addClasses(parseAST(iCompilationUnit));
             if (monitor != null) monitor.worked(1);
           }
         }
       }
     }
   } catch (JavaModelException e) {
     e.printStackTrace();
   }
   if (monitor != null) monitor.done();
 }
  public void testSmapGeneration2() {
    SmapStratum stratum_role2 = new SmapStratum(ISMAPConstants.OTJ_STRATUM_NAME);

    FileInfo fileinfo = stratum_role2.getOrCreateFileInfo("Team.java", "org/objectteams/Team.java");
    LineInfo lineInfo1 = new LineInfo(OT_CONFINED_GET_TEAM_LINE, 3);
    fileinfo.addLineInfo(lineInfo1);

    LineInfo lineInfo2 =
        new LineInfo(ISMAPConstants.STEP_INTO_LINENUMBER, ISMAPConstants.STEP_INTO_LINENUMBER);
    LineInfo lineInfo3 =
        new LineInfo(ISMAPConstants.STEP_OVER_LINENUMBER, ISMAPConstants.STEP_OVER_LINENUMBER);
    fileinfo.addLineInfo(lineInfo2);
    fileinfo.addLineInfo(lineInfo3);

    stratum_role2.optimize();

    TYPENAME = "__OT__Confined";
    _enclosingTypename = "SuperTeam";
    List<SmapStratum> strata_role2 = new ArrayList<SmapStratum>();
    strata_role2.add(stratum_role2);

    expectedStrata.put(TYPENAME, strata_role2);

    try {
      parseAndCompile(
          new org.eclipse.jdt.core.ICompilationUnit[] {_baseClass, _superTeam, _subTeam});
    } catch (JavaModelException e) {
      fail(e.getMessage());
    }
  }
  /**
   * Gets the fully qualified class name for an active file. For example, its value is foo.bar.Baz.
   *
   * @param file Get fully qualified class file.
   * @return The fully qualified class name. For example,foo.bar.Baz.
   */
  private String getFullyQualifedClassName(IFile file) {
    String fullClassName = "";
    if (file.exists() && file.getName().endsWith(EclipseSensorConstants.JAVA_EXT)) {
      ICompilationUnit compilationUnit = (ICompilationUnit) JavaCore.create(file);
      String className = compilationUnit.getElementName();
      if (className.endsWith(EclipseSensorConstants.JAVA_EXT)) {
        className = className.substring(0, className.length() - 5);
      }

      try {
        IPackageDeclaration[] packageDeclarations = compilationUnit.getPackageDeclarations();
        // Should only have one package declaration
        if (packageDeclarations == null || packageDeclarations.length == 0) {
          fullClassName = className;
        } else {
          fullClassName = packageDeclarations[0].getElementName() + '.' + className;
        }
      } catch (JavaModelException e) {
        // This exception will be thrown if user is working on a Java but did not open
        // it with "Java Perspective". Thus, the Java Model does not exist to parse
        // Java files. So we only log out exception while Eclipse's Java Perspective
        // exits.
        if (!e.isDoesNotExist()) {
          EclipseSensorPlugin.getDefault().log(file.getName(), e);
        }
      }
    }

    return fullClassName;
  }
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator#
   * isSelectedValid(java.lang.Object)
   */
  @Override
  public boolean isSelectedValid(Object element) {
    boolean isValid = false;
    try {
      if (element instanceof IJavaProject) {
        IJavaProject jproject = (IJavaProject) element;
        IPath path = jproject.getProject().getFullPath();
        isValid = (jproject.findPackageFragmentRoot(path) != null);
      } else if (element instanceof IPackageFragmentRoot) {
        IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) element;

        boolean isSrc = (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE);
        boolean isGen =
            packageFragmentRoot.getElementName().equals(IAndroidConstants.GEN_SRC_FOLDER)
                && (packageFragmentRoot.getParent() instanceof IJavaProject);

        isValid = isSrc && !isGen;
      } else {
        isValid = true;
      }
    } catch (JavaModelException e) {
      AndmoreLogger.error(ElementTreeValidator.class, e.getLocalizedMessage(), e);
    }
    return isValid;
  }
  private static void getOpenTabs(IWorkbenchWindow window) {
    openTabs.clear();
    WorkbenchPage activePage = (WorkbenchPage) window.getActivePage();
    IEditorReference[] editorRefs = ((WorkbenchPage) activePage).getSortedEditors();

    // WorkbenchPage.getSortedEditors() returns the editors in activation order (oldest
    // first). We want most recently activated to be first, so reverse the list.
    List<IEditorReference> editorRefsAsList = Arrays.asList(editorRefs);
    Collections.reverse(editorRefsAsList);

    try {
      for (IEditorReference ref : editorRefsAsList) {
        if (ref.getEditorInput() instanceof FileEditorInput) {
          IFile file = ((FileEditorInput) ref.getEditorInput()).getFile();
          IJavaElement editorElt = JavaCore.create(file);
          if (editorElt instanceof ICompilationUnit) {
            openTabs.addAll(Arrays.asList(((ICompilationUnit) editorElt).getAllTypes()));
          }
        }
      }
    } catch (PartInitException e) {
      System.out.print("Exception while getting all open tabs. " + e.getMessage());
      e.printStackTrace();
    } catch (JavaModelException e) {
      System.out.print("Exception while getting all open tabs. " + e.getMessage());
      e.printStackTrace();
    }
  }
Example #12
0
  /** @see edu.buffalo.cse.green.editor.model.commands.DeleteCommand#doDelete() */
  public void doDelete() {
    RootModel root = _typeModel.getRootModel();

    // Remove relationships first
    List<RelationshipModel> rels = root.getRelationships();

    // No iterators here due to CME's (ConcurrentModificationException)
    // Removal of relationships causes modifications to the rels list.
    for (int i = 0; i < rels.size(); i++) {
      IType t = _typeModel.getType();
      RelationshipModel r = rels.get(i);
      if (r.getSourceType() == t || r.getTargetType() == t) {
        DeleteCommand drc = r.getDeleteCommand(DiagramEditor.findProjectEditor(root.getProject()));
        drc.suppressMessage(true);
        drc.execute();
      }
    }

    _typeModel.removeChildren(); // remove fields/methods
    _typeModel.removeFromParent();
    try {
      IType type = _typeModel.getType();
      ICompilationUnit cu = (ICompilationUnit) type.getAncestor(IJavaElement.COMPILATION_UNIT);

      if (type.equals(cu.findPrimaryType())) {
        cu.delete(true, PlugIn.getEmptyProgressMonitor());
      } else {
        type.delete(true, PlugIn.getEmptyProgressMonitor());
      }
    } catch (JavaModelException e) {
      e.printStackTrace();
    }
    root.updateRelationships();
  }
 private String handleBrowse(String filter) {
   IJavaSearchScope scope = null;
   if (_project == null) {
     scope = SearchEngine.createWorkspaceScope();
   } else {
     scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {_project});
   }
   try {
     SelectionDialog dialog =
         JavaUI.createTypeDialog(
             Display.getCurrent().getActiveShell(),
             null,
             scope,
             IJavaElementSearchConstants.CONSIDER_CLASSES,
             false,
             filter.isEmpty() ? "* " : filter);
     if (dialog.open() == SelectionDialog.OK) {
       Object[] result = dialog.getResult();
       if (result.length > 0 && result[0] instanceof IType) {
         return ((IType) result[0]).getFullyQualifiedName();
       }
     }
   } catch (JavaModelException e) {
     e.printStackTrace();
   }
   return null;
 }
  protected List<String> getSourceFolders(IProject project) {
    List<String> result = new ArrayList<String>();
    IJavaProject javaProject = JavaCore.create(project);
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

    try {
      for (IPackageFragmentRoot packageFragmentRoot : javaProject.getPackageFragmentRoots()) {
        if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
          IPath path = packageFragmentRoot.getPath();
          IFolder folder = root.getFolder(path);
          String location = folder.getLocation().toString();

          if (!location.contains("src-gen")) {
            result.add(location);
          }
        }
      }

      for (IProject referencedProject : javaProject.getProject().getReferencedProjects()) {
        if (referencedProject.isAccessible() && referencedProject.hasNature(JavaCore.NATURE_ID)) {
          result.addAll(getSourceFolders(referencedProject));
        }
      }

    } catch (JavaModelException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();

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

    return result;
  }
Example #15
0
 public static String getType(final IField field) {
   try {
     return Signature.toString(field.getTypeSignature());
   } catch (final IllegalArgumentException e) {
     e.printStackTrace();
   } catch (final JavaModelException e) {
     e.printStackTrace();
   }
   return null;
 }
  /** Handle browse package. */
  private void handleBrowsePackage() {

    IPackageFragment[] packages = null;
    IJavaProject javaProject = JavaCore.create(project);
    IJavaElement javaElementArray[] = null;
    ArrayList<IJavaElement> javaElementsList = new ArrayList<IJavaElement>();

    // Si el projecto no esta abierto se cancela el proceso
    if (javaProject.isOpen() == false) {
      MessageDialog.openError(
          getShell(),
          Messages.WizardPageChooseSourceFolderAndPackage_29,
          Messages.WizardPageChooseSourceFolderAndPackage_30);
      return;
    }

    // Lee los paquetes solo del proyecto
    try {
      packages = javaProject.getPackageFragments();

      for (IPackageFragment iPackageFragment : packages) {
        if (iPackageFragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
          javaElementsList.add(iPackageFragment);
        }
      }
      if (javaElementsList.size() > 0) {
        javaElementArray = new IJavaElement[javaElementsList.size()];
        javaElementArray = javaElementsList.toArray(javaElementArray);
      }
    } catch (JavaModelException e) {
      MessageDialog.openError(
          getShell(), Messages.WizardPageChooseSourceFolderAndPackage_31, e.getMessage());
    }

    Shell shell = getShell();
    IJavaSearchScope iJavaSearchScope = SearchEngine.createJavaSearchScope(javaElementArray, false);
    PackageSelectionDialog packageSelectionDialog =
        new PackageSelectionDialog(
            shell,
            new ProgressMonitorDialog(shell),
            PackageSelectionDialog.F_REMOVE_DUPLICATES | PackageSelectionDialog.F_HIDE_EMPTY_INNER,
            iJavaSearchScope);

    packageSelectionDialog.setTitle(Messages.WizardPageChooseSourceFolderAndPackage_32);
    packageSelectionDialog.setMessage(Messages.WizardPageChooseSourceFolderAndPackage_33);

    if (packageSelectionDialog.open() == Window.OK) {
      Object results[] = packageSelectionDialog.getResult();
      if (results != null && results.length > 0) {
        PackageFragment packageFragment = (PackageFragment) results[0];
        txtPackage.setText(packageFragment.getElementName());
        EclipseGeneratorUtil.javaEntityPackage = packageFragment.getElementName();
      }
    }
  }
  private void validatePropertyPackage() {

    IPackageFragmentRoot root = fResourceBundlePackage.getSelectedFragmentRoot();
    if ((root == null) || !root.exists()) {
      setInvalid(
          IDX_BUNDLE_PACKAGE,
          NLSUIMessages.NLSAccessorConfigurationDialog_property_package_root_invalid);
      return;
    }

    IPackageFragment fragment = fResourceBundlePackage.getSelected();
    if ((fragment == null) || !fragment.exists()) {
      setInvalid(
          IDX_BUNDLE_PACKAGE,
          NLSUIMessages.NLSAccessorConfigurationDialog_property_package_invalid);
      return;
    }

    String pkgName = fragment.getElementName();

    IStatus status = JavaConventionsUtil.validatePackageName(pkgName, root);
    if ((pkgName.length() > 0) && (status.getSeverity() == IStatus.ERROR)) {
      setInvalid(IDX_BUNDLE_PACKAGE, status.getMessage());
      return;
    }

    IPath pkgPath = new Path(pkgName.replace('.', IPath.SEPARATOR)).makeRelative();

    IJavaProject project = fRefactoring.getCu().getJavaProject();
    try {
      IJavaElement element = project.findElement(pkgPath);
      if (element == null || !element.exists()) {
        setInvalid(IDX_BUNDLE_PACKAGE, NLSUIMessages.NLSAccessorConfigurationDialog_must_exist);
        return;
      }
      IPackageFragment fPkgFragment = (IPackageFragment) element;
      if (!PackageBrowseAdapter.canAddPackage(fPkgFragment)) {
        setInvalid(
            IDX_BUNDLE_PACKAGE, NLSUIMessages.NLSAccessorConfigurationDialog_incorrect_package);
        return;
      }
      if (!PackageBrowseAdapter.canAddPackageRoot(
          (IPackageFragmentRoot) fPkgFragment.getParent())) {
        setInvalid(
            IDX_BUNDLE_PACKAGE, NLSUIMessages.NLSAccessorConfigurationDialog_incorrect_package);
        return;
      }
    } catch (JavaModelException e) {
      setInvalid(IDX_BUNDLE_PACKAGE, e.getStatus().getMessage());
      return;
    }

    setValid(IDX_BUNDLE_PACKAGE);
  }
Example #18
0
 public void generate(
     ICompilationUnit compilationUnit,
     boolean createPrivateConstructor,
     boolean formatSource,
     List<IField> selectedFields) {
   try {
     System.out.println(compilationUnit.getSource());
   } catch (JavaModelException e) {
     e.printStackTrace();
   }
 }
 private IType getJDTType(JvmType jvmTypeRef) {
   try {
     IJavaProject javaProject =
         javaProjectProvider.getJavaProject(jvmTypeRef.eResource().getResourceSet());
     return javaProject.findType(jvmTypeRef.getQualifiedName());
   } catch (JavaModelException e) {
     // TODO Logging
     e.printStackTrace();
   }
   return null;
 }
 private IJavaElement visit(IParent parent) {
   try {
     for (IJavaElement child : parent.getChildren()) {
       IJavaElement elementFound = visit(child);
       if (elementFound != null) {
         return elementFound;
       }
     }
   } catch (JavaModelException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #21
0
 public static List<IField> findAllFields(final IType clazz) {
   final List<IField> fields = new ArrayList<IField>();
   try {
     for (final IField field : clazz.getFields()) {
       final int flags = field.getFlags();
       final boolean notStatic = !Flags.isStatic(flags);
       if (notStatic) fields.add(field);
     }
   } catch (final JavaModelException e) {
     e.printStackTrace();
   }
   return fields;
 }
 public String getCuttedSourceCode(ICompilationUnit unit) {
   int[] offsets = getSelectionStartAndEnd(unit);
   String source;
   String cutted;
   try {
     source = unit.getSource();
     cutted = source.substring(offsets[0], offsets[1] + 1);
     return cutted;
   } catch (JavaModelException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return null;
 }
 /** @since 2.4 */
 @Override
 public Map<URI, IStorage> getAllEntries(IPackageFragmentRoot root) {
   try {
     IResource underlyingResource = root.getUnderlyingResource();
     if (underlyingResource instanceof IFolder) {
       return host.getAllEntries((IFolder) underlyingResource);
     }
   } catch (JavaModelException e) {
     if (!e.isDoesNotExist()) log.error(e.getMessage(), e);
     return emptyMap();
   }
   PackageFragmentRootData data = getData(root);
   return data.uri2Storage;
 }
Example #24
0
 /**
  * Gets the classpath.
  *
  * @param project the project
  * @return the classpath
  * @see
  *     net.kbserve.pyjdt.properties.models.ICPEType#getClasspath(org.eclipse.core.resources.IProject)
  */
 @Override
 public IClasspathEntry getClasspath(IProject project) {
   IJavaProject javaProject = JavaCore.create(project);
   try {
     for (IClasspathEntry icp : javaProject.getRawClasspath()) {
       if (makeStringPath(icp).equals(getPath())) {
         return icp;
       }
     }
   } catch (JavaModelException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #25
0
 private IStatus validateClassFile() {
   IPackageFragmentRoot root = getPackageFragmentRoot();
   try {
     if (root.getKind() != IPackageFragmentRoot.K_BINARY)
       return new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, root);
   } catch (JavaModelException e) {
     return e.getJavaModelStatus();
   }
   IJavaProject project = getJavaProject();
   return JavaConventions.validateClassFileName(
       getElementName(),
       project.getOption(JavaCore.COMPILER_SOURCE, true),
       project.getOption(JavaCore.COMPILER_COMPLIANCE, true));
 }
Example #26
0
 private static PackageFragment defaultPackage(IProject proj) {
   IJavaProject jp = JavaCore.create(proj);
   try {
     IPackageFragment[] packageFragments = jp.getPackageFragments();
     for (IPackageFragment frag : packageFragments) {
       if (frag.getElementName().equals(DEFAULT_PACKAGE_NAME)) return (PackageFragment) frag;
     }
     return null;
   } catch (JavaModelException e) {
     e.printStackTrace();
     System.out.printf("Yikes!%n");
     return null;
   }
 }
  public void initialize(String variable) {
    IPreferenceStore preferenceStore = GradlePlugin.getPlugin().getPreferenceStore();
    String gradleCache = preferenceStore.getString(IGradlePreferenceConstants.GRADLE_CACHE);

    // create directory if it not already exists
    File gradleCacheDir = new File(gradleCache);
    gradleCacheDir.mkdirs();
    try {
      JavaCore.setClasspathVariable(variable, new Path(gradleCacheDir.getAbsolutePath()), null);
    } catch (JavaModelException e) {

      // TODO FIX ERROR HANDLING !!!
      e.printStackTrace();
    }
  }
 /** @since 2.4 */
 private void updateCache(IJavaProject project) {
   Set<PackageFragmentRootData> datas = newHashSet();
   try {
     if (project.exists() && project.getProject().isAccessible()) {
       for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
         boolean isCachable = root.isArchive() || root.isExternal();
         if (isCachable) datas.add(getCachedData(root));
       }
     }
   } catch (JavaModelException e) {
     if (!e.isDoesNotExist())
       log.error("Error getting package fragments roots of " + project.getElementName(), e);
   } finally {
     clearCache(project, datas);
   }
 }
  public IArchive createDefaultConfiguration(String projectName, IProgressMonitor monitor) {
    // IPackageType t = this;
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    Assert.isNotNull(project);

    IJavaProject javaProject = JavaCore.create(project);
    Assert.isNotNull(javaProject);

    if (monitor == null) monitor = new NullProgressMonitor();

    monitor.beginTask(
        ArchivesCore.bind(ArchivesCoreMessages.CreatingDefaultJarConfig, project.getName()), 2);

    IPath outputPath;
    try {
      outputPath = javaProject.getOutputLocation();
    } catch (JavaModelException e) {
      ArchivesCore.getInstance().getLogger().log(IStatus.WARNING, e.getMessage(), e);
      return null;
    }

    outputPath = outputPath.removeFirstSegments(1);
    IContainer outputContainer = project.getFolder(outputPath);

    IArchive jar = new ArchiveImpl();

    jar.setDestinationPath(project.getLocation());
    jar.setInWorkspace(true);
    jar.setExploded(false);
    jar.setName(project.getName() + ".jar"); // $NON-NLS-1$
    jar.setArchiveType(this);

    IArchiveStandardFileSet classes = new ArchiveFileSetImpl();
    classes.setIncludesPattern("**/*"); // $NON-NLS-1$
    classes.setRawSourcePath(outputContainer.getFullPath().toString());
    classes.setInWorkspace(true);

    try {
      jar.addChild(classes);
    } catch (ArchivesModelException ame) {
    }

    monitor.worked(1);
    monitor.done();

    return jar;
  }
  private void setContentsToCU(ICompilationUnit unit, String value) {
    if (unit == null) {
      return;
    }

    synchronized (unit) {
      IBuffer buffer;
      try {
        buffer = unit.getBuffer();
        if (buffer != null) {
          buffer.setContents(value);
        }
      } catch (JavaModelException e) {
        e.printStackTrace();
      }
    }
  }