com.sap.cds.framework.spring.feature.SpringLocalizedMessageProvider Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of cds-framework-spring-boot Show documentation
Show all versions of cds-framework-spring-boot Show documentation
Integration into the Spring Boot framework for CDS Services Java
/*********************************************************************
* (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";
}
}