Example usage for java.util SortedSet first

List of usage examples for java.util SortedSet first

Introduction

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

Prototype

E first();

Source Link

Document

Returns the first (lowest) element currently in this set.

Usage

From source file:com.revetkn.ios.analyzer.ArtworkAnalyzer.java

/** Modifies the passed-in {@code applicationArtwork} instance to include image reference data. */
protected void detectImageReferences(File projectRootDirectory, final ApplicationArtwork applicationArtwork,
        final ArtworkExtractionProgressCallback progressCallback) throws Exception {
    final Map<File, String> contentsOfReferencingFiles = extractContentsOfReferencingFiles(
            projectRootDirectory);//from  ww w  .  j a v  a2s.co  m
    final SortedSet<File> unreferencedImageFiles = synchronizedSortedSet(new TreeSet<File>());
    final SortedSet<File> onlyProjectFileReferencedImageFiles = synchronizedSortedSet(new TreeSet<File>());
    final SortedMap<File, SortedSet<File>> allImageFilesAndReferencingFiles = synchronizedSortedMap(
            new TreeMap<File, SortedSet<File>>());

    final AtomicInteger imageFilesProcessed = new AtomicInteger(0);

    Set<Callable<Object>> imageReferenceProcessingTasks = new HashSet<Callable<Object>>();

    for (final File imageFile : applicationArtwork.getAllImageFiles()) {
        imageReferenceProcessingTasks.add(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                String imageFilename = imageFile.getName();
                SortedSet<File> filesWhereImageIsReferenced = new TreeSet<File>();
                Set<String> imageFilenameVariants = imageFilenameVariants(imageFilename);

                for (Entry<File, String> entry : contentsOfReferencingFiles.entrySet()) {
                    String fileContents = entry.getValue();

                    for (String imageFilenameVariant : imageFilenameVariants) {
                        // Quoted references, e.g. "aboutBackground"
                        if (fileContents.indexOf(format("\"%s\"", imageFilenameVariant)) != -1)
                            filesWhereImageIsReferenced.add(entry.getKey());

                        // Nib files, e.g. <string key="NSResourceName">aboutBackground~ipad.png</string>
                        else if (fileContents.indexOf(format(">%s<", imageFilenameVariant)) != -1)
                            filesWhereImageIsReferenced.add(entry.getKey());
                    }
                }

                if (filesWhereImageIsReferenced.size() == 1 && "project.pbxproj"
                        .equals(filesWhereImageIsReferenced.first().getName().toLowerCase()))
                    onlyProjectFileReferencedImageFiles.add(imageFile);

                if (filesWhereImageIsReferenced.size() == 0) {
                    unreferencedImageFiles.add(imageFile);
                } else {
                    allImageFilesAndReferencingFiles.put(imageFile, filesWhereImageIsReferenced);
                }

                progressCallback.onProcessedImageReferences(imageFile, filesWhereImageIsReferenced,
                        imageFilesProcessed.incrementAndGet(), applicationArtwork.getAllImageFiles().size());

                return null;
            }
        });
    }

    for (Future<Object> future : getExecutorService().invokeAll(imageReferenceProcessingTasks))
        future.get();

    applicationArtwork.setAllImageFilesAndReferencingFiles(allImageFilesAndReferencingFiles);
    applicationArtwork.setUnreferencedImageFiles(unreferencedImageFiles);
    applicationArtwork.setOnlyProjectFileReferencedImageFiles(onlyProjectFileReferencedImageFiles);
}

From source file:io.fabric8.maven.plugin.HelmIndexMojo.java

protected void generateHTML(File outputHtmlFile, Map<String, ChartInfo> charts) throws MojoExecutionException {
    Map<String, SortedSet<ChartInfo>> chartMap = new TreeMap<>();
    for (ChartInfo chartInfo : charts.values()) {
        String key = chartInfo.getName();
        SortedSet<ChartInfo> set = chartMap.get(key);
        if (set == null) {
            set = new TreeSet(createChartComparator());
            chartMap.put(key, set);//from w w  w . jav a  2s.c om
        }
        set.add(chartInfo);
    }
    try (PrintWriter writer = new PrintWriter(new FileWriter(outputHtmlFile))) {
        writer.println("<html>");
        writer.println("<head>");
        writer.println(getHtmlFileContentOrDefault(headHtmlFile, "<link href='style.css' rel=stylesheet>\n"
                + "<link href='custom.css' rel=stylesheet>\n" + "<title>" + helmTitle + "</title>\n"));
        writer.println("</head>");
        writer.println("<body>");

        writer.println(getHtmlFileContentOrDefault(introductionHtmlFile, "<h1>" + helmTitle + "</h1>"));

        writer.println("<table class='table table-striped table-hover'>");
        writer.println("  <hhead>");
        writer.println("    <tr>");
        writer.println("      <th>Chart</th>");
        writer.println("      <th>Versions</th>");
        writer.println("    </tr>");
        writer.println("  </hhead>");
        writer.println("  <tbody>");
        for (Map.Entry<String, SortedSet<ChartInfo>> entry : chartMap.entrySet()) {
            String key = entry.getKey();
            SortedSet<ChartInfo> set = entry.getValue();
            if (!set.isEmpty()) {
                ChartInfo first = set.first();
                HelmMojo.Chart firstChartfile = first.getChartfile();
                if (firstChartfile == null) {
                    continue;
                }
                String chartDescription = getDescription(firstChartfile);
                writer.println("    <tr>");
                writer.println("      <td title='" + chartDescription + "'>");
                String iconHtml = "";
                String iconUrl = findIconURL(first, set);
                if (Strings.isNotBlank(iconUrl)) {
                    iconHtml = "<img class='logo' src='" + iconUrl + "'>";
                }
                writer.println("        " + iconHtml + "<span class='chart-name'>" + key + "</span>");
                writer.println("      </td>");
                writer.println("      <td class='versions'>");
                for (ChartInfo chartInfo : set) {
                    HelmMojo.Chart chartfile = chartInfo.getChartfile();
                    if (chartfile == null) {
                        continue;
                    }
                    String description = getDescription(chartfile);
                    String version = chartfile.getVersion();
                    String href = chartInfo.getUrl();
                    writer.println(
                            "        <a href='" + href + "' title='" + description + "'>" + version + "</a>");
                }
                writer.println("      </td>");
                writer.println("    </tr>");
            }
        }
        writer.println("  </tbody>");
        writer.println("  </table>");
        writer.println(getHtmlFileContentOrDefault(footerHtmlFile, ""));
        writer.println("</body>");
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to write to " + outputHtmlFile + ". " + e, e);
    }
}

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  .ja  va  2s  .  co  m*/
 * @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:io.fabric8.maven.plugin.mojo.internal.HelmIndexMojo.java

protected void generateHTML(File outputHtmlFile, Map<String, ChartInfo> charts) throws MojoExecutionException {
    Map<String, SortedSet<ChartInfo>> chartMap = new TreeMap<>();
    for (ChartInfo chartInfo : charts.values()) {
        String key = chartInfo.getName();
        SortedSet<ChartInfo> set = chartMap.get(key);
        if (set == null) {
            set = new TreeSet<>(createChartComparator());
            chartMap.put(key, set);/*from   w ww .ja  va 2 s  . c o  m*/
        }
        set.add(chartInfo);
    }
    try (PrintWriter writer = new PrintWriter(new FileWriter(outputHtmlFile))) {
        writer.println("<html>");
        writer.println("<head>");
        writer.println(getHtmlFileContentOrDefault(headHtmlFile, "<link href='style.css' rel=stylesheet>\n"
                + "<link href='custom.css' rel=stylesheet>\n" + "<title>" + helmTitle + "</title>\n"));
        writer.println("</head>");
        writer.println("<body>");

        writer.println(getHtmlFileContentOrDefault(introductionHtmlFile, "<h1>" + helmTitle + "</h1>"));

        writer.println("<table class='table table-striped table-hover'>");
        writer.println("  <hhead>");
        writer.println("    <tr>");
        writer.println("      <th>Chart</th>");
        writer.println("      <th>Versions</th>");
        writer.println("    </tr>");
        writer.println("  </hhead>");
        writer.println("  <tbody>");
        for (Map.Entry<String, SortedSet<ChartInfo>> entry : chartMap.entrySet()) {
            String key = entry.getKey();
            SortedSet<ChartInfo> set = entry.getValue();
            if (!set.isEmpty()) {
                ChartInfo first = set.first();
                HelmMojo.Chart firstChartfile = first.getChartfile();
                if (firstChartfile == null) {
                    continue;
                }
                String chartDescription = getDescription(firstChartfile);
                writer.println("    <tr>");
                writer.println("      <td title='" + chartDescription + "'>");
                String iconHtml = "";
                String iconUrl = findIconURL(first, set);
                if (Strings.isNotBlank(iconUrl)) {
                    iconHtml = "<img class='logo' src='" + iconUrl + "'>";
                }
                writer.println("        " + iconHtml + "<span class='chart-name'>" + key + "</span>");
                writer.println("      </td>");
                writer.println("      <td class='versions'>");
                for (ChartInfo chartInfo : set) {
                    HelmMojo.Chart chartfile = chartInfo.getChartfile();
                    if (chartfile == null) {
                        continue;
                    }
                    String description = getDescription(chartfile);
                    String version = chartfile.getVersion();
                    String href = chartInfo.firstUrl();
                    writer.println(
                            "        <a href='" + href + "' title='" + description + "'>" + version + "</a>");
                }
                writer.println("      </td>");
                writer.println("    </tr>");
            }
        }
        writer.println("  </tbody>");
        writer.println("  </table>");
        writer.println(getHtmlFileContentOrDefault(footerHtmlFile, ""));
        writer.println("</body>");
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to write to " + outputHtmlFile + ". " + e, e);
    }
}

From source file:org.hyperic.hq.measurement.server.session.AvailabilityManagerImpl.java

private AvailabilityDataRLE findAvailAfter(DataPoint state,
        Map<Integer, TreeSet<AvailabilityDataRLE>> currAvails) {
    final Integer mId = state.getMeasurementId();
    final TreeSet<AvailabilityDataRLE> rles = currAvails.get(mId);
    final long start = state.getTimestamp();
    final AvailabilityDataRLE tmp = new AvailabilityDataRLE();
    // tailSet is inclusive so we need to add 1 to start
    tmp.setStartime(start + 1);//from ww w.ja  v  a 2s. co  m
    final SortedSet<AvailabilityDataRLE> set = rles.tailSet(tmp);
    if (set.size() == 0) {
        return null;
    }
    return (AvailabilityDataRLE) set.first();
}

From source file:io.fabric8.maven.plugin.ManifestIndexMojo.java

protected void generateHTML(File outputHtmlFile, Map<String, ManifestInfo> manifests, boolean kubernetes,
        File introductionHtmlFile, File headHtmlFile, File footerHtmlFile) throws MojoExecutionException {
    Map<String, SortedSet<ManifestInfo>> manifestMap = new TreeMap<>();
    for (ManifestInfo manifestInfo : manifests.values()) {
        String key = manifestInfo.getName();
        SortedSet<ManifestInfo> set = manifestMap.get(key);
        if (set == null) {
            set = new TreeSet(createManifestComparator());
            manifestMap.put(key, set);//w ww  .j  a v a  2  s . c  o m
        }
        set.add(manifestInfo);
    }
    try (PrintWriter writer = new PrintWriter(new FileWriter(outputHtmlFile))) {
        writer.println("<html>");
        writer.println("<head>");
        writer.println(getHtmlFileContentOrDefault(headHtmlFile, "<link href='style.css' rel=stylesheet>\n"
                + "<link href='custom.css' rel=stylesheet>\n" + "<title>" + manifestTitle + "</title>\n"));
        writer.println("</head>");
        writer.println("<body>");

        writer.println(getHtmlFileContentOrDefault(introductionHtmlFile, "<h1>" + manifestTitle + "</h1>"));

        writer.println("<table class='table table-striped table-hover'>");
        writer.println("  <hhead>");
        writer.println("    <tr>");
        writer.println("      <th>Manifest</th>");
        writer.println("      <th>Versions</th>");
        writer.println("    </tr>");
        writer.println("  </hhead>");
        writer.println("  <tbody>");
        for (Map.Entry<String, SortedSet<ManifestInfo>> entry : manifestMap.entrySet()) {
            String key = entry.getKey();
            SortedSet<ManifestInfo> set = entry.getValue();
            if (!set.isEmpty()) {
                ManifestInfo first = set.first();
                first.configure(this);
                if (!first.isValid()) {
                    continue;
                }

                String manifestDescription = getDescription(first);
                writer.println("    <tr>");
                writer.println("      <td title='" + manifestDescription + "'>");
                String iconHtml = "";
                String iconUrl = findIconURL(set);
                if (Strings.isNotBlank(iconUrl)) {
                    iconHtml = "<img class='logo' src='" + iconUrl + "'>";
                }
                writer.println("        " + iconHtml + "<span class='manifest-name'>" + key + "</span>");
                writer.println("      </td>");
                writer.println("      <td class='versions'>");
                int count = 0;
                for (ManifestInfo manifestInfo : set) {
                    if (maxVersionsPerApp > 0 && ++count > maxVersionsPerApp) {
                        break;
                    }
                    String description = getDescription(manifestInfo);
                    String version = manifestInfo.getVersion();
                    String href = kubernetes ? manifestInfo.getKubernetesUrl() : manifestInfo.getOpenShiftUrl();
                    String versionId = manifestInfo.getId();
                    String command = kubernetes ? "kubectl" : "oc";
                    writer.println(
                            "        <a class='btn btn-default' role='button' data-toggle='collapse' href='#"
                                    + versionId + "' aria-expanded='false' aria-controls='" + versionId
                                    + "' title='" + description + "'>\n" + version + "\n" + "</a>\n"
                                    + "<div class='collapse' id='" + versionId + "'>\n"
                                    + "  <div class='well'>\n" + "    <p>To install version <b>" + version
                                    + "</b> of <b>" + key + "</b> type the following command:</p>\n"
                                    + "    <code>" + command + " apply -f " + href + "</code>\n"
                                    + "    <div class='version-buttons'><a class='btn btn-primary' title='Download the YAML manifest for "
                                    + key + " version " + version + "' href='" + href
                                    + "'><i class='fa fa-download' aria-hidden='true'></i> Download Manifest</a> "
                                    + "<a class='btn btn-primary' target='gofabric8' title='Run this application via the go.fabric8.io website' href='https://go.fabric8.io/?manifest="
                                    + href
                                    + "'><i class='fa fa-external-link' aria-hidden='true'></i> Run via browser</a></div>\n"
                                    + "  </div>\n" + "</div>");
                }
                writer.println("      </td>");
                writer.println("    </tr>");
            }
        }
        writer.println("  </tbody>");
        writer.println("  </table>");
        writer.println(getHtmlFileContentOrDefault(footerHtmlFile, ""));
        writer.println("</body>");
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to write to " + outputHtmlFile + ". " + e, e);
    }
}

From source file:io.fabric8.maven.plugin.mojo.internal.ManifestIndexMojo.java

protected void generateHTML(File outputHtmlFile, Map<String, ManifestInfo> manifests, boolean kubernetes,
        File introductionHtmlFile, File headHtmlFile, File footerHtmlFile) throws MojoExecutionException {
    Map<String, SortedSet<ManifestInfo>> manifestMap = new TreeMap<>();
    for (ManifestInfo manifestInfo : manifests.values()) {
        String key = manifestInfo.getName();
        SortedSet<ManifestInfo> set = manifestMap.get(key);
        if (set == null) {
            set = new TreeSet<>(createManifestComparator());
            manifestMap.put(key, set);//from   ww w.j  a  v a 2 s . c  o m
        }
        set.add(manifestInfo);
    }
    try (PrintWriter writer = new PrintWriter(new FileWriter(outputHtmlFile))) {
        writer.println("<html>");
        writer.println("<head>");
        writer.println(getHtmlFileContentOrDefault(headHtmlFile, "<link href='style.css' rel=stylesheet>\n"
                + "<link href='custom.css' rel=stylesheet>\n" + "<title>" + manifestTitle + "</title>\n"));
        writer.println("</head>");
        writer.println("<body>");

        writer.println(getHtmlFileContentOrDefault(introductionHtmlFile, "<h1>" + manifestTitle + "</h1>"));

        writer.println("<table class='table table-striped table-hover'>");
        writer.println("  <hhead>");
        writer.println("    <tr>");
        writer.println("      <th>Manifest</th>");
        writer.println("      <th>Versions</th>");
        writer.println("    </tr>");
        writer.println("  </hhead>");
        writer.println("  <tbody>");
        for (Map.Entry<String, SortedSet<ManifestInfo>> entry : manifestMap.entrySet()) {
            String key = entry.getKey();
            SortedSet<ManifestInfo> set = entry.getValue();
            if (!set.isEmpty()) {
                ManifestInfo first = set.first();
                first.configure(this);
                if (!first.isValid()) {
                    continue;
                }

                String manifestDescription = getDescription(first);
                writer.println("    <tr>");
                writer.println("      <td title='" + manifestDescription + "'>");
                String iconHtml = "";
                String iconUrl = findIconURL(set);
                if (Strings.isNotBlank(iconUrl)) {
                    iconHtml = "<img class='logo' src='" + iconUrl + "'>";
                }
                writer.println("        " + iconHtml + "<span class='manifest-name'>" + key + "</span>");
                writer.println("      </td>");
                writer.println("      <td class='versions'>");
                int count = 0;
                for (ManifestInfo manifestInfo : set) {
                    if (maxVersionsPerApp > 0 && ++count > maxVersionsPerApp) {
                        break;
                    }
                    String description = getDescription(manifestInfo);
                    String version = manifestInfo.getVersion();
                    String href = kubernetes ? manifestInfo.getKubernetesUrl() : manifestInfo.getOpenShiftUrl();
                    String versionId = manifestInfo.getId();
                    String command = kubernetes ? "kubectl" : "oc";
                    writer.println(
                            "        <a class='btn btn-default' role='button' data-toggle='collapse' href='#"
                                    + versionId + "' aria-expanded='false' aria-controls='" + versionId
                                    + "' title='" + description + "'>\n" + version + "\n" + "</a>\n"
                                    + "<div class='collapse' id='" + versionId + "'>\n"
                                    + "  <div class='well'>\n" + "    <p>To install version <b>" + version
                                    + "</b> of <b>" + key + "</b> type the following command:</p>\n"
                                    + "    <code>" + command + " apply -f " + href + "</code>\n"
                                    + "    <div class='version-buttons'><a class='btn btn-primary' title='Download the YAML manifest for "
                                    + key + " version " + version + "' href='" + href
                                    + "'><i class='fa fa-download' aria-hidden='true'></i> Download Manifest</a> "
                                    + "<a class='btn btn-primary' target='gofabric8' title='Run this application via the go.fabric8.io website' href='https://go.fabric8.io/?manifest="
                                    + href
                                    + "'><i class='fa fa-external-link' aria-hidden='true'></i> Run via browser</a></div>\n"
                                    + "  </div>\n" + "</div>");
                }
                writer.println("      </td>");
                writer.println("    </tr>");
            }
        }
        writer.println("  </tbody>");
        writer.println("  </table>");
        writer.println(getHtmlFileContentOrDefault(footerHtmlFile, ""));
        writer.println("</body>");
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to write to " + outputHtmlFile + ". " + e, e);
    }
}

From source file:org.apache.flume.channel.file.Log.java

private void removeOldLogs(SortedSet<Integer> fileIDs) {
    Preconditions.checkState(open, "Log is closed");
    // To maintain a single code path for deletes, if backup of checkpoint is
    // enabled or not, we will track the files which can be deleted after the
    // current checkpoint (since the one which just got backed up still needs
    // these files) and delete them only after the next (since the current
    // checkpoint will become the backup at that time,
    // and thus these files are no longer needed).
    for (File fileToDelete : pendingDeletes) {
        LOGGER.info("Removing old file: " + fileToDelete);
        FileUtils.deleteQuietly(fileToDelete);
    }/*w  w w.j  a v  a2  s . c o  m*/
    pendingDeletes.clear();
    // we will find the smallest fileID currently in use and
    // won't delete any files with an id larger than the min
    int minFileID = fileIDs.first();
    LOGGER.debug("Files currently in use: " + fileIDs);
    for (File logDir : logDirs) {
        List<File> logs = LogUtils.getLogs(logDir);
        // sort oldset to newest
        LogUtils.sort(logs);
        // ensure we always keep two logs per dir
        int size = logs.size() - MIN_NUM_LOGS;
        for (int index = 0; index < size; index++) {
            File logFile = logs.get(index);
            int logFileID = LogUtils.getIDForFile(logFile);
            if (logFileID < minFileID) {
                LogFile.RandomReader reader = idLogFileMap.remove(logFileID);
                if (reader != null) {
                    reader.close();
                }
                File metaDataFile = Serialization.getMetaDataFile(logFile);
                pendingDeletes.add(logFile);
                pendingDeletes.add(metaDataFile);
            }
        }
    }
}

From source file:uk.ac.rdg.evoportal.pages.ScaleTestDetail.java

public ScaleTestDetail(PageParameters params) {
    String idStr = params.getString("id");
    final long testID = Long.parseLong(idStr);
    ScaleTest scaleTest = ScaleTestsDataProvider.get(testID);
    int percentageDone = scaleTest.getPercentageDone();
    String testName = scaleTest.getLabel();
    int iterations = scaleTest.getIterations();
    add(new Label("id", idStr));
    add(new Label("name", testName));
    add(new Label("its", Integer.toString(iterations)));
    add(new Label("pcDone", percentageDone + "%"));
    add(new TextArea("controlBlock", new Model<String>(scaleTest.getBPBlock())));
    SortedSet<Integer> nodesSet = new TreeSet<Integer>();
    List<ScaleTestComputeJob> results = scaleTest.getScaleTestComputeJobs();
    double[][] runSeries = new double[2][results.size()];
    int j = 0;/*from   w ww . j a  va  2 s  .  c o m*/
    double testSize = (double) iterations;
    for (Iterator<ScaleTestComputeJob> i = results.iterator(); i.hasNext();) {
        ScaleTestComputeJob result = i.next();
        int nodes = result.getNodes();
        int duration = result.getDuration();
        runSeries[0][j] = (double) nodes;
        runSeries[1][j] = (double) duration; // in seconds
        nodesSet.add(result.getNodes());
        double m = ((double) duration / testSize);
        calc.putMultipler(nodes, m);
        j++;
    }
    List<Integer> iterationsChoices = Arrays.asList(
            new Integer[] { 100000, 200000, 300000, 400000, 500000, 1000000, 1200000, 1300000, 1400000, 1500000,
                    2000000, 3000000, 4000000, 5000000, 6000000, 7000000, 8000000, 9000000, 10000000 });
    Form calcForm = new Form("calcForm", new CompoundPropertyModel(calc));
    calcForm.setVisible(false);
    // only render image if test is completed with all jobs stopped
    boolean isResultsReady = percentageDone == 100;
    if (isResultsReady) {
        DefaultXYDataset xyData = new DefaultXYDataset();
        xyData.addSeries(testName, runSeries);
        JFreeChart scaleChart = ChartFactory.createScatterPlot("Scale test results for " + testName,
                "Number of nodes", "Time to run in seconds", xyData, PlotOrientation.VERTICAL, true, true,
                true);
        add(new ScaleTestResultsChart("chart", scaleChart, 600, 300));
        calc.setIterations(iterationsChoices.get(0));
        calc.setNodes(nodesSet.first());
        calcForm.setVisible(true);
    } else {
        add(new Image("chart"));
    }

    final Label durationText = new Label("durationString");
    durationText.setOutputMarkupId(true);
    DropDownChoice iterationsDropDown = new DropDownChoice("iterations", iterationsChoices);
    iterationsDropDown.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            target.addComponent(durationText);
        }
    });
    DropDownChoice nodesDropDown = new DropDownChoice("nodes", Arrays.asList(nodesSet.toArray()));
    nodesDropDown.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            target.addComponent(durationText);
        }
    });
    calcForm.add(iterationsDropDown);
    calcForm.add(nodesDropDown);
    calcForm.add(durationText);
    add(calcForm);
    ScaleTestComputeJobsDataProvider scaleTestComputeJobsDataProvider = new ScaleTestComputeJobsDataProvider(
            testID);
    add(new ScaleTestComputeJobsDataView("jobDetails", scaleTestComputeJobsDataProvider, testID));
    if (!isResultsReady) {
        AjaxSelfUpdatingTimerBehavior timer = new AjaxSelfUpdatingTimerBehavior(Duration.seconds(15)) {
            @Override
            protected void onPostProcessTarget(AjaxRequestTarget target) {
                ScaleTest refreshedScaleTest = ScaleTestsDataProvider.get(testID);
                int pcDone = refreshedScaleTest.getPercentageDone();
                get("pcDone").replaceWith(new Label("pcDone", pcDone + "%"));
                if (pcDone == 100) {
                    setResponsePage(ScaleTestDetail.class, new PageParameters("id=" + testID));
                }
            }
        };
        add(timer);
    }
}

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;
        }/*www .j ava2  s  .  c o m*/

        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();
}