Exemplo n.º 1
0
  @Override
  public IStatus execute(final IProgressMonitor monitor)
      throws CoreException, InvocationTargetException {
    final SubMonitor progress =
        SubMonitor.convert(
            monitor,
            Messages.getString("org.kalypso.model.flood.ui.map.operations.ImportTinOperation.0"),
            100); //$NON-NLS-1$

    /* Add sources as new tin references */
    progress.subTask(
        Messages.getString(
            "org.kalypso.model.flood.ui.map.operations.ImportTinOperation.1")); //$NON-NLS-1$
    m_tinRefs = new ITinReference[m_sources.length];
    final Feature[] changedFeatures = new Feature[m_sources.length];

    for (int i = 0; i < m_sources.length; i++) {
      final IGmlSource source = m_sources[i];

      final ITinReference tinRef = m_tins.addNew(-1, ITinReference.QNAME, ITinReference.class);
      tinRef.setName(source.getName());
      tinRef.setDescription(source.getDescription());
      tinRef.setSourceLocation(source.getLocation());
      tinRef.setSourceFeaturePath(source.getPath());
      tinRef.setSourceType(typeForSource(source));

      m_tinRefs[i] = tinRef;
      changedFeatures[i] = tinRef;
    }
    ProgressUtilities.worked(progress, 20);

    /* post command for events stuff... */
    final Feature parentFeature = m_tins.getParentFeature();
    final GMLWorkspace workspace = parentFeature.getWorkspace();
    final ModellEvent modelEvent =
        new FeatureStructureChangeModellEvent(
            workspace,
            parentFeature,
            changedFeatures,
            FeatureStructureChangeModellEvent.STRUCTURE_CHANGE_ADD);
    workspace.fireModellEvent(modelEvent);
    /* Save data model */
    // progress.subTask( "speichere Datenmodell" );
    // m_provider.saveModel( IFloodModel.class, progress.newChild( 20 ) );
    /* update tins */
    progress.subTask(
        Messages.getString(
            "org.kalypso.model.flood.ui.map.operations.ImportTinOperation.2")); //$NON-NLS-1$
    final UpdateTinsOperation updateOp = new UpdateTinsOperation(m_tinRefs, m_provider);
    updateOp.execute(progress.newChild(60));

    /* Jump to imported tins */
    final GM_Envelope envelope = FeatureHelper.getEnvelope(changedFeatures);
    final GM_Envelope scaledBox =
        envelope == null ? null : GeometryUtilities.scaleEnvelope(envelope, 1.05);
    if (m_mapPanel != null && scaledBox != null) m_mapPanel.setBoundingBox(scaledBox);

    return Status.OK_STATUS;
  }
Exemplo n.º 2
0
 private Collection<IInstallableUnit> filterInstallableUnits(
     String idPrefix,
     String idSuffix,
     IQueryResult<IInstallableUnit> queryResult,
     IProgressMonitor monitor)
     throws OperationCanceledException {
   if (monitor == null) {
     monitor = new NullProgressMonitor();
   }
   Collection<IInstallableUnit> wso2IUs = new ArrayList<IInstallableUnit>();
   Iterator<IInstallableUnit> iterator = queryResult.iterator();
   SubMonitor progress =
       SubMonitor.convert(monitor, Messages.UpdateManager_24, queryResult.toSet().size());
   ;
   while (iterator.hasNext()) {
     if (progress.isCanceled()) {
       throw new OperationCanceledException();
     }
     IInstallableUnit iu = iterator.next();
     String versionedID = iu.getId();
     progress.subTask(Messages.UpdateManager_25 + versionedID);
     if (versionedID != null
         && versionedID.startsWith(idPrefix)
         && versionedID.endsWith(idSuffix)) {
       wso2IUs.add(iu);
     }
     progress.worked(1);
   }
   return wso2IUs;
 }
Exemplo n.º 3
0
  /** @since 2.7 */
  protected void doBuild(
      List<IResourceDescription.Delta> deltas,
      Map<String, OutputConfiguration> outputConfigurations,
      Map<OutputConfiguration, Iterable<IMarker>> generatorMarkers,
      IBuildContext context,
      EclipseResourceFileSystemAccess2 access,
      IProgressMonitor progressMonitor)
      throws CoreException {
    final int numberOfDeltas = deltas.size();
    SubMonitor subMonitor =
        SubMonitor.convert(progressMonitor, numberOfDeltas / MONITOR_CHUNK_SIZE + 1);
    SubMonitor currentMonitor = null;
    int clusterIndex = 0;
    for (int i = 0; i < numberOfDeltas; i++) {
      IResourceDescription.Delta delta = deltas.get(i);

      if (subMonitor.isCanceled()) {
        throw new OperationCanceledException();
      }
      if (i % 10 == 0) {
        subMonitor.subTask(
            "Compiling chunk "
                + (i / MONITOR_CHUNK_SIZE + 1)
                + " of "
                + (numberOfDeltas / MONITOR_CHUNK_SIZE + 1));
        currentMonitor = subMonitor.newChild(1);
        access.setMonitor(currentMonitor);
      }
      if (logger.isDebugEnabled()) {
        logger.debug("Compiling " + delta.getUri() + " (" + i + " of " + numberOfDeltas + ")");
      }
      if (delta.getNew() != null
          && !clusteringPolicy.continueProcessing(
              context.getResourceSet(), delta.getUri(), clusterIndex)) {
        clearResourceSet(context.getResourceSet());
        clusterIndex = 0;
      }

      Set<IFile> derivedResources =
          getDerivedResources(delta, outputConfigurations, generatorMarkers);
      access.setPostProcessor(getPostProcessor(delta, context, derivedResources));

      if (doGenerate(delta, context, access)) {
        clusterIndex++;
        access.flushSourceTraces();
      }

      cleanDerivedResources(delta, derivedResources, context, access, currentMonitor);
    }
  }
Exemplo n.º 4
0
  @SuppressWarnings("unchecked")
  public IGithubPullRequest createPullRequest(
      String title, String body, GitRepository repo, IProgressMonitor monitor)
      throws CoreException {
    SubMonitor sub =
        SubMonitor.convert(monitor, Messages.GithubRepository_GeneratingPRTaskName, 100);
    String branch = repo.currentBranch();

    // push current branch to origin first!
    sub.subTask(Messages.GithubRepository_PushingBranchSubtaskName);
    IStatus pushStatus = repo.push(GitRepository.ORIGIN, branch);
    sub.worked(50);
    if (!pushStatus.isOK()) {
      throw new CoreException(pushStatus);
    }

    sub.subTask(Messages.GithubRepository_SubmittingPRSubtaskName);
    IGithubRepository parent = getParent();
    JSONObject prObject = new JSONObject();
    prObject.put("title", title); // $NON-NLS-1$
    prObject.put("body", body); // $NON-NLS-1$
    // TODO Allow user to choose branch on the fork to use as contents for PR?
    prObject.put("head", getOwner() + ':' + branch); // $NON-NLS-1$
    // FIXME Allow user to choose the branch from parent to merge against. Default to the parent's
    // default
    // branch
    prObject.put("base", parent.getDefaultBranch()); // $NON-NLS-1$

    JSONObject result =
        (JSONObject)
            getAPI()
                .post(
                    ((GithubRepository) parent).getAPIURL() + "/pulls",
                    prObject.toJSONString()); // $NON-NLS-1$
    return new GithubPullRequest(result);
  }
  /** @see org.apache.tools.ant.Task#execute() */
  @Override
  public void execute() throws BuildException {
    try {
      // Initialise ant-stuff: progress monitor and logging
      final Project antProject = getProject();
      final String message = getDescription();
      final String taskMessage = message == null || message.length() == 0 ? getTaskName() : message;

      final Hashtable<?, ?> references = antProject == null ? null : antProject.getReferences();
      final IProgressMonitor monitor =
          references == null
              ? null
              : (IProgressMonitor) references.get(AntCorePlugin.ECLIPSE_PROGRESS_MONITOR);

      // REMARK: It is NOT possible to put this inner class into an own .class file (at least not
      // inside the plugin
      // code) else we get an LinkageError when accessing the Project class.
      final ILogger logger =
          new ILogger() {
            /**
             * @see org.kalypso.contribs.java.util.logging.ILogger#log(java.util.logging.Level, int,
             *     java.lang.String)
             */
            @Override
            public void log(final Level level, final int msgCode, final String logMessage) {
              final String outString = LoggerUtilities.formatLogStylish(level, msgCode, logMessage);
              final int antLevel = mapLevelToAnt(level);

              antProject.log(RainfallGenerationTask.this, outString, antLevel);
            }
          };

      logger.log(Level.INFO, LoggerUtilities.CODE_NEW_MSGBOX, taskMessage);

      // Real work starts here: create the operation, convert and validate parameters
      final SubMonitor progress = SubMonitor.convert(monitor, taskMessage, 100);
      progress.subTask("Operation wird initialisiert");

      ProgressUtilities.worked(progress, 4);

      final IStatus status =
          executeOperation(antProject, progress.newChild(95, SubMonitor.SUPPRESS_NONE));
      // TODO: write status into logger
    } catch (final Throwable e) {
      e.printStackTrace();
      throw new BuildException(e);
    }
  }
Exemplo n.º 6
0
  protected void moveMotor(
      final IProgressMonitor monitor, final IScannableMotor motor, final double newPosition)
      throws DeviceException, InterruptedException {

    double motorSpeed = motor.getSpeed();

    double position = (Double) motor.getPosition();

    double distance = Math.abs(position - newPosition);

    double timeInSeconds = distance / motorSpeed;

    logger.debug(String.format("Time to move %1$f is %2$f", distance, timeInSeconds));
    logger.debug(String.format("Speed of motor %1$s is %2$f", motor.getName(), motor.getSpeed()));
    motorsRunning.add(motor);

    motor.asynchronousMoveTo(newPosition);

    int totalTimeTakenInMills = (int) (timeInSeconds * 1000);

    final int step = totalTimeTakenInMills / 10000;

    SubMonitor progress =
        SubMonitor.convert(
            monitor,
            String.format("Moving %s from %.3g to %.3g", motor.getName(), position, newPosition),
            10000);
    int count = 0;
    while (motor.isBusy()) {
      Double currPos = (Double) motor.getPosition();
      progress.subTask(String.format("%s position: %.3g", motor.getName(), currPos));
      progress.worked(1);
      Sleep.sleep(step);
      count++;
      if (monitor.isCanceled()) {
        motor.stop();
        throw new InterruptedException("User Cancelled");
      }
    }
    logger.debug("Motor queried count is {}", count);
    motorsRunning.remove(motor);
  }
 public ToBeBuilt updateProjectNewResourcesOnly(IProject project, IProgressMonitor monitor)
     throws CoreException {
   SubMonitor progress =
       SubMonitor.convert(monitor, Messages.ToBeBuiltComputer_CollectingReosurces, 1);
   progress.subTask(Messages.ToBeBuiltComputer_CollectingReosurces);
   ToBeBuilt toBeBuilt = updateProject(project, progress.newChild(1));
   Iterable<URI> existingURIs =
       Iterables.transform(
           builderState.getAllResourceDescriptions(),
           new Function<IResourceDescription, URI>() {
             public URI apply(IResourceDescription from) {
               return from.getURI();
             }
           });
   for (URI existingURI : existingURIs) {
     toBeBuilt.getToBeDeleted().remove(existingURI);
     toBeBuilt.getToBeUpdated().remove(existingURI);
   }
   return toBeBuilt;
 }
 private IStatus computeAllRemediations(IProgressMonitor monitor) {
   SubMonitor sub = SubMonitor.convert(monitor, remedyConfigs.length);
   sub.setTaskName(Messages.RemediationOperation_ProfileChangeRequestProgress);
   List<Remedy> tmpRemedies = new ArrayList<Remedy>(remedyConfigs.length);
   try {
     for (int i = 0; i < remedyConfigs.length; i++) {
       sub.subTask((i + 1) + " / " + remedyConfigs.length); // $NON-NLS-1$
       if (sub.isCanceled()) return Status.CANCEL_STATUS;
       Remedy remedy =
           computeRemedy(remedyConfigs[i], sub.newChild(1, SubMonitor.SUPPRESS_ALL_LABELS));
       if (remedy != null) {
         tmpRemedies.add(remedy);
       }
     }
   } finally {
     sub.done();
   }
   remedies = tmpRemedies;
   return getResolutionResult();
 }
Exemplo n.º 9
0
  /**
   * Pre-loads all class binary data that belong to the given package by reading the archive once
   * and caching them internally.
   *
   * <p>This does not actually preload "classes", it just reads the unzipped bytes for a given
   * class. To obtain a class, one must call {@link #findClass(String)} later.
   *
   * <p>All classes which package name starts with "packageFilter" will be included and can be found
   * later.
   *
   * <p>May throw some exceptions if the framework JAR cannot be read.
   *
   * @param packageFilter The package that contains all the class data to preload, using a fully
   *     qualified binary name (.e.g "com.my.package."). The matching algorithm is simple
   *     "startsWith". Use an empty string to include everything.
   * @param taskLabel An optional task name for the sub monitor. Can be null.
   * @param monitor A progress monitor. Can be null. Caller is responsible for calling done.
   * @throws IOException
   * @throws InvalidAttributeValueException
   * @throws ClassFormatError
   */
  public void preLoadClasses(String packageFilter, String taskLabel, IProgressMonitor monitor)
      throws IOException, InvalidAttributeValueException, ClassFormatError {
    // Transform the package name into a zip entry path
    String pathFilter = packageFilter.replaceAll("\\.", "/"); // $NON-NLS-1$ //$NON-NLS-2$

    SubMonitor progress = SubMonitor.convert(monitor, taskLabel == null ? "" : taskLabel, 100);

    // create streams to read the intermediary archive
    FileInputStream fis = new FileInputStream(mOsFrameworkLocation);
    ZipInputStream zis = new ZipInputStream(fis);
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
      // get the name of the entry.
      String entryPath = entry.getName();

      if (!entryPath.endsWith(AdtConstants.DOT_CLASS)) {
        // only accept class files
        continue;
      }

      // check if it is part of the package to preload
      if (pathFilter.length() > 0 && !entryPath.startsWith(pathFilter)) {
        continue;
      }
      String className = entryPathToClassName(entryPath);

      if (!mEntryCache.containsKey(className)) {
        long entrySize = entry.getSize();
        if (entrySize > Integer.MAX_VALUE) {
          throw new InvalidAttributeValueException();
        }
        byte[] data = readZipData(zis, (int) entrySize);
        mEntryCache.put(className, data);
      }

      // advance 5% of whatever is allocated on the progress bar
      progress.setWorkRemaining(100);
      progress.worked(5);
      progress.subTask(String.format("Preload %1$s", className));
    }
  }
  public ToBeBuilt updateProject(IProject project, IProgressMonitor monitor) throws CoreException {
    final SubMonitor progress =
        SubMonitor.convert(monitor, Messages.ToBeBuiltComputer_CollectingReosurces, 1);
    progress.subTask(Messages.ToBeBuiltComputer_CollectingReosurces);

    final ToBeBuilt toBeBuilt = removeProject(project, progress.newChild(1));
    if (!project.isAccessible()) return toBeBuilt;
    if (progress.isCanceled()) throw new OperationCanceledException();

    project.accept(
        new IResourceVisitor() {
          public boolean visit(IResource resource) throws CoreException {
            if (progress.isCanceled()) throw new OperationCanceledException();
            if (resource instanceof IStorage) {
              return updateStorage(null, toBeBuilt, (IStorage) resource);
            }
            return true;
          }
        });
    return toBeBuilt;
  }
Exemplo n.º 11
0
  /**
   * @param monitor the progress monitor to use for reporting progress to the user. It is the
   *     caller's responsibility to call done() on the given monitor. Accepts null, indicating that
   *     no progress should be reported and that the operation cannot be cancelled.
   */
  protected void incrementalBuild(IResourceDelta delta, final IProgressMonitor monitor)
      throws CoreException {
    final SubMonitor progress =
        SubMonitor.convert(monitor, Messages.XtextBuilder_CollectingResources, 10);
    progress.subTask(Messages.XtextBuilder_CollectingResources);

    if (queuedBuildData.needRebuild(getProject())) {
      needRebuild();
    }

    final ToBeBuilt toBeBuilt = new ToBeBuilt();
    IResourceDeltaVisitor visitor =
        new IResourceDeltaVisitor() {
          @Override
          public boolean visit(IResourceDelta delta) throws CoreException {
            if (progress.isCanceled()) throw new OperationCanceledException();
            if (delta.getResource() instanceof IProject) {
              return delta.getResource() == getProject();
            }
            if (delta.getResource() instanceof IStorage) {
              if (delta.getKind() == IResourceDelta.REMOVED) {
                return toBeBuiltComputer.removeStorage(
                    null, toBeBuilt, (IStorage) delta.getResource());
              } else if (delta.getKind() == IResourceDelta.ADDED
                  || delta.getKind() == IResourceDelta.CHANGED) {
                return toBeBuiltComputer.updateStorage(
                    null, toBeBuilt, (IStorage) delta.getResource());
              }
            }
            return true;
          }
        };
    delta.accept(visitor);
    if (progress.isCanceled()) throw new OperationCanceledException();
    progress.worked(2);
    doBuild(toBeBuilt, progress.newChild(8), BuildType.INCREMENTAL);
  }
Exemplo n.º 12
0
  /*
   * Read the database values for a build name and a list of scenarios.
   * The database is read only if the components does not already knows the
   * given build (i.e. if it has not been already read) or if the force arguments is set.
   */
  void updateBuild(
      String buildName,
      List scenarios,
      boolean force,
      File dataDir,
      SubMonitor subMonitor,
      PerformanceResults.RemainingTimeGuess timeGuess) {

    // Read all variations
    println("Component '" + this.name + "':"); // $NON-NLS-1$ //$NON-NLS-2$

    // manage monitor
    int size = scenarios.size();
    subMonitor.setWorkRemaining(size + 1);
    StringBuffer buffer = new StringBuffer("Component "); // $NON-NLS-1$
    buffer.append(this.name);
    buffer.append("..."); // $NON-NLS-1$
    String title = buffer.toString();
    subMonitor.subTask(title + timeGuess.display());
    timeGuess.count++;
    subMonitor.worked(1);
    if (subMonitor.isCanceled()) return;

    // Read new values for the local result
    boolean dirty = false;
    long readTime = System.currentTimeMillis();
    String log = " - read scenarios from DB:"; // $NON-NLS-1$
    if (size > 0) {
      for (int i = 0; i < size; i++) {

        // manage monitor
        subMonitor.subTask(title + timeGuess.display());
        timeGuess.count++;
        if (log != null) {
          println(log);
          log = null;
        }

        // read results
        ScenarioResults nextScenarioResults = (ScenarioResults) scenarios.get(i);
        ScenarioResults scenarioResults = (ScenarioResults) getResults(nextScenarioResults.id);
        if (scenarioResults == null) {
          // Scenario is not known yet, force an update
          scenarioResults = nextScenarioResults;
          scenarioResults.parent = this;
          scenarioResults.printStream = this.printStream;
          scenarioResults.updateBuild(buildName, true);
          dirty = true;
          addChild(scenarioResults, true);
        } else {
          if (scenarioResults.updateBuild(buildName, force)) {
            dirty = true;
          }
        }
        if (dataDir != null
            && dirty
            && (System.currentTimeMillis() - readTime) > 300000) { // save every 5mn
          writeData(buildName, dataDir, true, true);
          dirty = false;
          readTime = System.currentTimeMillis();
        }

        // manage monitor
        subMonitor.worked(1);
        if (subMonitor.isCanceled()) return;
      }
    }

    // Write local files
    if (dataDir != null) {
      writeData(buildName, dataDir, false, dirty);
    }

    // Print global time
    printGlobalTime(readTime);
  }
Exemplo n.º 13
0
  /** Returns OK, WARN or ERROR. */
  public IS2ProjectValidationStatus validate(
      IS2Project s2Project, String securityRealmIdFilter, IProgressMonitor monitor) {
    log.debug("Validating SCM access for project {}", s2Project.getName());

    List<IS2Module> modules = s2Project.getModules();

    SubMonitor progress =
        SubMonitor.convert(monitor, "Validating source repository access", modules.size());

    ArrayList<IStatus> results = new ArrayList<IStatus>();

    for (final IS2Module module : modules) {
      if (progress.isCanceled()) {
        throw new OperationCanceledException();
      }

      progress.subTask(module.getName());

      IResourceLocation scmLocation = module.getScmLocation();
      if (scmLocation == null) {
        results.add(
            new Status(
                IStatus.ERROR,
                S2ProjectValidationPlugin.PLUGIN_ID,
                "SCM location is not specified"));
        monitor.worked(1);
        continue;
      }

      String scmUrl = scmLocation.getUrl();
      String realmIdForUrl = null;
      IAuthRealm realmForUrl = AuthFacade.getAuthRegistry().getRealmForURI(scmUrl);
      if (realmForUrl != null) {
        realmIdForUrl = realmForUrl.getId();
      }
      if (securityRealmIdFilter != null
          && !securityRealmIdFilter.equals(realmIdForUrl)
          && !urlsEquals(securityRealmIdFilter, scmUrl)) {
        // This location does not match the specified securityRealmId
        monitor.worked(1);
        continue;
      }
      log.debug("Validating SCM access for module {} at {}", module.getName(), scmUrl);

      IStatus status = validate(scmLocation, progress);
      results.add(status);
    }

    progress.subTask("");
    progress.done();

    if (results.isEmpty()) {
      return null;
    }

    return new S2ProjectValidationMultiStatus(
        this,
        -1,
        results.toArray(new IStatus[results.size()]),
        null /* message */,
        null /* exception */);
  }
Exemplo n.º 14
0
  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ptp.rtsystem.IRuntimeSystem#startup(org.eclipse.core.runtime
   * .IProgressMonitor)
   */
  public void startup(IProgressMonitor monitor) throws CoreException {
    SubMonitor subMon = SubMonitor.convert(monitor, 100);

    synchronized (this) {
      startupMonitor = subMon;
    }

    initialize();

    subMon.subTask(Messages.AbstractToolRuntimeSystem_1);

    DebugUtil.trace(
        DebugUtil.RTS_TRACING,
        "RTS {0}: startup",
        getResourceManager().getConfiguration().getName()); // $NON-NLS-1$

    try {
      remoteServices =
          PTPRemoteCorePlugin.getDefault()
              .getRemoteServices(
                  getResourceManager().getControlConfiguration().getRemoteServicesId(),
                  subMon.newChild(10));
      if (remoteServices == null) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                RMCorePlugin.PLUGIN_ID,
                Messages.AbstractToolRuntimeSystem_Exception_NoRemoteServices));
      }

      IRemoteConnectionManager connectionManager = remoteServices.getConnectionManager();
      Assert.isNotNull(connectionManager);

      subMon.worked(10);
      subMon.subTask(Messages.AbstractToolRuntimeSystem_2);

      connection =
          connectionManager.getConnection(
              getResourceManager().getControlConfiguration().getConnectionName());
      if (connection == null) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                RMCorePlugin.PLUGIN_ID,
                Messages.AbstractToolRuntimeSystem_Exception_NoConnection));
      }

      if (!connection.isOpen()) {
        try {
          connection.open(subMon.newChild(50));
        } catch (RemoteConnectionException e) {
          throw new CoreException(
              new Status(IStatus.ERROR, RMCorePlugin.PLUGIN_ID, e.getMessage()));
        }
      }

      if (subMon.isCanceled()) {
        connection.close();
        return;
      }

      try {
        doStartup(subMon.newChild(40));
      } catch (CoreException e) {
        connection.close();
        throw e;
      }

      if (subMon.isCanceled()) {
        connection.close();
        return;
      }

      /*
       * Wait for discover job to complete so we can check it's status and
       * throw an exception if it fails.
       */
      Job discoverJob = createDiscoverJob();
      if (discoverJob != null) {
        /*
         * Disable error messages being displayed on job's progress
         * monitor. These are handled by the progress service starting
         * the RM.
         */
        discoverJob.setProperty(
            IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE);
        discoverJob.schedule();
        try {
          discoverJob.join();
        } catch (InterruptedException e) {
          // Just check result
        }
        IStatus status = discoverJob.getResult();
        if (!status.isOK()) {
          throw new CoreException(status);
        }
      }

      if (jobQueueThread == null) {
        jobQueueThread =
            new Thread(
                new JobRunner(), Messages.AbstractToolRuntimeSystem_JobQueueManagerThreadTitle);
        jobQueueThread.start();
      }

      /*
       * Register for connection events
       */
      connection.addConnectionChangeListener(fConnectionChangeHandler);

      fireRuntimeRunningStateEvent(eventFactory.newRuntimeRunningStateEvent());
    } finally {
      synchronized (this) {
        startupMonitor = null;
      }
      if (monitor != null) {
        monitor.done();
      }
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.core.resources.IWorkspaceRunnable#run(org.eclipse.core.runtime.IProgressMonitor)
   */
  public void run(IProgressMonitor monitor) throws CoreException {
    SubMonitor subMonitor = SubMonitor.convert(monitor, 1000);
    subMonitor.beginTask("Generating MyBatis/iBATIS Artifacts:", 1000);

    setClassLoader();

    try {
      subMonitor.subTask("Parsing Configuration");

      ConfigurationParser cp = new ConfigurationParser(warnings);
      Configuration config = cp.parseConfiguration(inputFile.getLocation().toFile());

      subMonitor.worked(50);

      MyBatisGenerator mybatisGenerator =
          new MyBatisGenerator(config, new EclipseShellCallback(), warnings);
      monitor.subTask("Generating Files from Database Tables");
      SubMonitor spm = subMonitor.newChild(950);
      mybatisGenerator.generate(new EclipseProgressCallback(spm));

    } catch (InterruptedException e) {
      throw new OperationCanceledException();
    } catch (SQLException e) {
      Status status =
          new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, e.getMessage(), e);
      Activator.getDefault().getLog().log(status);
      throw new CoreException(status);
    } catch (IOException e) {
      Status status =
          new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, e.getMessage(), e);
      Activator.getDefault().getLog().log(status);
      throw new CoreException(status);
    } catch (XMLParserException e) {
      List<String> errors = e.getErrors();
      MultiStatus multiStatus =
          new MultiStatus(
              Activator.PLUGIN_ID,
              IStatus.ERROR,
              "XML Parser Errors\n  See Details for more Information",
              null);

      Iterator<String> iter = errors.iterator();
      while (iter.hasNext()) {
        Status message =
            new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, iter.next(), null);

        multiStatus.add(message);
      }
      throw new CoreException(multiStatus);
    } catch (InvalidConfigurationException e) {
      List<String> errors = e.getErrors();

      MultiStatus multiStatus =
          new MultiStatus(
              Activator.PLUGIN_ID,
              IStatus.ERROR,
              "Invalid Configuration\n  See Details for more Information",
              null);

      Iterator<String> iter = errors.iterator();
      while (iter.hasNext()) {
        Status message =
            new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, iter.next(), null);

        multiStatus.add(message);
      }
      throw new CoreException(multiStatus);
    } finally {
      monitor.done();
      restoreClassLoader();
    }
  }
Exemplo n.º 16
0
  public void build(final IBuildContext context, IProgressMonitor monitor) throws CoreException {
    if (!isEnabled(context)) {
      return;
    }

    final List<IResourceDescription.Delta> deltas = getRelevantDeltas(context);
    if (deltas.isEmpty()) {
      return;
    }

    final int numberOfDeltas = deltas.size();

    // monitor handling
    if (monitor.isCanceled()) throw new OperationCanceledException();
    SubMonitor subMonitor = SubMonitor.convert(monitor, numberOfDeltas + 3);

    EclipseResourceFileSystemAccess2 access = fileSystemAccessProvider.get();
    final IProject builtProject = context.getBuiltProject();
    access.setProject(builtProject);
    final Map<String, OutputConfiguration> outputConfigurations = getOutputConfigurations(context);
    refreshOutputFolders(context, outputConfigurations, subMonitor.newChild(1));
    access.setOutputConfigurations(outputConfigurations);
    if (context.getBuildType() == BuildType.CLEAN || context.getBuildType() == BuildType.RECOVERY) {
      SubMonitor cleanMonitor =
          SubMonitor.convert(subMonitor.newChild(1), outputConfigurations.size());
      for (OutputConfiguration config : outputConfigurations.values()) {
        cleanOutput(context, config, cleanMonitor.newChild(1));
      }
      if (context.getBuildType() == BuildType.CLEAN) return;
    }

    Map<OutputConfiguration, Iterable<IMarker>> generatorMarkers = newHashMap();
    for (OutputConfiguration config : outputConfigurations.values()) {
      if (config.isCleanUpDerivedResources()) {
        final IFolder outputFolder = builtProject.getFolder(config.getOutputDirectory());
        final Iterable<IMarker> markers =
            derivedResourceMarkers.findDerivedResourceMarkers(
                outputFolder, generatorIdProvider.getGeneratorIdentifier());
        generatorMarkers.put(config, markers);
      }
    }

    for (int i = 0; i < numberOfDeltas; i++) {
      final IResourceDescription.Delta delta = deltas.get(i);

      // monitor handling
      if (subMonitor.isCanceled()) throw new OperationCanceledException();
      subMonitor.subTask(
          "Compiling " + delta.getUri().lastSegment() + " (" + i + " of " + numberOfDeltas + ")");
      access.setMonitor(subMonitor.newChild(1));

      final String uri = delta.getUri().toString();
      final Set<IFile> derivedResources = newLinkedHashSet();
      for (OutputConfiguration config : outputConfigurations.values()) {
        if (config.isCleanUpDerivedResources()) {
          Iterable<IMarker> markers = generatorMarkers.get(config);
          for (IMarker marker : markers) {
            String source = derivedResourceMarkers.getSource(marker);
            if (source != null && source.equals(uri))
              derivedResources.add((IFile) marker.getResource());
          }
        }
      }
      access.setPostProcessor(
          new EclipseResourceFileSystemAccess2.IFileCallback() {

            public boolean beforeFileDeletion(IFile file) {
              derivedResources.remove(file);
              context.needRebuild();
              return true;
            }

            public void afterFileUpdate(IFile file) {
              handleFileAccess(file);
            }

            public void afterFileCreation(IFile file) {
              handleFileAccess(file);
            }

            protected void handleFileAccess(IFile file) {
              try {
                derivedResources.remove(file);
                derivedResourceMarkers.installMarker(file, uri);
                context.needRebuild();
              } catch (CoreException e) {
                throw new RuntimeException(e);
              }
            }
          });
      if (delta.getNew() != null) {
        handleChangedContents(delta, context, access);
      }
      access.flushSourceTraces();
      SubMonitor deleteMonitor =
          SubMonitor.convert(subMonitor.newChild(1), derivedResources.size());
      for (IFile iFile : newLinkedHashSet(derivedResources)) {
        IMarker marker = derivedResourceMarkers.findDerivedResourceMarker(iFile, uri);
        if (marker != null) marker.delete();
        if (derivedResourceMarkers.findDerivedResourceMarkers(iFile).length == 0) {
          access.deleteFile(iFile, deleteMonitor);
          context.needRebuild();
        }
      }
    }
  }
Exemplo n.º 17
0
  @Override
  protected void pushApplication(
      CloudFoundryOperations client,
      final CloudFoundryApplicationModule appModule,
      ApplicationArchive applicationArchive,
      final IProgressMonitor monitor)
      throws CoreException {
    String appName = appModule.getDeploymentInfo().getDeploymentName();

    CloudApplication existingApp = null;

    try {
      existingApp = getBehaviour().getCloudApplication(appName, monitor);
    } catch (CoreException ce) {
      if (!CloudErrorUtil.isNotFoundException(ce)) {
        throw ce;
      }
    }

    // Create the application if it doesn't already exist
    if (existingApp == null) {
      String creatingAppLabel = NLS.bind(Messages.CONSOLE_APP_CREATION, appName);
      getBehaviour().printlnToConsole(appModule, creatingAppLabel);

      // BUG - [87862532]: Fetch all the information BEFORE
      // creating the application. The reason for this
      // is to prevent any other operation that updates the module from
      // clearing the deploymentinfo after the application is created
      // but before other properties are updated like environment
      // variables
      // and instances
      Staging staging = appModule.getDeploymentInfo().getStaging();
      List<String> uris =
          appModule.getDeploymentInfo().getUris() != null
              ? appModule.getDeploymentInfo().getUris()
              : new ArrayList<String>(0);
      List<String> services = appModule.getDeploymentInfo().asServiceBindingList();
      List<EnvironmentVariable> variables = appModule.getDeploymentInfo().getEnvVariables();
      int instances = appModule.getDeploymentInfo().getInstances();

      if (staging == null) {
        // For v2, a non-null staging is required.
        staging = new Staging();
      }
      CoreException cloudAppCreationClientError = null;

      // Guard against host taken errors and other errors that may
      // create the app but
      // prevent further deployment. If the app was still created
      // attempt to set env vars and instaces
      SubMonitor subMonitor = SubMonitor.convert(monitor, 50);
      subMonitor.subTask(creatingAppLabel);
      try {
        client.createApplication(
            appName, staging, appModule.getDeploymentInfo().getMemory(), uris, services);
      } catch (Exception e) {
        String hostTaken = CloudErrorUtil.getHostTakenError(e);
        if (hostTaken != null) {
          cloudAppCreationClientError = CloudErrorUtil.toCoreException(hostTaken);
        } else {
          cloudAppCreationClientError = CloudErrorUtil.toCoreException(e);
        }
      }

      subMonitor.worked(30);

      // [87881946] - Try setting the env vars and instances even if an
      // error was thrown while creating the application
      // as the application may still have been created in the Cloud space
      // in spite of the error
      try {
        CloudApplication actualApp =
            getBehaviour().getCloudApplication(appName, subMonitor.newChild(20));

        if (actualApp != null) {
          SubMonitor updateMonitor = SubMonitor.convert(subMonitor, 100);
          getBehaviour()
              .getRequestFactory()
              .getUpdateEnvVarRequest(appName, variables)
              .run(updateMonitor.newChild(50));

          // Update instances if it is more than 1. By default, app
          // starts
          // with 1 instance.

          if (instances > 1) {
            getBehaviour()
                .updateApplicationInstances(appName, instances, updateMonitor.newChild(50));
          } else {
            updateMonitor.worked(50);
          }
        }
      } catch (CoreException ce) {
        if (cloudAppCreationClientError == null) {
          throw ce;
        }
      }

      // Even if application was created in the Cloud space, and env vars
      // and instances set, if an exception
      // was thrown while creating the client, throw it
      if (cloudAppCreationClientError != null) {
        throw cloudAppCreationClientError;
      }
    }
    super.pushApplication(client, appModule, applicationArchive, monitor);
  }
  private static IStatus collectServerInfos(
      String address,
      int port,
      final SpecialAddress special,
      final List<RemoteR> infos,
      final SubMonitor progress) {
    try {
      if (special != null) {
        address = special.fPublicHost;
        port = special.fPort;
      }
      progress.subTask(
          NLS.bind(Messages.RRemoteConsoleSelectionDialog_task_Resolving_message, address));
      final InetAddress inetAddress = InetAddress.getByName(address);
      final String hostname = inetAddress.getHostName();
      final String hostip = inetAddress.getHostAddress();
      progress.worked(1);
      if (progress.isCanceled()) {
        return Status.CANCEL_STATUS;
      }

      progress.subTask(
          NLS.bind(Messages.RRemoteConsoleSelectionDialog_task_Connecting_message, hostname));
      final Registry registry;
      if (special != null) {
        final RMIClientSocketFactory socketFactory = special.getSocketFactory(progress.newChild(5));
        RjsComConfig.setRMIClientSocketFactory(socketFactory);
        registry = LocateRegistry.getRegistry(special.fPrivateHost, port, socketFactory);
      } else {
        RjsComConfig.setRMIClientSocketFactory(null);
        registry = LocateRegistry.getRegistry(address, port);
      }
      final String rmiBase =
          (port == Registry.REGISTRY_PORT)
              ? "//" + address + '/'
              : //$NON-NLS-1$
              "//" + address + ':' + port + '/'; // $NON-NLS-1$
      final String[] names = registry.list();
      for (final String name : names) {
        try {
          final Remote remote = registry.lookup(name);
          if (remote instanceof Server) {
            final Server server = (Server) remote;
            final ServerInfo info = server.getInfo();
            final String rmiAddress = rmiBase + name;
            final RemoteR r = new RemoteR(hostname, hostip, rmiAddress, info);
            infos.add(r);
          }
        } catch (final Exception e) {
        }
      }
      return Status.OK_STATUS;
    } catch (final RemoteException e) {
      return new Status(IStatus.WARNING, RConsoleUIPlugin.PLUGIN_ID, address);
    } catch (final UnknownHostException e) {
      return new Status(
          IStatus.ERROR,
          RConsoleUIPlugin.PLUGIN_ID,
          "Unknown host: " + e.getLocalizedMessage()); // $NON-NLS-1$
    } catch (final CoreException e) {
      return e.getStatus();
    } finally {
      RjsComConfig.clearRMIClientSocketFactory();
    }
  }