001 /* 002 * Util.java 003 * 004 * Licensed to the Apache Software Foundation (ASF) under one 005 * or more contributor license agreements. See the NOTICE file 006 * distributed with this work for additional information 007 * regarding copyright ownership. The ASF licenses this file 008 * to you under the Apache License, Version 2.0 (the 009 * "License"); you may not use this file except in compliance 010 * with the License. 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 021 022 package org.apache.hadoop.metrics2.util; 023 024 import java.net.InetSocketAddress; 025 import java.util.List; 026 027 import com.google.common.collect.Lists; 028 029 import org.apache.hadoop.classification.InterfaceAudience; 030 import org.apache.hadoop.classification.InterfaceStability; 031 032 /** 033 * Helpers to handle server addresses 034 */ 035 @InterfaceAudience.Public 036 @InterfaceStability.Evolving 037 public class Servers { 038 /** 039 * This class is not intended to be instantiated 040 */ 041 private Servers() {} 042 043 /** 044 * Parses a space and/or comma separated sequence of server specifications 045 * of the form <i>hostname</i> or <i>hostname:port</i>. If 046 * the specs string is null, defaults to localhost:defaultPort. 047 * 048 * @param specs server specs (see description) 049 * @param defaultPort the default port if not specified 050 * @return a list of InetSocketAddress objects. 051 */ 052 public static List<InetSocketAddress> parse(String specs, int defaultPort) { 053 List<InetSocketAddress> result = Lists.newArrayList(); 054 if (specs == null) { 055 result.add(new InetSocketAddress("localhost", defaultPort)); 056 } 057 else { 058 String[] specStrings = specs.split("[ ,]+"); 059 for (String specString : specStrings) { 060 int colon = specString.indexOf(':'); 061 if (colon < 0 || colon == specString.length() - 1) { 062 result.add(new InetSocketAddress(specString, defaultPort)); 063 } else { 064 String hostname = specString.substring(0, colon); 065 int port = Integer.parseInt(specString.substring(colon+1)); 066 result.add(new InetSocketAddress(hostname, port)); 067 } 068 } 069 } 070 return result; 071 } 072 }