Java Code Examples for java.util.Set#toString()

The following examples show how to use java.util.Set#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FrontendDependencies.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Visit all classes annotated with {@link NpmPackage} and update the list
 * of dependencies and their versions.
 *
 * @throws ClassNotFoundException
 * @throws IOException
 */
private void computePackages() throws ClassNotFoundException, IOException {
    FrontendAnnotatedClassVisitor npmPackageVisitor = new FrontendAnnotatedClassVisitor(
            getFinder(), NpmPackage.class.getName());

    for (Class<?> component : getFinder()
            .getAnnotatedClasses(NpmPackage.class.getName())) {
        npmPackageVisitor.visitClass(component.getName());
    }

    Set<String> dependencies = npmPackageVisitor.getValues(VALUE);
    for (String dependency : dependencies) {
        Set<String> versions = npmPackageVisitor.getValuesForKey(VALUE,
                dependency, VERSION);
        String version = versions.iterator().next();
        if (versions.size() > 1) {
            String foundVersions = versions.toString();
            log().warn(
                    "Multiple npm versions for {} found:  {}. First version found '{}' will be considered.",
                    dependency, foundVersions, version);
        }
        packages.put(dependency, version);
    }
}
 
Example 2
Source File: AbstractUserRoleMappingMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves all roles of the current user based on direct roles set to the user, its groups and their parent groups.
 * Then it recursively expands all composite roles, and restricts according to the given predicate {@code restriction}.
 * If the current client sessions is restricted (i.e. no client found in active user session has full scope allowed),
 * the final list of roles is also restricted by the client scope. Finally, the list is mapped to the token into
 * a claim.
 *
 * @param token
 * @param mappingModel
 * @param rolesToAdd
 * @param clientId
 * @param prefix
 */
protected static void setClaim(IDToken token, ProtocolMapperModel mappingModel, Set<String> rolesToAdd,
                               String clientId, String prefix) {

    Set<String> realmRoleNames;
    if (prefix != null && !prefix.isEmpty()) {
        realmRoleNames = rolesToAdd.stream()
                .map(roleName -> prefix + roleName)
                .collect(Collectors.toSet());
    } else {
        realmRoleNames = rolesToAdd;
    }

    Object claimValue = realmRoleNames;

    boolean multiValued = "true".equals(mappingModel.getConfig().get(ProtocolMapperUtils.MULTIVALUED));
    if (!multiValued) {
        claimValue = realmRoleNames.toString();
    }

    //OIDCAttributeMapperHelper.mapClaim(token, mappingModel, claimValue);
    mapClaim(token, mappingModel, claimValue, clientId);
}
 
Example 3
Source File: GenModuleInfoSource.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void mergeExportsOrOpens(Statement statement,
                                 Statement extra,
                                 Set<String> modules)
{
    String pn = statement.name;
    if (statement.isUnqualified() && extra.isQualified()) {
        throw new RuntimeException("can't add qualified exports to " +
            "unqualified exports " + pn);
    }

    Set<String> mods = extra.targets.stream()
        .filter(mn -> statement.targets.contains(mn))
        .collect(toSet());
    if (mods.size() > 0) {
        throw new RuntimeException("qualified exports " + pn + " to " +
            mods.toString() + " already declared in " + sourceFile);
    }

    // add qualified exports or opens to known modules only
    addTargets(statement, extra, modules);
}
 
Example 4
Source File: FieldsEditorExistingPanel.java    From ontopia with Apache License 2.0 6 votes vote down vote up
private static String getAllowedPlayerNames(RoleField rf) {
  Set<String> topicTypeNames = new TreeSet<String>();
  
  AssociationField afield = rf.getAssociationField();
  Iterator<RoleField> it = afield.getFieldsForRoles().iterator();
  while(it.hasNext()) {
    RoleField af2 = (RoleField) it.next();
    if(!rf.equals(af2)) { // one of the other association fields
        Iterator<TopicType> it2 =  af2.getDeclaredPlayerTypes().iterator();         
        while(it2.hasNext()) {
          topicTypeNames.add(((TopicType)it2.next()).getName());
        } 
    }      
  }
  return topicTypeNames.toString();
}
 
Example 5
Source File: NotificationResource.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
/** Do some basic checks on the JWT, until the MP-JWT annotations are ready. */
private void validateJWT() throws JWTException {
  // Make sure the authorization header was present.  This check is somewhat
  // silly since the jwtPrincipal will never actually be null since it's a
  // WELD proxy (injected).
  if (jwtPrincipal == null) {
    throw new JWTException("No authorization header or unable to inflate JWT");
  }

  // At this point, only the orchestrator can make notifications.
  Set<String> groups = jwtPrincipal.getGroups();
  if (groups.contains("orchestrator") == false) {
    throw new JWTException("User is not in a valid group [" + groups.toString() + "]");
  }

  // TODO: Additional checks as appropriate.
}
 
Example 6
Source File: ComponentGraph.java    From codebase with GNU Lesser General Public License v3.0 5 votes vote down vote up
public ComponentGraph(AbstractDirectedGraph<E, V> g, Collection<Set<V>> m, V v) {
	super();
	
	pmap = new HashMap<V, Set<Set<V>>>();
	
	// Build component graph
	Map<V, V> map = new HashMap<V, V>();
	
	for (Set<V> p: m) {
		@SuppressWarnings("unchecked")
		V vp = (V) new Vertex("CG:"+p.toString());
		addVertex(vp);
		
		// vp is a vertex in the ComponentGraph, which is then associated with
		// vertex from the partition in the original graph (any)
		map.put(vp, p.iterator().next());
		
		// Initialize the set of partitions associated to each node in the component graph
		Set<Set<V>> sopart =  new HashSet<Set<V>>();
		sopart.add(p);
		pmap.put(vp, sopart);
	}
	
	for (V xp: map.keySet()) {
		V x = map.get(xp);
		if (x.equals(v)) continue;
		for (V yp: map.keySet()) {
			V y = map.get(yp);
			if (y.equals(v) || x.equals(y)) continue;
			
			if (distinguishes(g, x, y, v))
				addEdge(xp, yp);
		}
	}
	
	// Compute connected components and collapse them
	contractSCC();
}
 
Example 7
Source File: TableSchema.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public TableSchema(String[] fieldNames, TypeInformation<?>[] fieldTypes) {
	this.fieldNames = Preconditions.checkNotNull(fieldNames);
	this.fieldTypes = Preconditions.checkNotNull(fieldTypes);

	if (fieldNames.length != fieldTypes.length) {
		throw new TableException(
			"Number of field names and field types must be equal.\n" +
			"Number of names is " + fieldNames.length + ", number of types is " + fieldTypes.length + ".\n" +
			"List of field names: " + Arrays.toString(fieldNames) + "\n" +
			"List of field types: " + Arrays.toString(fieldTypes));
	}

	// validate and create name to index mapping
	fieldNameToIndex = new HashMap<>();
	final Set<String> duplicateNames = new HashSet<>();
	final Set<String> uniqueNames = new HashSet<>();
	for (int i = 0; i < fieldNames.length; i++) {
		// check for null
		Preconditions.checkNotNull(fieldTypes[i]);
		final String fieldName = Preconditions.checkNotNull(fieldNames[i]);

		// collect indices
		fieldNameToIndex.put(fieldName, i);

		// check uniqueness of field names
		if (uniqueNames.contains(fieldName)) {
			duplicateNames.add(fieldName);
		} else {
			uniqueNames.add(fieldName);
		}
	}
	if (!duplicateNames.isEmpty()) {
		throw new TableException(
			"Field names must be unique.\n" +
			"List of duplicate fields: " + duplicateNames.toString() + "\n" +
			"List of all fields: " + Arrays.toString(fieldNames));
	}
}
 
Example 8
Source File: OrganismCompositionMongoWriter.java    From act with GNU General Public License v3.0 5 votes vote down vote up
private String singletonSet2Str(Set<String> ecnums, String metadata) {
  switch (ecnums.size()) {
    case 0:
      return "";
    case 1:
      return ecnums.toArray(new String[0])[0];
    default:
      return ecnums.toString(); // e.g., [2.7.1.74 , 2.7.1.76 , 2.7.1.145] for http://www.metacyc.org/META/NEW-IMAGE?object=DEOXYADENOSINE-KINASE-RXN
  }
}
 
Example 9
Source File: RemoteCentralAuthenticationService.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Check for errors by asking the validator to review each credential.
 *
 * @param credentials the credentials
 */
private void checkForErrors(final Credential... credentials) {
    if (credentials == null) {
        return;
    }

    for (final Credential c : credentials) {
        final Set<ConstraintViolation<Credential>> errors = this.validator.validate(c);
        if (!errors.isEmpty()) {
            throw new IllegalArgumentException("Error validating credentials: " + errors.toString());
        }
    }
}
 
Example 10
Source File: UnexpectedProxiesException.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private static String toStringRepresentiation(Map<EObject, Collection<EStructuralFeature.Setting>> unresolved) {
	Set<URI> uris = new HashSet<>();
	for (Collection<EStructuralFeature.Setting> collection : unresolved.values()) {
		for (EStructuralFeature.Setting setting : collection) {
			uris.addAll(UnexpectedProxiesException.getURIs(setting));
		}
	}
	return uris.toString();
}
 
Example 11
Source File: StringSetConverter.java    From ml-authentication with Apache License 2.0 5 votes vote down vote up
@Override
public String convertToDatabaseValue(Set entityProperty) {
    Log.d(getClass().getName(), "convertToDatabaseValue");

    String databaseValue = entityProperty.toString();
    Log.d(getClass().getName(), "databaseValue: " + databaseValue);
    return databaseValue;
}
 
Example 12
Source File: DefaultRedirectResolver.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
/**
 * Attempt to match one of the registered URIs to the that of the requested one.
 * 
 * @param redirectUris the set of the registered URIs to try and find a match. This cannot be null or empty.
 * @param requestedRedirect the URI used as part of the request
 * @return the matching URI
 * @throws RedirectMismatchException if no match was found
 */
private String obtainMatchingRedirect(Set<String> redirectUris, String requestedRedirect) {
	Assert.notEmpty(redirectUris, "Redirect URIs cannot be empty");

	if (redirectUris.size() == 1 && requestedRedirect == null) {
		return redirectUris.iterator().next();
	}
	for (String redirectUri : redirectUris) {
		if (requestedRedirect != null && redirectMatches(requestedRedirect, redirectUri)) {
			return requestedRedirect;
		}
	}
	throw new RedirectMismatchException("Invalid redirect: " + requestedRedirect
			+ " does not match one of the registered values: " + redirectUris.toString());
}
 
Example 13
Source File: IDTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static String getDiff(Set<String> set1, Set<String> set2) {
    Set<String> s1 = new HashSet<>(set1);
    s1.removeAll(set2);

    Set<String> s2 = new HashSet<>(set2);
    s2.removeAll(set1);
    s2.addAll(s1);
    return s2.toString();
}
 
Example 14
Source File: ExecutionControl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Search for a provider, then create and return the
 * {@code ExecutionControl} instance.
 *
 * @param env the execution environment (provided by JShell)
 * @param name the name of provider
 * @param parameters the parameter map.
 * @return the execution engine
 * @throws Throwable an exception that occurred attempting to find or create
 * the execution engine.
 * @throws IllegalArgumentException if no ExecutionControlProvider has the
 * specified {@code name} and {@code parameters}.
 */
static ExecutionControl generate(ExecutionEnv env, String name, Map<String, String> parameters)
        throws Throwable {
    Set<String> keys = parameters == null
            ? Collections.emptySet()
            : parameters.keySet();
    for (ExecutionControlProvider p : ServiceLoader.load(ExecutionControlProvider.class)) {
        if (p.name().equals(name)
            && p.defaultParameters().keySet().containsAll(keys)) {
            return p.generate(env, parameters);
        }
    }
    throw new IllegalArgumentException("No ExecutionControlProvider with name '"
            + name + "' and parameter keys: " + keys.toString());
}
 
Example 15
Source File: RestControllerIntegrationTestBase.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected boolean matchesSafely(final Iterable<String> inputUrls) {
    final Set<String> urisToMatch = Sets.newHashSet(this.expectedUris);
    for (String inputUrl : inputUrls) {
        final List<String> matchedUrls = urisToMatch
            .stream()
            .filter(inputUrl::endsWith)
            .collect(Collectors.toList());

        if (matchedUrls.size() == 1) {
            urisToMatch.remove(matchedUrls.get(0));
        } else if (matchedUrls.size() == 0) {
            this.mismatchDescription = "Unexpected input URL: " + inputUrl;
            return false;
        } else {
            this.mismatchDescription = "Duplicate input URL: " + inputUrl;
            return false;
        }
    }

    if (!urisToMatch.isEmpty()) {
        this.mismatchDescription = "Unmatched URLs: " + urisToMatch.toString();
        return false;
    }
    this.mismatchDescription = "Successfully matched";
    return true;
}
 
Example 16
Source File: DegreeWorksCourseRequests.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
	Set<String> courses = new TreeSet<String>(iCriticalCourses);
	if (iCriticalCourseIds != null)
		for (XCourseId c: iCriticalCourseIds)
			courses.add(c.getCourseName());
	return courses.toString();
}
 
Example 17
Source File: RegionsResourceTest.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean matchesSafely(JsonObject jsonRegion) {

    // check id
    String jsonRegionId = jsonRegion.get("id").asString();
    String regionId = region.id().toString();
    if (!jsonRegionId.equals(regionId)) {
        reason = "region id was " + jsonRegionId;
        return false;
    }

    // check type
    String jsonType = jsonRegion.get("type").asString();
    String type = region.type().toString();
    if (!jsonType.equals(type)) {
        reason = "type was " + jsonType;
        return false;
    }

    // check name
    String jsonName = jsonRegion.get("name").asString();
    String name = region.name();
    if (!jsonName.equals(name)) {
        reason = "name was " + jsonName;
        return false;
    }

    // check size of master array
    JsonArray jsonMasters = jsonRegion.get("masters").asArray();
    if (jsonMasters.size() != region.masters().size()) {
        reason = "masters size was " + jsonMasters.size();
        return false;
    }

    // check master
    for (Set<NodeId> set : region.masters()) {
        boolean masterFound = false;
        for (int masterIndex = 0; masterIndex < jsonMasters.size(); masterIndex++) {
            masterFound = checkEquality(jsonMasters.get(masterIndex).asArray(), set);
        }

        if (!masterFound) {
            reason = "master not found " + set.toString();
            return false;
        }
    }

    return true;
}
 
Example 18
Source File: LuceneRecord.java    From HongsCORE with MIT License 4 votes vote down vote up
/**
 * 确保操作合法
 * @param rd
 * @param ids
 * @param ern
 * @throws HongsException
 */
protected void permit(Map rd, Set ids, int ern) throws HongsException {
    if (rd  == null) {
        throw new NullPointerException( "rd can not be null" );
    }
    if (ids == null || ids.isEmpty()) {
        throw new NullPointerException("ids can not be empty");
    }

    Map wh = new HashMap();
    if (rd.containsKey(Cnst.AR_KEY)) {
        wh.put(Cnst.AR_KEY, rd.get(Cnst.AR_KEY));
    }
    if (rd.containsKey(Cnst.OR_KEY)) {
        wh.put(Cnst.OR_KEY, rd.get(Cnst.OR_KEY));
    }
    if (wh.isEmpty()) {
        return;
    }

    // 组织查询
    wh.put(Cnst.ID_KEY, ids);
    wh.put(Cnst.RB_KEY, Cnst.ID_KEY);
    Set idz = new HashSet( );
    Loop rs = search(wh,0,0);
    while  (  rs.hasNext() ) {
        Map ro = rs.next();
        idz.add( ro.get(Cnst.ID_KEY).toString());
    }

    // 对比数量, 取出多余的部分作为错误消息抛出
    if (ids.size( ) != idz.size( ) ) {
        Set    zd = new HashSet(ids);
               zd . removeAll  (idz);
        String er = zd.toString(  );
        if (ern == 0x1096) {
            throw new HongsException(ern, "Can not update by id: " + er);
        } else
        if (ern == 0x1097) {
            throw new HongsException(ern, "Can not delete by id: " + er);
        } else
        {
            throw new HongsException(ern, "Can not search by id: " + er);
        }
    }
}
 
Example 19
Source File: StandardRemoteGroupPort.java    From nifi with Apache License 2.0 4 votes vote down vote up
private int transferFlowFiles(final Transaction transaction, final ProcessContext context, final ProcessSession session, final FlowFile firstFlowFile) throws IOException, ProtocolException {
    FlowFile flowFile = firstFlowFile;

    try {
        final String userDn = transaction.getCommunicant().getDistinguishedName();
        final long startSendingNanos = System.nanoTime();
        final StopWatch stopWatch = new StopWatch(true);
        long bytesSent = 0L;

        final SiteToSiteClientConfig siteToSiteClientConfig = getSiteToSiteClient().getConfig();
        final long maxBatchBytes = siteToSiteClientConfig.getPreferredBatchSize();
        final int maxBatchCount = siteToSiteClientConfig.getPreferredBatchCount();
        final long preferredBatchDuration = siteToSiteClientConfig.getPreferredBatchDuration(TimeUnit.NANOSECONDS);
        final long maxBatchDuration = preferredBatchDuration > 0 ? preferredBatchDuration : BATCH_SEND_NANOS;


        final Set<FlowFile> flowFilesSent = new HashSet<>();
        boolean continueTransaction = true;
        while (continueTransaction) {
            final long startNanos = System.nanoTime();
            // call codec.encode within a session callback so that we have the InputStream to read the FlowFile
            final FlowFile toWrap = flowFile;
            session.read(flowFile, new InputStreamCallback() {
                @Override
                public void process(final InputStream in) throws IOException {
                    final DataPacket dataPacket = new StandardDataPacket(toWrap.getAttributes(), in, toWrap.getSize());
                    transaction.send(dataPacket);
                }
            });

            final long transferNanos = System.nanoTime() - startNanos;
            final long transferMillis = TimeUnit.MILLISECONDS.convert(transferNanos, TimeUnit.NANOSECONDS);

            flowFilesSent.add(flowFile);
            bytesSent += flowFile.getSize();
            logger.debug("{} Sent {} to {}", this, flowFile, transaction.getCommunicant().getUrl());

            final String transitUri = transaction.getCommunicant().createTransitUri(flowFile.getAttribute(CoreAttributes.UUID.key()));
            flowFile = session.putAttribute(flowFile, SiteToSiteAttributes.S2S_PORT_ID.key(), getTargetIdentifier());
            session.getProvenanceReporter().send(flowFile, transitUri, "Remote DN=" + userDn, transferMillis, false);
            session.remove(flowFile);

            final long sendingNanos = System.nanoTime() - startSendingNanos;

            if (maxBatchCount > 0 && flowFilesSent.size() >= maxBatchCount) {
                flowFile = null;
            } else if (maxBatchBytes > 0 && bytesSent >= maxBatchBytes) {
                flowFile = null;
            } else if (sendingNanos >= maxBatchDuration) {
                flowFile = null;
            } else {
                flowFile = session.get();
            }

            continueTransaction = (flowFile != null);
        }

        transaction.confirm();

        // consume input stream entirely, ignoring its contents. If we
        // don't do this, the Connection will not be returned to the pool
        stopWatch.stop();
        final String uploadDataRate = stopWatch.calculateDataRate(bytesSent);
        final long uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS);
        final String dataSize = FormatUtils.formatDataSize(bytesSent);

        transaction.complete();
        session.commit();

        final String flowFileDescription = (flowFilesSent.size() < 20) ? flowFilesSent.toString() : flowFilesSent.size() + " FlowFiles";
        logger.info("{} Successfully sent {} ({}) to {} in {} milliseconds at a rate of {}", new Object[]{
            this, flowFileDescription, dataSize, transaction.getCommunicant().getUrl(), uploadMillis, uploadDataRate});

        return flowFilesSent.size();
    } catch (final Exception e) {
        session.rollback();
        throw e;
    }

}
 
Example 20
Source File: KerasBatchNormalization.java    From deeplearning4j with Apache License 2.0 4 votes vote down vote up
/**
 * Set weights for layer.
 *
 * @param weights Map from parameter name to INDArray.
 */
@Override
public void setWeights(Map<String, INDArray> weights) throws InvalidKerasConfigurationException {
    this.weights = new HashMap<>();
    if (center) {
        if (weights.containsKey(PARAM_NAME_BETA))
            this.weights.put(BatchNormalizationParamInitializer.BETA, weights.get(PARAM_NAME_BETA));
        else
            throw new InvalidKerasConfigurationException("Parameter " + PARAM_NAME_BETA + " does not exist in weights");
    } else {
        INDArray dummyBeta = Nd4j.zerosLike(weights.get(PARAM_NAME_BETA));
        this.weights.put(BatchNormalizationParamInitializer.BETA, dummyBeta);
    }
    if (scale) {
        if (weights.containsKey(PARAM_NAME_GAMMA))
            this.weights.put(BatchNormalizationParamInitializer.GAMMA, weights.get(PARAM_NAME_GAMMA));
        else
            throw new InvalidKerasConfigurationException(
                    "Parameter " + PARAM_NAME_GAMMA + " does not exist in weights");
    } else {
        INDArray dummyGamma = weights.containsKey(PARAM_NAME_GAMMA)
                ? Nd4j.onesLike(weights.get(PARAM_NAME_GAMMA))
                : Nd4j.onesLike(weights.get(PARAM_NAME_BETA));
        this.weights.put(BatchNormalizationParamInitializer.GAMMA, dummyGamma);
    }
    if (weights.containsKey(conf.getLAYER_FIELD_BATCHNORMALIZATION_MOVING_MEAN()))
        this.weights.put(BatchNormalizationParamInitializer.GLOBAL_MEAN, weights.get(conf.getLAYER_FIELD_BATCHNORMALIZATION_MOVING_MEAN()));
    else
        throw new InvalidKerasConfigurationException(
                "Parameter " + conf.getLAYER_FIELD_BATCHNORMALIZATION_MOVING_MEAN() + " does not exist in weights");
    if (weights.containsKey(conf.getLAYER_FIELD_BATCHNORMALIZATION_MOVING_VARIANCE()))
        this.weights.put(BatchNormalizationParamInitializer.GLOBAL_VAR, weights.get(conf.getLAYER_FIELD_BATCHNORMALIZATION_MOVING_VARIANCE()));
    else
        throw new InvalidKerasConfigurationException(
                "Parameter " + conf.getLAYER_FIELD_BATCHNORMALIZATION_MOVING_VARIANCE() + " does not exist in weights");
    if (weights.size() > 4) {
        Set<String> paramNames = weights.keySet();
        paramNames.remove(PARAM_NAME_BETA);
        paramNames.remove(PARAM_NAME_GAMMA);
        paramNames.remove(conf.getLAYER_FIELD_BATCHNORMALIZATION_MOVING_MEAN());
        paramNames.remove(conf.getLAYER_FIELD_BATCHNORMALIZATION_MOVING_VARIANCE());
        String unknownParamNames = paramNames.toString();
        log.warn("Attempting to set weights for unknown parameters: "
                + unknownParamNames.substring(1, unknownParamNames.length() - 1));
    }
}