Java Code Examples for com.ibm.icu.text.MessageFormat#format()

The following examples show how to use com.ibm.icu.text.MessageFormat#format() . 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: ValidationContextImpl.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void add ( final Severity severity, Object[] data, final String message, final Object... arguments )
{
    if ( data == null )
    {
        data = new Object[] { this.target };
    }

    String formattedMessage;

    if ( arguments == null || arguments.length <= 0 )
    {
        formattedMessage = message;
    }
    else
    {
        formattedMessage = MessageFormat.format ( message, arguments );
    }

    final int severityCode = severity == null ? Diagnostic.OK : severity.getSeverityCode ();
    this.result.add ( new BasicDiagnostic ( severityCode, this.source, 0, formattedMessage, data ) );
}
 
Example 2
Source File: SlackClient.java    From mojito with Apache License 2.0 6 votes vote down vote up
User lookupUserByEmail(String email) throws SlackClientException {

        MultiValueMap<String, Object> payload = getBasePayloadMapWithAuthToken();
        payload.add("email", email);

        HttpEntity<MultiValueMap<String, Object>> httpEntity = getHttpEntityForPayload(payload);
        UserResponse userResponse = restTemplate.postForObject(getUrl(API_USER_LOOKUP_BY_EMAIL), httpEntity, UserResponse.class);

        if (!userResponse.getOk()) {
            String msg = MessageFormat.format("Cannot lookup user by email: {0} ({1})", email, userResponse.getError());
            logger.debug(msg);
            throw new SlackClientException(msg);
        }

        return userResponse.getUser();
    }
 
Example 3
Source File: TabbedPropertyRegistry.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Appends the given section to a tab from the list.
 */
protected void appendToTabDescriptor(ISectionDescriptor section,
		List aTabDescriptors) {
	for (Iterator i = aTabDescriptors.iterator(); i.hasNext();) {
		TabDescriptor tab = (TabDescriptor) i.next();
		if (tab.append(section)) {
			return;
		}
	}
	// could not append the section to any of the existing tabs - log error
	String message = MessageFormat.format(NO_TAB_ERROR, section.getId(), section.getTargetTab());
	Bundle bundle = FrameworkUtil.getBundle(TabbedPropertyRegistry.class);
	IStatus status = new Status(IStatus.ERROR, bundle.getSymbolicName(),
			TabbedPropertyViewStatusCodes.NO_TAB_ERROR, message, null);
	Platform.getLog(bundle).log(status);
}
 
Example 4
Source File: BindingFactory.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Add the binding.
 *
 * @param binding the binding to add.
 * @param override indicates if the binding could override an existing element.
 */
public void add(Binding binding, boolean override) {
	final Set<Binding> moduleBindings = this.module.get().getBindings();
	final Binding otherBinding = findBinding(moduleBindings, binding);
	if (!override) {
		if (otherBinding != null) {
			throw new IllegalArgumentException(MessageFormat.format(
					"Forbidden override of {0} by {1}.", //$NON-NLS-1$
					otherBinding, binding));
		}
	} else if (otherBinding != null) {
		this.removableBindings.add(otherBinding);
	}
	if (!this.bindings.add(binding)) {
		throw new IllegalArgumentException(
				MessageFormat.format("Duplicate binding for {0} in {1}", binding.getKey(), this.name)); //$NON-NLS-1$
	}
}
 
Example 5
Source File: PollableAspectParameters.java    From mojito with Apache License 2.0 6 votes vote down vote up
/**
 * Init this instance with information contained in the {@link Pollable}
 * annotation.
 */
private void initFromAnnotation() {
    MethodSignature ms = (MethodSignature) pjp.getSignature();
    Method m = ms.getMethod();
    annotation = m.getAnnotation(Pollable.class);

    if (!annotation.name().isEmpty()) {
        name = annotation.name();
    } else {
        name = pjp.getSignature().getName();
    }

    if (!annotation.message().isEmpty()) {
        message = MessageFormat.format(annotation.message(), getMessageParams());
    }

    expectedSubTaskNumber = annotation.expectedSubTaskNumber();
    async = annotation.async();
    timeout = annotation.timeout();
}
 
Example 6
Source File: BoxSDKAppUserService.java    From mojito with Apache License 2.0 6 votes vote down vote up
/**
 * Create a Box App User
 *
 * @return
 * @throws BoxSDKServiceException
 */
public BoxUser.Info createAppUser(String clientId, String clientSecret, String publicKeyId,
            String privateKey, String privateKeyPassword, String enterpriseId) throws BoxSDKServiceException {

    try {
        logger.debug("Creating Box App User: {}", MOJITO_APP_USER_NAME);
        JWTEncryptionPreferences jwtEncryptionPreferences = boxSDKJWTProvider.getJWTEncryptionPreferences(publicKeyId, privateKey, privateKeyPassword);
        BoxDeveloperEditionAPIConnection appEnterpriseConnection = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(
                enterpriseId,
                clientId,
                clientSecret,
                jwtEncryptionPreferences,
                new InMemoryLRUAccessTokenCache(5));

        CreateUserParams createUserParams = new CreateUserParams();
        createUserParams.setSpaceAmount(UNLIMITED_SPACE);

        return BoxUser.createAppUser(appEnterpriseConnection, MOJITO_APP_USER_NAME, createUserParams);
    } catch (BoxAPIException e) {
        String msg = MessageFormat.format("Couldn't create App User: {0}", e.getResponse());
        logger.error(msg);
        throw new BoxSDKServiceException(msg, e);
    }
}
 
Example 7
Source File: TabDescriptor.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Handle the tab error when an issue is found loading from the
 * configuration element.
 *
 * @param configurationElement
 *            the configuration element
 * @param exception
 *            an optional CoreException
 */
private void handleTabError(IConfigurationElement configurationElement,
		CoreException exception) {
	String pluginId = configurationElement.getDeclaringExtension()
			.getContributor().getName();
	String message = MessageFormat.format(TAB_ERROR, pluginId);
	IStatus status = new Status(IStatus.ERROR, pluginId,
			TabbedPropertyViewStatusCodes.TAB_ERROR, message, exception);
	Bundle bundle = FrameworkUtil.getBundle(TabDescriptor.class);
	Platform.getLog(bundle).log(status);
}
 
Example 8
Source File: InjectionFragment2.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Change the comment for the injection fragment.
 *
 * @param comment the comment for the fragment.
 */
public void setComment(String comment) {
	this.comment = comment;
	if (!Strings.isEmpty(comment)) {
		this.name = MessageFormat.format("{0} [{1}]", getClass().getName(), comment); //$NON-NLS-1$
	} else {
		this.name = getClass().getName();
	}
}
 
Example 9
Source File: ExtractionDiffService.java    From mojito with Apache License 2.0 5 votes vote down vote up
void checkExtractionDirectoryExists(String extractionName, ExtractionsPaths extractionsPaths) throws MissingExtractionDirectoryExcpetion {
    Path extractionPath = extractionsPaths.extractionPath(extractionName);

    if (!extractionPath.toFile().exists()) {
        String msg = MessageFormat.format("There is no directory for extraction: {0}, can't compare", extractionName);
        throw new MissingExtractionDirectoryExcpetion(msg);
    }
}
 
Example 10
Source File: ReportContextImpl.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public String getMessage( String key, Object[] params )
{
	String msg = context.getDesign( ).getMessage( key );
	if ( msg == null )
		return "";
	return MessageFormat.format( msg, params );
}
 
Example 11
Source File: TabbedPropertyRegistry.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Handle the tab error when an issue is found loading from the
 * configuration element.
 *
 * @param configurationElement
 *            the configuration element
 */
private void handleTabError(IConfigurationElement configurationElement,
		String category) {
	String pluginId = configurationElement.getDeclaringExtension()
			.getContributor().getName();
	String message = MessageFormat.format(TAB_ERROR, pluginId, category );
	IStatus status = new Status(IStatus.ERROR, pluginId,
			TabbedPropertyViewStatusCodes.TAB_ERROR, message, null);
	Bundle bundle = FrameworkUtil.getBundle(TabbedPropertyRegistry.class);
	Platform.getLog(bundle).log(status);
}
 
Example 12
Source File: TMService.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a current {@link TMTextUnitVariant} in a {@link TMTextUnit} for a
 * locale other than the default locale.
 * <p/>
 * Also checks for an existing {@link TMTextUnitCurrentVariant} and if it
 * references a {@link TMTextUnitVariant} that has same content, the
 * {@link TMTextUnitVariant} is returned and no entities are created.
 *
 * @param tmTextUnitId the text unit that will contains the translation
 * @param localeId locale id of the translation (default locale not
 * accepted)
 * @param content the translation content
 * @param comment the translation comment, can be {@code null}
 * @param status the translation status
 * @param includedInLocalizedFile indicate if the translation should be
 * included or not in the localized files
 * @param createdDate to specify a creation date (can be used to re-import
 * old TM), can be {@code null}
 * @return the result that contains the {@link TMTextUnitCurrentVariant} and
 * indicates if it was updated or not. The {@link TMTextUnitCurrentVariant}
 * holds the created {@link TMTextUnitVariant} or an existing one with same
 * content
 * @throws DataIntegrityViolationException If tmTextUnitId or localeId are
 * invalid
 */
public AddTMTextUnitCurrentVariantResult addTMTextUnitCurrentVariantWithResult(
        Long tmTextUnitId,
        Long localeId,
        String content,
        String comment,
        TMTextUnitVariant.Status status,
        boolean includedInLocalizedFile,
        DateTime createdDate) {

    logger.debug("Check if there is a current TMTextUnitVariant");
    TMTextUnitCurrentVariant currentTmTextUnitCurrentVariant = tmTextUnitCurrentVariantRepository.findByLocale_IdAndTmTextUnit_Id(localeId, tmTextUnitId);

    TMTextUnit tmTextUnit = tmTextUnitRepository.findOne(tmTextUnitId);

    if (tmTextUnit == null) {
        String msg = MessageFormat.format("Unable to find the TMTextUnit with ID: {0}. The TMTextUnitVariant and "
                + "TMTextUnitCurrentVariant will not be created.", tmTextUnitId);
        throw new RuntimeException(msg);
    }

    User createdBy = auditorAwareImpl.getCurrentAuditor();
    return addTMTextUnitCurrentVariantWithResult(currentTmTextUnitCurrentVariant,
            tmTextUnit.getTm().getId(),
            tmTextUnitId,
            localeId,
            content,
            comment,
            status,
            includedInLocalizedFile,
            createdDate,
            createdBy);
}
 
Example 13
Source File: ICUFormat.java    From tutorials with MIT License 4 votes vote down vote up
public static String getLabel(Locale locale, Object[] data) {
    ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
    String format = bundle.getString("label-icu");
    MessageFormat formatter = new MessageFormat(format, locale);
    return formatter.format(data);
}
 
Example 14
Source File: QuartzPollableTaskScheduler.java    From mojito with Apache License 2.0 4 votes vote down vote up
/**
 * Schedules a job.
 *
 * @param clazz                 class of the job to be executed
 * @param input                 the input of the job (will get serialized inline the quartz data or in the blobstorage, see inlineInput)
 * @param parentId              optional parentId for the pollable task id associated with the job
 * @param message               set on the pollable task
 * @param expectedSubTaskNumber set on the pollable task
 * @param triggerStartDate      date at which the job should be started
 * @param uniqueId              optional id used to generate the job keyname. If not provided the pollable task id is used.
 *                              Pollable id keeps changing, unique id can be used for recuring jobs (eg. update stats of repositry xyz)
 * @param inlineInput           to inline the input in quartz data or save it in the blobstorage
 * @param <I>
 * @param <O>
 * @return
 */
public <I, O> PollableFuture<O> scheduleJob(QuartzJobInfo<I, O> quartzJobInfo) {

    String pollableTaskName = getPollableTaskName(quartzJobInfo.getClazz());

    logger.debug("Create currentPollableTask with name: {}", pollableTaskName);
    PollableTask pollableTask = pollableTaskService.createPollableTask(
            quartzJobInfo.getParentId(),
            pollableTaskName,
            quartzJobInfo.getMessage(),
            quartzJobInfo.getExpectedSubTaskNumber(),
            quartzJobInfo.getTimeout());

    String uniqueId = quartzJobInfo.getUniqueId() != null ?
            quartzJobInfo.getUniqueId() : pollableTask.getId().toString();

    String keyName = getKeyName(quartzJobInfo.getClazz(), uniqueId);

    try {
        TriggerKey triggerKey = new TriggerKey(keyName, DYNAMIC_GROUP_NAME);
        JobKey jobKey = new JobKey(keyName, DYNAMIC_GROUP_NAME);

        JobDetail jobDetail = scheduler.getJobDetail(jobKey);

        if (jobDetail == null) {
            logger.debug("Job doesn't exist, create for key: {}", keyName);
            jobDetail = JobBuilder.newJob().ofType(quartzJobInfo.getClazz())
                    .withIdentity(jobKey)
                    .build();
        }

        logger.debug("Schedule a job for key: {}", keyName);

        TriggerBuilder<Trigger> triggerTriggerBuilder = TriggerBuilder.newTrigger()
                .startAt(quartzJobInfo.getTriggerStartDate())
                .forJob(jobDetail)
                .usingJobData(QuartzPollableJob.POLLABLE_TASK_ID, pollableTask.getId().toString())
                .withIdentity(triggerKey);

        if (quartzJobInfo.isInlineInput()) {
            logger.debug("This job input is inlined into the quartz job");
            triggerTriggerBuilder.usingJobData(QuartzPollableJob.INPUT, objectMapper.writeValueAsStringUnchecked(quartzJobInfo.getInput()));
        } else {
            logger.debug("The input data is saved into the blob storage");
            pollableTaskBlobStorage.saveInput(pollableTask.getId(), quartzJobInfo.getInput());
        }

        Trigger trigger = triggerTriggerBuilder.build();

        if (!scheduler.checkExists(triggerKey)) {
            logger.debug("Schedule QuartzPollableJob with key: {}", keyName);
            scheduler.scheduleJob(jobDetail, trigger);
        } else {
            logger.debug("Job already scheduled for key: {}, reschedule", keyName);
            scheduler.rescheduleJob(triggerKey, trigger);
        }
    } catch (SchedulerException se) {
        String msg = MessageFormat.format("Couldn't schedule QuartzPollableJob with key: {0}", keyName);
        logger.error(msg, se);
        throw new RuntimeException(msg, se);
    }

    Class<O> jobOutputType = getJobOutputType(quartzJobInfo);
    return new QuartzPollableFutureTask<O>(pollableTask, jobOutputType);
}
 
Example 15
Source File: ICUFormat.java    From tutorials with MIT License 4 votes vote down vote up
public static String getLabel(Locale locale, Object[] data) {
    ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
    String format = bundle.getString("label-icu");
    MessageFormat formatter = new MessageFormat(format, locale);
    return formatter.format(data);
}
 
Example 16
Source File: TabbedPropertyRegistry.java    From bonita-studio with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Handle the error when an issue is found loading from the configuration
 * element.
 *
 * @param id
 *            the configuration id.
 * @param exception
 *            an optional CoreException
 */
private void handleConfigurationError(String id, CoreException exception) {
	String message = MessageFormat.format(CONTRIBUTOR_ERROR, id);
	Bundle bundle = FrameworkUtil.getBundle(TabbedPropertyRegistry.class);
	IStatus status = new Status(IStatus.ERROR, bundle.getSymbolicName(),
			TabbedPropertyViewStatusCodes.CONTRIBUTOR_ERROR, message,
			exception);
	Platform.getLog(bundle).log(status);
}
 
Example 17
Source File: ResourceHandle.java    From birt with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Get a message that has placeholders. An assertion will be raised if the
 * message key does not exist in the resource bundle.
 * 
 * @param key
 *            the message key
 * @param arguments
 *            the set of arguments to be plugged into the message
 * @return the localized message for that key and the locale set in the
 *         constructor. Returns the key itself if the message was not found.
 * @see ResourceBundle#getString( String )
 * @see MessageFormat#format( String, Object[] )
 */

public String getMessage( String key, Object[] arguments )
{
	String message = getMessage( key );
	return MessageFormat.format( message, arguments );
}
 
Example 18
Source File: ResourceHandle.java    From birt with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Get a message that has placeholders. An assertion will be raised if the
 * message key does not exist in the resource bundle.
 * 
 * @param key
 *            the message key
 * @param arguments
 *            the set of arguments to be plugged into the message
 * @return the localized message for that key and the locale set in the
 *         constructor. Returns the key itself if the message was not found.
 * @see ResourceBundle#getString(String )
 * @see MessageFormat#format(String, Object[] )
 */

public String getMessage( String key, Object[] arguments )
{
	String message = getMessage( key );
	return MessageFormat.format( message, arguments );
}
 
Example 19
Source File: BirtResources.java    From birt with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns the string from the plugin's resource bundle, or 'key' if not
 * found.
 * 
 * @param key
 *            resource key
 * @param arguments
 *            list of arguments
 * @return locale string
 * @deprecated the getMessage( String key ) will returnt he formated
 *             message.
 */
public static String getFormattedString( String key, Object[] arguments )
{
	return MessageFormat.format( getString( key ), arguments );
}
 
Example 20
Source File: FoldingMessages.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns the formatted resource string associated with the given key in the resource bundle.
 * <code>MessageFormat</code> is used to format the message. If there isn't  any value
 * under the given key, the key is returned.
 *
 * @param key the resource key
 * @param args the message arguments
 * @return the string
 */
public static String getFormattedString(String key, Object[] args) {
	return MessageFormat.format(getString(key), args);
}