blob: 6d82fc62ba6b989bf526c94e8c71de21a378be67 [file] [log] [blame]
/**
*
* Copyright (c) 2011, 2016 - Loetz GmbH&Co.KG (69115 Heidelberg, Germany)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Christophe Loetz (Loetz GmbH&Co.KG) - initial implementation
*
*/
package org.eclipse.osbp.ecview.extension.presentation.converter;
import java.util.Locale;
import org.eclipse.osbp.ecview.core.common.services.IServiceRegistry;
import org.eclipse.osbp.runtime.common.i18n.I18nUtil;
import org.eclipse.osbp.runtime.web.vaadin.common.resource.IResourceProvider;
import com.vaadin.data.util.converter.Converter;
import com.vaadin.server.Resource;
import org.eclipse.osbp.ecview.extension.model.converter.CxNumericToResourceConfig;
import org.eclipse.osbp.ecview.extension.model.converter.CxNumericToResourceConverter;
@SuppressWarnings("serial")
public class NumericToResourceConverter implements Converter<Resource, Number> {
private CxNumericToResourceConverter cxConverter;
private IServiceRegistry registry;
public NumericToResourceConverter(IServiceRegistry registry,
CxNumericToResourceConverter cxConverter) {
this.registry = registry;
this.cxConverter = cxConverter;
}
@Override
public Number convertToModel(Resource value,
Class<? extends Number> targetType, Locale locale)
throws com.vaadin.data.util.converter.Converter.ConversionException {
throw new com.vaadin.data.util.converter.Converter.ConversionException(
"NumericToResourceConverter is readonly!");
}
@Override
public Resource convertToPresentation(Number value,
Class<? extends Resource> targetType, Locale locale)
throws com.vaadin.data.util.converter.Converter.ConversionException {
IResourceProvider provider = registry
.getService(IResourceProvider.class.getName());
for (CxNumericToResourceConfig config : cxConverter.getConfigs()) {
if (isMatch(value, config)) {
String iconKey = I18nUtil.getImageKey(config
.getResourceThemePath());
if (isValid(iconKey)) {
if (provider != null) {
return provider.getResource(iconKey);
}
}
throw new IllegalStateException("No image defined for "
+ config);
}
}
return null;
}
private boolean isValid(String iconKey) {
return iconKey != null && !iconKey.equals("");
}
protected boolean isMatch(Number value, CxNumericToResourceConfig config) {
double ref = config.getValue();
double val = value.doubleValue();
switch (config.getCompare()) {
case EQUAL:
return val == ref;
case GREATER_EQUAL:
return val >= ref;
case GREATER_THAN:
return val > ref;
case LOWER_EQUAL:
return val <= ref;
case LOWER_THAN:
return val < ref;
case NOT_EQUAL:
return val != ref;
}
return false;
}
@Override
public Class<Number> getModelType() {
return Number.class;
}
@Override
public Class<Resource> getPresentationType() {
return Resource.class;
}
}