001/*
002 * Copyright (c) 2015-2020, Oracle and/or its affiliates. All rights reserved.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.tribuo.data.columnar.extractors;
018
019import com.oracle.labs.mlrg.olcut.provenance.ConfiguredObjectProvenance;
020import com.oracle.labs.mlrg.olcut.provenance.impl.ConfiguredObjectProvenanceImpl;
021
022import java.util.Optional;
023import java.util.logging.Logger;
024
025/**
026 * Extracts the field value and converts it to a float.
027 * <p>
028 * Returns an empty optional if the value failed to parse.
029 */
030public class FloatExtractor extends SimpleFieldExtractor<Float> {
031
032    private static final Logger logger = Logger.getLogger(FloatExtractor.class.getName());
033
034    /**
035     * Extracts a float value from the supplied field name.
036     * Writes the metadata out using the field name as the key.
037     * @param fieldName The field name to inspect.
038     */
039    public FloatExtractor(String fieldName) {
040        super(fieldName);
041    }
042
043    /**
044     * Extracts a float value from the supplied field name.
045     * Writes the metadata out using the metadataName as the key.
046     * @param fieldName The field name to inspect.
047     * @param metadataName The metadata name to emit.
048     */
049    public FloatExtractor(String fieldName, String metadataName) {
050        super(fieldName, metadataName);
051    }
052
053    /**
054     * For olcut.
055     */
056    private FloatExtractor() {}
057
058    @Override
059    public Class<Float> getValueType() {
060        return Float.class;
061    }
062
063    @Override
064    protected Optional<Float> extractField(String value) {
065        try {
066            float f = Float.parseFloat(value);
067            return Optional.of(f);
068        } catch (NumberFormatException e) {
069            logger.warning("Failed to parse value for field " + fieldName + ", expected a float, got " + value);
070        }
071        return Optional.empty();
072    }
073
074    @Override
075    public ConfiguredObjectProvenance getProvenance() {
076        return new ConfiguredObjectProvenanceImpl(this,"FieldExtractor");
077    }
078}