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

com.sap.cds.adapter.odata.v4.metadata.provider.DefaultEdmxI18nProvider Maven / Gradle / Ivy

There is a newer version: 3.2.0
Show newest version
/**************************************************************************
 * (C) 2019-2024 SAP SE or an SAP affiliate company. All rights reserved. *
 **************************************************************************/
package com.sap.cds.adapter.odata.v4.metadata.provider;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;

import com.google.common.hash.Hashing;
import com.google.common.hash.HashingInputStream;
import com.sap.cds.adapter.edmx.EdmxI18nProvider;
import com.sap.cds.impl.localized.LocaleUtils;
import com.sap.cds.impl.parser.JsonParser;
import com.sap.cds.services.utils.CdsErrorStatuses;
import com.sap.cds.services.utils.ErrorStatusException;

class DefaultEdmxI18nProvider implements EdmxI18nProvider {

	private static final String PATH = "edmx/_i18n/i18n.json";

	private final Map> i18n;
	private final String eTag;

	@SuppressWarnings("unchecked")
	public static DefaultEdmxI18nProvider create() {
		try (InputStream in = DefaultEdmxI18nProvider.class.getClassLoader().getResourceAsStream(PATH)) {
			if (in != null) {
				HashingInputStream hasher = new HashingInputStream(Hashing.sha256(), in);
				var i18nResources = (Map>) JsonParser.map(new InputStreamReader(hasher, StandardCharsets.UTF_8));
				var eTag = hasher.hash().toString();
				return new DefaultEdmxI18nProvider(i18nResources, eTag);
			} else {
				return new DefaultEdmxI18nProvider(Collections.emptyMap(), null);
			}
		} catch (IOException e) {
			throw new ErrorStatusException(CdsErrorStatuses.INVALID_I18N_RESOURCES_FORMAT, PATH, e);
		}
	}

	private DefaultEdmxI18nProvider(Map> i18n, String eTag) {
		this.i18n = i18n;
		this.eTag = eTag;
	}

	@Override
	public String getETag(Locale locale) {
		return eTag;
	}

	String getETag(String locale) {
		return eTag;
	}

	@Override
	public Map getTexts(Locale locale) {
		// empty string represents the default language
		return getTexts(locale == null ? "" : LocaleUtils.getLocaleString(locale));
	}

	Map getTexts(String locale) {
		return i18n.getOrDefault(locale, i18n.getOrDefault("", Collections.emptyMap()));
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy