javatips.net counter

Java Examples for java.util.Set

The following java examples will help you to understand the usage of java.util.Set. These source code samples are taken from different open source projects.

Example 1
Project: liferay-ide-master  File: PublicRenderParameterValuesService.java View source code
/*
     * (non-Javadoc)
     * @see org.eclipse.sapphire.modeling.PossibleValuesService#fillPossibleValues(java.util.SortedSet)
     */
@Override
protected void compute(Set<String> values) {
    final PortletApp portletApp = context(PortletApp.class);
    ElementList<PublicRenderParameter> publicRenderParameters = portletApp.getPublicRenderParameters();
    for (PublicRenderParameter renderParameter : publicRenderParameters) {
        final String indentifer = renderParameter.getIdentifier().content();
        values.add(indentifer);
    }
}
Example 2
Project: turmeric-eclipse-master  File: TestSetUtil.java View source code
/**
	 * Test method for [email protected] [email protected]SetUtil#add(java.util.Set, T[])}.
	 */
@Test
public void testAdd() {
    Set<String> collection = new HashSet<String>();
    collection.add("3dfx");
    collection.add("Nvidia");
    collection.add("ATI");
    Assert.assertNull(SetUtil.add(null));
    String[] data = null;
    Assert.assertNotNull(SetUtil.add(collection, data));
    Assert.assertNotNull(SetUtil.add(collection));
    Assert.assertSame(collection, SetUtil.add(collection));
    String item = "S3";
    collection.add(item);
    Set<String> list = SetUtil.add(collection, item);
    assertSetEquals(collection, list);
}
Example 3
Project: google-web-toolkit-svnmirror-master  File: ExtractClassNamesVisitorTest.java View source code
public void testImportedClasses() throws UnableToCompleteException {
    ExtractClassNamesVisitor v = new ExtractClassNamesVisitor(new TreeSet<String>(Arrays.asList("blah-selector-", "prefixed-", "postfixed-")));
    test(TreeLogger.NULL, "extractClassNames", false, v);
    Set<String> expected = new TreeSet<String>(Arrays.asList("selector1", "selector2", "selector3", "external1", "external2", "external3", "selector_with_underscores", "-selector-with-hyphen"));
    Set<String> actual = new TreeSet<String>(v.getFoundClasses());
    assertEquals(expected, actual);
}
Example 4
Project: expenditures-master  File: TopLevelMissionItemTypeProvider.java View source code
public final Collection<Class> getAvailableTopLevelMissionItemTypes() {
    final Set<Class> missionItemTypes = new TreeSet<Class>(CLASS_COMPARATOR_BY_NAME);
    final DomainModel domainModel = FenixFramework.getDomainModel();
    for (final DomainClass domainClass : domainModel.getDomainClasses()) {
        if (isMissionItemDirectSubclass(domainClass)) {
            try {
                final Class clazz = Class.forName(domainClass.getFullName());
                missionItemTypes.add(clazz);
            } catch (final ClassNotFoundException e) {
                e.printStackTrace();
                throw new Error(e);
            }
        }
    }
    return missionItemTypes;
}
Example 5
Project: molgenis-master  File: QueryUtils.java View source code
public static boolean containsAnyOperator(List<QueryRule> rules, Set<Operator> operators) {
    for (QueryRule rule : rules) {
        if (!rule.getNestedRules().isEmpty() && containsAnyOperator(rule.getNestedRules(), operators)) {
            return true;
        }
        if (operators.contains(rule.getOperator())) {
            return true;
        }
    }
    return false;
}
Example 6
Project: sonar-java-master  File: EnumSetCheck.java View source code
public void doSomething(Set<COLOR> param) {
    // compliant, we ignore parameters.
    // Noncompliant [[sc=23;ec=43]] {{Convert this Set to an EnumSet.}}
    Set<COLOR> warm = new HashSet<COLOR>();
    Set foo = new HashSet();
    warm.add(COLORS.RED);
    warm.add(COLORS.ORANGE);
    SetString ss;
    SetColor sc;
    // Compliant, we check only initializer.
    ExtendedSet<COLOR> es;
    // Noncompliant [[sc=17;ec=37]] {{Convert this Set to an EnumSet.}}
    Set warm2 = new HashSet<COLOR>();
    EnumSet<COLOR> warm3 = EnumSet.of(COLOR.RED, COLOR.ORANGE);
    Set<COLOR> warm4 = EnumSet.of(COLOR.RED, COLOR.ORANGE);
    Set<Integer> ports2 = new HashSet<>();
    // Noncompliant [[sc=24;ec=39]] {{Convert this Set to an EnumSet.}}
    Set<COLOR> ports = new HashSet<>();
    SetColor ports3 = new HashSet<>();
    // Compliant - guava use an enum set with constraint of immutability
    Set<COLOR> ports4 = Sets.immutableEnumSet(COLOR.RED);
    // Compliant - guava use an enum set with constraint of immutability
    Set<COLOR> ports5 = Sets.immutableEnumSet(Lists.newArrayList(COLOR.RED));
    Collection<COLOR> col = new ArrayList<>();
    Set<COLOR> col2 = java.util.Collections.unmodifiableSet(EnumSet.of(COLOR.RED, COLOR.ORANGE));
    // Noncompliant
    Set<COLOR> col3 = java.util.Collections.unmodifiableSet(new HashSet<COLOR>());
}
Example 7
Project: tapestry-model-master  File: DefaultExclusionsBMModifierTest.java View source code
@Test
void exclude() {
    BeanModel model = mockBeanModel();
    DescriptorService descriptorService = newMock(DescriptorService.class);
    TynamoClassDescriptorImpl classDescriptor = new TynamoClassDescriptorImpl(Foo.class);
    IdentifierDescriptor idProp = new IdentifierDescriptorImpl(Foo.class, "id", String.class);
    TynamoPropertyDescriptor multiWordProp = new TynamoPropertyDescriptorImpl(Foo.class, "multiWordProperty", String.class);
    CollectionDescriptor bazzesDescriptor = new CollectionDescriptor(Foo.class, "bazzes", Set.class);
    bazzesDescriptor.setElementType(Baz.class);
    Collections.addAll(classDescriptor.getPropertyDescriptors(), idProp, multiWordProp, bazzesDescriptor);
    expect(model.exclude("id", "bazzes")).andReturn(model);
    expect(model.getBeanType()).andReturn(Foo.class);
    expect(descriptorService.getClassDescriptor(Foo.class)).andReturn(classDescriptor);
    replay();
    DefaultExclusionsBMModifier modifier = new DefaultExclusionsBMModifier(descriptorService);
    modifier.modify(model, PageType.LIST.getContextKey());
    verify();
}
Example 8
Project: bennu-master  File: SchedulerTaskAnnotationProcessor.java View source code
@Override
public void onStartup(Set<Class<?>> classes, ServletContext ctx) throws ServletException {
    if (classes != null) {
        for (Class<?> type : classes) {
            final Task annon = type.getAnnotation(Task.class);
            if (annon != null) {
                SchedulerSystem.addTask(type.getName(), annon);
            }
        }
    }
}
Example 9
Project: sitebricks-master  File: AbstractMagicTemplateCompiler.java View source code
public Renderable compile(final Class<?> page, final Template sitebricksTemplate) {
    return new Renderable() {

        @Override
        public void render(Object bound, Respond respond) {
            assert page.isInstance(bound);
            //
            // 1. Transform text to XHTML        
            // 2. Process the XHTML however the client wishes
            // 3. Blow the processed XHTML out of pipe
            //
            respond.write(process(page, bound, transform(sitebricksTemplate)));
        }

        @Override
        public <T extends Renderable> Set<T> collect(Class<T> clazz) {
            return ImmutableSet.of();
        }
    };
}
Example 10
Project: sisu-guice-master  File: SuiteUtils.java View source code
public static TestSuite removeSuppressedTests(TestSuite suite, Set<String> suppressedTestNames) {
    TestSuite result = new TestSuite(suite.getName());
    for (Enumeration e = suite.tests(); e.hasMoreElements(); ) {
        Test test = (Test) e.nextElement();
        if (suppressedTestNames.contains(test.toString())) {
            continue;
        }
        if (test instanceof TestSuite) {
            result.addTest(removeSuppressedTests((TestSuite) test, suppressedTestNames));
        } else {
            result.addTest(test);
        }
    }
    return result;
}
Example 11
Project: org.openntf.domino-master  File: ASTAssignment.java View source code
/*
	 * (non-Javadoc)
	 * @see org.openntf.formula.ast.SimpleNode#analyzeThis(java.util.Set, java.util.Set, java.util.Set, java.util.Set)
	 */
@Override
protected void analyzeThis(final Set<String> readFields, final Set<String> modifiedFields, final Set<String> variables, final Set<String> functions) {
    switch(type) {
        case FIELD:
            modifiedFields.add(varName.toLowerCase());
            break;
        case VAR:
        case DEFAULT:
            variables.add(varName.toLowerCase());
            break;
        case ENV:
            break;
    }
}
Example 12
Project: LambdaDojo-master  File: S404StreamInsteadOfFor.java View source code
private void splitSentences() {
    List<String> sentences = Arrays.asList("Peter Piper picked", "a peck of pickled peppers.", "A peck of pickled peppers", "Peter Piper picked. ", "If Peter Piper picked", "a peck of pickled peppers,", "Where's the peck of pickled peppers", "Peter Piper picked? ");
    Set<String> words = new HashSet<>();
    for (String sentence : sentences) {
        String[] splitedSentence = sentence.split("[\\.,\\? ]");
        for (String word : splitedSentence) {
            words.add(word.toLowerCase());
        }
    }
    System.out.println(words);
}
Example 13
Project: dataverse-master  File: GroupUtil.java View source code
/**
     * @param authenticatedUser An non-null AuthenticatedUser.
     * @param groups The groups associated with an AuthenticatedUser.
     * @return A list of identifiers for the user including groups, single
     * quoted, and separated by commas. Null if a null AuthenticatedUser is
     * passed.
     */
public static String getAllIdentifiersForUser(AuthenticatedUser authenticatedUser, Set<Group> groups) {
    if (authenticatedUser == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder();
    sb.append("'").append(authenticatedUser.getIdentifier()).append("'");
    if (groups != null) {
        groups.stream().forEach(( group) -> {
            sb.append(", ").append("'").append(group.getIdentifier()).append("'");
        });
    }
    return sb.toString();
}
Example 14
Project: cloudtm-data-platform-master  File: IndexesConfig.java View source code
/*
     *  This method uses the TransactionManager, so make sure that it is already initialized when
     *  this method is called.
     */
@Atomic
private void updateIndexes() {
    // Ensure the root index tree exists
    DomainRoot domRoot = FenixFramework.getDomainRoot();
    BPlusTree<BPlusTree> rootIndex = domRoot.getIndexRoot();
    if (rootIndex == null) {
        rootIndex = new BPlusTree<BPlusTree>();
        domRoot.setIndexRoot(rootIndex);
    }
    // Now check for new and unused slot indexes
    List<AnnotatedSlot> indexedSlots = FenixFramework.getDomainModel().getAnnotatedSlots().get(Annotation.INDEX_ANNOTATION);
    Set<? extends Comparable> persistedIndexedSlots = rootIndex.getKeys();
    if (indexedSlots != null) {
        for (AnnotatedSlot annSlot : indexedSlots) {
            String key = annSlot.getDomainClass().getFullName() + "." + annSlot.getSlot().getName();
            BPlusTree slotIndexTree = rootIndex.get(key);
            if (slotIndexTree == null) {
                slotIndexTree = new BPlusTree();
                rootIndex.insert(key, slotIndexTree);
            }
            // Remove this slots' key from the known ones, meaning its still being used
            persistedIndexedSlots.remove(key);
        }
    }
    // For each key left out, we know that the corresponding slot is no longer annotated. Thus, delete its index tree.
    for (Comparable key : persistedIndexedSlots) {
        rootIndex.remove(key);
    }
}
Example 15
Project: alien4cloud-master  File: ToscaContextualAspect.java View source code
@Around("@annotation(alien4cloud.tosca.context.ToscaContextual)")
public Object ensureContext(ProceedingJoinPoint joinPoint) throws Throwable {
    MethodSignature ms = (MethodSignature) joinPoint.getSignature();
    Method m = ms.getMethod();
    boolean requireNew = m.getAnnotation(ToscaContextual.class).requiresNew();
    boolean initContext = false;
    ToscaContext.Context existingContext = ToscaContext.get();
    if (requireNew || existingContext == null) {
        initContext = true;
    }
    try {
        // try to find dependencies from parameters
        if (initContext) {
            Set<CSARDependency> dependencies = findDependencies(joinPoint.getArgs());
            log.debug("Initializing Tosca Context with dependencies {}", dependencies);
            ToscaContext.init(dependencies);
        }
        return joinPoint.proceed();
    } finally {
        if (initContext) {
            log.debug("Destroying Tosca Context");
            ToscaContext.destroy();
        }
        if (existingContext != null) {
            log.debug("Set back the existing context");
            ToscaContext.set(existingContext);
        }
    }
}
Example 16
Project: geotools-old-master  File: DEMProcessFactoryTest.java View source code
@Test
public void testProcessFactory() {
    DEMProcessFactory factory = new DEMProcessFactory();
    Set<Name> names = factory.getNames();
    assertNotNull(names);
    final Name NAME = new NameImpl("http://localhost/dem/", "slope");
    assertTrue(names.contains(NAME));
    InternationalString description = factory.getDescription(NAME);
    assertNotNull(description);
    assertNotNull(description.toString());
    Map<String, Parameter<?>> input = factory.getParameterInfo(NAME);
    assertNotNull(input);
    Parameter<?> param = input.get("DEM");
    assertNotNull(param);
    assertEquals("DEM", param.key);
    Map<String, Parameter<?>> result = factory.getResultInfo(NAME, null);
    assertNotNull(result);
    Parameter<?> param2 = result.get("slope");
    assertNotNull(param2);
    assertEquals("slope", param2.key);
    Process process = factory.create(NAME);
    assertNotNull(process);
}
Example 17
Project: extFM-Tooling-master  File: MappingFeaturesReferenceResolver.java View source code
public void resolve(String identifier, org.feature.multi.perspective.mapping.viewmapping.Mapping container, org.eclipse.emf.ecore.EReference reference, int position, boolean resolveFuzzy, final org.feature.multi.perspective.mapping.viewmapping.resource.mtext.IMtextReferenceResolveResult<Feature> result) {
    EObject model = EcoreUtil.getRootContainer(container);
    if (model instanceof MappingModel) {
        MappingModel mappingModel = (MappingModel) model;
        FeatureModel featureModel = mappingModel.getFeatureModel();
        FeatureModelHelper helper = new FeatureModelHelper(featureModel);
        Set<Feature> allFeatures = helper.getAllFeatures();
        for (Feature feature : allFeatures) {
            String featureId = EcoreUtil.getID(feature);
            if (identifier.equals(featureId)) {
                result.addMapping(identifier, feature);
                break;
            }
        }
    } else {
        delegate.resolve(identifier, container, reference, position, resolveFuzzy, result);
    }
}
Example 18
Project: ARTPart-master  File: Main.java View source code
public static void main(String[] args) throws Exception {
    // These charsets must be provided; anything else is optional.
    List<String> standardCharsets = Arrays.asList("US-ASCII", "ISO-8859-1", "UTF-8", "UTF-16BE", "UTF-16LE", "UTF-16");
    SortedMap<String, Charset> all = Charset.availableCharsets();
    Set<String> needed = new HashSet<String>(standardCharsets);
    for (Map.Entry<String, Charset> e : all.entrySet()) {
        String canonicalName = e.getKey();
        needed.remove(canonicalName);
    }
    System.out.println("Missing: " + needed);
}
Example 19
Project: parkandrideAPI-master  File: ElementLengthSetValidator.java View source code
@Override
public boolean isValid(Set<? extends CharSequence> set, ConstraintValidatorContext context) {
    context.disableDefaultConstraintViolation();
    boolean ok = true;
    if (set != null) {
        int i = 0;
        for (CharSequence val : set) {
            if (val != null && (val.length() < min || val.length() > max)) {
                context.buildConstraintViolationWithTemplate(message).addBeanNode().inIterable().atIndex(i).addConstraintViolation();
                ok = false;
            }
            i++;
        }
    }
    return ok;
}
Example 20
Project: many-ql-master  File: Refresher.java View source code
private Set<Refreshable> evaluate(Set<Refreshable> items) {
    Set<Refreshable> unresolved = new HashSet<>();
    for (Refreshable r : items) {
        Value val = r.evaluate(this.valueTable);
        if (val.isUndefined()) {
            unresolved.add(r);
        }
    }
    return unresolved;
}
Example 21
Project: mjprof-master  File: JPSUtil.java View source code
public static int lookupProcessId(String lookForMainClass) throws MonitorException, URISyntaxException {
    HostIdentifier hostId = new HostIdentifier("local://localhost");
    MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost(hostId);
    // get the set active JVMs on the specified host.
    Set jvms = monitoredHost.activeVms();
    for (Object jvm : jvms) {
        int lvmid = (Integer) jvm;
        MonitoredVm vm = null;
        String vmidString = "//" + lvmid + "?mode=r";
        VmIdentifier id = new VmIdentifier(vmidString);
        vm = monitoredHost.getMonitoredVm(id, 0);
        String mainClass = MonitoredVmUtil.mainClass(vm, false);
        if (mainClass.equals(lookForMainClass))
            return lvmid;
    }
    return -1;
}
Example 22
Project: cms-ce-master  File: ContentIndexDataTestBase.java View source code
void verifyElementExistsAndNumberOfValues(Set<ContentIndexDataElement> contentDataElements, String name, int expectedValueElements) {
    for (ContentIndexDataElement contentDataElement : contentDataElements) {
        final Set<ContentIndexDataFieldAndValue> contentIndexDataFieldAndValues = ContentIndexDataFieldValueSetFactory.create(contentDataElement);
        final Set<ContentIndexDataFieldAndValue> allFieldAndValuesForElement = contentIndexDataFieldAndValues;
        for (ContentIndexDataFieldAndValue contentIndexDataFieldAndValue : allFieldAndValuesForElement) {
            if (name.equals(contentIndexDataFieldAndValue.getFieldName())) {
                final Object value = contentIndexDataFieldAndValue.getValue();
                if (expectedValueElements > 1) {
                    assertTrue(value instanceof Collection);
                    Collection collection = (Collection) value;
                    assertEquals(expectedValueElements, collection.size());
                } else {
                    if (value instanceof Collection) {
                        assertEquals(1, ((Collection) value).size());
                    }
                }
                return;
            }
        }
    }
    fail("Did not find Element with name: " + name);
}
Example 23
Project: quickml-master  File: RTCatBranchFinderBuilder.java View source code
@Override
public RTCatBranchFinder buildBranchFinder(MeanValueCounter meanValueCounter, Set<String> candidateAttributes) {
    AttributeValueIgnoringStrategy<MeanValueCounter> attributeValueIgnoringStrategy;
    if (attributeValueIgnoringStrategyBuilder == null) {
        RegTreeAttributeValueIgnoringStrategyBuilder regTreeAttributeValueIgnoringStrategyBuilder = new RegTreeAttributeValueIgnoringStrategyBuilder(getMinAttributeOccurences());
        //TODO
        attributeValueIgnoringStrategy = regTreeAttributeValueIgnoringStrategyBuilder.createAttributeValueIgnoringStrategy(meanValueCounter);
    } else {
        //TODO make an attributeValueIgnoringStrategy that takes a MeanValueCounter that informs upon the general ratio of interesting target values and uninteresting values.
        attributeValueIgnoringStrategy = attributeValueIgnoringStrategyBuilder.createAttributeValueIgnoringStrategy(meanValueCounter);
    }
    return new RTCatBranchFinder(candidateAttributes, branchingConditions, scorerFactory, attributeValueIgnoringStrategy, attributeIgnoringStrategy);
}
Example 24
Project: ManagedRuntimeInitiative-master  File: InterfaceDecl.java View source code
@Test(result = "java.util.Set")
String getQualifiedName3() {
    InterfaceDeclaration set = (InterfaceDeclaration) env.getTypeDeclaration("java.util.Set");
    return set.getQualifiedName();
}
Example 25
Project: EclipseTrader-master  File: CompositeSet.java View source code
/**
     * Add a Set to this composite
     *
     * @param c Must implement Set
     * @throws IllegalArgumentException if c does not implement java.util.Set
     *         or if a SetMutator is set, but fails to resolve a collision
     * @throws UnsupportedOperationException if there is no SetMutator set, or
     *         a CollectionMutator is set instead of a SetMutator
     * @see org.apache.commons.collections.collection.CompositeCollection.CollectionMutator
     * @see SetMutator
     */
public synchronized void addComposited(Collection c) {
    if (!(c instanceof Set)) {
        throw new IllegalArgumentException("Collections added must implement java.util.Set");
    }
    for (Iterator i = this.getCollections().iterator(); i.hasNext(); ) {
        Set set = (Set) i.next();
        Collection intersects = CollectionUtils.intersection(set, c);
        if (intersects.size() > 0) {
            if (this.mutator == null) {
                throw new UnsupportedOperationException("Collision adding composited collection with no SetMutator set");
            } else if (!(this.mutator instanceof SetMutator)) {
                throw new UnsupportedOperationException("Collision adding composited collection to a CompositeSet with a CollectionMutator instead of a SetMutator");
            }
            ((SetMutator) this.mutator).resolveCollision(this, set, (Set) c, intersects);
            if (CollectionUtils.intersection(set, c).size() > 0) {
                throw new IllegalArgumentException("Attempt to add illegal entry unresolved by SetMutator.resolveCollision()");
            }
        }
    }
    super.addComposited(new Collection[] { c });
}
Example 26
Project: Mint-Programming-Language-master  File: ViewStrings.java View source code
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
    short i = 0;
    while (i < Short.MAX_VALUE) {
        try {
            HashMap<Integer, String> strs = Heap.strings;
            if (strs == null) {
                return EMPTY_LIST;
            }
            Table tbl = new Table();
            ArrayList<Integer> keys = new ArrayList<Integer>();
            Set<Integer> s = strs.keySet();
            for (int element : s) {
                keys.add(element);
            }
            s = null;
            for (int key : keys) {
                SmartList<Pointer> pair = new SmartList<Pointer>();
                pair.add(new Pointer(Constants.INT_TYPE, key));
                pair.add(Heap.allocateString(strs.get(key)));
                tbl.addBinding(pair);
            }
            return Heap.allocateTable(tbl);
        } catch (Throwable t) {
        }
        ++i;
    }
    try {
        return Heap.allocateString(Heap.strings.toString());
    } catch (Throwable t) {
        return ChangeString.ERROR;
    }
}
Example 27
Project: openjdk-master  File: MyProcessor.java View source code
public boolean process(Set<? extends TypeElement> tes, RoundEnvironment renv) {
    if (!renv.processingOver()) {
        for (TypeElement e : ElementFilter.typesIn(renv.getRootElements())) {
            for (TypeParameterElement tp : e.getTypeParameters()) {
                if (tp.getSimpleName().toString().length() > 1) {
                    messager.printMessage(WARNING, "Type param names should be of length 1", tp);
                }
            }
        }
    }
    return true;
}
Example 28
Project: erlide-master  File: NodeHelper.java View source code
/**
     * Returns backends managed by erlide. Depending on argument nodes
     * irrelevant from user's point of view (tracing and ide backends) can be
     * omitted in resulting list.
     *
     * @param ignore
     *            if nodes should be omitted
     * @return list of backends
     */
public static Collection<? extends IBackend> getBackends(final boolean ignore) {
    if (!ignore) {
        return BackendCore.getBackendManager().getAllBackends();
    }
    final List<IBackend> backends = new ArrayList<>();
    final IBackendManager backendManager = BackendCore.getBackendManager();
    final Set<IBackend> ignored = new HashSet<>();
    IBackend backend;
    if ((backend = backendManager.getIdeBackend()) != null) {
        ignored.add(backend);
    }
    if ((backend = TraceBackend.getInstance().getBackend(false)) != null) {
        ignored.add(backend);
    }
    for (final IBackend erlideBackend : BackendCore.getBackendManager().getAllBackends()) {
        if (!ignored.contains(erlideBackend)) {
            backends.add(erlideBackend);
        }
    }
    return backends;
}
Example 29
Project: dtangler-master  File: GroupTest.java View source code
@Test
public void testGroupsWithExcludedItems() {
    Set<String> containedItems = new HashSet();
    containedItems.add("org.*");
    Set<String> excludedItems = new HashSet();
    excludedItems.add("org.public");
    Set<String> excludedItems2 = new HashSet();
    excludedItems2.add("org.public2");
    Group a = new Group("A", containedItems, excludedItems);
    Group b = new Group("A", containedItems, excludedItems);
    Group c = new Group("A", containedItems, excludedItems2);
    assertTrue(a.equals(b));
    assertTrue(b.equals(a));
    assertFalse(a.equals(c));
    assertFalse(c.equals(b));
}
Example 30
Project: cdo-master  File: CompareCDOMerger.java View source code
public void merge(final CDOTransaction localTransaction, CDOView remoteView, Set<CDOID> affectedIDs) throws ConflictException {
    CDOCompareEditorUtil.closeTransactionAfterCommit(localTransaction);
    CDOCompareEditorUtil.closeEditorWithTransaction(localTransaction);
    CDOCompareEditorUtil.openEditor(remoteView, localTransaction, affectedIDs, true);
}
Example 31
Project: geoserver-enterprise-master  File: UniqueProcessNamesTest.java View source code
@Test
public void testNamesUnique() throws Exception {
    List<String> procs = new ArrayList<String>();
    Set<String> uniqueProcs = new HashSet<String>();
    for (ProcessFactory pf : GeoServerProcessors.getProcessFactories()) {
        for (Name name : pf.getNames()) {
            String procName = name.getURI();
            procs.add(procName);
            uniqueProcs.add(procName);
        }
    }
    // remove duplicate names
    removeSingle(procs, uniqueProcs);
    if (procs.size() > 0) {
        System.out.println("Duplicate process names: " + procs);
    }
    assertTrue(procs.size() == 0);
}
Example 32
Project: ISAcreator-master  File: InvestigationUtils.java View source code
/**
     * Method return all the unannotated freetext found in the Investigation
     *
     * @param investigation @see Investigation
     * @return Map from Assay object (general container for spreadsheet) to a Map from the Column Name to its unannotated values
     */
public static Map<Assay, Map<String, Set<String>>> getFreeTextInInvestigationSpreadsheets(Investigation investigation) {
    Map<Assay, Map<String, Set<String>>> result = new HashMap<Assay, Map<String, Set<String>>>();
    Map<String, Study> studies = investigation.getStudies();
    for (String studyId : studies.keySet()) {
        Study study = studies.get(studyId);
        result.put(study.getStudySample(), SpreadsheetUtils.getFreetextInSpreadsheet(((AssaySpreadsheet) ApplicationManager.getUserInterfaceForISASection(study.getStudySample())).getSpreadsheet()));
        for (Assay assay : study.getAssays().values()) {
            result.put(assay, SpreadsheetUtils.getFreetextInSpreadsheet(((AssaySpreadsheet) ApplicationManager.getUserInterfaceForISASection(assay)).getSpreadsheet()));
        }
    }
    return result;
}
Example 33
Project: geotoolkit-master  File: GroovyConditionProcess.java View source code
@Override
protected void execute() throws ProcessException {
    final Map variables = value(GroovyDescriptor.VARIABLES, inputParameters);
    final String expression = value(GroovyDescriptor.SCRIPT, inputParameters);
    final String behavior = value(GroovyDescriptor.BEHAVIOR, inputParameters);
    final Binding binding = new Binding();
    final GroovyShell shell = new GroovyShell(binding);
    final Set<String> keys = variables.keySet();
    for (String key : keys) {
        shell.setVariable(key, variables.get(key));
    }
    Object result = shell.evaluate(expression);
    if ("EXCEPTION".equals(behavior)) {
        if (result != null && result instanceof Boolean && !((Boolean) result)) {
            throw new ProcessException("Groovy expression failed." + expression, this, null);
        }
    }
    getOrCreate(GroovyDescriptor.RESULT, outputParameters).setValue(result);
}
Example 34
Project: FTL-Hyperion-master  File: CrewEffects.java View source code
@Subscribe
public void getPowerEvent(GetSystemPowerEvent event) {
    AbstractShipSystem system = event.ship.getSystem(event.system);
    Room room = system.getRoom();
    if (room != null) {
        Set<Crew> crew = room.getCrew();
        for (Crew member : crew) {
            if (member.getRace().equals("Zoltan")) {
                // TODO: What if max power is 1 and there are 2 zoltans; calc additional power in loop then check to make sure it is not more than max power
                // TODO: What if the system was at max power and a zoltan walks in; perhaps should be taken care of in the system, if power is greater than max, remove curr-max power
                event.power++;
            }
        }
    }
}
Example 35
Project: dcache-master  File: DomainsDAOHelper.java View source code
@Override
public Set<CellResponse> sendCommand(Set<String> destinations, String command) throws DAOException {
    if (_isThrowingExceptionOnCommandSending) {
        throw new DAOException("exception throwing modus is active");
    }
    Set<CellResponse> responses = new HashSet<>();
    for (String destination : destinations) {
        CellResponse newResponse = new CellResponse();
        newResponse.setCellName(destination);
        newResponse.setResponse(RESPONSE_FOR_ALL_RESPONSES);
        newResponse.setIsFailure(_areAllResponsesFailure);
    }
    return responses;
}
Example 36
Project: eclipselink.runtime-master  File: IndirectSet.java View source code
/**
     * INTERNAL:
     * Return the freshly-built delegate.
     */
protected Set<E> buildDelegate() {
    Set<E> newDelegate = (Set<E>) getValueHolder().getValue();
    if (newDelegate == null) {
        newDelegate = new HashSet<>(this.initialCapacity, this.loadFactor);
    }
    // Unwrap any redundant indirection layers, which can cause issues and impact performance.
    while (newDelegate instanceof IndirectSet) {
        newDelegate = ((IndirectSet) newDelegate).getDelegate();
    }
    // First add/remove any cached changes.
    if (hasAddedElements()) {
        for (Iterator<E> iterator = getAddedElements().iterator(); iterator.hasNext(); ) {
            newDelegate.add(iterator.next());
        }
        this.addedElements = null;
    }
    if (hasRemovedElements()) {
        for (Iterator<E> iterator = getRemovedElements().iterator(); iterator.hasNext(); ) {
            newDelegate.remove(iterator.next());
        }
        this.removedElements = null;
    }
    return newDelegate;
}
Example 37
Project: raylew_algorithm-master  File: 统计字符.java View source code
public static void main(String[] args) {
    String str = "zdsgzd";
    Map map = new HashMap();
    int maxvalue = 0;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (map.get(c) == null) {
            map.put(c, 1);
        } else {
            int total = (Integer) map.get(c);
            total++;
            map.put(c, total);
            if (maxvalue < total) {
                maxvalue = total;
            }
        }
    }
    System.out.println("maxvalue:" + maxvalue);
    System.out.println(map.toString());
    Set set = map.keySet();
    Iterator iterator = set.iterator();
    int max = 0;
    char maxkey = 0;
    char key = 0;
    while (iterator.hasNext()) {
        key = (Character) iterator.next();
        if (max <= (Integer) map.get(key)) {
            max = (Integer) map.get(key);
            maxkey = key;
        }
    }
    System.out.println(maxkey + ":" + max);
}
Example 38
Project: tmdm-studio-se-master  File: ProcessAllCallJobVariableCandidatesHolder.java View source code
@Override
public String[] getExternalInfo() {
    if (service == null) {
        return new String[0];
    }
    Set<String> inputVariables = new HashSet<String>();
    for (WSTransformerProcessStep step : service.getProcessSteps()) {
        for (WSTransformerVariablesMapping mapping : step.getInputMappings()) {
            inputVariables.add(mapping.getPipelineVariable() == null ? TransformerMainPage.DEFAULT_VAR : mapping.getPipelineVariable());
        }
    }
    String[] results = inputVariables.toArray(new String[0]);
    Arrays.sort(results);
    return results;
}
Example 39
Project: beowulf-master  File: BwExecutorService.java View source code
public void submitJobs(Set<TestJob> testJobs) {
    for (TestJob job : testJobs) try {
        submitJob(job);
    } catch (JMSException e) {
        logger.error("Failed to submit testjob with id: {} and webscanObjId: {}", job.getTestJobObjId(), job.getWebScanObjId());
        e.printStackTrace();
    }
}
Example 40
Project: Light-Controller-master  File: AppReciever.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
    Set<String> enabled = prefs.getStringSet("enabled_api_apps", new HashSet<String>());
    if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
        String packageName = intent.getData().getEncodedSchemeSpecificPart();
        Log.d("package", "Package Removed:" + packageName);
        if (enabled.contains(packageName)) {
            enabled.remove(packageName);
            prefs.edit().putStringSet("enabled_api_apps", enabled).apply();
            Log.d("package", "API Permission removed");
        }
    }
}
Example 41
Project: metrics-master  File: ThreadDeadlockHealthCheckTest.java View source code
@Test
public void isUnhealthyIfThreadsAreDeadlocked() throws Exception {
    final Set<String> threads = new TreeSet<String>();
    threads.add("one");
    threads.add("two");
    final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class);
    final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector);
    when(detector.getDeadlockedThreads()).thenReturn(threads);
    final HealthCheck.Result result = healthCheck.execute();
    assertThat(result.isHealthy()).isFalse();
    assertThat(result.getMessage()).isEqualTo("[one, two]");
}
Example 42
Project: REST-OCD-Services-master  File: ExcelFileGenerator.java View source code
public void genFile(Map<String, Object[]> data) {
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Data");
    Set<String> keyset = data.keySet();
    int rownum = 0;
    for (String key : keyset) {
        rownum = Integer.parseInt(key);
        Row row = sheet.createRow(rownum);
        Object[] objectArray = data.get(key);
        int cellnum = 0;
        for (Object o : objectArray) {
            Cell c = row.createCell(cellnum++);
            if (o instanceof String) {
                c.setCellValue((String) o);
            }
            if (o instanceof Double) {
                c.setCellValue((Double) o);
            }
            if (o instanceof Integer) {
                c.setCellValue((Integer) o);
            }
        }
    }
    try {
        FileOutputStream out = new FileOutputStream(new File("Evaluation.xlsx"));
        workbook.write(out);
        out.close();
        System.out.println("Excel file written");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 43
Project: ldbc_snb_datagen-master  File: MinHash.java View source code
public ArrayList<Long> minHash(Set<Long> set) {
    ArrayList<Long> minHashes = new ArrayList<Long>();
    for (int i = 0; i < numHashes_; ++i) {
        long min = Long.MAX_VALUE;
        long minl = 0;
        for (Long l : set) {
            long hash = (a[i] * l + b[i]) % p[i];
            if (hash <= min) {
                min = hash;
                minl = l;
            }
        }
        minHashes.add(minl);
    }
    return minHashes;
}
Example 44
Project: Desktop-master  File: IncrementalSearcher.java View source code
protected boolean searchFields(Set<String> fields, BibtexEntry bibtexEntry, String searchString) {
    boolean found = false;
    if (fields != null) {
        for (String field : fields) {
            try {
                /*Globals.logger("Searching field '"+fields[i].toString()
				       +"' for '"
				       +pattern.toString()+"'.");*/
                if (bibtexEntry.getField(field.toString()) != null) {
                    if (prefs.getBoolean("caseSensitiveSearch")) {
                        if (bibtexEntry.getField(field.toString()).toString().indexOf(searchString) > -1)
                            found = true;
                    } else {
                        if (bibtexEntry.getField(field.toString()).toString().toLowerCase().indexOf(searchString.toLowerCase()) > -1)
                            found = true;
                    }
                    if (found) {
                        hitInField = field.toString();
                        return true;
                    }
                }
            } catch (Throwable t) {
                System.err.println("Searching error: " + t);
            }
        }
    }
    return false;
}
Example 45
Project: Katari-master  File: RoleSecurityUtils.java View source code
/**
   * Obtains the roles of the currently logged on user.
   *
   * @return a set the currently logged on user. It returns null only if the
   * user has not logged in yet.
   */
public static Set<Role> getCurrentUserRoles() {
    log.trace("Entering getCurrentUserRoles");
    Set<Role> roles = null;
    // Obtains the current user definition.
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (principal != null) {
        if (!(principal instanceof RoleDetails)) {
            throw new RuntimeException("The currently logged on user does not" + " implement RoleDetails.");
        }
        roles = ((RoleDetails) principal).getUserRoles();
    }
    log.trace("Leaving getCurrentUserRoles");
    return roles;
}
Example 46
Project: framework-master  File: NotselectablePaintSelections.java View source code
@Override
protected void setup() {
    // Multiselect
    Table t = new Table("Multiselect");
    addComponent(t);
    t.setSelectable(false);
    t.setMultiSelect(true);
    t.setPageLength(5);
    t.addContainerProperty("Name", String.class, null);
    Set<Object> selected = new HashSet<>();
    for (int i = 0; i < 30; i++) {
        Item item = t.addItem(i);
        item.getItemProperty("Name").setValue("Name " + i);
        if (i % 2 == 0) {
            selected.add(i);
        }
    }
    t.setValue(selected);
    // Singleselect
    t = new Table("Singleselect");
    addComponent(t);
    t.setSelectable(false);
    t.setMultiSelect(false);
    t.setPageLength(5);
    t.addContainerProperty("Name", String.class, null);
    for (int i = 0; i < 30; i++) {
        Item item = t.addItem(i);
        item.getItemProperty("Name").setValue("Name " + i);
    }
    t.setValue(3);
}
Example 47
Project: TextSecureSMP-master  File: CountryListLoader.java View source code
@Override
public ArrayList<Map<String, String>> loadInBackground() {
    Set<String> regions = PhoneNumberUtil.getInstance().getSupportedRegions();
    ArrayList<Map<String, String>> results = new ArrayList<Map<String, String>>(regions.size());
    for (String region : regions) {
        Map<String, String> data = new HashMap<String, String>(2);
        data.put("country_name", PhoneNumberFormatter.getRegionDisplayName(region));
        data.put("country_code", "+" + PhoneNumberUtil.getInstance().getCountryCodeForRegion(region));
        results.add(data);
    }
    Collections.sort(results, new RegionComparator());
    return results;
}
Example 48
Project: xmind-master  File: SpaceCollaborativeEngine.java View source code
public void refreshMinorSpace() {
    int maxCount = 0;
    ContentPane contentPane = null;
    Set<Object> keys = managedContentPanes.keySet();
    for (Object key : keys) {
        ContentPane cp = managedContentPanes.get(key);
        int size = cp.getChildren().size();
        if (size >= maxCount) {
            contentPane = cp;
            maxCount = size;
        }
    }
    List elements = contentPane.getChildren();
    if (contentPane == null || elements.isEmpty())
        return;
    Rectangle clientArea = contentPane.getClientArea();
    int totalSize = clientArea.width;
    int elementSize = ((IFigure) elements.get(0)).getPreferredSize(-1, -1).width;
    int calculatedCount = totalSize / elementSize;
    int calculatedTotalSpace = totalSize - calculatedCount * elementSize;
    int calculatedEachSpace = 0;
    if (calculatedCount > 1) {
        calculatedEachSpace = calculatedTotalSpace / (calculatedCount - 1);
    }
    Set<Object> managedKeys = managedContentPanes.keySet();
    for (Object key : managedKeys) {
        ContentPane cp = managedContentPanes.get(key);
        int oldSpace = cp.getMinorSpacing();
        if (oldSpace != calculatedEachSpace) {
            cp.setMinorSpacing(calculatedEachSpace);
        }
    }
}
Example 49
Project: dk-master  File: CacheService.java View source code
/**
	 * 将所有的redis指定key的缓存都清空
	 * 
	 * @param key
	 */
public void clear(Object key) {
    if (cacheService == null || cacheService.size() == 0) {
        return;
    }
    Set<Entry<String, SpringRedisCacheService>> entrySet = cacheService.entrySet();
    for (Entry<String, SpringRedisCacheService> entry : entrySet) {
        if (entry.getKey().equalsIgnoreCase(LOCAL)) {
            continue;
        }
        long result = entry.getValue().deleteObjectKey(key);
        if (// 重试一次
        result == // 重试一次
        FAIL) {
            entry.getValue().deleteObjectKey(key);
        }
    }
}
Example 50
Project: nuxeo-jsf-master  File: JSFAnnotationProvider.java View source code
@Override
public Map<Class<? extends Annotation>, Set<Class<?>>> getAnnotatedClasses(Set<URI> urls) {
    if (JSFContainerInitializer.self == null) {
        LogFactory.getLog(JSFAnnotationProvider.class).warn("container scanned classes unavailable, applying default scanning");
        return base.getAnnotatedClasses(urls);
    }
    return JSFContainerInitializer.self.index;
}
Example 51
Project: lettuce-master  File: NodeTopologyViewsTest.java View source code
@Test
public void shouldReuseKnownUris() throws Exception {
    RedisURI localhost = RedisURI.create("localhost", 6479);
    RedisURI otherhost = RedisURI.create("127.0.0.2", 7000);
    RedisURI host3 = RedisURI.create("127.0.0.3", 7000);
    String viewByLocalhost = "1 127.0.0.1:6479 master,myself - 0 1401258245007 2 connected 8000-11999\n" + "2 127.0.0.2:7000 master - 111 1401258245007 222 connected 7000 12000 12002-16383\n" + "3 127.0.0.3:7000 master - 111 1401258245007 222 connected 7000 12000 12002-16383\n";
    String viewByOtherhost = "1 127.0.0.1:6479 master - 0 1401258245007 2 connected 8000-11999\n" + "2 127.0.0.2:7000 master,myself - 111 1401258245007 222 connected 7000 12000 12002-16383\n" + "3 127.0.0.3:7000 master - 111 1401258245007 222 connected 7000 12000 12002-16383\n";
    NodeTopologyView localhostView = new NodeTopologyView(localhost, viewByLocalhost, "", 0);
    NodeTopologyView otherhostView = new NodeTopologyView(otherhost, viewByOtherhost, "", 0);
    NodeTopologyViews nodeTopologyViews = new NodeTopologyViews(Arrays.asList(localhostView, otherhostView));
    Set<RedisURI> clusterNodes = nodeTopologyViews.getClusterNodes();
    assertThat(clusterNodes).contains(localhost, otherhost, host3);
}
Example 52
Project: pmd-eclipse-plugin-master  File: RuleSetsExtension.java View source code
/**
     * Replace the core plugin fragment with our own rulesets
     * @see net.sourceforge.pmd.eclipse.core.IRuleSetsExtension#registerRuleSets(java.util.Set)
     */
public void registerRuleSets(Set<RuleSet> registeredRuleSets) {
    try {
        RuleSet ruleSet1 = getRuleSet1();
        RuleSet ruleSet2 = getRuleSet2();
        // registeredRuleSets.clear(); // to remove all rulesets already registered
        registeredRuleSets.add(ruleSet1);
        registeredRuleSets.add(ruleSet2);
    } catch (RuleSetNotFoundException e) {
        PMDPlugin.getDefault().log(IStatus.ERROR, "Unable to load rulesets", e);
    }
}
Example 53
Project: eclipse.jdt.core-master  File: Java8FilerProcessor.java View source code
/* (non-Javadoc)
	 * @see javax.annotation.processing.AbstractProcessor#process(java.util.Set, javax.annotation.processing.RoundEnvironment)
	 */
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    String packageName = "targets.filer8";
    this.reportSuccessAlready = true;
    if (++roundNo == 1) {
        this.reportSuccessAlready = false;
        try {
            createPackageBinary();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.setProperty(this.getClass().getName(), "Processor did not fully do the job");
    } else if (roundNo == 2) {
        PackageElement packageEl = null;
        for (Element e : roundEnv.getRootElements()) {
            if (e.getKind() == ElementKind.PACKAGE) {
                packageEl = (PackageElement) e;
            }
        }
        if (packageEl == null) {
            reportError("Package Element not found");
            return false;
        }
        if (!packageName.equals(packageEl.getQualifiedName().toString())) {
            reportError("Package Element \"targets.filer8\" not found");
            return false;
        }
        if (packageEl.isUnnamed()) {
            reportError("Package info not found");
            return false;
        }
        if (packageEl.getAnnotationMirrors().isEmpty()) {
            reportError("Annotatons not found in package-info");
            return false;
        }
    }
    if (this.reportSuccessAlready) {
        super.reportSuccess();
    }
    return false;
}
Example 54
Project: spikes-master  File: TechDebtAnnotationProcessor.java View source code
@Override
public boolean process(Set<? extends TypeElement> annotationElements, RoundEnvironment roundEnv) {
    for (TypeElement annotationElement : annotationElements) {
        final Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotationElement);
        for (Element annotadedElement : annotatedElements) {
            printWarning(annotadedElement);
        }
    }
    return true;
}
Example 55
Project: AIDR-master  File: ApplicationConfig.java View source code
/**
     * Do not modify addRestResourceClasses() method.
     * It is automatically re-generated to populate
     * given list with all resources defined in the project.
     */
private void addRestResourceClasses(Set<Class<?>> resources) {
    resources.add(MoxyJsonFeature.class);
    resources.add(JacksonFeature.class);
    resources.add(qa.qcri.aidr.analysis.api.GetTagDataStatistics.class);
    resources.add(qa.qcri.aidr.analysis.api.GetConfidenceStatistics.class);
    resources.add(qa.qcri.aidr.analysis.api.WriteStatisticsData.class);
}
Example 56
Project: katharsis-core-master  File: DefaultExceptionMapperLookup.java View source code
@Override
public Set<JsonApiExceptionMapper> getExceptionMappers() {
    Reflections reflections;
    if (resourceSearchPackage != null) {
        String[] packageNames = resourceSearchPackage.split(",");
        reflections = new Reflections(packageNames);
    } else {
        reflections = new Reflections(resourceSearchPackage);
    }
    Set<Class<?>> exceptionMapperClasses = reflections.getTypesAnnotatedWith(ExceptionMapperProvider.class);
    Set<JsonApiExceptionMapper> exceptionMappers = new HashSet<>();
    for (Class<?> exceptionMapperClazz : exceptionMapperClasses) {
        if (!JsonApiExceptionMapper.class.isAssignableFrom(exceptionMapperClazz)) {
            throw new InvalidResourceException(exceptionMapperClazz.getCanonicalName() + " is not an implementation of JsonApiExceptionMapper");
        }
        try {
            exceptionMappers.add((JsonApiExceptionMapper<? extends Throwable>) exceptionMapperClazz.newInstance());
        } catch (Exception e) {
            throw new InvalidResourceException(exceptionMapperClazz.getCanonicalName() + " can not be initialized", e);
        }
    }
    return exceptionMappers;
}
Example 57
Project: tdq-studio-se-master  File: AbstractImportBuildInFileAction.java View source code
/*
     * (non-Javadoc)
     * 
     * @see org.talend.dataprofiler.core.ui.action.AbstractImportFileAction#computeFilePath()
     */
@Override
public Map<File, IPath> computeFilePath() throws Exception {
    ERepositoryObjectType type = getRepositoryType();
    Plugin plugin = getPlugin();
    String srcPath = getSrcPath();
    Folder destFolder = (Folder) node.getObject();
    Set<String> suffix = getSuffix();
    boolean isResurse = isRecurse();
    Map<File, IPath> resultMap = new HashMap<File, IPath>();
    if (type != null && plugin != null && srcPath != null) {
        WorkspaceResourceHelper.computeFileFromPlugin(plugin, srcPath, isResurse, destFolder, suffix, type, resultMap);
    }
    return resultMap;
}
Example 58
Project: usergrid-master  File: AvailablePortFinder.java View source code
/**
     * Returns the [email protected] java.util.Set} of currently avaliable port numbers ([email protected] Integer}) between the specified port range.
     *
     * @throws IllegalArgumentException if port range is not between [email protected] #MIN_PORT_NUMBER} and [email protected]
     * #MAX_PORT_NUMBER} or <code>fromPort</code> if greater than <code>toPort</code>.
     */
public static Set<Integer> getAvailablePorts(int fromPort, int toPort) {
    if (fromPort < MIN_PORT_NUMBER || toPort > MAX_PORT_NUMBER || fromPort > toPort) {
        throw new IllegalArgumentException("Invalid port range: " + fromPort + " ~ " + toPort);
    }
    Set<Integer> result = new TreeSet<Integer>();
    for (int i = fromPort; i <= toPort; i++) {
        ServerSocket s = null;
        try {
            s = new ServerSocket(i);
            result.add(new Integer(i));
        } catch (IOException e) {
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                }
            }
        }
    }
    return result;
}
Example 59
Project: sgithub-master  File: OAuthServiceImpl.java View source code
/* (non-Javadoc)
	 * @see com.google.code.facebook.graph.client.oauth.FacebookOAuthService#getAuthorizationUrl(java.lang.String, java.util.Set)
	 */
@Override
public String getAuthorizationUrl(String callBackUrl, Set<Scope> permissions) {
    GitHubApiUrlBuilder builder = createGitHubApiUrlBuilder(GitHubApiUrls.OAuthUrls.AUTHORIZE_URL);
    builder.withParameter(ParameterNames.CLIENT_ID, clientId).withParameter(ParameterNames.REDIRECT_URI, callBackUrl);
    builder.withParameterEnumSet(ParameterNames.SCOPE, permissions, ",");
    return builder.buildUrl();
}
Example 60
Project: teiid-designer-master  File: EmfContainerSetup.java View source code
//############################################################################################################################
//# Instance Methods                                                                                                         #
//############################################################################################################################
/**
     * Creates the list of containers named by the keys within the specified map, marking the one, if any, that matches the
     * specified primary container as such.  The values for each map entry contain a list of model names that are then added to
     * each respective container.
     * @param primaryContainer The name of the primary container, if any.  May be null.
     * @since 3.1
     */
public void containerSetUp(final Map containers, final String primaryContainer) {
    final Set set = containers.entrySet();
    for (final Iterator ctnrIter = set.iterator(); ctnrIter.hasNext(); ) {
        final Entry entry = (Entry) ctnrIter.next();
        final String ctnr = (String) entry.getKey();
        EmfContainerUtils.createContainer(ctnr, ctnr.equals(primaryContainer));
        final List models = (List) entry.getValue();
        for (final Iterator modelIter = models.iterator(); modelIter.hasNext(); ) {
            EmfContainerUtils.addModel((String) modelIter.next(), ctnr);
        }
    }
}
Example 61
Project: richfaces-master  File: ExtendedVisitContextFactory.java View source code
/**
     * <p>
     * Wraps extended visit context from VisitContext created from parent factory,
     * </p>
     *
     * <p>
     * only if current view processing is inside of [email protected] ExtendedPartialViewContext#processPartial(javax.faces.event.PhaseId)}
     * processing
     * </p>
     *
     * <p>
     * either in [email protected] ExtendedVisitContextMode#EXECUTE} or [email protected] ExtendedVisitContextMode#RENDER}.
     * </p>
     *
     * <p>
     * Otherwise if [email protected] VisitContextFactory} is called outside of
     * [email protected] ExtendedPartialViewContext#processPartial(javax.faces.event.PhaseId)} processing, a [email protected] VisitContext} created
     * by parent factory is used instead.
     */
@Override
public VisitContext getVisitContext(FacesContext facesContext, Collection<String> clientIds, Set<VisitHint> hints) {
    final VisitContext visitContextToWrap = parentFactory.getVisitContext(facesContext, clientIds, hints);
    final ExtendedPartialViewContext epvc = ExtendedPartialViewContext.getInstance(facesContext);
    if (epvc != null && clientIds != null) {
        final ExtendedVisitContextMode visitMode = epvc.getVisitMode();
        if (visitMode != null) {
            switch(visitMode) {
                case EXECUTE:
                    return new ExtendedExecuteVisitContext(visitContextToWrap, facesContext, clientIds, hints);
                case RENDER:
                    // RF-14252: hack for MyFaces, with @resetValues MyFaces doesn't get render ids from epvc
                    if (clientIds.contains("@component")) {
                        clientIds.addAll(epvc.getRenderIds());
                    }
                    return new ExtendedRenderVisitContext(visitContextToWrap, facesContext, clientIds, hints, epvc.isLimitRender());
            }
        }
    }
    return visitContextToWrap;
}
Example 62
Project: spring-framework-2.5.x-master  File: SetFactoryBean.java View source code
protected Object createInstance() {
    if (this.sourceSet == null) {
        throw new IllegalArgumentException("'sourceSet' is required");
    }
    Set result = null;
    if (this.targetSetClass != null) {
        result = (Set) BeanUtils.instantiateClass(this.targetSetClass);
    } else {
        result = new LinkedHashSet(this.sourceSet.size());
    }
    Class valueType = null;
    if (this.targetSetClass != null && JdkVersion.isAtLeastJava15()) {
        valueType = GenericCollectionTypeResolver.getCollectionType(this.targetSetClass);
    }
    if (valueType != null) {
        TypeConverter converter = getBeanTypeConverter();
        for (Iterator it = this.sourceSet.iterator(); it.hasNext(); ) {
            result.add(converter.convertIfNecessary(it.next(), valueType));
        }
    } else {
        result.addAll(this.sourceSet);
    }
    return result;
}
Example 63
Project: records-management-master  File: ExtendedSecurityServiceImpl.java View source code
/**
     * @see org.alfresco.module.org_alfresco_module_rm.security.ExtendedSecurityService#set(org.alfresco.service.cmr.repository.NodeRef, java.util.Set, java.util.Set)
     */
@Override
public void set(NodeRef nodeRef, Set<String> readers, Set<String> writers) {
    ParameterCheck.mandatory("nodeRef", nodeRef);
    // remove existing extended security, assuming there is any
    remove(nodeRef);
    // find groups
    Pair<String, String> iprGroups = createOrFindIPRGroups(readers, writers);
    // assign groups to correct fileplan roles
    NodeRef filePlan = filePlanService.getFilePlan(nodeRef);
    filePlanRoleService.assignRoleToAuthority(filePlan, FilePlanRoleService.ROLE_EXTENDED_READERS, iprGroups.getFirst());
    filePlanRoleService.assignRoleToAuthority(filePlan, FilePlanRoleService.ROLE_EXTENDED_WRITERS, iprGroups.getSecond());
    // assign groups to node
    assignIPRGroupsToNode(iprGroups, nodeRef);
    // apply the readers to any renditions of the content
    if (isRecord(nodeRef)) {
        List<ChildAssociationRef> assocs = nodeService.getChildAssocs(nodeRef, RenditionModel.ASSOC_RENDITION, RegexQNamePattern.MATCH_ALL);
        for (ChildAssociationRef assoc : assocs) {
            NodeRef child = assoc.getChildRef();
            assignIPRGroupsToNode(iprGroups, child);
        }
    }
}
Example 64
Project: openjdk8-jdk-master  File: Synch3.java View source code
public static void main(String[] args) {
    Subject subject = new Subject();
    final Set principals = subject.getPrincipals();
    principals.add(new X500Principal("CN=Alice"));
    new Thread() {

        {
            start();
        }

        public void run() {
            X500Principal p = new X500Principal("CN=Bob");
            while (!finished) {
                principals.add(p);
                principals.remove(p);
            }
        }
    };
    for (int i = 0; i < 1000; i++) {
        subject.getPrincipals(X500Principal.class);
    }
    finished = true;
}
Example 65
Project: lucene-solr-master  File: DIHWriterBase.java View source code
@Override
public void setDeltaKeys(Set<Map<String, Object>> passedInDeltaKeys) {
    deltaKeys = new HashSet<>();
    for (Map<String, Object> aMap : passedInDeltaKeys) {
        if (aMap.size() > 0) {
            Object key = null;
            if (keyFieldName != null) {
                key = aMap.get(keyFieldName);
            } else {
                key = aMap.entrySet().iterator().next();
            }
            if (key != null) {
                deltaKeys.add(key);
            }
        }
    }
}
Example 66
Project: yarn-comment-master  File: TestFileContextResolveAfs.java View source code
@Test
public void testFileContextResolveAfs() throws IOException {
    Configuration conf = new Configuration();
    localFs = FileSystem.get(conf);
    Path localPath = new Path(TEST_ROOT_DIR_LOCAL + "/TestFileContextResolveAfs1");
    Path linkPath = new Path("file://" + TEST_ROOT_DIR_LOCAL + "/TestFileContextResolveAfs2");
    localFs.mkdirs(new Path(TEST_ROOT_DIR_LOCAL));
    localFs.create(localPath);
    fc.createSymlink(localPath, linkPath, true);
    Set<AbstractFileSystem> afsList = fc.resolveAbstractFileSystems(linkPath);
    Assert.assertEquals(1, afsList.size());
    localFs.deleteOnExit(localPath);
    localFs.deleteOnExit(linkPath);
    localFs.close();
}
Example 67
Project: dimple-master  File: NonNullTest.java View source code
@Test
public void test() {
    // NonNull.list
    List<Integer> list = NotNull.list(null);
    assertNotNull(list);
    assertTrue(list.isEmpty());
    ArrayList<Integer> list2 = new ArrayList<Integer>();
    list2.add(42);
    list = NotNull.list(list2);
    assertNotNull(list);
    assertEquals(list, list2);
    // NonNull.map
    Map<Integer, Integer> map = NotNull.map(null);
    assertNotNull(map);
    assertTrue(map.isEmpty());
    HashMap<Integer, Integer> map2 = new HashMap<Integer, Integer>();
    map2.put(42, 23);
    map = NotNull.map(map2);
    assertNotNull(map);
    assertEquals(map, map2);
    // NonNull.list
    Set<Integer> set = NotNull.set(null);
    assertNotNull(set);
    assertTrue(set.isEmpty());
    HashSet<Integer> set2 = new HashSet<Integer>();
    set2.add(42);
    set = NotNull.set(set2);
    assertNotNull(set);
    assertEquals(set, set2);
}
Example 68
Project: SmartAndroidSource-master  File: ExceptionToResourceMapping.java View source code
/** Mapping without checking the cause (done in mapThrowable). */
protected Integer mapThrowableFlat(Throwable throwable) {
    Class<? extends Throwable> throwableClass = throwable.getClass();
    Integer resId = throwableToMsgIdMap.get(throwableClass);
    if (resId == null) {
        Class<? extends Throwable> closestClass = null;
        Set<Entry<Class<? extends Throwable>, Integer>> mappings = throwableToMsgIdMap.entrySet();
        for (Entry<Class<? extends Throwable>, Integer> mapping : mappings) {
            Class<? extends Throwable> candidate = mapping.getKey();
            if (candidate.isAssignableFrom(throwableClass)) {
                if (closestClass == null || closestClass.isAssignableFrom(candidate)) {
                    closestClass = candidate;
                    resId = mapping.getValue();
                }
            }
        }
    }
    return resId;
}
Example 69
Project: fenixedu-cms-master  File: CMSInitializer.java View source code
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
    if (c != null) {
        for (Class<?> type : c) {
            if (type.isAnnotationPresent(ComponentType.class)) {
                Component.register(type);
            }
            if (type.isAnnotationPresent(RegisterSiteTemplate.class)) {
                RegisterSiteTemplate annotation = type.getAnnotation(RegisterSiteTemplate.class);
                Site.register(annotation.type(), type);
            }
        }
    }
    registerDefaultTheme(ctx);
}
Example 70
Project: open-mika-master  File: CertStoreCollectionSpi.java View source code
public Collection engineGetCertificates(CertSelector selector) throws CertStoreException {
    Set col = new HashSet();
    Iterator iter = params.getCollection().iterator();
    if (selector == null) {
        while (iter.hasNext()) {
            Object obj = iter.next();
            if (obj instanceof Certificate) {
                col.add(obj);
            }
        }
    } else {
        while (iter.hasNext()) {
            Object obj = iter.next();
            if ((obj instanceof Certificate) && selector.match((Certificate) obj)) {
                col.add(obj);
            }
        }
    }
    return col;
}
Example 71
Project: streamex-master  File: InternalsTest.java View source code
@Test
public void testArrayCollection() {
    Collection<Object> collection = new ArrayCollection(new Object[] { "1", "2" });
    List<Object> list = new LinkedList<>(collection);
    assertEquals("1", list.get(0));
    assertEquals("2", list.get(1));
    List<Object> list2 = new ArrayList<>(collection);
    assertEquals("1", list.get(0));
    assertEquals("2", list.get(1));
    assertEquals(list2, list);
    Set<Object> set = new HashSet<>(collection);
    assertTrue(set.contains("1"));
    assertTrue(set.contains("2"));
    assertEquals(2, set.size());
}
Example 72
Project: commons-eid-master  File: StringUtils.java View source code
public static void printTerminalSet(final Set<CardTerminal> set) {
    final StringBuilder overviewLine = new StringBuilder();
    for (CardTerminal terminal : set) {
        overviewLine.append("[");
        overviewLine.append(terminal.getName());
        overviewLine.append("] ");
    }
    System.out.println(overviewLine.toString());
}
Example 73
Project: databus-master  File: VersionedSchemaSetStatus.java View source code
@Override
public String[] getLoadedSchemas() {
    Set<String> schemaBaseNames = _schemaSet.getSchemaBaseNames();
    String[] results = new String[schemaBaseNames.size()];
    int idx = 0;
    for (String baseName : schemaBaseNames) {
        StringBuilder b = new StringBuilder(1000);
        b.append(baseName);
        b.append(": ");
        SortedMap<VersionedSchemaId, VersionedSchema> versions = _schemaSet.getAllVersionsByName(baseName);
        boolean isFirst = true;
        for (Entry<VersionedSchemaId, VersionedSchema> vs : versions.entrySet()) {
            if (!isFirst)
                b.append(", ");
            isFirst = false;
            b.append(vs.getKey().getVersion());
        }
        results[idx++] = b.toString();
    }
    return results;
}
Example 74
Project: raven-aws-emr-kissmetrics-mapreduce-parser-redshift-master  File: KissmetricsJsonToSchemaMapper.java View source code
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
    String s = value.toString();
    JSONParser jsonParser = new JSONParser();
    try {
        JSONObject jsonObject = (JSONObject) jsonParser.parse(s);
        Set<String> keyset = jsonObject.keySet();
        String jsonValue = "";
        for (String jsonkey : keyset) {
            jsonValue = (String) jsonObject.get(jsonkey).toString();
            if (jsonValue == null || jsonValue == "") {
                jsonValue = "";
            }
            String lenValue = String.valueOf(jsonValue.length());
            if (lenValue == null || lenValue == "") {
                lenValue = "0";
            }
            context.write(new Text(jsonkey), new Text("1\t" + lenValue));
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}
Example 75
Project: gs-collections-master  File: SetIterate.java View source code
/**
     * @see Collection#removeAll(Collection)
     * @since 1.0
     */
public static boolean removeAllIterable(Set<?> collection, Iterable<?> iterable) {
    if (iterable instanceof Set<?> && ((Set<?>) iterable).size() > collection.size()) {
        boolean modified = false;
        Iterator<?> e = collection.iterator();
        while (e.hasNext()) {
            if (((Set<?>) iterable).contains(e.next())) {
                e.remove();
                modified = true;
            }
        }
        return modified;
    }
    boolean modified = false;
    for (Object each : iterable) {
        if (collection.remove(each)) {
            modified = true;
        }
    }
    return modified;
}
Example 76
Project: Eclipse-Postfix-Code-Completion-master  File: ResourceProcessors.java View source code
private static void computeNatures(Set<String> result, Set<IProject> visitedProjects, IProject focus) throws CoreException {
    if (visitedProjects.contains(focus))
        return;
    String[] pns = focus.getDescription().getNatureIds();
    for (int p = 0; p < pns.length; p++) {
        result.add(pns[p]);
    }
    visitedProjects.add(focus);
    IProject[] referencing = focus.getReferencingProjects();
    for (int i = 0; i < referencing.length; i++) {
        computeNatures(result, visitedProjects, referencing[i]);
    }
}
Example 77
Project: btpka3.github.com-master  File: TestRepo.java View source code
public static void main(String[] args) {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserRepository userRepo = ctx.getBean("userRepository", UserRepository.class);
    // insert
    int num = 0;
    Set<String> tags = new HashSet<String>(2);
    tags.add("tag" + num + ".3");
    tags.add("tag" + num + ".4");
    List<String> addrs = new ArrayList<String>(2);
    addrs.add("addr" + num + ".3");
    addrs.add("addr" + num + ".4");
    Map<String, String> extra = new HashMap<String, String>(2);
    extra.put("key" + num + ".3", "value" + num + ".3");
    extra.put("key" + num + ".4", "value" + num + ".4");
    User u1 = new User();
    final User.Pk pk = new User.Pk("2", "sid0");
    u1.setPk(pk);
    u1.setTags(tags);
    u1.setAddrs(addrs);
    u1.setExtra(extra);
    u1.setMemo("memo" + num);
    userRepo.save(u1);
    System.out.println("insert : " + u1);
    // update
    User u2 = new User();
    u2.setPk(pk);
    u2.setMemo("memo0_111");
    userRepo.save(u2);
    System.out.println("update : " + u2);
    // query
    User u3 = userRepo.findOne(pk);
    System.out.println("select : " + u3);
    // count
    System.out.println("count : " + userRepo.count());
    // custom findBy
    // List<User> userList = userRepo.findByName("name0");
    // System.out.println("findByName : " + userList);
    // delete
    userRepo.delete(pk);
    System.out.println("delete : " + pk);
    CassandraOperations cassandraOps = ctx.getBean("cassandraTemplate", CassandraOperations.class);
    cassandraOps.getSession().getCluster().close();
    ctx.close();
}
Example 78
Project: Payara-master  File: CleanupPostBoot.java View source code
@Override
public void event(Event event) {
    if (event.is(EventTypes.SERVER_READY)) {
        logger.info("Cleaning JarFileFactory Cache to prevent jar FD leaks");
        try {
            // Ensure JarFile is closed
            Class clazz = Class.forName("sun.net.www.protocol.jar.JarFileFactory", true, URL.class.getClassLoader());
            Field fields[] = clazz.getDeclaredFields();
            for (Field field : fields) {
                if ("fileCache".equals(field.getName())) {
                    field.setAccessible(true);
                    HashMap<String, JarFile> files = (HashMap<String, JarFile>) field.get(null);
                    Set<JarFile> jars = new HashSet<>();
                    jars.addAll(files.values());
                    for (JarFile file : jars) {
                        file.close();
                    }
                }
            }
        } catch (ClassNotFoundExceptionIllegalAccessException | SecurityException | IllegalArgumentException |  ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }
}
Example 79
Project: keycloak-master  File: PairwiseClientValidator.java View source code
public static boolean validate(KeycloakSession session, ClientRepresentation client, ValidationMessages messages) {
    String rootUrl = client.getRootUrl();
    Set<String> redirectUris = new HashSet<>();
    boolean valid = true;
    List<ProtocolMapperRepresentation> foundPairwiseMappers = PairwiseSubMapperUtils.getPairwiseSubMappers(client);
    for (ProtocolMapperRepresentation foundPairwise : foundPairwiseMappers) {
        String sectorIdentifierUri = PairwiseSubMapperHelper.getSectorIdentifierUri(foundPairwise);
        if (client.getRedirectUris() != null)
            redirectUris.addAll(client.getRedirectUris());
        valid = valid && validate(session, rootUrl, redirectUris, sectorIdentifierUri, messages);
    }
    return true;
}
Example 80
Project: android-platform-tools-base-master  File: SdkManagerTest7.java View source code
public void testSdkManager_getBuildTools() {
    // There is no build-tools folder in this repository.
    SdkManager sdkman = getSdkManager();
    Set<FullRevision> v = sdkman.getBuildTools();
    // Make sure we get a stable set -- hashmap order isn't stable and can't be used in tests.
    if (!(v instanceof TreeSet<?>)) {
        v = Sets.newTreeSet(v);
    }
    // no errors in the logger
    assertEquals("", getLog().toString());
    assertEquals("[]", Arrays.toString(v.toArray()));
    assertNull(sdkman.getBuildTool(new FullRevision(1)));
    assertNull(sdkman.getBuildTool(new FullRevision(3, 0, 0)));
    assertNull(sdkman.getBuildTool(new FullRevision(12, 3, 4, 5)));
}
Example 81
Project: dashbuilder-master  File: DataSetProviderRegistryCDITest.java View source code
@Test
public void testRegistryDataSetDef() throws Exception {
    Set<DataSetProviderType> typeList = dataSetProviderRegistry.getAvailableTypes();
    assertTrue(typeList.contains(DataSetProviderType.STATIC));
    assertTrue(typeList.contains(DataSetProviderType.BEAN));
    assertTrue(typeList.contains(DataSetProviderType.CSV));
    assertTrue(typeList.contains(DataSetProviderType.SQL));
    assertTrue(typeList.contains(DataSetProviderType.ELASTICSEARCH));
    // In CDI contexts, DataSetProvider implementations are automatically registered
    assertTrue(typeList.contains(CustomDataSetProvider.TYPE));
    DataSetProvider customProvider = dataSetProviderRegistry.getDataSetProvider(CustomDataSetProvider.TYPE);
    assertNotNull(customProvider);
}
Example 82
Project: OpenClinica-master  File: LdapUserController.java View source code
@RequestMapping("/listLdapUsers")
public String listLdapUsers(HttpServletRequest req, @RequestParam(value = "filter", required = false) String filter) {
    // If no filter is provided, just render the page without results table
    if (!StringUtils.isEmpty(filter)) {
        // Retrieve existing users to remove them from LDAP search results.
        @SuppressWarnings("unchecked") Collection<UserAccountBean> existingAccounts = userAccountDao.findAll();
        Set<String> existingUsernames = new HashSet<String>(existingAccounts.size());
        for (UserAccountBean existingAccount : existingAccounts) {
            existingUsernames.add(existingAccount.getName());
        }
        req.setAttribute("memberList", ldapUserService.listNewUsers(filter, existingUsernames));
    }
    return PAGE_LIST_LDAP_USERS;
}
Example 83
Project: jena-master  File: IndexFactory.java View source code
// Contribution from P Gearon (@quoll)
public static IndexTable createIndex(Set<Var> commonVars, QueryIterator data) {
    try {
        if (commonVars.size() == 1) {
            return new SetIndexTable(commonVars, data);
        } else {
            return new HashIndexTable(commonVars, data);
        }
    } catch (MissingBindingException e) {
        return new LinearIndex(commonVars, data, e.getData(), e.getMap());
    }
}
Example 84
Project: c10n-master  File: DefaultLocaleMapping.java View source code
@Override
public Locale findClosestMatch(Set<Locale> fromSet, Locale forLocale) {
    String variant = forLocale.getDisplayVariant();
    String country = forLocale.getCountry();
    String language = forLocale.getLanguage();
    Locale[] c = new Locale[4];
    if (null != variant && !variant.isEmpty()) {
        c[0] = forLocale;
    }
    if (null != country && !country.isEmpty()) {
        c[1] = new Locale(language, country);
    }
    if (null != language && !language.isEmpty()) {
        c[2] = new Locale(language);
    }
    c[3] = Locale.ROOT;
    for (Locale candidateLocale : c) {
        if (fromSet.contains(candidateLocale)) {
            return candidateLocale;
        }
    }
    //This code intentionally uses Locale.getDefault()
    //in order to behave in the same was as the default
    //resource bundle locale search mechanism.
    //source: http://docs.oracle.com/javase/tutorial/i18n/resbundle/concept.html
    Locale systemDefaultLocale = Locale.getDefault();
    if (!systemDefaultLocale.equals(forLocale)) {
        return findClosestMatch(fromSet, systemDefaultLocale);
    }
    return null;
}
Example 85
Project: netty4.0.27Learn-master  File: IdentityCipherSuiteFilter.java View source code
@Override
public String[] filterCipherSuites(Iterable<String> ciphers, List<String> defaultCiphers, Set<String> supportedCiphers) {
    if (ciphers == null) {
        return defaultCiphers.toArray(new String[defaultCiphers.size()]);
    } else {
        List<String> newCiphers = new ArrayList<String>(supportedCiphers.size());
        for (String c : ciphers) {
            if (c == null) {
                break;
            }
            newCiphers.add(c);
        }
        return newCiphers.toArray(new String[newCiphers.size()]);
    }
}
Example 86
Project: org.eclipse.ecr-master  File: TestSidGenerator.java View source code
public void testGeneratorReset() throws Exception {
    Set<Long> ids = new HashSet<Long>();
    for (int i = 0; i < 1000; i++) {
        long id = SIDGenerator.next();
        if (!ids.add(id)) {
            fail("ID already generated");
        }
    }
    // change the counter to a value near the max one to force a counter reset
    Field field = SIDGenerator.class.getDeclaredField("count");
    field.setAccessible(true);
    field.set(null, Integer.MAX_VALUE - 1000);
    for (int i = 0; i < 3000; i++) {
        long id = SIDGenerator.next();
        if (!ids.add(id)) {
            fail("ID already generated");
        }
    }
    Integer counter = (Integer) field.get(null);
    assertEquals(2000, counter.intValue());
}
Example 87
Project: crux-master  File: Services.java View source code
/**
	 * Return the service that implements the interface informed.
	 * @param interfaceName
	 * @return
	 */
public static Class<?> getService(String interfaceName) {
    try {
        Set<String> serviceNames = ClassScanner.searchClassesByInterface(Class.forName(interfaceName));
        if (serviceNames != null) {
            for (String service : serviceNames) {
                Class<?> serviceClass = Class.forName(service);
                if (!serviceClass.isInterface()) {
                    return serviceClass;
                }
            }
        }
        logger.info("No implementation class found to service interface: [" + interfaceName + "].");
    } catch (ClassNotFoundException e) {
        logger.error("Error creating service [" + interfaceName + "].", e);
    }
    return null;
}
Example 88
Project: GlowstonePlusPlus-master  File: PlayerSwingArmHandler.java View source code
@Override
public void handle(GlowSession session, PlayerSwingArmMessage message) {
    final GlowPlayer player = session.getPlayer();
    Block block;
    try {
        block = player.getTargetBlock((Set<Material>) null, 6);
    } catch (IllegalStateException ex) {
        block = null;
    }
    if (block == null || block.isEmpty()) {
        if (EventFactory.onPlayerInteract(player, Action.LEFT_CLICK_AIR).useItemInHand() == Event.Result.DENY)
            return;
    // todo: item interactions with air
    }
    if (!EventFactory.callEvent(new PlayerAnimationEvent(player)).isCancelled()) {
        // play the animation to others
        AnimateEntityMessage toSend = new AnimateEntityMessage(player.getEntityId(), AnimateEntityMessage.OUT_SWING_ARM);
        for (GlowPlayer observer : player.getWorld().getRawPlayers()) {
            if (observer != player && observer.canSeeEntity(player)) {
                observer.getSession().send(toSend);
            }
        }
    }
}
Example 89
Project: hibernate-core-ogm-master  File: JavassistHelper.java View source code
public static FieldInterceptor injectFieldInterceptor(Object entity, String entityName, Set uninitializedFieldNames, SessionImplementor session) {
    FieldInterceptorImpl fieldInterceptor = new FieldInterceptorImpl(session, uninitializedFieldNames, entityName);
    ((FieldHandled) entity).setFieldHandler(fieldInterceptor);
    return fieldInterceptor;
}
Example 90
Project: i2p.android.base-master  File: I2PreferenceFragment.java View source code
@Override
public void onPause() {
    List<Properties> lProps = Util.getPropertiesFromPreferences(getActivity());
    Properties props = lProps.get(0);
    Properties propsToRemove = lProps.get(1);
    Properties logSettings = lProps.get(2);
    Set toRemove = propsToRemove.keySet();
    boolean restartRequired = Util.checkAndCorrectRouterConfig(getActivity(), props, toRemove);
    // Apply new config if we are running.
    RouterContext rCtx = Util.getRouterContext();
    if (rCtx != null) {
        rCtx.router().saveConfig(props, toRemove);
        // Merge in new log settings
        saveLoggingChanges(rCtx, logSettings);
    } else {
        // Merge in new config settings, write the file.
        Util.mergeResourceToFile(getActivity(), Util.getFileDir(getActivity()), "router.config", R.raw.router_config, props, toRemove);
        // Merge in new log settings
        saveLoggingChanges(I2PAppContext.getGlobalContext(), logSettings);
    }
    // Store the settings in Android
    super.onPause();
    if (restartRequired)
        Toast.makeText(getActivity(), R.string.settings_router_restart_required, Toast.LENGTH_LONG).show();
}
Example 91
Project: cdt-tests-runner-master  File: DsfDebugUITools.java View source code
public void run() {
    IWorkbenchActivitySupport workbenchActivitySupport = PlatformUI.getWorkbench().getActivitySupport();
    IActivityManager activityManager = workbenchActivitySupport.getActivityManager();
    Set<String> enabledActivityIds = new HashSet<String>(activityManager.getEnabledActivityIds());
    boolean changed = false;
    if (enableit)
        changed = enabledActivityIds.add(activityID);
    else
        changed = enabledActivityIds.remove(activityID);
    if (changed)
        workbenchActivitySupport.setEnabledActivityIds(enabledActivityIds);
}
Example 92
Project: elpaaso-core-master  File: RouteMappingProjectionRule.java View source code
@Override
public void apply(LogicalDeployment ld, TechnicalDeployment td, ProjectionContext projectionContext) {
    // list logical web guiservices
    Set<LogicalWebGUIService> logicalWebGUIServices = ld.listLogicalServices(LogicalWebGUIService.class);
    for (LogicalWebGUIService logicalWebGUIService : logicalWebGUIServices) {
        //list processing nodes associated to the logical web gui service
        Set<ProcessingNode> processingNodes = logicalWebGUIService.listDependentProcessingNodes();
        for (ProcessingNode processingNode : processingNodes) {
            //get associated app
            Set<App> apps = td.listXaasSubscriptionTemplates(App.class, processingNode.getName());
            for (App app : apps) {
                // get associated routes
                Set<Route> routes = td.listXaasSubscriptionTemplates(Route.class, logicalWebGUIService.getName());
                for (Route route : routes) {
                    app.mapRoute(route);
                }
            }
        }
    }
}
Example 93
Project: xchain-master  File: DependencyCycleException.java View source code
public static String createMessage(String message, Map cycle) {
    StringBuffer sb = new StringBuffer();
    sb.append(message).append("\n");
    Iterator cycleIterator = cycle.entrySet().iterator();
    while (cycleIterator.hasNext()) {
        Map.Entry cycleEntry = (Map.Entry) cycleIterator.next();
        sb.append("  ");
        sb.append(cycleEntry.getKey());
        sb.append(" dependends on ( ");
        Iterator dependencyIterator = ((Set) cycleEntry.getValue()).iterator();
        while (dependencyIterator.hasNext()) {
            sb.append(dependencyIterator.next());
            if (dependencyIterator.hasNext()) {
                sb.append(", ");
            }
        }
        sb.append(" )");
        if (cycleIterator.hasNext()) {
            sb.append("\n");
        }
    }
    return sb.toString();
}
Example 94
Project: trie4j-master  File: AbstractSetWikipediaSerializeTest.java View source code
@SuppressWarnings("unchecked")
@Test
public void test() throws Exception {
    WikipediaTitles wt = new WikipediaTitles();
    Set<String> set = wt.insertTo(set());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    LapTimer lt = new LapTimer();
    oos.writeObject(set);
    oos.flush();
    long wd = lt.lapMillis();
    byte[] serialized = baos.toByteArray();
    lt.reset();
    Set<String> t = (Set<String>) new ObjectInputStream(new ByteArrayInputStream(serialized)).readObject();
    long rd = lt.lapMillis();
    long vd = wt.assertAllContains(t);
    System.out.println(String.format("%s%s, size: %d, write(ms): %d, read(ms): %d, verify(ms): %d.", set.getClass().getSimpleName(), "", serialized.length, wd, rd, vd));
}
Example 95
Project: property-db-master  File: RoundRobinScheduler.java View source code
@Override
public Filter scheduleNextNode() {
    Set<Filter> all_filters = getGraph().getFilters();
    if (mLastPos >= all_filters.size())
        mLastPos = -1;
    int pos = 0;
    Filter first = null;
    int firstNdx = -1;
    for (Filter filter : all_filters) {
        if (filter.canProcess()) {
            if (pos <= mLastPos) {
                if (first == null) {
                    // store the first available filter
                    first = filter;
                    firstNdx = pos;
                }
            } else {
                // return the next available filter since last
                mLastPos = pos;
                return filter;
            }
        }
        pos++;
    }
    // going around from the beginning
    if (first != null) {
        mLastPos = firstNdx;
        return first;
    }
    // position.
    return null;
}
Example 96
Project: org.ops4j.pax.url-master  File: WarWrapTest.java View source code
@Test
public void shouldNotProduceDuplicatePackageImports() throws IOException {
    System.setProperty("java.protocol.handler.pkgs", "org.ops4j.pax.url");
    URL url = new URL("war:file:target/dependency/wicket-examples.war");
    InputStream is = url.openStream();
    JarInputStream jis = new JarInputStream(is);
    Manifest manifest = jis.getManifest();
    String importPackage = manifest.getMainAttributes().getValue("Import-Package");
    Set<String> packages = new HashSet<String>();
    for (String directive : importPackage.split(",")) {
        String[] parts = directive.split(";");
        String pkg = parts[0];
        assertThat("duplicate package " + pkg, packages.contains(pkg), is(false));
        packages.add(pkg);
    }
    jis.close();
}
Example 97
Project: mldht-master  File: RoutingTableTest.java View source code
void test(Function<Key, RoutingTableEntry> f) {
    for (int i = 0; i < 800; i++) {
        Set<RoutingTableEntry> toRemove = new HashSet<>(10);
        List<RoutingTableEntry> toAdd = new ArrayList<>(20);
        assertEquals(table.entries[0], f.apply(Key.MIN_KEY));
        assertEquals(table.entries[table.entries.length - 1], f.apply(Key.MAX_KEY));
        for (int j = 0; j < 7; j++) {
            Key k = Key.createRandomKey();
            RoutingTableEntry entry = f.apply(k);
            assertTrue(entry.prefix.isPrefixOf(k));
            assertEquals(entry, f.apply(entry.prefix.first()));
            assertEquals(entry, f.apply(entry.prefix.last()));
            if (toRemove.add(entry)) {
                toAdd.add(new RoutingTableEntry(entry.prefix.splitPrefixBranch(false), new KBucket(), ( x) -> false));
                toAdd.add(new RoutingTableEntry(entry.prefix.splitPrefixBranch(true), new KBucket(), ( x) -> false));
            }
        }
        table = table.modify(toRemove, toAdd);
    }
}
Example 98
Project: earthsci-master  File: DiscoverySeeder.java View source code
@Override
public void seed(Element element, URL context) {
    Set<String> serviceUrls = new HashSet<String>();
    for (IDiscoveryService service : DiscoveryServiceManager.getServices()) {
        serviceUrls.add(service.getServiceURL().toExternalForm());
    }
    Element[] children = XmlUtil.getElements(element);
    for (Element child : children) {
        try {
            List<IDiscoveryService> services = DiscoveryServiceManager.loadServices(child);
            for (IDiscoveryService service : services) {
                if (!serviceUrls.contains(service.getServiceURL().toExternalForm())) {
                    DiscoveryServiceManager.addService(service);
                }
            }
        } catch (PersistenceException e) {
            logger.error("Error unpersisting discovery services from seed file", e);
        }
    }
}
Example 99
Project: MyTracks-master  File: BluetoothDeviceUtils.java View source code
/**
   * Populates the device names and the device addresses with all the suitable
   * bluetooth devices.
   * 
   * @param bluetoothAdapter the bluetooth adapter
   * @param deviceNames list of device names
   * @param deviceAddresses list of device addresses
   */
public static void populateDeviceLists(BluetoothAdapter bluetoothAdapter, List<String> deviceNames, List<String> deviceAddresses) {
    // Ensure the bluetooth adapter is not in discovery mode.
    bluetoothAdapter.cancelDiscovery();
    Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
    for (BluetoothDevice device : pairedDevices) {
        BluetoothClass bluetoothClass = device.getBluetoothClass();
        if (bluetoothClass != null) {
            // Not really sure what we want, but I know what we don't want.
            switch(bluetoothClass.getMajorDeviceClass()) {
                case BluetoothClass.Device.Major.COMPUTER:
                case BluetoothClass.Device.Major.PHONE:
                    break;
                default:
                    deviceAddresses.add(device.getAddress());
                    deviceNames.add(device.getName());
            }
        }
    }
}
Example 100
Project: platform_tools_adt_idea-master  File: AndroidSourceItemsProvider.java View source code
@NotNull
@Override
public Collection<? extends PackagingSourceItem> getSourceItems(@NotNull ArtifactEditorContext editorContext, @NotNull Artifact artifact, @Nullable PackagingSourceItem parent) {
    if (parent instanceof ModuleSourceItemGroup && !AndroidArtifactUtil.containsAndroidPackage(editorContext, artifact)) {
        final Module module = ((ModuleSourceItemGroup) parent).getModule();
        final Set<AndroidFacet> facets = new HashSet<AndroidFacet>(editorContext.getFacetsProvider().getFacetsByType(module, AndroidFacet.ID));
        if (facets.size() > 0) {
            return Collections.singletonList(new FacetBasedSourceItem<AndroidFacet>(this, facets.iterator().next()));
        }
    }
    return Collections.emptyList();
}
Example 101
Project: milton2-master  File: SimplePropertyAuthoriser.java View source code
@Override
public Set<CheckResult> checkPermissions(Request request, Method method, PropertyPermission perm, Set<QName> fields, Resource resource) {
    Auth auth = request.getAuthorization();
    if (auth != null && auth.getTag() != null) {
        return null;
    } else {
        Set<CheckResult> s = new HashSet<CheckResult>();
        for (QName qn : fields) {
            s.add(new CheckResult(qn, Status.SC_UNAUTHORIZED, "Not logged in", resource));
        }
        return s;
    }
}