Example #1
7
  public SelectMany05Bean() {

    HobbitBean[] hobbits = {
      new HobbitBean("Bilbo", "Ring Finder"),
      new HobbitBean("Frodo", "Ring Bearer"),
      new HobbitBean("Merry", "Trouble Maker"),
      new HobbitBean("Pippin", "Trouble Maker")
    };

    Set<SelectItem> items = new LinkedHashSet<SelectItem>();
    for (HobbitBean hobbit : hobbits) {
      items.add(new SelectItem(hobbit.getName()));
    }
    hobbitCollection = new TreeSet<HobbitBean>();
    hobbitCollection.addAll(Arrays.asList(hobbits));
    possibleValues = Collections.unmodifiableSet(items);
    initialSortedSetValues = new TreeSet<String>(Collections.reverseOrder());
    initialSortedSetValues.add("Pippin");
    initialSortedSetValues.add("Frodo");
    initialCollectionValues = new LinkedHashSet<String>(2);
    initialCollectionValues.add("Bilbo");
    initialCollectionValues.add("Merry");
    initialSetValues = new CopyOnWriteArraySet<String>(); // not Cloneable
    initialSetValues.add("Frodo");
    initialListValues = new Vector<String>();
    initialListValues.add("Bilbo");
    initialListValues.add("Pippin");
    initialListValues.add("Merry");
    hobbitDataModel =
        new ListDataModel<HobbitBean>(new ArrayList<HobbitBean>(Arrays.asList(hobbits)));
  }
Example #2
1
 static {
   Set<String> set = new HashSet<String>();
   set.add("add");
   set.add("sub");
   set.add("and");
   set.add("or");
   twoArgArithmeticCommandSet = Collections.unmodifiableSet(set);
   set = new HashSet<String>();
   set.add("neg");
   set.add("not");
   singleArgArithmeticCommandSet = Collections.unmodifiableSet(set);
   set = new HashSet<String>();
   set.add("gt");
   set.add("lt");
   set.add("eq");
   twoArgArithmeticComparisonCommandSet = Collections.unmodifiableSet(set);
   Map<String, String> map = new HashMap<String, String>();
   map.put("add", "+");
   map.put("sub", "-");
   map.put("and", "&");
   map.put("or", "|");
   map.put("neg", "-");
   map.put("not", "!");
   map.put("gt", "JGT");
   map.put("lt", "JLT");
   map.put("eq", "JEQ");
   arithmeticOperatorMap = Collections.unmodifiableMap(map);
 }
Example #3
0
  /**
   * Prints the genetics of this Brain to a String.
   *
   * @return a String representation of the underlying neural network
   */
  public String toString() {
    // TODO: Make this and DNA use Braincraft.listToString()
    // First line
    String output = "genomestart " + ID + "\n";

    // Node list
    ArrayList<NNode> nodes = new ArrayList<NNode>();
    nodes.addAll(nodemap.values());
    Collections.sort(nodes);
    output += Braincraft.listToString(nodes);

    // Gene list
    Set<Gene> genes = new HashSet<Gene>();
    for (ArrayList<Gene> arl : connections.values()) {
      for (Gene g : arl) {
        genes.add(g);
      }
    }
    ArrayList<Gene> allgenes = new ArrayList<Gene>();
    allgenes.addAll(genes);
    Collections.sort(allgenes);
    output += Braincraft.listToString(allgenes);

    // Last line
    output += "genomeend" + "\n";

    return output;
  }
Example #4
0
  @Test
  public void testClientWildcard() throws Exception {
    BaseClientDetails theclient =
        new BaseClientDetails(
            "client",
            "zones",
            "zones.*.admin",
            "authorization_code, password",
            "scim.read, scim.write",
            "http://*****:*****@vmware.com"));

    accessToken = tokenServices.createAccessToken(authentication);

    endpoint.checkToken(accessToken.getValue());
  }
  @Override
  public List<String> getSuggestions(String query) {
    try {
      if (artistName == null) {
        return NamedData.namedDataListToNameList(
            internetSearchEngine.searchAudios(query, maxCount, 1).elements);
      } else {
        List<String> result = new ArrayList<>();
        List<Audio> audios = internetSearchEngine.searchAudios(query, maxCount * 2, 1).elements;
        audios = NamedData.uniqueNames(audios);

        int removedCount = 0;
        for (int i = audios.size() - 1; i >= 0; i--) {
          Audio audio = audios.get(i);
          if (result.size() - removedCount > minCount
              && !Strings.equalsIgnoreCase(audio.getArtistName(), artistName)) {
            removedCount++;
          } else {
            result.add(audio.getName());
          }
        }

        Collections.reverse(result);
        return result;
      }
    } catch (IOException e) {
      return Collections.emptyList();
    }
  }
  /** {@link IDataDeleter} implementations to delegate delete operations to. */
  @SuppressWarnings("unchecked")
  @Autowired(required = false)
  public void setDataDeleters(Collection<IDataDeleter<? extends Object>> dataDeleters) {
    final Map<String, IDataDeleter<Object>> dataDeletersMap =
        new LinkedHashMap<String, IDataDeleter<Object>>();

    final Set<IPortalDataType> portalDataTypes = new LinkedHashSet<IPortalDataType>();

    for (final IDataDeleter<?> dataImporter : dataDeleters) {
      final IPortalDataType portalDataType = dataImporter.getPortalDataType();
      final String typeId = portalDataType.getTypeId();

      this.logger.debug(
          "Registering IDataDeleter for '{}' - {}", new Object[] {typeId, dataImporter});
      final IDataDeleter<Object> existing =
          dataDeletersMap.put(typeId, (IDataDeleter<Object>) dataImporter);
      if (existing != null) {
        this.logger.warn(
            "Duplicate IDataDeleter typeId for {} Replacing {} with {}",
            new Object[] {typeId, existing, dataImporter});
      }

      portalDataTypes.add(portalDataType);
    }

    this.portalDataDeleters = Collections.unmodifiableMap(dataDeletersMap);
    this.deletePortalDataTypes = Collections.unmodifiableSet(portalDataTypes);
  }
  public void testRegisteredQueries() throws IOException {
    SearchModule module = new SearchModule(Settings.EMPTY, false, emptyList());
    List<String> allSupportedQueries = new ArrayList<>();
    Collections.addAll(allSupportedQueries, NON_DEPRECATED_QUERIES);
    Collections.addAll(allSupportedQueries, DEPRECATED_QUERIES);
    String[] supportedQueries = allSupportedQueries.toArray(new String[allSupportedQueries.size()]);
    assertThat(module.getQueryParserRegistry().getNames(), containsInAnyOrder(supportedQueries));

    IndicesQueriesRegistry indicesQueriesRegistry = module.getQueryParserRegistry();
    XContentParser dummyParser = XContentHelper.createParser(new BytesArray("{}"));
    for (String queryName : supportedQueries) {
      indicesQueriesRegistry.lookup(
          queryName, ParseFieldMatcher.EMPTY, dummyParser.getTokenLocation());
    }

    for (String queryName : NON_DEPRECATED_QUERIES) {
      QueryParser<?> queryParser =
          indicesQueriesRegistry.lookup(
              queryName, ParseFieldMatcher.STRICT, dummyParser.getTokenLocation());
      assertThat(queryParser, notNullValue());
    }
    for (String queryName : DEPRECATED_QUERIES) {
      try {
        indicesQueriesRegistry.lookup(
            queryName, ParseFieldMatcher.STRICT, dummyParser.getTokenLocation());
        fail("query is deprecated, getQueryParser should have failed in strict mode");
      } catch (IllegalArgumentException e) {
        assertThat(e.getMessage(), containsString("Deprecated field [" + queryName + "] used"));
      }
    }
  }
Example #8
0
 /**
  * Get IP address from first non-localhost interface
  *
  * @param ipv4 true=return ipv4, false=return ipv6
  * @return address or empty string
  */
 public static String getIPAddress(boolean useIPv4) {
   try {
     List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
     for (NetworkInterface intf : interfaces) {
       List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
       for (InetAddress addr : addrs) {
         if (!addr.isLoopbackAddress()) {
           String sAddr = addr.getHostAddress().toUpperCase();
           boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
           if (useIPv4) {
             if (isIPv4) return sAddr;
           } else {
             if (!isIPv4) {
               int delim = sAddr.indexOf('%'); // drop ip6 port
               // suffix
               return delim < 0 ? sAddr : sAddr.substring(0, delim);
             }
           }
         }
       }
     }
   } catch (Exception ex) {
   } // for now eat exceptions
   return "";
 }
 private List<SchemaTransaction> generateColumnTransactions(Table sourceTable, Table shadowTable) {
   List<SchemaTransaction> shemaTransactionList = new ArrayList<SchemaTransaction>();
   if (shadowTable == null) {
     for (Column column : sourceTable.getColumnList()) {
       shemaTransactionList.add(new SchemaTransaction(column, TransactionType.INSERT));
     }
   } else {
     Collections.sort(sourceTable.getColumnList());
     Collections.sort(shadowTable.getColumnList());
     for (Column column : sourceTable.getColumnList()) {
       if (!shadowTable.getColumnList().contains(column)) {
         column.setTable(shadowTable);
         shemaTransactionList.add(new SchemaTransaction(column, TransactionType.INSERT));
       } else {
         Column shadowColumn =
             shadowTable.getColumnList().get(shadowTable.getColumnList().indexOf(column));
         if (column.getOrdinalPosition() != (shadowColumn.getOrdinalPosition())
             || !column.getDataType().equals(shadowColumn.getDataType())
             || column.getSize() != shadowColumn.getSize()) {
           column.setId(shadowColumn.getId());
           shemaTransactionList.add(new SchemaTransaction(column, TransactionType.UPDATE));
         }
       }
     }
     for (Column column : shadowTable.getColumnList()) {
       if (!sourceTable.getColumnList().contains(column)) {
         shemaTransactionList.add(new SchemaTransaction(column, TransactionType.DELETE));
       }
     }
   }
   return shemaTransactionList;
 }
Example #10
0
  public static String getIPAddress(boolean useIPv4) throws SocketException {
    List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    for (NetworkInterface intf : interfaces) {
      List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
      for (InetAddress addr : addrs) {
        if (!addr.isLoopbackAddress()) {
          String sAddr = addr.getHostAddress().toUpperCase();
          boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);

          if (useIPv4) {
            if (isIPv4) return sAddr;
          } else {
            if (!isIPv4) {
              if (sAddr.startsWith("fe80")
                  || sAddr.startsWith("FE80")) // skipping link-local addresses
              continue;
              int delim = sAddr.indexOf('%'); // drop ip6 port suffix
              return delim < 0 ? sAddr : sAddr.substring(0, delim);
            }
          }
        }
      }
    }

    return "";
  }
  @Test
  public void extractFieldNames() {
    assertEquals(Collections.emptySet(), plugin.extractFieldNames(""));
    assertEquals(Collections.emptySet(), plugin.extractFieldNames("text"));
    assertEquals(Collections.emptySet(), plugin.extractFieldNames("+(^:text"));
    assertEquals(Collections.emptySet(), plugin.extractFieldNames("foo :bar"));

    assertEquals(Collections.singleton("foo"), plugin.extractFieldNames("foo:bar"));
    assertEquals(Collections.singleton("both"), plugin.extractFieldNames("both:(one two)"));
    assertEquals(Collections.singleton("title__"), plugin.extractFieldNames("title__:text"));
    assertEquals(
        Collections.singleton("title_zh_TW"), plugin.extractFieldNames("title_zh_TW:text"));
    assertEquals(
        Collections.singleton("property.Blog.BlogPostClass.title"),
        plugin.extractFieldNames("property.Blog.BlogPostClass.title:value"));
    assertEquals(
        Collections.singleton("property.Blog.Blog..Post$5EClass.title"),
        plugin.extractFieldNames("property.Blog.Blog..Post$5EClass.title:value"));

    assertEquals(
        new HashSet<String>(
            Arrays.asList(
                "abc",
                "g_h.i",
                "m$n-o",
                "_\u0103\u00EE\u00E2\u0219\u021B\u00E8\u00E9\u00EA\u00EB")),
        plugin.extractFieldNames(
            "+abc:def AND -g_h.i:jkl AND (m$n-o:pqr OR "
                + "_\u0103\u00EE\u00E2\u0219\u021B\u00E8\u00E9\u00EA\u00EB:stu^3)"));
  }
  private MethodDeclaration createOptionSetter(PropertyDeclaration property) {
    assert property != null;
    SimpleName paramName = context.createVariableName("option"); // $NON-NLS-1$

    Type optionType = context.getFieldType(property);
    return f.newMethodDeclaration(
        new JavadocBuilder(f)
            .text(
                Messages.getString("ProjectiveModelEmitter.javadocOptionSetter"), // $NON-NLS-1$
                context.getDescription(property))
            .param(paramName)
            .text(
                Messages.getString(
                    "ProjectiveModelEmitter.javadocOptionSetterParameter"), //$NON-NLS-1$
                context.getDescription(property))
            .toJavadoc(),
        new AttributeBuilder(f).toAttributes(),
        Collections.emptyList(),
        context.resolve(void.class),
        context.getOptionSetterName(property),
        Arrays.asList(
            new FormalParameterDeclaration[] {
              f.newFormalParameterDeclaration(optionType, paramName)
            }),
        0,
        Collections.emptyList(),
        null);
  }
Example #13
0
 protected <S, P> void filterUnambiguousPaths(
     final Pda<S, P> pda, S state, Map<S, Integer> dist, Map<S, List<S>> followers) {
   if (followers.containsKey(state)) return;
   List<S> f = Lists.newArrayList(pda.getFollowers(state));
   if (f.size() <= 1) {
     followers.put(state, f);
     if (f.size() == 1) filterUnambiguousPaths(pda, f.get(0), dist, followers);
     return;
   }
   int closestDist = dist.get(f.get(0));
   S closest = f.get(0);
   for (int i = 1; i < f.size(); i++) {
     int d = dist.get(f.get(i));
     if (d < closestDist) {
       closestDist = d;
       closest = f.get(i);
     }
   }
   IsPop<S, P> isPop = new IsPop<S, P>(pda);
   Set<S> closestPops = nfaUtil.findFirst(pda, Collections.singleton(closest), isPop);
   Iterator<S> it = f.iterator();
   while (it.hasNext()) {
     S next = it.next();
     if (next != closest) {
       Set<S> nextPops = nfaUtil.findFirst(pda, Collections.singleton(next), isPop);
       if (!closestPops.equals(nextPops)) it.remove();
     }
   }
   followers.put(state, f);
   for (S follower : f) filterUnambiguousPaths(pda, follower, dist, followers);
 }
  @Override
  public Object provide(Object source, Object currentValue) {

    final ExecutionYear currentYear = ExecutionYear.readCurrentExecutionYear();
    final ExecutionYear previousYear = currentYear.getPreviousExecutionYear();
    final List<ExecutionSemester> executionSemesters = new ArrayList<ExecutionSemester>();

    SpecialSeasonStudentEnrollmentBean bean = (SpecialSeasonStudentEnrollmentBean) source;
    if (bean.getScp()
        .getDegreeCurricularPlan()
        .hasOpenSpecialSeasonEnrolmentPeriod(currentYear.getLastExecutionPeriod())) {
      executionSemesters.add(currentYear.getLastExecutionPeriod());
    }
    if (bean.getScp()
        .getDegreeCurricularPlan()
        .hasOpenSpecialSeasonEnrolmentPeriod(currentYear.getFirstExecutionPeriod())) {
      executionSemesters.add(currentYear.getFirstExecutionPeriod());
    }
    if (bean.getScp()
        .getDegreeCurricularPlan()
        .hasOpenSpecialSeasonEnrolmentPeriod(previousYear.getLastExecutionPeriod())) {
      executionSemesters.add(previousYear.getLastExecutionPeriod());
    }
    if (bean.getScp()
        .getDegreeCurricularPlan()
        .hasOpenSpecialSeasonEnrolmentPeriod(previousYear.getFirstExecutionPeriod())) {
      executionSemesters.add(previousYear.getFirstExecutionPeriod());
    }

    Collections.sort(executionSemesters, ExecutionSemester.COMPARATOR_BY_SEMESTER_AND_YEAR);
    Collections.reverse(executionSemesters);
    return executionSemesters;
  }
Example #15
0
    public Connecting next(RoadGui.ViaConnector via) {
      if (vias.isEmpty()) {
        return new Connecting(lane, Collections.unmodifiableList(Arrays.asList(via)));
      }

      final List<RoadGui.ViaConnector> tmp = new ArrayList<>(vias.size() + 1);
      final boolean even = (vias.size() & 1) == 0;
      final RoadGui.ViaConnector last = vias.get(vias.size() - 1);

      if (last.equals(via)
          || !even && last.getRoadEnd().getJunction().equals(via.getRoadEnd().getJunction())) {
        return pop().next(via);
      }

      if (vias.size() >= 2) {
        if (lane.getOutgoingJunction().equals(via.getRoadEnd().getJunction())) {
          return new Connecting(lane);
        } else if (via.equals(getBacktrackViaConnector())) {
          return new Connecting(lane, vias.subList(0, vias.size() - 1));
        }
      }

      for (RoadGui.ViaConnector v : vias) {
        tmp.add(v);

        if (!(even && v.equals(last))
            && v.getRoadEnd().getJunction().equals(via.getRoadEnd().getJunction())) {
          return new Connecting(lane, Collections.unmodifiableList(tmp));
        }
      }

      tmp.add(via);
      return new Connecting(lane, Collections.unmodifiableList(tmp));
    }
 private List<SchemaTransaction> generateTableTransactions(
     Database sourceDatabase, Database shadowDatabase) {
   List<SchemaTransaction> schemaTransactionList = new ArrayList<SchemaTransaction>();
   if (shadowDatabase == null) {
     for (Table table : sourceDatabase.getTableList()) {
       schemaTransactionList.add(new SchemaTransaction(table, TransactionType.INSERT));
       schemaTransactionList.addAll(generateColumnTransactions(table, null));
     }
   } else {
     Collections.sort(sourceDatabase.getTableList());
     Collections.sort(shadowDatabase.getTableList());
     for (Table table : sourceDatabase.getTableList()) {
       if (!shadowDatabase.getTableList().contains(table)) {
         table.setDatabase(shadowDatabase);
         schemaTransactionList.add(new SchemaTransaction(table, TransactionType.INSERT));
         schemaTransactionList.addAll(generateColumnTransactions(table, null));
       } else {
         Table shadowTable =
             shadowDatabase.getTableList().get(shadowDatabase.getTableList().indexOf(table));
         if (!table.getPk().equals(shadowTable.getPk())) {
           table.setId(shadowTable.getId());
           schemaTransactionList.add(new SchemaTransaction(table, TransactionType.UPDATE));
         }
         schemaTransactionList.addAll(generateColumnTransactions(table, shadowTable));
       }
     }
     for (Table table : shadowDatabase.getTableList()) {
       if (!sourceDatabase.getTableList().contains(table)) {
         schemaTransactionList.add(new SchemaTransaction(table, TransactionType.DELETE));
       }
     }
   }
   return schemaTransactionList;
 }
 private Query makeQuery(String query) {
   Query q = new Query();
   q.setInput(Collections.<String, Object>singletonMap("query", query));
   q.setConnectorGuids(
       Collections.singletonList(UUID.fromString("39df3fe4-c716-478b-9b80-bdbee43bfbde")));
   return q;
 }
 private GetDeviceInputImpl(GetDeviceInputBuilder base) {
   this._deviceId = base.getDeviceId();
   switch (base.augmentation.size()) {
     case 0:
       this.augmentation = Collections.emptyMap();
       break;
     case 1:
       final Map.Entry<
               java.lang.Class<
                   ? extends
                       Augmentation<
                           org.onos.yang.gen.v1.urn.onos.core.device.service.rev151001
                               .GetDeviceInput>>,
               Augmentation<
                   org.onos.yang.gen.v1.urn.onos.core.device.service.rev151001.GetDeviceInput>>
           e = base.augmentation.entrySet().iterator().next();
       this.augmentation =
           Collections
               .<java.lang.Class<
                       ? extends
                           Augmentation<
                               org.onos.yang.gen.v1.urn.onos.core.device.service.rev151001
                                   .GetDeviceInput>>,
                   Augmentation<
                       org.onos.yang.gen.v1.urn.onos.core.device.service.rev151001
                           .GetDeviceInput>>
                   singletonMap(e.getKey(), e.getValue());
       break;
     default:
       this.augmentation = new HashMap<>(base.augmentation);
   }
 }
Example #19
0
 static {
   JAVA_IMMUTABLE =
       Collections.unmodifiableSet(
           new HashSet<>(
               Arrays.asList(
                   Boolean.class,
                   Byte.class,
                   Character.class,
                   Double.class,
                   Float.class,
                   Short.class,
                   Integer.class,
                   Long.class,
                   BigInteger.class,
                   BigDecimal.class,
                   String.class,
                   Class.class,
                   UUID.class,
                   URL.class,
                   URI.class,
                   Pattern.class,
                   Inet4Address.class,
                   Inet6Address.class,
                   InetSocketAddress.class,
                   LocalDate.class,
                   LocalTime.class,
                   LocalDateTime.class,
                   Instant.class,
                   Duration.class)));
   Map<Class<?>, Function<Object, Object>> strategies = new HashMap<>();
   strategies.put(Calendar.class, o -> ((Calendar) o).clone());
   strategies.put(Date.class, o -> ((Date) o).clone());
   JAVA_DEEP_COPY = Collections.unmodifiableMap(strategies);
 }
 static {
   TreeMap<String, Object> v = new TreeMap<String, Object>();
   v.put("wdBalloonPrintOrientationAuto", wdBalloonPrintOrientationAuto);
   v.put("wdBalloonPrintOrientationPreserve", wdBalloonPrintOrientationPreserve);
   v.put("wdBalloonPrintOrientationForceLandscape", wdBalloonPrintOrientationForceLandscape);
   values = Collections.synchronizedMap(Collections.unmodifiableMap(v));
 }
Example #21
0
  /**
   * Utility method used in the construction of {@link UnitGraph}s, to be called only after the
   * unitToPreds and unitToSuccs maps have been built.
   *
   * <p><code>UnitGraph</code> provides an implementation of <code>buildHeadsAndTails()</code> which
   * defines the graph's set of heads to include the first {@link Unit} in the graph's body,
   * together with any other <tt>Unit</tt> which has no predecessors. It defines the graph's set of
   * tails to include all <tt>Unit</tt>s with no successors. Subclasses of <code>UnitGraph</code>
   * may override this method to change the criteria for classifying a node as a head or tail.
   */
  protected void buildHeadsAndTails() {
    List tailList = new ArrayList();
    List headList = new ArrayList();

    for (Iterator unitIt = unitChain.iterator(); unitIt.hasNext(); ) {
      Unit s = (Unit) unitIt.next();
      List succs = (List) unitToSuccs.get(s);
      if (succs.size() == 0) {
        tailList.add(s);
      }
      List preds = (List) unitToPreds.get(s);
      if (preds.size() == 0) {
        headList.add(s);
      }
    }

    // Add the first Unit, even if it is the target of
    // a branch.
    Unit entryPoint = (Unit) unitChain.getFirst();
    if (!headList.contains(entryPoint)) {
      headList.add(entryPoint);
    }

    tails = Collections.unmodifiableList(tailList);
    heads = Collections.unmodifiableList(headList);
  }
  protected Collection getKeysOfType(int elementType) {

    LinkedList keys = (LinkedList) super.getKeysOfType(elementType);
    LinkedList temp = null;

    if ((elementType & PatternFilter.PROPERTY) != 0) {
      temp = new LinkedList();
      temp.addAll(patternAnalyser.getPropertyPatterns());
      Collections.sort(temp, new PatternComparator());
      keys.addAll(temp);
      // keys.addAll( patternAnalyser.getPropertyPatterns() );
    }
    if ((elementType & PatternFilter.IDXPROPERTY) != 0) {
      temp = new LinkedList();
      temp.addAll(patternAnalyser.getIdxPropertyPatterns());
      Collections.sort(temp, new PatternComparator());
      keys.addAll(temp);
      // keys.addAll( patternAnalyser.getIdxPropertyPatterns() );
    }
    if ((elementType & PatternFilter.EVENT_SET) != 0) {
      temp = new LinkedList();
      temp.addAll(patternAnalyser.getEventSetPatterns());
      Collections.sort(temp, new PatternComparator());
      keys.addAll(temp);
      // keys.addAll( patternAnalyser.getEventSetPatterns() );
    }

    //    if ((filter == null) || filter.isSorted ())
    //      Collections.sort (keys, comparator);
    return keys;
  }
  /** Test attributes map */
  public void testAttributes() throws Exception {
    Directory dir = newDirectory();
    Codec codec = getCodec();
    byte id[] = StringHelper.randomId();
    Map<String, String> attributes = new HashMap<>();
    attributes.put("key1", "value1");
    attributes.put("key2", "value2");
    SegmentInfo info =
        new SegmentInfo(
            dir,
            getVersions()[0],
            "_123",
            1,
            false,
            codec,
            Collections.emptyMap(),
            id,
            attributes,
            null);
    info.setFiles(Collections.<String>emptySet());
    codec.segmentInfoFormat().write(dir, info, IOContext.DEFAULT);
    SegmentInfo info2 = codec.segmentInfoFormat().read(dir, "_123", id, IOContext.DEFAULT);
    assertEquals(attributes, info2.getAttributes());

    // attributes map should be immutable
    expectThrows(
        UnsupportedOperationException.class,
        () -> {
          info2.getAttributes().put("bogus", "bogus");
        });

    dir.close();
  }
Example #24
0
  public void testIsEmpty() {
    Iterable<String> emptyList = Collections.emptyList();
    assertTrue(Iterables.isEmpty(emptyList));

    Iterable<String> singletonList = Collections.singletonList("foo");
    assertFalse(Iterables.isEmpty(singletonList));
  }
Example #25
0
  /**
   * Given a new LimitOrder, it will replace and old matching limit order in the orderbook or simply
   * get added. Finally, it is sorted.
   *
   * @param limitOrder
   */
  public void update(LimitOrder limitOrder) {

    if (limitOrder.getType().equals(OrderType.ASK)) {

      Iterator<LimitOrder> it = asks.iterator();
      while (it.hasNext()) {
        LimitOrder order = it.next();
        if (order.getLimitPrice().compareTo(limitOrder.getLimitPrice())
            == 0) { // they are equal. found it!
          it.remove();
          break;
        }
      }
      asks.add(limitOrder); // just add it
      Collections.sort(asks); // finally sort

    } else {

      Iterator<LimitOrder> it = bids.iterator();
      while (it.hasNext()) {
        LimitOrder order = it.next();
        if (order.getLimitPrice().compareTo(limitOrder.getLimitPrice())
            == 0) { // they are equal. found it!
          it.remove();
          break;
        }
      }
      bids.add(limitOrder); // just add it
      Collections.sort(bids); // finally sort
    }
  }
  @Override
  public List<MenuEntry> getEntries() {
    if (cfg == null || cfgSnapshot.isModified(cfgFile)) {
      cfgSnapshot = FileSnapshot.save(cfgFile);
      cfg = new FileBasedConfig(cfgFile, FS.DETECTED);
      try {
        cfg.load();
      } catch (ConfigInvalidException | IOException e) {
        return Collections.emptyList();
      }
    }

    List<MenuEntry> menuEntries = new ArrayList<>();
    for (String url : cfg.getSubsections(SECTION_MENU_ITEM)) {
      String name = cfg.getString(SECTION_MENU_ITEM, url, KEY_NAME);
      if (Strings.isNullOrEmpty(name)) {
        continue;
      }

      String topMenu = cfg.getString(SECTION_MENU_ITEM, url, KEY_TOP_MENU);
      if (topMenu == null) {
        topMenu = DEFAULT_TOP_MENU;
      }

      String target = cfg.getString(SECTION_MENU_ITEM, url, KEY_TARGET);
      String id = cfg.getString(SECTION_MENU_ITEM, url, KEY_ID);

      menuEntries.add(
          new MenuEntry(topMenu, Collections.singletonList(new MenuItem(name, url, target, id))));
    }
    return menuEntries;
  }
Example #27
0
 /** Searches for the node or nodes that match the path element for the given parent node */
 private List<NodeRef> getDirectDescendents(NodeRef pathRootNodeRef, String pathElement) {
   if (logger.isDebugEnabled()) {
     logger.debug(
         "Getting direct descendents: \n"
             + "   Path Root: "
             + pathRootNodeRef
             + "\n"
             + "   Path Element: "
             + pathElement);
   }
   List<NodeRef> results = null;
   // if this contains no wildcards, then we can fasttrack it
   if (!WildCard.containsWildcards(pathElement)) {
     // a specific name is required
     NodeRef foundNodeRef = fileFolderService.searchSimple(pathRootNodeRef, pathElement);
     if (foundNodeRef == null) {
       results = Collections.emptyList();
     } else {
       results = Collections.singletonList(foundNodeRef);
     }
   } else {
     // escape for the Lucene syntax search
     String escapedPathElement = SearchLanguageConversion.convertCifsToLucene(pathElement);
     // do the lookup
     List<org.alfresco.service.cmr.model.FileInfo> childInfos =
         fileFolderService.search(pathRootNodeRef, escapedPathElement, false);
     // convert to noderefs
     results = new ArrayList<NodeRef>(childInfos.size());
     for (org.alfresco.service.cmr.model.FileInfo info : childInfos) {
       results.add(info.getNodeRef());
     }
   }
   // done
   return results;
 }
Example #28
0
  private List<Future<?>> loadSavedMetricsToCaches(String accessLevelName) {
    String storage = metricStorage + "/" + accessLevelName;
    Path storageFile = Paths.get(storage);
    if (!Files.exists(storageFile)) {
      log.info("Cannot pre-load cache {} - file {} doesn't exist", accessLevelName, storage);
      return Collections.emptyList();
    }

    try (BufferedReader fromStorageFile =
        new BufferedReader(
            new InputStreamReader(
                new GZIPInputStream(Files.newInputStream(storageFile)),
                Charset.forName("UTF-8")))) {
      boolean firstLine = true;
      String metricName;
      List<Future<?>> futures = new ArrayList<>();
      while ((metricName = fromStorageFile.readLine()) != null) {
        if (firstLine) {
          firstLine = false;
        } else {
          futures.add(createNewCacheLines(metricName));
        }
      }
      return futures;
    } catch (IOException e) {
      log.info("could not find file for accessLevel " + accessLevelName, e);
      return Collections.emptyList();
    }
  }
  private List<InvoiceConfiguration> sort(List<InvoiceConfiguration> entries, boolean asc) {

    if (asc) {

      Collections.sort(
          entries,
          new Comparator<InvoiceConfiguration>() {

            @Override
            public int compare(InvoiceConfiguration arg0, InvoiceConfiguration arg1) {
              if (arg0.getAlias() == null) return -1;
              if (arg1.getAlias() == null) return 1;
              return (arg0).getAlias().compareTo((arg1).getAlias());
            }
          });

    } else {

      Collections.sort(
          entries,
          new Comparator<InvoiceConfiguration>() {

            @Override
            public int compare(InvoiceConfiguration arg0, InvoiceConfiguration arg1) {
              if (arg0.getAlias() == null) return 1;
              if (arg1.getAlias() == null) return -1;
              return (arg1).getAlias().compareTo((arg0).getAlias());
            }
          });
    }
    return entries;
  }
    @Override
    public void routeInputSourceTaskFailedEventToDestination(
        int sourceTaskIndex, Map<Integer, List<Integer>> destinationTaskAndInputIndices) {
      if (remainderRangeForLastShuffler < basePartitionRange) {
        int startOffset = sourceTaskIndex * basePartitionRange;
        List<Integer> allIndices = Lists.newArrayListWithCapacity(basePartitionRange);
        for (int i = 0; i < basePartitionRange; ++i) {
          allIndices.add(startOffset + i);
        }
        List<Integer> inputIndices = Collections.unmodifiableList(allIndices);
        for (int i = 0; i < numDestinationTasks - 1; ++i) {
          destinationTaskAndInputIndices.put(i, inputIndices);
        }

        startOffset = sourceTaskIndex * remainderRangeForLastShuffler;
        allIndices = Lists.newArrayListWithCapacity(remainderRangeForLastShuffler);
        for (int i = 0; i < remainderRangeForLastShuffler; ++i) {
          allIndices.add(startOffset + i);
        }
        inputIndices = Collections.unmodifiableList(allIndices);
        destinationTaskAndInputIndices.put(numDestinationTasks - 1, inputIndices);
      } else {
        // all tasks have same pattern
        int startOffset = sourceTaskIndex * basePartitionRange;
        List<Integer> allIndices = Lists.newArrayListWithCapacity(basePartitionRange);
        for (int i = 0; i < basePartitionRange; ++i) {
          allIndices.add(startOffset + i);
        }
        List<Integer> inputIndices = Collections.unmodifiableList(allIndices);
        for (int i = 0; i < numDestinationTasks; ++i) {
          destinationTaskAndInputIndices.put(i, inputIndices);
        }
      }
    }