001/*
002 * Copyright (c) 2007-2022 The Cascading Authors. All Rights Reserved.
003 *
004 * Project and contact information: https://cascading.wensel.net/
005 *
006 * This file is part of the Cascading project.
007 *
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *     http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 */
020
021package cascading.local.tap.splunk;
022
023import java.io.File;
024import java.io.IOException;
025import java.nio.file.Files;
026import java.nio.file.Path;
027import java.nio.file.Paths;
028import java.util.Collections;
029import java.util.Map;
030import java.util.stream.Collectors;
031
032import org.slf4j.Logger;
033import org.slf4j.LoggerFactory;
034
035/**
036 * Splunk helper utilities.
037 */
038public class SplunkUtil
039  {
040  private static final Logger LOG = LoggerFactory.getLogger( SplunkUtil.class );
041
042  /**
043   * Method loadSplunkRC will load a {@code .splunkrc} from either the location specified by
044   * the env variable {@code SPLUNK_RC_HOME} or {@code HOME}.
045   *
046   * @return A Map of configuration key/value pairs.
047   * @throws IOException if the file cannot be read.
048   */
049  public static Map<String, Object> loadSplunkRC() throws IOException
050    {
051    String home = System.getenv( "SPLUNK_RC_HOME" );
052
053    if( home == null )
054      home = System.getProperty( "user.home" );
055
056    Path path = Paths.get( home + File.separator + ".splunkrc" );
057
058    if( !Files.exists( path ) )
059      return Collections.emptyMap();
060
061    LOG.info( "reading .splunkrc from: {}", path );
062
063    Map<String, Object> params = Files.readAllLines( path ).stream()
064      .map( String::trim )
065      .filter( line -> !line.isEmpty() )
066      .filter( line -> !line.startsWith( "#" ) )
067      .map( line -> line.split( "=" ) )
068      .filter( pair -> pair.length == 2 )
069      .filter( pair -> pair[ 1 ] != null )
070      .collect( Collectors.toMap( pair -> pair[ 0 ], pair -> pair[ 1 ] ) );
071
072    params.computeIfPresent( "port", ( k, v ) -> Integer.parseInt( v.toString() ) );
073
074    return params;
075    }
076  }