Example usage for java.text MessageFormat format

List of usage examples for java.text MessageFormat format

Introduction

In this page you can find the example usage for java.text MessageFormat format.

Prototype

public final String format(Object obj) 

Source Link

Document

Formats an object to produce a string.

Usage

From source file:it.cnr.icar.eric.client.ui.swing.RegistryBrowser.java

/**
 * Utility method that checks if obj is an instance of targetType.
 * //from w w w.java 2 s  . co  m
 * @param obj
 *            Object to check
 * @param targetType
 *            Class type for which to check
 * 
 * @return true if obj is an instance of targetType
 * 
 * @throws InvalidRequestException
 *             if obj is not an instance of targetType.
 */
@SuppressWarnings("rawtypes")
public static boolean isInstanceOf(Object obj, Class targetType) throws InvalidRequestException {
    if (targetType.isInstance(obj)) {
        return true;
    } else {
        Object[] notInstanceOfArgs = { targetType.getName(), obj.getClass().getName() };
        MessageFormat form = new MessageFormat(resourceBundle.getString("error.notInstanceOf"));
        throw new InvalidRequestException(form.format(notInstanceOfArgs));
    }
}

From source file:org.eclipse.swt.examples.accessibility.BarChart.java

void addListeners() {
    addPaintListener(e -> {/*ww w  .  ja v a  2s  . c o m*/
        GC gc = e.gc;
        Rectangle rect = getClientArea();
        Display display = getDisplay();
        int count = data.size();
        Point valueSize = gc.stringExtent(Integer.valueOf(valueMax).toString());
        int leftX = rect.x + 2 * GAP + valueSize.x;
        int bottomY = rect.y + rect.height - 2 * GAP - valueSize.y;
        int unitWidth = (rect.width - 4 * GAP - valueSize.x - AXIS_WIDTH) / count - GAP;
        int unitHeight = (rect.height - 3 * GAP - AXIS_WIDTH - 2 * valueSize.y)
                / ((valueMax - valueMin) / valueIncrement);
        // draw the title
        int titleWidth = gc.stringExtent(title).x;
        int center = (Math.max(titleWidth, count * (unitWidth + GAP) + GAP) - titleWidth) / 2;
        gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK));
        gc.drawString(title, leftX + AXIS_WIDTH + center, rect.y + GAP);
        // draw the y axis and value labels
        gc.setLineWidth(AXIS_WIDTH);
        gc.drawLine(leftX, rect.y + GAP + valueSize.y, leftX, bottomY);
        for (int i1 = valueMin; i1 <= valueMax; i1 += valueIncrement) {
            int y = bottomY - i1 * unitHeight;
            gc.drawLine(leftX, y, leftX - GAP, y);
            gc.drawString(Integer.valueOf(i1).toString(), rect.x + GAP, y - valueSize.y);
        }
        // draw the x axis and item labels
        gc.drawLine(leftX, bottomY, rect.x + rect.width - GAP, bottomY);
        for (int i2 = 0; i2 < count; i2++) {
            Object[] dataItem1 = data.get(i2);
            String itemLabel = (String) dataItem1[0];
            int x1 = leftX + AXIS_WIDTH + GAP + i2 * (unitWidth + GAP);
            gc.drawString(itemLabel, x1, bottomY + GAP);
        }
        // draw the bars
        gc.setBackground(display.getSystemColor(color));
        for (int i3 = 0; i3 < count; i3++) {
            Object[] dataItem2 = data.get(i3);
            int itemValue1 = ((Integer) dataItem2[1]).intValue();
            int x2 = leftX + AXIS_WIDTH + GAP + i3 * (unitWidth + GAP);
            gc.fillRectangle(x2, bottomY - AXIS_WIDTH - itemValue1 * unitHeight, unitWidth,
                    itemValue1 * unitHeight);
        }
        if (isFocusControl()) {
            if (selectedItem == -1) {
                // draw the focus rectangle around the whole bar chart
                gc.drawFocus(rect.x, rect.y, rect.width, rect.height);
            } else {
                // draw the focus rectangle around the selected item
                Object[] dataItem3 = data.get(selectedItem);
                int itemValue2 = ((Integer) dataItem3[1]).intValue();
                int x3 = leftX + AXIS_WIDTH + GAP + selectedItem * (unitWidth + GAP);
                gc.drawFocus(x3, bottomY - itemValue2 * unitHeight - AXIS_WIDTH, unitWidth,
                        itemValue2 * unitHeight + AXIS_WIDTH + GAP + valueSize.y);
            }
        }
    });

    addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            redraw();
        }

        @Override
        public void focusLost(FocusEvent e) {
            redraw();
        }
    });

    addMouseListener(MouseListener.mouseDownAdapter(e -> {
        if (getClientArea().contains(e.x, e.y)) {
            setFocus();
            int item = -1;
            int count = data.size();
            for (int i = 0; i < count; i++) {
                if (itemBounds(i).contains(e.x, e.y)) {
                    item = i;
                    break;
                }
            }
            if (item != selectedItem) {
                selectedItem = item;
                redraw();
                getAccessible().setFocus(item);
                getAccessible().selectionChanged();
            }
        }
    }));

    addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            boolean change = false;
            switch (e.keyCode) {
            case SWT.ARROW_DOWN:
            case SWT.ARROW_RIGHT:
                selectedItem++;
                if (selectedItem >= data.size())
                    selectedItem = 0;
                change = true;
                break;
            case SWT.ARROW_UP:
            case SWT.ARROW_LEFT:
                selectedItem--;
                if (selectedItem <= -1)
                    selectedItem = data.size() - 1;
                change = true;
                break;
            case SWT.HOME:
                selectedItem = 0;
                change = true;
                break;
            case SWT.END:
                selectedItem = data.size() - 1;
                change = true;
                break;
            }
            if (change) {
                redraw();
                getAccessible().setFocus(selectedItem);
                getAccessible().selectionChanged();
            }
        }
    });

    addTraverseListener(e -> {
        switch (e.detail) {
        case SWT.TRAVERSE_TAB_NEXT:
        case SWT.TRAVERSE_TAB_PREVIOUS:
            e.doit = true;
            break;
        }
    });

    getAccessible().addAccessibleListener(new AccessibleAdapter() {
        @Override
        public void getName(AccessibleEvent e) {
            MessageFormat formatter = new MessageFormat(""); //$NON_NLS$
            formatter.applyPattern(bundle.getString("name")); //$NON_NLS$
            int childID = e.childID;
            if (childID == ACC.CHILDID_SELF) {
                e.result = title;
            } else {
                Object[] item = data.get(childID);
                e.result = formatter.format(item);
            }
        }

        @Override
        public void getDescription(AccessibleEvent e) {
            int childID = e.childID;
            if (childID != ACC.CHILDID_SELF) {
                Object[] item = data.get(childID);
                String value = item[1].toString();
                String colorName = bundle.getString("color" + color); //$NON_NLS$
                MessageFormat formatter = new MessageFormat(""); //$NON_NLS$
                formatter.applyPattern(bundle.getString("color_value")); //$NON_NLS$
                e.result = formatter.format(new String[] { colorName, value });
            }
        }
    });

    getAccessible().addAccessibleControlListener(new AccessibleControlAdapter() {
        @Override
        public void getRole(AccessibleControlEvent e) {
            if (e.childID == ACC.CHILDID_SELF) {
                e.detail = ACC.ROLE_LIST;
            } else {
                e.detail = ACC.ROLE_LISTITEM;
            }
        }

        @Override
        public void getChildCount(AccessibleControlEvent e) {
            e.detail = data.size();
        }

        @Override
        public void getChildren(AccessibleControlEvent e) {
            int count = data.size();
            Object[] children = new Object[count];
            for (int i = 0; i < count; i++) {
                children[i] = Integer.valueOf(i);
            }
            e.children = children;
        }

        @Override
        public void getChildAtPoint(AccessibleControlEvent e) {
            Point testPoint = toControl(e.x, e.y);
            int childID = ACC.CHILDID_NONE;
            if (getClientArea().contains(testPoint)) {
                childID = ACC.CHILDID_SELF;
                int count = data.size();
                for (int i = 0; i < count; i++) {
                    if (itemBounds(i).contains(testPoint)) {
                        childID = i;
                        break;
                    }
                }
            }
            e.childID = childID;
        }

        @Override
        public void getLocation(AccessibleControlEvent e) {
            Rectangle location = null;
            Point pt = null;
            int childID = e.childID;
            if (childID == ACC.CHILDID_SELF) {
                location = getClientArea();
                pt = getParent().toDisplay(location.x, location.y);
            } else {
                location = itemBounds(childID);
                pt = toDisplay(location.x, location.y);
            }
            e.x = pt.x;
            e.y = pt.y;
            e.width = location.width;
            e.height = location.height;
        }

        @Override
        public void getFocus(AccessibleControlEvent e) {
            int childID = ACC.CHILDID_NONE;
            if (isFocusControl()) {
                if (selectedItem == -1) {
                    childID = ACC.CHILDID_SELF;
                } else {
                    childID = selectedItem;
                }
            }
            e.childID = childID;

        }

        @Override
        public void getSelection(AccessibleControlEvent e) {
            e.childID = (selectedItem == -1) ? ACC.CHILDID_NONE : selectedItem;
        }

        @Override
        public void getValue(AccessibleControlEvent e) {
            int childID = e.childID;
            if (childID != ACC.CHILDID_SELF) {
                Object[] dataItem = data.get(childID);
                e.result = ((Integer) dataItem[1]).toString();
            }
        }

        @Override
        public void getState(AccessibleControlEvent e) {
            int childID = e.childID;
            e.detail = ACC.STATE_FOCUSABLE;
            if (isFocusControl())
                e.detail |= ACC.STATE_FOCUSED;
            if (childID != ACC.CHILDID_SELF) {
                e.detail |= ACC.STATE_SELECTABLE;
                if (childID == selectedItem)
                    e.detail |= ACC.STATE_SELECTED;
            }
        }
    });
}

From source file:com.xorcode.andtweet.PreferencesActivity.java

protected void showListPreference(String keyPreference, int keysR, int displayR, int summaryR) {
    String displayParm = "";
    ListPreference lP = (ListPreference) findPreference(keyPreference);
    if (lP != null) {
        String[] k = getResources().getStringArray(keysR);
        String[] d = getResources().getStringArray(displayR);
        displayParm = d[0];//w  ww  . ja  va2 s  . c  o  m
        String listValue = lP.getValue();
        for (int i = 0; i < k.length; i++) {
            if (listValue.equals(k[i])) {
                displayParm = d[i];
                break;
            }
        }
    } else {
        displayParm = keyPreference + " was not found";
    }
    MessageFormat sf = new MessageFormat(getText(summaryR).toString());
    lP.setSummary(sf.format(new Object[] { displayParm }));
}

From source file:com.opensymphony.xwork2.util.DefaultLocalizedTextProvider.java

private String formatWithNullDetection(MessageFormat mf, Object[] args) {
    String message = mf.format(args);
    if ("null".equals(message)) {
        return null;
    } else {/*from  ww w  .j a  v a 2s  . c o m*/
        return message;
    }
}

From source file:com.npower.dm.util.MessageResources.java

/**
 * Returns a text message after parametric replacement of the specified
 * parameter placeholders.  A null string result will be returned by
 * this method if no resource bundle has been configured.
 *
 * @param locale The requested message Locale, or <code>null</code>
 *  for the system default Locale//from  ww  w  . j av a  2 s  .c  om
 * @param key The message key to look up
 * @param args An array of replacement parameters for placeholders
 */
public String getMessage(Locale locale, String key, Object args[]) {

    // Cache MessageFormat instances as they are accessed
    if (locale == null) {
        locale = defaultLocale;
    }

    MessageFormat format = null;
    String formatKey = messageKey(locale, key);

    synchronized (formats) {
        format = (MessageFormat) formats.get(formatKey);
        if (format == null) {
            String formatString = getMessage(locale, key);

            if (formatString == null) {
                return returnNull ? null : ("???" + formatKey + "???");
            }

            format = new MessageFormat(escape(formatString));
            format.setLocale(locale);
            formats.put(formatKey, format);
        }

    }

    return format.format(args);
}

From source file:ImageAnalyzer.java

static String createMsg(String msg, Object[] args) {
    MessageFormat formatter = new MessageFormat(msg);
    return formatter.format(args);
}

From source file:ImageAnalyzer.java

static String createMsg(String msg, Object arg) {
    MessageFormat formatter = new MessageFormat(msg);
    return formatter.format(new Object[] { arg });
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.vigilancy.ConvokeManagement.java

public ActionForward confirmConvokes(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Boolean havingVigilantsThatAreTeachers = false;

    ConvokeBean beanWithTeachers = null;

    if (RenderUtils.getViewState("selectVigilantsThatAreTeachers") != null) {
        beanWithTeachers = (ConvokeBean) RenderUtils.getViewState("selectVigilantsThatAreTeachers")
                .getMetaObject().getObject();
    }/*from w  w  w  .  j  ava  2  s. c o  m*/

    ConvokeBean beanWithVigilants = (ConvokeBean) RenderUtils.getViewState("selectVigilants").getMetaObject()
            .getObject();

    ConvokeBean beanWithUnavailables = (ConvokeBean) RenderUtils
            .getViewState("selectVigilantsThatAreUnavailable").getMetaObject().getObject();

    List<VigilantWrapper> teachers = null;
    List<VigilantWrapper> vigilants, unavailables;

    if (RenderUtils.getViewState("selectVigilantsThatAreTeachers") != null) {
        teachers = beanWithTeachers.getSelectedTeachers();
    }

    vigilants = beanWithVigilants.getVigilants();
    unavailables = beanWithUnavailables.getSelectedUnavailableVigilants();

    String convokedVigilants = beanWithVigilants.getTeachersAsString();
    String teachersVigilancies = null;

    if (RenderUtils.getViewState("selectVigilantsThatAreTeachers") != null) {
        teachersVigilancies = beanWithTeachers.getVigilantsAsString();
        vigilants.addAll(teachers);
    } else {
        teachersVigilancies = RenderUtils.getResourceString("VIGILANCY_RESOURCES", "label.vigilancy.noone");
    }

    vigilants.addAll(unavailables);
    beanWithVigilants.setVigilants(vigilants);

    String email = RenderUtils.getResourceString("VIGILANCY_RESOURCES", "label.vigilancy.emailConvoke");
    MessageFormat format = new MessageFormat(email);
    WrittenEvaluation evaluation = beanWithVigilants.getWrittenEvaluation();
    DateTime beginDate = evaluation.getBeginningDateTime();
    String date = beginDate.getDayOfMonth() + "/" + beginDate.getMonthOfYear() + "/" + beginDate.getYear();

    String minutes = String.format("%02d", new Object[] { beginDate.getMinuteOfHour() });

    Object[] args = { evaluation.getFullName(), date, beginDate.getHourOfDay(), minutes,
            beanWithVigilants.getRoomsAsString(), teachersVigilancies, convokedVigilants,
            beanWithVigilants.getSelectedVigilantGroup().getRulesLink() };
    beanWithVigilants.setEmailMessage(format.format(args));
    request.setAttribute("bean", beanWithVigilants);
    return mapping.findForward("confirmConvokes");
}

From source file:ResourceBundleSupport.java

/**
 * Formats the message stored in the resource bundle (using a
 * MessageFormat)./*from  www  .j av a  2 s. com*/
 *
 * @param key        the resourcebundle key
 * @param parameters the parameter collection for the message
 * @return the formated string
 */
public String formatMessage(final String key, final Object[] parameters) {
    final MessageFormat format = new MessageFormat(getString(key));
    format.setLocale(getLocale());
    return format.format(parameters);
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

@Override
public Collection<NodeDescription> getPersons(final Date modifiedSince) {
    final String query;
    if (modifiedSince == null) {
        query = this.personQuery;
    } else {/*from   w w  w. j a va2 s .c  om*/
        final MessageFormat mf = new MessageFormat(this.personDifferentialQuery, Locale.ENGLISH);
        query = mf.format(new Object[] { this.timestampFormat.format(modifiedSince) });
    }

    final Supplier<InitialDirContext> contextSupplier = this.buildContextSupplier();
    final Function<InitialDirContext, Boolean> nextPageChecker = this.buildNextPageChecker();
    final Function<InitialDirContext, NamingEnumeration<SearchResult>> userSearcher = this
            .buildUserSearcher(query);

    final AtomicInteger totalEstimatedSize = new AtomicInteger(-1);
    if (this.enableProgressEstimation) {
        this.processQuery((result) -> {
            totalEstimatedSize.getAndIncrement();
        }, this.userSearchBase, query, new String[0]);
    }

    final NodeMapper userMapper = this.buildUserMapper();
    return new PersonCollection(contextSupplier, nextPageChecker, userSearcher, userMapper, this.queryBatchSize,
            totalEstimatedSize.get());
}