blob: 280b37e250d7565f57fad14b8682b62675547491 [file] [log] [blame]
/*=============================================================================#
# Copyright (c) 2021 Stephan Wahlbrink and others.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
# which is available at https://www.apache.org/licenses/LICENSE-2.0.
#
# SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
#
# Contributors:
# Stephan Wahlbrink <sw@wahlbrink.eu> - initial API and implementation
#=============================================================================*/
package org.eclipse.statet.jcommons.ts.core;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.statet.jcommons.lang.NonNullByDefault;
import org.eclipse.statet.jcommons.lang.Nullable;
@NonNullByDefault
public class BasicToolCommandData implements ToolCommandData {
private final Map<String, ?> data;
private final Map<String, @Nullable Object> returnData= new HashMap<>();
public BasicToolCommandData(final Map<String, ?> data) {
this.data= data;
}
public BasicToolCommandData() {
this.data= Map.of();
}
@Override
public @Nullable Object getRawData(final String key) {
return this.data.get(key);
}
protected @Nullable Object getData(final String key) {
Object data= this.returnData.get(key);
if (data == null) {
data= getRawData(key);
}
return data;
}
@Override
@SuppressWarnings("unchecked")
public <TData> @Nullable TData get(final String key, final Class<TData> type) {
final Object rawData= getData(key);
if (rawData != null) {
if (type.isInstance(rawData)) {
return (TData)rawData;
}
else {
final var typedData= convert(rawData, type);
if (typedData == null) {
throw new IllegalDataException(String.format("Data entry '%1$s' is incompatible (%2$s).",
key, rawData.getClass().getName() ));
}
return typedData;
}
}
return null;
}
protected Map<String, @Nullable Object> getReturnData() {
return this.returnData;
}
public boolean hasReturnData() {
return !this.returnData.isEmpty();
}
@Override
public void setReturnData(final String key, final @Nullable Object value) {
this.returnData.put(key, value);
}
@Override
public void removeReturnData(final String key) {
this.returnData.remove(key);
}
@SuppressWarnings("unchecked")
public <TData> @Nullable TData convert(@Nullable Object data, final Class<TData> type) {
if (data != null && data.getClass().isArray()
&& data.getClass().getComponentType().isAssignableFrom(type) ) {
final Object[] array= (Object[])data;
if (array.length == 1) {
data= array[0];
}
}
if (data == null || type.isInstance(data)) {
return (TData)data;
}
if (type == Integer.class) {
if (data instanceof Number) {
return (TData)Integer.valueOf(((Number)data).intValue());
}
}
if (type == Double.class ) {
if (data instanceof Number) {
return (TData)Double.valueOf(((Number)data).doubleValue());
}
}
return null;
}
}