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 StringBuffer format(Object arguments, StringBuffer result, FieldPosition pos) 

Source Link

Document

Formats an array of objects and appends the MessageFormat's pattern, with format elements replaced by the formatted objects, to the provided StringBuffer.

Usage

From source file:org.silverpeas.dbbuilder.DBBuilder.java

/**
 * @param args//  ww  w.j  av  a 2  s. com
 * @see
 */
public static void main(String[] args) {
    ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext(
            "classpath:/spring-jdbc-datasource.xml");
    try {
        // Ouverture des traces
        Date startDate = new Date();
        System.out.println(
                MessageFormat.format(messages.getString("dbbuilder.start"), DBBuilderAppVersion, startDate));
        console = new Console(DBBuilder.class);
        console.printMessage("*************************************************************");
        console.printMessage(
                MessageFormat.format(messages.getString("dbbuilder.start"), DBBuilderAppVersion, startDate));
        // Lecture des variables d'environnement  partir de dbBuilderSettings
        dbBuilderResources = FileUtil
                .loadResource("/org/silverpeas/dbBuilder/settings/dbBuilderSettings.properties");
        // Lecture des paramtres d'entre
        params = new CommandLineParameters(console, args);

        if (params.isSimulate() && DatabaseType.ORACLE == params.getDbType()) {
            throw new Exception(messages.getString("oracle.simulate.error"));
        }
        console.printMessage(messages.getString("jdbc.connection.configuration"));
        console.printMessage(ConnectionFactory.getConnectionInfo());
        console.printMessage("\tAction        : " + params.getAction());
        console.printMessage("\tVerbose mode  : " + params.isVerbose());
        console.printMessage("\tSimulate mode : " + params.isSimulate());
        if (Action.ACTION_CONNECT == params.getAction()) {
            // un petit message et puis c'est tout
            console.printMessage(messages.getString("connection.success"));
            System.out.println(messages.getString("connection.success"));
        } else {
            // Modules en place sur la BD avant install
            console.printMessage("DB Status before build :");
            List<String> packagesIntoDB = checkDBStatus();
            // initialisation d'un vecteur des instructions SQL  passer en fin d'upgrade
            // pour mettre  niveau les versions de modules en base
            MetaInstructions sqlMetaInstructions = new MetaInstructions();
            File dirXml = new File(params.getDbType().getDBContributionDir());
            DBXmlDocument destXml = loadMasterContribution(dirXml);
            UninstallInformations processesToCacheIntoDB = new UninstallInformations();

            File[] listeFileXml = dirXml.listFiles();
            Arrays.sort(listeFileXml);

            List<DBXmlDocument> listeDBXmlDocument = new ArrayList<DBXmlDocument>(listeFileXml.length);
            int ignoredFiles = 0;
            // Ouverture de tous les fichiers de configurations
            console.printMessage(messages.getString("ignored.contribution"));

            for (File xmlFile : listeFileXml) {
                if (xmlFile.isFile() && "xml".equals(FileUtil.getExtension(xmlFile))
                        && !(FIRST_DBCONTRIBUTION_FILE.equalsIgnoreCase(xmlFile.getName()))
                        && !(MASTER_DBCONTRIBUTION_FILE.equalsIgnoreCase(xmlFile.getName()))) {
                    DBXmlDocument fXml = new DBXmlDocument(dirXml, xmlFile.getName());
                    fXml.load();
                    // vrification des dpendances et prise en compte uniquement si dependences OK
                    if (hasUnresolvedRequirements(listeFileXml, fXml)) {
                        console.printMessage(
                                '\t' + xmlFile.getName() + " (because of unresolved requirements).");
                        ignoredFiles++;
                    } else if (ACTION_ENFORCE_UNINSTALL == params.getAction()) {
                        console.printMessage('\t' + xmlFile.getName() + " (because of "
                                + ACTION_ENFORCE_UNINSTALL + " mode).");
                        ignoredFiles++;
                    } else {
                        listeDBXmlDocument.add(fXml);
                    }
                }
            }
            if (0 == ignoredFiles) {
                console.printMessage("\t(none)");
            }

            // prpare une HashMap des modules prsents en fichiers de contribution
            Map packagesIntoFile = new HashMap();
            int j = 0;
            console.printMessage(messages.getString("merged.contribution"));
            console.printMessage(params.getAction().toString());
            if (ACTION_ENFORCE_UNINSTALL != params.getAction()) {
                console.printMessage('\t' + FIRST_DBCONTRIBUTION_FILE);
                j++;
            }
            for (DBXmlDocument currentDoc : listeDBXmlDocument) {
                console.printMessage('\t' + currentDoc.getName());
                j++;
            }
            if (0 == j) {
                console.printMessage("\t(none)");
            }
            // merge des diffrents fichiers de contribution ligibles :
            console.printMessage("Build decisions are :");
            // d'abord le fichier dbbuilder-contribution ...
            DBXmlDocument fileXml;
            if (ACTION_ENFORCE_UNINSTALL != params.getAction()) {
                try {
                    fileXml = new DBXmlDocument(dirXml, FIRST_DBCONTRIBUTION_FILE);
                    fileXml.load();
                } catch (Exception e) {
                    // contribution de dbbuilder non trouve -> on continue, on est certainement en train
                    // de desinstaller la totale
                    fileXml = null;
                }
                if (null != fileXml) {
                    DBBuilderFileItem dbbuilderItem = new DBBuilderFileItem(fileXml);
                    packagesIntoFile.put(dbbuilderItem.getModule(), null);
                    mergeActionsToDo(dbbuilderItem, destXml, processesToCacheIntoDB, sqlMetaInstructions);
                }
            }

            // ... puis les autres
            for (DBXmlDocument currentDoc : listeDBXmlDocument) {
                DBBuilderFileItem tmpdbbuilderItem = new DBBuilderFileItem(currentDoc);
                packagesIntoFile.put(tmpdbbuilderItem.getModule(), null);
                mergeActionsToDo(tmpdbbuilderItem, destXml, processesToCacheIntoDB, sqlMetaInstructions);
            }

            // ... et enfin les pices BD  dsinstaller
            // ... attention, l'ordonnancement n'tant pas dispo, on les traite dans
            // l'ordre inverse pour faire passer busCore a la fin, de nombreuses contraintes
            // des autres modules referencant les PK de busCore
            List<String> itemsList = new ArrayList<String>();

            boolean foundDBBuilder = false;
            for (String dbPackage : packagesIntoDB) {
                if (!packagesIntoFile.containsKey(dbPackage)) {
                    // Package en base et non en contribution -> candidat  desinstallation
                    if (DBBUILDER_MODULE.equalsIgnoreCase(dbPackage)) {
                        foundDBBuilder = true;
                    } else if (ACTION_ENFORCE_UNINSTALL == params.getAction()) {
                        if (dbPackage.equals(params.getModuleName())) {
                            itemsList.add(0, dbPackage);
                        }
                    } else {
                        itemsList.add(0, dbPackage);
                    }
                }
            }

            if (foundDBBuilder) {
                if (ACTION_ENFORCE_UNINSTALL == params.getAction()) {
                    if (DBBUILDER_MODULE.equals(params.getModuleName())) {
                        itemsList.add(itemsList.size(), DBBUILDER_MODULE);
                    }
                } else {
                    itemsList.add(itemsList.size(), DBBUILDER_MODULE);
                }
            }
            for (String item : itemsList) {
                console.printMessage("**** Treating " + item + " ****");
                DBBuilderDBItem tmpdbbuilderItem = new DBBuilderDBItem(item);
                mergeActionsToDo(tmpdbbuilderItem, destXml, processesToCacheIntoDB, sqlMetaInstructions);
            }
            destXml.setName("res.txt");
            destXml.save();
            console.printMessage("Build parts are :");
            // Traitement des pices slectionnes
            // remarque : durant cette phase, les erreurs sont traites -> on les catche en
            // retour sans les retraiter
            if (ACTION_INSTALL == params.getAction()) {
                processDB(destXml, processesToCacheIntoDB, sqlMetaInstructions, TAGS_TO_MERGE_4_INSTALL);
            } else if (ACTION_UNINSTALL == params.getAction()
                    || ACTION_ENFORCE_UNINSTALL == params.getAction()) {
                processDB(destXml, processesToCacheIntoDB, sqlMetaInstructions, TAGS_TO_MERGE_4_UNINSTALL);
            } else if (ACTION_OPTIMIZE == params.getAction()) {
                processDB(destXml, processesToCacheIntoDB, sqlMetaInstructions, TAGS_TO_MERGE_4_OPTIMIZE);
            } else if (ACTION_ALL == params.getAction()) {
                processDB(destXml, processesToCacheIntoDB, sqlMetaInstructions, TAGS_TO_MERGE_4_ALL);
            }
            // Modules en place sur la BD en final
            console.printMessage("Finally DB Status :");
            checkDBStatus();
        }
        Date endDate = new Date();
        console.printMessage(MessageFormat.format(messages.getString("dbbuilder.success"), endDate));
        System.out.println("*******************************************************************");
        System.out.println(MessageFormat.format(messages.getString("dbbuilder.success"), endDate));
    } catch (Exception e) {
        e.printStackTrace();
        console.printError(e.getMessage(), e);
        Date endDate = new Date();
        console.printError(MessageFormat.format(messages.getString("dbbuilder.failure"), endDate));
        System.out.println("*******************************************************************");
        System.out.println(MessageFormat.format(messages.getString("dbbuilder.failure"), endDate));
        System.exit(1);
    } finally {
        springContext.close();
        console.close();
    }
}

From source file:fr.inria.atlanmod.dag.instantiator.Launcher.java

public static void main(String[] args) throws GenerationException, IOException {

    ResourceSetImpl resourceSet = new ResourceSetImpl();
    { // initializing the registry

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX,
                new EcoreResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME,
                NeoEMFResourceFactory.eINSTANCE);

    }//from   ww  w. j  a  v  a2s.c  o  m

    Options options = new Options();

    configureOptions(options);

    CommandLineParser parser = new GnuParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        //         String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS);
        //         
        //         LOGGER.info("Start loading the package");
        //         Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class);
        //         EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null);
        //         
        //         Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy"));
        //          metamodelResource.getContents().add(_package);
        //          LOGGER.info("Finish loading the package");

        int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE;
        if (commandLine.hasOption(SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(SIZE);
            size = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        float variation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION,
                        number.floatValue()));
            }
            variation = number.floatValue();
        }

        float propVariation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(PROP_VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}",
                        PROP_VARIATION, number.floatValue()));
            }
            propVariation = number.floatValue();
        }

        long seed = System.currentTimeMillis();
        if (commandLine.hasOption(SEED)) {
            seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue();
        }

        Range<Integer> range = Range.between(Math.round(size * (1 - variation)),
                Math.round(size * (1 + variation)));

        ISpecimenConfiguration config = new DagMetamodelConfig(range, seed);
        IGenerator generator = new DagGenerator(config, config.getSeed());

        GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(generator);

        if (commandLine.hasOption(OUTPUT_PATH)) {
            String outDir = commandLine.getOptionValue(OUTPUT_PATH);
            //java.net.URI intermediateURI = java.net.URI.create(outDir);
            modelGen.setSamplesPath(outDir);
        }

        int numberOfModels = 1;
        if (commandLine.hasOption(N_MODELS)) {
            numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue();
        }

        int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH;
        if (commandLine.hasOption(VALUES_SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE);
            valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE;
        if (commandLine.hasOption(DEGREE)) {
            Number number = (Number) commandLine.getParsedOptionValue(DEGREE);
            referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        config.setValuesRange(Math.round(valuesSize * (1 - propVariation)),
                Math.round(valuesSize * (1 + propVariation)));

        config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        long start = System.currentTimeMillis();
        modelGen.runGeneration(resourceSet, numberOfModels, size, variation);
        long end = System.currentTimeMillis();
        LOGGER.info(
                MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000)));

        //         for (Resource rsc : resourceSet.getResources()) {
        //            if (rsc.getContents().get(0) instanceof DAG) {
        //               
        //            }
        //               
        //         }

        if (commandLine.hasOption(DIAGNOSE)) {
            for (Resource resource : resourceSet.getResources()) {
                LOGGER.info(
                        MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI()));
                BasicDiagnostic diagnosticChain = diagnoseResource(resource);
                if (!isFailed(diagnosticChain)) {
                    LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''",
                            resource.getURI()));
                } else {
                    LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''",
                            diagnosticChain.getChildren().size(), resource.getURI()));
                    for (Diagnostic diagnostic : diagnosticChain.getChildren()) {
                        LOGGER.fine(diagnostic.getMessage());
                    }
                }
            }
            LOGGER.info("Validation finished");
        }

    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new OptionComarator<Option>());
        try {
            formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80));
        } catch (Throwable t) {
            LOGGER.warning("Unable to get console information");
        }
        ;
        formatter.printHelp("java -jar <this-file.jar>", options, true);
        System.exit(ERROR);
    } catch (Throwable t) {
        System.err.println("ERROR: " + t.getLocalizedMessage());
        StringWriter stringWriter = new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter));
        System.err.println(t);
        LOGGER.severe(stringWriter.toString());
        System.exit(ERROR);
    }
}

From source file:gov.nih.nci.firebird.common.ValidationFailure.java

/**
 * Creates a new failure instance (non-field level).
 *
 * @param resources contains the failure messages
 * @param messageKey the key to the specific failure
 * @param arguments parameter values to be inserted into the failure message
 * @return the failure//from  ww w  . j a  v a 2s . c o  m
 */
public static ValidationFailure create(ResourceBundle resources, String messageKey, Object... arguments) {
    MessageFormat format = new MessageFormat(resources.getString(messageKey));
    String message = format.format(arguments, new StringBuffer(), new FieldPosition(0)).toString();
    return new ValidationFailure(message);
}

From source file:com.albert.util.StringUtilCommon.java

/**
 * Get message from resource bundle//from ww w  .  j a  v a2 s .  co m
 * 
 * @param key
 * @param locale
 * @param bundleName
 * @param params
 * @return
 */
public static String getMessage(String key, Locale locale, String bundleName, Object params[]) {

    String text = null;

    ResourceBundle bundle = ResourceBundle.getBundle(bundleName, locale);

    try {
        text = bundle.getString(key);
    } catch (Exception e) {
        text = key;
    }

    if (params != null) {
        MessageFormat mf = new MessageFormat(text, locale);
        text = mf.format(params, new StringBuffer(), null).toString();
    }

    return text;
}

From source file:io.stallion.secrets.SecretsCommandLineManager.java

public void listSecrets() {
    MessageFormat format = new MessageFormat("{0}: {1}");
    System.out.print("\n");
    if (vault.getSecretNames().size() == 0) {
        System.out.println("No secrets defined.");
    }//  w  ww . j ava2s  .  com
    for (String name : vault.getSecretNames()) {
        System.out.println(format.format("{0}: {1}", name, vault.getSecret(name)));
    }
    System.out.print("\n");
}

From source file:com.asakusafw.runtime.compatibility.CoreCompatibility.java

/**
 * Verifies the running core framework version.
 *//*  w ww  .  j a  v  a 2 s .  co m*/
public static void verifyFrameworkVersion() {
    FrameworkVersion running = FrameworkVersion.get();
    if (TARGET.isCompatibleTo(running) == false) {
        throw new IllegalStateException(MessageFormat.format(
                "Inconsistent environment version: expected-version={0}, installed-version={1}", TARGET,
                running));
    }
}

From source file:com.asakusafw.runtime.stage.StageUtil.java

/**
 * Returns whether the current job is on the local mode or not.
 * @param context the current context//from ww w. ja  v  a 2 s  .com
 * @return {@code true} if the target job is running on the local mode, otherwise {@code false}
 * @throws IllegalArgumentException if some parameters were {@code null}
 * @since 0.6.2
 */
public static boolean isLocalMode(JobContext context) {
    if (context == null) {
        throw new IllegalArgumentException("context must not be null"); //$NON-NLS-1$
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(MessageFormat.format("{0}={1}", //$NON-NLS-1$
                MRConfig.FRAMEWORK_NAME, context.getConfiguration().get(MRConfig.FRAMEWORK_NAME)));
    }
    String name = context.getConfiguration().get(MRConfig.FRAMEWORK_NAME, MRConfig.LOCAL_FRAMEWORK_NAME);
    return name.equals(MRConfig.LOCAL_FRAMEWORK_NAME);
}

From source file:com.microsoft.tfs.core.clients.registration.ServerMap.java

public static ServerMap load(final PersistenceStore cacheStore) {
    Check.notNull(cacheStore, "cacheStore"); //$NON-NLS-1$

    final PersistenceStore mapStore = cacheStore.getChildStore(CHILD_STORE_NAME);

    try {//from w w  w  . j  a v a2s  .  c om
        if (mapStore.containsItem(OBJECT_NAME) == false) {
            return new ServerMap();
        }

        final ServerMap map = (ServerMap) mapStore.retrieveItem(OBJECT_NAME, LockMode.WAIT_FOREVER, null,
                new ServerMapSerializer());

        if (map == null) {
            log.warn(MessageFormat.format("unable to load server map from {0}:{1} (interrupted)", //$NON-NLS-1$
                    mapStore.toString(), OBJECT_NAME));

            return new ServerMap();
        }

        return map;
    } catch (final Exception e) {
        log.warn(
                MessageFormat.format("unable to load server map from {0}:{1}", mapStore.toString(), //$NON-NLS-1$
                        OBJECT_NAME), e);

        return new ServerMap();
    }
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.teamexplorer.actions.ViewBuildsForDefinitionAction.java

@Override
public void doRun(final IAction action) {
    log.info(MessageFormat.format("Opening build definitions for {0} for project {1}", //$NON-NLS-1$
            selectedDefinition.getName(), selectedDefinition.getTeamProject()));

    BuildHelpers.viewTodaysBuildsForDefinition(selectedDefinition);
}

From source file:de.unioninvestment.eai.portal.portlet.crud.scripting.category.StringCategory.java

/**
 * Sollte der {@code s} lnger {@code MAX_LENGTH} sein, werden nur die
 * ersten {@code MAX_LENGTH} Zeichen zurck geliefert.
 * // w  ww .  j a v  a 2s.  c  o m
 * @param shortenedMessageFormat
 * @param maxLength
 */
public static String shorten(String s, int maxLength, String shortenedMessageFormat) {
    if (s.length() > maxLength) {
        return MessageFormat.format(shortenedMessageFormat, s.substring(0, maxLength), s.length());
    } else {
        return s;
    }
}