Example usage for java.text MessageFormat MessageFormat

List of usage examples for java.text MessageFormat MessageFormat

Introduction

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

Prototype

public MessageFormat(String pattern) 

Source Link

Document

Constructs a MessageFormat for the default java.util.Locale.Category#FORMAT FORMAT locale and the specified pattern.

Usage

From source file:org.cyberoam.iview.charts.Chart.java

/**
 * This Method gives Title with Dynamic values of Parameter
 * @param title//from  w ww .ja  va  2 s .  c om
 * @param request
 * @param reportGroupBean
 * @return
 */
public static String getFormattedTitle(HttpServletRequest request, ReportGroupBean reportGroupBean,
        boolean isPDF) {
    String title = null;
    if (request != null) {
        Object[] paramValues = null;
        String paramName = null, paramVal = null;
        StringTokenizer stToken = new StringTokenizer(reportGroupBean.getInputParams(), ",");
        paramValues = new Object[stToken.countTokens()];

        for (int i = 0; stToken.hasMoreTokens(); i++) {
            paramName = stToken.nextToken();
            if (paramName != null && (paramName.equalsIgnoreCase("Application")
                    || paramName.equalsIgnoreCase("Protocol Group") || paramName.equalsIgnoreCase("proto_group")
                            && request.getParameter(paramName).indexOf(':') != -1)) {
                paramVal = request.getParameter(paramName);
                try {
                    String data;
                    data = ProtocolBean.getProtocolNameById(
                            Integer.parseInt(paramVal.substring(0, paramVal.indexOf(':'))));
                    data = data + paramVal.substring(paramVal.indexOf(':'), paramVal.length());
                    paramVal = data;
                } catch (Exception ex) {
                }
            } else if (paramName.equalsIgnoreCase("Severity")) {
                paramVal = TabularReportConstants.getSeverity(request.getParameter(paramName));
            } else if (request.getParameter(paramName) == null || request.getParameter(paramName).equals("")) {
                paramVal = "N/A";
            } else {
                paramVal = request.getParameter(paramName);
            }
            if (isPDF) {
                paramValues[i] = paramVal;
            } else {
                paramValues[i] = "<i>" + paramVal + "</i>";
            }
        }
        MessageFormat queryFormat = new MessageFormat(reportGroupBean.getTitle());
        title = queryFormat.format(paramValues);
    }
    if (title == null) {
        return reportGroupBean.getTitle();
    } else {
        return title;
    }
}

From source file:json_to_xml_1.java

private String getI10nStringFormatted(String i10nStringName, Object... arguments) {
    MessageFormat formatter = new MessageFormat("");
    formatter.setLocale(this.getLocale());

    formatter.applyPattern(getI10nString(i10nStringName));
    return formatter.format(arguments);
}

From source file:net.sf.fspdfs.chartthemes.spring.EyeCandySixtiesChartTheme.java

/**
 *
 *//*w  w  w .j  a v  a  2s  .  c om*/
protected JFreeChart createDialChart() throws JRException {

    JRMeterPlot jrPlot = (JRMeterPlot) getPlot();

    GradientPaint gp = new GradientPaint(new Point(), Color.LIGHT_GRAY, new Point(), Color.BLACK, false);

    GradientPaint gp2 = new GradientPaint(new Point(), Color.GRAY, new Point(), Color.BLACK);

    // get data for diagrams
    DialPlot dialPlot = new DialPlot();
    //dialPlot.setView(0.0, 0.0, 1.0, 1.0);
    if (getDataset() != null) {
        dialPlot.setDataset((ValueDataset) getDataset());
    }
    StandardDialFrame dialFrame = new StandardDialFrame();
    //dialFrame.setRadius(0.60);
    //dialFrame.setBackgroundPaint(gp2);
    dialFrame.setForegroundPaint(gp2);
    dialPlot.setDialFrame(dialFrame);

    DialBackground db = new DialBackground(gp);
    db.setGradientPaintTransformer(new StandardGradientPaintTransformer(GradientPaintTransformType.VERTICAL));
    dialPlot.setBackground(db);
    StandardDialScale scale = null;
    int dialUnitScale = 1;
    Range range = convertRange(jrPlot.getDataRange());
    if (range != null) {
        double bound = Math.max(Math.abs(range.getUpperBound()), Math.abs(range.getLowerBound()));
        dialUnitScale = ChartThemesUtilities.getScale(bound);

        double lowerBound = ChartThemesUtilities.getTruncatedValue(range.getLowerBound(), dialUnitScale);
        double upperBound = ChartThemesUtilities.getTruncatedValue(range.getUpperBound(), dialUnitScale);

        scale = new StandardDialScale(lowerBound, upperBound, 225, -270, (upperBound - lowerBound) / 6, 15);
        if ((lowerBound == (int) lowerBound && upperBound == (int) upperBound
                && scale.getMajorTickIncrement() == (int) scale.getMajorTickIncrement()) || dialUnitScale > 1) {
            scale.setTickLabelFormatter(new DecimalFormat("#,##0"));
        } else if (dialUnitScale == 1) {

            scale.setTickLabelFormatter(new DecimalFormat("#,##0.0"));
        } else if (dialUnitScale <= 0) {
            scale.setTickLabelFormatter(new DecimalFormat("#,##0.00"));
        }

    } else {
        scale = new StandardDialScale();
    }
    scale.setTickRadius(0.9);
    scale.setTickLabelOffset(0.16);
    JRFont tickLabelFont = jrPlot.getTickLabelFont();
    Integer defaultBaseFontSize = (Integer) getDefaultValue(defaultChartPropertiesMap,
            ChartThemesConstants.BASEFONT_SIZE);
    Font themeTickLabelFont = getFont(
            (JRFont) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_TICK_LABEL_FONT),
            tickLabelFont, defaultBaseFontSize);
    scale.setTickLabelFont(themeTickLabelFont);
    scale.setMajorTickStroke(new BasicStroke(1f));
    scale.setMinorTickStroke(new BasicStroke(0.3f));
    scale.setMajorTickPaint(Color.WHITE);
    scale.setMinorTickPaint(Color.WHITE);
    scale.setTickLabelsVisible(true);
    scale.setFirstTickLabelVisible(true);
    dialPlot.addScale(0, scale);

    List intervals = jrPlot.getIntervals();
    if (intervals != null && intervals.size() > 0) {
        int size = Math.min(3, intervals.size());
        int colorStep = 0;
        if (size > 3)
            colorStep = 255 / (size - 3);

        for (int i = 0; i < size; i++) {
            JRMeterInterval interval = (JRMeterInterval) intervals.get(i);
            Range intervalRange = convertRange(interval.getDataRange());
            double intervalLowerBound = ChartThemesUtilities.getTruncatedValue(intervalRange.getLowerBound(),
                    dialUnitScale);
            double intervalUpperBound = ChartThemesUtilities.getTruncatedValue(intervalRange.getUpperBound(),
                    dialUnitScale);

            Color color = i < 3 ? (Color) ChartThemesConstants.AEGEAN_INTERVAL_COLORS.get(i)
                    : new Color(255 - colorStep * (i - 3), 0 + colorStep * (i - 3), 0);

            ScaledDialRange dialRange = new ScaledDialRange(intervalLowerBound, intervalUpperBound,
                    interval.getBackgroundColor() == null ? color : interval.getBackgroundColor(), 12f);
            dialRange.setInnerRadius(0.41);
            dialRange.setOuterRadius(0.41);
            dialPlot.addLayer(dialRange);
        }
    }

    JRValueDisplay display = jrPlot.getValueDisplay();
    String displayVisibility = display != null && getChart().hasProperties()
            ? getChart().getPropertiesMap().getProperty(DefaultChartTheme.PROPERTY_DIAL_VALUE_DISPLAY_VISIBLE)
            : "false";
    if (Boolean.parseBoolean(displayVisibility)) {
        ScaledDialValueIndicator dvi = new ScaledDialValueIndicator(0, dialUnitScale);
        dvi.setBackgroundPaint(ChartThemesConstants.TRANSPARENT_PAINT);
        //         dvi.setFont(JRFontUtil.getAwtFont(jrFont).deriveFont(10f).deriveFont(Font.BOLD));
        dvi.setOutlinePaint(ChartThemesConstants.TRANSPARENT_PAINT);
        dvi.setPaint(Color.WHITE);

        String pattern = display.getMask() != null ? display.getMask() : "#,##0.####";
        if (pattern != null)
            dvi.setNumberFormat(new DecimalFormat(pattern));
        dvi.setRadius(0.15);
        dvi.setValueAnchor(RectangleAnchor.CENTER);
        dvi.setTextAnchor(TextAnchor.CENTER);
        //dvi.setTemplateValue(Double.valueOf(getDialTickValue(dialPlot.getValue(0),dialUnitScale)));
        dialPlot.addLayer(dvi);
    }
    String label = getChart().hasProperties()
            ? getChart().getPropertiesMap().getProperty(DefaultChartTheme.PROPERTY_DIAL_LABEL)
            : null;

    if (label != null) {
        JRFont displayFont = jrPlot.getValueDisplay().getFont();
        Font themeDisplayFont = getFont(
                (JRFont) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_DISPLAY_FONT),
                displayFont, defaultBaseFontSize);
        if (dialUnitScale < 0)
            label = new MessageFormat(label)
                    .format(new Object[] { String.valueOf(Math.pow(10, dialUnitScale)) });
        else if (dialUnitScale < 3)
            label = new MessageFormat(label).format(new Object[] { "1" });
        else
            label = new MessageFormat(label)
                    .format(new Object[] { String.valueOf((int) Math.pow(10, dialUnitScale - 2)) });

        String[] textLines = label.split("\\n");
        for (int i = 0; i < textLines.length; i++) {
            DialTextAnnotation dialAnnotation = new DialTextAnnotation(textLines[i]);
            dialAnnotation.setFont(themeDisplayFont);
            dialAnnotation.setPaint(Color.WHITE);
            dialAnnotation.setRadius(Math.sin(Math.PI / 4.0) + i / 10.0);
            dialAnnotation.setAnchor(TextAnchor.CENTER);
            dialPlot.addLayer(dialAnnotation);
        }
    }

    //DialPointer needle = new DialPointer.Pointer();
    Paint paint = new Color(191, 48, 0);
    DialPointer needle = new ScaledDialPointer(dialUnitScale, paint, paint);

    needle.setVisible(true);
    needle.setRadius(0.91);
    dialPlot.addLayer(needle);

    DialCap cap = new DialCap();
    cap.setRadius(0.05);
    cap.setFillPaint(Color.DARK_GRAY);
    cap.setOutlinePaint(Color.GRAY);
    cap.setOutlineStroke(new BasicStroke(0.5f));
    dialPlot.setCap(cap);

    JFreeChart jfreeChart = new JFreeChart((String) evaluateExpression(getChart().getTitleExpression()), null,
            dialPlot, getChart().getShowLegend() == null ? false : getChart().getShowLegend().booleanValue());

    // Set all the generic options
    configureChart(jfreeChart, getPlot());

    jfreeChart.setBackgroundPaint(ChartThemesConstants.TRANSPARENT_PAINT);
    jfreeChart.setBorderVisible(false);

    return jfreeChart;

}

From source file:net.sf.jasperreports.chartthemes.spring.EyeCandySixtiesChartTheme.java

@Override
protected JFreeChart createDialChart() throws JRException {

    JRMeterPlot jrPlot = (JRMeterPlot) getPlot();

    GradientPaint gp = new GradientPaint(new Point(), Color.LIGHT_GRAY, new Point(), Color.BLACK, false);

    GradientPaint gp2 = new GradientPaint(new Point(), Color.GRAY, new Point(), Color.BLACK);

    // get data for diagrams
    DialPlot dialPlot = new DialPlot();
    //dialPlot.setView(0.0, 0.0, 1.0, 1.0);
    if (getDataset() != null) {
        dialPlot.setDataset((ValueDataset) getDataset());
    }//from   ww w  . ja va2  s  .c o  m
    StandardDialFrame dialFrame = new StandardDialFrame();
    //dialFrame.setRadius(0.60);
    //dialFrame.setBackgroundPaint(gp2);
    dialFrame.setForegroundPaint(gp2);
    dialPlot.setDialFrame(dialFrame);

    DialBackground db = new DialBackground(gp);
    db.setGradientPaintTransformer(new StandardGradientPaintTransformer(GradientPaintTransformType.VERTICAL));
    dialPlot.setBackground(db);
    StandardDialScale scale = null;
    int dialUnitScale = 1;
    Range range = convertRange(jrPlot.getDataRange());
    if (range != null) {
        double bound = Math.max(Math.abs(range.getUpperBound()), Math.abs(range.getLowerBound()));
        dialUnitScale = ChartThemesUtilities.getScale(bound);

        double lowerBound = ChartThemesUtilities.getTruncatedValue(range.getLowerBound(), dialUnitScale);
        double upperBound = ChartThemesUtilities.getTruncatedValue(range.getUpperBound(), dialUnitScale);
        int tickCount = jrPlot.getTickCount() != null && jrPlot.getTickCount() > 1 ? jrPlot.getTickCount() : 7;
        scale = new StandardDialScale(lowerBound, upperBound, 225, -270,
                (upperBound - lowerBound) / (tickCount - 1), 15);
        if ((lowerBound == (int) lowerBound && upperBound == (int) upperBound
                && scale.getMajorTickIncrement() == (int) scale.getMajorTickIncrement()) || dialUnitScale > 1) {
            scale.setTickLabelFormatter(
                    new DecimalFormat("#,##0", DecimalFormatSymbols.getInstance(getLocale())));
        } else if (dialUnitScale == 1) {

            scale.setTickLabelFormatter(
                    new DecimalFormat("#,##0.0", DecimalFormatSymbols.getInstance(getLocale())));
        } else if (dialUnitScale <= 0) {
            scale.setTickLabelFormatter(
                    new DecimalFormat("#,##0.00", DecimalFormatSymbols.getInstance(getLocale())));
        } else {
            // localizing the default tick label formatter
            scale.setTickLabelFormatter(
                    new DecimalFormat("0.0", DecimalFormatSymbols.getInstance(getLocale())));
        }

    } else {
        scale = new StandardDialScale();

        // localizing the default tick label formatter
        scale.setTickLabelFormatter(new DecimalFormat("0.0", DecimalFormatSymbols.getInstance(getLocale())));
    }
    scale.setTickRadius(0.9);
    scale.setTickLabelOffset(0.16);
    JRFont tickLabelFont = jrPlot.getTickLabelFont();
    Integer defaultBaseFontSize = (Integer) getDefaultValue(defaultChartPropertiesMap,
            ChartThemesConstants.BASEFONT_SIZE);
    Font themeTickLabelFont = getFont(
            (JRFont) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_TICK_LABEL_FONT),
            tickLabelFont, defaultBaseFontSize);
    scale.setTickLabelFont(themeTickLabelFont);
    scale.setMajorTickStroke(new BasicStroke(1f));
    scale.setMinorTickStroke(new BasicStroke(0.3f));
    scale.setMajorTickPaint(Color.WHITE);
    scale.setMinorTickPaint(Color.WHITE);
    scale.setTickLabelsVisible(true);
    scale.setFirstTickLabelVisible(true);

    dialPlot.addScale(0, scale);

    List<JRMeterInterval> intervals = jrPlot.getIntervals();
    if (intervals != null && intervals.size() > 0) {
        int size = Math.min(3, intervals.size());
        int colorStep = 0;
        if (size > 3)
            colorStep = 255 / (size - 3);

        for (int i = 0; i < size; i++) {
            JRMeterInterval interval = intervals.get(i);
            Range intervalRange = convertRange(interval.getDataRange());
            double intervalLowerBound = ChartThemesUtilities.getTruncatedValue(intervalRange.getLowerBound(),
                    dialUnitScale);
            double intervalUpperBound = ChartThemesUtilities.getTruncatedValue(intervalRange.getUpperBound(),
                    dialUnitScale);

            Color color = i < 3 ? (Color) ChartThemesConstants.AEGEAN_INTERVAL_COLORS.get(i)
                    : new Color(255 - colorStep * (i - 3), 0 + colorStep * (i - 3), 0);

            ScaledDialRange dialRange = new ScaledDialRange(intervalLowerBound, intervalUpperBound,
                    interval.getBackgroundColor() == null ? color : interval.getBackgroundColor(), 12f);
            dialRange.setInnerRadius(0.41);
            dialRange.setOuterRadius(0.41);
            dialPlot.addLayer(dialRange);
        }
    }

    JRValueDisplay display = jrPlot.getValueDisplay();
    String displayVisibility = display != null && getChart().hasProperties()
            ? getChart().getPropertiesMap().getProperty(DefaultChartTheme.PROPERTY_DIAL_VALUE_DISPLAY_VISIBLE)
            : "false";
    if (Boolean.parseBoolean(displayVisibility)) {
        ScaledDialValueIndicator dvi = new ScaledDialValueIndicator(0, dialUnitScale);
        dvi.setBackgroundPaint(ChartThemesConstants.TRANSPARENT_PAINT);
        //         dvi.setFont(JRFontUtil.getAwtFont(jrFont).deriveFont(10f).deriveFont(Font.BOLD));
        dvi.setOutlinePaint(ChartThemesConstants.TRANSPARENT_PAINT);
        dvi.setPaint(Color.WHITE);

        String pattern = display.getMask() != null ? display.getMask() : "#,##0.####";
        if (pattern != null)
            dvi.setNumberFormat(new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(getLocale())));
        dvi.setRadius(0.15);
        dvi.setValueAnchor(RectangleAnchor.CENTER);
        dvi.setTextAnchor(TextAnchor.CENTER);
        //dvi.setTemplateValue(Double.valueOf(getDialTickValue(dialPlot.getValue(0),dialUnitScale)));
        dialPlot.addLayer(dvi);
    }
    String label = getChart().hasProperties()
            ? getChart().getPropertiesMap().getProperty(DefaultChartTheme.PROPERTY_DIAL_LABEL)
            : null;

    if (label != null) {
        JRFont displayFont = jrPlot.getValueDisplay().getFont();
        Font themeDisplayFont = getFont(
                (JRFont) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_DISPLAY_FONT),
                displayFont, defaultBaseFontSize);
        if (dialUnitScale < 0)
            label = new MessageFormat(label)
                    .format(new Object[] { String.valueOf(Math.pow(10, dialUnitScale)) });
        else if (dialUnitScale < 3)
            label = new MessageFormat(label).format(new Object[] { "1" });
        else
            label = new MessageFormat(label)
                    .format(new Object[] { String.valueOf((int) Math.pow(10, dialUnitScale - 2)) });

        String[] textLines = label.split("\\n");
        for (int i = 0; i < textLines.length; i++) {
            DialTextAnnotation dialAnnotation = new DialTextAnnotation(textLines[i]);
            dialAnnotation.setFont(themeDisplayFont);
            dialAnnotation.setPaint(Color.WHITE);
            dialAnnotation.setRadius(Math.sin(Math.PI / 4.0) + i / 10.0);
            dialAnnotation.setAnchor(TextAnchor.CENTER);
            dialPlot.addLayer(dialAnnotation);
        }
    }

    //DialPointer needle = new DialPointer.Pointer();
    Paint paint = new Color(191, 48, 0);
    DialPointer needle = new ScaledDialPointer(dialUnitScale, paint, paint);

    needle.setVisible(true);
    needle.setRadius(0.91);
    dialPlot.addLayer(needle);

    DialCap cap = new DialCap();
    cap.setRadius(0.05);
    cap.setFillPaint(Color.DARK_GRAY);
    cap.setOutlinePaint(Color.GRAY);
    cap.setOutlineStroke(new BasicStroke(0.5f));
    dialPlot.setCap(cap);

    JFreeChart jfreeChart = new JFreeChart(evaluateTextExpression(getChart().getTitleExpression()), null,
            dialPlot, getChart().getShowLegend() == null ? false : getChart().getShowLegend());

    // Set all the generic options
    configureChart(jfreeChart, getPlot());

    jfreeChart.setBackgroundPaint(ChartThemesConstants.TRANSPARENT_PAINT);
    jfreeChart.setBorderVisible(false);

    return jfreeChart;

}

From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * Assigns the pattern for the distinguished name (DN) of the user's directory entry, with
 * <code>{0}</code> marking where the actual username should be inserted.
 * /*from   w  ww. j  a v  a  2s .  c  o m*/
 * @param userPattern
 *            the field value to assign
 */
public void setUserPattern(String userPattern) {
    this.isInitialized = false;
    this.userPattern = (userPattern == null) ? null : new MessageFormat(userPattern);
}

From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * Assigns the colon-separated list of LDAP filter expressions to use when searching for a
 * user's directory entry, with <code>{0}</code> marking where the actual username should be
 * inserted./*from   w w w. j  a  va2 s  .  c o m*/
 * 
 * @param userSearchPatterns
 *            the field value to assign
 */
public void setUserSearchPatterns(String userSearchPatterns) {
    this.isInitialized = false;

    if (userSearchPatterns != null) {
        String[] patternList = userSearchPatterns.split("\\:");
        this.userSearchPatterns = new MessageFormat[patternList.length];

        for (int i = 0; i < patternList.length; i++) {
            this.userSearchPatterns[i] = new MessageFormat(patternList[i]);
        }
    } else {
        this.userSearchPatterns = null;
    }
}

From source file:org.hyperic.hq.bizapp.server.session.EventsBossImpl.java

/**
 * Fix a batch of alerts. TODO: remove comment below Method is
 * "NotSupported" since all the alert fixes may take longer than the
 * transaction timeout. No need for a transaction in this context.
 * //from ww  w .  j  av a2 s.c  om
 */
public void fixAlert(int sessionID, EscalationAlertType alertType, Integer alertID, String moreInfo,
        boolean fixAllPrevious)
        throws SessionTimeoutException, SessionNotFoundException, PermissionException, ActionExecuteException {
    AuthzSubject subject = sessionManager.getSubject(sessionID);

    if (fixAllPrevious) {
        long fixCount = fixPreviousAlerts(sessionID, alertType, alertID, moreInfo);
        if (fixCount > 0) {
            if (moreInfo == null) {
                moreInfo = "";
            }
            StringBuffer sb = new StringBuffer();
            MessageFormat messageFormat = new MessageFormat(
                    ResourceBundle.getBundle(BUNDLE).getString("events.alert.fixAllPrevious"));
            messageFormat.format(new String[] { Long.toString(fixCount) }, sb, null);
            moreInfo = sb.toString() + moreInfo;
        }
    }
    // fix the selected alert
    escalationManager.fixAlert(subject, alertType, alertID, moreInfo, false);
}

From source file:org.talend.designer.runprocess.ui.DebugProcessTosComposite.java

@Override
public void debug() {
    if (manager.getClearBeforeExec()) {
        processContext.clearMessages();/*from  w  ww.ja v  a 2  s  .  c  o m*/
    }
    setHideconsoleLine(false);
    if ((processContext.getProcess()) instanceof org.talend.designer.core.ui.editor.process.Process) {
        ((org.talend.designer.core.ui.editor.process.Process) processContext.getProcess())
                .checkDifferenceWithRepository();
    }

    // final IPreferenceStore preferenceStore = DebugUIPlugin.getDefault().getPreferenceStore();
    final IPreferenceStore preferenceStore = DebugUITools.getPreferenceStore();
    final boolean oldValueConsoleOnOut = preferenceStore
            .getBoolean(IDebugPreferenceConstants.CONSOLE_OPEN_ON_OUT);
    final boolean oldValueConsoleOnErr = preferenceStore
            .getBoolean(IDebugPreferenceConstants.CONSOLE_OPEN_ON_ERR);

    preferenceStore.setValue(IDebugPreferenceConstants.CONSOLE_OPEN_ON_OUT, false);

    preferenceStore.setValue(IDebugPreferenceConstants.CONSOLE_OPEN_ON_ERR, false);
    // java debug to collect when tos
    int num = RunProcessPlugin.getDefault().getPreferenceStore()
            .getInt(RunProcessTokenCollector.TOS_COUNT_DEBUG_RUNS.getPrefKey());
    RunProcessPlugin.getDefault().getPreferenceStore()
            .setValue(RunProcessTokenCollector.TOS_COUNT_DEBUG_RUNS.getPrefKey(), num + 1);

    checkSaveBeforeRunSelection();

    if (contextComposite.promptConfirmLauch()) {
        setRunnable(false);
        final IContext context = contextComposite.getSelectedContext();

        IRunnableWithProgress worker = new IRunnableWithProgress() {

            @Override
            public void run(IProgressMonitor monitor) {
                IProcessor processor = ProcessorUtilities.getProcessor(processContext.getProcess(),
                        processContext.getProcess().getProperty(), context);
                monitor.beginTask("Launching debugger", IProgressMonitor.UNKNOWN); //$NON-NLS-1$
                try {
                    // use this function to generate childrens also.
                    ProcessorUtilities.generateCode(processContext.getProcess(), context, false, false, true,
                            monitor);

                    ILaunchConfiguration config = ((Processor) processor).getDebugConfiguration(
                            processContext.getStatisticsPort(), processContext.getTracesPort(), null);

                    // see feature 0004820: The run job doesn't verify if
                    // code is correct before launching
                    if (!JobErrorsChecker.hasErrors(DebugProcessTosComposite.this.getShell())) {

                        if (config != null) {
                            // PlatformUI.getWorkbench().
                            // getActiveWorkbenchWindow
                            // ().addPerspectiveListener(new
                            // DebugInNewWindowListener());
                            DebugUITools.launch(config, ILaunchManager.DEBUG_MODE);

                        } else {
                            MessageDialog.openInformation(getShell(),
                                    Messages.getString("ProcessDebugDialog.debugBtn"), //$NON-NLS-1$
                                    Messages.getString("ProcessDebugDialog.errortext")); //$NON-NLS-1$ 
                        }
                    }
                } catch (ProcessorException e) {
                    IStatus status = new Status(IStatus.ERROR, RunProcessPlugin.PLUGIN_ID, IStatus.OK,
                            "Debug launch failed.", e); //$NON-NLS-1$
                    RunProcessPlugin.getDefault().getLog().log(status);
                    MessageDialog.openError(getShell(), Messages.getString("ProcessDebugDialog.debugBtn"), ""); //$NON-NLS-1$ //$NON-NLS-2$
                } finally {
                    monitor.done();
                }
            }
        };

        IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
        try {
            progressService.runInUI(PlatformUI.getWorkbench().getProgressService(), worker,
                    ResourcesPlugin.getWorkspace().getRoot());
        } catch (InvocationTargetException e) {
            // e.printStackTrace();
            ExceptionHandler.process(e);
        } catch (InterruptedException e) {
            // e.printStackTrace();
            ExceptionHandler.process(e);
        }
    }

    debugMode = true;
    try {
        Thread thread = new Thread() {

            @Override
            public void run() {
                while (debugMode) {
                    final IProcess process = DebugUITools.getCurrentProcess();
                    if (process != null && process.isTerminated()) {
                        Display dis = Display.getCurrent();
                        if (dis == null) {
                            dis = Display.getDefault();
                        }
                        dis.asyncExec(new Runnable() {

                            @Override
                            public void run() {
                                setRunnable(true);
                                if (!killBtn.isDisposed() && killBtn != null) {
                                    killBtn.setEnabled(false);
                                }
                                preferenceStore.setValue(IDebugPreferenceConstants.CONSOLE_OPEN_ON_OUT,
                                        oldValueConsoleOnOut);

                                preferenceStore.setValue(IDebugPreferenceConstants.CONSOLE_OPEN_ON_ERR,
                                        oldValueConsoleOnErr);

                                if (isAddedStreamListener) {
                                    process.getStreamsProxy().getOutputStreamMonitor()
                                            .removeListener(streamListener);
                                    isAddedStreamListener = false;

                                    if (processContext.isRunning()) {
                                        final String endingPattern = Messages
                                                .getString("ProcessComposite.endPattern"); //$NON-NLS-1$
                                        MessageFormat mf = new MessageFormat(endingPattern);
                                        String byeMsg;
                                        try {
                                            byeMsg = "\n" //$NON-NLS-1$
                                                    + mf.format(new Object[] {
                                                            processContext.getProcess().getName(), new Date(),
                                                            new Integer(process.getExitValue()) });
                                            processContext.addDebugResultToConsole(
                                                    new ProcessMessage(MsgType.CORE_OUT, byeMsg));
                                        } catch (DebugException e) {
                                            // e.printStackTrace();
                                            ExceptionHandler.process(e);
                                        }
                                        processContext.setRunning(false);
                                    }
                                }
                                debugMode = false;
                            }
                        });
                    } else {
                        if (process != null) { // (one at leat) process
                            // still running
                            Display dis = Display.getCurrent();
                            if (dis == null) {
                                dis = Display.getDefault();
                            }
                            dis.asyncExec(new Runnable() {

                                @Override
                                public void run() {
                                    setRunnable(false);
                                    if (!killBtn.isDisposed() && killBtn != null) {
                                        killBtn.setEnabled(true);
                                    }
                                    processContext.setRunning(true);
                                    processContext.setDebugProcess(process);
                                    if (!isAddedStreamListener) {
                                        process.getStreamsProxy().getOutputStreamMonitor()
                                                .addListener(streamListener);
                                        // if (clearBeforeExec.getSelection()) {
                                        // processContext.clearMessages();
                                        // }
                                        // if (watchBtn.getSelection()) {
                                        // processContext.switchTime();
                                        // }

                                        ClearPerformanceAction clearPerfAction = new ClearPerformanceAction();
                                        clearPerfAction.setProcess(processContext.getProcess());
                                        clearPerfAction.run();

                                        ClearTraceAction clearTraceAction = new ClearTraceAction();
                                        clearTraceAction.setProcess(processContext.getProcess());
                                        clearTraceAction.run();
                                        isAddedStreamListener = true;

                                        final String startingPattern = Messages
                                                .getString("ProcessComposite.startPattern"); //$NON-NLS-1$
                                        MessageFormat mf = new MessageFormat(startingPattern);
                                        String welcomeMsg = mf.format(new Object[] {
                                                processContext.getProcess().getName(), new Date() });
                                        processContext.addDebugResultToConsole(
                                                new ProcessMessage(MsgType.CORE_OUT, welcomeMsg + "\r\n"));//$NON-NLS-1$
                                    }
                                }
                            });
                        } else { // no process running
                            Display dis = Display.getCurrent();
                            if (dis == null) {
                                dis = Display.getDefault();
                            }
                            dis.asyncExec(new Runnable() {

                                @Override
                                public void run() {
                                    setRunnable(true);
                                    if (!killBtn.isDisposed() && killBtn != null) {
                                        killBtn.setEnabled(false);
                                    }
                                }
                            });
                        }
                    }
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // e.printStackTrace();
                        ExceptionHandler.process(e);
                    }
                }
            }
        };
        thread.start();
    } catch (Exception e) {
        ExceptionHandler.process(e);
        processContext.addErrorMessage(e);
        kill();
    }
}

From source file:com.amalto.core.util.Util.java

public static String getMessage(String value, Object... args) {
    try {//from   ww  w  .  ja v  a2 s.com
        MessageFormat format = new MessageFormat(escape(value));
        value = format.format(args);
        return value;
    } catch (MissingResourceException e) {
        return "???" + value + "???";
    }
}

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

/**
 * Utility method that checks if obj is an instance of targetType.
 * //  w w w .  j av a 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));
    }
}