/**
  * Validate the given compilation unit name for the given source and compliance levels.
  *
  * <p>A compilation unit name must obey the following rules:
  *
  * <ul>
  *   <li>it must not be null
  *   <li>it must be suffixed by a dot ('.') followed by one of the {@link
  *       JavaCore#getJavaLikeExtensions() Java-like extensions}
  *   <li>its prefix must be a valid identifier
  *   <li>it must not contain any characters or substrings that are not valid on the file system on
  *       which workspace root is located.
  * </ul>
  *
  * @param name the name of a compilation unit
  * @param sourceLevel the source level
  * @param complianceLevel the compliance level
  * @return a status object with code <code>IStatus.OK</code> if the given name is valid as a
  *     compilation unit name, otherwise a status object indicating what is wrong with the name
  * @since 3.3
  */
 public static IStatus validateCompilationUnitName(
     String name, String sourceLevel, String complianceLevel) {
   if (name == null) {
     return new Status(
         IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.convention_unit_nullName, null);
   }
   if (!org.aspectj.org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(name)) {
     return new Status(
         IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.convention_unit_notJavaName, null);
   }
   String identifier;
   int index;
   index = name.lastIndexOf('.');
   if (index == -1) {
     return new Status(
         IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.convention_unit_notJavaName, null);
   }
   identifier = name.substring(0, index);
   // JSR-175 metadata strongly recommends "package-info.java" as the
   // file in which to store package annotations and
   // the package-level spec (replaces package.html)
   if (!identifier.equals(PACKAGE_INFO)) {
     IStatus status = validateIdentifier(identifier, sourceLevel, complianceLevel);
     if (!status.isOK()) {
       return status;
     }
   }
   IStatus status = ResourcesPlugin.getWorkspace().validateName(name, IResource.FILE);
   if (!status.isOK()) {
     return status;
   }
   return JavaModelStatus.VERIFIED_OK;
 }
 public long getSize(
     IProvisioningPlan provisioningPlan,
     IProfile profile,
     IEngine engine,
     ProvisioningContext context,
     IProgressMonitor monitor) {
   // If there is nothing to size, return 0
   if (provisioningPlan == null) {
     return SIZE_NOTAPPLICABLE;
   }
   if (((ProvisioningPlan) provisioningPlan).getOperands().length == 0) {
     return 0;
   }
   long installPlanSize = 0;
   if (provisioningPlan.getInstallerPlan() != null) {
     SizingPhaseSet set = new SizingPhaseSet(new Sizing(100));
     IStatus status = engine.perform(provisioningPlan, set, null);
     if (status.isOK()) {
       installPlanSize = set.getSizing().getDiskSize();
     }
   }
   SizingPhaseSet set = new SizingPhaseSet(new Sizing(100));
   IStatus status = engine.perform(provisioningPlan, set, null);
   if (status.isOK()) {
     return installPlanSize + set.getSizing().getDiskSize();
   }
   return SIZE_UNAVAILABLE;
 }
示例#3
0
  public IStatus service(Command command, IProcess context)
      throws InterruptedException, CoreException {
    if (!(command instanceof RepeatWith)) {
      return Status.CANCEL_STATUS;
    }

    RepeatWith repeatWith = (RepeatWith) command;
    Command todo = repeatWith.getCommand();
    ISession session = context.getSession();
    for (Object cmd : repeatWith.getCommands()) {
      Command prefix = getCommand(cmd);
      IPipe pipe = session.createPipe();
      IStatus status = session.execute(prefix, null, pipe).waitFor();
      if (!status.isOK()) {
        return status;
      }
      IPipe output = session.createPipe();
      status = session.execute(todo, pipe, output).waitFor();
      if (!status.isOK()) {
        return status;
      }
      for (Object obj : CoreUtils.readPipeContent(output)) {
        context.getOutput().write(obj);
      }
    }
    return Status.OK_STATUS;
  }
  public void createProject(
      AndroidSDK target, String projectName, File path, String activity, String packageName)
      throws CoreException {
    IStatus status = HybridProjectConventions.validateProjectName(projectName);
    if (!status.isOK()) throw new CoreException(status);
    // activity class name matches the project name
    status = HybridProjectConventions.validateProjectName(activity);
    if (!status.isOK()) throw new CoreException(status);

    status = HybridProjectConventions.validateProjectID(packageName);
    if (!status.isOK()) throw new CoreException(status);

    ExternalProcessUtility processUtility = new ExternalProcessUtility();
    StringBuilder command = new StringBuilder();
    command.append(getAndroidCommand());
    command.append(" create project");
    command.append(" --target ").append(target.getId());
    command.append(" --path ").append('"').append(path.getPath()).append('"');
    command.append(" --name ").append('"').append(projectName).append('"');
    command.append(" --activity ").append(activity);
    command.append(" --package ").append(packageName);

    CreateProjectResultParser parser = new CreateProjectResultParser();
    processUtility.execSync(
        command.toString(), null, parser, parser, new NullProgressMonitor(), null, null);
    if (parser.getErrorString() != null) {
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              AndroidCore.PLUGIN_ID,
              "Error creating the Android project: " + parser.getErrorString()));
    }
  }
  public static IStatus collectProposals(
      IInvocationContext context,
      IAnnotationModel model,
      Annotation[] annotations,
      boolean addQuickFixes,
      boolean addQuickAssists,
      Collection<IDartCompletionProposal> proposals) {
    List<ProblemLocation> problems = Lists.newArrayList();

    // collect problem locations and corrections from marker annotations
    for (int i = 0; i < annotations.length; i++) {
      Annotation curr = annotations[i];
      ProblemLocation problemLocation = null;
      if (curr instanceof IJavaAnnotation) {
        problemLocation = getProblemLocation((IJavaAnnotation) curr, model);
        if (problemLocation != null) {
          problems.add(problemLocation);
        }
      }
      if (problemLocation == null && addQuickFixes && curr instanceof SimpleMarkerAnnotation) {
        collectMarkerProposals((SimpleMarkerAnnotation) curr, proposals);
      }
    }
    MultiStatus resStatus = null;

    IProblemLocation[] problemLocations = problems.toArray(new IProblemLocation[problems.size()]);
    if (addQuickFixes) {
      IStatus status = collectCorrections(context, problemLocations, proposals);
      if (!status.isOK()) {
        resStatus =
            new MultiStatus(
                DartUI.ID_PLUGIN,
                IStatus.ERROR,
                CorrectionMessages.JavaCorrectionProcessor_error_quickfix_message,
                null);
        resStatus.add(status);
      }
    }

    if (addQuickAssists) {
      IStatus status = collectAssists(context, problemLocations, proposals);
      if (!status.isOK()) {
        if (resStatus == null) {
          resStatus =
              new MultiStatus(
                  DartUI.ID_PLUGIN,
                  IStatus.ERROR,
                  CorrectionMessages.JavaCorrectionProcessor_error_quickassist_message,
                  null);
        }
        resStatus.add(status);
      }
    }
    if (resStatus != null) {
      return resStatus;
    }
    return Status.OK_STATUS;
  }
  private void validateFolders() {
    boolean useFolders = fFoldersAsSourceFolder.getSelection();

    fSrcFolderNameText.setEnabled(useFolders);
    fBinFolderNameText.setEnabled(useFolders);
    fSrcFolderNameLabel.setEnabled(useFolders);
    fBinFolderNameLabel.setEnabled(useFolders);
    if (useFolders) {
      String srcName = fSrcFolderNameText.getText();
      String binName = fBinFolderNameText.getText();
      if (srcName.length() + binName.length() == 0) {
        updateStatus(
            new StatusInfo(
                IStatus.ERROR,
                PreferencesMessages.NewJavaProjectPreferencePage_folders_error_namesempty));
        return;
      }
      IWorkspace workspace = JavaPlugin.getWorkspace();
      IProject dmy = workspace.getRoot().getProject("project"); // $NON-NLS-1$

      IStatus status;
      IPath srcPath = dmy.getFullPath().append(srcName);
      if (srcName.length() != 0) {
        status = workspace.validatePath(srcPath.toString(), IResource.FOLDER);
        if (!status.isOK()) {
          String message =
              Messages.format(
                  PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidsrcname,
                  status.getMessage());
          updateStatus(new StatusInfo(IStatus.ERROR, message));
          return;
        }
      }
      IPath binPath = dmy.getFullPath().append(binName);
      if (binName.length() != 0) {
        status = workspace.validatePath(binPath.toString(), IResource.FOLDER);
        if (!status.isOK()) {
          String message =
              Messages.format(
                  PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidbinname,
                  status.getMessage());
          updateStatus(new StatusInfo(IStatus.ERROR, message));
          return;
        }
      }
      IClasspathEntry entry = JavaCore.newSourceEntry(srcPath);
      status =
          JavaConventions.validateClasspath(
              JavaCore.create(dmy), new IClasspathEntry[] {entry}, binPath);
      if (!status.isOK()) {
        String message = PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidcp;
        updateStatus(new StatusInfo(IStatus.ERROR, message));
        return;
      }
    }
    updateStatus(new StatusInfo()); // set to OK
  }
  /**
   * Perform the redo. All validity checks have already occurred.
   *
   * @param monitor
   * @param operation
   */
  private IStatus doRedo(IProgressMonitor monitor, IAdaptable info, IUndoableOperation operation)
      throws ExecutionException {

    IStatus status = getRedoApproval(operation, info);
    if (status.isOK()) {
      notifyAboutToRedo(operation);
      try {
        status = operation.redo(monitor, info);
      } catch (OperationCanceledException e) {
        status = Status.CANCEL_STATUS;
      } catch (ExecutionException e) {
        notifyNotOK(operation);
        if (DEBUG_OPERATION_HISTORY_UNEXPECTED) {
          Tracing.printTrace(
              "OPERATIONHISTORY", //$NON-NLS-1$
              "ExecutionException while redoing " + operation); // $NON-NLS-1$
        }
        throw e;
      } catch (Exception e) {
        notifyNotOK(operation);
        if (DEBUG_OPERATION_HISTORY_UNEXPECTED) {
          Tracing.printTrace(
              "OPERATIONHISTORY", //$NON-NLS-1$
              "Exception while redoing " + operation); // $NON-NLS-1$
        }
        throw new ExecutionException(
            "While redoing the operation, an exception occurred", e); // $NON-NLS-1$
      }
    }

    // if successful, the operation is removed from the redo history and
    // placed back in the undo history.
    if (status.isOK()) {
      boolean addedToUndo = true;
      synchronized (undoRedoHistoryLock) {
        redoList.remove(operation);
        if (checkUndoLimit(operation)) {
          undoList.add(operation);
        } else {
          addedToUndo = false;
        }
      }
      // dispose the operation since we could not add it to the
      // stack and will no longer have a reference to it.
      if (!addedToUndo) {
        operation.dispose();
      }

      // notify listeners must happen after history is updated
      notifyRedone(operation);
    } else {
      notifyNotOK(operation, status);
    }

    return status;
  }
  @Override
  public boolean performFinish() {
    IStatus status = Status.OK_STATUS;
    if (destinationPage.isFolder()) status = generateFolder(destinationPage.getFolderPath());
    else status = generateJar(destinationPage.getJarPath());

    if (!status.isOK()) ErrorDialog.openError(getShell(), "Error", null, status);

    return status.isOK();
  }
 @Override
 public boolean handleResult(final Shell shell, final IStatus resultStatus) {
   if (!resultStatus.isOK()) KalypsoCorePlugin.getDefault().getLog().log(resultStatus);
   ErrorDialog.openError(
       shell,
       Messages.getString("org.kalypso.model.flood.ui.map.operations.ImportTinOperation.6"),
       Messages.getString("org.kalypso.model.flood.ui.map.operations.ImportTinOperation.7"),
       resultStatus); //$NON-NLS-1$ //$NON-NLS-2$
   return resultStatus.isOK();
 }
  /**
   * Tests a JDT feature bundle container contains the appropriate bundles for a specific OS.
   *
   * @throws Exception
   */
  public void testMacOSFeatureBundleContainer() throws Exception {
    // extract the feature
    IPath location = extractModifiedFeatures();

    ITargetDefinition definition = getNewTarget();
    definition.setOS(Platform.OS_MACOSX);
    ITargetLocation container =
        getTargetService().newFeatureLocation(location.toOSString(), "org.eclipse.jdt", null);
    container.resolve(definition, null);
    TargetBundle[] bundles = container.getBundles();

    List expected = new ArrayList();
    expected.add("org.eclipse.jdt");
    expected.add("org.eclipse.jdt.launching");
    // 2 versions of JUnit
    expected.add("org.junit");
    expected.add("org.junit");
    expected.add("org.junit4");
    expected.add("org.eclipse.jdt.launching.macosx");

    assertEquals("Wrong number of bundles in JDT feature", expected.size(), bundles.length);
    for (int i = 0; i < bundles.length; i++) {
      String symbolicName = bundles[i].getBundleInfo().getSymbolicName();
      expected.remove(symbolicName);
      if (symbolicName.equals("org.eclipse.jdt.launching.macosx")) {
        // the bundle should be missing unless on Mac
        IStatus status = bundles[i].getStatus();
        if (Platform.getOS().equals(Platform.OS_MACOSX)) {
          assertTrue("Mac bundle should be present", status.isOK());
        } else {
          assertFalse("Mac bundle should be missing", status.isOK());
          assertEquals(
              "Mac bundle should be mssing",
              TargetBundle.STATUS_PLUGIN_DOES_NOT_EXIST,
              status.getCode());
        }
      }
    }
    Iterator iterator = expected.iterator();
    while (iterator.hasNext()) {
      String name = (String) iterator.next();
      System.err.println("Missing: " + name);
    }
    assertTrue("Wrong bundles in JDT feature", expected.isEmpty());

    // should be no source bundles
    for (int i = 0; i < bundles.length; i++) {
      TargetBundle bundle = bundles[i];
      assertFalse("Should be no source bundles", bundle.isSourceBundle());
    }
  }
  /**
   * Validate the given Java type name, either simple or qualified, for the given source and
   * compliance levels.
   *
   * <p>For example, <code>"java.lang.Object"</code>, or <code>"Object"</code>.
   *
   * <p>The source level and compliance level values should be taken from the constant defined
   * inside {@link JavaCore} class. The constants are named <code>JavaCore#VERSION_1_x</code>, x
   * being set between '1' and '8'.
   *
   * @param name the name of a type
   * @param sourceLevel the source level
   * @param complianceLevel the compliance level
   * @return a status object with code <code>IStatus.OK</code> if the given name is valid as a Java
   *     type name, a status with code <code>IStatus.WARNING</code> indicating why the given name is
   *     discouraged, otherwise a status object indicating what is wrong with the name
   * @since 3.3
   * @see JavaCore#VERSION_1_1
   * @see JavaCore#VERSION_1_2
   * @see JavaCore#VERSION_1_3
   * @see JavaCore#VERSION_1_4
   * @see JavaCore#VERSION_1_5
   * @see JavaCore#VERSION_1_6
   * @see JavaCore#VERSION_1_7
   * @see JavaCore#VERSION_1_8
   */
  public static IStatus validateJavaTypeName(
      String name, String sourceLevel, String complianceLevel) {
    if (name == null) {
      return new Status(
          IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.convention_type_nullName, null);
    }
    String trimmed = name.trim();
    if (!name.equals(trimmed)) {
      return new Status(
          IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.convention_type_nameWithBlanks, null);
    }
    int index = name.lastIndexOf('.');
    char[] scannedID;
    if (index == -1) {
      // simple name
      scannedID = scannedIdentifier(name, sourceLevel, complianceLevel);
    } else {
      // qualified name
      String pkg = name.substring(0, index).trim();
      IStatus status = validatePackageName(pkg, sourceLevel, complianceLevel);
      if (!status.isOK()) {
        return status;
      }
      String type = name.substring(index + 1).trim();
      scannedID = scannedIdentifier(type, sourceLevel, complianceLevel);
    }

    if (scannedID != null) {
      IStatus status =
          ResourcesPlugin.getWorkspace().validateName(new String(scannedID), IResource.FILE);
      if (!status.isOK()) {
        return status;
      }
      if (CharOperation.contains('$', scannedID)) {
        return new Status(
            IStatus.WARNING, JavaCore.PLUGIN_ID, -1, Messages.convention_type_dollarName, null);
      }
      if ((scannedID.length > 0 && ScannerHelper.isLowerCase(scannedID[0]))) {
        return new Status(
            IStatus.WARNING, JavaCore.PLUGIN_ID, -1, Messages.convention_type_lowercaseName, null);
      }
      return JavaModelStatus.VERIFIED_OK;
    } else {
      return new Status(
          IStatus.ERROR,
          JavaCore.PLUGIN_ID,
          -1,
          Messages.bind(Messages.convention_type_invalidName, name),
          null);
    }
  }
示例#12
0
 public void run() {
   while (true) {
     synchronized (JobManagerImpl.this.mySemaphor) {
       if (JobManagerImpl.this.mySemaphor.isClosed()) {
         try {
           JobManagerImpl.this.mySemaphor.wait();
         } catch (InterruptedException e) {
           cleanJobs();
         }
       }
     }
     synchronized (myJobs) {
       if (myJobs.isEmpty()) {
         try {
           myJobs.wait();
         } catch (InterruptedException e) {
           cleanJobs();
         }
       } else {
         InternalJobImpl next = (InternalJobImpl) myJobs.removeFirst();
         IStatus result = next.run(myProgressMonitor);
         next.setResult(result);
         if (result.isOK()) {
         } else {
           cleanJobs();
         }
       }
     }
   }
 }
  @Override
  protected boolean validatePage() {
    IStatus status =
        JavaConventions.validateCompilationUnitName(
            this.getFileName() + ".java", CompilerOptions.VERSION_1_3, CompilerOptions.VERSION_1_3);
    if (!status.isOK()) {
      setErrorMessage(status.getMessage());
      return false;
    }
    IProject project =
        ResourcesPlugin.getWorkspace().getRoot().getProject(getContainerFullPath().segment(0));

    // This may need to change depending on how we want to deal with localized components in future.
    LocatePlugin locatePlugin = LocatePlugin.getDefault();
    try {
      LocalizedComponentsLocateResult result =
          locatePlugin.getLocalizedComponentsLocateResult(project, getFileName());
      if (result.getResources().length > 0) {
        setErrorMessage("A component by that name already exists");
        return false;
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    // Check that we aren't going to create a wocomponent inside another wocomponent
    IPath path = getContainerFullPath();
    if (path.lastSegment().endsWith(".wo")) {
      setErrorMessage("Cannot create a component within another component");
      return false;
    }

    return super.validatePage();
  }
  private IStatus validateLocation() {
    String location = projectLocationField.getText();

    if (!new Path(location).isValidPath(getProjectName())) {
      return new Status(
          IStatus.ERROR,
          DartToolsPlugin.PLUGIN_ID,
          ProjectMessages.NewProjectCreationPage_invalid_loc);
    }

    if (doesProjectExist()) {
      return new Status(
          IStatus.ERROR,
          DartToolsPlugin.PLUGIN_ID,
          NLS.bind(ProjectMessages.NewApplicationWizardPage_error_existing, getProjectName()));
    }

    IStatus status = DirectoryVerification.getOpenDirectoryLocationStatus(new File(location));

    if (!status.isOK()) {
      return status;
    }

    return Status.OK_STATUS;
  }
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.papyrus.commands.ICreationCommand#createDiagram(org.eclipse.emf.ecore.resource.Resource, org.eclipse.emf.ecore.EObject,
   * org.eclipse.emf.ecore.EObject, org.eclipse.papyrus.infra.viewpoints.policy.ViewPrototype, java.lang.String)
   */
  @Override
  public final Diagram createDiagram(
      ModelSet modelSet, EObject owner, EObject element, ViewPrototype prototype, String name) {
    ICommand createCmd = getCreateDiagramCommand(modelSet, owner, element, prototype, name);
    TransactionalEditingDomain dom = modelSet.getTransactionalEditingDomain();
    CompositeCommand cmd = new CompositeCommand("Create diagram");
    cmd.add(createCmd);
    cmd.add(new OpenDiagramCommand(dom, createCmd));

    try {

      IStatus status =
          CheckedOperationHistory.getInstance().execute(cmd, new NullProgressMonitor(), null);
      if (status.isOK()) {
        CommandResult result = cmd.getCommandResult();
        Object returnValue = result.getReturnValue();

        // CompositeCommands should always return a collection
        if (returnValue instanceof Collection<?>) {
          for (Object returnElement : (Collection<?>) returnValue) {
            if (returnElement instanceof Diagram) {
              return (Diagram) returnElement;
            }
          }
        }
      } else if (status.getSeverity() != IStatus.CANCEL) {
        StatusManager.getManager().handle(status, StatusManager.SHOW);
      }
    } catch (ExecutionException ex) {
      Activator.log.error(ex);
    }

    return null;
  }
  public void testAddExternalJar02AddMuiltiLibs() throws Exception {
    fJavaProject = createProject(DEFAULT_OUTPUT_FOLDER_NAME);

    IPath[] jarPaths =
        new IPath[] {
          JavaProjectHelper.MYLIB.makeAbsolute(), JavaProjectHelper.NLS_LIB.makeAbsolute()
        };

    CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject);
    IStatus status = ClasspathModifier.checkAddExternalJarsPrecondition(jarPaths, cpProject);
    assertTrue(status.isOK());

    BuildpathDelta delta = ClasspathModifier.addExternalJars(jarPaths, cpProject);
    assertDeltaResources(delta, new IPath[0], new IPath[0], new IPath[0], new IPath[0]);
    assertDeltaDefaultOutputFolder(delta, fJavaProject.getOutputLocation());
    assertDeltaRemovedEntries(delta, new IPath[0]);
    assertDeltaAddedEntries(delta, jarPaths);

    ClasspathModifier.commitClassPath(cpProject, null);

    IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath();
    assertNumberOfEntries(classpathEntries, 3);
    assertIsOnBuildpath(classpathEntries, JavaProjectHelper.MYLIB.makeAbsolute());
    assertIsOnBuildpath(classpathEntries, JavaProjectHelper.NLS_LIB.makeAbsolute());
  }
  @Override
  protected void publishServer(int kind, IProgressMonitor monitor) throws CoreException {
    if (getServer().getRuntime() == null) return;

    IPath confDir = getBaseDirectory();
    getJonasVersionHandler()
        .createJonasBase(
            getServer().getRuntime().getLocation(),
            this.getJonasRuntimeInstance().getInstanceDirectory());
    IStatus status = getJonasVersionHandler().prepareDeployDirectory(confDir);

    if (status != null && !status.isOK()) throw new CoreException(status);

    IProgressMonitor monitor2 = ProgressUtil.getMonitorFor(monitor);
    monitor2.beginTask(Messages.publishServerTask, 600);

    // TODO OSAMI 1) Cleanup 2) Backup and Publish,

    // if (status != null && !status.isOK())
    // throw new CoreException(status);

    monitor2.done();

    setServerPublishState(IServer.PUBLISH_STATE_NONE);
  }
示例#18
0
  protected void checkIfPathValid() {
    fFolder = null;
    IContainer folder = null;
    if (fUseFolderButton.isSelected()) {
      String pathStr = fContainerDialogField.getText();
      if (pathStr.length() == 0) {
        fContainerFieldStatus.setError(NewWizardMessages.NewSourceFolderDialog_error_enterpath);
        return;
      }
      IPath path = fCurrProject.getFullPath().append(pathStr);
      IWorkspace workspace = fCurrProject.getWorkspace();

      IStatus pathValidation = workspace.validatePath(path.toString(), IResource.FOLDER);
      if (!pathValidation.isOK()) {
        fContainerFieldStatus.setError(
            Messages.format(
                NewWizardMessages.NewSourceFolderDialog_error_invalidpath,
                pathValidation.getMessage()));
        return;
      }
      folder = fCurrProject.getFolder(pathStr);
    } else {
      folder = fCurrProject;
    }
    if (isExisting(folder)) {
      fContainerFieldStatus.setError(NewWizardMessages.NewSourceFolderDialog_error_pathexists);
      return;
    }
    fContainerFieldStatus.setOK();
    fFolder = folder;
  }
示例#19
0
 public IBuffer getBuffer() throws JavaModelException {
   IStatus status = validateClassFile();
   if (status.isOK()) {
     return super.getBuffer();
   } else {
     // .class file not on classpath, create a new buffer to be nice (see
     // https://bugs.eclipse.org/bugs/show_bug.cgi?id=41444)
     Object info = ((ClassFile) getClassFile()).getBinaryTypeInfo((IFile) resource());
     IBuffer buffer = openBuffer(null, info);
     if (buffer != null && !(buffer instanceof NullBuffer)) return buffer;
     switch (status.getCode()) {
       case IJavaModelStatusConstants
           .ELEMENT_NOT_ON_CLASSPATH: // don't throw a JavaModelException to be able to open .class
         // file outside the classpath (see
         // https://bugs.eclipse.org/bugs/show_bug.cgi?id=138507 )
       case IJavaModelStatusConstants
           .INVALID_ELEMENT_TYPES: // don't throw a JavaModelException to be able to open .class
         // file in proj==src case without source (see
         // https://bugs.eclipse.org/bugs/show_bug.cgi?id=221904 )
         return null;
       default:
         throw new JavaModelException((IJavaModelStatus) status);
     }
   }
 }
    // private helper to appendProblems() that can be called recursively
    private void appendProblemsRecursive(IStatus[] statuses, StringBuffer output) {
      for (IStatus next : statuses) {
        if (!next.isOK()) {
          final String messagePattern;

          switch (next.getSeverity()) {
            case IStatus.ERROR:
              hasProblems = true;
              hasErrors = true;
              messagePattern = ValidationUIMessages.Validation_error;
              break;
            case IStatus.WARNING:
              hasProblems = true;
              messagePattern = ValidationUIMessages.Validation_warn;
              break;
            default:
              messagePattern = ValidationUIMessages.Validation_note;
              break;
          }

          output.append(MessageFormat.format(messagePattern, new Object[] {next.getMessage()}));
          output.append(PLATFORM_NEWLINE);
        }

        if (next.isMultiStatus()) {
          appendProblemsRecursive(next.getChildren(), output);
        }
      }
    }
  /* (non-Javadoc)
   * @see org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal#getAdditionalProposalInfo()
   */
  public Object getAdditionalProposalInfo(IProgressMonitor monitor) {
    StringBuffer result = new StringBuffer();

    IStatus status = getFixStatus();
    if (status != null && !status.isOK()) {
      result.append("<b>"); // $NON-NLS-1$
      if (status.getSeverity() == IStatus.WARNING) {
        result.append(CorrectionMessages.FixCorrectionProposal_WarningAdditionalProposalInfo);
      } else if (status.getSeverity() == IStatus.ERROR) {
        result.append(CorrectionMessages.FixCorrectionProposal_ErrorAdditionalProposalInfo);
      }
      result.append("</b>"); // $NON-NLS-1$
      result.append(status.getMessage());
      result.append("<br><br>"); // $NON-NLS-1$
    }

    String info = fFix.getAdditionalProposalInfo();
    if (info != null) {
      result.append(info);
    } else {
      result.append(super.getAdditionalProposalInfo(monitor));
    }

    return result.toString();
  }
 /**
  * Writes the appropriate configuration status of the workspace according to the status passed.
  *
  * @param status the status to check
  */
 public static void writeConfiguredFlag(IStatus status) {
   if (status.isOK()) {
     writeConfiguredAttribute(getFormattedTimestamp());
   } else {
     writeErrorFlag();
   }
 }
        public Map<String, IStatus> validate(Object value, Object context) {
          String name = value.toString();
          if (context != null && context instanceof ISeamProject) {
            ISeamProject seamProject = (ISeamProject) context;
            ISeamComponent component = seamProject.getComponent(name);
            if (component != null)
              return createErrormessage(
                  new Status(
                      IStatus.ERROR,
                      SeamCorePlugin.PLUGIN_ID,
                      NLS.bind(SeamCoreMessages.VALIDATOR_FACTORY_COMPONENT_ALREADY_EXISTS, name)));
          }

          String[] segs = name.split("\\."); // $NON-NLS-1$
          for (String segm : segs) {
            if (!segm.trim().equals(segm))
              return createErrormessage(
                  new Status(
                      IStatus.ERROR,
                      SeamCorePlugin.PLUGIN_ID,
                      SeamCoreMessages.VALIDATOR_FACTORY_NAME_IS_NOT_VALID));

            IStatus status =
                JavaConventions.validateClassFileName(
                    segm + ".class", DEFAULT_SOURCE_LEVEL, DEFAULT_COMPLIANCE_LEVEL); // $NON-NLS-1$
            if (!status.isOK())
              return createErrormessage(
                  new Status(
                      IStatus.ERROR,
                      SeamCorePlugin.PLUGIN_ID,
                      SeamCoreMessages.VALIDATOR_FACTORY_NAME_IS_NOT_VALID));
          }
          return NO_ERRORS;
        }
 protected void setStatus(IStatus status) {
   if (status == null || status.isOK()) {
     errorLabel.setText("");
     errorImage.setImage(null);
   } else {
     errorLabel.setText(status.getMessage());
     errorLabel.setToolTipText(status.getMessage());
     Image toUse = null;
     switch (status.getSeverity()) {
       case IStatus.WARNING:
         toUse =
             PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_WARN_TSK);
         break;
       case IStatus.ERROR:
         toUse =
             PlatformUI.getWorkbench()
                 .getSharedImages()
                 .getImage(ISharedImages.IMG_OBJS_ERROR_TSK);
         break;
       case IStatus.INFO:
         toUse =
             PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_INFO_TSK);
         break;
     }
     errorImage.setImage(toUse);
     errorImage.setVisible(true);
   }
 }
  @Override
  public boolean performFinish() {
    newProject = mainPage.getProjectHandle();
    destPath = mainPage.getLocationPath();
    location = null;
    if (!mainPage.useDefaults()) {
      location = mainPage.getLocationURI();
    } else {
      destPath = destPath.append(newProject.getName());
    }

    if (templatesPage != null) {
      selectedTemplate = templatesPage.getSelectedTemplate();
    }

    if (referencePage != null) {
      refProjects = referencePage.getReferencedProjects();
    }

    if (!deferCreatingProject()) {
      IStatus projectStatus = createAndRefreshProject(true, true, new NullProgressMonitor());
      return projectStatus.isOK();
    }
    return true;
  }
  public static final Status execute(final NewLiferayPluginProjectOp op, final ProgressMonitor pm) {
    final IProgressMonitor monitor = ProgressMonitorBridge.create(pm);

    monitor.beginTask(
        "Creating Liferay plugin project (this process may take several minutes)",
        100); //$NON-NLS-1$

    Status retval = null;

    try {
      final NewLiferayProjectProvider<NewLiferayPluginProjectOp> projectProvider =
          op.getProjectProvider().content(true);

      // IDE-1306  If the user types too quickly all the model changes may not have propagated
      final Path projectLocation = op.getLocation().content();
      updateLocation(op, projectLocation);

      final IStatus status = projectProvider.createNewProject(op, monitor);

      if (status.isOK()) {
        updateProjectPrefs(op);

        removeSampleCodeAndFiles(op);
      }

      retval = StatusBridge.create(status);
    } catch (Exception e) {
      final String msg = "Error creating Liferay plugin project."; // $NON-NLS-1$
      ProjectCore.logError(msg, e);

      return Status.createErrorStatus(msg + " Please see Eclipse error log for more details.", e);
    }

    return retval;
  }
 /**
  * Download the remote content and store it the temp directory.
  *
  * @param URLs
  * @param progressMonitor
  */
 public IStatus download(String[] URLs, IProgressMonitor progressMonitor) {
   if (URLs.length == 0) {
     String err = Messages.InstallerConfigurationProcessor_missingDownloadTargets;
     applyErrorAttributes(err);
     IdeLog.logError(
         PortalUIPlugin.getDefault(),
         "We expected an array of URLs, but got an empty array.",
         new Exception(err)); // $NON-NLS-1$
     return new Status(IStatus.ERROR, PortalUIPlugin.PLUGIN_ID, err);
   }
   downloadedPaths = null;
   DownloadManager downloadManager = new DownloadManager();
   List<URI> urlsList = new ArrayList<URI>(URLs.length);
   for (int i = 0; i < URLs.length; i++) {
     try {
       urlsList.add(new URI(urls[i]));
     } catch (URISyntaxException mue) {
       IdeLog.logError(PortalUIPlugin.getDefault(), mue);
     }
   }
   try {
     downloadManager.addURIs(urlsList);
     IStatus status = downloadManager.start(progressMonitor);
     if (status.isOK()) {
       downloadedPaths = downloadManager.getContentsLocations();
     }
     return status;
   } catch (Exception e) {
     IdeLog.logError(PortalUIPlugin.getDefault(), e);
   }
   return Status.CANCEL_STATUS;
 }
示例#28
0
  @Override
  public boolean requiresUpdate() {
    final long stamp = System.currentTimeMillis();
    if (Math.abs(fMirrorsStamp - stamp) > MIRROR_CHECK) {
      getWriteLock().lock();
      try {
        fRequireLoad |= (REQUIRE_CRAN | REQUIRE_BIOC);
        return true;
      } finally {
        getWriteLock().unlock();
      }
    }
    if ((fRequireLoad & (REQUIRE_REPOS | REQUIRE_CRAN | REQUIRE_BIOC)) != 0) {
      return true;
    }
    final IStatus status = getReposStatus(null);
    if (!status.isOK()) {
      return false;
    }

    if (Math.abs(fPkgsStamp - stamp) > MIRROR_CHECK) {
      getWriteLock().lock();
      try {
        fRequireLoad |= (REQUIRE_REPO_PKGS);
        return true;
      } finally {
        getWriteLock().unlock();
      }
    }
    if ((fRequireLoad & (REQUIRE_REPO_PKGS | REQUIRE_INST_PKGS)) != 0) {
      return true;
    }
    return false;
  }
示例#29
0
  /**
   * Checks if there was an error.
   *
   * @param caller The caller or <code>null</code>.
   * @param status The status. <code>null</code> if status should not be checked.
   * @param callback The callback to call on cancel or error.
   * @return <code>false</code> if everything is OK.
   */
  public static final boolean isError(Object caller, IStatus status, ICallback callback) {
    if (status == null) status = Status.OK_STATUS;

    if (!status.isOK() && status.getSeverity() != IStatus.CANCEL) {
      if (status.getSeverity() == IStatus.ERROR) {
        Throwable e = status.getException();
        try {
          throw e;
        } catch (Throwable thrown) {
          e = thrown;
        }
        CoreBundleActivator.getTraceHandler()
            .trace(
                status.getMessage(),
                1,
                ITraceIds.TRACE_CALLBACKS,
                status.getSeverity(),
                caller != null ? caller.getClass() : ProgressHelper.class);
        status =
            new Status(IStatus.ERROR, status.getPlugin(), status.getCode(), status.getMessage(), e);
      }

      if (callback != null) {
        if (caller instanceof ICallback) {
          Callback.copyProperties((ICallback) caller, callback);
        }
        callback.done(caller, status);
      }
      return true;
    }
    return false;
  }
  /*
   * Consult the IOperationApprovers to see if the proposed execution should
   * be allowed.
   *
   * @since 3.2
   */
  private IStatus getExecuteApproval(IUndoableOperation operation, IAdaptable info) {

    final Object[] approverArray = approvers.getListeners();

    for (int i = 0; i < approverArray.length; i++) {
      if (approverArray[i] instanceof IOperationApprover2) {
        IOperationApprover2 approver = (IOperationApprover2) approverArray[i];
        IStatus approval = approver.proceedExecuting(operation, this, info);
        if (!approval.isOK()) {
          if (DEBUG_OPERATION_HISTORY_APPROVAL) {
            Tracing.printTrace(
                "OPERATIONHISTORY", //$NON-NLS-1$
                "Execute not approved by "
                    + approver //$NON-NLS-1$
                    + "for operation "
                    + operation //$NON-NLS-1$
                    + " with status "
                    + approval); //$NON-NLS-1$
          }
          return approval;
        }
      }
    }
    return Status.OK_STATUS;
  }