Example usage for java.util SortedSet size

List of usage examples for java.util SortedSet size

Introduction

In this page you can find the example usage for java.util SortedSet size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

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  a  v  a  2s.  com
 * @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:org.apache.tajo.storage.hbase.HBaseTablespace.java

/**
 * Returns initial region split keys./*from   w w  w .j a  v  a 2  s .  co m*/
 *
 * @param conf
 * @param schema
 * @param meta
 * @return
 * @throws java.io.IOException
 */
private byte[][] getSplitKeys(TajoConf conf, String hbaseTableName, Schema schema, TableMeta meta)
        throws MissingTablePropertyException, InvalidTablePropertyException, IOException {

    String splitRowKeys = meta.getProperty(HBaseStorageConstants.META_SPLIT_ROW_KEYS_KEY, "");
    String splitRowKeysFile = meta.getProperty(HBaseStorageConstants.META_SPLIT_ROW_KEYS_FILE_KEY, "");

    if ((splitRowKeys == null || splitRowKeys.isEmpty())
            && (splitRowKeysFile == null || splitRowKeysFile.isEmpty())) {
        return null;
    }

    ColumnMapping columnMapping = new ColumnMapping(schema, meta.getPropertySet());
    boolean[] isBinaryColumns = columnMapping.getIsBinaryColumns();
    boolean[] isRowKeys = columnMapping.getIsRowKeyMappings();

    boolean rowkeyBinary = false;
    int numRowKeys = 0;
    Column rowKeyColumn = null;
    for (int i = 0; i < isBinaryColumns.length; i++) {
        if (isBinaryColumns[i] && isRowKeys[i]) {
            rowkeyBinary = true;
        }
        if (isRowKeys[i]) {
            numRowKeys++;
            rowKeyColumn = schema.getColumn(i);
        }
    }

    if (rowkeyBinary && numRowKeys > 1) {
        throw new InvalidTablePropertyException("If rowkey is mapped to multi column and a rowkey is binary, "
                + "Multiple region for creation is not support.", hbaseTableName);
    }

    if (splitRowKeys != null && !splitRowKeys.isEmpty()) {
        String[] splitKeyTokens = splitRowKeys.split(",");
        byte[][] splitKeys = new byte[splitKeyTokens.length][];
        for (int i = 0; i < splitKeyTokens.length; i++) {
            if (numRowKeys == 1 && rowkeyBinary) {
                splitKeys[i] = HBaseBinarySerializerDeserializer.serialize(rowKeyColumn,
                        new TextDatum(splitKeyTokens[i]));
            } else {
                splitKeys[i] = HBaseTextSerializerDeserializer.serialize(rowKeyColumn,
                        new TextDatum(splitKeyTokens[i]));
            }
        }
        return splitKeys;
    }

    if (splitRowKeysFile != null && !splitRowKeysFile.isEmpty()) {
        // If there is many split keys, Tajo allows to define in the file.
        Path path = new Path(splitRowKeysFile);
        FileSystem fs = path.getFileSystem(conf);

        if (!fs.exists(path)) {
            throw new MissingTablePropertyException(
                    "hbase.split.rowkeys.file=" + path.toString() + " not exists.", hbaseTableName);
        }

        SortedSet<String> splitKeySet = new TreeSet<>();
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new InputStreamReader(fs.open(path)));
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (line.isEmpty()) {
                    continue;
                }
                splitKeySet.add(line);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        if (splitKeySet.isEmpty()) {
            return null;
        }

        byte[][] splitKeys = new byte[splitKeySet.size()][];
        int index = 0;
        for (String eachKey : splitKeySet) {
            if (numRowKeys == 1 && rowkeyBinary) {
                splitKeys[index++] = HBaseBinarySerializerDeserializer.serialize(rowKeyColumn,
                        new TextDatum(eachKey));
            } else {
                splitKeys[index++] = HBaseTextSerializerDeserializer.serialize(rowKeyColumn,
                        new TextDatum(eachKey));
            }
        }

        return splitKeys;
    }

    return null;
}

From source file:org.fenixedu.ulisboa.specifications.domain.evaluation.markSheet.CompetenceCourseMarkSheet.java

public GradeScaleValidator getGradeScaleValidator() {
    final SortedSet<GradeScaleValidator> result = Sets.newTreeSet(DomainObjectUtil.COMPARATOR_BY_ID);

    for (final GradeScaleValidator validator : EvaluationSeasonRule.find(getEvaluationSeason(),
            GradeScaleValidator.class)) {

        if (validator.getGradeScale() != getGradeScale()) {
            continue;
        }//from   w w w  .j  a va2 s .c  om

        final Set<DegreeType> markSheetDegreeTypes = getExecutionCourse().getAssociatedCurricularCoursesSet()
                .stream().map(c -> c.getDegree().getDegreeType()).collect(Collectors.toSet());
        if (Sets.intersection(markSheetDegreeTypes, validator.getDegreeTypeSet()).isEmpty()) {
            continue;
        }

        if (!validator.getAppliesToCurriculumAggregatorEntry()
                || !isCurriculumAggregatorEntryScaleConsistent()) {
            continue;
        }

        result.add(validator);
    }

    if (result.size() > 1) {
        logger.warn("Mark sheet {} has more than one GradeScaleValidator configured, returning the oldest",
                this);
    }

    return result.isEmpty() ? null : result.first();
}

From source file:org.codehaus.groovy.grails.web.mapping.DefaultUrlMappingsHolder.java

/**
 * Performs a match uses reverse mappings to looks up a mapping from the
 * controller, action and params. This is refactored to use a list of mappings
 * identified by only controller and action and then matches the mapping to select
 * the mapping that best matches the params (most possible matches).
 *
 *
 * @param controller The controller name
 * @param action The action name//  www.  j  av a 2  s  .c  om
 * @param httpMethod The HTTP method
 * @param version
 * @param params The params  @return A UrlMapping instance or null
 */
@SuppressWarnings("unchecked")
protected UrlMapping lookupMapping(String controller, String action, String namespace, String pluginName,
        String httpMethod, String version, Map params) {
    final UrlMappingsListKey lookupKey = new UrlMappingsListKey(controller, action, namespace, pluginName,
            httpMethod, version);
    SortedSet mappingKeysSet = mappingsListLookup.get(lookupKey);

    final String actionName = lookupKey.action;
    boolean secondAttempt = false;
    final boolean isIndexAction = GrailsControllerClass.INDEX_ACTION.equals(actionName);
    if (null == mappingKeysSet) {
        lookupKey.httpMethod = UrlMapping.ANY_HTTP_METHOD;
        mappingKeysSet = mappingsListLookup.get(lookupKey);
    }
    if (null == mappingKeysSet && actionName != null) {
        lookupKey.action = null;

        mappingKeysSet = mappingsListLookup.get(lookupKey);
        secondAttempt = true;
    }
    if (null == mappingKeysSet)
        return null;

    Set<String> lookupParams = new HashSet<String>(params.keySet());
    if (secondAttempt) {
        lookupParams.removeAll(DEFAULT_ACTION_PARAMS);
        lookupParams.addAll(DEFAULT_ACTION_PARAMS);
    }

    UrlMappingKey[] mappingKeys = (UrlMappingKey[]) mappingKeysSet
            .toArray(new UrlMappingKey[mappingKeysSet.size()]);
    for (int i = mappingKeys.length; i > 0; i--) {
        UrlMappingKey mappingKey = mappingKeys[i - 1];
        if (lookupParams.containsAll(mappingKey.paramNames)) {
            final UrlMapping mapping = mappingsLookup.get(mappingKey);
            if (canInferAction(actionName, secondAttempt, isIndexAction, mapping)) {
                return mapping;
            }
            if (!secondAttempt) {
                return mapping;
            }
        }
    }
    return null;
}

From source file:org.apache.tajo.storage.hbase.HBaseStorageManager.java

/**
 * Returns initial region split keys./*  ww  w .  j  av a 2  s  . c o m*/
 *
 * @param conf
 * @param schema
 * @param meta
 * @return
 * @throws java.io.IOException
 */
private byte[][] getSplitKeys(TajoConf conf, Schema schema, TableMeta meta) throws IOException {
    String splitRowKeys = meta.getOption(HBaseStorageConstants.META_SPLIT_ROW_KEYS_KEY, "");
    String splitRowKeysFile = meta.getOption(HBaseStorageConstants.META_SPLIT_ROW_KEYS_FILE_KEY, "");

    if ((splitRowKeys == null || splitRowKeys.isEmpty())
            && (splitRowKeysFile == null || splitRowKeysFile.isEmpty())) {
        return null;
    }

    ColumnMapping columnMapping = new ColumnMapping(schema, meta);
    boolean[] isBinaryColumns = columnMapping.getIsBinaryColumns();
    boolean[] isRowKeys = columnMapping.getIsRowKeyMappings();

    boolean rowkeyBinary = false;
    int numRowKeys = 0;
    Column rowKeyColumn = null;
    for (int i = 0; i < isBinaryColumns.length; i++) {
        if (isBinaryColumns[i] && isRowKeys[i]) {
            rowkeyBinary = true;
        }
        if (isRowKeys[i]) {
            numRowKeys++;
            rowKeyColumn = schema.getColumn(i);
        }
    }

    if (rowkeyBinary && numRowKeys > 1) {
        throw new IOException("If rowkey is mapped to multi column and a rowkey is binary, "
                + "Multiple region for creation is not support.");
    }

    if (splitRowKeys != null && !splitRowKeys.isEmpty()) {
        String[] splitKeyTokens = splitRowKeys.split(",");
        byte[][] splitKeys = new byte[splitKeyTokens.length][];
        for (int i = 0; i < splitKeyTokens.length; i++) {
            if (numRowKeys == 1 && rowkeyBinary) {
                splitKeys[i] = HBaseBinarySerializerDeserializer.serialize(rowKeyColumn,
                        new TextDatum(splitKeyTokens[i]));
            } else {
                splitKeys[i] = HBaseTextSerializerDeserializer.serialize(rowKeyColumn,
                        new TextDatum(splitKeyTokens[i]));
            }
        }
        return splitKeys;
    }

    if (splitRowKeysFile != null && !splitRowKeysFile.isEmpty()) {
        // If there is many split keys, Tajo allows to define in the file.
        Path path = new Path(splitRowKeysFile);
        FileSystem fs = path.getFileSystem(conf);
        if (!fs.exists(path)) {
            throw new IOException("hbase.split.rowkeys.file=" + path.toString() + " not exists.");
        }

        SortedSet<String> splitKeySet = new TreeSet<String>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(fs.open(path)));
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (line.isEmpty()) {
                    continue;
                }
                splitKeySet.add(line);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        if (splitKeySet.isEmpty()) {
            return null;
        }

        byte[][] splitKeys = new byte[splitKeySet.size()][];
        int index = 0;
        for (String eachKey : splitKeySet) {
            if (numRowKeys == 1 && rowkeyBinary) {
                splitKeys[index++] = HBaseBinarySerializerDeserializer.serialize(rowKeyColumn,
                        new TextDatum(eachKey));
            } else {
                splitKeys[index++] = HBaseTextSerializerDeserializer.serialize(rowKeyColumn,
                        new TextDatum(eachKey));
            }
        }

        return splitKeys;
    }

    return null;
}

From source file:org.ednovo.gooru.domain.service.revision_history.CollectionRevisionHistoryRollBack.java

private void mergeCollectionItem(Set<CollectionItem> existingCollectionItems,
        Set<CollectionItem> revisionCollectionItems) {
    SortedSet<CollectionItem> removeExistsCollectionItems = new TreeSet<CollectionItem>();

    for (CollectionItem existCollectionItem : existingCollectionItems) {
        boolean CollectionItemExists = false;
        for (CollectionItem revisionCollectionItem : revisionCollectionItems) {
            if (revisionCollectionItem.getCollectionItemId()
                    .equalsIgnoreCase(existCollectionItem.getCollectionItemId())) {
                //update exists 
                existCollectionItem.setResource(revisionCollectionItem.getResource());
                existCollectionItem.setCollection(revisionCollectionItem.getCollection());
                existCollectionItem.setItemType(revisionCollectionItem.getItemType());
                existCollectionItem.setNarration(revisionCollectionItem.getNarration());
                existCollectionItem.setNarrationType(revisionCollectionItem.getNarrationType());
                existCollectionItem.setItemSequence(revisionCollectionItem.getItemSequence());
                existCollectionItem.setStart(revisionCollectionItem.getStart());
                existCollectionItem.setStop(revisionCollectionItem.getStop());
                existCollectionItem.setDocumentid(revisionCollectionItem.getDocumentid());

                existCollectionItem.setDocumentkey(revisionCollectionItem.getDocumentkey());
                CollectionItemExists = true;
                revisionCollectionItems.remove(revisionCollectionItem);
                break;
            }//from w w  w  .j  a v  a  2 s  .  c om
        }
        if (!CollectionItemExists) {
            removeExistsCollectionItems.add(existCollectionItem);
        }
    }
    if (removeExistsCollectionItems.size() > 0) {
        existingCollectionItems.removeAll(removeExistsCollectionItems);
        collectionRepository.removeAll(removeExistsCollectionItems);
    }
    if (revisionCollectionItems != null && revisionCollectionItems.size() > 0) {
        existingCollectionItems.addAll(revisionCollectionItems);
    }

}

From source file:com.palantir.atlasdb.keyvalue.rdbms.PostgresKeyValueService.java

private Map<Cell, Value> getRowsInternal(final String tableName, final Collection<byte[]> rows,
        final ColumnSelection columnSelection, final long timestamp) {
    if (rows.isEmpty()) {
        return Maps.newHashMap();
    }/*from   ww w . ja va2 s.c o m*/

    return getDbi().inTransaction(new TransactionCallback<Map<Cell, Value>>() {
        @Override
        public Map<Cell, Value> inTransaction(Handle handle, TransactionStatus status) {

            final List<Pair<Cell, Value>> list;

            if (columnSelection.allColumnsSelected()) {
                final Query<Pair<Cell, Value>> query = handle.createQuery("SELECT "
                        + Columns.ROW_COLUMN_TIMESTAMP_CONTENT_AS("t") + " " + "FROM "
                        + USR_TABLE(tableName, "t") + " " + "LEFT JOIN " + USR_TABLE(tableName, "t2") + " "
                        + "ON "
                        + Columns.ROW("t").eq(Columns.ROW("t2")).and(Columns.COLUMN("t"))
                                .eq(Columns.COLUMN("t2")).and(Columns.TIMESTAMP("t"))
                                .lt(Columns.TIMESTAMP("t2")).and(Columns.TIMESTAMP("t2"))
                        + "<" + timestamp + " " + "WHERE " + Columns.ROW("t") + " IN ("
                        + makeSlots("row", rows.size()) + ") " + "    AND " + Columns.TIMESTAMP("t2")
                        + " IS NULL" +
                // This is a LEFT JOIN -> the below condition cannot be in ON clause
                "    AND " + Columns.TIMESTAMP("t") + " < " + timestamp).map(CellValueMapper.instance());
                AtlasSqlUtils.bindAll(query, rows);
                list = query.list();
            } else {
                SortedSet<byte[]> columns = Sets.newTreeSet(UnsignedBytes.lexicographicalComparator());
                Iterables.addAll(columns, columnSelection.getSelectedColumns());

                final Query<Pair<Cell, Value>> query = handle.createQuery("SELECT "
                        + Columns.ROW_COLUMN_TIMESTAMP_CONTENT_AS("t") + " " + "FROM "
                        + USR_TABLE(tableName, "t") + " " + "LEFT JOIN " + USR_TABLE(tableName, "t2") + " "
                        + "ON "
                        + Columns.ROW("t").eq(Columns.ROW("t2"))
                                .and(Columns.COLUMN("t").eq(Columns.COLUMN("t2"))).and(Columns.TIMESTAMP("t"))
                                .lt(Columns.TIMESTAMP("t2")).and(Columns.TIMESTAMP("t2"))
                        + "<" + timestamp + " " + "WHERE " + Columns.ROW("t") + " IN ("
                        + makeSlots("row", rows.size()) + ") " + "    AND " + Columns.COLUMN("t") + " IN ("
                        + makeSlots("column", columns.size()) + ") " + "    AND " + Columns.TIMESTAMP("t2")
                        + " IS NULL " +
                // This is a LEFT JOIN -> the below condition cannot be in ON clause
                "    AND " + Columns.TIMESTAMP("t") + " < " + timestamp).map(CellValueMapper.instance());

                AtlasSqlUtils.bindAll(query, rows);
                AtlasSqlUtils.bindAll(query, columns, rows.size());
                list = query.list();
            }
            return AtlasSqlUtils.listToMap(list);
        }
    });
}

From source file:org.logstash.dependencies.ReportGenerator.java

public boolean generateReport(InputStream licenseMappingStream, InputStream acceptableLicensesStream,
        InputStream rubyDependenciesStream, InputStream[] javaDependenciesStreams, Writer output)
        throws IOException {

    SortedSet<Dependency> dependencies = new TreeSet<>();
    Dependency.addDependenciesFromRubyReport(rubyDependenciesStream, dependencies);

    for (InputStream stream : javaDependenciesStreams) {
        Dependency.addDependenciesFromJavaReport(stream, dependencies);
    }//ww w. j a  va 2s .  c o m

    Map<String, LicenseUrlPair> licenseMapping = new HashMap<>();
    readLicenseMapping(licenseMappingStream, licenseMapping);
    List<String> acceptableLicenses = new ArrayList<>();
    readAcceptableLicenses(acceptableLicensesStream, acceptableLicenses);
    for (Dependency dependency : dependencies) {
        String nameAndVersion = dependency.name + ":" + dependency.version;
        if (licenseMapping.containsKey(nameAndVersion)) {
            LicenseUrlPair pair = licenseMapping.get(nameAndVersion);

            if (pair.url != null && !pair.url.equals("")
                    && (acceptableLicenses.stream().anyMatch(pair.license::equalsIgnoreCase))) {
                dependency.spdxLicense = pair.license;
                dependency.url = pair.url;
            } else {
                // unacceptable license or missing URL
                UNKNOWN_LICENSES.add(dependency);
            }
        } else {
            dependency.spdxLicense = UNKNOWN_LICENSE;
            UNKNOWN_LICENSES.add(dependency);
        }
    }

    try (CSVPrinter csvPrinter = new CSVPrinter(output, CSVFormat.DEFAULT.withHeader(CSV_HEADERS))) {
        for (Dependency dependency : dependencies) {
            csvPrinter.printRecord(dependency.toCsvReportRecord());
        }
        csvPrinter.flush();
    }

    String msg = "Generated report with %d dependencies (%d unknown or unacceptable licenses).";
    System.out.println(String.format(msg + "\n", dependencies.size(), UNKNOWN_LICENSES.size()));

    if (UNKNOWN_LICENSES.size() > 0) {
        String errMsg = "Add complying licenses (using the SPDX license ID from https://spdx.org/licenses) "
                + "with URLs for the libraries listed below to tools/dependencies-report/src/main/resources/"
                + "licenseMapping.csv:";
        System.out.println(errMsg);
        for (Dependency dependency : UNKNOWN_LICENSES) {
            System.out.println(String.format("\"%s:%s\"", dependency.name, dependency.version));
        }
    }

    return UNKNOWN_LICENSES.size() == 0;
}

From source file:org.apache.accumulo.shell.commands.CreateTableCommand.java

@Override
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState)
        throws AccumuloException, AccumuloSecurityException, TableExistsException, TableNotFoundException,
        IOException, ClassNotFoundException {

    final String testTableName = cl.getArgs()[0];
    final HashMap<String, String> props = new HashMap<String, String>();

    if (!testTableName.matches(Tables.VALID_NAME_REGEX)) {
        shellState.getReader()/*from  ww  w  . jav  a 2  s  .  c  om*/
                .println("Only letters, numbers and underscores are allowed for use in table names.");
        throw new IllegalArgumentException();
    }

    final String tableName = cl.getArgs()[0];
    if (shellState.getConnector().tableOperations().exists(tableName)) {
        throw new TableExistsException(null, tableName, null);
    }
    final SortedSet<Text> partitions = new TreeSet<Text>();
    final boolean decode = cl.hasOption(base64Opt.getOpt());

    if (cl.hasOption(createTableOptSplit.getOpt())) {
        partitions.addAll(ShellUtil.scanFile(cl.getOptionValue(createTableOptSplit.getOpt()), decode));
    } else if (cl.hasOption(createTableOptCopySplits.getOpt())) {
        final String oldTable = cl.getOptionValue(createTableOptCopySplits.getOpt());
        if (!shellState.getConnector().tableOperations().exists(oldTable)) {
            throw new TableNotFoundException(null, oldTable, null);
        }
        partitions.addAll(shellState.getConnector().tableOperations().listSplits(oldTable));
    }

    if (cl.hasOption(createTableOptCopyConfig.getOpt())) {
        final String oldTable = cl.getOptionValue(createTableOptCopyConfig.getOpt());
        if (!shellState.getConnector().tableOperations().exists(oldTable)) {
            throw new TableNotFoundException(null, oldTable, null);
        }
    }

    TimeType timeType = TimeType.MILLIS;
    if (cl.hasOption(createTableOptTimeLogical.getOpt())) {
        timeType = TimeType.LOGICAL;
    }

    if (cl.hasOption(createTableOptInitProp.getOpt())) {
        String[] keyVals = StringUtils.split(cl.getOptionValue(createTableOptInitProp.getOpt()), ',');
        for (String keyVal : keyVals) {
            String[] sa = StringUtils.split(keyVal, '=');
            props.put(sa[0], sa[1]);
        }
    }

    // create table
    shellState.getConnector().tableOperations().create(tableName,
            new NewTableConfiguration().setTimeType(timeType).setProperties(props));
    if (partitions.size() > 0) {
        shellState.getConnector().tableOperations().addSplits(tableName, partitions);
    }

    shellState.setTableName(tableName); // switch shell to new table context

    if (cl.hasOption(createTableNoDefaultIters.getOpt())) {
        for (String key : IteratorUtil.generateInitialTableProperties(true).keySet()) {
            shellState.getConnector().tableOperations().removeProperty(tableName, key);
        }
    }

    // Copy options if flag was set
    if (cl.hasOption(createTableOptCopyConfig.getOpt())) {
        if (shellState.getConnector().tableOperations().exists(tableName)) {
            final Iterable<Entry<String, String>> configuration = shellState.getConnector().tableOperations()
                    .getProperties(cl.getOptionValue(createTableOptCopyConfig.getOpt()));
            for (Entry<String, String> entry : configuration) {
                if (Property.isValidTablePropertyKey(entry.getKey())) {
                    shellState.getConnector().tableOperations().setProperty(tableName, entry.getKey(),
                            entry.getValue());
                }
            }
        }
    }

    if (cl.hasOption(createTableOptEVC.getOpt())) {
        try {
            shellState.getConnector().tableOperations().addConstraint(tableName,
                    VisibilityConstraint.class.getName());
        } catch (AccumuloException e) {
            Shell.log.warn(e.getMessage() + " while setting visibility constraint, but table was created");
        }
    }

    // Load custom formatter if set
    if (cl.hasOption(createTableOptFormatter.getOpt())) {
        final String formatterClass = cl.getOptionValue(createTableOptFormatter.getOpt());

        shellState.getConnector().tableOperations().setProperty(tableName,
                Property.TABLE_FORMATTER_CLASS.toString(), formatterClass);
    }
    return 0;
}

From source file:cerrla.LocalCrossEntropyDistribution.java

/**
 * Modifies the policy values before updating (cutting the values down to
 * size)./*ww  w.jav  a  2 s  .  co  m*/
 * 
 * @param elites
 *            The policy values to modify.
 * @param numElite
 *            The minimum number of elite samples.
 * @param staleValue
 *            The number of policies a sample hangs around for.
 * @param minValue
 *            The minimum observed value.
 * @return The policy values that were removed.
 */
private SortedSet<PolicyValue> preUpdateModification(SortedSet<PolicyValue> elites, int numElite,
        int staleValue, double minValue) {
    // Firstly, remove any policy values that have been around for more
    // than N steps

    // Make a backup - just in case the elites are empty afterwards
    SortedSet<PolicyValue> backup = new TreeSet<PolicyValue>(elites);

    // Only remove stuff if the elites are a representative solution
    if (!ProgramArgument.GLOBAL_ELITES.booleanValue()) {
        int iteration = policyGenerator_.getPoliciesEvaluated();
        for (Iterator<PolicyValue> iter = elites.iterator(); iter.hasNext();) {
            PolicyValue pv = iter.next();
            if (iteration - pv.getIteration() >= staleValue) {
                if (ProgramArgument.RETEST_STALE_POLICIES.booleanValue())
                    policyGenerator_.retestPolicy(pv.getPolicy());
                iter.remove();
            }
        }
    }
    if (elites.isEmpty())
        elites.addAll(backup);

    SortedSet<PolicyValue> tailSet = null;
    if (elites.size() > numElite) {
        // Find the N_E value
        Iterator<PolicyValue> pvIter = elites.iterator();
        PolicyValue currentPV = null;
        for (int i = 0; i < numElite; i++)
            currentPV = pvIter.next();

        // Iter at N_E value. Remove any values less than N_E's value
        tailSet = new TreeSet<PolicyValue>(elites.tailSet(new PolicyValue(null, currentPV.getValue(), -1)));
        elites.removeAll(tailSet);
    }

    return tailSet;
}