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

The following examples show how to use java.util.Set#toArray() . 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: MapReduceServiceImpl.java    From pentaho-hadoop-shims with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( "squid:S2095" )
private Class<?> loadClassByName( final String className, final URL jarUrl, final ClassLoader parentClassLoader, boolean addConfigFiles )
  throws ClassNotFoundException, MalformedURLException, URISyntaxException {
  if ( className != null ) {
    // ignoring this warning; paths are to the local file system so no host name lookup should happen
    @SuppressWarnings( "squid:S2112" )
    Set<URL> urlSet = new HashSet<>();
    if ( addConfigFiles ) {
      List<URL> urlList = new ArrayList<>();
      ShimConfigsLoader.addConfigsAsResources( namedCluster.getName(), urlList::add );
      for ( URL url : urlList ) {
        // get the parent dir of each config file
        urlSet.add( Paths.get( url.toURI() ).getParent().toUri().toURL() );
      }
    }
    urlSet.add( jarUrl );
    URLClassLoader cl = new URLClassLoader( urlSet.toArray( new URL[0] ), parentClassLoader );
    return cl.loadClass( className.replace( "/", "." ) );
  } else {
    return null;
  }
}
 
Example 2
Source File: InternalThreadLocal.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
/**
 * Removes all {@link InternalThreadLocal} variables bound to the current thread.  This operation is useful when you
 * are in a container environment, and you don't want to leave the thread local variables in the threads you do not
 * manage.删除绑定到当前线程的所有内部线程本地变量。当您在容器环境中,并且不希望将线程本地变量留在不管理的线程中时,此操作非常有用。
 */
@SuppressWarnings("unchecked")
public static void removeAll() {
    InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet();
    if (threadLocalMap == null) {
        return;
    }

    try {
        Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex);
        if (v != null && v != InternalThreadLocalMap.UNSET) {
            Set<InternalThreadLocal<?>> variablesToRemove = (Set<InternalThreadLocal<?>>) v;
            InternalThreadLocal<?>[] variablesToRemoveArray =
                    variablesToRemove.toArray(new InternalThreadLocal[variablesToRemove.size()]);
            for (InternalThreadLocal<?> tlv : variablesToRemoveArray) {
                tlv.remove(threadLocalMap);
            }
        }
    } finally {
        InternalThreadLocalMap.remove();
    }
}
 
Example 3
Source File: AudioSystem.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Obtains the file types that the system can write from the
 * audio input stream specified.
 * @param stream the audio input stream for which audio file type support
 * is queried
 * @return array of file types.  If no file types are supported,
 * an array of length 0 is returned.
 */
public static AudioFileFormat.Type[] getAudioFileTypes(AudioInputStream stream) {
    List providers = getAudioFileWriters();
    Set returnTypesSet = new HashSet();

    for(int i=0; i < providers.size(); i++) {
        AudioFileWriter writer = (AudioFileWriter) providers.get(i);
        AudioFileFormat.Type[] fileTypes = writer.getAudioFileTypes(stream);
        for(int j=0; j < fileTypes.length; j++) {
            returnTypesSet.add(fileTypes[j]);
        }
    }
    AudioFileFormat.Type returnTypes[] = (AudioFileFormat.Type[])
        returnTypesSet.toArray(new AudioFileFormat.Type[0]);
    return returnTypes;
}
 
Example 4
Source File: UserHelper.java    From rebuild with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取部门或角色下的成员
 * 
 * @param groupId ID of Role/Department
 * @return
 */
public static Member[] getMembers(ID groupId) {
	Set<Principal> ms = null;
	try {
		if (groupId.getEntityCode() == EntityHelper.Department) {
			ms = Application.getUserStore().getDepartment(groupId).getMembers();
		} else if (groupId.getEntityCode() == EntityHelper.Role) {
			ms = Application.getUserStore().getRole(groupId).getMembers();
		}
	} catch (NoMemberFoundException ex) {
		LOG.error("No group found : " + groupId);
	}
	
	if (ms == null || ms.isEmpty()) {
		return new Member[0];
	}
       // noinspection SuspiciousToArrayCall
       return ms.toArray(new Member[0]);
}
 
Example 5
Source File: AnnotationActionModuleTypeHelper.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
public ActionType buildModuleType(String UID, Map<String, Set<ModuleInformation>> moduleInformation) {
    Set<ModuleInformation> mis = moduleInformation.get(UID);
    List<ConfigDescriptionParameter> configDescriptions = new ArrayList<>();

    if (mis != null && !mis.isEmpty()) {
        ModuleInformation mi = (ModuleInformation) mis.toArray()[0];

        ActionModuleKind kind = ActionModuleKind.SINGLE;
        if (mi.getConfigName() != null && mi.getThingUID() != null) {
            logger.error(
                    "ModuleType with UID {} has thingUID ({}) and multi-service ({}) property set, ignoring it.",
                    UID, mi.getConfigName(), mi.getThingUID());
            return null;
        } else if (mi.getConfigName() != null) {
            kind = ActionModuleKind.SERVICE;
        } else if (mi.getThingUID() != null) {
            kind = ActionModuleKind.THING;
        }

        ConfigDescriptionParameter configParam = buildConfigParam(mis, kind);
        if (configParam != null) {
            configDescriptions.add(configParam);
        }

        ActionType at = new ActionType(UID, configDescriptions, mi.getLabel(), mi.getDescription(), mi.getTags(),
                mi.getVisibility(), mi.getInputs(), mi.getOutputs());
        return at;
    }
    return null;
}
 
Example 6
Source File: ServerRequestHandlerFactory.java    From RTSP-Java-UrlConnection with Apache License 2.0 5 votes vote down vote up
public String[] getSupportedClientMethod() {
	Set set = new HashSet();
	for (int i = 0; i < factories.length; i++) {
		String[] sub = factories[i].getSupportedClientMethod();
		if (sub != null)
			for (int j = 0; j < sub.length; j++)
				set.add(sub[j]);
	}
	return (String[]) set.toArray(new String[set.size()]);
}
 
Example 7
Source File: LogAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static File[] replaceCopiedFiles (File[] files) {
    if (files == null) {
        return null;
    }
    Set<File> originalFiles = new LinkedHashSet<File>(files.length);
    FileStatusCache cache = Mercurial.getInstance().getFileStatusCache();
    for (File file : files) {
        FileStatus st = cache.getStatus(file).getStatus(null);
        if (st != null && st.isCopied() && st.getOriginalFile() != null) {
            file = st.getOriginalFile();
        }
        originalFiles.add(file);
    }
    return originalFiles.toArray(new File[originalFiles.size()]);
}
 
Example 8
Source File: TestIDList.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void print(){
    System.out.println("-----------------");

    Set<Integer> keys = objs.keySet();
    Integer[] keysArr = keys.toArray(new Integer[0]);
    Arrays.sort(keysArr);
    for (int i = 0; i < keysArr.length; i++){
        System.out.println(keysArr[i]+" => "+objs.get(keysArr[i]).hashCode());
    }
}
 
Example 9
Source File: BezierCurve.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public final Point[] getIntersections(ICurve curve) {
	Set<Point> intersections = new HashSet<>();

	for (BezierCurve c : curve.toBezier()) {
		intersections.addAll(Arrays.asList(getIntersections(c)));
	}

	return intersections.toArray(new Point[] {});
}
 
Example 10
Source File: ClaraClulsterCalulator.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private Artifact computeNewMedoid(Cluster[] Clusters, int clusterID) {
	Artifact newMedoid = null;
	Set<Artifact> tmp = new HashSet<Artifact>();
	tmp.addAll(Clusters[clusterID].getArtifacts());
	Artifact medoid = Clusters[clusterID].getMostRepresentative();
	Set<Artifact> tmp2 = new HashSet<Artifact>();
	Artifact[] nonMedoids = null;
	float d = 0.0f;
	float minDistance = 0.0f;
	Map<String, Float> distances = new HashMap<String, Float>();
	nonMedoids = tmp.toArray(new Artifact[tmp.size()]);
	distances = readDistanceScores(medoid.getId());
	minDistance = getAverageDistance(distances, nonMedoids);
	newMedoid = medoid;
	tmp.add(medoid);
	for (Artifact object : tmp) {
		tmp2 = new HashSet<Artifact>();
		tmp2.addAll(tmp);
		tmp2.remove(object);

		distances = readDistanceScores(object.getId());
		nonMedoids = (Artifact[]) tmp2.toArray(new Artifact[tmp2.size()]);
		d = getAverageDistance(distances, nonMedoids);
		if (d < minDistance) {
			minDistance = d;
			newMedoid = object;
		}
	}
	return newMedoid;
}
 
Example 11
Source File: CollectionTagger.java    From storm-crawler with Apache License 2.0 5 votes vote down vote up
public String[] tag(String url) {
    Set<String> tags = new HashSet<String>();
    for (Collection collection : collections) {
        if (collection.matches(url)) {
            tags.add(collection.getName());
        }
    }
    return tags.toArray(new String[tags.size()]);
}
 
Example 12
Source File: ZCashClientCaller.java    From zencash-swing-wallet-ui with MIT License 5 votes vote down vote up
public synchronized String[] getWalletAllPublicAddresses()
	throws WalletCallException, IOException, InterruptedException
{
	JsonArray jsonReceivedOutputs = executeCommandAndGetJsonArray("listreceivedbyaddress", "0", "true");

	Set<String> addresses = new HashSet<>();
	for (int i = 0; i < jsonReceivedOutputs.size(); i++)
	{
	   	JsonObject outp = jsonReceivedOutputs.get(i).asObject();
	   	addresses.add(outp.getString("address", "ERROR!"));
	}

	return addresses.toArray(new String[0]);
   }
 
Example 13
Source File: StateNode.java    From flow with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private static Class[] getNonRepeatebleFeatures(StateNode node) {
    if (node.featureSet.reportedFeatures.isEmpty()) {
        Set<Class<? extends NodeFeature>> set = node.featureSet.mappings
                .keySet();
        return set.toArray(new Class[set.size()]);
    }
    return node.featureSet.mappings.keySet().stream().filter(
            clazz -> !node.featureSet.reportedFeatures.contains(clazz))
            .toArray(Class[]::new);
}
 
Example 14
Source File: QuarkusProxyFactory.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private Class[] toArray(Set<Class> interfaces) {
    if (interfaces == null) {
        return ArrayHelper.EMPTY_CLASS_ARRAY;
    }

    return interfaces.toArray(new Class[interfaces.size()]);
}
 
Example 15
Source File: MasterRegistrationControlEntryManager.java    From joynr with Apache License 2.0 5 votes vote down vote up
private MasterRegistrationControlEntry[] executeAndConvert(Query query) {
    List<MasterRegistrationControlEntryEntity> resultList = query.getResultList();
    Set<MasterRegistrationControlEntry> resultSet = resultList.stream()
                                                              .map(this::mapEntityToJoynrType)
                                                              .collect(Collectors.toSet());
    return resultSet.toArray(new MasterRegistrationControlEntry[resultSet.size()]);
}
 
Example 16
Source File: MonitorsLabelProvider.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void handleMapChange ( final MapChangeEvent event )
{
    final Set<?> affectedElements = event.diff.getChangedKeys ();
    if ( !affectedElements.isEmpty () )
    {
        final LabelProviderChangedEvent newEvent = new LabelProviderChangedEvent ( MonitorsLabelProvider.this, affectedElements.toArray () );
        fireLabelProviderChanged ( newEvent );
    }
}
 
Example 17
Source File: MemberGroupConverter.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private String[] getMemberGroupNames() {
  final Set<String> memberGroups = getMemberGroups();
  return memberGroups.toArray(new String[memberGroups.size()]);
}
 
Example 18
Source File: SunClipboard.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
public synchronized FlavorListener[] getFlavorListeners() {
    Set<FlavorListener> flavorListeners = getFlavorListeners(AppContext.getAppContext());
    return flavorListeners == null ? new FlavorListener[0]
            : flavorListeners.toArray(new FlavorListener[flavorListeners.size()]);
}
 
Example 19
Source File: LazyObject.java    From LazyJSON with Apache License 2.0 4 votes vote down vote up
public static java.lang.String[] getNames(LazyObject obj){
	Set<String> keys=obj.keySet();
	return keys.toArray(new String[keys.size()]);
}
 
Example 20
Source File: PermissionUtility.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
/**
 * パーミッションの許諾リクエストを要求する.
 *
 * <p>
 * Android OS 6.0以上の端末では、このメソッドが呼び出されると内部でActivityが起動して、ユーザに対してパーミッションの許諾確認を行う。<br>
 * ユーザから許可された場合には、{@link org.deviceconnect.android.activity.PermissionUtility.PermissionRequestCallback#onSuccess}が呼び出され、
 * 拒否された場合には、{@link org.deviceconnect.android.activity.PermissionUtility.PermissionRequestCallback#onFail(String)}が呼び出される。
 * </p>
 * <p>
 * Android OS 6.0未満の端末では、{@link org.deviceconnect.android.activity.PermissionUtility.PermissionRequestCallback#onSuccess}が常に呼び出される。
 * </p>
 * <br>
 * サンプルコード:
 * <pre>
 * {@code
 * String[] permissions = new String[] {
 *     Manifest.permission.ACCESS_COARSE_LOCATION,
 *     Manifest.permission.ACCESS_FINE_LOCATION
 * }
 * 
 * PermissionUtility.requestPermissions(getActivity(), new Handler(),
 *         permissions,
 *         new PermissionUtility.PermissionRequestCallback() {
 *             public void onSuccess() {
 *                 // 許可された時の処理
 *             }
 *             public void onFail(final String deniedPermission) {
 *                 // 拒否された時の処理
 *             }
 *         });
 * }
 * </pre>
 * @param context コンテキスト
 * @param handler ハンドラー
 * @param permissions 許可を求めるパーミッション群
 * @param callback 許諾通知を行うコールバック
 */
public static void requestPermissions(@NonNull final Context context, @NonNull final Handler handler,
        @NonNull final String[] permissions, @NonNull final PermissionRequestCallback callback) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        callback.onSuccess();
    } else {
        Set<String> mPermissionSet = new HashSet<>(Arrays.asList(permissions));

        if (mPermissionSet.size() == 0) {
            callback.onSuccess();
            return;
        }
        Set<String> tmp = new HashSet<>(mPermissionSet);
        for (final String permission : tmp) {
            if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
                mPermissionSet.remove(permission);
            }
        }
        if (mPermissionSet.size() == 0) {
            callback.onSuccess();
        } else {
            String[] missingPermissions = mPermissionSet.toArray(new String[mPermissionSet.size()]);
            PermissionRequestActivity.requestPermissions(context, missingPermissions, new ResultReceiver(handler) {
                @Override
                protected void onReceiveResult(final int resultCode, final Bundle resultData) {
                    String[] retPermissions = resultData.getStringArray(PermissionRequestActivity.EXTRA_PERMISSIONS);
                    int[] retGrantResults = resultData.getIntArray(PermissionRequestActivity.EXTRA_GRANT_RESULTS);
                    if (retPermissions == null || retGrantResults == null) {
                        callback.onFail(null);
                        return;
                    }
                    for (int i = 0; i < retPermissions.length; ++i) {
                        if (retGrantResults[i] == PackageManager.PERMISSION_DENIED) {
                            callback.onFail(retPermissions[i]);
                            return;
                        }
                    }
                    callback.onSuccess();
                }
            });
        }
    }
}