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 double. 027 * <p> 028 * Returns an empty optional if the value failed to parse. 029 */ 030public class DoubleExtractor extends SimpleFieldExtractor<Double> { 031 private static final Logger logger = Logger.getLogger(DoubleExtractor.class.getName()); 032 033 /** 034 * Extracts a double value from the supplied field name. 035 * Writes the metadata out using the field name as the key. 036 * @param fieldName The field name to inspect. 037 */ 038 public DoubleExtractor(String fieldName) { 039 super(fieldName); 040 } 041 042 /** 043 * Extracts a double value from the supplied field name. 044 * Writes the metadata out using the metadataName as the key. 045 * @param fieldName The field name to inspect. 046 * @param metadataName The metadata name to emit. 047 */ 048 public DoubleExtractor(String fieldName, String metadataName) { 049 super(fieldName, metadataName); 050 } 051 052 /** 053 * For olcut. 054 */ 055 private DoubleExtractor() {} 056 057 @Override 058 public Class<Double> getValueType() { 059 return Double.class; 060 } 061 062 @Override 063 protected Optional<Double> extractField(String value) { 064 try { 065 double f = Double.parseDouble(value); 066 return Optional.of(f); 067 } catch (NumberFormatException e) { 068 logger.warning("Failed to parse value for field " + fieldName + ", expected a double, got " + value); 069 } 070 return Optional.empty(); 071 } 072 073 @Override 074 public ConfiguredObjectProvenance getProvenance() { 075 return new ConfiguredObjectProvenanceImpl(this,"FieldExtractor"); 076 } 077}