java.util.Collections Java Examples

The following examples show how to use java.util.Collections. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: redisson   Author: redisson   File: StreamObjectMapReplayDecoder.java    License: Apache License 2.0 8 votes vote down vote up
@Override
public Map<Object, Object> decode(List<Object> parts, State state) {
    if (parts.get(0) == null
            || (parts.get(0) instanceof List && ((List) parts.get(0)).isEmpty())) {
        parts.clear();
        return Collections.emptyMap();
    }

    if (parts.get(0) instanceof Map) {
        Map<Object, Object> result = new LinkedHashMap<Object, Object>(parts.size());
        for (int i = 0; i < parts.size(); i++) {
            result.putAll((Map<? extends Object, ? extends Object>) parts.get(i));
        }
        return result;
    }
    return super.decode(parts, state);
}
 
Example #2
Source Project: cover-checker   Author: naver   File: GithubDiffReader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RawDiff next() {
	CommitFile file = files.next();
	log.info("get file {}", file.getFilename());
	List<String> lines;
	if (file.getPatch() != null && file.getPatch().length() > 0) {
		lines = Arrays.asList(file.getPatch().split("\r?\n"));
	} else {
		lines = Collections.emptyList();
	}
	return RawDiff.builder()
			.fileName(file.getFilename())
			.rawDiff(lines)
			.type(file.getPatch() != null ? FileType.SOURCE : FileType.BINARY)
			.build();
}
 
Example #3
Source Project: validatar   Author: yahoo   File: FormatManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteReportOnlyOnFailureForFailingQueriesAndTests() throws IOException {
    String[] args = {"--report-on-failure-only", "true"};
    MockFormatter formatter = new MockFormatter();
    FormatManager manager = new FormatManager(args);
    manager.setAvailableFormatters(Collections.singletonMap("MockFormat", formatter));
    manager.setFormattersToUse(new ArrayList<>());
    manager.setupFormatter("MockFormat", args);
    TestSuite suite = new TestSuite();

    Assert.assertFalse(formatter.wroteReport);

    com.yahoo.validatar.common.Test failingTest = new com.yahoo.validatar.common.Test();
    failingTest.setFailed();
    Query failingQuery = new Query();
    failingQuery.setFailed();
    suite.queries = Collections.singletonList(failingQuery);
    suite.tests = Collections.singletonList(failingTest);
    manager.writeReports(Collections.singletonList(suite));
    Assert.assertTrue(formatter.wroteReport);
}
 
Example #4
Source Project: titus-control-plane   Author: Netflix   File: ClusterAgentAutoScalerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testScaleUpMinIdle() {
    AgentInstanceGroup instanceGroup = createPartition("instanceGroup1", InstanceGroupLifecycleState.Active, "r4.16xlarge", 0, 0, 10);
    when(agentManagementService.getInstanceGroups()).thenReturn(singletonList(instanceGroup));

    when(agentManagementService.getAgentInstances("instanceGroup1")).thenReturn(Collections.emptyList());
    when(agentManagementService.scaleUp(eq("instanceGroup1"), anyInt())).thenReturn(Completable.complete());

    testScheduler.advanceTimeBy(6, TimeUnit.MINUTES);

    ClusterAgentAutoScaler clusterAgentAutoScaler = new ClusterAgentAutoScaler(titusRuntime, configuration,
            agentManagementService, v3JobOperations, schedulingService, testScheduler);

    clusterAgentAutoScaler.doAgentScaling().await();

    verify(agentManagementService).scaleUp("instanceGroup1", 5);
}
 
Example #5
Source Project: java-metrics   Author: opentracing-contrib   File: MicrometerMetricsReporterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testReportSpan() {
    // prepare
    SpanData spanData = defaultMockSpanData();
    when(spanData.getTags()).thenReturn(Collections.singletonMap(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT));

    MicrometerMetricsReporter reporter = MicrometerMetricsReporter.newMetricsReporter()
            .withConstLabel("span.kind", Tags.SPAN_KIND_CLIENT)
            .build();

    // test
    reporter.reportSpan(spanData);

    // verify
    List<Tag> tags = defaultTags();

    assertEquals(100, (long) registry.find("span").timer().totalTime(TimeUnit.MILLISECONDS));
    assertEquals(1, Metrics.timer("span", tags).count());
}
 
Example #6
Source Project: netbeans   Author: apache   File: CompositeComponentWizardIterator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Set<DataObject> instantiate(TemplateWizard wiz) throws IOException {
    DataObject result = null;
    String targetName = Templates.getTargetName(wizard);
    FileObject targetDir = Templates.getTargetFolder(wizard);
    DataFolder df = DataFolder.findFolder(targetDir);

    FileObject template = Templates.getTemplate( wizard );
    DataObject dTemplate = DataObject.find(template);
    HashMap<String, Object> templateProperties = new HashMap<String, Object>();
    if (selectedText != null) {
        templateProperties.put("implementation", selectedText);   //NOI18N
    }
    Project project = Templates.getProject(wizard);
    WebModule webModule = WebModule.getWebModule(project.getProjectDirectory());
    if (webModule != null) {
        JSFVersion version = JSFVersion.forWebModule(webModule);
        if (version != null && version.isAtLeast(JSFVersion.JSF_2_2)) {
            templateProperties.put("isJSF22", Boolean.TRUE); //NOI18N
        }
    }

    result  = dTemplate.createFromTemplate(df,targetName,templateProperties);
    return Collections.singleton(result);
}
 
Example #7
Source Project: gocd   Author: gocd   File: RulesServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void shouldErrorOutWhenMaterialIsReferringToNoneExistingSecretConfig() {
    GitMaterial gitMaterial = new GitMaterial("http://example.com");
    gitMaterial.setPassword("{{SECRET:[secret_config_id][password]}}");

    PipelineConfig up42 = PipelineConfigMother.pipelineConfig("up42", new MaterialConfigs(gitMaterial.config()));
    PipelineConfigs defaultGroup = PipelineConfigMother.createGroup("default", up42);
    CruiseConfig cruiseConfig = defaultCruiseConfig();
    cruiseConfig.setGroup(new PipelineGroups(defaultGroup));

    when(goConfigService.cruiseConfig()).thenReturn(cruiseConfig);
    when(goConfigService.pipelinesWithMaterial(gitMaterial.getFingerprint())).thenReturn(Collections.singletonList(new CaseInsensitiveString("up42")));
    when(goConfigService.findGroupByPipeline(new CaseInsensitiveString("up42"))).thenReturn(defaultGroup);
    when(goConfigService.findPipelineByName(new CaseInsensitiveString("up42"))).thenReturn(up42);

    assertThatCode(() -> rulesService.validateSecretConfigReferences(gitMaterial))
            .isInstanceOf(RulesViolationException.class)
            .hasMessage("Pipeline 'up42' is referring to none-existent secret config 'secret_config_id'.");
}
 
Example #8
Source Project: ditto   Author: eclipse   File: StatusInfoTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void compositeReturnsStatusUpWhenAllChildrenAreUp() {
    final Map<String, StatusInfo> childrenMap = new LinkedHashMap<>();
    final String upChild1Label = "up-child-1-label";
    childrenMap.put(upChild1Label, KNOWN_UP_STATUS_INFO_WITH_WARN_MSG);
    final String upChild2Label = "up-child-2-label";
    childrenMap.put(upChild2Label, KNOWN_UP_STATUS_INFO_WITH_WARN_MSG);

    final StatusInfo actual = StatusInfo.composite(childrenMap);

    final List<StatusDetailMessage> expectedDetails = Collections.singletonList(
            (createExpectedCompositeDetailMessage(KNOWN_MESSAGE_WARN.getLevel(),
                    Arrays.asList(upChild1Label, upChild2Label))));
    final List<StatusInfo> expectedLabeledChildren =
            Arrays.asList(KNOWN_UP_STATUS_INFO_WITH_WARN_MSG.label(upChild1Label),
                    KNOWN_UP_STATUS_INFO_WITH_WARN_MSG.label(upChild2Label));
    final StatusInfo expected =
            StatusInfo.of(StatusInfo.Status.UP, expectedDetails, expectedLabeledChildren, null);
    assertThat(actual).isEqualTo(expected);
    assertThat(actual.isComposite()).isTrue();
}
 
Example #9
Source Project: desugar_jdk_libs   Author: google   File: DateTimeTextProvider.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param valueTextMap  the map of values to text to store, assigned and not altered, not null
 */
LocaleStore(Map<TextStyle, Map<Long, String>> valueTextMap) {
    this.valueTextMap = valueTextMap;
    Map<TextStyle, List<Entry<String, Long>>> map = new HashMap<>();
    List<Entry<String, Long>> allList = new ArrayList<>();
    for (Map.Entry<TextStyle, Map<Long, String>> vtmEntry : valueTextMap.entrySet()) {
        Map<String, Entry<String, Long>> reverse = new HashMap<>();
        for (Map.Entry<Long, String> entry : vtmEntry.getValue().entrySet()) {
            if (reverse.put(entry.getValue(), createEntry(entry.getValue(), entry.getKey())) != null) {
                // TODO: BUG: this has no effect
                continue;  // not parsable, try next style
            }
        }
        List<Entry<String, Long>> list = new ArrayList<>(reverse.values());
        Collections.sort(list, COMPARATOR);
        map.put(vtmEntry.getKey(), list);
        allList.addAll(list);
        map.put(null, allList);
    }
    Collections.sort(allList, COMPARATOR);
    this.parsable = map;
}
 
Example #10
Source Project: jaxb2-maven-plugin   Author: mojohaus   File: FileSystemUtilitiesTest.java    License: Apache License 2.0 6 votes vote down vote up
private List<String> getRelativeCanonicalPaths( final List<File> fileList, final File cutoff )
{

    final String cutoffPath = FileSystemUtilities.getCanonicalPath( cutoff ).replace( File.separator, "/" );
    final List<String> toReturn = new ArrayList<String>();

    for ( File current : fileList )
    {

        final String canPath = FileSystemUtilities.getCanonicalPath( current ).replace( File.separator, "/" );
        if ( !canPath.startsWith( cutoffPath ) )
        {
            throw new IllegalArgumentException(
                    "Illegal cutoff provided. Cutoff: [" + cutoffPath + "] must be a parent to CanonicalPath [" + canPath + "]" );
        }

        toReturn.add( canPath.substring( cutoffPath.length() ) );
    }
    Collections.sort( toReturn );

    return toReturn;
}
 
Example #11
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: ConcurrentHashMapTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Elements of classes with erased generic type parameters based
 * on Comparable can be inserted and found.
 */
public void testGenericComparable() {
    int size = 120;         // makes measured test run time -> 60ms
    ConcurrentHashMap<Object, Boolean> m =
        new ConcurrentHashMap<Object, Boolean>();
    for (int i = 0; i < size; i++) {
        BI bi = new BI(i);
        BS bs = new BS(String.valueOf(i));
        LexicographicList<BI> bis = new LexicographicList<BI>(bi);
        LexicographicList<BS> bss = new LexicographicList<BS>(bs);
        assertTrue(m.putIfAbsent(bis, true) == null);
        assertTrue(m.containsKey(bis));
        if (m.putIfAbsent(bss, true) == null)
            assertTrue(m.containsKey(bss));
        assertTrue(m.containsKey(bis));
    }
    for (int i = 0; i < size; i++) {
        assertTrue(m.containsKey(Collections.singletonList(new BI(i))));
    }
}
 
Example #12
Source Project: cryptotrader   Author: after-the-sunrise   File: FiscoDepth.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@VisibleForTesting
NavigableMap<BigDecimal, BigDecimal> convert(BigDecimal[][] values, Comparator<BigDecimal> comparator) {

    if (values == null) {
        return null;
    }

    NavigableMap<BigDecimal, BigDecimal> map = new TreeMap<>(comparator);

    Stream.of(values)
            .filter(ArrayUtils::isNotEmpty)
            .filter(ps -> ps.length == 2)
            .filter(ps -> ps[0] != null)
            .filter(ps -> ps[1] != null)
            .forEach(ps -> map.put(ps[0], ps[1]))
    ;

    return Collections.unmodifiableNavigableMap(map);

}
 
Example #13
Source Project: MtgDesktopCompanion   Author: nicho92   File: PackagesProvider.java    License: GNU General Public License v3.0 6 votes vote down vote up
public List<MagicEdition> listEditions() {

		if (!list.isEmpty())
			return list;

		try {
			XPath xPath = XPathFactory.newInstance().newXPath();
			String expression = "//edition/@id";
			NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
			for (int i = 0; i < nodeList.getLength(); i++)
			{
				list.add(MTGControler.getInstance().getEnabled(MTGCardsProvider.class).getSetById(nodeList.item(i).getNodeValue()));
			}
			
			Collections.sort(list);
		} catch (Exception e) {
			logger.error("Error retrieving IDs ", e);
		}
		return list;
	}
 
Example #14
Source Project: james-project   Author: apache   File: DefaultStager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param stage the annotation that specifies this stage
 * @param mode  execution order
 */
public DefaultStager(Class<A> stage, Order mode) {
    this.stage = stage;

    Queue<Stageable> localStageables;
    switch (mode) {
        case FIRST_IN_FIRST_OUT: {
            localStageables = new ArrayDeque<>();
            break;
        }

        case FIRST_IN_LAST_OUT: {
            localStageables = Collections.asLifoQueue(new ArrayDeque<>());
            break;
        }

        default: {
            throw new IllegalArgumentException("Unknown mode: " + mode);
        }
    }
    stageables = localStageables;
}
 
Example #15
Source Project: spectator   Author: Netflix   File: EvaluatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void updateSub() {

  // Eval with sum
  List<Subscription> sumSub = new ArrayList<>();
  sumSub.add(newSubscription("sum", ":true,:sum"));
  Evaluator evaluator = newEvaluator();
  evaluator.sync(sumSub);
  EvalPayload payload = evaluator.eval(0L, data("foo", 1.0, 2.0, 3.0));
  List<EvalPayload.Metric> metrics = new ArrayList<>();
  metrics.add(new EvalPayload.Metric("sum", Collections.emptyMap(), 6.0));
  EvalPayload expected = new EvalPayload(0L, metrics);
  Assertions.assertEquals(expected, payload);

  // Update to use max instead
  List<Subscription> maxSub = new ArrayList<>();
  maxSub.add(newSubscription("sum", ":true,:max"));
  evaluator.sync(maxSub);
  payload = evaluator.eval(0L, data("foo", 1.0, 2.0, 3.0));
  metrics = new ArrayList<>();
  metrics.add(new EvalPayload.Metric("sum", Collections.emptyMap(), 3.0));
  expected = new EvalPayload(0L, metrics);
  Assertions.assertEquals(expected, payload);
}
 
Example #16
Source Project: development   Author: servicecatalog   File: OperatorServiceBeanWithDataServiceIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void addAvailablePaymentTypes_FindsExistingEntry() throws Exception {
    OrganizationReference createdOrgRef = runTX(new Callable<OrganizationReference>() {
        @Override
        public OrganizationReference call() throws Exception {
            OrganizationReference orgRef = new OrganizationReference(
                    platformOp, supplier,
                    OrganizationReferenceType.PLATFORM_OPERATOR_TO_SUPPLIER);
            dataService.persist(orgRef);
            dataService.flush();
            return orgRef;
        }
    });
    operatorService
            .addAvailablePaymentTypes(OrganizationAssembler
                    .toVOOrganization(supplier, false, new LocalizerFacade(
                            localizer, "en")), Collections
                    .singleton("CREDIT_CARD"));
    validate(createdOrgRef, true);
}
 
Example #17
Source Project: ignite   Author: apache   File: GridClientImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Maps Collection of strings to collection of {@code InetSocketAddress}es.
 *
 * @param cfgAddrs Collection fo string representations of addresses.
 * @return Collection of {@code InetSocketAddress}es
 * @throws GridClientException In case of error.
 */
private static Collection<InetSocketAddress> parseAddresses(Collection<String> cfgAddrs)
    throws GridClientException {
    Collection<InetSocketAddress> addrs = new ArrayList<>(cfgAddrs.size());

    for (String srvStr : cfgAddrs) {
        try {
            String[] split = srvStr.split(":");

            InetSocketAddress addr = new InetSocketAddress(split[0], Integer.parseInt(split[1]));

            addrs.add(addr);
        }
        catch (RuntimeException e) {
            throw new GridClientException("Failed to create client (invalid server address specified): " +
                srvStr, e);
        }
    }

    return Collections.unmodifiableCollection(addrs);
}
 
Example #18
Source Project: development   Author: servicecatalog   File: DatabaseUpgradeHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Determines the files that have to be executed (according to the provided
 * version information) and orders them in ascending order.
 * 
 * @param fileList
 *            The list of files to be investigated. The names must have
 *            passed the test in method
 *            {@link #getScriptFilesFromDirectory(String, String)}.
 * @return The files to be executed in the execution order.
 */
protected List<File> getFileExecutionOrder(List<File> fileList,
        DatabaseVersionInfo currentVersion, DatabaseVersionInfo toVersion) {
    List<File> result = new ArrayList<File>();
    // if the file contains statements for a newer schema, add the file to
    // the list
    for (File file : fileList) {
        DatabaseVersionInfo info = determineVersionInfoForFile(file);
        if (info.compareTo(currentVersion) > 0
                && info.compareTo(toVersion) <= 0) {
            result.add(file);
        }
    }
    // now sort the list ascending
    Collections.sort(result);

    return result;
}
 
Example #19
Source Project: jmxtrans-agent   Author: jmxtrans   File: JmxTransConfigurationXmlLoader.java    License: MIT License 5 votes vote down vote up
private List<String> getAttributes(Element queryElement, String objectName) {
    String attribute = queryElement.getAttribute("attribute");
    String attributes = queryElement.getAttribute("attributes");
    validateOnlyAttributeOrAttributesSpecified(attribute, attributes, objectName);
    if (attribute.isEmpty() && attributes.isEmpty()) {
        return Collections.emptyList();
    }
    if (!attribute.isEmpty()) {
        return Collections.singletonList(attribute);
    } else {
        String[] splitAttributes = ATTRIBUTE_SPLIT_PATTERN.split(attributes);
        return Arrays.asList(splitAttributes);
    }
}
 
Example #20
Source Project: dal   Author: ctripcorp   File: EntityManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGrandParentColumnNames() {
    try {
        String[] columnNames = getAllColumnNames(grandParentClass);
        List<String> actualColumnNames = Arrays.asList(columnNames);
        Collections.sort(actualColumnNames);

        List<String> expectedColumnNames = getExpectedColumnNamesOfGrandParent();
        Collections.sort(expectedColumnNames);

        Assert.assertEquals(actualColumnNames, expectedColumnNames);
    } catch (Exception e) {
        Assert.fail();
    }
}
 
Example #21
Source Project: java-stellar-sdk   Author: stellar   File: Transaction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new transaction builder.
 * @param sourceAccount The source account for this transaction. This account is the account
 * who will use a sequence number. When build() is called, the account object's sequence number
 * will be incremented.
 */
public Builder(TransactionBuilderAccount sourceAccount, Network network) {
  checkNotNull(sourceAccount, "sourceAccount cannot be null");
  mSourceAccount = sourceAccount;
  mOperations = Collections.synchronizedList(new ArrayList<Operation>());
  mNetwork = checkNotNull(network, "Network cannot be null");
}
 
Example #22
Source Project: gama   Author: gama-platform   File: ExperimentAgent.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return
 */
public Iterable<IOutputManager> getAllSimulationOutputs() {
	final SimulationPopulation pop = getSimulationPopulation();
	if (pop != null) {
		return Iterables.filter(Iterables.concat(Iterables.transform(pop, each -> each.getOutputManager()),
				Collections.singletonList(getOutputManager())), each -> each != null);
	}
	return Collections.EMPTY_LIST;
}
 
Example #23
Source Project: Jockey   Author: marverenic   File: ListTransactionTest.java    License: Apache License 2.0 5 votes vote down vote up
private List<String> generateLongList(int itemCount) {
    List<String> list = new ArrayList<>(itemCount);
    for (int i = 0; i < itemCount; i++) {
        list.add(Integer.toString(i));
    }

    return Collections.unmodifiableList(list);
}
 
Example #24
Source Project: android-oauth-client   Author: wuman   File: CompatUri.java    License: Apache License 2.0 5 votes vote down vote up
static Set<String> getQueryParameterNames(Uri uri) {
    if (uri.isOpaque()) {
        throw new UnsupportedOperationException(NOT_HIERARCHICAL);
    }

    String query = uri.getEncodedQuery();
    if (query == null) {
        return Collections.emptySet();
    }

    Set<String> names = new LinkedHashSet<String>();
    int start = 0;
    do {
        int next = query.indexOf('&', start);
        int end = (next == -1) ? query.length() : next;

        int separator = query.indexOf('=', start);
        if (separator > end || separator == -1) {
            separator = end;
        }

        String name = query.substring(start, separator);
        names.add(Uri.decode(name));

        // Move start to end of name
        start = end + 1;
    } while (start < query.length());

    return Collections.unmodifiableSet(names);
}
 
Example #25
Source Project: gemfirexd-oss   Author: gemxd   File: DiskStoreCommands.java    License: Apache License 2.0 5 votes vote down vote up
protected DiskStoreDetails getDiskStoreDescription(final String memberName, final String diskStoreName) {
  final DistributedMember member = getMember(getCache(), memberName); // may throw a MemberNotFoundException

  final ResultCollector<?, ?> resultCollector = getMembersFunctionExecutor(Collections.singleton(member))
    .withArgs(diskStoreName).execute(new DescribeDiskStoreFunction());

  final Object result = ((List<?>) resultCollector.getResult()).get(0);

  if (result instanceof DiskStoreDetails) { // disk store details in hand...
    return (DiskStoreDetails) result;
  }
  else if (result instanceof DiskStoreNotFoundException) { // bad disk store name...
    throw (DiskStoreNotFoundException) result;
  }
  else { // unknown and unexpected return type...
    final Throwable cause = (result instanceof Throwable ? (Throwable) result : null);

    if (isLogging()) {
      if (cause != null) {
        getGfsh().logSevere(String.format(
          "Exception (%1$s) occurred while executing '%2$s' on member (%3$s) with disk store (%4$s).",
            ClassUtils.getClassName(cause), CliStrings.DESCRIBE_DISK_STORE, memberName, diskStoreName), cause);
      }
      else {
        getGfsh().logSevere(String.format(
          "Received an unexpected result of type (%1$s) while executing '%2$s' on member (%3$s) with disk store (%4$s).",
            ClassUtils.getClassName(result), CliStrings.DESCRIBE_DISK_STORE, memberName, diskStoreName), null);
      }
    }

    throw new RuntimeException(CliStrings.format(CliStrings.UNEXPECTED_RETURN_TYPE_EXECUTING_COMMAND_ERROR_MESSAGE,
      ClassUtils.getClassName(result), CliStrings.DESCRIBE_DISK_STORE), cause);
  }
}
 
Example #26
Source Project: carbon-commons   Author: wso2   File: CarbonEventingMessageReceiver.java    License: Apache License 2.0 5 votes vote down vote up
public List<Subscription> sortResults(String sortingInstructions, final boolean ascending, List<Subscription> list) {
    if (sortingInstructions != null) {
        Comparator<Subscription> comparator = null;

        if (sortingInstructions.equals("eventSinkAddress")) {
            comparator = new Comparator<Subscription>() {
                public int compare(Subscription o1, Subscription o2) {
                    if (o2 == null || o1 == null) {
                        return 0;
                    }
                    return (ascending ? 1 : -1) * o1.getEventSinkURL().compareTo(o2.getEventSinkURL());
                }
            };
        } else if (sortingInstructions.equals("createdTime")) {
            comparator = new Comparator<Subscription>() {
                public int compare(Subscription o1, Subscription o2) {
                    if (o2 == null || o1 == null) {
                        return 0;
                    }
                    return (ascending ? 1 : -1) * o1.getCreatedTime().compareTo(o2.getCreatedTime());
                }
            };
        } else if (sortingInstructions.equals("subscriptionEndingTime")) {
            comparator = new Comparator<Subscription>() {
                public int compare(Subscription o1, Subscription o2) {
                    if (o2 == null || o1 == null) {
                        return 0;
                    }
                    return (ascending ? 1 : -1) * o1.getExpires().compareTo(o2.getExpires());
                }
            };

        }
        if (comparator != null) {
            Collections.sort(list, comparator);
        }
    }
    return list;
}
 
Example #27
Source Project: Llunatic   Author: donatellosantoro   File: FindAttributesWithLabeledNulls.java    License: GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Set<AttributeRef> findAttributes(DirectedGraph<AttributeRef, ExtendedEdge> dependencyGraph, Scenario scenario) {
    if (dependencyGraph == null) {
        return Collections.EMPTY_SET;
    }
    if (logger.isDebugEnabled()) logger.debug("Finding attributes with null in dependency graph\n" + dependencyGraph);
    Set<AttributeRef> initialAttributes = findInitialAttributes(scenario);
    if (logger.isDebugEnabled()) logger.debug("Initial attributes with nulls: " + initialAttributes);
    Set<AttributeRef> result = findReachableAttribuesOnGraph(initialAttributes, dependencyGraph);
    if (logger.isDebugEnabled()) logger.debug("Attributes with nulls: " + result);
    return result;
}
 
Example #28
Source Project: PerWorldInventory   Author: EbonJaeger   File: PlayerSpawnLocationListenerTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void shouldProcessChange() {
    // given
    Player player = mock(Player.class);
    World world = mock(World.class);
    given(world.getName()).willReturn("world");

    Set<String> worlds = new HashSet<>();
    Group spawnWorldGroup = mockGroup("spawn", Arrays.asList("otherWorld", world.getName()), GameMode.SURVIVAL);

    given(groupManager.getGroupFromWorld(world.getName())).willReturn(spawnWorldGroup);

    Location spawnLocation = new Location(world, 1, 2, 3);
    PlayerSpawnLocationEvent event = new PlayerSpawnLocationEvent(player, spawnLocation);
    given(settings.getProperty(PwiProperties.LOAD_DATA_ON_JOIN)).willReturn(true);

    World oldWorld = mock(World.class);
    given(oldWorld.getName()).willReturn("other_world");
    Location lastLocation = new Location(oldWorld, 4, 5, 6);
    given(dataSource.getLogoutData(player)).willReturn(lastLocation);
    Group oldWorldGroup = mockGroup("oldWorldGroup", Collections.singletonList(oldWorld.getName()), GameMode.SURVIVAL);
    given(groupManager.getGroupFromWorld(oldWorld.getName())).willReturn(oldWorldGroup);

    // when
    listener.onPlayerSpawn(event);

    // then
    verify(process, only()).processWorldChangeOnSpawn(player, oldWorldGroup, spawnWorldGroup);
}
 
Example #29
Source Project: ignite   Author: apache   File: JdbcThinDatabaseMetadata.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public ResultSet getFunctions(String catalog, String schemaPtrn,
    String functionNamePtrn) throws SQLException {
    // TODO: IGNITE-6028
    return new JdbcThinResultSet(Collections.<List<Object>>emptyList(), asList(
        new JdbcColumnMeta(null, null, "FUNCTION_CAT", String.class),
        new JdbcColumnMeta(null, null, "FUNCTION_SCHEM", String.class),
        new JdbcColumnMeta(null, null, "FUNCTION_NAME", String.class),
        new JdbcColumnMeta(null, null, "REMARKS", String.class),
        new JdbcColumnMeta(null, null, "FUNCTION_TYPE", String.class),
        new JdbcColumnMeta(null, null, "SPECIFIC_NAME", String.class)
    ));
}
 
Example #30
Source Project: Telegram-FOSS   Author: Telegram-FOSS-Team   File: SimpleExoPlayer.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void stop(boolean reset) {
  verifyApplicationThread();
  player.stop(reset);
  if (mediaSource != null) {
    mediaSource.removeEventListener(analyticsCollector);
    analyticsCollector.resetForNewMediaSource();
    if (reset) {
      mediaSource = null;
    }
  }
  audioFocusManager.handleStop();
  currentCues = Collections.emptyList();
}