Ejemplo n.º 1
1
 @Override
 public int compare(Intent i1, Intent i2) {
   if (i1 == null && i2 == null) return 0;
   if (i1 == null && i2 != null) return -1;
   if (i1 != null && i2 == null) return 1;
   if (i1.equals(i2)) return 0;
   String action1 = i1.getAction();
   String action2 = i2.getAction();
   if (action1 == null && action2 != null) return -1;
   if (action1 != null && action2 == null) return 1;
   if (action1 != null && action2 != null) {
     if (!action1.equals(action2)) {
       return action1.compareTo(action2);
     }
   }
   Uri data1 = i1.getData();
   Uri data2 = i2.getData();
   if (data1 == null && data2 != null) return -1;
   if (data1 != null && data2 == null) return 1;
   if (data1 != null && data2 != null) {
     if (!data1.equals(data2)) {
       return data1.compareTo(data2);
     }
   }
   ComponentName component1 = i1.getComponent();
   ComponentName component2 = i2.getComponent();
   if (component1 == null && component2 != null) return -1;
   if (component1 != null && component2 == null) return 1;
   if (component1 != null && component2 != null) {
     if (!component1.equals(component2)) {
       return component1.compareTo(component2);
     }
   }
   String package1 = i1.getPackage();
   String package2 = i2.getPackage();
   if (package1 == null && package2 != null) return -1;
   if (package1 != null && package2 == null) return 1;
   if (package1 != null && package2 != null) {
     if (!package1.equals(package2)) {
       return package1.compareTo(package2);
     }
   }
   Set<String> categories1 = i1.getCategories();
   Set<String> categories2 = i2.getCategories();
   if (categories1 == null) return categories2 == null ? 0 : -1;
   if (categories2 == null) return 1;
   if (categories1.size() > categories2.size()) return 1;
   if (categories1.size() < categories2.size()) return -1;
   String[] array1 = categories1.toArray(new String[0]);
   String[] array2 = categories2.toArray(new String[0]);
   Arrays.sort(array1);
   Arrays.sort(array2);
   for (int i = 0; i < array1.length; ++i) {
     int val = array1[i].compareTo(array2[i]);
     if (val != 0) return val;
   }
   return 0;
 }
Ejemplo n.º 2
1
 @Override
 public int compare(Intent i1, Intent i2) {
   if (i1 == null && i2 == null) return 0;
   if (i1 == null && i2 != null) return -1;
   if (i1 != null && i2 == null) return 1;
   if (i1.equals(i2)) return 0;
   if (i1.getAction() == null && i2.getAction() != null) return -1;
   if (i1.getAction() != null && i2.getAction() == null) return 1;
   if (i1.getAction() != null && i2.getAction() != null) {
     if (!i1.getAction().equals(i2.getAction())) {
       return i1.getAction().compareTo(i2.getAction());
     }
   }
   if (i1.getData() == null && i2.getData() != null) return -1;
   if (i1.getData() != null && i2.getData() == null) return 1;
   if (i1.getData() != null && i2.getData() != null) {
     if (!i1.getData().equals(i2.getData())) {
       return i1.getData().compareTo(i2.getData());
     }
   }
   if (i1.getComponent() == null && i2.getComponent() != null) return -1;
   if (i1.getComponent() != null && i2.getComponent() == null) return 1;
   if (i1.getComponent() != null && i2.getComponent() != null) {
     if (!i1.getComponent().equals(i2.getComponent())) {
       return i1.getComponent().compareTo(i2.getComponent());
     }
   }
   if (i1.getPackage() == null && i2.getPackage() != null) return -1;
   if (i1.getPackage() != null && i2.getPackage() == null) return 1;
   if (i1.getPackage() != null && i2.getPackage() != null) {
     if (!i1.getPackage().equals(i2.getPackage())) {
       return i1.getPackage().compareTo(i2.getPackage());
     }
   }
   Set<String> categories1 = i1.getCategories();
   Set<String> categories2 = i2.getCategories();
   if (categories1 == null) return categories2 == null ? 0 : -1;
   if (categories2 == null) return 1;
   if (categories1.size() > categories2.size()) return 1;
   if (categories1.size() < categories2.size()) return -1;
   String[] array1 = categories1.toArray(new String[0]);
   String[] array2 = categories2.toArray(new String[0]);
   Arrays.sort(array1);
   Arrays.sort(array2);
   for (int i = 0; i < array1.length; ++i) {
     int val = array1[i].compareTo(array2[i]);
     if (val != 0) return val;
   }
   return 0;
 }
Ejemplo n.º 3
1
  /**
   * Loads the contents of the given locations into memory.
   *
   * @param locations locations to add (of type {@link java.io.File &lt;File&gt;}).
   * @throws IOException if an I/O error occurred.
   */
  public synchronized void loadAll(List locations) throws IOException {
    if (locations == null) {
      return;
    }

    Set data = new HashSet(1000);

    for (Iterator i = locations.iterator(); i.hasNext(); ) {
      File location = (File) i.next();
      ClassRepositoryEntry entry = loadEntry(location);

      if (entry != null) {
        data.addAll(entry.getData());

        if (Loggers.IO.isDebugEnabled()) {
          Loggers.IO.debug("ClassRepository: Loaded " + data.size() + " classes from " + location);
        }
      }
    }

    if (!data.isEmpty()) {
      data.addAll(Arrays.asList(_content));
      _content = (String[]) data.toArray(EMPTY_STRING_ARRAY);
      Arrays.sort(_content);
    }
  }
Ejemplo n.º 4
0
  public static void main(final String[] args) throws IOException {
    DependencyVisitor v = new DependencyVisitor();

    ZipFile f = new ZipFile(args[0]);

    long l1 = System.currentTimeMillis();
    Enumeration<? extends ZipEntry> en = f.entries();
    while (en.hasMoreElements()) {
      ZipEntry e = en.nextElement();
      String name = e.getName();
      if (name.endsWith(".class")) {
        new ClassReader(f.getInputStream(e)).accept(v, 0);
      }
    }
    long l2 = System.currentTimeMillis();

    Map<String, Map<String, Integer>> globals = v.getGlobals();
    Set<String> jarPackages = globals.keySet();
    Set<String> classPackages = v.getPackages();
    int size = classPackages.size();
    System.err.println("time: " + (l2 - l1) / 1000f + "  " + size);

    String[] jarNames = jarPackages.toArray(new String[jarPackages.size()]);
    String[] classNames = classPackages.toArray(new String[classPackages.size()]);
    Arrays.sort(jarNames);
    Arrays.sort(classNames);

    buildDiagram(jarNames, classNames, globals);
  }
Ejemplo n.º 5
0
  public String validateEdges() {
    StringBuilder sb = new StringBuilder();
    Set<String> inIds = getInEdges();
    for (String id : inIds.toArray(new String[0])) {
      Document chk = getParent().getRawDatabase().getDocumentByUNID(id);
      if (chk == null) {
        inIds.remove(id);
        inDirty_ = true;
        sb.append("IN: ");
        sb.append(id);
        sb.append(",");
      }
    }

    Set<String> outIds = getOutEdges();
    for (String id : outIds.toArray(new String[0])) {
      Document chk = getParent().getRawDatabase().getDocumentByUNID(id);
      if (chk == null) {
        outIds.remove(id);
        outDirty_ = true;
        sb.append("OUT: ");
        sb.append(id);
        sb.append(",");
      }
    }
    return sb.toString();
  }
Ejemplo n.º 6
0
 @Override
 protected Object computeValues(EquityIndexOption derivative, EquityOptionDataBundle market) {
   final NodalDoublesSurface vegaSurface =
       CALCULATOR.calcBlackVegaForEntireSurface(derivative, market);
   final Double[] xValues = vegaSurface.getXData();
   final Double[] yValues = vegaSurface.getYData();
   final Set<Double> xSet = new HashSet<Double>(Arrays.asList(xValues));
   final Set<Double> ySet = new HashSet<Double>(Arrays.asList(yValues));
   final Double[] uniqueX = xSet.toArray(new Double[0]);
   final Double[] uniqueY = ySet.toArray(new Double[0]);
   final double[][] values = new double[ySet.size()][xSet.size()];
   int i = 0;
   for (final Double x : xSet) {
     int j = 0;
     for (final Double y : ySet) {
       double vega;
       try {
         vega = vegaSurface.getZValue(x, y);
       } catch (final IllegalArgumentException e) {
         vega = 0;
       }
       values[j++][i] = vega;
     }
     i++;
   }
   final DoubleLabelledMatrix2D matrix = new DoubleLabelledMatrix2D(uniqueX, uniqueY, values);
   return matrix;
 }
Ejemplo n.º 7
0
  /** March through the classloaders to find one that can return urls. */
  @SuppressWarnings("resource")
  private URL[] getUrls() {
    Set<URL> urlSet = new HashSet<URL>();

    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    while (true) {
      if (cl == null) {
        return urlSet.toArray(new URL[urlSet.size()]);
      }

      if (!(cl instanceof URLClassLoader)) {
        cl = cl.getParent();
        continue;
      }

      URLClassLoader ucl = (URLClassLoader) cl;
      URL[] urls = ucl.getURLs();
      urlSet.addAll(Arrays.asList(urls));

      if (cl == ClassLoader.getSystemClassLoader()) {
        return urlSet.toArray(new URL[urlSet.size()]);
      }

      cl = cl.getParent();
    }
  }
  public static void updateModuleList(Node node) {
    List<ModuleNeeded> moduleNeededList = ModulesNeededProvider.getModulesNeeded();
    Set<String> moduleNameList = new TreeSet<String>();
    Set<String> moduleValueList = new TreeSet<String>();
    for (ModuleNeeded module : moduleNeededList) {

      String moduleName = module.getModuleName();
      moduleNameList.add(moduleName);
      moduleValueList.add(TalendTextUtils.addQuotes(moduleName));
    }
    Comparator<String> comprarator = new IgnoreCaseComparator();
    String[] moduleNameArray = moduleNameList.toArray(new String[0]);
    String[] moduleValueArray = moduleValueList.toArray(new String[0]);
    Arrays.sort(moduleNameArray, comprarator);
    Arrays.sort(moduleValueArray, comprarator);

    for (int i = 0; i < node.getElementParameters().size(); i++) {
      IElementParameter param = node.getElementParameters().get(i);
      if (param.getFieldType() == EParameterFieldType.MODULE_LIST) {
        param.setListItemsDisplayName(moduleNameArray);
        param.setListItemsValue(moduleValueArray);
      } else if (param.getFieldType() == EParameterFieldType.TABLE) {
        Object[] listItemsValue = param.getListItemsValue();
        if (listItemsValue != null) {
          for (Object o : listItemsValue) {
            if (o instanceof IElementParameter
                && ((IElementParameter) o).getFieldType() == EParameterFieldType.MODULE_LIST) {
              ((IElementParameter) o).setListItemsDisplayName(moduleNameArray);
              ((IElementParameter) o).setListItemsValue(moduleValueArray);
            }
          }
        }
      }
    }
  }
 private static void setJobName(JobConf jobConf, List<DataSegment> segments) {
   if (segments.size() == 1) {
     final DataSegment segment = segments.get(0);
     jobConf.setJobName(
         String.format(
             "druid-convert-%s-%s-%s",
             segment.getDataSource(), segment.getInterval(), segment.getVersion()));
   } else {
     final Set<String> dataSources =
         Sets.newHashSet(
             Iterables.transform(
                 segments,
                 new Function<DataSegment, String>() {
                   @Override
                   public String apply(DataSegment input) {
                     return input.getDataSource();
                   }
                 }));
     final Set<String> versions =
         Sets.newHashSet(
             Iterables.transform(
                 segments,
                 new Function<DataSegment, String>() {
                   @Override
                   public String apply(DataSegment input) {
                     return input.getVersion();
                   }
                 }));
     jobConf.setJobName(
         String.format(
             "druid-convert-%s-%s",
             Arrays.toString(dataSources.toArray()), Arrays.toString(versions.toArray())));
   }
 }
Ejemplo n.º 10
0
  @Test
  public void toArray() {
    assertTrue(Arrays.equals(toTest.toArray(), new Serializable[] {}));

    toTest.add("Test1");
    toTest.add("Test2");

    assertTrue(Arrays.equals(toTest.toArray(), new String[] {"Test1", "Test2"}));

    String[] sArray = new String[2];
    String[] result = toTest.toArray(sArray);

    assertSame(sArray, result);
    assertTrue(Arrays.equals(sArray, new String[] {"Test1", "Test2"}));

    sArray = new String[3];
    result = toTest.toArray(sArray);

    assertSame(sArray, result);
    assertTrue(Arrays.equals(sArray, new String[] {"Test1", "Test2", null}));

    result = toTest.toArray(new String[] {});

    assertTrue(Arrays.equals(result, new String[] {"Test1", "Test2"}));
  }
  public void elementsChanged(Object[] updatedElements) {
    if (fResult == null) return;
    int addCount = 0;
    int removeCount = 0;
    int addLimit = getAddLimit();

    TableViewer viewer = (TableViewer) getPage().getViewer();
    Set<Object> updated = new HashSet<Object>();
    Set<Object> added = new HashSet<Object>();
    Set<Object> removed = new HashSet<Object>();
    for (int i = 0; i < updatedElements.length; i++) {
      if (getPage().getDisplayedMatchCount(updatedElements[i]) > 0) {
        if (viewer.testFindItem(updatedElements[i]) != null) updated.add(updatedElements[i]);
        else {
          if (addLimit > 0) {
            added.add(updatedElements[i]);
            addLimit--;
            addCount++;
          }
        }
      } else {
        removed.add(updatedElements[i]);
        removeCount++;
      }
    }

    viewer.add(added.toArray());
    viewer.update(updated.toArray(), new String[] {SearchLabelProvider.PROPERTY_MATCH_COUNT});
    viewer.remove(removed.toArray());
  }
Ejemplo n.º 12
0
  @Test
  public void testClassNames() {
    Document doc = Jsoup.parse("<div class=\"c1 c2\">C</div>");
    Element div = doc.select("div").get(0);

    assertEquals("c1 c2", div.className());

    final Set<String> set1 = div.classNames();
    final Object[] arr1 = set1.toArray();
    assertTrue(arr1.length == 2);
    assertEquals("c1", arr1[0]);
    assertEquals("c2", arr1[1]);

    // Changes to the set should not be reflected in the Elements getters
    set1.add("c3");
    assertTrue(2 == div.classNames().size());
    assertEquals("c1 c2", div.className());

    // Update the class names to a fresh set
    final Set<String> newSet = new LinkedHashSet<String>(3);
    newSet.addAll(set1);
    newSet.add("c3");

    div.classNames(newSet);

    assertEquals("c1 c2 c3", div.className());

    final Set<String> set2 = div.classNames();
    final Object[] arr2 = set2.toArray();
    assertTrue(arr2.length == 3);
    assertEquals("c1", arr2[0]);
    assertEquals("c2", arr2[1]);
    assertEquals("c3", arr2[2]);
  }
Ejemplo n.º 13
0
  /**
   * See class description. First {@link AAssignSubstitution} nodes are checked, then the other
   * nodes.
   *
   * <p>An {@link CheckException} is thrown if there are {@link AAssignSubstitution} or {@link
   * AOperationCallSubstitution} nodes with illegal elements in the LHS. Otherwise the other
   * relevant nodes are checked for illegal entries in their identifier lists.
   *
   * <p>In both cases the erroneous nodes are collected, so that only one exception is thrown for
   * the {@link AAssignSubstitution} and {@link AOperationCallSubstitution} nodes respectively one
   * for all other nodes.
   *
   * @param rootNode
   * @throws CheckException : Erroneous {@link AAssignSubstitution} and {@link
   *     AOperationCallSubstitution} nodes are collected in one exception and all other nodes in
   *     another one.
   */
  public void runChecks(final Start rootNode) throws CheckException {
    nonIdentifiers.clear();

    /*
     * First check all assignment nodes if the LHS only contains identifiers
     * or functions.
     */
    final AssignCheck assignCheck = new AssignCheck();
    rootNode.apply(assignCheck);

    final Set<Node> assignErrorNodes = assignCheck.nonIdentifiers;
    if (assignErrorNodes.size() > 0) {
      throw new CheckException(
          "Identifier or function expected",
          assignErrorNodes.toArray(new Node[assignErrorNodes.size()]));
    }

    /*
     * Then check other constructs which can only contain identifiers at
     * special places.
     */
    rootNode.apply(this);

    if (nonIdentifiers.size() > 0) {
      // at least one error was found
      throw new CheckException(
          "Identifier expected", nonIdentifiers.toArray(new Node[nonIdentifiers.size()]));
    }
  }
Ejemplo n.º 14
0
  private void readOldState(DataInputStream dis) throws IOException, TeamException {
    int repoSize = dis.readInt();
    boolean version1 = false;
    if (repoSize == STATE_FILE_VERSION_1) {
      version1 = true;
      repoSize = dis.readInt();
    }
    for (int i = 0; i < repoSize; i++) {
      ICVSRepositoryLocation root = KnownRepositories.getInstance().getRepository(dis.readUTF());
      RepositoryRoot repoRoot = getRepositoryRootFor(root);

      // read branch tags associated with this root
      int tagsSize = dis.readInt();
      CVSTag[] branchTags = new CVSTag[tagsSize];
      for (int j = 0; j < tagsSize; j++) {
        String tagName = dis.readUTF();
        int tagType = dis.readInt();
        branchTags[j] = new CVSTag(tagName, tagType);
      }
      // Ignore the branch tags since they are handled differently now
      // addBranchTags(root, branchTags);

      // read the number of projects for this root that have version tags
      int projSize = dis.readInt();
      if (projSize > 0) {
        for (int j = 0; j < projSize; j++) {
          String name = dis.readUTF();
          Set tagSet = new HashSet();
          int numTags = dis.readInt();
          for (int k = 0; k < numTags; k++) {
            tagSet.add(new CVSTag(dis.readUTF(), CVSTag.VERSION));
          }
          CVSTag[] tags = (CVSTag[]) tagSet.toArray(new CVSTag[tagSet.size()]);
          repoRoot.addTags(name, tags);
        }
      }
      // read the auto refresh filenames for this project
      if (version1) {
        try {
          projSize = dis.readInt();
          if (projSize > 0) {
            for (int j = 0; j < projSize; j++) {
              String name = dis.readUTF();
              Set filenames = new HashSet();
              int numFilenames = dis.readInt();
              for (int k = 0; k < numFilenames; k++) {
                filenames.add(name + "/" + dis.readUTF()); // $NON-NLS-1$
              }
              repoRoot.setAutoRefreshFiles(
                  name, (String[]) filenames.toArray(new String[filenames.size()]));
            }
          }
        } catch (EOFException e) {
          // auto refresh files are not persisted, continue and save them next time.
        }
      }
      broadcastRepositoryChange(repoRoot);
    }
  }
  private Set<Metric> getAllPredictedMetrics() {

    Set<Relationship> relationships =
        inventory.relationships().named(Configuration.PREDICTION_RELATIONSHIP).entities();

    Set<CanonicalPath> metricsCp = new HashSet<>();
    Set<CanonicalPath> metricTypesCp = new HashSet<>();
    Set<CanonicalPath> tenantsCp = new HashSet<>();

    for (Relationship relationship : relationships) {

      predictionRelationships.relationships().put(relationship.getTarget(), relationship);

      if (relationship.getTarget().getSegment().getElementType().equals(Metric.class)) {
        metricsCp.add(relationship.getTarget());
      } else if (relationship.getTarget().getSegment().getElementType().equals(MetricType.class)) {
        metricTypesCp.add(relationship.getTarget());
      } else if (relationship.getTarget().getSegment().getElementType().equals(Tenant.class)) {
        tenantsCp.add(relationship.getTarget());
      }
    }

    Set<Metric> metrics =
        inventory
            .tenants()
            .getAll()
            .feeds()
            .getAll()
            .metrics()
            .getAll(With.paths(metricsCp.toArray(new CanonicalPath[0])))
            .entities();
    Set<Metric> metricsUnderTypes =
        inventory
            .tenants()
            .getAll()
            .feeds()
            .getAll()
            .metricTypes()
            .getAll(With.paths(metricTypesCp.toArray(new CanonicalPath[0])))
            .metrics()
            .getAll()
            .entities();
    Set<Metric> metricsUnderTenant =
        inventory
            .tenants()
            .getAll(With.paths(tenantsCp.toArray(new CanonicalPath[0])))
            .feeds()
            .getAll()
            .metrics()
            .getAll()
            .entities();

    metrics.addAll(metricsUnderTypes);
    metrics.addAll(metricsUnderTenant);

    return metrics;
  }
Ejemplo n.º 16
0
  public Integer[] getIds() {
    if (ids != null && ids.contains("-") && ids.contains(",")) {
      Set<Integer> result = new HashSet<Integer>();
      String[] idInfo = ids.split(",");
      for (String info : idInfo) {
        if (info.contains("-")) {
          String[] inner = info.split("-");
          int start = Integer.parseInt(inner[0]);
          int end = Integer.parseInt(inner[1]);
          if (start > end) {
            int temp = start;
            start = end;
            end = temp;
          }
          for (int i = start; i < end + 1; i++) {
            result.add(i);
          }
        } else {
          result.add(Integer.parseInt(info));
        }
      }
      return result.toArray(new Integer[result.size()]);
    }
    if (ids != null && ids.contains("-")) {
      String[] idInfo = ids.split("-");
      int start = Integer.parseInt(idInfo[0]);
      int end = Integer.parseInt(idInfo[1]);
      if (start > end) {
        int temp = start;
        start = end;
        end = temp;
      }
      Set<Integer> result = new HashSet<Integer>();
      for (int i = start; i < end + 1; i++) {
        result.add(i);
      }
      return result.toArray(new Integer[result.size()]);
    }
    if (ids != null && ids.contains(",")) {
      String[] idInfo = ids.split(",");
      Set<Integer> result = new HashSet<Integer>();
      for (int i = 0; i < idInfo.length; i++) {
        result.add(Integer.parseInt(idInfo[i]));
      }
      return result.toArray(new Integer[result.size()]);
    }
    if (ids != null) {
      Integer[] result = new Integer[1];

      result[0] = Integer.parseInt(ids);

      return result;
    }

    return id;
  }
 @Test
 public void keySetToArray() {
   MutableMapIterable<String, Integer> map =
       this.newMapWithKeysValues("One", 1, "Two", 2, "Three", 3);
   MutableList<String> expected = FastList.newListWith("One", "Two", "Three").toSortedList();
   Set<String> keySet = map.keySet();
   Assert.assertEquals(expected, FastList.newListWith(keySet.toArray()).toSortedList());
   Assert.assertEquals(
       expected, FastList.newListWith(keySet.toArray(new String[keySet.size()])).toSortedList());
 }
Ejemplo n.º 18
0
  /**
   * Innermost method for a reduction rule. Implementation of the abstract method from superclass.
   *
   * @net YNet to perform reduction
   * @element an for consideration. returns a reduced YNet or null if a given net cannot be reduced.
   */
  public YNet reduceElement(YNet net, YExternalNetElement nextElement) {
    YNet reducedNet = net;
    if (nextElement instanceof YCondition) {
      YCondition condition = (YCondition) nextElement;
      Set postSet = condition.getPostsetElements();
      Set preSet = condition.getPresetElements();

      // \pre{p} = 1, \post{p} = 1
      if (preSet.size() == 1 && postSet.size() == 1) {
        YTask t = (YTask) preSet.toArray()[0];
        YTask u = (YTask) postSet.toArray()[0];
        Set preSetOfu = u.getPresetElements();
        Set postSetOfu = u.getPostsetElements();
        // t,u and p are not reset
        // u does not have reset arcs

        Set postSetOft = new HashSet(t.getPostsetElements());
        postSetOft.retainAll(postSetOfu);

        if (t.getSplitType() == YTask._AND
            && u.getSplitType() == YTask._AND
            && preSetOfu.size() == 1
            && u.getRemoveSet().isEmpty()
            && t.getCancelledBySet().isEmpty()
            && u.getCancelledBySet().isEmpty()
            && condition.getCancelledBySet().isEmpty()
            && (!checkReset(postSetOfu))
            && postSetOft.isEmpty()) {

          // set postflows from u to t

          Iterator postFlowIter = postSetOfu.iterator();
          while (postFlowIter.hasNext()) {
            YExternalNetElement next = (YExternalNetElement) postFlowIter.next();
            t.addPostset(new YFlow(t, next));
          }

          // remove condition from postset of t
          t.removePostsetFlow(new YFlow(condition, t));

          reducedNet.removeNetElement(condition);
          reducedNet.removeNetElement(u);

          t.addToYawlMappings(condition);
          t.addToYawlMappings(condition.getYawlMappings());
          t.addToYawlMappings(u);
          t.addToYawlMappings(u.getYawlMappings());

          return reducedNet;
        } // if nested
      } // if - size 1
    } // endif - condition

    return null;
  }
Ejemplo n.º 19
0
  public void synchronize(boolean manualSync, SyncResult syncResult)
      throws URISyntaxException, LocalStorageException, IOException, HttpException, DavException {
    // PHASE 1: push local changes to server
    int deletedRemotely = pushDeleted(), addedRemotely = pushNew(), updatedRemotely = pushDirty();

    syncResult.stats.numEntries = deletedRemotely + addedRemotely + updatedRemotely;

    // PHASE 2A: check if there's a reason to do a sync with remote (= forced sync or remote CTag
    // changed)
    boolean fetchCollection = syncResult.stats.numEntries > 0;
    if (manualSync) {
      Log.i(TAG, "Synchronization forced");
      fetchCollection = true;
    }
    if (!fetchCollection) {
      String currentCTag = remote.getCTag(), lastCTag = local.getCTag();
      Log.d(TAG, "Last local CTag = " + lastCTag + "; current remote CTag = " + currentCTag);
      if (currentCTag == null || !currentCTag.equals(lastCTag)) fetchCollection = true;
    }

    if (!fetchCollection) {
      Log.i(TAG, "No local changes and CTags match, no need to sync");
      return;
    }

    // PHASE 2B: detect details of remote changes
    Log.i(TAG, "Fetching remote resource list");
    Set<Resource> remotelyAdded = new HashSet<Resource>(),
        remotelyUpdated = new HashSet<Resource>();

    Resource[] remoteResources = remote.getMemberETags();
    for (Resource remoteResource : remoteResources) {
      try {
        Resource localResource = local.findByRemoteName(remoteResource.getName(), false);
        if (localResource.getETag() == null
            || !localResource.getETag().equals(remoteResource.getETag()))
          remotelyUpdated.add(remoteResource);
      } catch (RecordNotFoundException e) {
        remotelyAdded.add(remoteResource);
      }
    }

    // PHASE 3: pull remote changes from server
    syncResult.stats.numInserts = pullNew(remotelyAdded.toArray(new Resource[0]));
    syncResult.stats.numUpdates = pullChanged(remotelyUpdated.toArray(new Resource[0]));
    syncResult.stats.numEntries += syncResult.stats.numInserts + syncResult.stats.numUpdates;

    Log.i(TAG, "Removing non-dirty resources that are not present remotely anymore");
    local.deleteAllExceptRemoteNames(remoteResources);
    local.commit();

    // update collection CTag
    Log.i(TAG, "Sync complete, fetching new CTag");
    local.setCTag(remote.getCTag());
  }
Ejemplo n.º 20
0
  /** A deserialized serialized set is equal */
  public void testSerialization() throws Exception {
    Set x = populatedSet(SIZE);
    Set y = serialClone(x);

    assertNotSame(y, x);
    assertEquals(x.size(), y.size());
    assertEquals(x.toString(), y.toString());
    assertTrue(Arrays.equals(x.toArray(), y.toArray()));
    assertEquals(x, y);
    assertEquals(y, x);
  }
Ejemplo n.º 21
0
  @Before
  public void setUp() {
    /*
     * Meal(
     *   Fish(
     *     Meat(),
     *     Oven(
     *       Wood(),
     *       Fire()
     *     )
     *   ),
     *   Cake(
     *     Eggs(),
     *     Oven(...)
     *   ),
     *   Beer(
     *     Hops(),
     *   ),
     *   Fork()
     * )
     */

    // Leaves
    deps(meat);
    deps(wood);
    deps(fire);
    deps(eggs);
    deps(hops);
    deps(fork);

    // Foods
    deps(oven, wood, fire);
    deps(fish, meat, oven);
    deps(cake, eggs, oven);
    deps(beer, hops);
    deps(meal, fish, cake, beer);

    replay(allLibraries.toArray());

    sourceUnderTest(mealTest, meal);
    sourceUnderTest(fishTest, fish);
    sourceUnderTest(meatTest, meat);
    sourceUnderTest(ovenTest, oven);
    sourceUnderTest(woodTest, wood);
    sourceUnderTest(fireTest, fire);
    sourceUnderTest(cakeTest, cake);
    sourceUnderTest(eggsTest, eggs);
    sourceUnderTest(beerTest, beer);
    sourceUnderTest(hopsTest, hops);

    replay(allTests.toArray());
  }
Ejemplo n.º 22
0
  public List<Integer> getSpriteIDs() {
    Map<Integer, Object> dataImages = getImages();
    Set<Integer> spriteSet = dataImages.keySet();
    List<Integer> spriteIDs = new LinkedList<Integer>();

    Object[] spriteSetArr = spriteSet.toArray();

    for (int i = 0; i < spriteSet.size(); i++) {
      spriteIDs.add(new Integer((Integer) spriteSet.toArray()[i]));
    }

    return spriteIDs;
  }
Ejemplo n.º 23
0
    public boolean isValidTaintedHashtable(Hashtable h, Hashtable taintH)
    {
        Set entries = h.entrySet();
        Set taintEntries = taintH.entrySet();

        Map.Entry[] e;
        Map.Entry[] taintE;
        e = (Map.Entry[]) entries.toArray(new Map.Entry[entries.size()]);
        taintE = (Map.Entry[]) 
            taintEntries.toArray(new Map.Entry[taintEntries.size()]);

        if (e.length != taintE.length)
            return false;

        for (int i = 0; i < e.length; i++) {
            String s = (String) e[i].getKey();
            String[] sa = (String []) e[i].getValue();
            boolean found = false;

            for (int j = 0; j < taintE.length; j++) {
                String taintS = (String) taintE[j].getKey();

                if (taintS.equals(s)) {
                    if (!isValidTaintedString(s, taintS))
                        return false;
                    found = true;
                    break;
                }
            }

            if (!found)
                return false;
            found = false;

            for (int j = 0; j < taintE.length; j++) {
                String[] taintSa = (String[]) taintE[j].getValue();

                if (Arrays.equals(sa, taintSa)) {
                    if (!isValidTaintedStringArray(sa, taintSa))
                        return false;
                    found = true;
                    break;
                }
            }

            if (!found)
                return false;
        }

        return true;
    }
 private static PsiAnnotation[] getHierarchyAnnotations(
     PsiModifierListOwner listOwner, PsiModifierList modifierList) {
   final Set<PsiAnnotation> all =
       new HashSet<PsiAnnotation>() {
         public boolean add(PsiAnnotation o) {
           // don't overwrite "higher level" annotations
           return !contains(o) && super.add(o);
         }
       };
   if (listOwner instanceof PsiMethod) {
     ContainerUtil.addAll(all, modifierList.getAnnotations());
     SuperMethodsSearch.search((PsiMethod) listOwner, null, true, true)
         .forEach(
             new Processor<MethodSignatureBackedByPsiMethod>() {
               public boolean process(final MethodSignatureBackedByPsiMethod superMethod) {
                 ContainerUtil.addAll(
                     all, superMethod.getMethod().getModifierList().getAnnotations());
                 return true;
               }
             });
     return all.toArray(new PsiAnnotation[all.size()]);
   }
   if (listOwner instanceof PsiParameter) {
     PsiParameter parameter = (PsiParameter) listOwner;
     PsiElement declarationScope = parameter.getDeclarationScope();
     PsiParameterList parameterList;
     if (declarationScope instanceof PsiMethod
         && parameter.getParent()
             == (parameterList = ((PsiMethod) declarationScope).getParameterList())) {
       PsiMethod method = (PsiMethod) declarationScope;
       final int parameterIndex = parameterList.getParameterIndex(parameter);
       ContainerUtil.addAll(all, modifierList.getAnnotations());
       SuperMethodsSearch.search(method, null, true, true)
           .forEach(
               new Processor<MethodSignatureBackedByPsiMethod>() {
                 public boolean process(final MethodSignatureBackedByPsiMethod superMethod) {
                   PsiParameter superParameter =
                       superMethod.getMethod().getParameterList().getParameters()[parameterIndex];
                   PsiModifierList modifierList = superParameter.getModifierList();
                   if (modifierList != null) {
                     ContainerUtil.addAll(all, modifierList.getAnnotations());
                   }
                   return true;
                 }
               });
       return all.toArray(new PsiAnnotation[all.size()]);
     }
   }
   return modifierList.getAnnotations();
 }
Ejemplo n.º 25
0
  public void testVariantTwoWildcard() throws InterruptedException {
    String stmtText =
        "insert into event1 select * from " + SupportBean.class.getName() + ".win:length(100)";
    String otherText = "select * from default.event1.win:length(10)";

    // Attach listener to feed
    EPStatement stmtOne = epService.getEPAdministrator().createEPL(stmtText, "stmt1");
    assertEquals(
        StatementType.INSERT_INTO,
        ((EPStatementSPI) stmtOne).getStatementMetadata().getStatementType());
    SupportUpdateListener listenerOne = new SupportUpdateListener();
    stmtOne.addListener(listenerOne);
    EPStatement stmtTwo = epService.getEPAdministrator().createEPL(otherText, "stmt2");
    SupportUpdateListener listenerTwo = new SupportUpdateListener();
    stmtTwo.addListener(listenerTwo);

    SupportBean theEvent = sendEvent(10, 11);
    assertTrue(listenerOne.getAndClearIsInvoked());
    assertEquals(1, listenerOne.getLastNewData().length);
    assertEquals(10, listenerOne.getLastNewData()[0].get("intPrimitive"));
    assertEquals(11, listenerOne.getLastNewData()[0].get("intBoxed"));
    assertEquals(20, listenerOne.getLastNewData()[0].getEventType().getPropertyNames().length);
    assertSame(theEvent, listenerOne.getLastNewData()[0].getUnderlying());

    assertTrue(listenerTwo.getAndClearIsInvoked());
    assertEquals(1, listenerTwo.getLastNewData().length);
    assertEquals(10, listenerTwo.getLastNewData()[0].get("intPrimitive"));
    assertEquals(11, listenerTwo.getLastNewData()[0].get("intBoxed"));
    assertEquals(20, listenerTwo.getLastNewData()[0].getEventType().getPropertyNames().length);
    assertSame(theEvent, listenerTwo.getLastNewData()[0].getUnderlying());

    // assert statement-type reference
    EPServiceProviderSPI spi = (EPServiceProviderSPI) epService;
    assertTrue(spi.getStatementEventTypeRef().isInUse("event1"));
    Set<String> stmtNames = spi.getStatementEventTypeRef().getStatementNamesForType("event1");
    EPAssertionUtil.assertEqualsAnyOrder(stmtNames.toArray(), new String[] {"stmt1", "stmt2"});
    assertTrue(spi.getStatementEventTypeRef().isInUse(SupportBean.class.getName()));
    stmtNames =
        spi.getStatementEventTypeRef().getStatementNamesForType(SupportBean.class.getName());
    EPAssertionUtil.assertEqualsAnyOrder(stmtNames.toArray(), new String[] {"stmt1"});

    stmtOne.destroy();
    assertTrue(spi.getStatementEventTypeRef().isInUse("event1"));
    stmtNames = spi.getStatementEventTypeRef().getStatementNamesForType("event1");
    EPAssertionUtil.assertEqualsAnyOrder(new String[] {"stmt2"}, stmtNames.toArray());
    assertFalse(spi.getStatementEventTypeRef().isInUse(SupportBean.class.getName()));

    stmtTwo.destroy();
    assertFalse(spi.getStatementEventTypeRef().isInUse("event1"));
  }
Ejemplo n.º 26
0
 @Override
 public void writeToParcel(final Parcel out, final int flags) {
   out.writeStringArray(geocodes.toArray(new String[geocodes.size()]));
   out.writeStringArray(filteredGeocodes.toArray(new String[filteredGeocodes.size()]));
   out.writeSerializable(error);
   out.writeString(url);
   if (viewstates == null) {
     out.writeInt(-1);
   } else {
     out.writeInt(viewstates.length);
     out.writeStringArray(viewstates);
   }
   out.writeInt(getTotalCountGC());
 }
Ejemplo n.º 27
0
  private SSLEngineConfigurator createSSLEngineConfigurator(HTTPConnectionHandlerCfg config)
      throws DirectoryException {
    if (!config.isUseSSL()) {
      return null;
    }

    try {
      SSLContext sslContext = createSSLContext(config);
      SSLEngineConfigurator configurator = new SSLEngineConfigurator(sslContext);
      configurator.setClientMode(false);

      // configure with defaults from the JVM
      final SSLEngine defaults = sslContext.createSSLEngine();
      configurator.setEnabledProtocols(defaults.getEnabledProtocols());
      configurator.setEnabledCipherSuites(defaults.getEnabledCipherSuites());

      final Set<String> protocols = config.getSSLProtocol();
      if (!protocols.isEmpty()) {
        configurator.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
      }

      final Set<String> ciphers = config.getSSLCipherSuite();
      if (!ciphers.isEmpty()) {
        configurator.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()]));
      }

      switch (config.getSSLClientAuthPolicy()) {
        case DISABLED:
          configurator.setNeedClientAuth(false);
          configurator.setWantClientAuth(false);
          break;
        case REQUIRED:
          configurator.setNeedClientAuth(true);
          configurator.setWantClientAuth(true);
          break;
        case OPTIONAL:
        default:
          configurator.setNeedClientAuth(false);
          configurator.setWantClientAuth(true);
          break;
      }

      return configurator;
    } catch (Exception e) {
      logger.traceException(e);
      ResultCode resCode = DirectoryServer.getServerErrorResultCode();
      throw new DirectoryException(
          resCode, ERR_CONNHANDLER_SSL_CANNOT_INITIALIZE.get(getExceptionMessage(e)), e);
    }
  }
  /* (non-Javadoc)
   * @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent)
   */
  public void resourceChanged(final IResourceChangeEvent event) {
    String[] markerTypes = getMarkerTypes();
    Set handledResources = new HashSet();
    Set changes = new HashSet();

    // Accumulate all distinct resources that have had problem marker
    // changes
    for (int idx = 0; idx < markerTypes.length; idx++) {
      IMarkerDelta[] markerDeltas = event.findMarkerDeltas(markerTypes[idx], true);
      for (int i = 0; i < markerDeltas.length; i++) {
        IMarkerDelta delta = markerDeltas[i];
        IResource resource = delta.getResource();
        if (!handledResources.contains(resource)) {
          handledResources.add(resource);
          ISynchronizeModelElement[] elements =
              provider.getClosestExistingParents(delta.getResource());
          if (elements != null && elements.length > 0) {
            for (int j = 0; j < elements.length; j++) {
              ISynchronizeModelElement element = elements[j];
              changes.add(element);
            }
          }
        }
      }
    }

    if (!changes.isEmpty()) {
      updateMarkersFor(
          (ISynchronizeModelElement[])
              changes.toArray(new ISynchronizeModelElement[changes.size()]));
    }
  }
 private void performImport() {
   FileDialog dialog = new FileDialog(this.fDialog.getShell(), SWT.OPEN);
   dialog.setText("Export environment variables to file");
   String file = dialog.open();
   if (file != null) {
     File handle = new File(file);
     if (!handle.exists()) {
       String text = "Selected file not exists.";
       showErrorMessage("Environment import", text);
       return;
     }
     EnvironmentVariable[] vars = null;
     try {
       vars = EnvironmentVariablesFileUtils.load(file);
     } catch (Exception e) {
       showErrorMessage("Environment import", e.getMessage());
     }
     if (vars != null) {
       EnvironmentVariable[] variables = this.fEnvironmentVariablesContentProvider.getVariables();
       Set nvars = new HashSet();
       nvars.addAll(Arrays.asList(vars));
       nvars.addAll(Arrays.asList(variables));
       this.fEnvironmentVariablesContentProvider.setVariables(
           (EnvironmentVariable[]) nvars.toArray(new EnvironmentVariable[nvars.size()]));
     }
   }
 }
  private void checkExisting(
      File targetFile, ClassLoader classLoader, Document doc, Set<String> entityClasses) {
    if (targetFile.exists()) {
      final Set<String> alreadyDefined = PersistenceXmlHelper.getClassesAlreadyDefined(doc);
      for (String className : alreadyDefined) {
        if (!ReflectionHelper.classExists(className, classLoader)) {
          getLog().warn("Class " + className + " defined in " + targetFile + " does not exist");
        }
      }

      if (!alreadyDefined.containsAll(entityClasses)) {
        final Set<String> undefined = new TreeSet<>();
        for (String className : entityClasses) {
          if (!alreadyDefined.contains(className)) {
            undefined.add(className);
          }
        }

        getLog()
            .warn(
                "The following classes was not defined in "
                    + targetFile
                    + " even "
                    + "though they are available on the class path: "
                    + Arrays.toString(undefined.toArray()));
      }

      // Don't add so we end up with duplicates
      entityClasses.removeAll(alreadyDefined);
    }
  }