public static <T> List<T> getInstancesOfAnnotation(ASMDataTable asmDataTable, Class annotationClass, Class<T> instanceClass) { String annotationClassName = annotationClass.getCanonicalName(); Set<ASMDataTable.ASMData> asmDatas = asmDataTable.getAll(annotationClassName); List<T> instances = new ArrayList<>(); for (ASMDataTable.ASMData asmData : asmDatas) { try { Class<?> asmClass = Class.forName(asmData.getClassName()); Class<? extends T> asmInstanceClass = asmClass.asSubclass(instanceClass); T instance = asmInstanceClass.newInstance(); instances.add(instance); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | LinkageError e) { HarshenCastle.LOGGER.error("Failed to load: {}", asmData.getClassName(), e); } } return instances; }
public static String buildQuery(Map<String, String> params, String charset) throws IOException { if (params == null || params.isEmpty()) { return null; } StringBuilder query = new StringBuilder(); Set<Entry<String, String>> entries = params.entrySet(); boolean hasParam = false; for (Entry<String, String> entry : entries) { String name = entry.getKey(); String value = entry.getValue(); // 忽略参数名或参数值为空的参数 if (StringUtils.isAnyEmpty(name, value)) { if (hasParam) { query.append("&"); } else { hasParam = true; } query.append(name).append("=").append(URLEncoder.encode(value, charset)); } } return query.toString(); }
private void executeWithThrowException(FunctionContext context) { DistributedSystem ds = InternalDistributedSystem.getAnyInstance(); RegionFunctionContext rfContext = (RegionFunctionContext) context; LogWriter logger = ds.getLogWriter(); logger.fine("Executing executeWithThrowException in TestFunction on Member : " + ds.getDistributedMember() + "with Context : " + context); if (context.getArguments() instanceof Boolean) { logger.fine("MyFunctionExecutionException Exception is intentionally thrown"); throw new MyFunctionExecutionException("I have been thrown from TestFunction"); } else if (rfContext.getArguments() instanceof Set) { Set origKeys = (Set) rfContext.getArguments(); for (Iterator i = origKeys.iterator(); i.hasNext();) { Region r = PartitionRegionHelper.getLocalDataForContext(rfContext); Object key = i.next(); Object val = r.get(key); if (val != null) { throw new MyFunctionExecutionException("I have been thrown from TestFunction"); } } } else { logger.fine("Result sent back :" + Boolean.FALSE); rfContext.getResultSender().lastResult(Boolean.FALSE); } }
public Set <String> getExtraOptionsLD( boolean debug, boolean coreCopied ) { String chipkitCoreDirectory = data.get("build.core.path"); String chipkitVariantDirectory = data.get("build.variant.path"); String ldScriptDirectory = data.get("build.ldscript_dir.path"); String ldscript = debug ? data.get("ldscript-debug") : data.get("ldscript"); String ldcommon = data.get("ldcommon"); Set <String> optionSet = new LinkedHashSet<>(); parseOptions( optionSet, data.get("compiler.c.elf.flags") ); removeRedundantCompilerOptions(optionSet); removeRedundantLinkerOptions(optionSet); optionSet.add("-mnewlib-libc"); if ( coreCopied ) { optionSet.add("-T\"" + ldscript + "\""); optionSet.add("-T\"" + ldcommon + "\""); } else { Path ldcommonPath = Paths.get( chipkitCoreDirectory, ldcommon ); Path ldscriptPath = Paths.get( debug && !ldScriptDirectory.isEmpty() ? ldScriptDirectory : chipkitCoreDirectory, ldscript ); if ( !Files.exists(ldscriptPath) && !debug ) { ldscriptPath = Paths.get( chipkitVariantDirectory, ldscript ); } optionSet.add("-T\"" + ldscriptPath.toString() + "\""); optionSet.add("-T\"" + ldcommonPath.toString() + "\""); } return optionSet; }
public void testBasicSubprojects() throws Exception { Set subprojects = simpleSubprojects.getSubprojects(); assertTrue("no subprojects for simple", subprojects.isEmpty()); assertEquals("no subprojects for simple", Collections.EMPTY_SET, subprojects); assertTrue("no subprojects for simple", subprojects.isEmpty()); subprojects = extsrcrootSubprojects.getSubprojects(); assertFalse("extsrcroot has simple as a subproject", subprojects.isEmpty()); assertEquals("extsrcroot has simple as a subproject", Collections.singleton(simple), subprojects); assertFalse("extsrcroot has simple as a subproject", subprojects.isEmpty()); subprojects = simple2Subprojects.getSubprojects(); assertTrue("no subprojects for simple", subprojects.isEmpty()); assertEquals("no subprojects for simple", Collections.EMPTY_SET, subprojects); assertTrue("no subprojects for simple", subprojects.isEmpty()); }
private static boolean diff(PrintWriter writer, PgDiffArguments arguments) throws InterruptedException, IOException, URISyntaxException { PgDiffScript script; try (PrintWriter encodedWriter = getDiffWriter(arguments)) { script = PgDiff.createDiff(encodedWriter != null ? encodedWriter : writer, arguments); } if (arguments.isSafeMode()) { Set<DangerStatement> dangerTypes = script.findDangers(arguments.getAllowedDangers()); if (!dangerTypes.isEmpty()) { String msg = MessageFormat.format(Messages.Main_danger_statements, dangerTypes.stream().map(DangerStatement::name) .collect(Collectors.joining(", "))); writer.println(msg); try (PrintWriter encodedWriter = getDiffWriter(arguments)) { if (encodedWriter != null) { encodedWriter.println("-- " + msg); } } return false; } } return true; }
private void checkIfGivenExpressionIsValid(Map<String, Class<?>> inputSchemaFields, Set<String> errors, ExpressionData expressionData, ErrorLogTableViewer errorLogTableViewer) { if(StringUtils.isBlank(expressionData.getExpressionEditorData().getExpression())){ errors.add(Messages.EXPRESSION_IS_BLANK); } else{ Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { ExpressionEditorUtil.validateExpression(expressionData.getExpressionEditorData().getExpression(), inputSchemaFields,expressionData.getExpressionEditorData()); if(!expressionData.getExpressionEditorData().isValid()){ errors.add(Messages.EXPRESSION_IS_INVALID); errorLogTableViewer.refresh(); } } }); } }
/** * Creates an instance of {@code PKIXParameters} that * populates the set of most-trusted CAs from the trusted * certificate entries contained in the specified {@code KeyStore}. * Only keystore entries that contain trusted {@code X509Certificates} * are considered; all other certificate types are ignored. * * @param keystore a {@code KeyStore} from which the set of * most-trusted CAs will be populated * @throws KeyStoreException if the keystore has not been initialized * @throws InvalidAlgorithmParameterException if the keystore does * not contain at least one trusted certificate entry * @throws NullPointerException if the keystore is {@code null} */ public PKIXParameters(KeyStore keystore) throws KeyStoreException, InvalidAlgorithmParameterException { if (keystore == null) throw new NullPointerException("the keystore parameter must be " + "non-null"); Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>(); Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keystore.isCertificateEntry(alias)) { Certificate cert = keystore.getCertificate(alias); if (cert instanceof X509Certificate) hashSet.add(new TrustAnchor((X509Certificate)cert, null)); } } setTrustAnchors(hashSet); this.unmodInitialPolicies = Collections.<String>emptySet(); this.certPathCheckers = new ArrayList<PKIXCertPathChecker>(); this.certStores = new ArrayList<CertStore>(); }
@Override public List<String> resolve(Context context, List<String> expressions) { IndicesOptions options = context.getOptions(); MetaData metaData = context.getState().metaData(); if (options.expandWildcardsClosed() == false && options.expandWildcardsOpen() == false) { return expressions; } if (isEmptyOrTrivialWildcard(expressions)) { return resolveEmptyOrTrivialWildcard(options, metaData, true); } Set<String> result = innerResolve(context, expressions, options, metaData); if (result == null) { return expressions; } if (result.isEmpty() && !options.allowNoIndices()) { IndexNotFoundException infe = new IndexNotFoundException((String)null); infe.setResources("index_or_alias", expressions.toArray(new String[0])); throw infe; } return new ArrayList<>(result); }
private static ResourcePoolManager createPoolManager(Set<Archive> archives, Map<String, List<Entry>> entriesForModule, ByteOrder byteOrder, BasicImageWriter writer) throws IOException { ResourcePoolManager resources = new ResourcePoolManager(byteOrder, new StringTable() { @Override public int addString(String str) { return writer.addString(str); } @Override public String getString(int id) { return writer.getString(id); } }); for (Archive archive : archives) { String mn = archive.moduleName(); entriesForModule.get(mn).stream() .map(e -> new ArchiveEntryResourcePoolEntry(mn, e.getResourcePoolEntryName(), e)) .forEach(resources::add); } return resources; }
/** * Checks that the given core is unsatisfiable with respect to the given * bounds. * * @return true if the core is correct; false otherwise */ static boolean checkCorrect(Set<Formula> core, Bounds bounds) { System.out.print("checking correctness ... "); final long start = System.currentTimeMillis(); Solver solver = solver(); solver.options().setSolver(SATFactory.MiniSat); final Solution sol = solver.solve(Formula.and(core), bounds); final long end = System.currentTimeMillis(); if (sol.instance() == null) { System.out.println("correct (" + (end - start) + " ms)."); return true; } else { System.out.println("incorrect! (" + (end - start) + " ms). The core is satisfiable:"); System.out.println(sol); return false; } }
public Set<String> findContainers(Collection<EClass> collection, String selectedType) { Set<String> result = new HashSet<String>(); SigTrace typeTrace; try { typeTrace = getSigTraceByType(selectedType); } catch (TraceException e1) { return result; } EList<EClass> superTypes = typeTrace.getEClass().getEAllSuperTypes(); for (EClass eClass : collection) { for (EReference eReference : eClass.getEAllReferences()) { if (eReference.isContainment()) { try { if (superTypes.stream() .anyMatch(s -> s.getName().equals(eReference.getEReferenceType().getName()))) { result.add(getSigTraceByClassName(eClass.getName()).getSigType()); } } catch (TraceException e) { // no need to handle } } } } return result; }
@SuppressWarnings("unchecked") private Result computeNodeWildcard(Wildcard expr) { Result result = new Result(); LabelVar var = expr.getWildcardId(); Set<@NonNull TypeNode> candidates = new HashSet<>(); if (var.hasName()) { candidates.addAll((Collection<@NonNull TypeNode>) this.varTyping.get(var)); } else { candidates.addAll(this.typeGraph.nodeSet()); } TypeGuard guard = expr.getWildcardGuard(); for (TypeNode typeNode : guard.filter(candidates)) { result.add(typeNode, typeNode); } return result; }
@Override protected Set<TypeToken<? super T>> delegate() { ImmutableSet<TypeToken<? super T>> result = classes; if (result == null) { @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableList<TypeToken<? super T>> collectedTypes = (ImmutableList) TypeCollector.FOR_GENERIC_TYPE.classesOnly().collectTypes(TypeToken.this); return (classes = FluentIterable.from(collectedTypes) .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD) .toSet()); } else { return result; } }
public Response createPublicGroup(GroupCreateRequest request) { Set<Long> permissions = request.permissions.stream(). map(permission -> permission.getId()).collect(Collectors.toSet()); Set<Long> roles = request.roles.stream(). map(role -> role.getId()).collect(Collectors.toSet()); String error = validateCreateRequest(request.name, permissions, roles); if (StringUtils.isNoneEmpty(error)) { throw new WebApplicationException( error, Response.Status.BAD_REQUEST); } Group group = new Group(request.name); return updateOrCreateGroup(group, permissions, roles); }
/** * {@inheritDoc} */ @Override public void apply(RequestTemplate template) { String url = template.request().url(); if (urlFilter.accept(url)) { Set<Entry<String, String>> propagatedAttributes = copy(template); log.trace("Propagated outbound headers {} for url [{}].", propagatedAttributes, url); } else { log.trace("Propagation disabled for url [{}]", url); } }
public void loadBlocked(Set<Integer> blocked) { for (Integer id : blocked) { blockedIds.add(id); availabilityMap.set(id); } }
void visit(GeneratorAdapter mv, Set<String> strings, String className) { this.className = className; this.classData = AcesoProguardMap.instance().getClassData(className); if (classData == null) { throw new GradleException("can not find class: " + className + " , sure you aceso-mapping is right and this class not in blacklist."); } visitClassifier(mv, strings); }
@Override protected void updateGoalState(ClusterModel clusterModel, Set<String> excludedTopics) throws AnalysisInputException { // While proposals exclude the excludedTopics, the leader bytes in still considers replicas of the excludedTopics. if (!_overLimitBrokerIds.isEmpty()) { LOG.warn("There were still {} brokers over the limit.", _overLimitBrokerIds.size()); _succeeded = false; } finish(); }
PowerSet(Set<E> input) { ImmutableMap.Builder<E, Integer> builder = ImmutableMap.builder(); int i = 0; for (E e : checkNotNull(input)) { builder.put(e, i++); } this.inputSet = builder.build(); checkArgument(inputSet.size() <= 30, "Too many elements to create power set: %s > 30", inputSet.size()); }
@Override public void dataChanged ( final List<BrowserEntry> addedOrUpdated, final Set<String> removed, final boolean full ) { logger.debug ( "Browser data changed: {}, {}, {}", new Object[] { addedOrUpdated, removed, full } ); this.connection.handleBrowseDataChanged ( this, addedOrUpdated, removed, full ); }
public URL configure(URL url) { if (configuratorUrl == null || configuratorUrl.getHost() == null || url == null || url.getHost() == null) { return url; } if (Constants.ANYHOST_VALUE.equals(configuratorUrl.getHost()) || url.getHost().equals(configuratorUrl.getHost())) { String configApplication = configuratorUrl.getParameter(Constants.APPLICATION_KEY, configuratorUrl.getUsername()); String currentApplication = url.getParameter(Constants.APPLICATION_KEY, url.getUsername()); if (configApplication == null || Constants.ANY_VALUE.equals(configApplication) || configApplication.equals(currentApplication)) { if (configuratorUrl.getPort() == 0 || url.getPort() == configuratorUrl.getPort()) { Set<String> condtionKeys = new HashSet<String>(); condtionKeys.add(Constants.CATEGORY_KEY); condtionKeys.add(Constants.CHECK_KEY); condtionKeys.add(Constants.DYNAMIC_KEY); condtionKeys.add(Constants.ENABLED_KEY); for (Map.Entry<String, String> entry : configuratorUrl.getParameters().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key.startsWith("~") || Constants.APPLICATION_KEY.equals(key) || Constants.SIDE_KEY.equals(key)) { condtionKeys.add(key); if (value != null && ! Constants.ANY_VALUE.equals(value) && ! value.equals(url.getParameter(key.startsWith("~") ? key.substring(1) : key))) { return url; } } } return doConfigure(url, configuratorUrl.removeParameters(condtionKeys)); } } } return url; }
@Override public Set<String> keys() { if(role==TripleComponentRole.OBJECT && id>graph.getNShared()) { return Collections.emptySet(); } return new VertexPropertySet(this); }
@Test public void testGetAvailablePaymentTypesFromSupplier_NoRelationAllSupplierDefaults() throws Exception { Set<String> prodPt = new HashSet<>( Arrays.asList(BaseAdmUmTest.PAYMENT_TYPE_IDS_INV_DD)); Set<String> suppDefPt = new HashSet<>( Arrays.asList(BaseAdmUmTest.PAYMENT_TYPE_IDS)); // expected: intersect prodPt and suppDefPt Set<String> expPt = new HashSet<>( Arrays.asList(BaseAdmUmTest.PAYMENT_TYPE_IDS_INV_DD)); getAvailablePaymentTypesFromSupplier(prodPt, suppDefPt, false, expPt); }
public V putSingleValue(K key, V value) { Set<V> values = map.get(key); if (values == null) { values = new HashSet<V>(); map.put(key, values); } values.add(value); return value; }
@Test public void testContains() { Set<TestObject> set = redisson.getSet("set"); set.add(new TestObject("1", "2")); set.add(new TestObject("1", "2")); set.add(new TestObject("2", "3")); set.add(new TestObject("3", "4")); set.add(new TestObject("5", "6")); Assert.assertTrue(set.contains(new TestObject("2", "3"))); Assert.assertTrue(set.contains(new TestObject("1", "2"))); Assert.assertFalse(set.contains(new TestObject("1", "9"))); }
public User(String firstname, String lastname, String email, Set<String> roles) { super(); this.firstname = firstname; this.lastname = lastname; this.email = email; this.roles = roles; }
/** * TODO: Comment. * * @return */ public Set<ObjectName> getRootMBeanObjectNames() { if (isDestroyed()) { return null; } return _MBeanModelManager.findKeys(getData()); }
public void updatePeers() { Set<Peer> allPeers = Collections.synchronizedSet(new HashSet<>()); arkNetwork.getHosts().parallelStream().forEach(host -> { try { String baseUrl = arkNetwork.getHttpScheme() + "://" + host.getHostname() + ":" + host.getPort(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("nethash", arkNetwork.getNetHash()); headers.set("version", arkNetwork.getVersion()); headers.set("port", arkNetwork.getPort()); HttpEntity<Void> requestEntity = new HttpEntity<>(headers); PeerList peerList = restTemplate .exchange( baseUrl + "/peer/list", HttpMethod.GET, requestEntity, PeerList.class ) .getBody(); Set<Peer> peers = peerList.getPeers().stream() .filter(peer -> Objects.equals(peer.getStatus(), "OK")) .collect(Collectors.toSet()); allPeers.addAll(peers); } catch (Exception e) { // ignore failed hosts } }); Set<Peer> newPeers = new HashSet<>(peers); newPeers.retainAll(allPeers); newPeers.addAll(allPeers); peers.addAll(newPeers); peers.retainAll(newPeers); log.info("Updated peers: "); log.info(new NiceObjectMapper(new ObjectMapper()).writeValueAsString(peers)); }
@Override Iterable<Set<Location>> listLocationsForModules() { if (searchPath == null) return Collections.emptyList(); return ModulePathIterator::new; }
private Set<SourceNodeFactory> findSourcesForProcessorParents(final String[] parents) { final Set<SourceNodeFactory> sourceNodes = new HashSet<>(); for (String parent : parents) { final NodeFactory nodeFactory = nodeFactories.get(parent); if (nodeFactory instanceof SourceNodeFactory) { sourceNodes.add((SourceNodeFactory) nodeFactory); } else if (nodeFactory instanceof ProcessorNodeFactory) { sourceNodes.addAll(findSourcesForProcessorParents(((ProcessorNodeFactory) nodeFactory).parents)); } } return sourceNodes; }
private static Iterable<String> getCoveredPackages(Module mod, Source[] sources) { if (mod != null) { Set<String> ret = mod.getCoveredPackages(); if (ret != null) { return ret; } } Set<String> known = new HashSet<String>(); Manifest m = mod == null ? null : mod.getManifest(); if (m != null) { Attributes attr = m.getMainAttributes(); String pack = attr.getValue("Covered-Packages"); // NOI18N if (pack != null) { known.addAll(Arrays.asList(pack.split(",", -1))); mod.registerCoveredPackages(known); return known; } } // not precomputed/cached, analyze StringBuffer save = new StringBuffer(); for (Source s : sources) s.listCoveredPackages(known, save); if (save.length() > 0) save.setLength(save.length()-1); if (mod != null) { mod.registerCoveredPackages(known); } return known; }
@Override public Set<String> findPermissionByUserId(String uuid) { List<Permission> list = permissionMapper.selectPermissionByUserId(uuid); Set<String> set = new HashSet<>(); for (Permission permission : list) { set.add(permission.getPermissionName()); } return set; }
public Set getAvailableRoomFeatures() { Set features = new TreeSet(GlobalRoomFeature.getAllGlobalRoomFeatures(getSession())); Department dept = getManagingDept(); if (dept!=null) features.addAll(DepartmentRoomFeature.getAllDepartmentRoomFeatures(dept)); return features; }
private static Set<IdIdentifier> getWrittenIds(final Context context) { Set<IdIdentifier> result = (Set<IdIdentifier>) context.getData(WRITTEN_IDS_DATAKEY); if (result == null) { result = new HashSet<>(); context.setData(WRITTEN_IDS_DATAKEY, result); } return result; }
@Override public Set<Entry<E>> entrySet() { Set<Entry<E>> result = entrySet; if (result == null) { entrySet = result = createEntrySet(); } return result; }
@Override public Set getResourceDomains() { HashSet hashset = Sets.newHashSet(); hashset.add("animation"); return hashset; }
@Override public Set<InternalDistributedMember> send(DistributionMessage msg, NetView alternateView) { if (this.encrypt != null) { this.encrypt.installView(alternateView); } return send(msg, true); }
/** * @return map containing all class names as key, extracted RuntimeBeans as * values. If more than zero values is returned, exactly one * RuntimeBeanEntry will have isRoot set to true, even if yang does * not contain special configuration for it. */ public static Map<String, RuntimeBeanEntry> extractClassNameToRuntimeBeanMap( final String packageName, final DataNodeContainer container, final String moduleYangName, final TypeProviderWrapper typeProviderWrapper, final String javaNamePrefix, final Module currentModule, final SchemaContext schemaContext) { AttributesRpcsAndRuntimeBeans attributesRpcsAndRuntimeBeans = extractSubtree( packageName, container, typeProviderWrapper, currentModule, schemaContext); Map<String, RuntimeBeanEntry> result = new HashMap<>(); List<AttributeIfc> attributes; Set<Rpc> rpcs; if (attributesRpcsAndRuntimeBeans.isEmpty() == false) { attributes = attributesRpcsAndRuntimeBeans.getAttributes(); rpcs = attributesRpcsAndRuntimeBeans.getRpcs(); } else { // create artificial root if not defined in yang attributes = Collections.emptyList(); rpcs = Collections.emptySet(); } RuntimeBeanEntry rootRuntimeBeanEntry = createRoot(packageName, container, moduleYangName, attributes, javaNamePrefix, attributesRpcsAndRuntimeBeans.getRuntimeBeanEntries(), rpcs); Deque<RuntimeBeanEntry> stack = new LinkedList<>(); stack.add(rootRuntimeBeanEntry); while (stack.isEmpty() == false) { RuntimeBeanEntry first = stack.pollFirst(); if (result.containsKey(first.getJavaNameOfRuntimeMXBean())) { throw new NameConflictException( first.getJavaNameOfRuntimeMXBean(), null, null); } result.put(first.getJavaNameOfRuntimeMXBean(), first); stack.addAll(first.getChildren()); } return result; }
Set<ElementHandle<TypeElement>> loadDescenantsOfNode() { if (namePrefix.length() < PREFIX_TRESHOLD) { return loadDescenantsOfNode2(); } TypeElement baseClass = getBaseClass(); if (baseClass == null) { return Collections.emptySet(); } Set<ElementHandle<TypeElement>> handles = new HashSet<ElementHandle<TypeElement>>(); Set<ElementHandle<TypeElement>> els = ctx.getClasspathInfo().getClassIndex(). getDeclaredTypes(namePrefix, ClassIndex.NameKind.CASE_INSENSITIVE_PREFIX, EnumSet.of(ClassIndex.SearchScope.DEPENDENCIES, ClassIndex.SearchScope.SOURCE)); TypeMirror nodeType = baseClass.asType(); for (Iterator<ElementHandle<TypeElement>> it = els.iterator(); it.hasNext(); ) { ElementHandle<TypeElement> h = it.next(); TypeElement e = h.resolve(ctx.getCompilationInfo()); if (e == null || !acceptsQName(e.getQualifiedName(), e.getSimpleName()) || e.getModifiers().contains(Modifier.ABSTRACT) || !FxClassUtils.isFxmlAccessible(e) || !ctx.getCompilationInfo().getTypes().isAssignable(e.asType(), nodeType)) { continue; } handles.add(h); } return handles; }