Example usage for java.util HashSet toArray

List of usage examples for java.util HashSet toArray

Introduction

In this page you can find the example usage for java.util HashSet toArray.

Prototype

<T> T[] toArray(T[] a);

Source Link

Document

Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Usage

From source file:com.github.pjungermann.config.specification.constraint.url.UrlConstraint.java

@NotNull
@SuppressWarnings("unchecked")
protected String[] configureAllowedSchemes() {
    final Collection<String> schemesConfig = (Collection<String>) config.get(SCHEMES_KEY);
    if (schemesConfig == null || schemesConfig.isEmpty()) {
        return new String[0];
    }/*from  w  ww .jav  a 2s  . c  o  m*/

    final HashSet<String> schemes = new HashSet<>();
    final Set<String> checked = checkedSet(schemes, String.class);
    checked.addAll(schemesConfig);

    return schemes.toArray(new String[schemes.size()]);
}

From source file:org.osiam.resources.helper.AttributesRemovalHelper.java

private ObjectWriter getObjectWriter(ObjectMapper mapper, String[] fieldsToReturn) {

    if (fieldsToReturn.length != 0) {
        mapper.addMixInAnnotations(Object.class, PropertyFilterMixIn.class);

        HashSet<String> givenFields = new HashSet<>();
        givenFields.add("schemas");
        Collections.addAll(givenFields, fieldsToReturn);
        String[] finalFieldsToReturn = givenFields.toArray(new String[givenFields.size()]);

        FilterProvider filters = new SimpleFilterProvider().addFilter("filter properties by name",
                SimpleBeanPropertyFilter.filterOutAllExcept(finalFieldsToReturn));
        return mapper.writer(filters);
    }/*from  www .ja  v  a  2s  .  co m*/
    return mapper.writer();
}

From source file:com.cyclopsgroup.waterview.spi.ThemeManager.java

/**
 * Get all theme names// w  w  w  .j  a v  a  2 s  . c o  m
 *
 * @return Array of them names
 */
public String[] getThemeNames() {
    HashSet names = new HashSet();
    for (Iterator i = themeProviders.iterator(); i.hasNext();) {
        ThemeProvider provider = (ThemeProvider) i.next();
        CollectionUtils.addAll(names, provider.getThemeNames());
    }
    return (String[]) names.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}

From source file:org.osiam.resource_server.resources.helper.AttributesRemovalHelper.java

private ObjectWriter getObjectWriter(ObjectMapper mapper, String[] fieldsToReturn) {

    if (fieldsToReturn.length != 0) {
        mapper.addMixInAnnotations(Object.class, PropertyFilterMixIn.class);

        HashSet<String> givenFields = new HashSet<String>();
        givenFields.add("schemas");
        for (String field : fieldsToReturn) {
            givenFields.add(field);//from ww w.j av  a  2 s  .c om
        }
        String[] finalFieldsToReturn = givenFields.toArray(new String[givenFields.size()]);

        FilterProvider filters = new SimpleFilterProvider().addFilter("filter properties by name",
                SimpleBeanPropertyFilter.filterOutAllExcept(finalFieldsToReturn));
        return mapper.writer(filters);
    }
    return mapper.writer();
}

From source file:com.l2jfree.gameserver.model.skills.effects.templates.EffectTemplate.java

/**
 * Support for improved buffs, in case it gets overwritten in DP
 * //w w w .j  a v a 2  s.co m
 * @param skill
 * @param template
 * @return
 */
public boolean merge(L2Skill skill, EffectTemplate template) {
    if (!name.equals(template.name))
        return false;

    if (lambda != 0 || template.lambda != 0)
        return false;

    if (count != template.count || period != template.period)
        return false;

    if (effectPower != template.effectPower || effectType != template.effectType)
        return false;

    if (triggeredSkill != null || template.triggeredSkill != null)
        return false;

    if (chanceCondition != null || template.chanceCondition != null)
        return false;

    abnormalEffect |= template.abnormalEffect;
    specialEffect |= template.specialEffect;

    final HashSet<String> tmp = new HashSet<String>();

    for (String s : stackTypes)
        tmp.add(s);

    for (String s : template.stackTypes)
        tmp.add(s);

    stackTypes = tmp.toArray(new String[tmp.size()]);
    stackOrder = 99;

    showIcon = showIcon || template.showIcon;

    for (FuncTemplate f : template.funcTemplates)
        attach(f);

    _log.info("Effect templates merged for " + skill);
    return true;
}

From source file:org.entando.entando.aps.system.XmlWebApplicationContext.java

@Override
public String[] getBeanNamesForType(Class<?> type) {
    String[] beanNames = super.getBeanNamesForType(type);
    List<ClassPathXmlApplicationContext> contexts = (List<ClassPathXmlApplicationContext>) this
            .getServletContext().getAttribute("pluginsContextsList");
    Set removedPluginsSubMenuSet = (Set<String>) this.getServletContext()
            .getAttribute("removedPluginsSubMenuSet");
    if (contexts != null) {
        for (ClassPathXmlApplicationContext classPathXmlApplicationContext : contexts) {
            String[] beanNamesTemp = classPathXmlApplicationContext.getBeanNamesForType(type);
            beanNames = (String[]) ArrayUtils.addAll(beanNames, beanNamesTemp);
            HashSet hs = new HashSet();
            for (int i = 0; i < beanNames.length; i++) {
                String beanName = beanNames[i];
                hs.add(beanName);//from   w w w.  j a v a  2s  . c o m
            }
            beanNames = (String[]) hs.toArray(new String[0]);
            Arrays.sort(beanNames);
        }
    }
    Set hs = new HashSet();
    for (int i = 0; i < beanNames.length; i++) {
        String beanName = beanNames[i];
        if (removedPluginsSubMenuSet != null && removedPluginsSubMenuSet.contains(beanName)) {
            continue;
        }
        hs.add(beanName);
    }
    beanNames = (String[]) hs.toArray(new String[0]);
    Arrays.sort(beanNames);
    return beanNames;
}

From source file:org.apache.james.transport.mailets.HeadersToHTTP.java

private String httpPost(HashSet<NameValuePair> pairs) throws IOException {

    CloseableHttpClient client = null;/*from  w ww .java 2 s  .c o  m*/
    CloseableHttpResponse clientResponse = null;
    try {
        client = HttpClientBuilder.create().build();
        HttpUriRequest request = RequestBuilder.post(url).addParameters(pairs.toArray(new NameValuePair[0]))
                .build();
        clientResponse = client.execute(request);
        String result = clientResponse.getStatusLine().getStatusCode() + ": " + clientResponse.getStatusLine();
        log("HeadersToHTTP: " + result);
        return result;
    } finally {
        IOUtils.closeQuietly(clientResponse);
        IOUtils.closeQuietly(client);
    }
}

From source file:at.bitfire.davdroid.mirakel.webdav.TlsSniSocketFactory.java

@SuppressLint("DefaultLocale")
private void setReasonableEncryption(SSLSocket ssl) {
    // set reasonable SSL/TLS settings before the handshake

    // Android 5.0+ (API level21) provides reasonable default settings
    // but it still allows SSLv3
    // https://developer.android.com/about/versions/android-5.0-changes.html#ssl

    // - enable all supported protocols (enables TLSv1.1 and TLSv1.2 on Android <5.0, if available)
    // - remove all SSL versions (especially SSLv3) because they're insecure now
    List<String> protocols = new LinkedList<String>();
    for (String protocol : ssl.getSupportedProtocols())
        if (!protocol.toUpperCase().contains("SSL"))
            protocols.add(protocol);/*from w  w  w.j  ava2 s.  c om*/
    Log.v(TAG, "Setting allowed TLS protocols: " + StringUtils.join(protocols, ", "));
    ssl.setEnabledProtocols(protocols.toArray(new String[0]));

    if (android.os.Build.VERSION.SDK_INT < 21) {
        // choose secure cipher suites
        List<String> allowedCiphers = Arrays.asList(// TLS 1.2
                "TLS_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_128_GCM_SHA256",
                "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
                "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
                "TLS_ECHDE_RSA_WITH_AES_128_GCM_SHA256",
                // maximum interoperability
                "TLS_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA",
                // additionally
                "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
                "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
                "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");

        List<String> availableCiphers = Arrays.asList(ssl.getSupportedCipherSuites());

        // preferred ciphers = allowed Ciphers \ availableCiphers
        HashSet<String> preferredCiphers = new HashSet<String>(allowedCiphers);
        preferredCiphers.retainAll(availableCiphers);

        // add preferred ciphers to enabled ciphers
        // for maximum security, preferred ciphers should *replace* enabled ciphers,
        // but I guess for the security level of DAVdroid, disabling of insecure
        // ciphers should be a server-side task
        HashSet<String> enabledCiphers = preferredCiphers;
        enabledCiphers.addAll(new HashSet<String>(Arrays.asList(ssl.getEnabledCipherSuites())));

        Log.v(TAG, "Setting allowed TLS ciphers: " + StringUtils.join(enabledCiphers, ", "));
        ssl.setEnabledCipherSuites(enabledCiphers.toArray(new String[0]));
    }
}

From source file:com.ryan.ryanreader.reddit.prepared.RedditPreparedPost.java

public static void onActionMenuItemSelected(final RedditPreparedPost post, final Fragment fragmentParent,
        final Action action) {

    final Activity activity = fragmentParent.getSupportActivity();

    switch (action) {

    case UPVOTE://  ww w  .  jav a2  s.co m
        post.action(activity, RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        post.action(activity, RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        post.action(activity, RedditAPI.RedditAction.UNVOTE);
        break;

    case SAVE:
        post.action(activity, RedditAPI.RedditAction.SAVE);
        break;

    case UNSAVE:
        post.action(activity, RedditAPI.RedditAction.UNSAVE);
        break;

    case HIDE:
        post.action(activity, RedditAPI.RedditAction.HIDE);
        break;

    case UNHIDE:
        post.action(activity, RedditAPI.RedditAction.UNHIDE);
        break;

    case REPORT:

        new AlertDialog.Builder(activity).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.REPORT);
                        // TODO update the view to show the result
                        // TODO don't forget, this also hides
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case EXTERNAL: {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(post.url));
        activity.startActivity(intent);
        break;
    }

    case SELFTEXT_LINKS: {

        final HashSet<String> linksInComment = LinkHandler
                .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.selftext));

        if (linksInComment.isEmpty()) {
            General.quickToast(activity, R.string.error_toast_no_urls_in_self);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_selftext_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;
    }

    case SAVE_IMAGE: {

        final RedditAccount anon = RedditAccountManager.getAnon();

        CacheManager.getInstance(activity)
                .makeRequest(new CacheRequest(General.uriFromString(post.imageUrl), anon, null,
                        Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY,
                        Constants.FileType.IMAGE, false, false, false, activity) {

                    @Override
                    protected void onCallbackException(Throwable t) {
                        BugReportActivity.handleGlobalError(context, t);
                    }

                    @Override
                    protected void onDownloadNecessary() {
                        General.quickToast(context, R.string.download_downloading);
                    }

                    @Override
                    protected void onDownloadStarted() {
                    }

                    @Override
                    protected void onFailure(RequestFailureType type, Throwable t, StatusLine status,
                            String readableMessage) {
                        final RRError error = General.getGeneralErrorForFailure(context, type, t, status);
                        General.showResultDialog(activity, error);
                    }

                    @Override
                    protected void onProgress(long bytesRead, long totalBytes) {
                    }

                    @Override
                    protected void onSuccess(CacheManager.ReadableCacheFile cacheFile, long timestamp,
                            UUID session, boolean fromCache, String mimetype) {

                        File dst = new File(
                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                General.uriFromString(post.imageUrl).getPath());

                        if (dst.exists()) {
                            int count = 0;

                            while (dst.exists()) {
                                count++;
                                dst = new File(
                                        Environment.getExternalStoragePublicDirectory(
                                                Environment.DIRECTORY_PICTURES),
                                        count + "_"
                                                + General.uriFromString(post.imageUrl).getPath().substring(1));
                            }
                        }

                        try {
                            General.copyFile(cacheFile.getInputStream(), dst);
                        } catch (IOException e) {
                            notifyFailure(RequestFailureType.STORAGE, e, null, "Could not copy file");
                            return;
                        }

                        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                Uri.parse("file://" + dst.getAbsolutePath())));

                        General.quickToast(context, context.getString(R.string.action_save_image_success) + " "
                                + dst.getAbsolutePath());
                    }
                });

        break;
    }

    case SHARE: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, post.title);
        mailer.putExtra(Intent.EXTRA_TEXT, post.url);
        activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share)));
        break;
    }

    case SHARE_COMMENTS: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.title);
        mailer.putExtra(Intent.EXTRA_TEXT,
                Constants.Reddit.getUri(Constants.Reddit.PATH_COMMENTS + post.idAlone).toString());
        activity.startActivity(
                Intent.createChooser(mailer, activity.getString(R.string.action_share_comments)));
        break;
    }

    case COPY: {

        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        manager.setText(post.url);
        break;
    }

    case GOTO_SUBREDDIT: {

        final RedditSubreddit subreddit = new RedditSubreddit("/r/" + post.src.subreddit,
                "/r/" + post.src.subreddit, true);

        final Intent intent = new Intent(activity, PostListingActivity.class);
        intent.putExtra("subreddit", subreddit);
        activity.startActivityForResult(intent, 1);
        break;
    }

    case USER_PROFILE:
        UserProfileDialog.newInstance(post.src.author).show(activity);
        break;

    case PROPERTIES:
        PostPropertiesDialog.newInstance(post.src).show(activity);
        break;

    case COMMENTS:
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostCommentsSelected(post);
        break;

    case LINK:
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostSelected(post);
        break;

    case COMMENTS_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostCommentsSelected(post);
        break;

    case LINK_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostSelected(post);
        break;

    case ACTION_MENU:
        showActionMenu(activity, fragmentParent, post);
        break;

    case REPLY:
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", post.idAndType);
        activity.startActivity(intent);
        break;
    }
}

From source file:de.uni_tuebingen.ub.ixTheo.handler.component.FacetPrefixSortComponent.java

/**
 * Actually run the query// ww  w. ja v  a  2s.c  o m
 */
@Override
public void process(ResponseBuilder rb) throws IOException {
    if (rb.doFacets) {
        final ModifiableSolrParams params = new ModifiableSolrParams();
        final SolrParams origParams = rb.req.getParams();
        final Iterator<String> iter = origParams.getParameterNamesIterator();
        setCollator(origParams.get("lang"));
        while (iter.hasNext()) {
            final String paramName = iter.next();
            // Deduplicate the list with LinkedHashSet, but _only_ for facet
            // params.
            if (!paramName.startsWith(FacetParams.FACET)) {
                params.add(paramName, origParams.getParams(paramName));
                continue;
            }
            final HashSet<String> deDupe = new LinkedHashSet<>(Arrays.asList(origParams.getParams(paramName)));
            params.add(paramName, deDupe.toArray(new String[deDupe.size()]));
        }

        final SimplePrefixSortFacets facets = new SimplePrefixSortFacets(rb.req, rb.getResults().docSet, params,
                rb);
        final NamedList<Object> counts = org.apache.solr.handler.component.FacetComponent
                .getFacetCounts(facets);

        final String[] pivots = params.getParams(FacetParams.FACET_PIVOT);
        if (pivots != null && pivots.length > 0) {
            PivotFacetProcessor pivotProcessor = new PivotFacetProcessor(rb.req, rb.getResults().docSet, params,
                    rb);
            SimpleOrderedMap<List<NamedList<Object>>> v = pivotProcessor.process(pivots);
            if (v != null) {
                counts.add(PIVOT_KEY, v);
            }
        }

        // Check whether we have to reorder out results
        // according to prefix

        final String sort = params.get(FacetParams.FACET_SORT);
        if (FacetPrefixSortParams.FACET_SORT_PREFIX.equals(sort)) {

            // Determine a score relative to the original query

            // Determine the query and make it compatible with our metric
            // class
            // by splitting the single terms
            String[] queryTerms = params.getParams(CommonParams.Q);
            final Collection<String> queryTermsCollection = new ArrayList<>();
            for (String s : queryTerms) {
                // Split at whitespace except we have a quoted term
                Matcher matcher = WHITE_SPACES_WITH_QUOTES_SPLITTING_PATTERN.matcher(s);
                while (matcher.find()) {
                    queryTermsCollection.add(matcher.group().replaceAll("^\"|\"$", ""));
                }
            }

            // In some contexts, i.e. in KWC that are derived from ordinary
            // keywords or if
            // wildcards occur, also add all the query terms as a single
            // phrase term
            // with stripped wildcards
            StringBuilder sb = new StringBuilder();
            for (String s : queryTermsCollection) {
                s = s.replace("*", "");
                sb.append(s);
                sb.append(" ");
            }

            queryTermsCollection.add(sb.toString().trim());

            final ArrayList<String> queryList = new ArrayList<>(queryTermsCollection);
            final String facetfield = params.get(FacetParams.FACET_FIELD);

            // Get the current facet entry and make it compatible with our
            // metric class
            // "facet_fields" itself contains a NamedList with the
            // facet.field as key

            final NamedList<Object> facetFieldsNamedList = (NamedList<Object>) counts.get("facet_fields");
            final NamedList<Object> facetFields = (NamedList<Object>) facetFieldsNamedList.get(facetfield);

            final List<Entry<Entry<String, Object>, Double>> facetPrefixListScored = new ArrayList<>();
            for (final Entry<String, Object> entry : facetFields) {
                final String facetTerms = entry.getKey();

                // Split up each KWC and calculate the scoring

                ArrayList<String> facetList = new ArrayList<>(
                        Arrays.asList(facetTerms.split("(?<!" + Pattern.quote("\\") + ")/")));

                // For usability reasons sort the result facets according to
                // the order of the search
                facetList = KeywordSort.sortToReferenceChain(queryList, facetList);

                final double score = KeywordChainMetric.calculateSimilarityScore(queryList, facetList);

                // Collect the result in a sorted list and throw away
                // garbage
                if (score > 0) {
                    String facetTermsSorted = StringUtils.join(facetList, "/");
                    Map.Entry<String, Object> sortedEntry = new AbstractMap.SimpleEntry<>(facetTermsSorted,
                            entry.getValue());
                    facetPrefixListScored.add(new AbstractMap.SimpleEntry<>(sortedEntry, score));
                }
            }

            Collections.sort(facetPrefixListScored, ENTRY_COMPARATOR);

            // Extract all the values wrap it back to NamedList again and
            // replace in the original structure

            facetFieldsNamedList.clear();
            NamedList<Object> facetNamedListSorted = new NamedList<>();

            // We had to disable all limits and offsets sort according
            // Handle this accordingly now

            int offset = (params.getInt(FacetParams.FACET_OFFSET) != null)
                    ? params.getInt(FacetParams.FACET_OFFSET)
                    : 0;
            int limit = (params.getInt(FacetParams.FACET_LIMIT) != null)
                    ? params.getInt(FacetParams.FACET_LIMIT)
                    : 100;

            // Strip uneeded elements
            int s = facetPrefixListScored.size();
            int off = (offset < s) ? offset : 0;
            limit = (limit < 0) ? s : limit; // Handle a negative limit
            // param, i.e. unlimited results
            int lim = (offset + limit <= s) ? (offset + limit) : s;

            final List<Entry<Entry<String, Object>, Double>> facetPrefixListScoredTruncated = facetPrefixListScored
                    .subList(off, lim);

            for (Entry<Entry<String, Object>, Double> e : facetPrefixListScoredTruncated) {
                facetNamedListSorted.add(e.getKey().getKey(), e.getKey().getValue());
            }

            facetFieldsNamedList.add(facetfield, facetNamedListSorted);
            NamedList<Object> countList = new NamedList<>();
            countList.add("count", facetPrefixListScored.size());
            facetFieldsNamedList.add(facetfield + "-count", countList);

            counts.remove("facet_fields");
            counts.add("facet_fields", facetFieldsNamedList);
        }

        rb.rsp.add("facet_counts", counts);
    }
}