@Test
 public void forceNewGameWillRestartTableAndStartNewGame() {
   Map<BigDecimal, BigDecimal> playerIdToAccountIdOverrides = new HashMap<>();
   playerIdToAccountIdOverrides.put(PLAYER_ID, BigDecimal.valueOf(202020));
   com.yazino.game.api.GameStatus status = new GameStatus(new PrintlnStatus());
   com.yazino.game.api.ExecutionResult result =
       new com.yazino.game.api.ExecutionResult.Builder(gameRules, status).build();
   when(gameRules.startNewGame(isA(com.yazino.game.api.GameCreationContext.class)))
       .thenReturn(result);
   when(auditor.newLabel()).thenReturn("X");
   host = gameHost(new InMemoryGameRepository(gameRules));
   table.setTableStatus(TableStatus.closed);
   table.setCurrentGame(null);
   Collection<com.yazino.game.api.PlayerAtTableInformation> playersAtTable =
       Arrays.asList(
           new com.yazino.game.api.PlayerAtTableInformation(
               new com.yazino.game.api.GamePlayer(PLAYER1_ID, null, "One"),
               Collections.<String, String>emptyMap()),
           new com.yazino.game.api.PlayerAtTableInformation(
               new com.yazino.game.api.GamePlayer(PLAYER2_ID, null, "Two"),
               Collections.<String, String>emptyMap()));
   host.forceNewGame(table, playersAtTable, playerIdToAccountIdOverrides);
   ArgumentCaptor<com.yazino.game.api.GameCreationContext> contextCaptor =
       ArgumentCaptor.forClass(com.yazino.game.api.GameCreationContext.class);
   verify(gameRules).startNewGame(contextCaptor.capture());
   assertEquals(TableStatus.open, table.getTableStatus());
   assertEquals(status, table.getCurrentGame());
   assertEquals(playersAtTable, contextCaptor.getValue().getPlayersAtTableInformation());
 }
  @Test
  public void shouldQueryResourceSetToken() throws Exception {

    // Given
    Map<String, Object> queryParameters = new HashMap<String, Object>();
    queryParameters.put(ResourceSetTokenField.CLIENT_ID, "CLIENT_ID");
    ResourceSetDescription resourceSet1 =
        new ResourceSetDescription(
            "123", "CLIENT_ID", "RESOURCE_OWNER_ID", Collections.<String, Object>emptyMap());
    ResourceSetDescription resourceSet2 =
        new ResourceSetDescription(
            "456", "CLIENT_ID", "RESOURCE_OWNER_ID", Collections.<String, Object>emptyMap());

    given(dataStore.query(Matchers.<QueryFilter<String>>anyObject()))
        .willReturn(asSet(resourceSet1, resourceSet2));
    resourceSet1.setRealm("REALM");
    resourceSet2.setRealm("REALM");

    // When
    QueryFilter<String> query = QueryFilter.alwaysTrue();
    Set<ResourceSetDescription> resourceSetDescriptions = store.query(query);

    // Then
    assertThat(resourceSetDescriptions).contains(resourceSet1, resourceSet2);
    ArgumentCaptor<QueryFilter> tokenFilterCaptor = ArgumentCaptor.forClass(QueryFilter.class);
    verify(dataStore).query(tokenFilterCaptor.capture());
    assertThat(tokenFilterCaptor.getValue())
        .isEqualTo(
            QueryFilter.and(query, QueryFilter.equalTo(ResourceSetTokenField.REALM, "REALM")));
  }
  @Test
  public void testCompatibleExtensionTogetherSuccess() {
    // initialize
    expect(mainHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("main")))
        .andReturn(mainExtensionMock)
        .anyTimes();
    expect(mainHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("fallback")))
        .andReturn(null)
        .anyTimes();
    replay(mainHandshakerMock);

    expect(fallbackHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("fallback")))
        .andReturn(fallbackExtensionMock)
        .anyTimes();
    expect(fallbackHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("main")))
        .andReturn(null)
        .anyTimes();
    replay(fallbackHandshakerMock);

    expect(mainExtensionMock.rsv()).andReturn(WebSocketExtension.RSV1).anyTimes();
    expect(mainExtensionMock.newReponseData())
        .andReturn(new WebSocketExtensionData("main", Collections.<String, String>emptyMap()))
        .once();
    expect(mainExtensionMock.newExtensionEncoder()).andReturn(new DummyEncoder()).once();
    expect(mainExtensionMock.newExtensionDecoder()).andReturn(new DummyDecoder()).once();
    replay(mainExtensionMock);

    expect(fallbackExtensionMock.rsv()).andReturn(WebSocketExtension.RSV2).anyTimes();
    expect(fallbackExtensionMock.newReponseData())
        .andReturn(new WebSocketExtensionData("fallback", Collections.<String, String>emptyMap()))
        .once();
    expect(fallbackExtensionMock.newExtensionEncoder()).andReturn(new Dummy2Encoder()).once();
    expect(fallbackExtensionMock.newExtensionDecoder()).andReturn(new Dummy2Decoder()).once();
    replay(fallbackExtensionMock);

    // execute
    EmbeddedChannel ch =
        new EmbeddedChannel(
            new WebSocketServerExtensionHandler(mainHandshakerMock, fallbackHandshakerMock));

    HttpRequest req = newUpgradeRequest("main, fallback");
    ch.writeInbound(req);

    HttpResponse res = newUpgradeResponse(null);
    ch.writeOutbound(res);

    HttpResponse res2 = ch.readOutbound();
    List<WebSocketExtensionData> resExts =
        WebSocketExtensionUtil.extractExtensions(
            res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));

    // test
    assertEquals(2, resExts.size());
    assertEquals("main", resExts.get(0).name());
    assertEquals("fallback", resExts.get(1).name());
    assertNotNull(ch.pipeline().get(DummyDecoder.class));
    assertNotNull(ch.pipeline().get(DummyEncoder.class));
    assertNotNull(ch.pipeline().get(Dummy2Decoder.class));
    assertNotNull(ch.pipeline().get(Dummy2Encoder.class));
  }
Ejemplo n.º 4
0
  public void easyLub() {
    java.util.Map<String, Number> m = java.util.Collections.emptyMap();

    lombok.val foo =
        (System.currentTimeMillis() > 0) ? m : java.util.Collections.<String, Number>emptyMap();
    System.out.println(foo);
  }
  /**
   * Obtains attributes first from the repository by calling {@link
   * org.jasig.services.persondir.IPersonAttributeDao#getPerson(String)}.
   *
   * @param id the person id to locate in the attribute repository
   * @return the map of attributes
   */
  private Map<String, List<Object>> retrievePersonAttributesToPrincipalAttributes(final String id) {

    final IPersonAttributes attrs;
    if (this.attributeRepository == null) {
      final ApplicationContext context = ApplicationContextProvider.getApplicationContext();
      final IPersonAttributeDao attributeRepository =
          context.getBean("attributeRepository", IPersonAttributeDao.class);
      attrs = attributeRepository.getPerson(id);
    } else {
      attrs = this.attributeRepository.getPerson(id);
    }

    if (attrs == null) {
      LOGGER.debug(
          "Could not find principal [{}] in the repository so no attributes are returned.", id);
      return Collections.emptyMap();
    }

    final Map<String, List<Object>> attributes = attrs.getAttributes();
    if (attributes == null) {
      LOGGER.debug("Principal [{}] has no attributes and so none are returned.", id);
      return Collections.emptyMap();
    }
    return attributes;
  }
Ejemplo n.º 6
0
  public Map<String, String> getContextClassifiers(SNode contextNode) {
    // only AnonymousClass has Classifier as reference
    // todo: make it clearer
    if (SNodeOperations.isInstanceOf(
        contextNode, "jetbrains.mps.baseLanguage.structure.IAnonymousClass")) {
      contextNode = SNodeOperations.getParent(contextNode);
    }
    if (SNodeOperations.isInstanceOf(
        contextNode, "jetbrains.mps.baseLanguage.structure.Classifier")) {
      if (LOG.isEnabledFor(Level.WARN)) {
        LOG.warn("contextNode is classifier in getContextClassifiers: " + contextNode);
      }
      return Collections.emptyMap();
    }

    // find first classifier in path
    String sourceChildRole = null;
    while ((contextNode != null)
        && !(SNodeOperations.isInstanceOf(
            contextNode, "jetbrains.mps.baseLanguage.structure.Classifier"))) {
      sourceChildRole = contextNode.getRoleInParent();
      contextNode = SNodeOperations.getParent(contextNode);
    }

    if ((contextNode == null)) {
      // todo: impossible?
      return Collections.emptyMap();
    }

    return contextClassifiersCache.get(
        MultiTuple.<SNode, String>from(
            SNodeOperations.cast(contextNode, "jetbrains.mps.baseLanguage.structure.Classifier"),
            sourceChildRole));
  }
 public void testBackCompatOverrideDefaultIndexAndSearchAnalyzer() {
   Version version =
       VersionUtils.randomVersionBetween(
           random(),
           VersionUtils.getFirstVersion(),
           VersionUtils.getPreviousVersion(Version.V_5_0_0_alpha1));
   Settings settings =
       Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, version).build();
   Map<String, AnalyzerProvider<?>> analyzers = new HashMap<>();
   analyzers.put("default_index", analyzerProvider("default_index"));
   analyzers.put("default_search", analyzerProvider("default_search"));
   IndexAnalyzers indexAnalyzers =
       registry.build(
           IndexSettingsModule.newIndexSettings("index", settings),
           analyzers,
           Collections.emptyMap(),
           Collections.emptyMap(),
           Collections.emptyMap(),
           Collections.emptyMap());
   assertThat(
       indexAnalyzers.getDefaultIndexAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class));
   assertThat(
       indexAnalyzers.getDefaultSearchAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class));
   assertThat(
       indexAnalyzers.getDefaultSearchQuoteAnalyzer().analyzer(),
       instanceOf(EnglishAnalyzer.class));
   assertWarnings(
       "setting [index.analysis.analyzer.default_index] is deprecated, use [index.analysis.analyzer.default] "
           + "instead for index [index]");
 }
Ejemplo n.º 8
0
  public void testFoo() throws Exception {
    RAMFileSystem fs = new RAMFileSystem();
    FileSystemScanner<RAMPath> scanner = new FileSystemScanner<RAMPath>(fs);

    //
    assertEquals(Collections.<String, Change>emptyMap(), scanner.scan());

    //
    RAMPath foo = fs.addDir(fs.getRoot(), "foo");
    assertEquals(Collections.<String, Change>emptyMap(), scanner.scan());

    RAMFile bar = fs.addFile(foo, "bar.txt");
    waitForOneMillis();
    assertEquals(Collections.singletonMap("foo/bar.txt", Change.ADD), scanner.scan());
    assertEquals(Collections.<String, Change>emptyMap(), scanner.scan());

    bar.update("abc");
    waitForOneMillis();
    assertEquals(Collections.singletonMap("foo/bar.txt", Change.UPDATE), scanner.scan());
    assertEquals(Collections.<String, Change>emptyMap(), scanner.scan());

    bar.remove();
    waitForOneMillis();
    assertEquals(Collections.singletonMap("foo/bar.txt", Change.REMOVE), scanner.scan());
    assertEquals(Collections.<String, Change>emptyMap(), scanner.scan());
  }
 public void testBackCompatOverrideDefaultIndexAndSearchAnalyzer() {
   Version version =
       VersionUtils.randomVersionBetween(
           getRandom(),
           VersionUtils.getFirstVersion(),
           VersionUtils.getPreviousVersion(Version.V_3_0_0));
   Settings settings =
       Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, version).build();
   Map<String, AnalyzerProvider> analyzers = new HashMap<>();
   analyzers.put("default_index", analyzerProvider("default_index"));
   analyzers.put("default_search", analyzerProvider("default_search"));
   AnalysisService analysisService =
       new AnalysisService(
           IndexSettingsModule.newIndexSettings("index", settings),
           analyzers,
           Collections.emptyMap(),
           Collections.emptyMap(),
           Collections.emptyMap());
   assertThat(
       analysisService.defaultIndexAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class));
   assertThat(
       analysisService.defaultSearchAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class));
   assertThat(
       analysisService.defaultSearchQuoteAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class));
 }
Ejemplo n.º 10
0
  /**
   * @param props The {@link Properties} holding the server's configuration - ignored if {@code
   *     null}/empty
   * @param options The {@link LinkOption}s to use when checking files existence
   * @return A {@link Map} of the found identities where key=the identity type (case
   *     <U>insensitive</U>) and value=the {@link Path} of the file holding the specific type key
   * @throws IOException If failed to access the file system
   * @see #getIdentityType(String)
   * @see #HOST_KEY_CONFIG_PROP
   * @see org.apache.sshd.common.config.SshConfigFileReader#readConfigFile(File)
   */
  public static Map<String, Path> findIdentities(Properties props, LinkOption... options)
      throws IOException {
    if (GenericUtils.isEmpty(props)) {
      return Collections.emptyMap();
    }

    String keyList = props.getProperty(HOST_KEY_CONFIG_PROP);
    String[] paths = GenericUtils.split(keyList, ',');
    if (GenericUtils.isEmpty(paths)) {
      return Collections.emptyMap();
    }

    Map<String, Path> ids = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    for (String p : paths) {
      File file = new File(p);
      Path path = file.toPath();
      if (!Files.exists(path, options)) {
        continue;
      }

      String type = getIdentityType(path.getFileName().toString());
      if (GenericUtils.isEmpty(type)) {
        type = p; // just in case the file name does not adhere to the standard naming convention
      }
      Path prev = ids.put(type, path);
      ValidateUtils.checkTrue(prev == null, "Multiple mappings for type=%s", type);
    }

    return ids;
  }
  @Override
  public Map<X509Certificate, List<X509Certificate>> getSignerCertificates(int signersType) {
    SignedContentFactory factory = equinoxContainer.getSignedContentFactory();
    if (factory == null) {
      return Collections.emptyMap();
    }

    try {
      SignerInfo[] infos = signerInfos;
      if (infos == null) {
        SignedContent signedContent = factory.getSignedContent(this);
        infos = signedContent.getSignerInfos();
        signerInfos = infos;
      }
      if (infos.length == 0) return Collections.emptyMap();
      Map<X509Certificate, List<X509Certificate>> results =
          new HashMap<X509Certificate, List<X509Certificate>>(infos.length);
      for (int i = 0; i < infos.length; i++) {
        if (signersType == SIGNERS_TRUSTED && !infos[i].isTrusted()) continue;
        Certificate[] certs = infos[i].getCertificateChain();
        if (certs == null || certs.length == 0) continue;
        List<X509Certificate> certChain = new ArrayList<X509Certificate>();
        for (int j = 0; j < certs.length; j++) certChain.add((X509Certificate) certs[j]);
        results.put((X509Certificate) certs[0], certChain);
      }
      return results;
    } catch (Exception e) {
      return Collections.emptyMap();
    }
  }
Ejemplo n.º 12
0
 @Override
 protected Map<String, String> _run() {
   Output.print(description);
   List<Action> comments = RestTemplate.get(url, new TypeReference<List<Action>>() {});
   if ((comments == null) || comments.isEmpty()) {
     Output.print("  ^black^None^r^");
     return Collections.emptyMap();
   }
   Collections.reverse(comments); // reverse order of comments so most recent appear on bottom
   String color = "white";
   for (Action comment : comments) {
     Output.print("^%s^|^r^%n^%s^|^r^ %s", color, color, comment.getMemberCreator().getFullName());
     Output.print("^%s^|^r^ ^black^%s^r^%n^%s^|^r^", color, comment.getDate(), color);
     String text = comment.getData().getText();
     String[] splits = text.split("\n");
     for (String split : splits) {
       Output.print("^%s^|^r^ ^b^%s^r^", color, split);
     }
     Output.print("^%s^|^r^%n", color);
     if ("white".equals(color)) {
       color = "black";
     } else {
       color = "white";
     }
   }
   return Collections.emptyMap();
 }
Ejemplo n.º 13
0
 public void testCopyOfEmptyMap() {
   ImmutableBiMap<String, Integer> copy =
       ImmutableBiMap.copyOf(Collections.<String, Integer>emptyMap());
   assertEquals(Collections.<String, Integer>emptyMap(), copy);
   assertSame(copy, ImmutableBiMap.copyOf(copy));
   assertSame(ImmutableBiMap.of(), copy);
 }
Ejemplo n.º 14
0
 @SuppressWarnings("deprecation")
 private void testUnsupportedOperations() throws SQLException {
   ResultSet rs = stat.executeQuery("select 1 as x from dual");
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).getUnicodeStream(1);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).getUnicodeStream("x");
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs)
       .getObject(1, Collections.<String, Class<?>>emptyMap());
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs)
       .getObject("x", Collections.<String, Class<?>>emptyMap());
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).getRef(1);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).getRef("x");
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).getURL(1);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).getURL("x");
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).getRowId(1);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).getRowId("x");
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).getSQLXML(1);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).getSQLXML("x");
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).updateRef(1, (Ref) null);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).updateRef("x", (Ref) null);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).updateArray(1, (Array) null);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).updateArray("x", (Array) null);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).updateRowId(1, (RowId) null);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).updateRowId("x", (RowId) null);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).updateNClob(1, (NClob) null);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).updateNClob("x", (NClob) null);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).updateSQLXML(1, (SQLXML) null);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).updateSQLXML("x", (SQLXML) null);
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).getCursorName();
   assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, rs).setFetchDirection(ResultSet.FETCH_FORWARD);
 }
  /** Initializes future. */
  public void init() {
    AffinityTopologyVersion lockedTopVer = cctx.shared().lockedTopologyVersion(null);

    if (lockedTopVer != null) {
      canRemap = false;

      map(
          keys,
          Collections.<ClusterNode, LinkedHashMap<KeyCacheObject, Boolean>>emptyMap(),
          lockedTopVer);
    } else {
      AffinityTopologyVersion topVer =
          this.topVer.topologyVersion() > 0
              ? this.topVer
              : canRemap
                  ? cctx.affinity().affinityTopologyVersion()
                  : cctx.shared().exchange().readyAffinityVersion();

      map(
          keys,
          Collections.<ClusterNode, LinkedHashMap<KeyCacheObject, Boolean>>emptyMap(),
          topVer);
    }

    markInitialized();
  }
Ejemplo n.º 16
0
  /**
   * Should only be called while holding a lock from {@link #lock}
   *
   * @return
   */
  private Snapshot getSnapshot(boolean openingPrices) {
    lock.readLock().lock();
    try {
      Availability availability = getCurrentAvailability();
      /* Nothing we can check */
      if (availability == Availability.NONE) {
        return new Snapshot(availability, null, Collections.<String, Double>emptyMap());
      }

      /* Pick a random Jedis to call */
      Map<ServiceReference<Endpoint>, JedisPool> toUse =
          new HashMap<ServiceReference<Endpoint>, JedisPool>(writableMap);
      toUse.putAll(readableMap);
      ServiceReference<Endpoint> ref = getARandomJedis(toUse);

      /* Get the prices */
      Map<String, Double> prices = getPrices(toUse.get(ref), openingPrices);
      while (prices == null && !toUse.isEmpty()) {
        // This Jedis didn't work!
        toUse.remove(ref);
        ref = getARandomJedis(toUse);
        prices = getPrices(toUse.get(ref), openingPrices);
      }
      /* Return the data */
      return (prices == null)
          ? new Snapshot(Availability.NONE, null, Collections.<String, Double>emptyMap())
          : new Snapshot(availability, (String) ref.getProperty(Endpoint.URI), prices);
    } finally {
      lock.readLock().unlock();
    }
  }
Ejemplo n.º 17
0
  public boolean announceMigration(boolean isLocalOnly) throws RequestValidationException {
    CFMetaData cfm = Schema.instance.getCFMetaData(keyspace(), columnFamily()).copy();
    IndexTarget target = rawTarget.prepare(cfm);
    logger.debug("Updating column {} definition for index {}", target.column, indexName);
    ColumnDefinition cd = cfm.getColumnDefinition(target.column);

    if (cd.getIndexType() != null && ifNotExists) return false;

    if (properties.isCustom) {
      cd.setIndexType(IndexType.CUSTOM, properties.getOptions());
    } else if (cfm.comparator.isCompound()) {
      Map<String, String> options = Collections.emptyMap();
      // For now, we only allow indexing values for collections, but we could later allow
      // to also index map keys, so we record that this is the values we index to make our
      // lives easier then.
      if (cd.type.isCollection() && cd.type.isMultiCell())
        options =
            ImmutableMap.of(
                target.isCollectionKeys
                    ? SecondaryIndex.INDEX_KEYS_OPTION_NAME
                    : SecondaryIndex.INDEX_VALUES_OPTION_NAME,
                "");
      cd.setIndexType(IndexType.COMPOSITES, options);
    } else {
      cd.setIndexType(IndexType.KEYS, Collections.<String, String>emptyMap());
    }

    cd.setIndexName(indexName);
    cfm.addDefaultIndexNames();
    MigrationManager.announceColumnFamilyUpdate(cfm, false, isLocalOnly);
    return true;
  }
Ejemplo n.º 18
0
  public static Map<String, String> getParameters(String url) {
    if (url == null || (url = url.trim()).length() == 0) {
      return Collections.<String, String>emptyMap();
    }

    String parametersStr = StringUtils.subString(url, "?", null);
    if (parametersStr == null || parametersStr.length() == 0) {
      return Collections.<String, String>emptyMap();
    }

    String[] parametersArray = parametersStr.split("&");
    Map<String, String> parameters = new LinkedHashMap<String, String>();

    for (String parameterStr : parametersArray) {
      int index = parameterStr.indexOf("=");
      if (index <= 0) {
        continue;
      }

      String name = parameterStr.substring(0, index);
      String value = parameterStr.substring(index + 1);
      parameters.put(name, value);
    }
    return parameters;
  }
  @NotNull
  private static Map<Module, String> collectJpsPluginModules(@NotNull Module module) {
    XmlFile pluginXml = PluginModuleType.getPluginXml(module);
    if (pluginXml == null) return Collections.emptyMap();

    DomFileElement<IdeaPlugin> fileElement =
        DomManager.getDomManager(module.getProject()).getFileElement(pluginXml, IdeaPlugin.class);
    if (fileElement == null) return Collections.emptyMap();

    Map<Module, String> jpsPluginToOutputPath = new HashMap<Module, String>();
    IdeaPlugin plugin = fileElement.getRootElement();
    List<Extensions> extensions = plugin.getExtensions();
    for (Extensions extensionGroup : extensions) {
      XmlTag extensionsTag = extensionGroup.getXmlTag();
      String defaultExtensionNs = extensionsTag.getAttributeValue("defaultExtensionNs");
      for (XmlTag tag : extensionsTag.getSubTags()) {
        String name = tag.getLocalName();
        String qualifiedName = defaultExtensionNs != null ? defaultExtensionNs + "." + name : name;
        if (CompileServerPlugin.EP_NAME.getName().equals(qualifiedName)) {
          String classpath = tag.getAttributeValue("classpath");
          if (classpath != null) {
            for (String path : StringUtil.split(classpath, ";")) {
              String moduleName = FileUtil.getNameWithoutExtension(PathUtil.getFileName(path));
              Module jpsModule =
                  ModuleManager.getInstance(module.getProject()).findModuleByName(moduleName);
              if (jpsModule != null) {
                jpsPluginToOutputPath.put(jpsModule, path);
              }
            }
          }
        }
      }
    }
    return jpsPluginToOutputPath;
  }
 public FileTypeAssocTable() {
   this(
       Collections.<CharSequence, T>emptyMap(),
       Collections.<CharSequence, T>emptyMap(),
       Collections.<CharSequence, T>emptyMap(),
       Collections.<Pair<FileNameMatcher, T>>emptyList());
 }
Ejemplo n.º 21
0
  public static Map<String, Object> merge(
      Map<String, Object> source, Map<String, Object> defaultMap) {
    if (source == null) {
      source = Collections.emptyMap();
    }
    if (defaultMap == null) {
      defaultMap = Collections.emptyMap();
    }
    Map<String, Object> result = new HashMap<String, Object>(defaultMap);
    for (String key : source.keySet()) {
      Object sourceValue = source.get(key);
      Object resultValue = result.get(key);
      if (resultValue instanceof Map || sourceValue instanceof Map) {
        @SuppressWarnings(value = "unchecked")
        Map<String, Object> subDefault = (Map<String, Object>) resultValue;

        @SuppressWarnings(value = "unchecked")
        Map<String, Object> subSource = (Map<String, Object>) sourceValue;

        result.put(key, merge(subSource, subDefault));
      } else {
        result.put(key, sourceValue);
      }
    }
    return result;
  }
 public void testNoParentNullFieldCreatedIfNoParentSpecified() throws Exception {
   Index index = new Index("_index", "testUUID");
   IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(index, Settings.EMPTY);
   NamedAnalyzer namedAnalyzer =
       new NamedAnalyzer("default", AnalyzerScope.INDEX, new StandardAnalyzer());
   IndexAnalyzers indexAnalyzers =
       new IndexAnalyzers(
           indexSettings, namedAnalyzer, namedAnalyzer, namedAnalyzer, Collections.emptyMap());
   SimilarityService similarityService =
       new SimilarityService(indexSettings, Collections.emptyMap());
   MapperService mapperService =
       new MapperService(
           indexSettings,
           indexAnalyzers,
           similarityService,
           new IndicesModule(emptyList()).getMapperRegistry(),
           () -> null);
   XContentBuilder mappingSource =
       jsonBuilder()
           .startObject()
           .startObject("some_type")
           .startObject("properties")
           .endObject()
           .endObject()
           .endObject();
   mapperService.merge(
       "some_type",
       new CompressedXContent(mappingSource.string()),
       MergeReason.MAPPING_UPDATE,
       false);
   Set<String> allFields = new HashSet<>(mapperService.simpleMatchToIndexNames("*"));
   assertTrue(allFields.contains("_parent"));
   assertFalse(allFields.contains("_parent#null"));
 }
Ejemplo n.º 23
0
  /**
   * Get user ratings from gcvote.com
   *
   * @param guids
   * @param geocodes
   * @return
   */
  @NonNull
  private static Map<String, GCVoteRating> getRating(
      final List<String> guids, final List<String> geocodes) {
    if (guids == null && geocodes == null) {
      return Collections.emptyMap();
    }

    final Parameters params = new Parameters("version", "cgeo");
    final ImmutablePair<String, String> login = Settings.getGCvoteLogin();
    if (login != null) {
      params.put("userName", login.left, "password", login.right);
    }

    // use guid or gccode for lookup
    final boolean requestByGuids = CollectionUtils.isNotEmpty(guids);
    if (requestByGuids) {
      params.put("cacheIds", StringUtils.join(guids, ','));
    } else {
      params.put("waypoints", StringUtils.join(geocodes, ','));
    }
    final InputStream response =
        Network.getResponseStream(Network.getRequest("http://gcvote.com/getVotes.php", params));
    if (response == null) {
      return Collections.emptyMap();
    }
    try {
      return getRatingsFromXMLResponse(response, requestByGuids);
    } finally {
      IOUtils.closeQuietly(response);
    }
  }
  public void testSelectNewPathForShard() throws Exception {
    assumeFalse(
        "Consistenty fails on windows ('could not remove the following files')", Constants.WINDOWS);
    Path path = PathUtils.get(createTempDir().toString());

    // Use 2 data paths:
    String[] paths = new String[] {path.resolve("a").toString(), path.resolve("b").toString()};

    Settings settings =
        Settings.builder().put("path.home", path).putArray("path.data", paths).build();
    NodeEnvironment nodeEnv = new NodeEnvironment(settings, new Environment(settings));

    // Make sure all our mocking above actually worked:
    NodePath[] nodePaths = nodeEnv.nodePaths();
    assertEquals(2, nodePaths.length);

    assertEquals("mocka", nodePaths[0].fileStore.name());
    assertEquals("mockb", nodePaths[1].fileStore.name());

    // Path a has lots of free space, but b has little, so new shard should go to a:
    aFileStore.usableSpace = 100000;
    bFileStore.usableSpace = 1000;

    ShardId shardId = new ShardId("index", 0);
    ShardPath result =
        ShardPath.selectNewPathForShard(
            nodeEnv, shardId, Settings.EMPTY, 100, Collections.<Path, Integer>emptyMap());
    assertTrue(result.getDataPath().toString().contains(aPathPart));

    // Test the reverse: b has lots of free space, but a has little, so new shard should go to b:
    aFileStore.usableSpace = 1000;
    bFileStore.usableSpace = 100000;

    shardId = new ShardId("index", 0);
    result =
        ShardPath.selectNewPathForShard(
            nodeEnv, shardId, Settings.EMPTY, 100, Collections.<Path, Integer>emptyMap());
    assertTrue(result.getDataPath().toString().contains(bPathPart));

    // Now a and be have equal usable space; we allocate two shards to the node, and each should go
    // to different paths:
    aFileStore.usableSpace = 100000;
    bFileStore.usableSpace = 100000;

    Map<Path, Integer> dataPathToShardCount = new HashMap<>();
    ShardPath result1 =
        ShardPath.selectNewPathForShard(
            nodeEnv, shardId, Settings.EMPTY, 100, dataPathToShardCount);
    dataPathToShardCount.put(NodeEnvironment.shardStatePathToDataPath(result1.getDataPath()), 1);
    ShardPath result2 =
        ShardPath.selectNewPathForShard(
            nodeEnv, shardId, Settings.EMPTY, 100, dataPathToShardCount);

    // #11122: this was the original failure: on a node with 2 disks that have nearly equal
    // free space, we would always allocate all N incoming shards to the one path that
    // had the most free space, never using the other drive unless new shards arrive
    // after the first shards started using storage:
    assertNotEquals(result1.getDataPath(), result2.getDataPath());
  }
Ejemplo n.º 25
0
  @NewEnv(type = NewEnv.Type.NONE)
  @Test
  public void testGetFilesEmptyMap() throws Exception {
    NoticeableFuture<Map<Path, Path>> noticeableFuture =
        _nettyRepository.getFiles(_embeddedChannel, Collections.<Path, Path>emptyMap(), true);

    Assert.assertSame(Collections.<Path, Path>emptyMap(), noticeableFuture.get());
  }
Ejemplo n.º 26
0
 public PortManager() {
   this.lock = new ReentrantReadWriteLock();
   this.portList = Collections.emptyList();
   this.enabledPortList = Collections.emptyList();
   this.enabledPortNumbers = Collections.emptyList();
   this.portsByName = Collections.emptyMap();
   this.portsByNumber = Collections.emptyMap();
 }
Ejemplo n.º 27
0
 @Check
 public void checkDuplicateFeatureName(final MobaEntity dto) {
   Map<String, MobaEntityFeature> _xifexpression = null;
   MobaEntity _superType = dto.getSuperType();
   boolean _notEquals = (!Objects.equal(_superType, null));
   if (_notEquals) {
     Map<String, MobaEntityFeature> _xtrycatchfinallyexpression = null;
     try {
       MobaEntity _superType_1 = dto.getSuperType();
       List<MobaEntityFeature> _allFeatures = _superType_1.getAllFeatures();
       final Function1<MobaEntityFeature, String> _function =
           (MobaEntityFeature it) -> {
             return it.getName();
           };
       _xtrycatchfinallyexpression =
           IterableExtensions.<String, MobaEntityFeature>toMap(_allFeatures, _function);
     } catch (final Throwable _t) {
       if (_t instanceof RecursionException) {
         final RecursionException ex = (RecursionException) _t;
         _xtrycatchfinallyexpression = Collections.<String, MobaEntityFeature>emptyMap();
       } else {
         throw Exceptions.sneakyThrow(_t);
       }
     }
     _xifexpression = _xtrycatchfinallyexpression;
   } else {
     _xifexpression = Collections.<String, MobaEntityFeature>emptyMap();
   }
   final Map<String, MobaEntityFeature> superFeatureMap = _xifexpression;
   final Set<String> currentFeatures = CollectionLiterals.<String>newHashSet();
   int index = 0;
   EList<MobaEntityFeature> _features = dto.getFeatures();
   for (final MobaEntityFeature feature : _features) {
     {
       String _name = feature.getName();
       boolean _containsKey = superFeatureMap.containsKey(_name);
       if (_containsKey) {
         this.error(
             "Supertype contains same feature name",
             dto,
             MobaPackage.Literals.MOBA_ENTITY__FEATURES,
             index);
       }
       String _name_1 = feature.getName();
       boolean _contains = currentFeatures.contains(_name_1);
       if (_contains) {
         this.error(
             "Feature name must be unique",
             dto,
             MobaPackage.Literals.MOBA_ENTITY__FEATURES,
             index);
       }
       String _name_2 = feature.getName();
       currentFeatures.add(_name_2);
       index++;
     }
   }
 }
Ejemplo n.º 28
0
  /**
   * Creates a new definition with the provided information.
   *
   * <p>If no <code>primaryName</code> is specified, but a set of <code>names</code> is specified,
   * then the first name retrieved from the set of <code>names</code> will be used as the primary
   * name.
   *
   * @param primaryName The primary name for this definition, or <code>null</code> if there is no
   *     primary name.
   * @param names The full set of names for this definition, or <code>null</code> if there are no
   *     names.
   * @param oid The OID for this definition (must not be <code>null</code>).
   * @param description The description for the definition, or <code>null</code> if there is no
   *     description.
   * @param isObsolete Indicates whether this definition is declared "obsolete".
   * @param extraProperties A set of extra properties for this definition, or <code>null</code> if
   *     there are no extra properties.
   * @throws NullPointerException If the provided OID was <code>null</code>.
   */
  protected CommonSchemaElements(
      String primaryName,
      Collection<String> names,
      String oid,
      String description,
      boolean isObsolete,
      Map<String, List<String>> extraProperties)
      throws NullPointerException {

    // Make sure mandatory parameters are specified.
    if (oid == null) {
      throw new NullPointerException("No oid specified in constructor");
    }

    this.oid = oid;
    this.description = description;
    this.isObsolete = isObsolete;

    // Make sure we have a primary name if possible.
    if (primaryName == null) {
      if (names != null && !names.isEmpty()) {
        this.primaryName = names.iterator().next();
      } else {
        this.primaryName = null;
      }
    } else {
      this.primaryName = primaryName;
    }
    this.lowerName = toLowerCase(primaryName);

    // OPENDJ-1645: oid changes during server bootstrap, so prefer using name if available
    hashCode = getNameOrOID().hashCode();

    // Construct the normalized attribute name mapping.
    if (names != null) {
      this.names = new LinkedHashMap<>(names.size());

      // Make sure the primary name is first (never null).
      this.names.put(lowerName, this.primaryName);

      // Add the remaining names in the order specified.
      for (String name : names) {
        this.names.put(toLowerCase(name), name);
      }
    } else if (this.primaryName != null) {
      this.names = Collections.singletonMap(lowerName, this.primaryName);
    } else {
      this.names = Collections.emptyMap();
    }

    // FIXME: should really be a deep-copy.
    if (extraProperties != null) {
      this.extraProperties = new LinkedHashMap<>(extraProperties);
    } else {
      this.extraProperties = Collections.emptyMap();
    }
  }
Ejemplo n.º 29
0
 private void resolveService(ServiceModule service, ServiceModule parent) throws AmbariException {
   service.resolve(
       parent,
       Collections.<String, StackModule>emptyMap(),
       Collections.<String, ServiceModule>emptyMap());
   // during runtime this would be called by the Stack module when it's resolve completed
   service.finalizeModule();
   parent.finalizeModule();
 }
Ejemplo n.º 30
0
/**
 * DTO for the content of a single PM.
 *
 * @author olaf boede
 */
public class PmContentContainer implements Serializable {
  private static final long serialVersionUID = 1L;

  /** The path of the PM that sends/receives the content. */
  private String pmPath;

  /** Stores {@link PmAspect}s like value, title etc. */
  private Map<PmAspect, Serializable> aspectMap = Collections.emptyMap();

  /**
   * Stores content of named objects. The attributes and named sub-elements are usually stored here.
   */
  private Map<String, PmContentContainer> namedChildContentMap = Collections.emptyMap();

  public void addAspect(PmAspect aspect, Serializable value) {
    if (aspectMap.size() == 0) {
      aspectMap = new HashMap<PmAspect, Serializable>();
    }
    aspectMap.put(aspect, value);
  }

  public Serializable getAspect(PmAspect aspect) {
    return aspectMap.get(aspect);
  }

  public PmContentContainer addNamedChildContent(String childName) {
    if (namedChildContentMap.size() == 0) {
      namedChildContentMap = new HashMap<String, PmContentContainer>();
    }
    PmContentContainer c = new PmContentContainer();
    namedChildContentMap.put(childName, c);
    return c;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append(aspectMap.toString());
    return sb.toString();
  }

  public Map<PmAspect, Serializable> getAspectMap() {
    return aspectMap;
  }

  public Map<String, PmContentContainer> getNamedChildContentMap() {
    return namedChildContentMap;
  }

  public String getPmPath() {
    return pmPath;
  }

  public void setPmPath(String pmPath) {
    this.pmPath = pmPath;
  }
}