下面列出了怎么用javax.naming.ConfigurationException的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testPingCommandStatusFail() throws ConfigurationException, BrocadeVcsApiException {
resource.configure("BrocadeVcsResource", parameters);
final VcsNodeInfo nodeInfo = mock(VcsNodeInfo.class);
when(nodeInfo.getNodeState()).thenReturn("Offline");
List<VcsNodeInfo> nodes = new ArrayList<VcsNodeInfo>();
nodes.add(nodeInfo);
final VcsNodes vcsNodes = mock(VcsNodes.class);
final Output output = mock(Output.class);
when(output.getVcsNodes()).thenReturn(vcsNodes);
when(vcsNodes.getVcsNodeInfo()).thenReturn(nodes);
when(api.getSwitchStatus()).thenReturn(output);
final PingCommand ping = resource.getCurrentStatus(42);
assertTrue(ping == null);
}
@Override
public ServerResource reloadResource(HostVO host) {
String resourceName = host.getResource();
ServerResource resource = getResource(resourceName);
if (resource != null) {
_hostDao.loadDetails(host);
HashMap<String, Object> params = buildConfigParams(host);
try {
resource.configure(host.getName(), params);
} catch (ConfigurationException e) {
s_logger.warn("Unable to configure resource due to " + e.getMessage());
return null;
}
if (!resource.start()) {
s_logger.warn("Unable to start the resource");
return null;
}
}
return resource;
}
@Test
public void testOverrideSomeTrafficTypes() throws ConfigurationException {
final Map<String, Object> params = new HashMap<>();
params.put(this.LibVirtVifDriver + "." + "Public", this.FakeVifDriverClassName);
params.put(this.LibVirtVifDriver + "." + "Guest", LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS);
this.res.setBridgeType(BridgeType.NATIVE);
configure(params);
// Initially, set all traffic types to use default
for (final TrafficType trafficType : TrafficType.values()) {
this.assertions.put(trafficType, this.bridgeVifDriver);
}
this.assertions.put(TrafficType.Public, this.fakeVifDriver);
this.assertions.put(TrafficType.Guest, this.ovsVifDriver);
checkAssertions();
}
@Test
public void testDiscovery() throws ConfigurationException {
// Setting the MqttService will enable the background scanner
MqttServiceDiscoveryService d = new MqttServiceDiscoveryService();
d.addDiscoveryListener(discoverListener);
d.setMqttService(service);
d.startScan();
// We expect 3 discoveries. An embedded thing, a textual configured one, a non-textual one
ArgumentCaptor<DiscoveryResult> discoveryCapture = ArgumentCaptor.forClass(DiscoveryResult.class);
verify(discoverListener, times(2)).thingDiscovered(eq(d), discoveryCapture.capture());
List<DiscoveryResult> discoveryResults = discoveryCapture.getAllValues();
assertThat(discoveryResults.size(), is(2));
assertThat(discoveryResults.get(0).getThingTypeUID(), is(MqttBindingConstants.BRIDGE_TYPE_SYSTEMBROKER));
assertThat(discoveryResults.get(1).getThingTypeUID(), is(MqttBindingConstants.BRIDGE_TYPE_SYSTEMBROKER));
// Add another thing
d.brokerAdded("anotherone", new MqttBrokerConnection("tcp://123.123.123.123", null, false, null));
discoveryCapture = ArgumentCaptor.forClass(DiscoveryResult.class);
verify(discoverListener, times(3)).thingDiscovered(eq(d), discoveryCapture.capture());
discoveryResults = discoveryCapture.getAllValues();
assertThat(discoveryResults.size(), is(3));
assertThat(discoveryResults.get(2).getThingTypeUID(), is(MqttBindingConstants.BRIDGE_TYPE_SYSTEMBROKER));
}
public BuildFarmInstances(
String session,
List<InstanceConfig> instanceConfigs,
String defaultInstanceName,
Runnable onStop)
throws InterruptedException, ConfigurationException {
instances = new HashMap<String, Instance>();
createInstances(session, instanceConfigs, onStop);
if (!defaultInstanceName.isEmpty()) {
if (!instances.containsKey(defaultInstanceName)) {
throw new ConfigurationException(
defaultInstanceName + " not specified in instance configs.");
}
defaultInstance = instances.get(defaultInstanceName);
} else {
defaultInstance = null;
}
}
@Override
public boolean configure(final String name, final Map<String, Object> xmlParams) throws ConfigurationException {
this._peers = new HashMap<>(7);
this._sslEngines = new HashMap<>(7);
this._nodeId = ManagementServerNode.getManagementServerId();
s_logger.info("Configuring ClusterAgentManagerImpl. management server node id(msid): " + this._nodeId);
ClusteredAgentAttache.initialize(this);
this._clusterMgr.registerListener(this);
this._clusterMgr.registerDispatcher(new ClusterDispatcher());
this._gson = GsonHelper.getGson();
return super.configure(name, xmlParams);
}
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
this._configDao.getValue(Config.BackupSnapshotWait.toString());
Type.HOURLY.setMax(NumbersUtil.parseInt(this._configDao.getValue("snapshot.max.hourly"), HOURLYMAX));
Type.DAILY.setMax(NumbersUtil.parseInt(this._configDao.getValue("snapshot.max.daily"), DAILYMAX));
Type.WEEKLY.setMax(NumbersUtil.parseInt(this._configDao.getValue("snapshot.max.weekly"), WEEKLYMAX));
Type.MONTHLY.setMax(NumbersUtil.parseInt(this._configDao.getValue("snapshot.max.monthly"), MONTHLYMAX));
this._totalRetries = NumbersUtil.parseInt(this._configDao.getValue("total.retries"), 4);
this._pauseInterval = 2 * NumbersUtil.parseInt(this._configDao.getValue("ping.interval"), 60);
s_logger.info("Snapshot Manager is configured.");
return true;
}
@Override
public ServerResource reloadResource(final HostVO host) {
final String resourceName = host.getResource();
final ServerResource resource = getResource(resourceName);
if (resource != null) {
this._hostDao.loadDetails(host);
updateNetworkLabels(host);
final HashMap<String, Object> params = buildConfigParams(host);
try {
resource.configure(host.getName(), params);
} catch (final ConfigurationException e) {
s_logger.warn("Unable to configure resource due to " + e.getMessage());
return null;
}
if (!resource.start()) {
s_logger.warn("Unable to start the resource");
return null;
}
}
return resource;
}
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_snapshotPollInterval = NumbersUtil.parseInt(_configDao.getValue("snapshot.poll.interval"), 300);
final boolean snapshotsRecurringTest = Boolean.parseBoolean(_configDao.getValue("snapshot.recurring.test"));
if (snapshotsRecurringTest) {
// look for some test values in the configuration table so that snapshots can be taken more frequently (QA test code)
final int minutesPerHour = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.minutes.per.hour"), 60);
final int hoursPerDay = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.hours.per.day"), 24);
final int daysPerWeek = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.days.per.week"), 7);
final int daysPerMonth = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.days.per.month"), 30);
final int weeksPerMonth = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.weeks.per.month"), 4);
final int monthsPerYear = NumbersUtil.parseInt(_configDao.getValue("snapshot.test.months.per.year"), 12);
_testTimerTask = new TestClock(this, minutesPerHour, hoursPerDay, daysPerWeek, daysPerMonth, weeksPerMonth, monthsPerYear);
}
_currentTimestamp = new Date();
s_logger.info("Snapshot Scheduler is configured.");
return true;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
boolean result = super.configure(name, params);
countVnetsDedicatedToAccount = createSearchBuilder(Integer.class);
countVnetsDedicatedToAccount.and("dc", countVnetsDedicatedToAccount.entity().getDataCenterId(), SearchCriteria.Op.EQ);
countVnetsDedicatedToAccount.and("accountGuestVlanMapId", countVnetsDedicatedToAccount.entity().getAccountGuestVlanMapId(), Op.NNULL);
AccountGuestVlanMapSearch = _accountGuestVlanMapDao.createSearchBuilder();
AccountGuestVlanMapSearch.and("accountId", AccountGuestVlanMapSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
countVnetsDedicatedToAccount.join("AccountGuestVlanMapSearch", AccountGuestVlanMapSearch, countVnetsDedicatedToAccount.entity().getAccountGuestVlanMapId(),
AccountGuestVlanMapSearch.entity().getId(), JoinBuilder.JoinType.INNER);
countVnetsDedicatedToAccount.select(null, Func.COUNT, countVnetsDedicatedToAccount.entity().getId());
countVnetsDedicatedToAccount.done();
AccountGuestVlanMapSearch.done();
return result;
}
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
if (!super.configure(name, params)) {
return false;
}
final String value = (String) params.get("mac.address.prefix");
_prefix = (long) NumbersUtil.parseInt(value, 06) << 40;
if (!_ipAllocDao.configure("Ip Alloc", params)) {
return false;
}
if (!_vnetAllocDao.configure("vnet Alloc", params)) {
return false;
}
return true;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
final Properties props = new Properties();
try {
final FileInputStream is = new FileInputStream(PropertiesUtil.findConfigFile("kafka.producer.properties"));
props.load(is);
is.close();
} catch (Exception e) {
// Fallback to default properties
props.setProperty("bootstrap.servers", "192.168.22.1:9092");
props.setProperty("acks", "all");
props.setProperty("retries", "1");
props.setProperty("topic", "cosmic");
props.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
}
_producer = new KafkaProducer<String,String>(props);
_name = name;
return true;
}
@Override
public String getServiceEndpointName(final String strPeer) {
try {
init();
} catch (final ConfigurationException e) {
s_logger.error("Unable to init ClusterServiceServletAdapter");
return null;
}
final long msid = Long.parseLong(strPeer);
final ManagementServerHostVO mshost = _mshostDao.findByMsid(msid);
if (mshost == null) {
return null;
}
return composeEndpointName(mshost.getServiceIP(), mshost.getServicePort());
}
@Override
public String getServiceEndpointName(String strPeer) {
try {
init();
} catch (ConfigurationException e) {
s_logger.error("Unable to init ClusterServiceServletAdapter");
return null;
}
long msid = Long.parseLong(strPeer);
ManagementServerHostVO mshost = _mshostDao.findByMsid(msid);
if (mshost == null)
return null;
return composeEndpointName(mshost.getServiceIP(), mshost.getServicePort());
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
super.configure(name, params);
_firstFitStoragePoolAllocator = ComponentContext.inject(ClusterScopeStoragePoolAllocator.class);
_firstFitStoragePoolAllocator.configure("GCFirstFitStoragePoolAllocator", params);
_localStoragePoolAllocator = ComponentContext.inject(LocalStoragePoolAllocator.class);
_localStoragePoolAllocator.configure("GCLocalStoragePoolAllocator", params);
String storagePoolCleanupEnabled = _configDao.getValue("storage.pool.cleanup.enabled");
_storagePoolCleanupEnabled = (storagePoolCleanupEnabled == null) ? true : Boolean.parseBoolean(storagePoolCleanupEnabled);
return true;
}
private ConnectionTest prepare() throws ConfigurationException {
Ovm3Configuration config = new Ovm3Configuration(configTest.getParams());
con = support.prepConnectionResults();
hypervisor.setConnection(con);
results.basicBooleanTest(hypervisor.configure(config.getAgentName(),
configTest.getParams()));
return con;
}
@Test
public void testPingCommandStatusOk() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters);
final ControlClusterStatus ccs = mock(ControlClusterStatus.class);
when(ccs.getClusterStatus()).thenReturn("stable");
when(nvpApi.getControlClusterStatus()).thenReturn(ccs);
final PingCommand ping = resource.getCurrentStatus(42);
assertTrue(ping != null);
assertTrue(ping.getHostId() == 42);
assertTrue(ping.getHostType() == Host.Type.L2Networking);
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
_messageBus.subscribe(AsyncJob.Topics.JOB_HEARTBEAT, MessageDispatcher.getDispatcher(this));
_timer.scheduleAtFixedRate(new ManagedContextTimerTask() {
@Override
protected void runInContext() {
heartbeat();
}
}, _inactivityCheckIntervalMs, _inactivityCheckIntervalMs);
return true;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
Map<String, String> configs = _configDao.getConfiguration("management-server", params);
// set up the email system for alerts
String emailAddressList = configs.get("alert.email.addresses");
String[] emailAddresses = null;
if (emailAddressList != null) {
emailAddresses = emailAddressList.split(",");
}
String smtpHost = configs.get("alert.smtp.host");
int smtpPort = NumbersUtil.parseInt(configs.get("alert.smtp.port"), 25);
String useAuthStr = configs.get("alert.smtp.useAuth");
boolean useAuth = ((useAuthStr == null) ? false : Boolean.parseBoolean(useAuthStr));
String smtpUsername = configs.get("alert.smtp.username");
String smtpPassword = configs.get("alert.smtp.password");
String emailSender = configs.get("alert.email.sender");
String smtpDebugStr = configs.get("alert.smtp.debug");
boolean smtpDebug = false;
if (smtpDebugStr != null) {
smtpDebug = Boolean.parseBoolean(smtpDebugStr);
}
_emailAlert = new EmailAlert(emailAddresses, smtpHost, smtpPort, useAuth, smtpUsername, smtpPassword, emailSender, smtpDebug);
return true;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
hostGuid = (String)params.get("guid");
_simMgr = ComponentContext.inject(SimulatorManagerImpl.class);
_simMgr.configure(name, params);
agentHost = getAgentMgr().getHost(hostGuid);
return true;
}
private ConfigurationException wrapException(Exception e) {
ConfigurationException ce = new ConfigurationException(
"Cannot load implementation of javax.naming.ldap.StartTlsResponse");
ce.setRootCause(e);
return ce;
}
@Before
public void setUp() throws ConfigurationException {
_resource = new CiscoVnmcResource();
_parameters = new HashMap<String, Object>();
_parameters.put("name", "CiscoVnmc");
_parameters.put("zoneId", "1");
_parameters.put("physicalNetworkId", "100");
_parameters.put("ip", "1.2.3.4");
_parameters.put("username", "admin");
_parameters.put("password", "pass");
_parameters.put("guid", "e8e13097-0a08-4e82-b0af-1101589ec3b8");
_parameters.put("numretries", "3");
_parameters.put("timeout", "300");
}
public Processor buildQcow2Processor(final StorageLayer storage) throws ConfigurationException {
final Map<String, Object> params = new HashMap<>();
params.put(StorageLayer.InstanceConfigKey, storage);
final Processor qcow2Processor = new QCOW2Processor();
qcow2Processor.configure("QCOW2 Processor", params);
return qcow2Processor;
}
private ConfigurationException wrapException(Exception e) {
ConfigurationException ce = new ConfigurationException(
"Cannot load implementation of javax.naming.ldap.StartTlsResponse");
ce.setRootCause(e);
return ce;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
if (_configDao == null) {
throw new ConfigurationException("Unable to get the configuration dao.");
}
_vmSnapshotMax = NumbersUtil.parseInt(_configDao.getValue("vmsnapshot.max"), VMSNAPSHOTMAX);
String value = _configDao.getValue("vmsnapshot.create.wait");
_wait = NumbersUtil.parseInt(value, 1800);
return true;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
if (!super.configure(name, params)) {
s_logger.warn("Base class was unable to configure");
return false;
}
return true;
}
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
super.configure(name, params);
this._mountParent = this._params.get("mount.parent");
if (this._mountParent == null) {
this._mountParent = "/mnt";
}
final String useServiceVM = this._params.get("secondary.storage.vm");
if ("true".equalsIgnoreCase(useServiceVM)) {
this._useServiceVM = true;
}
return true;
}
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_agentMgr.registerForHostEvents(this, true, false, true);
VirtualMachine.State.getStateMachine().registerListener(this);
_messageBus.subscribe("VM_ReservedCapacity_Free", new MessageSubscriber() {
@Override
public void onPublishMessage(final String senderAddress, final String subject, final Object obj) {
final VMInstanceVO vm = ((VMInstanceVO) obj);
s_logger.debug("MessageBus message: host reserved capacity released for VM: " + vm.getLastHostId() +
", checking if host reservation can be released for host:" + vm.getLastHostId());
final Long hostId = vm.getLastHostId();
checkHostReservationRelease(hostId);
}
});
_vmCapacityReleaseInterval = NumbersUtil.parseInt(_configDao.getValue(Config.CapacitySkipcountingHours.key()), 3600);
final String hostReservationReleasePeriod = _configDao.getValue(Config.HostReservationReleasePeriod.key());
if (hostReservationReleasePeriod != null) {
_hostReservationReleasePeriod = Long.parseLong(hostReservationReleasePeriod);
if (_hostReservationReleasePeriod <= 0) {
_hostReservationReleasePeriod = Long.parseLong(Config.HostReservationReleasePeriod.getDefaultValue());
}
}
_timer = new Timer("HostReservationReleaseChecker");
_nodeId = ManagementServerNode.getManagementServerId();
return super.configure(name, params);
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = (String)params.get("name");
if (_name == null) {
throw new ConfigurationException("Unable to find name");
}
_guid = (String)params.get("guid");
if (_guid == null) {
throw new ConfigurationException("Unable to find the guid");
}
_zoneId = (String)params.get("zoneId");
if (_zoneId == null) {
throw new ConfigurationException("Unable to find zone");
}
_numRetries = 2;
String ip = (String)params.get("ip");
if (ip == null) {
throw new ConfigurationException("Unable to find IP");
}
String adminuser = (String)params.get("adminuser");
if (adminuser == null) {
throw new ConfigurationException("Unable to find admin username");
}
String adminpass = (String)params.get("adminpass");
if (adminpass == null) {
throw new ConfigurationException("Unable to find admin password");
}
_brocadeVcsApi = createBrocadeVcsApi(ip, adminuser, adminpass);
return true;
}
private void createInstances(
String session, List<InstanceConfig> instanceConfigs, Runnable onStop)
throws InterruptedException, ConfigurationException {
for (InstanceConfig instanceConfig : instanceConfigs) {
String name = instanceConfig.getName();
HashFunction hashFunction = getValidHashFunction(instanceConfig);
DigestUtil digestUtil = new DigestUtil(hashFunction);
switch (instanceConfig.getTypeCase()) {
default:
case TYPE_NOT_SET:
throw new IllegalArgumentException("Instance type not set in config");
case MEMORY_INSTANCE_CONFIG:
instances.put(
name, new MemoryInstance(name, digestUtil, instanceConfig.getMemoryInstanceConfig()));
break;
case SHARD_INSTANCE_CONFIG:
instances.put(
name,
new ShardInstance(
name,
session + "-" + name,
digestUtil,
instanceConfig.getShardInstanceConfig(),
onStop));
break;
}
}
}