/**
  * Validates that the version of the given plug-in is available in the registry. Adds a warning if
  * the plug-in could not be found.
  *
  * @param plugin xml element describing the plug-in to look for in the registry
  * @param attr set of element attributes
  */
 private void validateVersion(Element plugin, Attr attr) {
   String id = plugin.getAttribute("id"); // $NON-NLS-1$
   String version = plugin.getAttribute("version"); // $NON-NLS-1$
   if (id.trim().length() == 0
       || version.trim().length() == 0
       || version.equals("0.0.0")) // $NON-NLS-1$
   return;
   ModelEntry entry = MonitorRegistry.findEntry(id);
   if (entry != null) {
     IMonitorModelBase[] allModels = entry.getActiveModels();
     for (int i = 0; i < allModels.length; i++) {
       IMonitorModelBase availablePlugin = allModels[i];
       if (id.equals(availablePlugin.getMonitorBase().getId())) {
         if (version.equals(availablePlugin.getMonitorBase().getVersion())) {
           return;
         }
       }
     }
   }
   report(
       NLS.bind(
           MDECoreMessages.Builders_Feature_mismatchPluginVersion, new String[] {version, id}),
       getLine(plugin, attr.getName()),
       CompilerFlags.WARNING,
       MDEMarkerFactory.CAT_OTHER);
 }
  private void validateUnpack(Element parent) {
    int severity = CompilerFlags.getFlag(fProject, CompilerFlags.F_UNRESOLVED_PLUGINS);
    if (severity == CompilerFlags.IGNORE) {
      return;
    }
    if (severity == CompilerFlags.ERROR) {
      // this might not be an error, so max the flag at WARNING level.
      severity = CompilerFlags.WARNING;
    }
    String unpack = parent.getAttribute("unpack"); // $NON-NLS-1$
    IMonitorModelBase pModel = MonitorRegistry.findModel(parent.getAttribute("id")); // $NON-NLS-1$
    if (pModel == null) {
      return;
    }

    if (pModel instanceof IBundlePluginModel) {
      IBundlePluginModel bModel = (IBundlePluginModel) pModel;
      IManifestHeader header =
          bModel
              .getBundleModel()
              .getBundle()
              .getManifestHeader(ICoreConstants.ECLIPSE_BUNDLE_SHAPE);
      if (header != null) {
        String value = header.getValue();
        String unpackValue =
            "true".equals(unpack) ? "jar" : "dir"; // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        if (value != null && !value.equalsIgnoreCase(unpackValue)) {
          String message =
              NLS.bind(
                  MDECoreMessages.Builders_Feature_mismatchUnpackBundleShape,
                  (new String[] {
                    "unpack=" + unpack, parent.getAttribute("id"), "Eclipse-BundleShape: " + value
                  })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          report(message, getLine(parent), severity, MDEMarkerFactory.CAT_OTHER);
        }
      }
    }

    if ("true".equals(unpack)
        && !CoreUtility.guessUnpack(pModel.getBundleDescription())) { // $NON-NLS-1$
      String message =
          NLS.bind(
              MDECoreMessages.Builders_Feature_missingUnpackFalse,
              (new String[] {
                parent.getAttribute("id"), "unpack=\"false\""
              })); //$NON-NLS-1$ //$NON-NLS-2$
      report(message, getLine(parent), severity, MDEMarkerFactory.CAT_OTHER);
    }
  }
 private static boolean hasChanged(IMonitorModelBase model, long timestamp) {
   if (model.getUnderlyingResource() != null) {
     File[] files = new File(model.getInstallLocation()).listFiles();
     if (files != null) {
       for (int i = 0; i < files.length; i++) {
         if (files[i].isDirectory()) continue;
         String name = files[i].getName();
         if (name.startsWith(Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME)
             && name.endsWith(".properties") // $NON-NLS-1$
             && files[i].lastModified() > timestamp) {
           return true;
         }
       }
     }
   }
   return false;
 }
 public ExtensionsErrorReporter(IFile file) {
   super(file);
   fModel = MonitorRegistry.findModel(file.getProject());
   try {
     if (fModel != null && fModel.getUnderlyingResource() != null)
       fBuildModel = ClasspathUtilCore.getBuild(fModel);
   } catch (CoreException e) {
   }
 }
 private static String[] getValue(BundleDescription bundle, MDEState state) {
   IMonitorModelBase model = MonitorRegistry.findModel(bundle);
   String[] result = null;
   if (model != null) {
     IMonitorLibrary[] libs = model.getMonitorBase().getLibraries();
     result = new String[libs.length];
     for (int i = 0; i < libs.length; i++) {
       result[i] = libs[i].getName();
     }
   } else {
     String[] libs = state.getLibraryNames(bundle.getBundleId());
     result = new String[libs.length];
     for (int i = 0; i < libs.length; i++) {
       result[i] = libs[i];
     }
   }
   if (result.length == 0) return new String[] {"."}; // $NON-NLS-1$
   return result;
 }
  public static String getTargetVersionString() {
    IMonitorModelBase model = MonitorRegistry.findModel(IPDEBuildConstants.BUNDLE_OSGI);
    if (model == null) return ICoreConstants.TARGET37;

    String version = model.getMonitorBase().getVersion();
    if (VersionUtil.validateVersion(version).getSeverity() == IStatus.OK) {
      Version vid = new Version(version);
      int major = vid.getMajor();
      int minor = vid.getMinor();
      if (major == 3 && minor == 0) return ICoreConstants.TARGET30;
      if (major == 3 && minor == 1) return ICoreConstants.TARGET31;
      if (major == 3 && minor == 2) return ICoreConstants.TARGET32;
      if (major == 3 && minor == 3) return ICoreConstants.TARGET33;
      if (major == 3 && minor == 4) return ICoreConstants.TARGET34;
      if (major == 3 && minor == 5) return ICoreConstants.TARGET35;
      if (major == 3 && minor == 6) return ICoreConstants.TARGET36;
    }
    return ICoreConstants.TARGET37;
  }
  private String getBundles(boolean defaultAuto) {
    StringBuffer buffer = new StringBuffer();
    Iterator iter = fModels.keySet().iterator();
    while (iter.hasNext()) {
      IMonitorModelBase model = (IMonitorModelBase) iter.next();
      String id = model.getMonitorBase().getId();
      if (!IPDEBuildConstants.BUNDLE_OSGI.equals(id)) {
        if (buffer.length() > 0) buffer.append(","); // $NON-NLS-1$
        buffer.append(LaunchConfigurationHelper.getBundleURL(model, true));

        // fragments must not be started or have a start level
        if (model instanceof IFragmentModel) continue;

        String data = fModels.get(model).toString();
        appendStartData(buffer, data, defaultAuto);
      }
    }
    return buffer.toString();
  }
 public static boolean matchesCurrentEnvironment(IMonitorModelBase model) {
   BundleContext context = MDECore.getDefault().getBundleContext();
   Dictionary environment = getTargetEnvironment();
   BundleDescription bundle = model.getBundleDescription();
   String filterSpec = bundle != null ? bundle.getPlatformFilter() : null;
   try {
     return filterSpec == null || context.createFilter(filterSpec).match(environment);
   } catch (InvalidSyntaxException e) {
     return false;
   }
 }
 private void validatePluginID(Element element, Attr attr, boolean isFragment) {
   String id = attr.getValue();
   if (!validatePluginID(element, attr)) {
     return;
   }
   int severity = CompilerFlags.getFlag(fProject, CompilerFlags.F_UNRESOLVED_PLUGINS);
   if (severity != CompilerFlags.IGNORE) {
     IMonitorModelBase model = MonitorRegistry.findModel(id);
     if (model == null
         || !model.isEnabled()
         || (isFragment && !model.isFragmentModel())
         || (!isFragment && model.isFragmentModel())) {
       report(
           NLS.bind(MDECoreMessages.Builders_Feature_reference, id),
           getLine(element, attr.getName()),
           severity,
           MDEMarkerFactory.CAT_OTHER);
     }
   }
 }
 protected void addBundleManifestChange(CompositeChange result, IProgressMonitor pm)
     throws CoreException {
   super.addBundleManifestChange(result, pm);
   IMonitorModelBase model = MonitorRegistry.findModel(fProject);
   if (model != null) {
     BundleDescription desc = model.getBundleDescription();
     if (desc != null) {
       BundleDescription[] dependents = desc.getDependents();
       for (int i = 0; i < dependents.length; i++) {
         if (isAffected(desc, dependents[i])) {
           IMonitorModelBase candidate = MonitorRegistry.findModel(dependents[i]);
           if (candidate instanceof IBundlePluginModelBase) {
             IFile file = (IFile) candidate.getUnderlyingResource();
             addBundleManifestChange(file, result, pm);
           }
         }
       }
     }
   }
 }
  /*
   * (non-Javadoc)
   * @see org.eclipse.pde.ui.launcher.AbstractPDELaunchConfiguration#preLaunchCheck(org.eclipse.debug.core.ILaunchConfiguration, org.eclipse.debug.core.ILaunch, org.eclipse.core.runtime.IProgressMonitor)
   */
  protected void preLaunchCheck(
      ILaunchConfiguration configuration, ILaunch launch, IProgressMonitor monitor)
      throws CoreException {
    fModels = BundleLauncherHelper.getMergedBundleMap(configuration, true);
    fAllBundles = new HashMap(fModels.size());
    Iterator iter = fModels.keySet().iterator();
    while (iter.hasNext()) {
      IMonitorModelBase model = (IMonitorModelBase) iter.next();
      fAllBundles.put(model.getMonitorBase().getId(), model);
    }

    if (!fAllBundles.containsKey(IPDEBuildConstants.BUNDLE_OSGI)) {
      // implicitly add it
      IMonitorModelBase model = MonitorRegistry.findModel(IPDEBuildConstants.BUNDLE_OSGI);
      if (model != null) {
        fModels.put(model, "default:default"); // $NON-NLS-1$
        fAllBundles.put(IPDEBuildConstants.BUNDLE_OSGI, model);
      } else {
        String message = MDEMessages.EquinoxLaunchConfiguration_oldTarget;
        throw new CoreException(LauncherUtils.createErrorStatus(message));
      }
    }
    super.preLaunchCheck(configuration, launch, monitor);
  }
  public void validateContent(IProgressMonitor monitor) {
    Element element = getDocumentRoot();
    if (element == null) return;
    String elementName = element.getNodeName();
    if (!"plugin".equals(elementName)
        && !"fragment".equals(elementName)) { // $NON-NLS-1$ //$NON-NLS-2$
      reportIllegalElement(element, CompilerFlags.ERROR);
    } else {
      int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_DEPRECATED);
      if (severity != CompilerFlags.IGNORE) {
        NamedNodeMap attrs = element.getAttributes();
        for (int i = 0; i < attrs.getLength(); i++) {
          reportUnusedAttribute(element, attrs.item(i).getNodeName(), severity);
        }
      }

      NodeList children = element.getChildNodes();
      for (int i = 0; i < children.getLength(); i++) {
        if (monitor.isCanceled()) break;
        Element child = (Element) children.item(i);
        String name = child.getNodeName();
        if (name.equals("extension")) { // $NON-NLS-1$
          validateExtension(child);
        } else if (name.equals("extension-point")) { // $NON-NLS-1$
          validateExtensionPoint(child);
        } else {
          if (!name.equals("runtime") && !name.equals("requires")) { // $NON-NLS-1$ //$NON-NLS-2$
            severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ELEMENT);
            if (severity != CompilerFlags.IGNORE) reportIllegalElement(child, severity);
          } else {
            severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_DEPRECATED);
            if (severity != CompilerFlags.IGNORE) reportUnusedElement(child, severity);
          }
        }
      }

      IExtensions extensions = fModel.getExtensions();
      if (extensions != null
          && extensions.getExtensions().length == 0
          && extensions.getExtensionPoints().length == 0)
        report(
            MDECoreMessages.Builders_Manifest_useless_file,
            -1,
            IMarker.SEVERITY_WARNING,
            MDEMarkerFactory.P_USELESS_FILE,
            MDEMarkerFactory.CAT_OTHER);
    }
  }
  protected void validateJavaAttribute(Element element, Attr attr) {
    String value = attr.getValue();
    IJavaProject javaProject = JavaCore.create(fFile.getProject());

    // be careful: people have the option to use the format:
    // fullqualifiedName:staticMethod
    int index = value.indexOf(":"); // $NON-NLS-1$
    if (index != -1) value = value.substring(0, index);

    // assume we're on the classpath already
    boolean onClasspath = true;
    int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_CLASS);
    if (severity != CompilerFlags.IGNORE && javaProject.isOpen()) {
      onClasspath = PDEJavaHelper.isOnClasspath(value, javaProject);
      if (!onClasspath) {
        report(
            NLS.bind(
                MDECoreMessages.Builders_Manifest_class, (new String[] {value, attr.getName()})),
            getLine(element, attr.getName()),
            severity,
            MDEMarkerFactory.P_UNKNOWN_CLASS,
            element,
            attr.getName() + F_ATT_VALUE_PREFIX + attr.getValue(),
            MDEMarkerFactory.CAT_FATAL);
      }
    }

    severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_DISCOURAGED_CLASS);
    if (severity != CompilerFlags.IGNORE && javaProject.isOpen()) {
      BundleDescription desc = fModel.getBundleDescription();
      if (desc == null) return;
      // only check if we're discouraged if there is something on the classpath
      if (onClasspath && PDEJavaHelper.isDiscouraged(value, javaProject, desc)) {
        report(
            NLS.bind(
                MDECoreMessages.Builders_Manifest_discouragedClass,
                (new String[] {value, attr.getName()})),
            getLine(element, attr.getName()),
            severity,
            MDEMarkerFactory.M_DISCOURAGED_CLASS,
            element,
            attr.getName() + F_ATT_VALUE_PREFIX + attr.getValue(),
            MDEMarkerFactory.CAT_OTHER);
      }
    }
  }
  private void validateInternalExtensionAttribute(Element element, ISchemaElement schemaElement) {
    int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_INTERNAL);
    if (severity == CompilerFlags.IGNORE) return;

    if (schemaElement instanceof ISchemaRootElement) {
      ISchemaRootElement rootElement = (ISchemaRootElement) schemaElement;
      String epid = schemaElement.getSchema().getPluginId();
      String pid = fModel.getMonitorBase().getId();
      if (epid == null || pid == null) return;
      if (rootElement.isInternal() && !epid.equals(pid)) {
        String point = element.getAttribute("point"); // $NON-NLS-1$
        if (point == null) return; // should never come to this...
        report(
            NLS.bind(MDECoreMessages.Builders_Manifest_internal_rootElement, point),
            getLine(element, "point"),
            severity,
            MDEMarkerFactory.CAT_DEPRECATION); // $NON-NLS-1$
      }
    }
  }
 private boolean isPerfectMatch(IMonitorModelBase model, IPath path) {
   return model == null ? false : path.equals(new Path(model.getInstallLocation()));
 }
  private boolean resourceExists(String location) {
    String bundleJar = null;
    IPath path = new Path(location);
    if ("platform:".equals(path.getDevice()) && path.segmentCount() > 2) { // $NON-NLS-1$
      if ("plugin".equals(path.segment(0))) { // $NON-NLS-1$
        String id = path.segment(1);
        IMonitorModelBase model = MonitorRegistry.findModel(id);
        if (model != null && model.isEnabled()) {
          path = path.setDevice(null).removeFirstSegments(2);
          String bundleLocation = model.getInstallLocation();
          if (bundleLocation.endsWith(".jar")) { // $NON-NLS-1$
            bundleJar = bundleLocation;
          } else {
            path = new Path(model.getInstallLocation()).append(path);
          }
          location = path.toString();
        }
      }
    } else if (path.getDevice() == null
        && path.segmentCount() > 3
        && "platform:".equals(path.segment(0))) { // $NON-NLS-1$
      if ("plugin".equals(path.segment(1))) { // $NON-NLS-1$
        String id = path.segment(2);
        IMonitorModelBase model = MonitorRegistry.findModel(id);
        if (model != null && model.isEnabled()) {
          path = path.removeFirstSegments(3);
          String bundleLocation = model.getInstallLocation();
          if (bundleLocation.endsWith(".jar")) { // $NON-NLS-1$
            bundleJar = bundleLocation;
          } else {
            path = new Path(model.getInstallLocation()).append(path);
          }
          location = path.toString();
        }
      }
    }

    ArrayList paths = new ArrayList();
    if (location.indexOf("$nl$") != -1) { // $NON-NLS-1$
      StringTokenizer tokenizer = new StringTokenizer(TargetPlatform.getNL(), "_"); // $NON-NLS-1$
      String language = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
      String country = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
      if (language != null && country != null)
        paths.add(
            location.replaceAll(
                "\\$nl\\$",
                "nl"
                    + IPath.SEPARATOR
                    + language
                    + IPath.SEPARATOR
                    + country)); //$NON-NLS-1$ //$NON-NLS-2$
      if (language != null)
        paths.add(
            location.replaceAll(
                "\\$nl\\$", "nl" + IPath.SEPARATOR + language)); // $NON-NLS-1$ //$NON-NLS-2$
      paths.add(location.replaceAll("\\$nl\\$", "")); // $NON-NLS-1$ //$NON-NLS-2$
    } else {
      paths.add(location);
    }

    for (int i = 0; i < paths.size(); i++) {
      if (bundleJar == null) {
        IPath currPath = new Path(paths.get(i).toString());
        if (currPath.isAbsolute() && currPath.toFile().exists()) return true;
        if (PDEProject.getBundleRoot(fFile.getProject()).findMember(currPath) != null) return true;
        if (fBuildModel != null
            && fBuildModel.getEntry("source." + paths.get(i)) != null) // $NON-NLS-1$
        return true;
      } else {
        if (CoreUtility.jarContainsResource(new File(bundleJar), paths.get(i).toString(), false))
          return true;
      }
    }

    return false;
  }