001/* 002 * Copyright 2020 nils.hoffmann. 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 or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package de.isas.lipidomics.palinom; 017 018import java.util.Optional; 019import java.util.function.Function; 020import org.antlr.v4.runtime.tree.RuleNode; 021 022/** 023 * Common functions for ANTLRv4's RuleNode handling. 024 * 025 * @author nils.hoffmann 026 */ 027public class HandlerUtils { 028 029 /** 030 * Parse the provided context's text value as an Integer or use default 031 * value. 032 * 033 * @param <T> the type of the context. 034 * @param context the context. 035 * @param defaultValue the default value. 036 * @return the context's text value as an integer, or the default value. 037 */ 038 public static <T extends RuleNode> Integer asInt(T context, Integer defaultValue) { 039 return maybeMapOr(context, (t) -> { 040 return Integer.parseInt(t.getText()); 041 }, defaultValue); 042 } 043 044 /** 045 * Wrap t as an optional of nullable. 046 * 047 * @param <T> the type of t. 048 * @param t the argument. 049 * @return an optional. 050 */ 051 public static <T> Optional<T> maybe(T t) { 052 return Optional.ofNullable(t); 053 } 054 055 /** 056 * Wrap t as an optional and return r if t is null or empty. 057 * 058 * @param <T> the type of t. 059 * @param <R> the type of the return value r. 060 * @param t the argument to wrap. 061 * @param mapper the mapping function to get from t to r, if t is not null. 062 * @param r the default return value. 063 * @return the mapped value for t of type R, or the default value r. 064 */ 065 public static <T, R> R maybeMapOr(T t, Function<? super T, R> mapper, R r) { 066 return maybe(t).map(mapper).orElse(r); 067 } 068}