下面列出了怎么用java.util.Dictionary的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void start ( final BundleContext context ) throws Exception
{
Activator.instance = this;
if ( !Boolean.getBoolean ( "org.eclipse.scada.core.client.ngp.disableSharedProcessor" ) )
{
this.processor = new SimpleIoProcessorPool<> ( NioProcessor.class );
}
this.factory = new DriverFactoryImpl ( this.processor );
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( org.eclipse.scada.core.client.DriverFactory.INTERFACE_NAME, "ca" );
properties.put ( org.eclipse.scada.core.client.DriverFactory.DRIVER_NAME, "ngp" );
properties.put ( Constants.SERVICE_DESCRIPTION, "Eclipse SCADA CA NGP Adapter" );
properties.put ( Constants.SERVICE_VENDOR, "Eclipse SCADA Project" );
this.handle = context.registerService ( org.eclipse.scada.core.client.DriverFactory.class, this.factory, properties );
}
/**
* Updates the configuration for the binding and (re-)starts the
* communicator.
*/
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
if (config != null) {
setProperlyConfigured(false);
communicator.stop();
context.getConfig().parse(config);
logger.info(context.getConfig().toString());
if (context.getConfig().isValid()) {
communicator.start();
setProperlyConfigured(true);
for (HomematicBindingProvider hmProvider : providers) {
for (String itemName : hmProvider.getItemNames()) {
informCommunicator(hmProvider, itemName);
}
}
}
}
}
private Stick setupStick(Dictionary<String, ?> config) {
String port = ObjectUtils.toString(config.get("stick.port"), null);
if (port == null) {
return null;
}
Stick stick = new Stick(port, this);
logger.debug("Plugwise added Stick connected to serial port {}", port);
String interval = ObjectUtils.toString(config.get("stick.interval"), null);
if (interval != null) {
stick.setInterval(Integer.valueOf(interval));
logger.debug("Setting the interval to send ZigBee PDUs to {} ms", interval);
}
String retries = ObjectUtils.toString(config.get("stick.retries"), null);
if (retries != null) {
stick.setRetries(Integer.valueOf(retries));
logger.debug("Setting the maximum number of attempts to send a message to ", retries);
}
return stick;
}
/**
@see PropertySetCallback#validate
*/
public boolean validate(String key, Serializable value, Dictionary p) {
// GemStone changes BEGIN
boolean isUserProp = key.startsWith(com.pivotal.gemfirexd.internal.iapi
.reference.Property.USER_PROPERTY_PREFIX)
//SQLF:BC
|| key.startsWith(com.pivotal.gemfirexd.internal.iapi
.reference.Property.SQLF_USER_PROPERTY_PREFIX);
if (GemFireXDUtils.TraceAuthentication) {
if (isUserProp) {
SanityManager.DEBUG_PRINT(AuthenticationTrace, key
+ " recognized as database user & credentials "
+ "will be stored.");
}
else {
SanityManager.DEBUG_PRINT(AuthenticationTrace, key
+ " not recognized as a database user & therefore "
+ "credentials won't be stored in GemFireXD.");
}
}
// GemStone changes END
return isUserProp;
}
@Modified
public void modified(ComponentContext context) {
if (context == null) {
return;
}
Dictionary<?, ?> properties = context.getProperties();
try {
String s = get(properties, FLOW_COUNT);
flowCount = isNullOrEmpty(s) ? flowCount : Integer.parseInt(s.trim());
s = get(properties, ROUTE_COUNT);
routeCount = isNullOrEmpty(s) ? routeCount : Integer.parseInt(s.trim());
log.info("Reconfigured; flowCount={}; routeCount={}", flowCount, routeCount);
adjustFlows();
adjustRoutes();
} catch (NumberFormatException | ClassCastException e) {
log.warn("Misconfigured", e);
}
}
/**
* Loads the image from the URL <code>getImageURL</code>. This should
* only be invoked from <code>refreshImage</code>.
*/
private void loadImage() {
URL src = getImageURL();
Image newImage = null;
if (src != null) {
Dictionary cache = (Dictionary)getDocument().
getProperty(IMAGE_CACHE_PROPERTY);
if (cache != null) {
newImage = (Image)cache.get(src);
}
else {
newImage = Toolkit.getDefaultToolkit().createImage(src);
if (newImage != null && getLoadsSynchronously()) {
// Force the image to be loaded by using an ImageIcon.
ImageIcon ii = new ImageIcon();
ii.setImage(newImage);
}
}
}
image = newImage;
}
/**
* Returns the smallest value that has an entry in the label table.
*
* @return smallest value that has an entry in the label table, or
* null.
* @since 1.6
*/
protected Integer getLowestValue() {
Dictionary dictionary = slider.getLabelTable();
if (dictionary == null) {
return null;
}
Enumeration keys = dictionary.keys();
Integer min = null;
while (keys.hasMoreElements()) {
Integer i = (Integer) keys.nextElement();
if (min == null || i < min) {
min = i;
}
}
return min;
}
private void triggerUpdate(String componentName) {
try {
Configuration cfg = cfgAdmin.getConfiguration(componentName, null);
Map<String, ConfigProperty> map = properties.get(componentName);
if (map == null) {
// Prevent NPE if the component isn't there
log.warn("Component not found for " + componentName);
return;
}
Dictionary<String, Object> props = new Hashtable<>();
map.values().stream().filter(p -> p.value() != null)
.forEach(p -> props.put(p.name(), p.value()));
cfg.update(props);
} catch (IOException e) {
log.warn("Unable to update configuration for " + componentName, e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
if (config != null) {
// to override the default refresh interval one has to add a
// parameter to openhab.cfg like
// <bindingName>:refresh=<intervalInMs>
String refreshIntervalString = (String) config.get("refreshinterval");
if (StringUtils.isNotBlank(refreshIntervalString)) {
refreshInterval = Long.parseLong(refreshIntervalString);
}
String ipString = (String) config.get("ip");
if (StringUtils.isNotBlank(ipString)) {
ip = ipString;
setProperlyConfigured(true);
}
String portString = (String) config.get("port");
if (StringUtils.isNotBlank(portString)) {
port = portString;
}
}
}
/**
* Returns the smallest value that has an entry in the label table.
*
* @return smallest value that has an entry in the label table, or
* null.
* @since 1.6
*/
protected Integer getLowestValue() {
Dictionary dictionary = slider.getLabelTable();
if (dictionary == null) {
return null;
}
Enumeration keys = dictionary.keys();
Integer min = null;
while (keys.hasMoreElements()) {
Integer i = (Integer) keys.nextElement();
if (min == null || i < min) {
min = i;
}
}
return min;
}
protected final static Map<String, ?> dict2map(
final Dictionary<String, ?> dict) {
if (dict == null) {
return null;
}
if (dict instanceof Hashtable) {
return (Hashtable<String, ?>) dict;
}
// legacy dictionary...
// don't care about the performance...
final HashMap<String, Object> map = new HashMap<String, Object>();
for (final Enumeration<String> e = dict.keys(); e.hasMoreElements();) {
final String key = e.nextElement();
map.put(key, dict.get(key));
}
return map;
}
/**
* run the test
*/
public void runTest() throws Throwable {
/* create the hashtable to put properties in */
Dictionary props = new Hashtable();
/* put service.pid property in hashtable */
props.put(EventConstants.EVENT_TOPIC, topicsToConsume);
/* register the service */
serviceRegistration = bundleContext.registerService
(EventHandler.class.getName(), this, props);
assertNotNull(getName() +" service registration should not be null",
serviceRegistration);
if (serviceRegistration == null) {
fail("Could not get Service Registration ");
}
}
public void updated(String pid, Dictionary<String, ?> props)
throws ConfigurationException {
if (pid == null) {
return;
}
Dictionary<String, String> properties = CastUtils.cast(props);
String queueName = properties.get(AutomaticWorkQueueImpl.PROPERTY_NAME);
if (queues.containsKey(queueName)) {
queues.get(queueName).update(properties);
} else {
AutomaticWorkQueueImpl wq = new AutomaticWorkQueueImpl(queueName);
wq.setShared(true);
wq.update(properties);
wq.addChangeListener(this);
queues.put(pid, wq);
}
}
/**
* Loads the image from the URL <code>getImageURL</code>. This should
* only be invoked from <code>refreshImage</code>.
*/
private void loadImage() {
URL src = getImageURL();
Image newImage = null;
if (src != null) {
Dictionary cache = (Dictionary)getDocument().
getProperty(IMAGE_CACHE_PROPERTY);
if (cache != null) {
newImage = (Image)cache.get(src);
}
else {
newImage = Toolkit.getDefaultToolkit().createImage(src);
if (newImage != null && getLoadsSynchronously()) {
// Force the image to be loaded by using an ImageIcon.
ImageIcon ii = new ImageIcon();
ii.setImage(newImage);
}
}
}
image = newImage;
}
/***************************************************************************
* Helper method that gets the editing dictionary of the current configuration
* from the session. Returns a new empty dictionary if current is set but have
* no dictionary set yet.
**************************************************************************/
private Dictionary<String, Object> getEditingDict(Session session)
{
@SuppressWarnings("unchecked")
Dictionary<String, Object> dict =
(Dictionary<String, Object>) session.getProperties().get(EDITED);
if (dict == null) {
final Configuration cfg = getCurrent(session);
long changeCount = Long.MIN_VALUE;
if (cfg != null) {
changeCount = cfg.getChangeCount();
dict = cfg.getProperties();
}
if (dict == null) {
dict = new Hashtable<String, Object>();
}
setEditingDict(session, dict, changeCount);
}
return dict;
}
@Modified
public void modified(ComponentContext context) {
Dictionary<?, ?> properties = context.getProperties();
if (properties == null) {
return;
}
String strDistributed = Tools.get(properties, DISTRIBUTED);
boolean expectDistributed = Boolean.parseBoolean(strDistributed);
// Start route store during first start or config change
// NOTE: new route store will be empty
if (currentRouteStore == null || expectDistributed != distributed) {
if (expectDistributed) {
currentRouteStore = distributedRouteStore;
} else {
currentRouteStore = localRouteStore;
}
this.distributed = expectDistributed;
log.info("Switched to {} route store", distributed ? "distributed" : "local");
}
}
public int cmdUnset(Dictionary<?, ?> opts,
Reader in,
PrintWriter out,
Session session)
{
int retcode = 1; // 1 initially not set to 0 until end of try block
try {
if (getCurrent(session) == null) {
throw new Exception("No configuration open currently");
}
final String p = (String) opts.get("property");
final Dictionary<String, Object> dict = getEditingDict(session);
final Object o = dict.remove(p);
if (o == null) {
throw new Exception("No property named " + p
+ " in current configuration.");
}
retcode = 0; // Success!
} catch (final Exception e) {
out.print("Unset failed. Details:");
final String reason = e.getMessage();
out.println(reason == null ? "<unknown>" : reason);
} finally {
}
return retcode;
}
/**
* {@inheritDoc}
*/
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
if (config != null) {
// to specify the host one has to add a
// parameter to openhab.cfg like tivo:host=<host>
host = (String) config.get("host");
}
}
/**
* Returns true if all the labels from the label table have the same
* baseline.
*
* @return true if all the labels from the label table have the
* same baseline
* @since 1.6
*/
protected boolean labelsHaveSameBaselines() {
if (!checkedLabelBaselines) {
checkedLabelBaselines = true;
Dictionary dictionary = slider.getLabelTable();
if (dictionary != null) {
sameLabelBaselines = true;
Enumeration elements = dictionary.elements();
int baseline = -1;
while (elements.hasMoreElements()) {
JComponent label = (JComponent) elements.nextElement();
Dimension pref = label.getPreferredSize();
int labelBaseline = label.getBaseline(pref.width,
pref.height);
if (labelBaseline >= 0) {
if (baseline == -1) {
baseline = labelBaseline;
}
else if (baseline != labelBaseline) {
sameLabelBaselines = false;
break;
}
}
else {
sameLabelBaselines = false;
break;
}
}
}
else {
sameLabelBaselines = false;
}
}
return sameLabelBaselines;
}
private Dictionary<String, Object> collectProperties(ServiceReference<?> sr)
{
final Dictionary<String, Object> props = new Hashtable<String, Object>();
final String[] keys = sr.getPropertyKeys();
if (keys != null) {
for (final String key : keys) {
props.put(key, sr.getProperty(key));
}
}
return props;
}
private void registerSkippedTransports(BundleContext bundleContext) {
IntStream.range(0, SKIPPED_SERVICE_COUNT)
.forEach($ -> {
Dictionary<String, Object> properties = new Hashtable<>();
properties.put("skipCarbonStartupResolver", true);
bundleContext.registerService(Transport.class, new FtpTransport(), properties);
});
}
public void open(Dictionary<String, Object> config) {
this.config = config;
String tableName = getValue(config, TABLE_NAME_PROPERTY, TABLE_NAME_DEFAULT);
try (Connection connection = dataSource.getConnection()) {
createStructure(connection);
} catch (Exception e) {
LOGGER.debug("Error creating table " + tableName, e);
}
}
private void configure(UndertowHTTPServerEngine e, Dictionary<String, ?> properties) {
ThreadingParameters threading = createThreadingParameters(properties);
if (threading != null) {
e.setThreadingParameters(threading);
}
Enumeration<String> keys = properties.keys();
while (keys.hasMoreElements()) {
String k = keys.nextElement();
if ("continuationsEnabled".equals(k)) {
e.setContinuationsEnabled(Boolean.parseBoolean((String)properties.get(k)));
} else if ("maxIdleTime".equals(k)) {
e.setMaxIdleTime(Integer.parseInt((String)properties.get(k)));
}
}
}
public boolean match(ServiceReference serviceReference) {
try {
return match(((ServiceReferenceImpl) serviceReference).properties);
} catch (Exception e) {
Dictionary hashtable = new Hashtable();
String[] propertyKeys = serviceReference.getPropertyKeys();
for (int i = RFC1960Filter.EQUALS; i < propertyKeys.length; i += RFC1960Filter.PRESENT) {
hashtable.put(propertyKeys[i], serviceReference.getProperty(propertyKeys[i]));
}
return match(hashtable);
}
}
@Override
public Dictionary getProperties() {
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("allowDuplicateIps", "true");
props.put("monitorHosts", "true");
props.put("probeRate", "40000");
return props;
}
private void setFeedbackValues(Dictionary<Integer, JLabel> labelTable, JLabel labelForFont) {
logger.info("Setting up feedback values for value slider. " + "@IntRangeQuestionPanel");
for (int i = question.getIntRangeMin(); i <= question.getIntRangeMax(); ++i) {
JLabel label = new JLabel("" + i);
label.setFont(labelForFont.getFont().deriveFont(Font.BOLD));
labelTable.put(i, label);
}
}
void set(String p, Dictionary<String,Object> newDict, boolean doReport) {
if (cmDicts.put(p, newDict) == null) {
cmPidSet(this, p, doReport);
} else {
cmPidUpdated(this, p);
}
}
@Test
public void testMatchingFilter() throws Exception {
WebTarget webTarget = createDefaultTarget().path("extended");
assertEquals(
"This should return nothing", 404,
webTarget.request().get().getStatus());
Dictionary<String, Object> properties = new Hashtable<>();
properties.put(JaxrsWhiteboardConstants.JAX_RS_RESOURCE, "true");
properties.put(
JaxrsWhiteboardConstants.JAX_RS_WHITEBOARD_TARGET,
"(service.pid=org.apache.aries.jax.rs.whiteboard.default)");
ServiceRegistration<Object> serviceRegistration =
bundleContext.registerService(
Object.class, new TestAddon(), properties);
try {
assertEquals(
"This should say hello", "Hello extended",
webTarget.request().get().readEntity(String.class));
}
finally {
serviceRegistration.unregister();
}
}
void savePropertyDefault(TransactionController tc, String key, Serializable value)
throws StandardException
{
if (saveServiceProperty(key,value)) return;
Dictionary defaults = (Dictionary)readProperty(tc,AccessFactoryGlobals.DEFAULT_PROPERTY_NAME);
if (defaults == null) defaults = new FormatableHashtable();
if (value==null)
defaults.remove(key);
else
defaults.put(key,value);
if (defaults.size() == 0) defaults = null;
saveProperty(tc,AccessFactoryGlobals.DEFAULT_PROPERTY_NAME,(Serializable)defaults);
}
/**
* Returns true if all the labels from the label table have the same
* baseline.
*
* @return true if all the labels from the label table have the
* same baseline
* @since 1.6
*/
protected boolean labelsHaveSameBaselines() {
if (!checkedLabelBaselines) {
checkedLabelBaselines = true;
Dictionary dictionary = slider.getLabelTable();
if (dictionary != null) {
sameLabelBaselines = true;
Enumeration elements = dictionary.elements();
int baseline = -1;
while (elements.hasMoreElements()) {
JComponent label = (JComponent) elements.nextElement();
Dimension pref = label.getPreferredSize();
int labelBaseline = label.getBaseline(pref.width,
pref.height);
if (labelBaseline >= 0) {
if (baseline == -1) {
baseline = labelBaseline;
}
else if (baseline != labelBaseline) {
sameLabelBaselines = false;
break;
}
}
else {
sameLabelBaselines = false;
break;
}
}
}
else {
sameLabelBaselines = false;
}
}
return sameLabelBaselines;
}