001/*
002 * JPPF.
003 * Copyright (C) 2005-2016 JPPF Team.
004 * http://www.jppf.org
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.jppf.utils.cli;
020
021import java.util.Map;
022
023/**
024 *
025 * @author Laurent Cohen
026 */
027public class PositionalArguments extends AbstractCLIArguments<PositionalArguments> {
028  @Override
029  public PositionalArguments printUsage() {
030    if (title != null) System.out.println(title);
031    int maxLen = 0;
032    for (CLIArgument arg: argDefs.values()) {
033      int len = arg.getName().length();
034      if (len > maxLen) maxLen = len;
035    }
036    String format = "%-" + maxLen + "s : %s%n";
037    for (Map.Entry<String, CLIArgument> entry: argDefs.entrySet()) {
038      CLIArgument arg = entry.getValue();
039      System.out.printf(format, arg.getName(), arg.getUsage());
040    }
041    return this;
042  }
043
044  @Override
045  public PositionalArguments parseArguments(final String...clArgs)  throws Exception {
046    boolean end = false;
047    int pos = 0;
048    try {
049      for (Map.Entry<String, CLIArgument> entry: argDefs.entrySet()) {
050        if (pos >= clArgs.length) break;
051        setString(Integer.toString(pos), clArgs[pos++]);
052      }
053    } catch (Exception e) {
054      printError(null, e, clArgs);
055      throw e;
056    }
057    return this;
058  }
059
060  /**
061   * Get the value of the argument at the specified position.
062   * @param position the posiiton of the argument ot lookup.
063   * @return the argument value, or {@code null} if it is not found.
064   */
065  public String getString(final int position) {
066    return getString(Integer.toString(position));
067  }
068}