org.apache.commons.configuration2.XMLConfiguration Java Examples

The following examples show how to use org.apache.commons.configuration2.XMLConfiguration. 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: TestCombinedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 7 votes vote down vote up
/**
 * Tests if the configuration was correctly created by the builder.
 *
 * @return the combined configuration obtained from the builder
 */
private CombinedConfiguration checkConfiguration()
        throws ConfigurationException
{
    final CombinedConfiguration compositeConfiguration =
            builder.getConfiguration();

    assertEquals("Number of configurations", 3,
            compositeConfiguration.getNumberOfConfigurations());
    assertEquals(PropertiesConfiguration.class, compositeConfiguration
            .getConfiguration(0).getClass());
    assertEquals(XMLPropertiesConfiguration.class, compositeConfiguration
            .getConfiguration(1).getClass());
    assertEquals(XMLConfiguration.class, compositeConfiguration
            .getConfiguration(2).getClass());

    // check the first configuration
    final PropertiesConfiguration pc =
            (PropertiesConfiguration) compositeConfiguration
                    .getConfiguration(0);
    assertNotNull("No properties configuration", pc);

    // check some properties
    checkProperties(compositeConfiguration);
    return compositeConfiguration;
}
 
Example #2
Source File: TestMultiFileConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether a {@code ConfigurationInterpolator} is created from
 * properties defined in the parameters object if necessary.
 */
@Test
public void testInterpolatorFromParameters() throws ConfigurationException
{
    final BasicBuilderParameters params =
            new MultiFileBuilderParametersImpl().setFilePattern(PATTERN)
                    .setPrefixLookups(
                            Collections.singletonMap(
                                    DefaultLookups.SYSTEM_PROPERTIES
                                            .getPrefix(),
                                    DefaultLookups.SYSTEM_PROPERTIES
                                            .getLookup()));
    final MultiFileConfigurationBuilder<XMLConfiguration> builder =
            new MultiFileConfigurationBuilder<>(
                    XMLConfiguration.class);
    builder.configure(params);
    switchToConfig(1);
    assertEquals("Wrong property", 15,
            builder.getConfiguration().getInt("rowsPerPage"));
}
 
Example #3
Source File: NetworkMessage.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Basic constructor for the message. Only time stamp is computed.
 * 
 * @param config Configuration of the OGWAPI.
 * @param logger Logger of the OGWAPI.
 */
public NetworkMessage(XMLConfiguration config, Logger logger){
	
	// initialise
	
	timeStamp = System.currentTimeMillis();
	valid = true;
	stale = false;
	messageType = NetworkMessage.MESSAGE_TYPE;
	
	sourceOid = null;
	destinationOid = null;
	jsonRepresentation = null;
	
	this.config = config;
	this.logger = logger;
	
}
 
Example #4
Source File: TestReloadingCombinedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a definition configuration which does not contain sources with
 * reloading support.
 */
@Test
public void testNoReloadableSources() throws ConfigurationException
{
    final File testFile =
            ConfigurationAssert
                    .getTestFile("testDigesterConfiguration.xml");
    builder.configure(new CombinedBuilderParametersImpl()
            .setDefinitionBuilder(
                    new FileBasedConfigurationBuilder<>(
                            XMLConfiguration.class))
            .setDefinitionBuilderParameters(
                    new FileBasedBuilderParametersImpl().setFile(testFile)));
    builder.getConfiguration();
    final CombinedReloadingController rc =
            (CombinedReloadingController) builder.getReloadingController();
    assertTrue("Got sub reloading controllers", rc.getSubControllers()
            .isEmpty());
}
 
Example #5
Source File: MailboxListenersLoaderImplTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void aListenerCanBeRegisteredOnSeveralGroups() throws Exception {
    XMLConfiguration configuration = toConfigutation("<listeners>" +
                "<listener>" +
                    "<class>org.apache.james.modules.mailbox.NoopMailboxListener</class>" +
                    "<group>Avengers</group>" +
                "</listener>" +
                "<listener>" +
                    "<class>org.apache.james.modules.mailbox.NoopMailboxListener</class>" +
                    "<group>Fantastic 4</group>" +
                "</listener>" +
            "</listeners>");

    testee.configure(configuration);

    assertThat(eventBus.registeredGroups()).containsExactlyInAnyOrder(new GenericGroup("Avengers"), new GenericGroup("Fantastic 4"));
}
 
Example #6
Source File: Task.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Initialisation method, giving baseline values for fields and generates the task ID.
 * 
 * @param config Configuration of the OGWAPI.
 * @param logger Logger of the OGWAPI.
 * @param connector The {@link eu.bavenir.ogwapi.commons.connectors.AgentConnector AgentConnector} instance to be used.
 * @param sourceOid ID of the object that ordered the job.
 * @param destinationOid ID of the owner.
 * @param actionId The ID of the {@link eu.bavenir.ogwapi.commons.Action action}.
 * @param body Body of the request that was used for creation of this task.
 * @param parameters Parameters used when making a start/stop call through the {@link eu.bavenir.ogwapi.commons.connectors.AgentConnector AgentConnector}.
 */
private void initialize(XMLConfiguration config, Logger logger, AgentConnector connector, String sourceOid, 
		String destinationOid, String actionId, String body, Map<String, String> parameters) {
	startTime = 0;
	endTime = 0;
	runningTime = 0;
	
	creationTime = System.currentTimeMillis();
	
	taskId = UUID.randomUUID().toString();		
	returnValue = null;
	
	this.config = config;
	this.logger = logger;
	this.destinationOid = destinationOid;
	this.body = body;
	this.sourceOid = sourceOid;
	this.actionId = actionId;
	this.connector = connector;
	this.parameters = parameters;
	
}
 
Example #7
Source File: FileConfigurationProvider.java    From james-project with Apache License 2.0 6 votes vote down vote up
public static XMLConfiguration getConfig(InputStream configStream) throws ConfigurationException {
    FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<>(XMLConfiguration.class)
        .configure(new Parameters()
            .xml()
            .setListDelimiterHandler(new DisabledListDelimiterHandler()));
    XMLConfiguration xmlConfiguration = builder.getConfiguration();
    FileHandler fileHandler = new FileHandler(xmlConfiguration);
    fileHandler.load(configStream);
    try {
        configStream.close();
    } catch (IOException ignored) {
        // Ignored
    }

    return xmlConfiguration;
}
 
Example #8
Source File: TestCombinedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether the force-create attribute is taken into account.
 */
@Test
public void testLoadOptionalForceCreate() throws ConfigurationException
{
    final String name = "optionalConfig";
    final Map<String, Object> attrs = new HashMap<>();
    attrs.put("fileName", "nonExisting.xml");
    attrs.put("config-name", name);
    attrs.put("config-optional", Boolean.TRUE);
    attrs.put("config-forceCreate", Boolean.TRUE);
    final BaseHierarchicalConfiguration defConfig =
            createDefinitionConfig("xml", attrs);
    final BasicConfigurationBuilder<? extends BaseHierarchicalConfiguration> defBuilder =
            createDefinitionBuilder(defConfig);
    builder.configure(new CombinedBuilderParametersImpl()
            .setDefinitionBuilder(defBuilder));
    final CombinedConfiguration cc = builder.getConfiguration();
    assertEquals("Wrong number of configurations", 1,
            cc.getNumberOfConfigurations());
    assertTrue("Wrong configuration type",
            cc.getConfiguration(name) instanceof XMLConfiguration);
}
 
Example #9
Source File: NetworkMessageEvent.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This constructor attempts to build this object by parsing incoming JSON. If the parsing operation is not 
 * successful, the result is an object with validity {@link NetworkMessage#valid flag} set to false.
 * 
 * @param json JSON that arrived from the network. 
 * @param config Configuration of the OGWAPI.
 * @param logger Logger of the OGWAPI.
 */
public NetworkMessageEvent(JsonObject json, XMLConfiguration config, Logger logger){
	// always call this guy
	super(config, logger);
	
	// remember the json this message was created from
	jsonRepresentation = json;
	
	eventId = null;
	eventBody = null;
	parameters = new LinkedHashMap<String, String>();
	
	// parse the JSON, or mark this message as invalid
	if (!parseJson(json)){
		
		setValid(false);
	}
}
 
Example #10
Source File: MessageCounter.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Connector
 */
public MessageCounter(XMLConfiguration config, Logger logger) {
	
	this.config = config;
	this.logger = logger;
	
	nmConnector = new NeighbourhoodManagerConnector(config, logger);
	
	logger.info("Trying to load counters from file...");
	CountersPersistence = new Counters(config, logger);
	records = CountersPersistence.getRecords();
	count = CountersPersistence.getCountOfMessages();
	
	// Initialize max counters stored before sending - MAX 500 - DEFAULT 100
	countOfSendingRecords = config.getInt(CONFIG_PARAM_MAXRECORDS, CONFIG_DEF_MAXRECORDS);		
	if(countOfSendingRecords > 500) {
		countOfSendingRecords = 500;
	} 
}
 
Example #11
Source File: TestMultiFileConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether access to multiple configurations works.
 */
@Test
public void testGetConfiguration() throws ConfigurationException
{
    final MultiFileConfigurationBuilder<XMLConfiguration> builder =
            createTestBuilder(null);
    final String key = "rowsPerPage";
    switchToConfig(1);
    assertEquals("Wrong property (1)", 15, builder.getConfiguration()
            .getInt(key));
    switchToConfig(2);
    assertEquals("Wrong property (2)", 25, builder.getConfiguration()
            .getInt(key));
    switchToConfig(3);
    assertEquals("Wrong property (3)", 35, builder.getConfiguration()
            .getInt(key));
}
 
Example #12
Source File: TestCombinedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether an entity resolver can be defined in the definition file.
 */
@Test
public void testCustomEntityResolver() throws ConfigurationException
{
    final File resolverFile =
            ConfigurationAssert.getTestFile("testCCEntityResolver.xml");
    builder.configure(createParameters()
            .setFile(resolverFile));
    final CombinedConfiguration cc = builder.getConfiguration();
    final XMLConfiguration xmlConf =
            (XMLConfiguration) cc.getConfiguration("xml");
    final EntityResolverWithPropertiesTestImpl resolver =
            (EntityResolverWithPropertiesTestImpl) xmlConf
                    .getEntityResolver();
    assertFalse("No lookups", resolver.getInterpolator().getLookups()
            .isEmpty());
}
 
Example #13
Source File: TestFileBasedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether a default encoding can be determined even if it was set for
 * an interface.
 */
@Test
public void testGetDefaultEncodingInterface()
{
    final String encoding = "testEncoding";
    FileBasedConfigurationBuilder.setDefaultEncoding(Configuration.class,
            encoding);
    assertEquals("Wrong default encoding", encoding,
            FileBasedConfigurationBuilder
                    .getDefaultEncoding(XMLConfiguration.class));
    FileBasedConfigurationBuilder.setDefaultEncoding(Configuration.class,
            null);
    assertNull("Default encoding not removed",
            FileBasedConfigurationBuilder
                    .getDefaultEncoding(XMLConfiguration.class));
}
 
Example #14
Source File: TestMultiFileConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether builder events of other types can be received.
 */
@Test
public void testBuilderListenerOtherTypes() throws ConfigurationException
{
    final BuilderEventListenerImpl listener = new BuilderEventListenerImpl();
    final MultiFileConfigurationBuilder<XMLConfiguration> builder =
            createTestBuilder(null);
    builder.addEventListener(ConfigurationBuilderEvent.ANY, listener);
    switchToConfig(1);
    builder.getConfiguration();
    final ConfigurationBuilderEvent event =
            listener.nextEvent(ConfigurationBuilderEvent.CONFIGURATION_REQUEST);
    assertEquals("Wrong event source of request event", builder,
            event.getSource());
    final ConfigurationBuilderResultCreatedEvent createdEvent =
            listener.nextEvent(ConfigurationBuilderResultCreatedEvent.RESULT_CREATED);
    assertEquals("Wrong source of creation event", builder,
            createdEvent.getSource());
    listener.assertNoMoreEvents();
}
 
Example #15
Source File: XmppMessageEngine.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Constructor for the XMPP message engine. It initialises fields and a {@link java.util.Timer Timer} that periodically
 * in interval that is randomly set, executes the {@link #renewPresenceAndRoster() renewPresenceAndRoster} method.
 * 
 * @param objectId String with the object ID that connects via this engine.
 * @param password Password string for authentication.
 * @param config Configuration of the OGWAPI.
 * @param logger Logger of the OGWAPI. 
 * @param connectionDescriptor Connection descriptor that is using this particular instance of engine.
 */
public XmppMessageEngine(String objectId, String password, XMLConfiguration config, Logger logger, 
																	ConnectionDescriptor connectionDescriptor) {
	super(objectId, password, config, logger, connectionDescriptor);
	
	connection = null;
	chatManager = null;
	roster = null;
	
	// initialise map with opened chats
	openedChats = new HashMap<EntityBareJid, Chat>();
	
	// compute the random time in seconds after which a roster will be renewed
	long timeForRosterRenewal = (long) ((Math.random() * ((ROSTER_RELOAD_TIME_MAX - ROSTER_RELOAD_TIME_MIN) + 1)) 
			+ ROSTER_RELOAD_TIME_MIN) * 1000;
	
	logger.finest("The roster for " + objectId + " will be renewed every " 
			+ timeForRosterRenewal + "ms.");
	
	
	// timer for roster renewing
	Timer timerForRosterRenewal = new Timer();
	timerForRosterRenewal.schedule(new TimerTask() {
		@Override
		public void run() {
			renewPresenceAndRoster();
		}
	}, timeForRosterRenewal, timeForRosterRenewal);
	
	// enable debugging if desired
	boolean debuggingEnabled = config.getBoolean(CONFIG_PARAM_XMPPDEBUG, CONFIG_DEF_XMPPDEBUG);
	if (debuggingEnabled) {
		SmackConfiguration.DEBUG = debuggingEnabled;
		logger.config("XMPP debugging enabled.");
	}
}
 
Example #16
Source File: PreDeletionHooksConfigurationTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void fromShouldThrowWhenInvalidHookConfiguration() throws Exception {
    XMLConfiguration configuration = FileConfigurationProvider.getConfig(new ByteArrayInputStream((
        "<preDeletionHooks>" +
            "  <preDeletionHook>" +
            "    <class></class>" +
            "  </preDeletionHook>" +
            "</preDeletionHooks>")
        .getBytes(StandardCharsets.UTF_8)));

    HierarchicalConfiguration<ImmutableNode> invalidConfigurationEntry = new BaseHierarchicalConfiguration();
    configuration.addProperty(PreDeletionHooksConfiguration.CONFIGURATION_ENTRY_NAME, ImmutableList.of(invalidConfigurationEntry));

    assertThatThrownBy(() -> PreDeletionHooksConfiguration.from(configuration))
        .isInstanceOf(ConfigurationException.class);
}
 
Example #17
Source File: CamelMailetContainerModuleTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void getProcessorConfigurationShouldReturnConfigurationWhenSome() throws Exception {
    XMLConfiguration configuration = FileConfigurationProvider.getConfig(new ByteArrayInputStream((
                "<mailetcontainer>" +
                "  <processors>" +
                "    <key>value</key>" +
                "  </processors>" +
                "</mailetcontainer>")
        .getBytes(StandardCharsets.UTF_8)));
    ConfigurationProvider configurationProvider = mock(ConfigurationProvider.class);
    when(configurationProvider.getConfiguration("mailetcontainer")).thenReturn(configuration);

    MailetModuleInitializationOperation testee = new MailetModuleInitializationOperation(configurationProvider,
        mock(CamelCompositeProcessor.class),
        NO_TRANSPORT_CHECKS,
        mock(CamelMailetContainerModule.DefaultProcessorsConfigurationSupplier.class),
        mock(DefaultCamelContext.class));

    HierarchicalConfiguration<ImmutableNode> mailetContextConfiguration = testee.getProcessorConfiguration();
    assertThat(mailetContextConfiguration.getString("key"))
        .isEqualTo("value");
}
 
Example #18
Source File: Api.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Constructor, initialises necessary objects and inserts the {@link org.apache.commons.configuration2.XMLConfiguration
 * configuration}, {@link java.util.logging.Logger logger} and {@link eu.bavenir.ogwapi.xmpp.CommunicationManager
 * CommunicationNode} into the RESTLET {@link org.restlet.Context context}.
 * 
 * All parameters are mandatory, failure to include them will lead to a swift end of application execution.
 * 
 * @param config Configuration object.
 * @param logger Java logger.
 */
public Api(XMLConfiguration config, Logger logger, MessageCounter messageCounter){
	this.config = config;
	this.logger = logger;
	
	// this will initialise the CommunicationNode
	communicationManager = new CommunicationManager(config, logger, messageCounter);
	
	// insert stuff into context
	applicationContext = new Context();
	
	applicationContext.getAttributes().put(CONTEXT_CONFIG, config);
	applicationContext.getAttributes().put(CONTEXT_LOGGER, logger);
	applicationContext.getAttributes().put(CONTEXT_COMMMANAGER, communicationManager);
	
	applicationContext.setLogger(logger);
	
	setContext(applicationContext);
	
	// load authentication challenge scheme method from configuration
	configureChallengeScheme();
}
 
Example #19
Source File: CamelMailetContainerModuleTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void getProcessortConfigurationShouldReturnEmptyWhenNoContextSection() throws Exception {
    ConfigurationProvider configurationProvider = mock(ConfigurationProvider.class);
    when(configurationProvider.getConfiguration("mailetcontainer"))
        .thenReturn(new BaseHierarchicalConfiguration());
    XMLConfiguration defaultConfiguration = FileConfigurationProvider.getConfig(new ByteArrayInputStream((
            "<processors>" +
            "  <key>value</key>" +
            "</processors>")
        .getBytes(StandardCharsets.UTF_8)));

    MailetModuleInitializationOperation testee = new MailetModuleInitializationOperation(configurationProvider,
        mock(CamelCompositeProcessor.class),
        NO_TRANSPORT_CHECKS,
        () -> defaultConfiguration,
        mock(DefaultCamelContext.class));

    assertThat(testee.getProcessorConfiguration())
        .isEqualTo(defaultConfiguration);
}
 
Example #20
Source File: AgentsAgidObjects.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Register the IoT object(s) of the underlying eco-system e.g. devices, VA service.
 * 
 * @param entity Representation of the incoming JSON. List of IoT thing descriptions that are to be registered 
 * (from request).
 * @return All VICINITY identifiers of objects registered under VICINITY Gateway by this call.
 * 
 */
@Post("json")
public Representation accept(Representation entity) {
	
	String attrAgid = getAttribute(ATTR_AGID);
	
	Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER);
	XMLConfiguration config = (XMLConfiguration) getContext().getAttributes().get(Api.CONTEXT_CONFIG);
	
	
	if (attrAgid == null){
		logger.info("AGID: " + attrAgid + " Invalid Agent ID.");
		throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, 
				"Invalid Agent ID.");
	}
	
	if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){
		logger.info("AGID: " + attrAgid + " Invalid object descriptions.");
		
		throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, 
				"Invalid object descriptions");
	}
	
	return storeObjects(entity, logger, config);
}
 
Example #21
Source File: AgentsAgidObjects.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Update the thing descriptions of objects registered under the Agent.
 * 
 * @param entity Representation of the incoming JSON.
 * 
 */
@Put("json")
public Representation store(Representation entity) {
	
	String attrAgid = getAttribute(ATTR_AGID);
	
	Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER);
	XMLConfiguration config = (XMLConfiguration) getContext().getAttributes().get(Api.CONTEXT_CONFIG);
	
	if (attrAgid == null){
		logger.info("AGID: " + attrAgid + " Invalid Agent ID.");
		throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, 
				"Invalid Agent ID.");
	}
	
	if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){
		logger.info("AGID: " + attrAgid + " Invalid object descriptions.");
		
		throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, 
				"Invalid object descriptions");
	}
	
	return heavyweightUpdate(entity, logger, config);
}
 
Example #22
Source File: TestMultiFileConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether managed builders are cached.
 */
@Test
public void testCaching() throws ConfigurationException
{
    final Collection<FileBasedConfigurationBuilder<XMLConfiguration>> managedBuilders =
            new ArrayList<>();
    final MultiFileConfigurationBuilder<XMLConfiguration> builder =
            createBuilderWithAccessToManagedBuilders(managedBuilders);
    switchToConfig(1);
    builder.getConfiguration();
    assertEquals("Wrong number of managed builders (1)", 1,
            managedBuilders.size());
    builder.getConfiguration();
    assertEquals("Wrong number of managed builders (2)", 1,
            managedBuilders.size());
    switchToConfig(2);
    builder.getConfiguration();
    assertEquals("Wrong number of managed builders (3)", 2,
            managedBuilders.size());
}
 
Example #23
Source File: TestReloadingMultiFileConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether parameters passed to the constructor are passed to the
 * super class.
 */
@Test
public void testInitWithParameters() throws ConfigurationException
{
    final ExpressionEngine engine = new XPathExpressionEngine();
    final BasicBuilderParameters params =
            createTestBuilderParameters(new XMLBuilderParametersImpl()
                    .setExpressionEngine(engine));
    final ReloadingMultiFileConfigurationBuilder<XMLConfiguration> builder =
            new ReloadingMultiFileConfigurationBuilder<>(
                    XMLConfiguration.class, params.getParameters());
    switchToConfig(1);
    final XMLConfiguration config = builder.getConfiguration();
    assertSame("Expression engine not set", engine,
            config.getExpressionEngine());
}
 
Example #24
Source File: AgentsAgidObjectsUpdate.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
@Put("json")
public Representation store(Representation entity) {
	
	String attrAgid = getAttribute(ATTR_AGID);
	
	Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER);
	XMLConfiguration config = (XMLConfiguration) getContext().getAttributes().get(Api.CONTEXT_CONFIG);
	
	if (attrAgid == null){
		logger.info("AGID: " + attrAgid + " Invalid Agent ID.");
		throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, 
				"Invalid Agent ID.");
	}
	
	if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){
		logger.info("AGID: " + attrAgid + " Invalid object descriptions.");
		
		throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, 
				"Invalid object descriptions");
	}
	
	return lightweightUpdate(entity, logger, config);
}
 
Example #25
Source File: AgentsAgidObjectsDelete.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Deletes - unregisters the IoT object(s).
 * 
 * @param entity Representation of the incoming JSON. List of IoT thing descriptions that are to be removed 
 * (taken from request).
 * @return Notification of success or failure.
 * 
 */
@Post("json")
public Representation accept(Representation entity) {
	
	String attrAgid = getAttribute(ATTR_AGID);
	
	Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER);
	XMLConfiguration config = (XMLConfiguration) getContext().getAttributes().get(Api.CONTEXT_CONFIG);
	
	if (attrAgid == null){
		logger.info("AGID: " + attrAgid + " Invalid Agent ID.");
		throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, 
				"Invalid Agent ID.");
	}
	
	if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){
		logger.info("AGID: " + attrAgid + " Invalid object descriptions.");
		
		throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, 
				"Invalid object descriptions");
	}
	
	return deleteObjects(entity, logger, config);
}
 
Example #26
Source File: TestMultiFileConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether the ConfigurationInterpolator is reset, too.
 */
@Test
public void testInterpolatorReset()
{
    final BasicBuilderParameters params =
            new MultiFileBuilderParametersImpl().setFilePattern(PATTERN);
    final MultiFileConfigurationBuilder<XMLConfiguration> builder =
            new MultiFileConfigurationBuilder<>(
                    XMLConfiguration.class);
    builder.configure(params);
    final ConfigurationInterpolator interpolator = builder.getInterpolator();
    assertNotNull("No interpolator", interpolator);
    builder.resetParameters();
    assertNotSame("No new interpolator", interpolator,
            builder.getInterpolator());
}
 
Example #27
Source File: TestMultiFileConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a test builder instance which allows access to the managed
 * builders created by it. The returned builder instance overrides the
 * method for creating managed builders. It stores newly created builders in
 * the passed in collection.
 *
 * @param managedBuilders a collection in which to store managed builders
 * @return the test builder instance
 */
private static MultiFileConfigurationBuilder<XMLConfiguration> createBuilderWithAccessToManagedBuilders(
        final Collection<FileBasedConfigurationBuilder<XMLConfiguration>> managedBuilders)
{
    final MultiFileConfigurationBuilder<XMLConfiguration> builder =
            new MultiFileConfigurationBuilder<XMLConfiguration>(
                    XMLConfiguration.class)
            {
                @Override
                protected FileBasedConfigurationBuilder<XMLConfiguration> createInitializedManagedBuilder(
                        final String fileName,
                        final java.util.Map<String, Object> params)
                        throws ConfigurationException
                {
                    final FileBasedConfigurationBuilder<XMLConfiguration> result =
                            super.createInitializedManagedBuilder(fileName,
                                    params);
                    managedBuilders.add(result);
                    return result;
                }
            };
    builder.configure(createTestBuilderParameters(null));
    return builder;
}
 
Example #28
Source File: TestMultiFileConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether builder reset events are handled correctly.
 */
@Test
public void testBuilderListenerReset() throws ConfigurationException
{
    final BuilderEventListenerImpl listener = new BuilderEventListenerImpl();
    final Collection<FileBasedConfigurationBuilder<XMLConfiguration>> managedBuilders =
            new ArrayList<>();
    final MultiFileConfigurationBuilder<XMLConfiguration> builder =
            createBuilderWithAccessToManagedBuilders(managedBuilders);
    switchToConfig(1);
    builder.addEventListener(ConfigurationBuilderEvent.RESET, listener);
    final XMLConfiguration configuration = builder.getConfiguration();
    managedBuilders.iterator().next().resetResult();
    final ConfigurationBuilderEvent event =
            listener.nextEvent(ConfigurationBuilderEvent.RESET);
    assertSame("Wrong event source", builder, event.getSource());
    assertNotSame("Configuration not reset", configuration,
            builder.getConfiguration());
}
 
Example #29
Source File: QuotaMailingListenerConfigurationTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void fromShouldAcceptEmptyThreshold() throws Exception {
    XMLConfiguration xmlConfiguration = FileConfigurationProvider.getConfig(toStream(
        "<configuration>\n" +
            "  <thresholds></thresholds>\n" +
            "  <gracePeriod>3 days</gracePeriod>\n" +
            "</configuration>"));

    QuotaMailingListenerConfiguration result = QuotaMailingListenerConfiguration.from(xmlConfiguration);

    assertThat(result)
        .isEqualTo(QuotaMailingListenerConfiguration.builder()
            .gracePeriod(Duration.ofDays(3))
            .build());
}
 
Example #30
Source File: TestReloadingCombinedConfigurationBuilderFileBased.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether a change in the definition file is detected and causes a
 * reload if a specific builder for the definition configuration is
 * provided.
 */
@Test
public void testReloadDefinitionFileExplicitBuilder()
        throws ConfigurationException, IOException, InterruptedException
{
    final File defFile = folder.newFile();
    builder.configure(parameters.combined().setDefinitionBuilder(
            new ReloadingFileBasedConfigurationBuilder<>(
                    XMLConfiguration.class).configure(parameters.xml()
                    .setReloadingRefreshDelay(0L).setFile(defFile))));
    checkReloadDefinitionFile(defFile);
}