@Override
 public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
   pm.beginTask("", 2); // $NON-NLS-1$
   RefactoringStatus result;
   try {
     result = new RefactoringStatus();
     IJavaElement element = (IJavaElement) getModifiedElement();
     // don't check for read-only since we don't go through
     // validate edit.
     result.merge(super.isValid(new SubProgressMonitor(pm, 1)));
     if (result.hasFatalError()) return result;
     if (element != null && element.exists() && element instanceof IPackageFragment) {
       IPackageFragment pack = (IPackageFragment) element;
       if (fRenameSubpackages) {
         IPackageFragment[] allPackages = JavaElementUtil.getPackageAndSubpackages(pack);
         SubProgressMonitor subPm = new SubProgressMonitor(pm, 1);
         subPm.beginTask("", allPackages.length); // $NON-NLS-1$
         for (int i = 0; i < allPackages.length; i++) {
           // don't check for read-only since we don't go through
           // validate edit.
           checkIfModifiable(result, allPackages[i].getResource(), VALIDATE_NOT_DIRTY);
           if (result.hasFatalError()) return result;
           isValid(result, allPackages[i], new SubProgressMonitor(subPm, 1));
         }
       } else {
         isValid(result, pack, new SubProgressMonitor(pm, 1));
       }
     }
   } finally {
     pm.done();
   }
   return result;
 }
  /**
   * Reports progress by creating a balanced binary tree of progress monitors. Simulates mixed usage
   * of IProgressMonitor in a typical usage. Calls isCanceled once each time work is reported. Half
   * of the work is reported using internalWorked and half is reported using worked, to simulate
   * mixed usage of the progress monitor.
   *
   * @deprecated to suppress deprecation warnings
   * @param monitor progress monitor (callers are responsible for calling done() if necessary)
   * @param loopSize total size of the recursion tree
   */
  public static void reportWorkInBalancedTree(IProgressMonitor monitor, int loopSize) {
    monitor.beginTask("", 100);
    int leftBranch = loopSize / 2;
    int rightBranch = loopSize - leftBranch;

    if (leftBranch > 1) {
      SubProgressMonitor leftProgress = new SubProgressMonitor(monitor, 50);
      reportWorkInBalancedTree(leftProgress, leftBranch);
      leftProgress.done();
    } else {
      monitor.worked(25);
      monitor.internalWorked(25.0);
      monitor.isCanceled();
    }

    if (rightBranch > 1) {
      SubProgressMonitor rightProgress = new SubProgressMonitor(monitor, 50);
      reportWorkInBalancedTree(rightProgress, rightBranch);
      rightProgress.done();
    } else {
      monitor.worked(25);
      monitor.internalWorked(25.0);
      monitor.isCanceled();
    }
  }
Exemplo n.º 3
0
 /** Dispose any members at the end of the day. */
 public void dispose(IProgressMonitor monitor) {
   monitor.beginTask(Messages.ICatalog_dispose, 100);
   List<? extends IResolve> members;
   try {
     members = members(new SubProgressMonitor(monitor, 1));
   } catch (Throwable e) {
     ErrorManager.get()
         .displayException(
             e,
             "Error disposing members of catalog: " + getIdentifier(),
             CatalogPlugin.ID); // $NON-NLS-1$
     return;
   }
   int steps = (int) ((double) 99 / (double) members.size());
   for (IResolve resolve : members) {
     try {
       SubProgressMonitor subProgressMonitor = new SubProgressMonitor(monitor, steps);
       resolve.dispose(subProgressMonitor);
       subProgressMonitor.done();
     } catch (Throwable e) {
       ErrorManager.get()
           .displayException(
               e,
               "Error disposing members of catalog: " + getIdentifier(),
               CatalogPlugin.ID); // $NON-NLS-1$
     }
   }
 }
  /**
   * Allows a given set or subset of runtime detectors the ability to search through a folder
   *
   * @param directory
   * @param runtimeCollector
   * @param depth
   * @param runtimeDetectors
   * @param monitor
   */
  public void searchDirectory(
      File directory,
      List<RuntimeDefinition> runtimeCollector,
      int depth,
      Set<IRuntimeDetector> runtimeDetectors,
      IProgressMonitor monitor) {

    if (depth == 0 || monitor.isCanceled() || directory == null || !directory.isDirectory()) {
      return;
    }

    int workSize = (1000 + (10 * runtimeDetectors.size()));
    monitor.beginTask(
        Messages.JBossRuntimeLocator_Searching + directory.getAbsolutePath(), workSize);
    monitor.setTaskName(Messages.JBossRuntimeLocator_Searching + directory.getAbsolutePath());

    for (IRuntimeDetector detector : runtimeDetectors) {
      if (monitor.isCanceled()) {
        return;
      }
      if (!detector.isEnabled()) {
        monitor.worked(10);
        continue;
      }
      RuntimeDefinition runtimeDefinition =
          detector.getRuntimeDefinition(directory, new SubProgressMonitor(monitor, 10));
      if (runtimeDefinition != null) {
        runtimeCollector.add(runtimeDefinition);
        monitor.done();
        return;
      }
    }

    File[] files =
        directory.listFiles(
            new FileFilter() {
              public boolean accept(File file) {
                return file.isDirectory();
              }
            });

    SubProgressMonitor childrenMonitor = new SubProgressMonitor(monitor, 1000);
    childrenMonitor.beginTask("", 100 * files.length);
    if (files != null) {
      int size = files.length;
      for (int i = 0; i < size; i++) {
        if (monitor.isCanceled()) return;
        searchDirectory(
            files[i],
            runtimeCollector,
            depth - 1,
            runtimeDetectors,
            new SubProgressMonitor(childrenMonitor, 100));
      }
    }
    childrenMonitor.done();
  }
  /**
   * Creates and destroys the given number of child progress monitors under the given parent.
   *
   * @param monitor monitor to create children under. The caller must call done on this monitor if
   *     necessary.
   * @param progressSize total number of children to create.
   * @deprecated to suppress deprecation warnings
   */
  private static void createChildrenUnderParent(IProgressMonitor monitor, int progressSize) {
    monitor.beginTask("", progressSize);

    for (int count = 0; count < progressSize; count++) {
      SubProgressMonitor mon = new SubProgressMonitor(monitor, 1);
      mon.beginTask("", 100);
      mon.done();
    }
  }
 /**
  * Calls done on the given progress monitor and all of its parents, to a maximum of the given
  * depth.
  *
  * @deprecated to suppress deprecation warnings
  * @param monitor
  * @param depth
  */
 public static void callDoneOnChain(IProgressMonitor monitor, int depth) {
   IProgressMonitor current = monitor;
   for (int count = 0; count < depth; count++) {
     current.done();
     if (!(current instanceof SubProgressMonitor)) return;
     SubProgressMonitor cur = (SubProgressMonitor) current;
     current = cur.getWrappedProgressMonitor();
   }
 }
  public void rollback(IProgressMonitor monitor) throws Exception {
    monitor.beginTask(Messages.AddFeaturesCommand_undoTaskMessage, commands.size() * 2);

    for (int i = commands.size() - 1; i > -1; i--) {
      SubProgressMonitor subProgressMonitor = new SubProgressMonitor(monitor, 2);
      commands.get(i).rollback(subProgressMonitor);
      subProgressMonitor.done();
    }
    monitor.done();
  }
Exemplo n.º 8
0
  private void buildMetaInf(IPath outputLocation, IProgressMonitor monitor)
      throws CoreException, JavaModelException {
    IProject project = getProject();
    IFolder metaInf = project.getFolder(META_INF);

    if (!metaInf.exists()) {
      error("META-INF folder not found for project: " + getProject().getName()); // $NON-NLS-1$
      return;
    }

    IFolder binFolder = ResourcesPlugin.getWorkspace().getRoot().getFolder(outputLocation);
    if (!binFolder.exists()) {
      binFolder.create(true, true, null);
    } else {
      binFolder.refreshLocal(IResource.DEPTH_ONE, null);
    }
    IFolder binaryMetaInf = binFolder.getFolder(META_INF);
    if (!binaryMetaInf.exists()) {
      binaryMetaInf.create(true, true, null);
    } else {
      binaryMetaInf.refreshLocal(IResource.DEPTH_ONE, null);
    }

    SubProgressMonitor sub = new SubProgressMonitor(monitor, 1);

    IResource[] children = metaInf.members();
    sub.beginTask(Messages.Builder_CopyMetaInfContent, children.length);
    for (IResource iResource : children) {
      if (!iResource.isTeamPrivateMember() && !iResource.isDerived()) {
        IPath target = binaryMetaInf.getFullPath().append(iResource.getName());
        IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(target);
        if (res != null && res.exists()) {
          if (DEBUG) {
            debug(res.getFullPath().toString() + " exists, deleting"); // $NON-NLS-1$
          }
          res.refreshLocal(IResource.DEPTH_INFINITE, null);
          res.delete(true, null);
          if (DEBUG) {
            debug(res.getFullPath().toString() + " deleted"); // $NON-NLS-1$
          }
        }
        iResource.copy(target, true, null);
        if (DEBUG) {
          debug(
              "Copied "
                  + iResource.getFullPath().toString()
                  + " to "
                  + target.toString()); // $NON-NLS-1$ //$NON-NLS-2$
        }
      }
      sub.worked(1);
    }
    monitor.done();
  }
Exemplo n.º 9
0
  public IStatus build(
      org.emftext.language.sql.resource.sql.mopp.SqlResource resource, IProgressMonitor monitor) {
    // Set option 'overrideBuilder' to 'false' and then perform build here.

    // We use one tick from the parent monitor because the BuilderAdapter reserves one
    // tick for the Builder.
    SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1);
    subMonitor.beginTask("Building " + resource.getURI().lastSegment(), 10);
    // The actual work of the builder can be performed here.
    subMonitor.worked(10);
    subMonitor.done();
    return Status.OK_STATUS;
  }
  /** Test SubProgressMonitor's created with negative a work value. */
  public void testNegativeWorkValues() {
    TestProgressMonitor top = new TestProgressMonitor();
    top.beginTask("", 10);

    SubProgressMonitor childMonitor = new SubProgressMonitor(top, IProgressMonitor.UNKNOWN); // -1
    childMonitor.beginTask("", 10);
    childMonitor.worked(5);
    Assert.assertEquals(0.0, top.getTotalWork(), 0.01d);
    childMonitor.done();
    Assert.assertEquals(0.0, top.getTotalWork(), 0.01d);

    top.done();
  }
Exemplo n.º 11
0
 static ICompilationUnit[] createNewWorkingCopies(
     ICompilationUnit[] compilationUnitsToModify,
     TextChangeManager manager,
     WorkingCopyOwner owner,
     SubProgressMonitor pm)
     throws CoreException {
   pm.beginTask("", compilationUnitsToModify.length); // $NON-NLS-1$
   ICompilationUnit[] newWorkingCopies = new ICompilationUnit[compilationUnitsToModify.length];
   for (int i = 0; i < compilationUnitsToModify.length; i++) {
     ICompilationUnit cu = compilationUnitsToModify[i];
     newWorkingCopies[i] = createNewWorkingCopy(cu, manager, owner, new SubProgressMonitor(pm, 1));
   }
   pm.done();
   return newWorkingCopies;
 }
    @Override
    public IStatus run(final IProgressMonitor monitor) {
      monitor.beginTask(Messages.LifecycleDeployHandler_Task_Starting, this.resources.length);
      for (final IResource resource : this.resources) {
        final IProject project = resource.getProject();
        monitor.setTaskName(Messages.LifecycleDeployHandler_Task_RunFor + project.getName());

        final IMavenJobData jobData =
            new IMavenJobData() {

              @Override
              public void manipulateRequest(final MavenExecutionRequest request) {
                // empty
              }

              @Override
              public IProject getProject() {
                return project;
              }

              @Override
              public String[] getMavenCommands() {
                return new String[] {"deploy"}; // $NON-NLS-1$
              }

              @Override
              public boolean canProcessRequest(
                  final MavenExecutionRequest request, final IMavenProjectFacade projectFacade) {
                return true;
              }
            };
        final MavenJob job = new MavenJob(jobData);
        final SubProgressMonitor subMonitor =
            new SubProgressMonitor(monitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
        final IStatus mavenResult = job.execute(subMonitor);
        subMonitor.done();

        if (!mavenResult.isOK()) {
          monitor.done();
          this.done(mavenResult);
          return mavenResult;
        }
      }
      monitor.done();
      this.done(Status.OK_STATUS);
      return Status.OK_STATUS;
    }
  /**
   * Creates a balanced binary tree of progress monitors, without calling worked. Tests progress
   * monitor creation and cleanup time, and ensures that excess progress is being collected when
   * IProgressMonitor.done() is called.
   *
   * @deprecated to suppress deprecation warnings
   * @param monitor progress monitor (callers are responsible for calling done() if necessary)
   * @param loopSize total size of the recursion tree
   */
  public static void createBalancedTree(IProgressMonitor monitor, int loopSize) {
    monitor.beginTask("", 100);
    int leftBranch = loopSize / 2;
    int rightBranch = loopSize - leftBranch;

    if (leftBranch > 1) {
      SubProgressMonitor leftProgress = new SubProgressMonitor(monitor, 50);
      createBalancedTree(leftProgress, leftBranch);
      leftProgress.done();
    }

    if (rightBranch > 1) {
      SubProgressMonitor rightProgress = new SubProgressMonitor(monitor, 50);
      createBalancedTree(rightProgress, rightBranch);
      rightProgress.done();
    }
  }
  /** @see net.refractions.udig.project.internal.command.MapCommand#run() */
  @SuppressWarnings("deprecation")
  public void run(IProgressMonitor monitor) throws Exception {
    monitor.beginTask(Messages.WriteFeatureChangesCommand_runTask, 3);
    SubProgressMonitor subProgressMonitor = new SubProgressMonitor(monitor, 1);
    editFeature = featureProvider.get(subProgressMonitor);
    subProgressMonitor.done();
    store = storeProvider.get(subProgressMonitor);
    if (editFeature == null || store == null) {
      noChange = true;
      return;
    }

    FeatureType featureType = editFeature.getFeatureType();
    FilterFactory factory = FilterFactoryFinder.createFilterFactory();
    subProgressMonitor = new SubProgressMonitor(monitor, 1);
    subProgressMonitor.done();
    filter = factory.createFidFilter(editFeature.getID());
    FeatureCollection results = store.getFeatures(filter);

    FeatureIterator reader = results.features();
    try {
      if (reader.hasNext()) {
        try {
          store.modifyFeatures(
              featureType.getAttributeTypes(),
              editFeature.getAttributes(new Object[featureType.getAttributeCount()]),
              filter);
        } catch (Exception e) {
          ProjectPlugin.log("", e); // $NON-NLS-1$
          noChange = true;
        }

      } else {
        added = true;
        store.addFeatures(
            new StaticFeatureCollection(Collections.singleton(editFeature), featureType));
      }
    } finally {
      if (reader != null) reader.close();
    }
  }
Exemplo n.º 15
0
  /**
   * called from within a job
   *
   * @param monitor
   */
  public void evaluateChecks(
      Collection<ITypingCheck> checks, IProject project, IProgressMonitor monitor) {
    SubProgressMonitor monitor2 = new SubProgressMonitor(monitor, 1);
    monitor2.beginTask("Evaluating type checks...", checks.size() + 10);

    // called from within a job!
    IEvaluationStrategy strategy = null;

    try {
      strategy = EvaluationStrategyManager.getInstance().getEvaluationStrategy(project);
      // cannot check anything without a strategy
      if (strategy == null) return;
    } catch (FeatureModelNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    monitor2.worked(10);

    int i = 0;
    for (ITypingCheck check : checks) {
      i++;
      if (i % 25 == 0) {
        monitor2.subTask("Evaluating type check " + i + "/" + checks.size());
        monitor2.worked(25);
      }

      boolean isWelltyped = check.evaluate(strategy);

      if (!isWelltyped) markIlltyped(check);
      else markWelltyped(check);
    }

    monitor2.done();
  }
  public void run(IProgressMonitor monitor) throws Exception {
    monitor.beginTask(Messages.AddFeaturesCommand_taskMessage, 10);
    monitor.worked(1);

    FeatureStore<SimpleFeatureType, SimpleFeature> store =
        layer.getResource(FeatureStore.class, new SubProgressMonitor(monitor, 2));
    String geomAttributeName = layer.getSchema().getGeometryDescriptor().getLocalName();
    String[] desiredProperties = new String[] {geomAttributeName};
    Query query = new DefaultQuery(layer.getSchema().getTypeName(), filter, desiredProperties);
    FeatureCollection<SimpleFeatureType, SimpleFeature> features = store.getFeatures(query);

    FeatureIterator<SimpleFeature> iter = features.features();
    try {
      commands = new ArrayList<UndoableMapCommand>();
      while (iter.hasNext()) {
        SimpleFeature feature = iter.next();
        commands.add(new SelectFeatureCommand(bb, feature));
      }

      float index = 0;
      float inc = (float) 7 / commands.size();
      for (UndoableMapCommand command : commands) {
        command.setMap(getMap());
        index += inc;
        SubProgressMonitor subProgressMonitor = new SubProgressMonitor(monitor, (int) index);
        command.run(subProgressMonitor);
        subProgressMonitor.done();
        if (index > 1) {
          index = 0;
        }
      }
    } finally {
      features.close(iter);
    }

    monitor.done();
  }
Exemplo n.º 17
0
 // FIXME deal with interfaces/implementations
 public final void addFrom(final IJavaElement scope, final SubProgressMonitor progressMonitor)
     throws CoreException {
   progressMonitor.beginTask("Adding resources and resourceMethods", 1);
   HTTPMethods httpMethods = metamodel.getHttpMethods();
   List<IType> javaTypes =
       JAXRSAnnotationsScanner.findResources(scope, httpMethods.getTypeNames(), progressMonitor);
   for (IType javaType : javaTypes) {
     try {
       resources.put(
           javaType.getFullyQualifiedName(), new Resource(javaType, metamodel, progressMonitor));
     } catch (InvalidModelElementException e) {
       Logger.warn(
           "Type '"
               + javaType.getFullyQualifiedName()
               + "' is not a valid JAX-RS Resource: "
               + e.getMessage());
     }
   }
 }
Exemplo n.º 18
0
    @Override
    public IStatus run(final IProgressMonitor monitor) {
      monitor.beginTask(Messages.InfoPhpHandler_Task_Starting, this.resources.length);
      for (final IResource resource : this.resources) {
        final IProject project = resource.getProject();
        monitor.setTaskName(Messages.InfoPhpHandler_Task_RunFor + project.getName());

        final IMavenProjectFacade facade = MavenPhpUtils.fetchProjectFacade(project);
        final IFolder targetFolder =
            project.getFolder(
                facade.getOutputLocation().removeFirstSegments(1).append("eclipse")); // $NON-NLS-1$
        final IFile phpInfoPhp = targetFolder.getFile("phpinfo.php"); // $NON-NLS-1$
        final IFile phpInfoTxt = targetFolder.getFile("phpinfo.txt"); // $NON-NLS-1$
        try {
          ResourceUtils.mkdirs(targetFolder);
          if (phpInfoPhp.exists()) {
            phpInfoPhp.setContents(
                new ByteArrayInputStream(
                    ("<?php\n"
                            + //$NON-NLS-1$
                            "ob_start();\n"
                            + //$NON-NLS-1$
                            "phpinfo();\n"
                            + //$NON-NLS-1$
                            "file_put_contents(__DIR__.'/phpinfo.txt', ob_get_contents());\n"
                            + //$NON-NLS-1$
                            "ob_end_clean();\n")
                        .getBytes()),
                IResource.FORCE,
                monitor); //$NON-NLS-1$
          } else {
            phpInfoPhp.create(
                new ByteArrayInputStream(
                    ("<?php\n"
                            + //$NON-NLS-1$
                            "ob_start();\n"
                            + //$NON-NLS-1$
                            "phpinfo();\n"
                            + //$NON-NLS-1$
                            "file_put_contents(__DIR__.'/phpinfo.txt', ob_get_contents());\n"
                            + //$NON-NLS-1$
                            "ob_end_clean();\n")
                        .getBytes()),
                IResource.FORCE,
                monitor); //$NON-NLS-1$
          }
        } catch (CoreException ex) {
          final IStatus status =
              new Status(
                  IStatus.ERROR,
                  PhpmavenUiPlugin.PLUGIN_ID,
                  Messages.InfoPhpHandler_ErrorCreatingPhpinfoPhp,
                  ex);
          monitor.done();
          this.done(status);
          return status;
        }

        String phpMavenVersion = null;
        try {
          phpMavenVersion = MavenPhpUtils.getPhpmavenVersion(facade);
        } catch (CoreException ex) {
          final IStatus status =
              new Status(
                  IStatus.ERROR,
                  PhpmavenUiPlugin.PLUGIN_ID,
                  Messages.InfoPhpHandler_ErrorFetchingPhpmavenVersion,
                  ex);
          monitor.done();
          this.done(status);
          return status;
        }
        final String mavenCommand =
            "org.phpmaven:maven-php-plugin:"
                + phpMavenVersion
                + ":exec"; //$NON-NLS-1$ //$NON-NLS-2$

        final IMavenJobData jobData =
            new IMavenJobData() {

              @Override
              public void manipulateRequest(final MavenExecutionRequest request) {
                final Properties sysProps = request.getSystemProperties();
                sysProps.put("phpFile", phpInfoPhp.getLocation().toOSString()); // $NON-NLS-1$
              }

              @Override
              public IProject getProject() {
                return project;
              }

              @Override
              public String[] getMavenCommands() {
                return new String[] {mavenCommand};
              }

              @Override
              public boolean canProcessRequest(
                  final MavenExecutionRequest request, final IMavenProjectFacade projectFacade) {
                return true;
              }
            };
        final MavenJob job = new MavenJob(jobData);
        final SubProgressMonitor subMonitor =
            new SubProgressMonitor(monitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
        final IStatus mavenResult = job.execute(subMonitor);
        subMonitor.done();

        if (!mavenResult.isOK()) {
          monitor.done();
          this.done(mavenResult);
          return mavenResult;
        }

        final Job job2 = new ExecutionUiJob(Messages.InfoPhpHandler_DisplayingInfo, phpInfoTxt);
        job2.setRule(this.getRule());
        job2.setUser(false);
        job2.schedule();
      }
      monitor.done();
      this.done(Status.OK_STATUS);
      return Status.OK_STATUS;
    }
  @SuppressWarnings("unchecked")
  private void copyFeatures(
      ILayer sourceLayer, Filter filter, final Layer targetLayer, final IProgressMonitor monitor) {
    monitor.beginTask(Messages.CopyFeaturesCommand_name, 104);
    final int[] worked = new int[] {-3};
    monitor.worked(1);
    try {
      SubProgressMonitor subProgressMonitor = new SubProgressMonitor(monitor, 2);
      FeatureStore<SimpleFeatureType, SimpleFeature> destination =
          targetLayer.getResource(FeatureStore.class, subProgressMonitor);
      subProgressMonitor.done();
      worked[0] += 2;
      subProgressMonitor = new SubProgressMonitor(monitor, 2);
      FeatureSource<SimpleFeatureType, SimpleFeature> source =
          sourceLayer.getResource(FeatureSource.class, subProgressMonitor);
      subProgressMonitor.done();
      worked[0] += 2;
      // If no FeatureStore then features can't be copied
      // If no FeatureSource then features can't be copied
      if (destination == null || source == null) {
        targetLayer.setFilter(filter);
        return;
      }

      // Create a query that will get the attributes that are compatible
      // what is compatible? Do the attribute names and types have to be the same or
      // just the types.
      // Executive decision:
      // Match both name and type, the rest must be customized.
      final HashMap<String, String> attributeMap = new HashMap<String, String>();
      Query query = createQuery(sourceLayer, filter, targetLayer, attributeMap);
      if (attributeMap.isEmpty()) {
        targetLayer.setFilter(filter);
        return;
      }
      MathTransform mt = createMathTransform(sourceLayer, targetLayer);
      FeatureCollection<SimpleFeatureType, SimpleFeature> features = source.getFeatures(query);
      SimpleFeatureType schema = targetLayer.getSchema();

      CopyFeatureCollection c =
          new CopyFeatureCollection(
              schema,
              features,
              monitor,
              worked,
              mt,
              attributeMap,
              targetLayer.layerToMapTransform());
      Envelope env = c.env;
      targetLayer.eSetDeliver(false);
      try {
        List<FeatureId> fids = destination.addFeatures(c);

        displayCopiedFeatures(env);

        FilterFactory filterFactory =
            CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
        addedFeaturesFilter = filterFactory.id(new HashSet(fids));
      } finally {
        targetLayer.eSetDeliver(true);
      }
      getMap().getRenderManager().refresh(targetLayer, env);
    } catch (IOException e) {
      throw (RuntimeException) new RuntimeException().initCause(e);
    } finally {
      monitor.done();
    }
  }
  /** @deprecated to suppress deprecation warnings */
  public void testCancellation() {
    TestProgressMonitor root = new TestProgressMonitor();
    root.beginTask("", 1000);

    SubProgressMonitor spm = new SubProgressMonitor(root, 1000);

    // Test that changes at the root propogate to the child
    root.setCanceled(true);
    Assert.assertTrue(spm.isCanceled());
    root.setCanceled(false);
    Assert.assertFalse(spm.isCanceled());

    // Test that changes to the child propogate to the root
    spm.setCanceled(true);
    Assert.assertTrue(root.isCanceled());
    spm.setCanceled(false);
    Assert.assertFalse(root.isCanceled());

    // Test a chain of depth 2
    spm.beginTask("", 1000);
    SubProgressMonitor spm2 = new SubProgressMonitor(spm, 1000);

    // Test that changes at the root propogate to the child
    root.setCanceled(true);
    Assert.assertTrue(spm2.isCanceled());
    root.setCanceled(false);
    Assert.assertFalse(spm2.isCanceled());

    // Test that changes to the child propogate to the root
    spm2.setCanceled(true);
    Assert.assertTrue(root.isCanceled());
    spm2.setCanceled(false);
    Assert.assertFalse(root.isCanceled());
  }
  /**
   * Tests the automatic cleanup when progress monitors are created via their constructor
   *
   * @deprecated to suppress deprecation warnings
   */
  public void testParallelChildren() {
    TestProgressMonitor top = new TestProgressMonitor();
    top.beginTask("", 1000);
    SubProgressMonitor mon = new SubProgressMonitor(top, 1000);
    mon.beginTask("", 1000);

    SubProgressMonitor monitor1 = new SubProgressMonitor(mon, 200);
    SubProgressMonitor monitor2 = new SubProgressMonitor(mon, 200);

    Assert.assertEquals("Ensure no work has been reported yet", 0.0, top.getTotalWork(), 0.01d);
    monitor1.beginTask("", 1000);
    Assert.assertEquals("Ensure no work has been reported yet", 0.0, top.getTotalWork(), 0.01d);
    monitor2.beginTask("", 1000);
    Assert.assertEquals("Should not have cleaned up monitor 1", 0.0, top.getTotalWork(), 0.01d);
    monitor1.done();

    Assert.assertEquals("Should have cleaned up monitor 1", 200.0, top.getTotalWork(), 0.01d);
    monitor1.worked(1000);
    Assert.assertEquals(
        "Monitor1 shouldn't report work once it's complete", 200.0, top.getTotalWork(), 0.01d);
    monitor2.worked(500);
    Assert.assertEquals(300.0, top.getTotalWork(), 0.01d);

    // Create a monitor that will leak - monitors won't be auto-completed until their done methods
    // are
    // called
    SubProgressMonitor monitor3 = new SubProgressMonitor(mon, 300);
    Assert.assertEquals(
        "Monitor2 should not have been cleaned up yet", 300.0, top.getTotalWork(), 0.01d);
    SubProgressMonitor monitor4 = new SubProgressMonitor(mon, 300);
    monitor4.beginTask("", 100);
    mon.done();
    Assert.assertNotNull(monitor3);

    Assert.assertEquals(
        "All leaked work should have been collected", 1000.0, top.getTotalWork(), 0.01d);
  }
  /**
   * Tests SubProgressMonitor nesting when using the default constructor. Tests constructors in int
   * mode.
   *
   * @deprecated to suppress deprecation warnings
   */
  public void testConstructorNestingInt() {
    TestProgressMonitor top = new TestProgressMonitor();
    top.beginTask("", 2000);

    // Create an SPM leave it in int mode, and consume half its work
    SubProgressMonitor fpMonitor = new SubProgressMonitor(top, 1000);
    fpMonitor.beginTask("", 100);
    fpMonitor.worked(50);

    Assert.assertEquals(500.0, top.getTotalWork(), 0.01d);

    // Create a child monitor, and ensure that it grabs the correct amount of work
    // from the parent.
    SubProgressMonitor childMonitor = new SubProgressMonitor(fpMonitor, 20);
    childMonitor.beginTask("", 100);
    childMonitor.worked(100);
    childMonitor.done();

    Assert.assertEquals(700.0, top.getTotalWork(), 0.01d);

    // Create a child monitor, and ensure that it grabs the correct amount of work
    // from the parent.
    SubProgressMonitor childMonitor2 = new SubProgressMonitor(fpMonitor, 30);
    childMonitor2.beginTask("", 100);
    childMonitor2.worked(100);
    childMonitor2.done();

    Assert.assertEquals(1000.0, top.getTotalWork(), 0.01d);

    // Ensure that creating another child will have no effect
    SubProgressMonitor childMonitor3 = new SubProgressMonitor(fpMonitor, 10);
    childMonitor3.beginTask("", 100);
    childMonitor3.worked(100);
    childMonitor3.done();

    Assert.assertEquals(1000.0, top.getTotalWork(), 0.01d);
    fpMonitor.worked(100);
    Assert.assertEquals(1000.0, top.getTotalWork(), 0.01d);
    fpMonitor.done();
    Assert.assertEquals(1000.0, top.getTotalWork(), 0.01d);
  }
  /**
   * Tests the style bits in SubProgressMonitor
   *
   * @deprecated to suppress deprecation warnings
   */
  public void testStyles() {

    int[] styles =
        new int[] {
          0,
          SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK,
          SubProgressMonitor.SUPPRESS_SUBTASK_LABEL,
          SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK
              | SubProgressMonitor.SUPPRESS_SUBTASK_LABEL
        };

    HashMap expected = new HashMap();
    expected.put("style 0 below style 2", new String[] {"setTaskName0", "", "setTaskName1"});
    expected.put(
        "style 2 below style 0", new String[] {"setTaskName1", "beginTask1 ", "setTaskName1"});
    expected.put(
        "style 6 below style 0", new String[] {"setTaskName1", "beginTask1 ", "setTaskName1"});
    expected.put(
        "style 2 below style 4",
        new String[] {"setTaskName1", "beginTask0 beginTask1 ", "setTaskName1"});
    expected.put(
        "style 0 below style 0", new String[] {"setTaskName0", "subTask1", "setTaskName1"});
    expected.put("style 6 as top-level monitor", new String[] {"", "", "setTaskName0"});
    expected.put("style 6 below style 2", new String[] {"setTaskName1", "", "setTaskName1"});
    expected.put("style 6 below style 6", new String[] {"setTaskName1", "", "setTaskName1"});
    expected.put("style 0 below style 6", new String[] {"setTaskName0", "", "setTaskName1"});
    expected.put("style 4 below style 2", new String[] {"setTaskName1", "", "setTaskName1"});
    expected.put("style 0 as top-level monitor", new String[] {"", "subTask0", "setTaskName0"});
    expected.put(
        "style 0 below style 4",
        new String[] {"setTaskName0", "beginTask0 subTask1", "setTaskName1"});
    expected.put(
        "style 4 below style 0",
        new String[] {"setTaskName1", "beginTask1 subTask1", "setTaskName1"});
    expected.put(
        "style 4 as top-level monitor", new String[] {"", "beginTask0 subTask0", "setTaskName0"});
    expected.put("style 2 below style 6", new String[] {"setTaskName1", "", "setTaskName1"});
    expected.put("style 4 below style 6", new String[] {"setTaskName1", "", "setTaskName1"});
    expected.put("style 2 below style 2", new String[] {"setTaskName1", "", "setTaskName1"});
    expected.put("style 2 as top-level monitor", new String[] {"", "", "setTaskName0"});
    expected.put(
        "style 6 below style 4",
        new String[] {"setTaskName1", "beginTask0 beginTask1 ", "setTaskName1"});
    expected.put(
        "style 4 below style 4",
        new String[] {"setTaskName1", "beginTask0 beginTask1 subTask1", "setTaskName1"});
    HashMap results = new HashMap();

    for (int i = 0; i < styles.length; i++) {
      int style = styles[i];
      TestProgressMonitor top = new TestProgressMonitor();
      top.beginTask("", 100);
      SubProgressMonitor child = new SubProgressMonitor(top, 100, style);

      String testName = "style " + style + " as top-level monitor";
      results.put(testName, runChildTest(0, top, child, 100 * styles.length));

      for (int j = 0; j < styles.length; j++) {
        int innerStyle = styles[j];
        SubProgressMonitor innerChild = new SubProgressMonitor(child, 100, innerStyle);
        testName = "style " + innerStyle + " below style " + style;
        results.put(testName, runChildTest(1, top, innerChild, 100));
        innerChild.done();
      }
      child.done();
    }

    String failure = null;
    // Output the code for the observed results, in case one of them has changed intentionally
    for (Iterator iter = results.entrySet().iterator(); iter.hasNext(); ) {
      Map.Entry next = (Map.Entry) iter.next();
      String[] expectedResult = (String[]) expected.get(next.getKey());
      String[] value = (String[]) next.getValue();
      if (compareArray(value, expectedResult)) continue;

      System.out.print("expected.put(\"" + next.getKey() + "\", new String[] {");
      failure = (String) next.getKey();
      String list = concatArray(value);
      System.out.println(list + "});");
    }

    if (failure != null) // Now actually throw an assertation if one of the results failed
    Assert.assertEquals(
          failure,
          concatArray((String[]) expected.get(failure)),
          concatArray((String[]) results.get(failure)));
  }
Exemplo n.º 24
0
  /**
   * Generates a new key pair given the parameters in fheparams, stores the key locally and in the
   * keypair parameter
   *
   * @param fheparams the scheme parameters
   * @param keyPair holds the keypair
   */
  public GHKeyGen(FHEParams fheparams, GHKeyPair keyPair, IProgressMonitor monitor, int work) {
    t = fheparams.t;
    n = 1 << fheparams.logn;

    SubProgressMonitor sm = new SubProgressMonitor(monitor, work / 3);
    sm.beginTask("", work / 3);
    do { // try until HNF has the desired form, i.e. determinant is odd and lattice contains the
         // vector (-r,1,0,...,0)
      // generate random polynomial with coefficients uniformly random in [-2^t,2^t]
      v = Polynomial.randomPolynomial(n - 1, t);

      // verify whether the coefficient sum is odd, otherwise add 1
      int parity = 0;
      for (int i = 0; i < n; i++) {
        parity ^= (v.coeffs[i].testBit(0) ? 1 : 0);
      }
      if (parity == 0) v.coeffs[0].add(new BigInteger("1"));
      if (sm.isCanceled()) return;

    } while (!invModFx(v, fheparams.logn));
    sm.done();
    sm.beginTask("", work / 3);
    BigInteger sum = new BigInteger("0");
    BigInteger factor;
    // the public key blocks that squash the decryption scheme
    pkBlocksX = new BigInteger[fheparams.s];
    // the correct power such that \sum_pkBlocksX[i]*R^pkBlocksIdX[i] = w mod d
    int[] pkBlocksIdX = new int[fheparams.s];
    // make sure the sum is correct
    boolean sumtest = false;

    while (!sumtest) {
      sum = new BigInteger("0");
      // generate the first s-1 randomly
      for (int i = 0; i < fheparams.s - 1; i++) {
        byte[] temp = new byte[det.bitLength() / 8];
        r.nextBytes(temp);
        pkBlocksX[i] = (new BigInteger(temp)).abs().mod(det);
        pkBlocksIdX[i] = r.nextInt(fheparams.S);
        factor =
            (new BigInteger("2"))
                .modPow(
                    (new BigInteger(Integer.toString(pkBlocksIdX[i])))
                        .multiply(new BigInteger(Integer.toString(fheparams.logR))),
                    det);
        factor = (factor.multiply(pkBlocksX[i])).mod(det);
        sum = (sum.add(factor)).mod(det);
      }
      sum = w.subtract(sum).mod(det);
      // calculate the last x_i from the first s-1, try until the sum is invertible
      while (pkBlocksX[fheparams.s - 1] == null) {
        try {
          pkBlocksIdX[fheparams.s - 1] = r.nextInt(fheparams.S);
          factor =
              new BigInteger("2")
                  .modPow(
                      (new BigInteger(Integer.toString(pkBlocksIdX[fheparams.s - 1])))
                          .multiply(new BigInteger(Integer.toString(fheparams.logR))),
                      det);
          factor = factor.modInverse(det);
          pkBlocksX[fheparams.s - 1] = sum.multiply(factor).mod(det);
        } catch (ArithmeticException e) {

        }
        if (sm.isCanceled()) return;
      }
      // check whether \sum_pkBlocksX[i]*R^pkBlocksIdX[i] = w mod d
      sum = new BigInteger("0");
      for (int i = 0; i < fheparams.s; i++) {
        factor =
            new BigInteger("2")
                .modPow(
                    new BigInteger(Integer.toString(pkBlocksIdX[i]))
                        .multiply(new BigInteger(Integer.toString(fheparams.logR))),
                    det);
        factor = factor.multiply(pkBlocksX[i]).mod(det);
        sum = sum.add(factor).mod(det);
      }
      if (sum.compareTo(w) == 0) {
        sumtest = true;
      }
      if (sm.isCanceled()) return;
    }
    sm.done();
    // Compute the number of ciphertext for each progression,
    // i.e., an integer N such that N(N-1)/2 > S
    sm.beginTask("", work / 3);
    int nCtxts = (int) Math.ceil(2 * Math.sqrt(fheparams.S));
    int[] bits = new int[nCtxts * fheparams.s];
    for (int i = 0; i < fheparams.s; i++) {
      // let j1,j2 be the idx'th pair in {nCtxts choose 2}
      int j1, j2;
      int[] temp = encodeIndex(pkBlocksIdX[i], nCtxts);
      j1 = temp[0];
      j2 = temp[1];
      bits[i * nCtxts + j1] = bits[i * nCtxts + j2] = 1; // set these two bits to one
      if (sm.isCanceled()) return;
    }
    sm.done();
    ctxts = GHEncrypt.encrypt(fheparams, this, bits);
    keyPair.setKeyPair(det, root, w, ctxts, pkBlocksX);
  }