Java Code Examples for org.apache.commons.configuration.ConfigurationException

The following examples show how to use org.apache.commons.configuration.ConfigurationException. These examples are extracted from open source projects. 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 Project: openmessaging-benchmark   Author: openmessaging   File: DlogBenchmarkDriver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(File configurationFile, StatsLogger statsLogger) throws IOException {
    config = mapper.readValue(configurationFile, Config.class);

    PropertiesConfiguration propsConf = new PropertiesConfiguration();
    DistributedLogConfiguration conf = new DistributedLogConfiguration();
    try {
        propsConf.load(new StringReader(config.dlogConf));
        conf.loadConf(propsConf);
    } catch (ConfigurationException e) {
        log.error("Failed to load dlog configuration : \n{}\n", config.dlogConf, e);
        throw new IOException("Failed to load configuration : \n" + config.dlogConf + "\n", e);
    }
    URI dlogUri = URI.create(config.dlogUri);

    dlshade.org.apache.bookkeeper.stats.StatsLogger dlStatsLogger =
        new CachingStatsLogger(new StatsLoggerAdaptor(statsLogger.scope("dlog")));

    namespace = NamespaceBuilder.newBuilder()
        .conf(conf)
        .uri(dlogUri)
        .statsLogger(dlStatsLogger)
        .build();

    log.info("Initialized distributedlog namespace at {}", dlogUri);
}
 
Example #2
Source Project: distributedlog   Author: apache   File: ConfigurationSubscription.java    License: Apache License 2.0 6 votes vote down vote up
private boolean initConfig() {
    if (fileConfigs.isEmpty()) {
        try {
            for (FileConfigurationBuilder fileConfigBuilder : fileConfigBuilders) {
                FileConfiguration fileConfig = fileConfigBuilder.getConfiguration();
                FileChangedReloadingStrategy reloadingStrategy = new FileChangedReloadingStrategy();
                reloadingStrategy.setRefreshDelay(0);
                fileConfig.setReloadingStrategy(reloadingStrategy);
                fileConfigs.add(fileConfig);
            }
        } catch (ConfigurationException ex) {
            if (!fileNotFound(ex)) {
                LOG.error("Config init failed {}", ex);
            }
        }
    }
    return !fileConfigs.isEmpty();
}
 
Example #3
Source Project: navigator-sdk   Author: cloudera   File: ClientConfigFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a PluginConfiguration from the properties contained in the
 * given filePath
 *
 * @param filePath
 * @return
 */
public ClientConfig readConfigurations(String filePath) {
  try {
    PropertiesConfiguration props = new PropertiesConfiguration(filePath);
    ClientConfig config = new ClientConfig();
    config.setApplicationUrl(props.getString(APP_URL));
    config.setFormat(Format.valueOf(
        props.getString(FILE_FORMAT, Format.JSON.name())));
    config.setNamespace(props.getString(NAMESPACE));
    config.setNavigatorUrl(props.getString(NAV_URL));
    config.setApiVersion(props.getInt(API_VERSION));
    config.setUsername(props.getString(USERNAME));
    config.setPassword(props.getString(PASSWORD));
    config.setAutocommit(props.getBoolean(AUTOCOMMIT, false));
    config.setDisableSSLValidation(props.getBoolean(DISABLE_SSL_VALIDATION,
        false));
    config.setSSLTrustStoreLocation(props.getString(SSL_KEYSTORE_LOCATION,
        null));
    config.setSSLTrustStorePassword(props.getString(SSL_KEYSTORE_PASSWORD,
        null));
    return config;
  } catch (ConfigurationException e) {
    throw Throwables.propagate(e);
  }
}
 
Example #4
Source Project: product-ei   Author: wso2   File: PerMessageAcknowledgementsTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initializing test case
 *
 * @throws XPathExpressionException
 */
@BeforeClass(alwaysRun = true)
public void init() throws XPathExpressionException, IOException, AutomationUtilException, ConfigurationException {
    super.init(TestUserMode.SUPER_TENANT_USER);

    // Updating the redelivery attempts to 1 to speed up the test case.
    super.serverManager = new ServerConfigurationManager(automationContext);
    String defaultMBConfigurationPath = ServerConfigurationManager.getCarbonHome() + File.separator + "wso2" +
                                        File.separator + "broker" + File.separator + "conf" + File.separator +
                                        "broker.xml";
    ConfigurationEditor configurationEditor = new ConfigurationEditor(defaultMBConfigurationPath);

    // Changing "maximumRedeliveryAttempts" value to "1" in broker.xml
    configurationEditor.updateProperty(AndesConfiguration.TRANSPORTS_AMQP_MAXIMUM_REDELIVERY_ATTEMPTS, "1");
    // Restarting server
    configurationEditor.applyUpdatedConfigurationAndRestartServer(serverManager);

    // Get current "AndesAckWaitTimeOut" system property.
    defaultAndesAckWaitTimeOut = System.getProperty(AndesClientConstants.ANDES_ACK_WAIT_TIMEOUT_PROPERTY);

    // Setting system property "AndesAckWaitTimeOut" for andes
    System.setProperty(AndesClientConstants.ANDES_ACK_WAIT_TIMEOUT_PROPERTY, "3000");
}
 
Example #5
Source Project: peer-os   Author: subutai-io   File: SystemManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@RolesAllowed( "System-Management|Update" )
public void setNetworkSettings( final String publicUrl, final String publicSecurePort, final boolean useRhIp )
        throws ConfigurationException
{
    try
    {
        peerManager
                .setPublicUrl( peerManager.getLocalPeer().getId(), publicUrl, Integer.parseInt( publicSecurePort ),
                        useRhIp );
    }
    catch ( Exception e )
    {
        throw new ConfigurationException( e );
    }
}
 
Example #6
Source Project: incubator-pinot   Author: apache   File: StarTreeIndexContainer.java    License: Apache License 2.0 6 votes vote down vote up
public StarTreeIndexContainer(File segmentDirectory, SegmentMetadataImpl segmentMetadata,
    Map<String, ColumnIndexContainer> indexContainerMap, ReadMode readMode)
    throws ConfigurationException, IOException {
  File indexFile = new File(segmentDirectory, StarTreeV2Constants.INDEX_FILE_NAME);
  if (readMode == ReadMode.heap) {
    _dataBuffer = PinotDataBuffer
        .loadFile(indexFile, 0, indexFile.length(), ByteOrder.LITTLE_ENDIAN, "Star-tree V2 data buffer");
  } else {
    _dataBuffer = PinotDataBuffer
        .mapFile(indexFile, true, 0, indexFile.length(), ByteOrder.LITTLE_ENDIAN, "Star-tree V2 data buffer");
  }
  File indexMapFile = new File(segmentDirectory, StarTreeV2Constants.INDEX_MAP_FILE_NAME);
  List<Map<IndexKey, IndexValue>> indexMapList =
      StarTreeIndexMapUtils.loadFromFile(indexMapFile, segmentMetadata.getStarTreeV2MetadataList().size());
  _starTrees = StarTreeLoaderUtils.loadStarTreeV2(_dataBuffer, indexMapList, segmentMetadata, indexContainerMap);
}
 
Example #7
Source Project: peer-os   Author: subutai-io   File: RestServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Response getNetworkSettings()
{
    try
    {
        NetworkSettings pojo = systemManager.getNetworkSettings();
        String networkSettingsInfo = JsonUtil.GSON.toJson( pojo );

        return Response.status( Response.Status.OK ).entity( networkSettingsInfo ).build();
    }
    catch ( ConfigurationException e )
    {
        LOG.error( e.getMessage() );

        return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).
                entity( e.getMessage() ).build();
    }
}
 
Example #8
Source Project: juddi   Author: apache   File: ValidatePublish.java    License: Apache License 2.0 6 votes vote down vote up
public void validateSaveServiceMax(EntityManager em, String businessKey) throws DispositionReportFaultMessage {

                //Obtain the maxSettings for this publisher or get the defaults
                Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName());
                Integer maxServices = publisher.getMaxBusinesses();
                try {
                        if (maxServices == null) {
                                if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_SERVICES_PER_BUSINESS)) {
                                        maxServices = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1);
                                } else {
                                        maxServices = -1;
                                }
                        }
                } catch (ConfigurationException e) {
                        log.error(e.getMessage(), e);
                        maxServices = -1; //incase the configuration isn't available
                }
                //if we have the maxServices set for a business then we need to make sure we did not exceed it.
                if (maxServices > 0) {
                        //get the businesses owned by this publisher
                        org.apache.juddi.model.BusinessEntity modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, businessKey);
                        if (modelBusinessEntity.getBusinessServices() != null && modelBusinessEntity.getBusinessServices().size() > maxServices) {
                                throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxServicesExceeded"));
                        }
                }
        }
 
Example #9
Source Project: product-ei   Author: wso2   File: LZ4UITestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Enabling compression to verify decompression and reducing the maximum content chunk size, to create more content chunks
 * from compressed content, to check chunk data retrieval.
 * Increase the managementConsole/maximumMessageDisplayLength to match the large message size that is tested.
 *
 * @throws XPathExpressionException
 * @throws java.io.IOException
 * @throws org.apache.commons.configuration.ConfigurationException
 * @throws org.wso2.carbon.integration.common.utils.exceptions.AutomationUtilException
 */
@BeforeClass
public void setupConfiguration() throws AutomationUtilException, XPathExpressionException, IOException,
        ConfigurationException {

    super.serverManager = new ServerConfigurationManager(mbServer);

    String defaultMBConfigurationPath = ServerConfigurationManager.getCarbonHome() + File.separator + "wso2"
                                        + File.separator + "broker" + File.separator + "conf" + File.separator
                                        + "broker.xml";

    log.info("DEFAULT_MB_CONFIG_PATH : " + defaultMBConfigurationPath);

    ConfigurationEditor configurationEditor = new ConfigurationEditor(defaultMBConfigurationPath);

    configurationEditor.updateProperty(AndesConfiguration
            .MANAGEMENT_CONSOLE_MAX_DISPLAY_LENGTH_FOR_MESSAGE_CONTENT, String.valueOf(MESSAGE_SIZE_IN_BYTES + 1));
    configurationEditor.updateProperty(AndesConfiguration.PERFORMANCE_TUNING_ALLOW_COMPRESSION, "true");
    configurationEditor.updateProperty(AndesConfiguration.PERFORMANCE_TUNING_MAX_CONTENT_CHUNK_SIZE, "100");

    configurationEditor.applyUpdatedConfigurationAndRestartServer(serverManager);
}
 
Example #10
Source Project: singer   Author: pinterest   File: DefaultLogMonitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param monitorIntervalInSecs monitor interval in seconds.
 * @param singerConfig          the SingerConfig.
 */
protected DefaultLogMonitor(int monitorIntervalInSecs,
                            SingerConfig singerConfig)
    throws ConfigurationException {
  Preconditions.checkArgument(monitorIntervalInSecs > 0);
  this.monitorIntervalInSecs = monitorIntervalInSecs;
  this.processedLogStreams = Maps.newHashMap();
  this.isStopped = true;
  this.scheduledFuture = null;
  this.logMonitorExecutor = Executors.newSingleThreadScheduledExecutor(
          new ThreadFactoryBuilder().setNameFormat("LogMonitor").build());
  if (singerConfig.isSetSingerRestartConfig() && singerConfig.singerRestartConfig.restartDaily) {
    dailyRestart = true;
    setDailyRestartTime(singerConfig.singerRestartConfig);
  }
}
 
Example #11
Source Project: yfiton   Author: yfiton   File: YfitonBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public Yfiton build() throws ConversionException, ConfigurationException {
    Notifier notifier = this.notifier;

    if (notifier == null) {
        notifier = resolve(this.notifierKey);
    }

    if (configurationFile == null) {
        try {
            configurationFile = Configuration.getNotifierConfigurationFilePath(notifier.getKey());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    HierarchicalINIConfiguration hierarchicalConfiguration =
            new HierarchicalINIConfiguration(configurationFile.toFile());

    return new Yfiton(notifier, hierarchicalConfiguration, displayStackTraces);
}
 
Example #12
Source Project: singer   Author: pinterest   File: DefaultLogMonitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Monitor the log streams, and start the log stream processor for new log streams.
 *
 * @throws Exception when fail to monitor the SingerLog.
 */
private LogStreamProcessor createLogStreamProcessor(SingerLogConfig singerLogConfig,
                                                    LogStream logStream)
    throws ConfigurationException, LogStreamReaderException, LogStreamWriterException {
  LogStreamReader reader =
      createLogStreamReader(logStream, singerLogConfig.getLogStreamReaderConfig());
  LogStreamWriter writer =
      createLogStreamWriter(logStream, singerLogConfig.getLogStreamWriterConfig());

  LogStreamProcessorConfig processorConfig = singerLogConfig.getLogStreamProcessorConfig();
  int batchSize = processorConfig.getBatchSize();
  batchSize = writer.isAuditingEnabled() ? batchSize - 1 : batchSize;

  return new DefaultLogStreamProcessor(
      logStream,
      singerLogConfig.getLogDecider(),
      reader,
      writer,
      batchSize,
      processorConfig.getProcessingIntervalInMillisecondsMin(),
      processorConfig.getProcessingIntervalInMillisecondsMax(),
      processorConfig.getProcessingTimeSliceInMilliseconds(),
      singerLogConfig.getLogRetentionInSeconds());
}
 
Example #13
Source Project: juddi   Author: apache   File: API_040_BusinessServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setup() throws ConfigurationException {
	Registry.start();
               logger.info("API_040_BusinessServiceTest");
	logger.debug("Getting auth tokens..");
               
	try {
		api010.saveJoePublisher();
		api010.saveSamSyndicator();
		UDDISecurityPortType security      = new UDDISecurityImpl();
		authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(),  TckPublisher.getJoePassword());
		authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(),  TckPublisher.getSamPassword());
		String authInfoUDDI  = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(),  TckPublisher.getUDDIPassword());
		tckTModel.saveUDDIPublisherTmodel(authInfoUDDI);
		tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML);
	} catch (RemoteException e) {
		logger.error(e.getMessage(), e);
		Assert.fail("Could not obtain authInfo token.");
	}
}
 
Example #14
Source Project: singer   Author: pinterest   File: DefaultLogMonitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Expand a name by replacing placeholder (such as \1, \2) in the name with captured group
 * from LogStream name.
 *
 * @param logStreamName the LogStream name this string will be expanded in.
 * @param streamRegex   the stream name regex.
 * @param name          the name to be expanded.
 * @return expanded name with placeholder replaced.
 * @throws ConfigurationException
 */
public static String extractTopicNameFromLogStreamName(
    String logStreamName, String streamRegex, String name) throws ConfigurationException {
  try {
    Pattern pattern = Pattern.compile(streamRegex);
    Matcher logStreamNameMatcher = pattern.matcher(logStreamName);
    Preconditions.checkState(logStreamNameMatcher.matches());

    // Replace all group numbers in "name" with the groups from logStreamName.
    Pattern p = Pattern.compile("\\\\(\\d{1})");
    Matcher groupMatcher = p.matcher(name);
    StringBuffer sb = new StringBuffer();
    while (groupMatcher.find()) {
      groupMatcher.appendReplacement(
          sb,
          logStreamNameMatcher.group(Integer.parseInt(groupMatcher.group(1))));
    }
    groupMatcher.appendTail(sb);
    return sb.toString();
  } catch (NumberFormatException e) {
    throw new ConfigurationException("Cannot expand " + name + " in log stream " + logStreamName,
        e);
  }
}
 
Example #15
Source Project: onos   Author: opennetworkinglab   File: YangXmlUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests getting a multiple object nested configuration via passing the path
 * and a list of YangElements containing with the element and desired value.
 *
 * @throws ConfigurationException
 */
@Test
public void getXmlConfigurationFromYangElements() throws ConfigurationException {

    assertNotEquals("Null testConfiguration", new XMLConfiguration(), testCreateConfig);
    testCreateConfig.load(getClass().getResourceAsStream("/testYangConfig.xml"));
    List<YangElement> elements = new ArrayList<>();
    elements.add(new YangElement("capable-switch", ImmutableMap.of("id", "openvswitch")));
    elements.add(new YangElement("switch", ImmutableMap.of("id", "ofc-bridge")));
    List<ControllerInfo> controllers =
            ImmutableList.of(new ControllerInfo(IpAddress.valueOf("1.1.1.1"), 1, "tcp"),
                             new ControllerInfo(IpAddress.valueOf("2.2.2.2"), 2, "tcp"));
    controllers.forEach(cInfo -> {
        elements.add(new YangElement("controller", ImmutableMap.of("id", cInfo.target(),
                                                                   "ip-address", cInfo.ip().toString())));
    });
    XMLConfiguration cfg =
            new XMLConfiguration(YangXmlUtils.getInstance()
                                         .getXmlConfiguration(OF_CONFIG_XML_PATH, elements));
    assertEquals("Wrong configuaration", IteratorUtils.toList(testCreateConfig.getKeys()),
                 IteratorUtils.toList(cfg.getKeys()));
    assertEquals("Wrong string configuaration", canonicalXml(utils.getString(testCreateConfig)),
                 canonicalXml(utils.getString(cfg)));
}
 
Example #16
Source Project: incubator-gobblin   Author: apache   File: CliOptions.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parse command line arguments and return a {@link java.util.Properties} object for the gobblin job found.
 * @param caller Class of the calling main method. Used for error logs.
 * @param args Command line arguments.
 * @return Instance of {@link Properties} for the Gobblin job to run.
 * @throws IOException
 */
public static Properties parseArgs(Class<?> caller, String[] args) throws IOException {
  try {
    // Parse command-line options
    CommandLine cmd = new DefaultParser().parse(options(), args);

    if (cmd.hasOption(HELP_OPTION.getOpt())) {
      printUsage(caller);
      System.exit(0);
    }

    if (!cmd.hasOption(SYS_CONFIG_OPTION.getLongOpt()) || !cmd.hasOption(JOB_CONFIG_OPTION.getLongOpt())) {
      printUsage(caller);
      System.exit(1);
    }

    // Load system and job configuration properties
    Properties sysConfig = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(SYS_CONFIG_OPTION.getLongOpt()));
    Properties jobConfig = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(JOB_CONFIG_OPTION.getLongOpt()));

    return JobConfigurationUtils.combineSysAndJobProperties(sysConfig, jobConfig);
  } catch (ParseException | ConfigurationException e) {
    throw new IOException(e);
  }
}
 
Example #17
Source Project: otroslogviewer   Author: otros-systems   File: PropertyPatternMessageColorizer.java    License: Apache License 2.0 6 votes vote down vote up
public void init(InputStream in) throws ConfigurationException {
  propertiesConfiguration = new PropertiesConfiguration();
  propertiesConfiguration.setDelimiterParsingDisabled(true);
  propertiesConfiguration.load(in, "UTF-8");
  configuration = new DataConfiguration(propertiesConfiguration);
  configuration.setDelimiterParsingDisabled(true);
  String pa = configuration.getString(PROP_PATTERN);
  int flags = 0;
  flags = flags | (configuration.getBoolean(PROP_PATTERN_CANON_EQ, false) ? Pattern.CANON_EQ : 0);
  flags = flags | (configuration.getBoolean(PROP_PATTERN_CASE_INSENSITIVE, false) ? Pattern.CASE_INSENSITIVE : 0);
  flags = flags | (configuration.getBoolean(PROP_PATTERN_COMMENTS, false) ? Pattern.COMMENTS : 0);
  flags = flags | (configuration.getBoolean(PROP_PATTERN_DOTALL, false) ? Pattern.DOTALL : 0);
  flags = flags | (configuration.getBoolean(PROP_PATTERN_LITERAL, false) ? Pattern.LITERAL : 0);
  flags = flags | (configuration.getBoolean(PROP_PATTERN_MULTILINE, false) ? Pattern.MULTILINE : 0);
  flags = flags | (configuration.getBoolean(PROP_PATTERN_UNICODE_CASE, false) ? Pattern.UNICODE_CASE : 0);
  flags = flags | (configuration.getBoolean(PROP_PATTERN_UNIX_LINES, false) ? Pattern.UNIX_LINES : 0);

  pattern = Pattern.compile(pa, flags);
  groupCount = countGroups(pattern);
  name = configuration.getString(PROP_NAME, "NAME NOT SET!");
  description = configuration.getString(PROP_DESCRIPTION, "DESCRIPTION NOT SET!");
  testMessage = configuration.getString(PROP_TEST_MESSAGE, "");

}
 
Example #18
Source Project: yfiton   Author: yfiton   File: SlackNotifier.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void storeAccessTokenData(AccessTokenData accessTokenData, HierarchicalINIConfiguration configuration) throws NotificationException {
    String teamId = accessTokenData.get("teamId");
    configuration.setProperty(KEY_DEFAULT_TEAM_ID, teamId);

    SubnodeConfiguration section = configuration.getSection(teamId);

    section.setProperty(KEY_ACCESS_TOKEN, accessTokenData.getAccessToken());
    for (Map.Entry<String, String> entry : accessTokenData.getData()) {
        section.setProperty(entry.getKey(), entry.getValue());
    }

    try {
        configuration.save();
    } catch (ConfigurationException e) {
        throw new NotificationException(e);
    }
}
 
Example #19
Source Project: googleads-java-lib   Author: googleads   File: ConfigurationHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Loads configuration from a specified path. If not absolute, will look in
 * the user home directory, the current classpath and the system classpath.
 * Absolute classpath references will not work.
 *
 * @param path the path to try first as a resource, then as a file
 * @throws ConfigurationLoadException if the configuration could not be
 *         loaded.
 * @returns properties loaded from the specified path or null.
 */
public Configuration fromFile(String path) throws ConfigurationLoadException {
  PropertiesConfiguration propertiesConfiguration =
      setupConfiguration(new PropertiesConfiguration());
  propertiesConfiguration.setFileName(path);
  try {
    propertiesConfiguration.load();
  } catch (ConfigurationException e) {
    if (Throwables.getRootCause(e) instanceof AccessControlException){
      AdsServiceLoggers.ADS_API_LIB_LOG.debug("Properties could not be loaded.", e);
    } else {
      throw new ConfigurationLoadException(
          "Encountered a problem reading the provided configuration file \"" + path + "\"!", e);
    }
  }
  return propertiesConfiguration;
}
 
Example #20
Source Project: juddi   Author: apache   File: API_170_CustodyTransferTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setup() throws ConfigurationException {
        Registry.start();
        logger.info("API_030_BusinessEntityTest");
        logger.debug("Getting auth token..");
        try {
                api010.saveJoePublisher();
                api010.saveSamSyndicator();
                UDDISecurityPortType security = new UDDISecurityImpl();
                authInfoMary = TckSecurity.getAuthToken(security, TckPublisher.getMaryPublisherId(), TckPublisher.getMaryPassword());
                authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword());
                String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword());
                tckTModel.saveUDDIPublisherTmodel(authInfoUDDI);
                tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML);
                tckTModel.saveMaryPublisherTmodel(authInfoMary);
                tckTModel.saveSamSyndicatorTmodel(authInfoSam);
        } catch (RemoteException e) {
                logger.error(e.getMessage(), e);
                Assert.fail("Could not obtain authInfo token.");
        }
}
 
Example #21
Source Project: distributedlog   Author: twitter   File: DistributedLogServer.java    License: Apache License 2.0 6 votes vote down vote up
private StreamConfigProvider getStreamConfigProvider(DistributedLogConfiguration dlConf,
                                                     StreamPartitionConverter partitionConverter)
        throws ConfigurationException {
    StreamConfigProvider streamConfProvider = new NullStreamConfigProvider();
    if (streamConf.isPresent() && conf.isPresent()) {
        String dynConfigPath = streamConf.get();
        String defaultConfigFile = conf.get();
        streamConfProvider = new ServiceStreamConfigProvider(
                dynConfigPath,
                defaultConfigFile,
                partitionConverter,
                configExecutorService,
                dlConf.getDynamicConfigReloadIntervalSec(),
                TimeUnit.SECONDS);
    } else if (conf.isPresent()) {
        String configFile = conf.get();
        streamConfProvider = new DefaultStreamConfigProvider(configFile, configExecutorService,
                dlConf.getDynamicConfigReloadIntervalSec(), TimeUnit.SECONDS);
    }
    return streamConfProvider;
}
 
Example #22
Source Project: hugegraph   Author: hugegraph   File: RegisterUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void registerBackends() {
    String confFile = "/backend.properties";
    InputStream input = RegisterUtil.class.getClass()
                                    .getResourceAsStream(confFile);
    E.checkState(input != null,
                 "Can't read file '%s' as stream", confFile);

    PropertiesConfiguration props = new PropertiesConfiguration();
    props.setDelimiterParsingDisabled(true);
    try {
        props.load(input);
    } catch (ConfigurationException e) {
        throw new HugeException("Can't load config file: %s", e, confFile);
    }

    HugeConfig config = new HugeConfig(props);
    List<String> backends = config.get(DistOptions.BACKENDS);
    for (String backend : backends) {
        registerBackend(backend);
    }
}
 
Example #23
Source Project: juddi   Author: apache   File: ServiceLocator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Looks up the Endpoints for a Service. If the cache is in use it will try to 
 * obtain them from the cache. If no Endpoints are found, or if the cache is not
 * in use, the clerk will do a lookup for this service. After Endpoints are found
 * it will use a policy to pick one Endpoint to return. Returns null if no endpoints
 * are found.
 * 
 * @param serviceKey
 * @return endpoint
 * @throws RemoteException
 * @throws ConfigurationException
 * @throws TransportException
 */
public String lookupEndpoint(String serviceKey) throws RemoteException, ConfigurationException, TransportException {
	Topology topology = null;
               if (simpleCache != null && simpleCache.containsKey(serviceKey)){
                       topology = simpleCache.get(serviceKey);
               } else if (serviceCache==null) { //nocache in use
		topology = lookupEndpointInUDDI(serviceKey);
	} else { //with cache
		//try to get it from the cache first
		topology = serviceCache.lookupService(serviceKey);
		if (topology == null) { //not found in the cache
			topology = lookupEndpointInUDDI(serviceKey);
		}
	}
               if (topology!=null && topology.getEprs().size() > 0) {
                       if (simpleCache!=null){
                               simpleCache.put(serviceKey,topology);
                       }
                       String epr = getPolicy().select(topology);
                       return epr;
               } 
               return null;
}
 
Example #24
Source Project: juddi   Author: apache   File: UDDI_070_FindEntityIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startManager() throws ConfigurationException {
     if (!TckPublisher.isEnabled()) return;
        manager = new UDDIClient();
        manager.start();

        logger.debug("Getting auth tokens..");
        try {
                JAXWSv2TranslationTransport transport = (JAXWSv2TranslationTransport) manager.getTransport("uddiv2");
                Publish security = transport.getUDDIv2PublishService();
                authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword());
                //Assert.assertNotNull(authInfoJoe);

                Publish publication = transport.getUDDIv2PublishService();
                inquiry = transport.getUDDIv2InquiryService();

                if (!TckPublisher.isUDDIAuthMode()) {
                        TckSecurity.setCredentials((BindingProvider) publication, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword());
                        TckSecurity.setCredentials((BindingProvider) inquiry, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword());
                }

                tckTModel = new TckTModel(publication, inquiry);
                tckBusiness = new TckBusiness(publication, inquiry);
                tckBusinessService = new TckBusinessService(publication, inquiry);
                tckBindingTemplate = new TckBindingTemplate(publication, inquiry);
                tckFindEntity = new TckFindEntity(inquiry);

        } catch (Exception e) {
                logger.error(e.getMessage(), e);
                Assert.fail("Could not obtain authInfo token.");
        }
}
 
Example #25
Source Project: onos   Author: opennetworkinglab   File: ApplicationArchive.java    License: Apache License 2.0 5 votes vote down vote up
private String getSelfContainedBundleCoordinates(ApplicationDescription desc) {
    try {
        XMLConfiguration cfg = new XMLConfiguration();
        cfg.setAttributeSplittingDisabled(true);
        cfg.setDelimiterParsingDisabled(true);
        cfg.load(appFile(desc.name(), FEATURES_XML));
        return cfg.getString("feature.bundle")
                .replaceFirst("wrap:", "")
                .replaceFirst("\\$Bundle-.*$", "");
    } catch (ConfigurationException e) {
        log.warn("Self-contained application {} has no features.xml", desc.name());
        return null;
    }
}
 
Example #26
Source Project: zap-extensions   Author: zaproxy   File: EncoderConfig.java    License: Apache License 2.0 5 votes vote down vote up
public static List<TabModel> loadConfig() throws ConfigurationException, IOException {
    Path config = getConfigPath(CONFIG_FILE);
    if (Files.notExists(config)) {
        return loadDefaultConfig();
    }
    return loadConfig(config);
}
 
Example #27
Source Project: sqlg   Author: pietermartin   File: TestLoadSchemaViaNotify.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    URL sqlProperties = Thread.currentThread().getContextClassLoader().getResource("sqlg.properties");
    try {
        configuration = new PropertiesConfiguration(sqlProperties);
        Assume.assumeTrue(isPostgres());
        configuration.addProperty("distributed", true);
        if (!configuration.containsKey("jdbc.url"))
            throw new IllegalArgumentException(String.format("SqlGraph configuration requires that the %s be set", "jdbc.url"));

    } catch (ConfigurationException e) {
        throw new RuntimeException(e);
    }
}
 
Example #28
Source Project: juddi   Author: apache   File: UDDI_090_HttpExternalTest.java    License: Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void stop() throws ConfigurationException {
        if (!TckPublisher.isEnabled()) return;
        stopManager();
        endPoint.stop();
        endPoint = null;

}
 
Example #29
Source Project: spring-boot   Author: h819   File: MyConfigurationXMLUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取树状结构数据
 */
public void getHierarchicalExample() {

    try {
        XMLConfiguration config = new XMLConfiguration("properties-website-job.xml");
        log.info(config.getFileName());
        //   log.info(config.getStringByEncoding("jdbc.oracle.work.235.url", "GBK"));

        //包含 websites.site.name 的集合
        Object prop = config.getProperty("websites.site.name");

        if (prop instanceof Collection) {
            //  System.out.println("Number of tables: " + ((Collection<?>) prop).size());
            Collection<String> c = (Collection<String>) prop;
            int i = 0;

            for (String s : c) {

                System.out.println("sitename :" + s);

                List<HierarchicalConfiguration> fields = config.configurationsAt("websites.site(" + String.valueOf(i) + ").fields.field");
                for (HierarchicalConfiguration sub : fields) {
                    // sub contains all data about a single field
                    //此处可以包装成 bean
                    String name = sub.getString("name");
                    String type = sub.getString("type");
                    System.out.println("name :" + name + " , type :" + type);
                }

                i++;
                System.out.println(" === ");
            }
        }
    } catch (ConfigurationException e) {
        e.printStackTrace();
    }


}
 
Example #30
Source Project: BUbiNG   Author: LAW-Unimi   File: StartupConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
private void checkRootDir() throws ConfigurationException {
	if (rootDirChecked) return;
	final File d = new File(rootDir);
	if (crawlIsNew) {
		if (d.exists()) throw new ConfigurationException("Root directory " + d + " exists");
		if (! d.mkdirs()) throw new ConfigurationException("Cannot create root directory " + d);
	}
	else if (! d.exists()) throw new ConfigurationException("Cannot find root directory " + rootDir + " for the crawl");
	rootDirChecked = true;
}