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

com.liferay.adaptive.media.image.internal.util.AMImageSerializerImpl Maven / Gradle / Ivy

/**
 * SPDX-FileCopyrightText: (c) 2000 Liferay, Inc. https://liferay.com
 * SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06
 */

package com.liferay.adaptive.media.image.internal.util;

import com.liferay.adaptive.media.AMAttribute;
import com.liferay.adaptive.media.AdaptiveMedia;
import com.liferay.adaptive.media.exception.AMRuntimeException;
import com.liferay.adaptive.media.image.internal.configuration.AMImageAttributeMapping;
import com.liferay.adaptive.media.image.internal.processor.AMImage;
import com.liferay.adaptive.media.image.processor.AMImageAttribute;
import com.liferay.adaptive.media.image.processor.AMImageProcessor;
import com.liferay.adaptive.media.image.util.AMImageSerializer;
import com.liferay.portal.kernel.json.JSONException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;

import java.io.InputStream;

import java.net.URI;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;

import org.osgi.service.component.annotations.Component;

/**
 * @author Adolfo Pérez
 */
@Component(immediate = true, service = AMImageSerializer.class)
public class AMImageSerializerImpl implements AMImageSerializer {

	@Override
	public AdaptiveMedia deserialize(
		String s, Supplier inputStreamSupplier) {

		try {
			JSONObject jsonObject = JSONFactoryUtil.createJSONObject(s);

			Map properties = new HashMap<>();

			JSONObject attributesJSONObject = jsonObject.getJSONObject(
				"attributes");

			Map> allowedAMAttributes =
				AMImageAttribute.getAllowedAMAttributes();

			allowedAMAttributes.forEach(
				(name, amAttribute) -> {
					if (attributesJSONObject.has(name)) {
						properties.put(
							name, attributesJSONObject.getString(name));
					}
				});

			String uri = jsonObject.getString("uri");

			return new AMImage(
				inputStreamSupplier,
				AMImageAttributeMapping.fromProperties(properties),
				URI.create(uri));
		}
		catch (JSONException jsone) {
			throw new AMRuntimeException(jsone);
		}
	}

	@Override
	public String serialize(AdaptiveMedia adaptiveMedia) {
		JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

		JSONObject attributesJSONObject = JSONFactoryUtil.createJSONObject();

		Map> allowedAMAttributes =
			AMImageAttribute.getAllowedAMAttributes();

		allowedAMAttributes.forEach(
			(name, amAttribute) -> {
				Optional valueOptional = adaptiveMedia.getValueOptional(
					(AMAttribute)amAttribute);

				valueOptional.ifPresent(
					value -> attributesJSONObject.put(
						name, String.valueOf(value)));
			});

		jsonObject.put("attributes", attributesJSONObject);

		jsonObject.put("uri", adaptiveMedia.getURI());

		return jsonObject.toString();
	}

}