Example usage for java.util HashSet clear

List of usage examples for java.util HashSet clear

Introduction

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

Prototype

public void clear() 

Source Link

Document

Removes all of the elements from this set.

Usage

From source file:it.iit.genomics.cru.structures.bridges.uniprot.UniprotkbUtils.java

/**
 *
 * @param refSeqs/*from   w ww. ja va 2 s  . c om*/
 * @return
 * @throws BridgesRemoteAccessException
 */
public MapOfMap<String, MoleculeEntry> getUniprotEntriesFromRefSeqs(Collection<String> refSeqs)
        throws BridgesRemoteAccessException {
    String tool = UNIPROT_TOOL;

    MapOfMap<String, MoleculeEntry> refseq2uniprots = new MapOfMap<>(refSeqs);

    if (refSeqs.isEmpty()) {
        return refseq2uniprots;
    }

    HashSet<String> refs2get = new HashSet<>();

    try {
        for (String refseq : refSeqs) {
            if (cache.containsKey(refseq.toUpperCase().split("\\.")[0])) {
                refseq2uniprots.addAll(refseq, cache.get(refseq.toUpperCase().split("\\.")[0]));
            } else {
                refs2get.add(refseq);

                // if size == limit, do query
                if (refs2get.size() == maxQueries) {

                    String location = UNIPROT_SERVER + tool + "/?" + "query=keyword:181+AND+organism:"
                            + URLEncoder.encode("\"" + taxid + "\"", "UTF-8")
                            + "+AND+(database%3A(type%3Arefseq+"
                            + URLEncoder.encode(
                                    "" + StringUtils.join(refs2get, ") OR database:(type:refseq ") + "",
                                    "UTF-8")
                            + "))";

                    Collection<MoleculeEntry> uniprotEntries = getUniprotEntriesXML(location);

                    for (MoleculeEntry entry : uniprotEntries) {
                        for (String xref : entry.getRefseqs()) {
                            if (xref.endsWith(".")) {
                                xref = xref.substring(0, xref.length() - 1);
                            }
                            if (refseq2uniprots.containsKey(xref.trim())) {
                                refseq2uniprots.add(xref, entry);
                            } else if (refseq2uniprots.containsKey(xref.split("[.]")[0])) {
                                refseq2uniprots.add(xref.split("[.]")[0], entry);
                            }
                        }
                    }
                    refs2get.clear();
                }

            }
        }

        if (refs2get.isEmpty()) {
            return refseq2uniprots;
        }

        String location = UNIPROT_SERVER + tool + "/?" + "query=keyword:181+AND+organism:"
                + URLEncoder.encode("\"" + taxid + "\"", "UTF-8") + "+AND+(database%3A(type%3Arefseq+"
                + URLEncoder.encode("" + StringUtils.join(refs2get, ") OR database:(type:refseq ") + "",
                        "UTF-8")
                + "))";

        Collection<MoleculeEntry> uniprotEntries = getUniprotEntriesXML(location);

        for (MoleculeEntry entry : uniprotEntries) {
            for (String xref : entry.getRefseqs()) {
                if (xref.endsWith(".")) {
                    xref = xref.substring(0, xref.length() - 1);
                }
                if (refseq2uniprots.containsKey(xref.trim())) {
                    refseq2uniprots.add(xref, entry);
                } else if (refseq2uniprots.containsKey(xref.split("[.]")[0])) {
                    refseq2uniprots.add(xref.split("[.]")[0], entry);
                }
            }
        }

    } catch (UnsupportedEncodingException e) {
        logger.error("cannot get proteins for " + StringUtils.join(refSeqs, ", "), e);
    }

    return refseq2uniprots;
}

From source file:it.iit.genomics.cru.structures.bridges.uniprot.UniprotkbUtils.java

/**
 *
 * @param ensemblGeneIDs/*from   w ww .ja  v a  2  s . co m*/
 * @return
 * @throws BridgesRemoteAccessException
 */
public MapOfMap<String, MoleculeEntry> getUniprotEntriesFromEnsembl(Collection<String> ensemblGeneIDs)
        throws BridgesRemoteAccessException {
    String tool = UNIPROT_TOOL;

    MapOfMap<String, MoleculeEntry> ensembl2uniprots = new MapOfMap<>(ensemblGeneIDs);

    if (ensemblGeneIDs.isEmpty()) {
        return ensembl2uniprots;
    }

    HashSet<String> refs2get = new HashSet<>();

    try {

        for (String ensemblGeneID : ensemblGeneIDs) {
            if (cache.containsKey(ensemblGeneID.toUpperCase().split("\\.")[0])) {
                ensembl2uniprots.addAll(ensemblGeneID, cache.get(ensemblGeneID.toUpperCase().split("\\.")[0]));
            } else {
                refs2get.add(ensemblGeneID);

                // if size == limit, do query
                if (refs2get.size() == maxQueries) {
                    String location = UNIPROT_SERVER + tool + "/?" + "query=keyword:181+AND+organism:"
                            + URLEncoder.encode("\"" + taxid + "\"", "UTF-8")
                            + "+AND+(database%3A(type%3Aensembl+"
                            + URLEncoder.encode(
                                    "" + StringUtils.join(refs2get, ") OR database:(type:ensembl ") + "",
                                    "UTF-8")
                            + "))";

                    Collection<MoleculeEntry> uniprotEntries = getUniprotEntriesXML(location);

                    for (MoleculeEntry entry : uniprotEntries) {
                        for (String xref : entry.getEnsemblGenes()) {
                            if (xref.endsWith(".")) {
                                xref = xref.substring(0, xref.length() - 1);
                            }
                            if (ensembl2uniprots.containsKey(xref.trim())) {
                                ensembl2uniprots.add(xref, entry);
                            } else if (ensembl2uniprots.containsKey(xref.split("[.]")[0])) {
                                ensembl2uniprots.add(xref.split("[.]")[0], entry);
                            }
                        }
                    }
                    refs2get.clear();
                }
            }
        }

        if (refs2get.isEmpty()) {
            return ensembl2uniprots;
        }

        String location = UNIPROT_SERVER + tool + "/?" + "query=keyword:181+AND+organism:"
                + URLEncoder.encode("\"" + taxid + "\"", "UTF-8") + "+AND+(database%3A(type%3Aensembl+"
                + URLEncoder.encode("" + StringUtils.join(refs2get, ") OR database:(type:ensembl ") + "",
                        "UTF-8")
                + "))";

        Collection<MoleculeEntry> uniprotEntries = getUniprotEntriesXML(location);

        for (MoleculeEntry entry : uniprotEntries) {
            for (String xref : entry.getEnsemblGenes()) {
                if (xref.endsWith(".")) {
                    xref = xref.substring(0, xref.length() - 1);
                }
                if (ensembl2uniprots.containsKey(xref.trim())) {
                    ensembl2uniprots.add(xref, entry);
                } else if (ensembl2uniprots.containsKey(xref.split("[.]")[0])) {
                    ensembl2uniprots.add(xref.split("[.]")[0], entry);
                }
            }
        }

    } catch (UnsupportedEncodingException e) {
        logger.error("cannot get proteins for " + StringUtils.join(ensemblGeneIDs, ", "), e);
    }

    return ensembl2uniprots;
}

From source file:com.android.mms.transaction.MessagingNotification.java

/**
 * updateNotification is *the* main function for building the actual notification handed to
 * the NotificationManager/*from  w  w w.  j  av a 2s  .c om*/
 * @param context
 * @param newThreadId the new thread id
 * @param uniqueThreadCount
 * @param notificationSet the set of notifications to display
 */
private static void updateNotification(Context context, long newThreadId, int uniqueThreadCount,
        SortedSet<NotificationInfo> notificationSet) {
    boolean isNew = newThreadId != THREAD_NONE;
    CMConversationSettings conversationSettings = CMConversationSettings.getOrNew(context, newThreadId);

    // If the user has turned off notifications in settings, don't do any notifying.
    if ((isNew && !conversationSettings.getNotificationEnabled())
            || !MessagingPreferenceActivity.getNotificationEnabled(context)) {
        if (DEBUG) {
            Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing");
        }
        return;
    }

    // Figure out what we've got -- whether all sms's, mms's, or a mixture of both.
    final int messageCount = notificationSet.size();
    NotificationInfo mostRecentNotification = notificationSet.first();

    final NotificationCompat.Builder noti = new NotificationCompat.Builder(context)
            .setWhen(mostRecentNotification.mTimeMillis);

    if (isNew) {
        noti.setTicker(mostRecentNotification.mTicker);
    }

    // If we have more than one unique thread, change the title (which would
    // normally be the contact who sent the message) to a generic one that
    // makes sense for multiple senders, and change the Intent to take the
    // user to the conversation list instead of the specific thread.

    // Cases:
    //   1) single message from single thread - intent goes to ComposeMessageActivity
    //   2) multiple messages from single thread - intent goes to ComposeMessageActivity
    //   3) messages from multiple threads - intent goes to ConversationList

    final Resources res = context.getResources();
    String title = null;
    Bitmap avatar = null;
    PendingIntent pendingIntent = null;
    boolean isMultiNewMessages = MessageUtils.isMailboxMode() ? messageCount > 1 : uniqueThreadCount > 1;
    if (isMultiNewMessages) { // messages from multiple threads
        Intent mainActivityIntent = getMultiThreadsViewIntent(context);
        pendingIntent = PendingIntent.getActivity(context, 0, mainActivityIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        title = context.getString(R.string.message_count_notification, messageCount);
    } else { // same thread, single or multiple messages
        title = mostRecentNotification.mTitle;
        avatar = mostRecentNotification.mSender.getAvatar(context);
        noti.setSubText(mostRecentNotification.mSimName); // no-op in single SIM case
        if (avatar != null) {
            // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we
            // have to scale 'em up to 128x128 to fill the whole notification large icon.
            final int idealIconHeight = res
                    .getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
            final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
            noti.setLargeIcon(BitmapUtil.getRoundedBitmap(avatar, idealIconWidth, idealIconHeight));
        }

        pendingIntent = PendingIntent.getActivity(context, 0, mostRecentNotification.mClickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }
    // Always have to set the small icon or the notification is ignored
    noti.setSmallIcon(R.drawable.stat_notify_sms);

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);

    // Update the notification.
    noti.setContentTitle(title).setContentIntent(pendingIntent)
            .setColor(context.getResources().getColor(R.color.mms_theme_color))
            .setCategory(Notification.CATEGORY_MESSAGE).setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming
                                                                                                                                                                                                                                  // from a favorite.

    // Tag notification with all senders.
    for (NotificationInfo info : notificationSet) {
        Uri peopleReferenceUri = info.mSender.getPeopleReferenceUri();
        if (peopleReferenceUri != null) {
            noti.addPerson(peopleReferenceUri.toString());
        }
    }

    int defaults = 0;

    if (isNew) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

        if (conversationSettings.getVibrateEnabled()) {
            String pattern = conversationSettings.getVibratePattern();

            if (!TextUtils.isEmpty(pattern)) {
                noti.setVibrate(parseVibratePattern(pattern));
            } else {
                defaults |= Notification.DEFAULT_VIBRATE;
            }
        }

        String ringtoneStr = conversationSettings.getNotificationTone();
        noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
        Log.d(TAG, "updateNotification: new message, adding sound to the notification");
    }

    defaults |= Notification.DEFAULT_LIGHTS;

    noti.setDefaults(defaults);

    // set up delete intent
    noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0));

    // See if QuickMessage pop-up support is enabled in preferences
    boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context);

    // Set up the QuickMessage intent
    Intent qmIntent = null;
    if (mostRecentNotification.mIsSms) {
        // QuickMessage support is only for SMS
        qmIntent = new Intent();
        qmIntent.setClass(context, QuickMessagePopup.class);
        qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName());
        qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber());
        qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification);
    }

    // Start getting the notification ready
    final Notification notification;

    //Create a WearableExtender to add actions too
    WearableExtender wearableExtender = new WearableExtender();

    if (messageCount == 1 || uniqueThreadCount == 1) {
        // Add the Quick Reply action only if the pop-up won't be shown already
        if (!qmPopupEnabled && qmIntent != null) {

            // This is a QR, we should show the keyboard when the user taps to reply
            qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true);

            // Create the pending intent and add it to the notification
            CharSequence qmText = context.getText(R.string.menu_reply);
            PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent);

            //Wearable
            noti.extend(wearableExtender.addAction(
                    new NotificationCompat.Action.Builder(R.drawable.ic_reply, qmText, qmPendingIntent)
                            .build()));
        }

        // Add the 'Mark as read' action
        CharSequence markReadText = context.getText(R.string.qm_mark_read);
        Intent mrIntent = new Intent();
        mrIntent.setClass(context, QmMarkRead.class);
        mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId);
        PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        noti.addAction(R.drawable.ic_mark_read, markReadText, mrPendingIntent);

        // Add the Call action
        CharSequence callText = context.getText(R.string.menu_call);
        Intent callIntent = new Intent(Intent.ACTION_CALL);
        callIntent.setData(Uri.parse("tel:" + mostRecentNotification.mSender.getNumber()));
        PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent);

        //Wearable
        noti.extend(wearableExtender.addAction(
                new NotificationCompat.Action.Builder(R.drawable.ic_menu_call, callText, callPendingIntent)
                        .build()));

        //Set up remote input
        String replyLabel = context.getString(R.string.qm_wear_voice_reply);
        RemoteInput remoteInput = new RemoteInput.Builder(QuickMessageWear.EXTRA_VOICE_REPLY)
                .setLabel(replyLabel).build();
        //Set up pending intent for voice reply
        Intent voiceReplyIntent = new Intent(context, QuickMessageWear.class);
        voiceReplyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        voiceReplyIntent.putExtra(QuickMessageWear.SMS_CONATCT, mostRecentNotification.mSender.getName());
        voiceReplyIntent.putExtra(QuickMessageWear.SMS_SENDER, mostRecentNotification.mSender.getNumber());
        voiceReplyIntent.putExtra(QuickMessageWear.SMS_THEAD_ID, mostRecentNotification.mThreadId);
        PendingIntent voiceReplyPendingIntent = PendingIntent.getActivity(context, 0, voiceReplyIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        //Wearable voice reply action
        NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_reply,
                context.getString(R.string.qm_wear_reply_by_voice), voiceReplyPendingIntent)
                        .addRemoteInput(remoteInput).build();
        noti.extend(wearableExtender.addAction(action));
    }

    if (messageCount == 1) {
        // We've got a single message

        // This sets the text for the collapsed form:
        noti.setContentText(mostRecentNotification.formatBigMessage(context));

        if (mostRecentNotification.mAttachmentBitmap != null) {
            // The message has a picture, show that

            NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(noti)
                    .bigPicture(mostRecentNotification.mAttachmentBitmap)
                    .setSummaryText(mostRecentNotification.formatPictureMessage(context));

            notification = noti.setStyle(bigPictureStyle).build();
        } else {
            // Show a single notification -- big style with the text of the whole message
            NotificationCompat.BigTextStyle bigTextStyle1 = new NotificationCompat.BigTextStyle(noti)
                    .bigText(mostRecentNotification.formatBigMessage(context));

            notification = noti.setStyle(bigTextStyle1).build();
        }
        if (DEBUG) {
            Log.d(TAG, "updateNotification: single message notification");
        }
    } else {
        // We've got multiple messages
        if (!isMultiNewMessages) {
            // We've got multiple messages for the same thread.
            // Starting with the oldest new message, display the full text of each message.
            // Begin a line for each subsequent message.
            SpannableStringBuilder buf = new SpannableStringBuilder();
            NotificationInfo infos[] = notificationSet.toArray(new NotificationInfo[messageCount]);
            int len = infos.length;
            for (int i = len - 1; i >= 0; i--) {
                NotificationInfo info = infos[i];

                buf.append(info.formatBigMessage(context));

                if (i != 0) {
                    buf.append('\n');
                }
            }

            noti.setContentText(context.getString(R.string.message_count_notification, messageCount));

            // Show a single notification -- big style with the text of all the messages
            NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
            bigTextStyle.bigText(buf)
                    // Forcibly show the last line, with the app's smallIcon in it, if we
                    // kicked the smallIcon out with an avatar bitmap
                    .setSummaryText((avatar == null) ? null : " ");
            notification = noti.setStyle(bigTextStyle).build();
            if (DEBUG) {
                Log.d(TAG, "updateNotification: multi messages for single thread");
            }
        } else {
            // Build a set of the most recent notification per threadId.
            HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount);
            ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>();
            Iterator<NotificationInfo> notifications = notificationSet.iterator();
            while (notifications.hasNext()) {
                NotificationInfo notificationInfo = notifications.next();
                if (!uniqueThreads.contains(notificationInfo.mThreadId)) {
                    uniqueThreads.add(notificationInfo.mThreadId);
                    mostRecentNotifPerThread.add(notificationInfo);
                }
            }
            // When collapsed, show all the senders like this:
            //     Fred Flinstone, Barry Manilow, Pete...
            noti.setContentText(formatSenders(context, mostRecentNotifPerThread));
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(noti);

            // We have to set the summary text to non-empty so the content text doesn't show
            // up when expanded.
            inboxStyle.setSummaryText(" ");

            // At this point we've got multiple messages in multiple threads. We only
            // want to show the most recent message per thread, which are in
            // mostRecentNotifPerThread.
            int uniqueThreadMessageCount = mostRecentNotifPerThread.size();
            int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount);

            for (int i = 0; i < maxMessages; i++) {
                NotificationInfo info = mostRecentNotifPerThread.get(i);
                inboxStyle.addLine(info.formatInboxMessage(context));
            }
            notification = inboxStyle.build();

            uniqueThreads.clear();
            mostRecentNotifPerThread.clear();

            if (DEBUG) {
                Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification");
            }
        }
    }

    notifyUserIfFullScreen(context, title);
    nm.notify(NOTIFICATION_ID, notification);

    // Trigger the QuickMessage pop-up activity if enabled
    // But don't show the QuickMessage if the user is in a call or the phone is ringing
    if (qmPopupEnabled && qmIntent != null) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE && !ConversationList.mIsRunning
                && !ComposeMessageActivity.mIsRunning) {
            context.startActivity(qmIntent);
        }
    }
}

From source file:com.tulskiy.musique.library.Library.java

public void rescan(Map<String, Object> progress) {
    List<String> folders = LibraryConfiguration.getFolders();
    if (CollectionUtils.isEmpty(folders)) {
        return;/*from   w  ww.j  av a 2  s  .c  o  m*/
    }
    progress.put("processing.file", "");

    data.removeDeadItems();

    HashMap<TrackData, Track> trackDatas = new HashMap<TrackData, Track>();
    for (Track track : data) {
        trackDatas.put(track.getTrackData(), track);
    }

    LinkedList<File> queue = new LinkedList<File>();
    for (String path : folders) {
        File f = new File(path);
        if (f.exists())
            queue.add(f);
    }

    HashSet<Track> processed = new HashSet<Track>();
    final Set<String> formats = Codecs.getFormats();
    ArrayList<Track> temp = new ArrayList<Track>();
    while (!queue.isEmpty()) {
        try {
            File file = queue.pop();
            if (progress != null) {
                if (progress.get("processing.stop") != null) {
                    break;
                }
                progress.put("processing.file", file.getAbsolutePath());
            }
            if (file.isDirectory()) {
                queue.addAll(0, Arrays.asList(file.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File file) {
                        if (file.isHidden() || !file.canRead()) {
                            return false;
                        }

                        if (file.isDirectory())
                            return true;

                        String ext = Util.getFileExt(file).toLowerCase();
                        if (formats.contains(ext)) {
                            String name = Util.removeExt(file.getAbsolutePath()) + ".cue";
                            return !new File(name).exists();
                        }
                        return ext.equals("cue");
                    }
                })));
            } else {
                TrackData trackData = new TrackData(file.toURI(), 0);
                Track track = trackDatas.get(trackData);
                if (track != null) {
                    if (track.getTrackData().getLastModified() != file.lastModified()) {
                        track.getTrackData().clearTags();
                        TrackIO.getAudioFileReader(file.getName()).reload(track);
                    }
                    processed.add(track);
                } else {
                    temp.clear();
                    TrackIO.getAudioFileReader(file.getName()).read(file, temp);
                    for (Track newTrack : temp) {
                        trackData = newTrack.getTrackData();
                        if (trackDatas.containsKey(trackData)) {
                            // it must be the cue file, so  merge the track data
                            trackData.merge(newTrack.getTrackData());
                        }
                        processed.add(newTrack);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    data.clear();
    data.addAll(processed);
    processed.clear();
    trackDatas.clear();
    rebuildTree();
}

From source file:com.dtolabs.rundeck.core.authorization.providers.TestYamlPolicy.java

public void testYamlEnvironmentalContext() throws URISyntaxException {
    {/*w w  w .j  a v a  2 s  .c  o m*/
        final Map context = new HashMap();
        context.put("project", "abc");
        final YamlPolicy.YamlEnvironmentalContext test = new YamlPolicy.YamlEnvironmentalContext("test://",
                context);

        assertTrue(test.isValid());
        final HashSet<Attribute> env = new HashSet<Attribute>();

        //empty env
        assertFalse(test.matches(env));

        //single matching env
        env.add(new Attribute(new URI("test://project"), "abc"));
        assertTrue(test.matches(env));

        //multi attrs, matches context value
        env.add(new Attribute(new URI("test://application"), "bloo"));
        assertTrue(test.matches(env));
    }
    {
        final Map context = new HashMap();
        context.put("project", "ab[c");
        final YamlPolicy.YamlEnvironmentalContext test = new YamlPolicy.YamlEnvironmentalContext("test://",
                context);

        assertTrue(test.isValid());
        final HashSet<Attribute> env = new HashSet<Attribute>();

        //invalid regex should be equality check
        env.add(new Attribute(new URI("test://project"), "abc"));
        assertFalse(test.matches(env));

        env.clear();
        env.add(new Attribute(new URI("test://project"), "ab[c"));
        assertTrue(test.matches(env));

    }
}

From source file:phonegraph.PhoneGraph.java

public void CreateGraphGT(String filename, int k) {
    try {//from   w w w .  j av  a  2s.  c o m
        FileReader fileReader = new FileReader(filename);
        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line;
        int count = 0;
        HashSet<Integer> nodes = new HashSet<Integer>(10000);
        while ((line = bufferedReader.readLine()) != null) {
            //ignore the prefix for phone and uri
            JSONObject documentInfo = (JSONObject) new JSONParser().parse(line);
            JSONArray phones = (JSONArray) documentInfo.get("high_precision_phone");
            //JSONObject rawdata = (JSONObject)documentInfo.get("crawl_data");
            if (phones != null) {
                for (int i = 0; i < phones.size(); i++) {
                    JSONObject o = (JSONObject) phones.get(i);
                    JSONArray a = (JSONArray) o.get("result");
                    for (int j = 0; j < a.size(); j++) {
                        JSONObject entity = (JSONObject) a.get(j);
                        String phone = (String) entity.get("value");
                        if (phonemaps.containsKey(phone) == true) {
                            int id = phonemaps.get(phone);
                            nodes.add(id);
                        }
                    }
                }

            }
            JSONArray emails = (JSONArray) documentInfo.get("high_precision_email");
            if (emails != null) {
                for (int i = 0; i < emails.size(); i++) {
                    JSONObject o = (JSONObject) emails.get(i);
                    JSONArray a = (JSONArray) o.get("result");
                    for (int j = 0; j < a.size(); j++) {
                        JSONObject entity = (JSONObject) a.get(j);
                        String email = (String) entity.get("value");
                        if (phonemaps.containsKey(email) == true) {
                            int id = phonemaps.get(email);
                            nodes.add(id);
                        }
                    }
                }
            }
            if (nodes.size() < k) {
                Integer[] arr = nodes.toArray(new Integer[nodes.size()]);
                for (int i = 0; i < arr.length; i++) {
                    for (int j = (i + 1); j < arr.length; j++) {
                        IntPair o = new IntPair(arr[i], arr[j]);
                        if (arr[i] > arr[j]) {
                            o.setKey(arr[j]);
                            o.setValue(arr[i]);
                        }
                        if (this.edges.containsKey(o) == false) {
                            this.edges.put(o, 1);
                        } else {
                            int freq = this.edges.get(o);
                            this.edges.put(o, freq + 1);
                        }
                    }
                }
            }
            nodes.clear();
            count++;
            if (count % 100 == 0) {
                System.out.println(count);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(PhoneGraph.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(PhoneGraph.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ddf.catalog.impl.CatalogFrameworkImplTest.java

@Test
public void testCreateWithStores() throws Exception {
    MockEventProcessor eventAdmin = new MockEventProcessor();
    MockMemoryProvider provider = new MockMemoryProvider("Provider", "Provider", "v1.0", "DDF", new HashSet<>(),
            true, new Date());

    Map<String, CatalogStore> storeMap = new HashMap<>();

    MockCatalogStore store = new MockCatalogStore("catalogStoreId-1", true);
    storeMap.put(store.getId(), store);//from   w  ww . j  a  v a 2  s  .  com

    CatalogFramework framework = createDummyCatalogFramework(provider, storeMap, null, eventAdmin);

    List<Metacard> metacards = new ArrayList<>();
    MetacardImpl newCard = new MetacardImpl();
    newCard.setId(null);
    metacards.add(newCard);
    Map<String, Serializable> reqProps = new HashMap<>();
    HashSet<String> destinations = new HashSet<>();

    //==== test writing to store and not local ====
    destinations.add("catalogStoreId-1");
    CreateResponse response = framework.create(new CreateRequestImpl(metacards, reqProps, destinations));
    assertEquals(0, provider.size());
    assertEquals(response.getCreatedMetacards().size(), store.size());
    assertEquals(1, store.size());
    assertFalse(eventAdmin.wasEventPosted());

    //==== test writing to store and local ====
    destinations.add("mockMemoryProvider");
    newCard.setId(null);
    reqProps = new HashMap<>();
    response = framework.create(new CreateRequestImpl(metacards, reqProps, destinations));
    assertEquals(1, provider.size());
    assertEquals(response.getCreatedMetacards().size(), provider.size());
    assertEquals(2, store.size());
    assertTrue(eventAdmin.wasEventPosted());

    //==== test writing to local when no destination ====
    destinations.clear();
    newCard.setId(null);
    reqProps = new HashMap<>();
    response = framework.create(new CreateRequestImpl(metacards, reqProps, destinations));
    assertEquals(2, provider.size());
    assertEquals(response.getCreatedMetacards().size(), 1);
    assertEquals(2, store.size());
}

From source file:ddf.catalog.impl.CatalogFrameworkImplTest.java

@Test
public void testUpdateWithStores() throws Exception {
    MockEventProcessor eventAdmin = new MockEventProcessor();
    MockMemoryProvider provider = new MockMemoryProvider("Provider", "Provider", "v1.0", "DDF", new HashSet<>(),
            true, new Date());

    Map<String, CatalogStore> storeMap = new HashMap<>();
    Map<String, FederatedSource> sourceMap = new HashMap<>();
    MockCatalogStore store = new MockCatalogStore("catalogStoreId-1", true);
    storeMap.put(store.getId(), store);//from w w w  .  j a v  a2  s  .  co m
    sourceMap.put(store.getId(), store);

    CatalogFramework framework = createDummyCatalogFramework(provider, storeMap, sourceMap, eventAdmin);
    FilterFactory filterFactory = new FilterFactoryImpl();

    Filter filter = filterFactory.like(filterFactory.property(Metacard.METADATA), "*", "*", "?", "/", false);

    List<Metacard> metacards = new ArrayList<>();
    String id = UUID.randomUUID().toString();
    MetacardImpl newCard = new MetacardImpl();
    newCard.setId(id);
    newCard.setAttribute("myKey", "myValue1");
    metacards.add(newCard);
    Map<String, Serializable> reqProps = new HashMap<>();
    HashSet<String> destinations = new HashSet<>();
    destinations.add("mockMemoryProvider");
    destinations.add("catalogStoreId-1");
    framework.create(new CreateRequestImpl(metacards, reqProps, destinations));

    MetacardImpl updateCard = new MetacardImpl();
    updateCard.setId(id);
    updateCard.setAttribute("myKey", "myValue2");
    List<Entry<Serializable, Metacard>> updates = new ArrayList<>();
    updates.add(new SimpleEntry<>(id, updateCard));
    destinations.remove("mockMemoryProvider");
    framework.update(new UpdateRequestImpl(updates, Metacard.ID, new HashMap<>(), destinations));
    assertThat(provider.hasReceivedUpdateByIdentifier(), is(false));
    assertThat(store.hasReceivedUpdateByIdentifier(), is(true));
    QueryResponse storeResponse = framework.query(new QueryRequestImpl(new QueryImpl(filter), destinations));
    assertThat(storeResponse.getResults().size(), is(1));
    assertThat(storeResponse.getResults().get(0).getMetacard().getAttribute("myKey").getValue(),
            equalTo("myValue2"));
    destinations.clear();
    QueryResponse providerResponse = framework.query(new QueryRequestImpl(new QueryImpl(filter), destinations));
    assertThat(providerResponse.getResults().size(), is(1));
    assertThat(providerResponse.getResults().get(0).getMetacard().getAttribute("myKey").getValue(),
            equalTo("myValue1"));

}

From source file:com.mishiranu.dashchan.ui.navigator.page.PostsPage.java

@Override
public boolean onSearchSubmit(String query) {
    PostsAdapter adapter = getAdapter();
    if (adapter.isEmpty()) {
        return false;
    }/* ww w . j a v  a 2  s.c om*/
    searchFoundPosts.clear();
    int listPosition = ListPosition.obtain(getListView()).position;
    searchLastPosition = 0;
    boolean positionDefined = false;
    Locale locale = Locale.getDefault();
    SearchHelper helper = new SearchHelper();
    helper.setFlags("m", "r", "a", "d", "e", "op");
    HashSet<String> queries = helper.handleQueries(locale, query);
    HashSet<String> fileNames = new HashSet<>();
    PostsExtra extra = getExtra();
    OUTER: for (int i = 0; i < adapter.getCount(); i++) {
        PostItem postItem = adapter.getItem(i);
        if (postItem != null && !postItem.isHidden(hidePerformer)) {
            String postNumber = postItem.getPostNumber();
            String comment = postItem.getComment().toString().toLowerCase(locale);
            boolean userPost = postItem.isUserPost();
            boolean reply = false;
            HashSet<String> referencesTo = postItem.getReferencesTo();
            if (referencesTo != null) {
                for (String referenceTo : referencesTo) {
                    if (extra.userPostNumbers.contains(referenceTo)) {
                        reply = true;
                        break;
                    }
                }
            }
            boolean hasAttachments = postItem.hasAttachments();
            boolean deleted = postItem.isDeleted();
            boolean edited = lastEditedPostNumbers.contains(postNumber);
            boolean originalPoster = postItem.isOriginalPoster();
            if (!helper.checkFlags("m", userPost, "r", reply, "a", hasAttachments, "d", deleted, "e", edited,
                    "op", originalPoster)) {
                continue;
            }
            for (String lowQuery : helper.getExcluded()) {
                if (comment.contains(lowQuery)) {
                    continue OUTER;
                }
            }
            String subject = postItem.getSubject().toLowerCase(locale);
            String name = postItem.getFullName().toString().toLowerCase(locale);
            fileNames.clear();
            ArrayList<AttachmentItem> attachmentItems = postItem.getAttachmentItems();
            if (attachmentItems != null) {
                for (AttachmentItem attachmentItem : attachmentItems) {
                    String fileName = attachmentItem.getFileName();
                    if (fileName != null) {
                        fileNames.add(fileName.toLowerCase(locale));
                        String originalName = attachmentItem.getOriginalName();
                        if (originalName != null) {
                            fileNames.add(originalName.toLowerCase(locale));
                        }
                    }
                }
            }
            boolean found = false;
            if (helper.hasIncluded()) {
                QUERIES: for (String lowQuery : helper.getIncluded()) {
                    if (comment.contains(lowQuery)) {
                        found = true;
                        break;
                    } else if (subject.contains(lowQuery)) {
                        found = true;
                        break;
                    } else if (name.contains(lowQuery)) {
                        found = true;
                        break;
                    } else {
                        for (String fileName : fileNames) {
                            if (fileName.contains(lowQuery)) {
                                found = true;
                                break QUERIES;
                            }
                        }
                    }
                }
            } else {
                found = true;
            }
            if (found) {
                if (!positionDefined && i > listPosition) {
                    searchLastPosition = searchFoundPosts.size();
                    positionDefined = true;
                }
                searchFoundPosts.add(i);
            }
        }
    }
    boolean found = searchFoundPosts.size() > 0;
    getUiManager().view().setHighlightText(found ? queries : null);
    adapter.notifyDataSetChanged();
    searching = true;
    if (found) {
        setCustomSearchView(searchController);
        updateOptionsMenu(true);
        searchLastPosition--;
        findForward();
        return true;
    } else {
        ToastUtils.show(getActivity(), R.string.message_not_found);
        searchLastPosition = -1;
        updateSearchTitle();
        return false;
    }
}

From source file:gov.nih.nci.evs.browser.utils.DataUtils.java

public static Vector getPropertyNamesByType(Entity concept, String property_type) {
    Vector v = new Vector();
    org.LexGrid.commonTypes.Property[] properties = null;

    if (property_type.compareToIgnoreCase("GENERIC") == 0) {
        properties = concept.getProperty();
    } else if (property_type.compareToIgnoreCase("PRESENTATION") == 0) {
        properties = concept.getPresentation();
    } else if (property_type.compareToIgnoreCase("COMMENT") == 0) {
        properties = concept.getComment();
    } else if (property_type.compareToIgnoreCase("DEFINITION") == 0) {
        properties = concept.getDefinition();
    }//from   w  w  w. jav  a2  s.  co  m

    if (properties == null || properties.length == 0)
        return v;
    HashSet hset = new HashSet();
    for (int i = 0; i < properties.length; i++) {
        Property p = (Property) properties[i];
        String nm = p.getPropertyName();
        if (!hset.contains(nm)) {
            hset.add(nm);
            v.add(p.getPropertyName());
        }
    }
    hset.clear();
    return v;
}