All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sap.cds.framework.spring.feature.SpringLocalizedMessageProvider Maven / Gradle / Ivy

There is a newer version: 3.2.0
Show newest version
/*********************************************************************
 * (C) 2019 SAP SE or an SAP affiliate company. All rights reserved. *
 *********************************************************************/
package com.sap.cds.framework.spring.feature;

import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.MessageFormatter;

import com.sap.cds.feature.localization.LocalizedMessageProvider;
import com.sap.cds.framework.spring.utils.SpringObjects;

public class SpringLocalizedMessageProvider implements LocalizedMessageProvider {

	private final static Logger logger = LoggerFactory.getLogger(SpringLocalizedMessageProvider.class);

	@Override
	public String getMessage(String code, Object[] args, Locale locale) {

		try {
			String message = SpringObjects.getMessageSource().getMessage(code, args, null, locale);
			if (message != null) { // NOSONAR
				return message;
			} else {
				return MessageFormatter.arrayFormat(code, args).getMessage();
			}

		} catch (Exception e) {  // NOSONAR
			// be tolerant - we don't want to break the request due to wrong message resolution
			logger.warn("Invalid message format '{}' or incompatible arguments {}", code, toStringSafely(args), e);
			return code;
		}

	}

	private static String toStringSafely(Object[] args) {
		if (args != null) {
			StringBuffer sb = new StringBuffer();
			for (Object arg : args) {
				sb.append('<');
				try {
					sb.append(arg.toString());
				} catch(Exception e) { // NOSONAR
					sb.append(e.getMessage());
				}
				sb.append('>');
			}
			return sb.toString();
		}
		return "";
	}

	@Override
	public boolean isActiveFeature() {
		return true;
	}

	@Override
	public String getFeatureName() {
		return "Spring Localized Message Provider";
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy