com.beust.jcommander.internal.Console Java Examples

The following examples show how to use com.beust.jcommander.internal.Console. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecurityUtilsTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncryptionDecryption() throws Exception {
  final String rawInput = "geowave";
  Console console = new JCommander().getConsole();
  final File tokenFile =
      SecurityUtils.getFormattedTokenKeyFileForConfig(
          ConfigOptions.getDefaultPropertyFile(console));
  if ((tokenFile != null) && tokenFile.exists()) {
    final String encryptedValue =
        SecurityUtils.encryptAndHexEncodeValue(rawInput, tokenFile.getCanonicalPath(), console);

    final String decryptedValue =
        SecurityUtils.decryptHexEncodedValue(
            encryptedValue,
            tokenFile.getCanonicalPath(),
            console);

    assertEquals(decryptedValue, rawInput);
  }
}
 
Example #2
Source File: BaseEncryption.java    From geowave with Apache License 2.0 6 votes vote down vote up
/** Check if encryption token exists. If not, create one initially */
private void checkForToken(Console console) throws Throwable {
  if (getResourceLocation() != null) {
    // this is simply caching the location, ideally under all
    // circumstances resource location exists
    tokenFile = new File(getResourceLocation());
  } else {
    // and this is initializing it for the first time, this just assumes
    // the default config file path
    // because of that assumption this can cause inconsistency
    // under all circumstances this seems like it should never happen
    tokenFile =
        SecurityUtils.getFormattedTokenKeyFileForConfig(
            ConfigOptions.getDefaultPropertyFile(console));
  }
  if (!tokenFile.exists()) {
    generateNewEncryptionToken(tokenFile);
  }
}
 
Example #3
Source File: SecurityUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an instance of the encryption service, initialized with the token at the provided
 * resource location
 *
 * @param resourceLocation location of the resource token to initialize the encryption service
 *        with
 * @return An initialized instance of the encryption service
 * @throws Exception
 */
private static synchronized BaseEncryption getEncryptionService(
    final String resourceLocation,
    Console console) throws Throwable {
  if (encService == null) {
    if ((resourceLocation != null) && !"".equals(resourceLocation.trim())) {
      LOGGER.trace(
          "Setting resource location for encryption service: [" + resourceLocation + "]");
      encService = new GeoWaveEncryption(resourceLocation, console);
    } else {
      encService = new GeoWaveEncryption(console);
    }
  } else {
    if (!resourceLocation.equals(encService.getResourceLocation())) {
      encService = new GeoWaveEncryption(resourceLocation, console);
    }
  }
  return encService;
}
 
Example #4
Source File: VersionUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
public static Properties getBuildProperties(final Console console) {

    final Properties props = new Properties();
    try (InputStream stream =
        VersionUtils.class.getClassLoader().getResourceAsStream(BUILD_PROPERTIES_FILE_NAME);) {

      if (stream != null) {
        props.load(stream);
      }

      return props;
    } catch (final IOException e) {
      LOGGER.warn("Cannot read GeoWave build properties to show version information", e);

      if (console != null) {
        console.println(
            "Cannot read GeoWave build properties to show version information: " + e.getMessage());
      }
    }
    return props;
  }
 
Example #5
Source File: ConfigOptions.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * The default property file is in the user's home directory, in the .geowave folder. If the
 * version can not be found the first available property file in the folder is used.
 *
 * @param console console to print output to
 *
 * @return the default property file
 */
public static File getDefaultPropertyFile(final Console console) {
  // HP Fortify "Path Manipulation" false positive
  // What Fortify considers "user input" comes only
  // from users with OS-level access anyway
  final File defaultPath = getDefaultPropertyPath();
  final String version = VersionUtils.getVersion(console);
  if (version != null) {
    return formatConfigFile(version, defaultPath);
  } else {
    final String[] configFiles = defaultPath.list(new FilenameFilter() {

      @Override
      public boolean accept(final File dir, final String name) {
        return name.endsWith("-config.properties");
      }
    });
    if ((configFiles != null) && (configFiles.length > 0)) {
      final String backupVersion = configFiles[0].substring(0, configFiles[0].length() - 18);
      return formatConfigFile(backupVersion, defaultPath);
    } else {
      return formatConfigFile("unknownversion", defaultPath);
    }
  }
}
 
Example #6
Source File: RemoveStatCommand.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean performStatsCommand(
    final DataStorePluginOptions storeOptions,
    final InternalDataAdapter<?> adapter,
    final StatsCommandLineOptions statsOptions,
    final Console console) throws IOException {

  // Remove the stat
  final DataStatisticsStore statStore = storeOptions.createDataStatisticsStore();
  final String[] authorizations = getAuthorizations(statsOptions.getAuthorizations());

  if (!statStore.removeStatistics(
      adapter.getAdapterId(),
      fieldName,
      new BaseStatisticsType<>(statType),
      authorizations)) {
    throw new RuntimeException("Unable to remove statistic: " + statType);
  }

  return true;
}
 
Example #7
Source File: ConfigOptions.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Write the given properties to the file, and log an error if an exception occurs.
 *
 * @return true if success, false if failure
 */
public static boolean writeProperties(
    final File configFile,
    final Properties properties,
    final Console console) {
  return writeProperties(configFile, properties, null, null, console);
}
 
Example #8
Source File: BaseEncryption.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Method to initialize all required fields, check for the existence of the cryptography token
 * key, and generate the key for encryption/decryption
 */
private void init(Console console) {
  try {
    checkForToken(console);
    setResourceLocation(tokenFile.getCanonicalPath());

    salt = "Ge0W@v3-Ro0t-K3y".getBytes("UTF-8");

    generateRootKeyFromToken();
  } catch (final Throwable t) {
    LOGGER.error(t.getLocalizedMessage(), t);
  }
}
 
Example #9
Source File: BaseEncryption.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Base constructor for encryption, allowing a resource location for the cryptography token key to
 * be specified, rather than using the default-generated path
 *
 * @param resourceLocation Path to cryptography token key file
 */
public BaseEncryption(final String resourceLocation, Console console) {
  try {
    setResourceLocation(resourceLocation);
    init(console);
  } catch (final Throwable t) {
    LOGGER.error(t.getLocalizedMessage(), t);
  }
}
 
Example #10
Source File: SecurityUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Method to encrypt and hex-encode a string value
 *
 * @param value value to encrypt and hex-encode
 * @param resourceLocation resource token to use for encrypting the value
 * @return If encryption is successful, encrypted and hex-encoded string value is returned wrapped
 *         with ENC{}
 */
public static String encryptAndHexEncodeValue(
    final String value,
    final String resourceLocation,
    Console console) throws Exception {
  LOGGER.debug("Encrypting and hex-encoding value");
  if ((value != null) && !"".equals(value.trim())) {
    if (!BaseEncryption.isProperlyWrapped(value)) {
      try {
        return getEncryptionService(resourceLocation, console).encryptAndHexEncode(value);
      } catch (final Throwable t) {
        LOGGER.error(
            "Encountered exception during content encryption: " + t.getLocalizedMessage(),
            t);
      }
    } else {
      LOGGER.debug(
          "WARNING: Value to encrypt already appears to be encrypted and already wrapped with "
              + WRAPPER
              + ". Not encrypting value.");
      return value;
    }
  } else {
    LOGGER.debug("WARNING: No value specified to encrypt.");
    return value;
  }
  return value;
}
 
Example #11
Source File: SecurityUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Method to decrypt a value
 *
 * @param value Value to decrypt. Should be wrapped with ENC{}
 * @param resourceLocation Optional value to specify the location of the encryption service
 *        resource location
 * @return decrypted value
 */
public static String decryptHexEncodedValue(
    final String value,
    final String resourceLocation,
    Console console) throws Exception {
  LOGGER.trace("Decrypting hex-encoded value");
  if ((value != null) && !"".equals(value.trim())) {
    if (BaseEncryption.isProperlyWrapped(value.trim())) {
      try {
        return getEncryptionService(resourceLocation, console).decryptHexEncoded(value);
      } catch (final Throwable t) {
        LOGGER.error(
            "Encountered exception during content decryption: " + t.getLocalizedMessage(),
            t);
      }
    } else {
      LOGGER.debug(
          "WARNING: Value to decrypt was not propertly encoded and wrapped with "
              + WRAPPER
              + ". Not decrypting value.");
      return value;
    }
  } else {
    LOGGER.debug("WARNING: No value specified to decrypt.");
  }
  return "";
}
 
Example #12
Source File: SpatialJoinCommand.java    From geowave with Apache License 2.0 5 votes vote down vote up
private DataStorePluginOptions loadStore(
    final String storeName,
    final File configFile,
    final Console console) {
  final StoreLoader storeLoader = new StoreLoader(storeName);
  if (!storeLoader.loadFromConfig(configFile, console)) {
    throw new ParameterException("Cannot find left store: " + storeLoader.getStoreName());
  }
  return storeLoader.getDataStorePlugin();
}
 
Example #13
Source File: RocksDBOptions.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public void validatePluginOptions(final Properties properties, final Console console)
    throws ParameterException {
  // Set the directory to be absolute
  dir = new File(dir).getAbsolutePath();
  super.validatePluginOptions(properties, console);
}
 
Example #14
Source File: StoreLoader.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Attempt to load the data store configuration from the config file.
 *
 * @param console the console to print output to
 * @param configFile
 * @return {@code true} if the configuration was successfully loaded
 */
public boolean loadFromConfig(final File configFile, final Console console) {

  final String namespace = DataStorePluginOptions.getStoreNamespace(storeName);

  return loadFromConfig(
      ConfigOptions.loadProperties(configFile, "^" + namespace),
      namespace,
      configFile,
      console);
}
 
Example #15
Source File: FileSystemOptions.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public void validatePluginOptions(final Properties properties, final Console console)
    throws ParameterException {
  // Set the directory to be absolute
  dir = Paths.get(dir).toAbsolutePath().toString();
  super.validatePluginOptions(properties, console);
}
 
Example #16
Source File: GeoServerRestClientTest.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Before
public void prepare() {
  webTarget = mockedWebTarget();
  final Console console = new JCommander().getConsole();
  config = new GeoServerConfig(console);
  client = GeoServerRestClient.getInstance(config, console);
  client.setWebTarget(webTarget);
}
 
Example #17
Source File: GeoServerRestClient.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static GeoServerRestClient getInstance(
    final GeoServerConfig config,
    final Console console) {
  if (SINGLETON_INSTANCE == null) {
    SINGLETON_INSTANCE = new GeoServerRestClient(config, console);
  }
  return SINGLETON_INSTANCE;
}
 
Example #18
Source File: GeoServerRestClient.java    From geowave with Apache License 2.0 5 votes vote down vote up
private GeoServerRestClient(
    final GeoServerConfig config,
    final WebTarget webTarget,
    final Console console) {
  this.config = config;
  this.webTarget = webTarget;
  this.console = console;
}
 
Example #19
Source File: VectorMRExportJobRunner.java    From geowave with Apache License 2.0 5 votes vote down vote up
public VectorMRExportJobRunner(
    final DataStorePluginOptions storeOptions,
    final VectorMRExportOptions mrOptions,
    final String hdfsHostPort,
    final String hdfsPath,
    final Console console) {
  this.storeOptions = storeOptions;
  this.mrOptions = mrOptions;
  this.hdfsHostPort = hdfsHostPort;
  this.hdfsPath = hdfsPath;
  this.console = console;
}
 
Example #20
Source File: VersionUtils.java    From geowave with Apache License 2.0 4 votes vote down vote up
public static List<String> getVersionInfo(final Console console) {
  final List<String> buildAndPropertyList =
      Arrays.asList(getBuildProperties(console).toString().split(","));
  Collections.sort(buildAndPropertyList.subList(1, buildAndPropertyList.size()));
  return buildAndPropertyList;
}
 
Example #21
Source File: VersionUtils.java    From geowave with Apache License 2.0 4 votes vote down vote up
public static void printVersionInfo(final Console console) {
  final List<String> buildAndPropertyList = getVersionInfo(console);
  for (final String str : buildAndPropertyList) {
    console.println(str);
  }
}
 
Example #22
Source File: StoreFactoryOptions.java    From geowave with Apache License 2.0 4 votes vote down vote up
/**
 * Method to perform global validation for all plugin options
 *
 * @throws Exception
 */
public void validatePluginOptions(final Properties properties, final Console console)
    throws ParameterException {
  LOGGER.trace("ENTER :: validatePluginOptions()");
  final PropertiesUtils propsUtils = new PropertiesUtils(properties);
  final boolean defaultEchoEnabled =
      propsUtils.getBoolean(Constants.CONSOLE_DEFAULT_ECHO_ENABLED_KEY, false);
  final boolean passwordEchoEnabled =
      propsUtils.getBoolean(Constants.CONSOLE_PASSWORD_ECHO_ENABLED_KEY, defaultEchoEnabled);
  LOGGER.debug(
      "Default console echo is {}, Password console echo is {}",
      new Object[] {
          defaultEchoEnabled ? "enabled" : "disabled",
          passwordEchoEnabled ? "enabled" : "disabled"});
  for (final Field field : this.getClass().getDeclaredFields()) {
    for (final Annotation annotation : field.getAnnotations()) {
      if (annotation.annotationType() == Parameter.class) {
        final Parameter parameter = (Parameter) annotation;
        if (JCommanderParameterUtils.isRequired(parameter)) {
          field.setAccessible(true); // HPFortify
          // "Access Specifier Manipulation"
          // False Positive: These
          // fields are being modified
          // by trusted code,
          // in a way that is not
          // influenced by user input
          Object value = null;
          try {
            value = field.get(this);
            if (value == null) {
              console.println(
                  "Field ["
                      + field.getName()
                      + "] is required: "
                      + Arrays.toString(parameter.names())
                      + ": "
                      + parameter.description());
              console.print("Enter value for [" + field.getName() + "]: ");
              final boolean echoEnabled =
                  JCommanderParameterUtils.isPassword(parameter) ? passwordEchoEnabled
                      : defaultEchoEnabled;
              char[] password = console.readPassword(echoEnabled);
              final String strPassword = new String(password);
              password = null;

              if (!"".equals(strPassword.trim())) {
                value =
                    ((strPassword != null) && !"".equals(strPassword.trim())) ? strPassword.trim()
                        : null;
              }
              if (value == null) {
                throw new ParameterException(
                    "Value for [" + field.getName() + "] cannot be null");
              } else {
                field.set(this, value);
              }
            }
          } catch (final Exception ex) {
            LOGGER.error(
                "An error occurred validating plugin options for ["
                    + this.getClass().getName()
                    + "]: "
                    + ex.getLocalizedMessage(),
                ex);
          }
        }
      }
    }
  }
}
 
Example #23
Source File: CalculateStatCommand.java    From geowave with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean performStatsCommand(
    final DataStorePluginOptions storeOptions,
    final InternalDataAdapter<?> adapter,
    final StatsCommandLineOptions statsOptions,
    final Console console) throws IOException {

  try {
    final DataStore dataStore = storeOptions.createDataStore();
    if (!(dataStore instanceof BaseDataStore)) {
      LOGGER.warn(
          "Datastore type '"
              + dataStore.getClass().getName()
              + "' must be instance of BaseDataStore to recalculate stats");
      return false;
    }
    final AdapterIndexMappingStore mappingStore = storeOptions.createAdapterIndexMappingStore();
    final IndexStore indexStore = storeOptions.createIndexStore();

    boolean isFirstTime = true;
    for (final Index index : mappingStore.getIndicesForAdapter(adapter.getAdapterId()).getIndices(
        indexStore)) {

      @SuppressWarnings({"rawtypes", "unchecked"})
      final String[] authorizations = getAuthorizations(statsOptions.getAuthorizations());
      final DataStoreStatisticsProvider provider =
          new DataStoreStatisticsProvider(adapter, index, isFirstTime) {
            @Override
            public StatisticsId[] getSupportedStatistics() {
              return new StatisticsId[] {
                  new StatisticsId(new BaseStatisticsType<>(statType), fieldName)};
            }
          };

      try (StatsCompositionTool<?> statsTool =
          new StatsCompositionTool(
              provider,
              storeOptions.createDataStatisticsStore(),
              index,
              adapter)) {

        try (CloseableIterator<?> entryIt =
            ((BaseDataStore) dataStore).query(
                QueryBuilder.newBuilder().addTypeName(adapter.getTypeName()).indexName(
                    index.getName()).setAuthorizations(authorizations).build(),
                (ScanCallback) statsTool)) {
          while (entryIt.hasNext()) {
            entryIt.next();
          }
        }
      }
      isFirstTime = false;
    }

  } catch (final Exception ex) {
    LOGGER.error("Error while writing statistics.", ex);
    return false;
  }

  return true;
}
 
Example #24
Source File: AbstractStatsCommand.java    From geowave with Apache License 2.0 4 votes vote down vote up
/** Abstracted command method to be called when command selected */
protected abstract boolean performStatsCommand(
    final DataStorePluginOptions options,
    final InternalDataAdapter<?> adapter,
    final StatsCommandLineOptions statsOptions,
    final Console console) throws IOException;
 
Example #25
Source File: RecalculateStatsCommand.java    From geowave with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean performStatsCommand(
    final DataStorePluginOptions storeOptions,
    final InternalDataAdapter<?> adapter,
    final StatsCommandLineOptions statsOptions,
    final Console console) throws IOException {

  try {
    final DataStore dataStore = storeOptions.createDataStore();
    if (!(dataStore instanceof BaseDataStore)) {
      LOGGER.warn(
          "Datastore type '"
              + dataStore.getClass().getName()
              + "' must be instance of BaseDataStore to recalculate stats");
      return false;
    }

    final AdapterIndexMappingStore mappingStore = storeOptions.createAdapterIndexMappingStore();
    final IndexStore indexStore = storeOptions.createIndexStore();

    boolean isFirstTime = true;
    for (final Index index : mappingStore.getIndicesForAdapter(adapter.getAdapterId()).getIndices(
        indexStore)) {
      @SuppressWarnings({"rawtypes", "unchecked"})
      final DataStoreStatisticsProvider provider =
          new DataStoreStatisticsProvider(adapter, index, isFirstTime);
      final String[] authorizations = getAuthorizations(statsOptions.getAuthorizations());

      try (StatsCompositionTool<?> statsTool =
          new StatsCompositionTool(
              provider,
              storeOptions.createDataStatisticsStore(),
              index,
              adapter,
              true)) {
        try (CloseableIterator<?> entryIt =
            ((BaseDataStore) dataStore).query(
                QueryBuilder.newBuilder().addTypeName(adapter.getTypeName()).indexName(
                    index.getName()).setAuthorizations(authorizations).build(),
                (ScanCallback) statsTool)) {
          while (entryIt.hasNext()) {
            entryIt.next();
          }
        }
      }
      isFirstTime = false;
    }

  } catch (final Exception ex) {
    LOGGER.error("Error while writing statistics.", ex);
    return false;
  }

  return true;
}
 
Example #26
Source File: StoreLoader.java    From geowave with Apache License 2.0 4 votes vote down vote up
/**
 * Attempt to load the data store configuration from the config file.
 *
 * @param configFile
 * @return {@code true} if the configuration was successfully loaded
 */
public boolean loadFromConfig(
    final Properties props,
    final String namespace,
    final File configFile,
    final Console console) {

  dataStorePlugin = new DataStorePluginOptions();

  // load all plugin options and initialize dataStorePlugin with type and
  // options
  if (!dataStorePlugin.load(props, namespace)) {
    return false;
  }

  // knowing the datastore plugin options and class type, get all fields
  // and parameters in order to detect which are password fields
  if ((configFile != null) && (dataStorePlugin.getFactoryOptions() != null)) {
    File tokenFile = SecurityUtils.getFormattedTokenKeyFileForConfig(configFile);
    final Field[] fields = dataStorePlugin.getFactoryOptions().getClass().getDeclaredFields();
    for (final Field field : fields) {
      for (final Annotation annotation : field.getAnnotations()) {
        if (annotation.annotationType() == Parameter.class) {
          final Parameter parameter = (Parameter) annotation;
          if (JCommanderParameterUtils.isPassword(parameter)) {
            final String storeFieldName =
                ((namespace != null) && !"".equals(namespace.trim()))
                    ? namespace + "." + DefaultPluginOptions.OPTS + "." + field.getName()
                    : field.getName();
            if (props.containsKey(storeFieldName)) {
              final String value = props.getProperty(storeFieldName);
              String decryptedValue = value;
              try {
                decryptedValue =
                    SecurityUtils.decryptHexEncodedValue(
                        value,
                        tokenFile.getAbsolutePath(),
                        console);
              } catch (final Exception e) {
                LOGGER.error(
                    "An error occurred encrypting specified password value: "
                        + e.getLocalizedMessage(),
                    e);
              }
              props.setProperty(storeFieldName, decryptedValue);
            }
          }
        }
      }
    }
    tokenFile = null;
  }
  // reload datastore plugin with new password-encrypted properties
  if (!dataStorePlugin.load(props, namespace)) {
    return false;
  }

  return true;
}
 
Example #27
Source File: StoreFactoryOptions.java    From geowave with Apache License 2.0 4 votes vote down vote up
public void validatePluginOptions(final Console console) throws ParameterException {
  validatePluginOptions(new Properties(), console);
}
 
Example #28
Source File: VersionUtils.java    From geowave with Apache License 2.0 4 votes vote down vote up
public static String getVersion(final Console console) {
  return getBuildProperties(console).getProperty(VERSION_PROPERTY_KEY);
}
 
Example #29
Source File: GeoWaveEncryption.java    From geowave with Apache License 2.0 4 votes vote down vote up
/** Base constructor for encryption */
public GeoWaveEncryption(Console console) {
  super(console);
}
 
Example #30
Source File: BaseEncryption.java    From geowave with Apache License 2.0 4 votes vote down vote up
/** Base constructor for encryption */
public BaseEncryption(Console console) {
  init(console);
}