Java Code Examples for java.text.MessageFormat#setFormat()

The following examples show how to use java.text.MessageFormat#setFormat() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Bug4185816Test.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void writeFormatToFile(final String name) {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream(name));

        MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
        double[] filelimits = {0,1,2};
        String[] filepart = {"no files","one file","{0,number} files"};
        ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
        fmt.setFormat(1,fileform); // NOT zero, see below

        out.writeObject(fmt);
        out.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 2
Source File: Bug4185816Test.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void writeFormatToFile(final String name) {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream(name));

        MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
        double[] filelimits = {0,1,2};
        String[] filepart = {"no files","one file","{0,number} files"};
        ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
        fmt.setFormat(1,fileform); // NOT zero, see below

        out.writeObject(fmt);
        out.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 3
Source File: Bug4185816Test.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static void writeFormatToFile(final String name) {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream(name));

        MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
        double[] filelimits = {0,1,2};
        String[] filepart = {"no files","one file","{0,number} files"};
        ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
        fmt.setFormat(1,fileform); // NOT zero, see below

        out.writeObject(fmt);
        out.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 4
Source File: Bug4185816Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void writeFormatToFile(final String name) {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream(name));

        MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
        double[] filelimits = {0,1,2};
        String[] filepart = {"no files","one file","{0,number} files"};
        ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
        fmt.setFormat(1,fileform); // NOT zero, see below

        out.writeObject(fmt);
        out.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 5
Source File: MCRCommand.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
public MCRCommand(Method cmd) {
    className = cmd.getDeclaringClass().getName();
    methodName = cmd.getName();
    parameterTypes = cmd.getParameterTypes();
    org.mycore.frontend.cli.annotation.MCRCommand cmdAnnotation = cmd
        .getAnnotation(org.mycore.frontend.cli.annotation.MCRCommand.class);
    help = cmdAnnotation.help();
    messageFormat = new MessageFormat(cmdAnnotation.syntax(), Locale.ROOT);
    setMethod(cmd);

    for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> paramtype = parameterTypes[i];
        if (ClassUtils.isAssignable(paramtype, Integer.class, true)
            || ClassUtils.isAssignable(paramtype, Long.class, true)) {
            messageFormat.setFormat(i, NumberFormat.getIntegerInstance(Locale.ROOT));
        } else if (!String.class.isAssignableFrom(paramtype)) {
            unsupportedArgException(className + "." + methodName, paramtype.getName());
        }
    }

    int pos = cmdAnnotation.syntax().indexOf("{");
    suffix = pos == -1 ? cmdAnnotation.syntax() : cmdAnnotation.syntax().substring(0, pos);
}
 
Example 6
Source File: Bug4185816Test.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void writeFormatToFile(final String name) {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream(name));

        MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
        double[] filelimits = {0,1,2};
        String[] filepart = {"no files","one file","{0,number} files"};
        ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
        fmt.setFormat(1,fileform); // NOT zero, see below

        out.writeObject(fmt);
        out.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 7
Source File: LocalizedMessage.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
protected String formatWithTimeZone(
        String template,
        Object[] arguments, 
        Locale locale,
        TimeZone timezone) 
{
    MessageFormat mf = new MessageFormat(" ");
    mf.setLocale(locale);
    mf.applyPattern(template);
    if (!timezone.equals(TimeZone.getDefault())) 
    {
        Format[] formats = mf.getFormats();
        for (int i = 0; i < formats.length; i++) 
        {
            if (formats[i] instanceof DateFormat) 
            {
                DateFormat temp = (DateFormat) formats[i];
                temp.setTimeZone(timezone);
                mf.setFormat(i,temp);
            }
        }
    }
    return mf.format(arguments);
}
 
Example 8
Source File: LocalizedMessage.java    From ripple-lib-java with ISC License 6 votes vote down vote up
protected String formatWithTimeZone(
        String template,
        Object[] arguments, 
        Locale locale,
        TimeZone timezone) 
{
    MessageFormat mf = new MessageFormat(" ");
    mf.setLocale(locale);
    mf.applyPattern(template);
    if (!timezone.equals(TimeZone.getDefault())) 
    {
        Format[] formats = mf.getFormats();
        for (int i = 0; i < formats.length; i++) 
        {
            if (formats[i] instanceof DateFormat) 
            {
                DateFormat temp = (DateFormat) formats[i];
                temp.setTimeZone(timezone);
                mf.setFormat(i,temp);
            }
        }
    }
    return mf.format(arguments);
}
 
Example 9
Source File: MessageFormatDemo.java    From geekbang-lessons with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        int planet = 7;
        String event = "a disturbance in the Force";

        String messageFormatPattern = "At {1,time,long} on {1,date,full}, there was {2} on planet {0,number,integer}.";
        MessageFormat messageFormat = new MessageFormat(messageFormatPattern);
        String result = messageFormat.format(new Object[]{planet, new Date(), event});
        System.out.println(result);

        // 重置 MessageFormatPattern
        // applyPattern
        messageFormatPattern = "This is a text : {0}, {1}, {2}";
        messageFormat.applyPattern(messageFormatPattern);
        result = messageFormat.format(new Object[]{"Hello,World", "666"});
        System.out.println(result);

        // 重置 Locale
        messageFormat.setLocale(Locale.ENGLISH);
        messageFormatPattern = "At {1,time,long} on {1,date,full}, there was {2} on planet {0,number,integer}.";
        messageFormat.applyPattern(messageFormatPattern);
        result = messageFormat.format(new Object[]{planet, new Date(), event});
        System.out.println(result);

        // 重置 Format
        // 根据参数索引来设置 Pattern
        messageFormat.setFormat(1,new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"));
        result = messageFormat.format(new Object[]{planet, new Date(), event});
        System.out.println(result);
    }
 
Example 10
Source File: MavenArtifactResolver.java    From spring-cloud-deployer with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve an artifact and return its location in the local repository. Aether performs the normal
 * Maven resolution process ensuring that the latest update is cached to the local repository.
 * In addition, if the {@link MavenProperties#resolvePom} flag is <code>true</code>,
 * the POM is also resolved and cached.
 * @param resource the {@link MavenResource} representing the artifact
 * @return a {@link FileSystemResource} representing the resolved artifact in the local repository
 * @throws IllegalStateException if the artifact does not exist or the resolution fails
 */
Resource resolve(MavenResource resource) {
	Assert.notNull(resource, "MavenResource must not be null");
	validateCoordinates(resource);
	RepositorySystemSession session = newRepositorySystemSession(this.repositorySystem,
			this.properties.getLocalRepository());
	ArtifactResult resolvedArtifact;
	try {
		List<ArtifactRequest> artifactRequests = new ArrayList<>(2);
		if (properties.isResolvePom()) {
			artifactRequests.add(new ArtifactRequest(toPomArtifact(resource),
					this.remoteRepositories,
					JavaScopes.RUNTIME));
		}
		artifactRequests.add(new ArtifactRequest(toJarArtifact(resource),
				this.remoteRepositories,
				JavaScopes.RUNTIME));

		List<ArtifactResult> results = this.repositorySystem.resolveArtifacts(session, artifactRequests);
		resolvedArtifact = results.get(results.size() - 1);
	}
	catch (ArtifactResolutionException e) {

		ChoiceFormat pluralizer = new ChoiceFormat(
				new double[] { 0d, 1d, ChoiceFormat.nextDouble(1d) },
				new String[] { "repositories: ", "repository: ", "repositories: " });
		MessageFormat messageFormat = new MessageFormat(
				"Failed to resolve MavenResource: {0}. Configured remote {1}: {2}");
		messageFormat.setFormat(1, pluralizer);
		String repos = properties.getRemoteRepositories().isEmpty()
				? "none"
				: StringUtils.collectionToDelimitedString(properties.getRemoteRepositories().keySet(), ",", "[", "]");
		throw new IllegalStateException(
				messageFormat.format(new Object[] { resource, properties.getRemoteRepositories().size(), repos }),
				e);
	}
	return toResource(resolvedArtifact);
}
 
Example 11
Source File: DatePicker.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void setLinkDay(Date linkDay) {
    MessageFormat todayFormat = new MessageFormat(AppBeans.get(Messages.class).getMessage("com.haulmont.cuba.desktop", "DatePicker.linkFormat"));
    todayFormat.setFormat(0, new SimpleDateFormat(Datatypes.getFormatStrings(AppBeans.get(UserSessionSource.class).getLocale()).getDateFormat()));
    setLinkFormat(todayFormat);
    super.setLinkDay(linkDay);
}
 
Example 12
Source File: MessageFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_equalsLjava_lang_Object() {
    MessageFormat format1 = new MessageFormat("{0}");
    MessageFormat format2 = new MessageFormat("{1}");
    assertTrue("Should not be equal", !format1.equals(format2));
    format2.applyPattern("{0}");
    assertTrue("Should be equal", format1.equals(format2));
    SimpleDateFormat date = (SimpleDateFormat) DateFormat.getTimeInstance();
    format1.setFormat(0, DateFormat.getTimeInstance());
    format2.setFormat(0, new SimpleDateFormat(date.toPattern()));
    assertTrue("Should be equal2", format1.equals(format2));
}
 
Example 13
Source File: MCRCommand.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates a new MCRCommand.
 * 
 * @param format
 *            the command syntax, e.g. "save document {0} to directory {1}"
 * @param methodSignature
 *            the method to invoke, e.g. "miless.commandline.DocumentCommands.saveDoc int String"
 * @param helpText
 *            the helpt text for this command
 */
public MCRCommand(String format, String methodSignature, String helpText) {
    StringTokenizer st = new StringTokenizer(methodSignature, " ");

    String token = st.nextToken();
    int point = token.lastIndexOf(".");

    className = token.substring(0, point);
    methodName = token.substring(point + 1);
    int numParameters = st.countTokens();
    parameterTypes = new Class<?>[numParameters];
    messageFormat = new MessageFormat(format, Locale.ROOT);

    for (int i = 0; i < numParameters; i++) {
        token = st.nextToken();

        Format f = null;
        switch (token) {
            case "int":
                parameterTypes[i] = Integer.TYPE;
                f = NumberFormat.getIntegerInstance(Locale.ROOT);
                break;
            case "long":
                parameterTypes[i] = Long.TYPE;
                f = NumberFormat.getIntegerInstance(Locale.ROOT);
                break;
            case "String":
                parameterTypes[i] = String.class;
                break;
            default:
                unsupportedArgException(methodSignature, token);
        }
        messageFormat.setFormat(i, f);
    }

    int pos = format.indexOf("{");
    suffix = pos == -1 ? format : format.substring(0, pos);

    if (helpText != null) {
        help = helpText;
    } else {
        help = "No help text available for this command";
    }
}