src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
VirtualHostController extends LegacyCategoryController { @Override public LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object) { return new VirtualHostController.LegacyVirtualHost(getManagementController(), object); } VirtualHostController(final LegacyManagementController legacyManagementController,
final Set<TypeController> typeControllers); @Override LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object); @Override @SuppressWarnings("unchecked") Map<String, Object> convertAttributesToNextVersion(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes); static final String TYPE; } | @Test public void convertNextVersionLegacyConfiguredObject() { final LegacyConfiguredObject nextVersionVirtualHost = mock(LegacyConfiguredObject.class); when(nextVersionVirtualHost.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("test"); final LegacyConfiguredObject converted = _virtualHostController.convertNextVersionLegacyConfiguredObject(nextVersionVirtualHost); assertThat(converted, is(notNullValue())); assertThat(converted.getCategory(), is(equalTo(VirtualHostController.TYPE))); assertThat(converted.getAttribute(LegacyConfiguredObject.NAME), is(equalTo("test"))); assertThat(converted.getAttribute("modelVersion"), is(equalTo("6.1"))); assertThat(converted.getAttribute("queue_deadLetterQueueEnabled"), is(equalTo(false))); } |
VirtualHostController extends LegacyCategoryController { @Override @SuppressWarnings("unchecked") public Map<String, Object> convertAttributesToNextVersion(final ConfiguredObject<?> root, final List<String> path, final Map<String, Object> attributes) { final Map<String, String> context = (Map<String, String>) attributes.get(CONTEXT); if (attributes.containsKey(LegacyVirtualHost.QUEUE_DEAD_LETTER_QUEUE_ENABLED) || (context != null && context.containsKey("queue.deadLetterQueueEnabled"))) { final Map<String, Object> converted = new LinkedHashMap<>(attributes); converted.remove("queue_deadLetterQueueEnabled"); if (context != null) { final Map<String, String> convertedContext = new LinkedHashMap<>(context); converted.put("context", convertedContext); convertedContext.remove("queue.deadLetterQueueEnabled"); } return converted; } return attributes; } VirtualHostController(final LegacyManagementController legacyManagementController,
final Set<TypeController> typeControllers); @Override LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object); @Override @SuppressWarnings("unchecked") Map<String, Object> convertAttributesToNextVersion(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes); static final String TYPE; } | @Test public void convertAttributesToNextVersion() { Map<String, Object> attributes = new HashMap<>(); attributes.put(LegacyConfiguredObject.NAME, "test"); attributes.put("queue_deadLetterQueueEnabled", true); Map<String, String> context = new HashMap<>(); context.put("queue.deadLetterQueueEnabled", "true"); context.put("virtualhost.housekeepingCheckPeriod", "30"); attributes.put(LegacyConfiguredObject.CONTEXT, context); final ConfiguredObject<?> root = mock(ConfiguredObject.class); final List<String> path = Collections.singletonList("test-vhn"); Map<String, Object> converted = _virtualHostController.convertAttributesToNextVersion(root, path, attributes); assertThat(converted, is(notNullValue())); assertThat(converted.get(LegacyConfiguredObject.NAME), is(equalTo("test"))); assertThat(converted.containsKey("queue_deadLetterQueueEnabled"), is(equalTo(false))); Object contextObject = converted.get(LegacyConfiguredObject.CONTEXT); assertThat(converted, is(instanceOf(Map.class))); Map<?,?> convertedContext = (Map<?,?>)contextObject; assertThat(convertedContext.get("virtualhost.housekeepingCheckPeriod"), is(equalTo("30"))); assertThat(convertedContext.containsKey("queue.deadLetterQueueEnabled"), is(equalTo(false))); } |
BrokerController extends LegacyCategoryController { @Override public LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object) { return new LegacyBroker(getManagementController(), object); } BrokerController(final LegacyManagementController legacyManagementController,
final Set<TypeController> typeControllers); @Override LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object); static final String TYPE; } | @Test public void convertNextVersionLegacyConfiguredObject() { final LegacyConfiguredObject object = mock(LegacyConfiguredObject.class); when(object.getAttribute("modelVersion")).thenReturn("foo"); final Map<String, String> context = new HashMap<>(); context.put("qpid.port.sessionCountLimit", "512"); context.put("qpid.port.heartbeatDelay", "10000"); context.put("qpid.port.closeWhenNoRoute", "true"); when(object.getAttribute("context")).thenReturn(context); final BrokerController controller = new BrokerController(_legacyVersionManagementController, Collections.emptySet()); assertThat(controller.getCategory(), is(equalTo("Broker"))); final LegacyConfiguredObject converted = controller.convertFromNextVersion(object); assertThat(converted.getAttribute("modelVersion"), is(equalTo(MODEL_VERSION))); assertThat(converted.getAttribute("connection.sessionCountLimit"), is(equalTo(512))); assertThat(converted.getAttribute("connection.heartBeatDelay"), is(equalTo(10000L))); assertThat(converted.getAttribute("connection.closeWhenNoRoute"), is(equalTo(true))); } |
BrokerController extends LegacyCategoryController { @Override @SuppressWarnings("unchecked") protected Map<String, Object> convertAttributesToNextVersion(final ConfiguredObject<?> root, final List<String> path, final Map<String, Object> attributes) { final Map<String, Object> converted = new LinkedHashMap<>(attributes); final Map<String, String> context = (Map<String, String>) converted.get(LegacyConfiguredObject.CONTEXT); final Map<String, String> newContext = new LinkedHashMap<>(); if (context != null) { newContext.putAll(context); } converted.put(LegacyConfiguredObject.CONTEXT, newContext); for (String attributeName : BROKER_ATTRIBUTES_MOVED_INTO_CONTEXT.keySet()) { Object value = converted.remove(attributeName); if (value != null) { newContext.put(BROKER_ATTRIBUTES_MOVED_INTO_CONTEXT.get(attributeName), String.valueOf(value)); } } converted.remove("statisticsReportingResetEnabled"); final Object statisticsReportingPeriod = converted.get("statisticsReportingPeriod"); if (statisticsReportingPeriod != null && !newContext.containsKey("qpid.broker.statisticsReportPattern") && (ConverterHelper.toInt(statisticsReportingPeriod) > 0 || ConverterHelper.isContextVariable( statisticsReportingPeriod))) { newContext.put("qpid.broker.statisticsReportPattern", "messagesIn=${messagesIn}, bytesIn=${bytesIn:byteunit}, messagesOut=${messagesOut}, bytesOut=${bytesOut:byteunit}"); } return converted; } BrokerController(final LegacyManagementController legacyManagementController,
final Set<TypeController> typeControllers); @Override LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object); static final String TYPE; } | @Test public void convertAttributesToNextVersion() { final Map<String, Object> attributes = new HashMap<>(); attributes.put("connection.sessionCountLimit", 512); attributes.put("connection.heartBeatDelay", 10000L); attributes.put("connection.closeWhenNoRoute", true); attributes.put("statisticsReportingResetEnabled", true); attributes.put("statisticsReportingEnabled", true); final BrokerController controller = new BrokerController(_legacyVersionManagementController, Collections.emptySet()); assertThat(controller.getCategory(), is(equalTo("Broker"))); final Map<String, Object> converted = controller.convertAttributesToNextVersion(mock(ConfiguredObject.class), Collections.emptyList(), attributes); assertThat(converted.size(), is(equalTo(2))); assertThat(converted.get("statisticsReportingEnabled"), is(equalTo(true))); final Map<String, String> expectedContext = new HashMap<>(); expectedContext.put("qpid.port.sessionCountLimit", "512"); expectedContext.put("qpid.port.heartbeatDelay", "10000"); expectedContext.put("qpid.port.closeWhenNoRoute", "true"); assertThat(converted.get("context"), is(equalTo(expectedContext))); } |
LegacyCategoryController extends GenericCategoryController { @Override public String[] getParentCategories() { return _parentCategories; } LegacyCategoryController(final LegacyManagementController managementController,
final String name,
final String[] parentCategories,
final String defaultType,
final Set<TypeController> typeControllers); @Override String[] getParentCategories(); } | @Test public void getParentCategories() { assertThat(_controller.getParentCategories(), is(equalTo(new String[]{BrokerController.TYPE}))); } |
LegacyCategoryController extends GenericCategoryController { @Override protected LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object) { return new GenericLegacyConfiguredObject(getManagementController(), object, getCategory()); } LegacyCategoryController(final LegacyManagementController managementController,
final String name,
final String[] parentCategories,
final String defaultType,
final Set<TypeController> typeControllers); @Override String[] getParentCategories(); } | @Test public void convertNextVersionLegacyConfiguredObject() { final LegacyConfiguredObject node = mock(LegacyConfiguredObject.class); when(node.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("test"); final LegacyConfiguredObject converted = _controller.convertNextVersionLegacyConfiguredObject(node); assertThat(converted, is(notNullValue())); assertThat(converted.getCategory(), is(equalTo(VirtualHostNode.TYPE))); assertThat(converted.getAttribute(LegacyConfiguredObject.NAME), is(equalTo("test"))); } |
ConsumerController implements CategoryController { @Override public String getCategory() { return TYPE; } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void getCategory() { assertThat(_controller.getCategory(), is(equalTo("Consumer"))); } |
ConsumerController implements CategoryController { @Override public String getNextVersionCategory() { return TYPE; } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void getNextVersionCategory() { assertThat(_controller.getNextVersionCategory(), is(equalTo("Consumer"))); } |
ConsumerController implements CategoryController { @Override public String getDefaultType() { return null; } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void getDefaultType() { assertThat(_controller.getDefaultType(), is(equalTo(null))); } |
ConsumerController implements CategoryController { @Override public String[] getParentCategories() { return new String[]{SessionController.TYPE, QueueController.TYPE}; } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void getParentCategories() { assertThat(_controller.getParentCategories(), is(equalTo(new String[]{"Session", "Queue"}))); } |
ConsumerController implements CategoryController { @Override public LegacyManagementController getManagementController() { return _managementController; } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void getManagementController() { assertThat(_controller.getManagementController(), is(equalTo(_managementController))); } |
ConsumerController implements CategoryController { @Override public Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters) throws ManagementException { final Collection<String> hierarchy = _managementController.getCategoryHierarchy(root, TYPE); final String consumerName = path.size() == hierarchy.size() ? path.get(hierarchy.size() - 1) : null; final String queueName = path.size() >= hierarchy.size() - 1 ? path.get(hierarchy.size() - 2) : null; final String sessionName = path.size() >= hierarchy.size() - 2 ? path.get(hierarchy.size() - 3) : null; List<String> virtualHostPath = path; if (virtualHostPath.size() > hierarchy.size() - 3) { virtualHostPath = virtualHostPath.subList(0, hierarchy.size() - 3); } final Object queues = getNextVersionManagementController().get(root, "Queue", virtualHostPath, Collections.emptyMap()); Collection<LegacyConfiguredObject> consumers; if (queues instanceof LegacyConfiguredObject) { consumers = getQueueConsumers(sessionName, queueName, consumerName, (LegacyConfiguredObject) queues); } else if (queues instanceof Collection) { consumers = ((Collection<?>) queues).stream() .map(LegacyConfiguredObject.class::cast) .map(q -> getQueueConsumers(sessionName, queueName, consumerName, q)) .flatMap(Collection::stream) .collect(Collectors.toList()); } else { throw createInternalServerErrorManagementException("Unexpected consumer format from next version"); } return consumers; } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void get() { final List<String> path = Arrays.asList("my-vhn", "my-vh", "my-session", "my-queue", "my-consumer"); final Map<String, List<String>> parameters = Collections.singletonMap("actuals", Collections.singletonList("true")); final List<String> hierarchy = Arrays.asList("virtualhostnode", "virtualhost", "session", "queue", "consumer"); when(_managementController.getCategoryHierarchy(_root, "Consumer")).thenReturn(hierarchy); final LegacyConfiguredObject session = mock(LegacyConfiguredObject.class); when(session.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-session"); when(session.getCategory()).thenReturn("Session"); final LegacyConfiguredObject consumer = mock(LegacyConfiguredObject.class); when(consumer.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-consumer"); when(consumer.getAttribute("session")).thenReturn(session); final Collection<LegacyConfiguredObject> consumers = Collections.singletonList(consumer); final LegacyConfiguredObject queue1 = mock(LegacyConfiguredObject.class); when(queue1.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-queue1"); final LegacyConfiguredObject queue2 = mock(LegacyConfiguredObject.class); when(queue2.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-queue"); when(queue2.getChildren(ConsumerController.TYPE)).thenReturn(consumers); final Collection<LegacyConfiguredObject> queues = Arrays.asList(queue1, queue2); doReturn(queues).when(_nextVersionManagementController) .get(eq(_root), eq("Queue"), eq(Arrays.asList("my-vhn", "my-vh")), eq(Collections.emptyMap())); final Object result = _controller.get(_root, path, parameters); assertThat(result, is(instanceOf(Collection.class))); Collection<?> consumerItems = (Collection<?>)result; assertThat(consumerItems.size(), is(equalTo(1))); final Object object = consumerItems.iterator().next(); assertThat(object, is(instanceOf(LegacyConfiguredObject.class))); final LegacyConfiguredObject consumerObject = (LegacyConfiguredObject) object; assertThat(consumerObject.getAttribute(LegacyConfiguredObject.NAME), is(equalTo("my-consumer"))); assertThat(consumerObject.getCategory(), is(equalTo("Consumer"))); } |
ConsumerController implements CategoryController { @Override public int delete(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters) throws ManagementException { throw createBadRequestManagementException("Consumer cannot be deleted via management interfaces"); } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void delete() { final List<String> path = Arrays.asList("my-vhn", "my-vh", "my-queue", "my-consumer"); final Map<String, List<String>> parameters = Collections.emptyMap(); try { _controller.delete(_root, path, parameters); fail("Consumer cannot be deleted from REST"); } catch (ManagementException e) { } } |
ConsumerController implements CategoryController { @Override public LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root, List<String> path, Map<String, Object> attributes, boolean isPost) throws ManagementException { throw createBadRequestManagementException("Consumer cannot be created or updated via management interfaces"); } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void createOrUpdate() { final List<String> path = Arrays.asList("my-vhn", "my-vh", "my-queue", "my-consumer"); final Map<String, Object> attributes = Collections.singletonMap(LegacyConfiguredObject.NAME, "my-consumer" ); try { _controller.createOrUpdate(_root, path, attributes, true); fail("Consumer cannot be created from REST"); } catch (ManagementException e) { } } |
ConsumerController implements CategoryController { @Override public ManagementResponse invoke(ConfiguredObject<?> root, List<String> path, String operation, Map<String, Object> parameters, boolean isPost, final boolean isSecure) throws ManagementException { Object result = get( root, path, Collections.emptyMap()); if (result instanceof Collection && ((Collection)result).size() == 1) { LegacyConfiguredObject object = (LegacyConfiguredObject) ((Collection<?>)result).iterator().next(); return object.invoke(operation, parameters, isSecure); } throw createBadRequestManagementException(String.format("Cannot find consumer for path %s", String.join("/" + path))); } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void invoke() { final List<String> path = Arrays.asList("my-vhn", "my-vh", "my-session", "my-queue", "my-consumer"); final List<String> hierarchy = Arrays.asList("virtualhostnode", "virtualhost", "session", "queue", "consumer"); when(_managementController.getCategoryHierarchy(_root, "Consumer")).thenReturn(hierarchy); final LegacyConfiguredObject consumer = mock(LegacyConfiguredObject.class); final LegacyConfiguredObject queue = mock(LegacyConfiguredObject.class); final LegacyConfiguredObject session = mock(LegacyConfiguredObject.class); when(queue.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-queue"); when(consumer.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-consumer"); when(consumer.getAttribute("session")).thenReturn(session); when(session.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-session"); final Object stats = mock(Object.class); final ManagementResponse statistics = new ControllerManagementResponse(ResponseType.DATA, stats); when(consumer.invoke(eq("getStatistics"), eq(Collections.emptyMap()), eq(false))).thenReturn(statistics); final Collection<LegacyConfiguredObject> consumers = Collections.singletonList(consumer); when(queue.getChildren(ConsumerController.TYPE)).thenReturn(consumers); final Collection<LegacyConfiguredObject> queues = Collections.singletonList(queue); doReturn(queues).when(_nextVersionManagementController) .get(eq(_root), eq("Queue"), eq(Arrays.asList("my-vhn", "my-vh")), eq(Collections.emptyMap())); ManagementResponse response = _controller.invoke(_root, path, "getStatistics", Collections.emptyMap(), false, false); assertThat(response, is(notNullValue())); assertThat(response.getResponseCode(), is(equalTo(200))); assertThat(response.getBody(), is(notNullValue())); assertThat(response.getBody(), is(equalTo(stats))); } |
ConsumerController implements CategoryController { @Override public Object getPreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters) throws ManagementException { throw createBadRequestManagementException("Preferences not supported for Consumer"); } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void getPreferences() { final List<String> path = Arrays.asList("my-vhn", "my-vh", "my-queue", "my-consumer"); final Map<String, List<String>> parameters = Collections.emptyMap(); try { _controller.getPreferences(_root, path, parameters); fail("Consumer preferences are unknown"); } catch (ManagementException e) { } } |
ConsumerController implements CategoryController { @Override public void setPreferences(ConfiguredObject<?> root, List<String> path, Object preferences, Map<String, List<String>> parameters, boolean isPost) throws ManagementException { throw createBadRequestManagementException("Preferences not supported for Consumer"); } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void setPreferences() { final List<String> path = Arrays.asList("my-vhn", "my-vh", "my-queue", "my-consumer"); final Map<String, List<String>> parameters = Collections.emptyMap(); try { _controller.setPreferences(_root, path, Collections.singletonMap("Consumer-Preferences", Collections.singleton(Collections.singletonMap("value", "foo"))), parameters, true); fail("Consumer preferences are unknown"); } catch (ManagementException e) { } } |
ConsumerController implements CategoryController { @Override public int deletePreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters) throws ManagementException { throw createBadRequestManagementException("Preferences not supported for Consumer"); } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void deletePreferences() { final List<String> path = Arrays.asList("my-vhn", "my-vh", "my-queue", "my-consumer"); final Map<String, List<String>> parameters = Collections.emptyMap(); try { _controller.deletePreferences(_root, path, parameters); fail("Consumer preferences are unknown"); } catch (ManagementException e) { } } |
ConsumerController implements CategoryController { @Override public LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject) { return new LegacyConsumer(getManagementController(), nextVersionObject); } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void convertFromNextVersion() { final LegacyConfiguredObject session = mock(LegacyConfiguredObject.class); when(session.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-session"); when(session.getCategory()).thenReturn("Session"); final LegacyConfiguredObject queue1 = mock(LegacyConfiguredObject.class); when(queue1.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-queue1"); final LegacyConfiguredObject queue2 = mock(LegacyConfiguredObject.class); when(queue2.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-queue"); final LegacyConfiguredObject nextVersionConfiguredObject = mock(LegacyConfiguredObject.class); when(nextVersionConfiguredObject.getAttribute("session")).thenReturn(session); when(nextVersionConfiguredObject.getAttribute("queue")).thenReturn(queue2); when(nextVersionConfiguredObject.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("test-consumer"); when(nextVersionConfiguredObject.getParent(eq("Queue"))).thenReturn(queue2); final Collection<LegacyConfiguredObject> consumers = Collections.singletonList(nextVersionConfiguredObject); when(queue2.getChildren(ConsumerController.TYPE)).thenReturn(consumers); final LegacyConfiguredObject convertedSession = mock(LegacyConfiguredObject.class); when(_managementController.convertFromNextVersion(session)).thenReturn(convertedSession); final LegacyConfiguredObject convertedQueue = mock(LegacyConfiguredObject.class); when(_managementController.convertFromNextVersion(queue2)).thenReturn(convertedQueue); final LegacyConfiguredObject converted = _controller.convertFromNextVersion(nextVersionConfiguredObject); LegacyConfiguredObject sessionParent = converted.getParent("Session"); LegacyConfiguredObject queueParent = converted.getParent("Queue"); assertThat(sessionParent, is(equalTo(convertedSession))); assertThat(queueParent, is(equalTo(convertedQueue))); LegacyConfiguredObject sessionAttribute = (LegacyConfiguredObject)converted.getAttribute("session"); LegacyConfiguredObject queueAttribute = (LegacyConfiguredObject)converted.getAttribute("queue"); assertThat(sessionAttribute, is(equalTo(convertedSession))); assertThat(queueAttribute, is(equalTo(convertedQueue))); } |
QueueController extends DestinationController { @Override protected LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object) { return new LegacyQueue(getManagementController(), object); } QueueController(final LegacyManagementController legacyManagementController,
final Set<TypeController> typeControllers); @Override Map<String, Object> convertAttributesToNextVersion(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes); static final String TYPE; } | @Test public void convertNextVersionLegacyConfiguredObject() { final String exchangeName = "testExchange"; final String alternateExchangeName = "altExchange"; final String queueName = "testQueue"; final String bindingKey = "testBindingKey"; final LegacyConfiguredObject nextVersionQueue = mock(LegacyConfiguredObject.class); final Binding nextVersionBinding = mock(Binding.class); final LegacyConfiguredObject nextVersionVirtualHost = mock(LegacyConfiguredObject.class); final LegacyConfiguredObject nextVersionAlternateExchange = mock(LegacyConfiguredObject.class); final LegacyConfiguredObject nextVersionExchange = mock(LegacyConfiguredObject.class); final AlternateBinding alternateDestination = mock(AlternateBinding.class); when(alternateDestination.getDestination()).thenReturn(alternateExchangeName); when(nextVersionQueue.getCategory()).thenReturn(QueueController.TYPE); when(nextVersionQueue.getParent(VirtualHostController.TYPE)).thenReturn(nextVersionVirtualHost); when(nextVersionQueue.getAttribute("alternateBinding")).thenReturn(alternateDestination); when(nextVersionQueue.getAttribute(AbstractConfiguredObject.NAME)).thenReturn(queueName); when(nextVersionQueue.getAttribute("overflowPolicy")).thenReturn("PRODUCER_FLOW_CONTROL"); when(nextVersionQueue.getAttribute("maximumQueueDepthBytes")).thenReturn(10000L); when(nextVersionQueue.getAttribute("context")).thenReturn(Collections.singletonMap("queue.queueFlowResumeLimit", "70")); when(nextVersionQueue.getAttribute("messageGroupType")).thenReturn("SHARED_GROUPS"); when(nextVersionQueue.getAttribute("messageGroupKeyOverride")).thenReturn("test"); when(nextVersionBinding.getDestination()).thenReturn(queueName); when(nextVersionBinding.getBindingKey()).thenReturn(bindingKey); when(nextVersionExchange.getAttribute(AbstractConfiguredObject.NAME)).thenReturn(exchangeName); when(nextVersionExchange.getCategory()).thenReturn(ExchangeController.TYPE); when(nextVersionExchange.getAttribute("bindings")).thenReturn(Collections.singletonList(nextVersionBinding)); when(nextVersionAlternateExchange.getCategory()).thenReturn(ExchangeController.TYPE); when(nextVersionAlternateExchange.getCategory()).thenReturn(ExchangeController.TYPE); when(nextVersionAlternateExchange.getAttribute(LegacyConfiguredObject.NAME)).thenReturn(alternateExchangeName); when(nextVersionVirtualHost.getChildren(ExchangeController.TYPE)).thenReturn(Arrays.asList(nextVersionExchange, nextVersionAlternateExchange)); when(nextVersionVirtualHost.getChildren(QueueController.TYPE)).thenReturn(Collections.singletonList(nextVersionExchange)); final LegacyConfiguredObject convertedExchange = mock(LegacyConfiguredObject.class); final LegacyConfiguredObject convertedAltExchange = mock(LegacyConfiguredObject.class); final LegacyConfiguredObject convertedQueue = mock(LegacyConfiguredObject.class); when(_legacyVersionManagementController.convertFromNextVersion(nextVersionQueue)).thenReturn( convertedQueue); when(_legacyVersionManagementController.convertFromNextVersion(nextVersionAlternateExchange)).thenReturn( convertedAltExchange); when(_legacyVersionManagementController.convertFromNextVersion(nextVersionExchange)).thenReturn(convertedExchange); final LegacyConfiguredObject destination = _queueController.convertFromNextVersion(nextVersionQueue); assertThat(destination.getAttribute("alternateExchange"), is(equalTo(convertedAltExchange))); assertThat(destination.getAttribute("queueFlowControlSizeBytes"), is(equalTo(10000L))); assertThat(destination.getAttribute("queueFlowResumeSizeBytes"), is(equalTo(7000L))); assertThat(destination.getAttribute("messageGroupSharedGroups"), is(equalTo(true))); assertThat(destination.getAttribute("messageGroupKey"), is(equalTo("test"))); final Collection<LegacyConfiguredObject> children = destination.getChildren(BindingController.TYPE); assertThat(children.size(), is(equalTo(1))); final LegacyConfiguredObject o = children.iterator().next(); assertThat(o.getCategory(), is(equalTo(BindingController.TYPE))); assertThat(o.getAttribute(AbstractConfiguredObject.NAME), is(equalTo(bindingKey))); assertThat(o.getAttribute("queue"), is(equalTo(convertedQueue))); assertThat(o.getAttribute("exchange"), is(equalTo(convertedExchange))); } |
QueueController extends DestinationController { @Override public Map<String, Object> convertAttributesToNextVersion(final ConfiguredObject<?> root, final List<String> path, final Map<String, Object> attributes) { Map<String, Object> converted = new LinkedHashMap<>(attributes); Object queueFlowControlSizeBytes = converted.remove("queueFlowControlSizeBytes"); Object queueFlowResumeSizeBytes = converted.remove("queueFlowResumeSizeBytes"); if (queueFlowControlSizeBytes != null) { long queueFlowControlSizeBytesValue = ConverterHelper.toLong(queueFlowControlSizeBytes); if (queueFlowControlSizeBytesValue > 0) { if (queueFlowResumeSizeBytes != null) { long queueFlowResumeSizeBytesValue = ConverterHelper.toLong(queueFlowResumeSizeBytes); double ratio = ((double) queueFlowResumeSizeBytesValue) / ((double) queueFlowControlSizeBytesValue); String flowResumeLimit = String.format("%.2f", ratio * 100.0); Object context = converted.get("context"); Map<String, String> contextMap; if (context instanceof Map) { contextMap = (Map) context; } else { contextMap = new LinkedHashMap<>(); converted.put("context", contextMap); } contextMap.put("queue.queueFlowResumeLimit", flowResumeLimit); } converted.put("overflowPolicy", "PRODUCER_FLOW_CONTROL"); converted.put("maximumQueueDepthBytes", queueFlowControlSizeBytes); } } if (converted.containsKey("messageGroupKey")) { if (converted.containsKey("messageGroupSharedGroups") && ConverterHelper.toBoolean(converted.remove("messageGroupSharedGroups"))) { converted.put("messageGroupType", "SHARED_GROUPS"); } else { converted.put("messageGroupType", "STANDARD"); } Object oldMessageGroupKey = converted.remove("messageGroupKey"); if (!"JMSXGroupId".equals(oldMessageGroupKey)) { converted.put("messageGroupKeyOverride", oldMessageGroupKey); } } else { converted.put("messageGroupType", "NONE"); } return super.convertAttributesToNextVersion(root, path, converted); } QueueController(final LegacyManagementController legacyManagementController,
final Set<TypeController> typeControllers); @Override Map<String, Object> convertAttributesToNextVersion(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes); static final String TYPE; } | @Test public void convertAttributesToNextVersion() { final Map<String, Object> attributes = new HashMap<>(); attributes.put("queueFlowResumeSizeBytes", 7000L); attributes.put("queueFlowControlSizeBytes", 10000L); attributes.put("messageGroupSharedGroups", true); attributes.put("messageGroupKey", "groupKey"); attributes.put("name", "testQueue"); final ConfiguredObject<?> root = mock(ConfiguredObject.class); final List path = Arrays.asList("my-vhn", "my-vh", "testQueue"); final Map<String, Object> converted = _queueController.convertAttributesToNextVersion(root, path, attributes); assertThat(converted, is(notNullValue())); assertThat(converted.get("overflowPolicy"), is(equalTo("PRODUCER_FLOW_CONTROL"))); assertThat(converted.get("maximumQueueDepthBytes"), is(equalTo(10000L))); assertThat(converted.get("messageGroupType"), is(equalTo("SHARED_GROUPS"))); assertThat(converted.get("messageGroupKeyOverride"), is(equalTo("groupKey"))); assertThat(converted.get("name"), is(equalTo("testQueue"))); final Object contextObject = converted.get("context"); assertThat(contextObject, is(instanceOf(Map.class))); final Map<?,?> context =(Map<?,?>)contextObject; NumberFormat formatter = NumberFormat.getInstance(); formatter.setMinimumFractionDigits(2); assertThat(context.get("queue.queueFlowResumeLimit"), is(equalTo(formatter.format(70L)))); } |
BindingController implements CategoryController { @Override public String getCategory() { return TYPE; } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes,
final boolean isPost); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void getCategory() { assertThat(_controller.getCategory(), is(equalTo("Binding"))); } |
BindingController implements CategoryController { @Override public String getNextVersionCategory() { return null; } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes,
final boolean isPost); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void getNextVersionCategory() { assertThat(_controller.getNextVersionCategory(), is(equalTo(null))); } |
BindingController implements CategoryController { @Override public String getDefaultType() { return null; } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes,
final boolean isPost); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void getDefaultType() { assertThat(_controller.getDefaultType(), is(equalTo(null))); } |
BindingController implements CategoryController { @Override public String[] getParentCategories() { return new String[]{ExchangeController.TYPE, QueueController.TYPE}; } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes,
final boolean isPost); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void getParentCategories() { assertThat(_controller.getParentCategories(), is(equalTo(new String[]{"Exchange", "Queue"}))); } |
BindingController implements CategoryController { @Override public LegacyManagementController getManagementController() { return _managementController; } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes,
final boolean isPost); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void getManagementController() { assertThat(_controller.getManagementController(), is(equalTo(_managementController))); } |
BindingController implements CategoryController { @Override public Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters) throws ManagementException { final Collection<String> hierarchy = _managementController.getCategoryHierarchy(root, getCategory()); final String bindingName = path.size() == hierarchy.size() ? path.get(hierarchy.size() - 1) : null; final String queueName = path.size() >= hierarchy.size() - 1 ? path.get(hierarchy.size() - 2) : null; final List<String> exchangePath = path.size() >= hierarchy.size() - 2 ? path.subList(0, hierarchy.size() - 2) : path; return getExchangeBindings(root, exchangePath, queueName, bindingName); } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes,
final boolean isPost); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void get() { final List<String> path = Arrays.asList("my-vhn", "my-vh", "my-exchange", "my-queue", "my-binding"); final Map<String, List<String>> parameters = Collections.singletonMap("actuals", Collections.singletonList("true")); final List<String> hierarchy = Arrays.asList("virtualhostnode", "virtualhost", "exchange", "queue", "binding"); when(_managementController.getCategoryHierarchy(_root, "Binding")).thenReturn(hierarchy); final LegacyConfiguredObject exchange1 = mock(LegacyConfiguredObject.class); when(exchange1.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("foo"); when(exchange1.getCategory()).thenReturn("Exchange"); final LegacyConfiguredObject exchange2 = mock(LegacyConfiguredObject.class); when(exchange2.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-exchange"); when(exchange2.getCategory()).thenReturn("Exchange"); final LegacyConfiguredObject vh = mock(LegacyConfiguredObject.class); when(exchange2.getParent("VirtualHost")).thenReturn(vh); final LegacyConfiguredObject queue = mock(LegacyConfiguredObject.class); when(queue.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-queue"); final Collection<LegacyConfiguredObject> queues = Collections.singletonList(queue); when(vh.getChildren("Queue")).thenReturn(queues); final Binding binding = mock(Binding.class); when(binding.getName()).thenReturn("my-binding"); when(binding.getDestination()).thenReturn("my-queue"); when(binding.getBindingKey()).thenReturn("my-binding"); final Collection<Binding> bindings = Collections.singletonList(binding); when(exchange2.getAttribute("bindings")).thenReturn(bindings); final Collection<LegacyConfiguredObject> exchanges = Arrays.asList(exchange1, exchange2); doReturn(exchanges).when(_nextVersionManagementController).get(any(), eq("exchange"), any(), any()); final Object readResult = _controller.get(_root, path, parameters); assertThat(readResult, is(instanceOf(Collection.class))); final Collection<?> exchangeBindings = (Collection<?>) readResult; assertThat(exchangeBindings.size(), is(equalTo(1))); final Object object = exchangeBindings.iterator().next(); assertThat(object, is(instanceOf(LegacyConfiguredObject.class))); final LegacyConfiguredObject bindingObject = (LegacyConfiguredObject) object; assertThat(bindingObject.getAttribute(LegacyConfiguredObject.NAME), is(equalTo("my-binding"))); } |
BindingController implements CategoryController { @Override public LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root, final List<String> path, final Map<String, Object> attributes, final boolean isPost) throws ManagementException { if (path.contains("*")) { throw createBadRequestManagementException("Wildcards in path are not supported for post and put requests"); } final Collection<String> hierarchy = _managementController.getCategoryHierarchy(root, getCategory()); if (path.size() < hierarchy.size() - 2) { throw createBadRequestManagementException(String.format("Cannot create binding for path %s", String.join("/" + path))); } String queueName = null; if (path.size() > hierarchy.size() - 2) { queueName = path.get(hierarchy.size() - 2); } if (queueName == null) { queueName = (String) attributes.get("queue"); } if (queueName == null) { throw createBadRequestManagementException( "Queue is required for binding creation. Please specify queue either in path or in binding attributes"); } final List<String> exchangePath = path.subList(0, hierarchy.size() - 2); final LegacyConfiguredObject nextVersionExchange = getNextVersionObject(root, exchangePath, ExchangeController.TYPE); final List<String> queuePath = new ArrayList<>(path.subList(0, hierarchy.size() - 3)); queuePath.add(queueName); final LegacyConfiguredObject nextVersionQueue = getNextVersionObject(root, queuePath, QueueController.TYPE); String bindingKey = (String) attributes.get(GenericLegacyConfiguredObject.NAME); if (bindingKey == null) { bindingKey = path.size() == hierarchy.size() ? path.get(hierarchy.size() - 1) : null; } if (bindingKey == null) { bindingKey = ""; } final Map<String, Object> parameters = new LinkedHashMap<>(); parameters.put("bindingKey", bindingKey); parameters.put("destination", queueName); Map<String, Object> arguments = null; if (attributes.containsKey("arguments")) { Object args = attributes.get("arguments"); if (args instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> argumentsMap = (Map<String, Object>) args; arguments = new HashMap<>(argumentsMap); if (!arguments.isEmpty()) { parameters.put("arguments", arguments); } } else { throw createBadRequestManagementException(String.format("Unexpected attributes specified : %s", args)); } } parameters.put("replaceExistingArguments", !isPost); ManagementResponse response = nextVersionExchange.invoke("bind", parameters, true); final boolean newBindings = Boolean.TRUE.equals(response.getBody()); if (!newBindings) { return null; } return new LegacyBinding(_managementController, nextVersionExchange, nextVersionQueue, bindingKey, arguments); } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes,
final boolean isPost); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void createOrUpdate() { final List<String> path = Arrays.asList("my-vhn", "my-vh", "my-exchange"); final Map<String, Object> attributes = new HashMap<>(); attributes.put("name", "my-binding"); attributes.put("queue", "my-queue"); final List<String> hierarchy = Arrays.asList("virtualhostnode", "virtualhost", "exchange", "queue", "binding"); doReturn(hierarchy).when(_managementController).getCategoryHierarchy(_root, "Binding"); final LegacyConfiguredObject exchange = mock(LegacyConfiguredObject.class); when(exchange.getCategory()).thenReturn("Exchange"); when(exchange.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-exchange"); final ManagementResponse bindingResult = new ControllerManagementResponse(ResponseType.DATA, Boolean.TRUE); when(exchange.invoke(eq("bind"), any(), eq(true))).thenReturn(bindingResult); final LegacyConfiguredObject queue = mock(LegacyConfiguredObject.class); when(queue.getCategory()).thenReturn("Queue"); when(queue.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-queue"); doReturn(exchange).when(_nextVersionManagementController).get(any(), eq("exchange"), any(), any()); doReturn(queue).when(_nextVersionManagementController).get(any(), eq("queue"), any(), any()); when(_managementController.convertFromNextVersion(exchange)).thenReturn(exchange); when(_managementController.convertFromNextVersion(queue)).thenReturn(queue); final LegacyConfiguredObject binding = _controller.createOrUpdate(_root, path, attributes, true); assertThat(binding, is(notNullValue())); assertThat(binding.getAttribute(LegacyConfiguredObject.NAME), is(equalTo("my-binding"))); Object queueObject = binding.getAttribute("queue"); Object exchangeObject = binding.getAttribute("exchange"); assertThat(queueObject, is(instanceOf(LegacyConfiguredObject.class))); assertThat(exchangeObject, is(instanceOf(LegacyConfiguredObject.class))); assertThat(((LegacyConfiguredObject) queueObject).getAttribute(LegacyConfiguredObject.NAME), is(equalTo("my-queue"))); assertThat(((LegacyConfiguredObject) exchangeObject).getAttribute(LegacyConfiguredObject.NAME), is(equalTo("my-exchange"))); } |
BindingController implements CategoryController { @Override public int delete(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters) throws ManagementException { if (path.contains("*")) { throw createBadRequestManagementException("Wildcards in path are not supported for delete requests"); } final Collection<String> hierarchy = _managementController.getCategoryHierarchy(root, getCategory()); if (path.size() < hierarchy.size() - 2) { throw createBadRequestManagementException(String.format("Cannot delete binding for path %s", String.join("/", path))); } final String bindingName = path.size() == hierarchy.size() ? path.get(hierarchy.size() - 1) : null; final String queueName = path.get(hierarchy.size() - 2); final List<String> ids = parameters.get(GenericLegacyConfiguredObject.ID); final List<String> exchangePath = path.subList(0, hierarchy.size() - 2); final LegacyConfiguredObject exchange = getNextVersionObject(root, exchangePath, ExchangeController.TYPE); final AtomicInteger counter = new AtomicInteger(); if (ids != null && !ids.isEmpty()) { @SuppressWarnings("unchecked") Collection<Binding> bindings = (Collection<Binding>) exchange.getAttribute("bindings"); if (bindings != null) { bindings.stream() .filter(b -> ids.contains(String.valueOf(generateBindingId(exchange, b.getDestination(), b.getBindingKey())))) .forEach(b -> { Map<String, Object> params = new LinkedHashMap<>(); params.put("bindingKey", b.getBindingKey()); params.put("destination", b.getDestination()); ManagementResponse r = exchange.invoke("unbind", params, true); if (Boolean.TRUE.equals(r.getBody())) { counter.incrementAndGet(); } }); } } else if (bindingName != null) { Map<String, Object> params = new LinkedHashMap<>(); params.put("bindingKey", bindingName); params.put("destination", queueName); ManagementResponse response = exchange.invoke("unbind", params, true); if (Boolean.TRUE.equals(response.getBody())) { counter.incrementAndGet(); } } else { throw createBadRequestManagementException("Only deletion by binding full path or ids is supported"); } return counter.get(); } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes,
final boolean isPost); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void delete() { final List<String> path = Arrays.asList("my-vhn", "my-vh", "my-exchange", "my-queue", "my-binding"); final List<String> hierarchy = Arrays.asList("virtualhostnode", "virtualhost", "exchange", "queue", "binding"); doReturn(hierarchy).when(_managementController).getCategoryHierarchy(_root, "Binding"); final LegacyConfiguredObject exchange = mock(LegacyConfiguredObject.class); when(exchange.getCategory()).thenReturn("Exchange"); when(exchange.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-exchange"); final ManagementResponse unbindingResult = new ControllerManagementResponse(ResponseType.DATA, Boolean.TRUE); when(exchange.invoke(eq("unbind"), any(), eq(true))).thenReturn(unbindingResult); doReturn(exchange).when(_nextVersionManagementController).get(any(), eq("exchange"), any(), any()); int result = _controller.delete(_root, path, Collections.emptyMap()); assertThat(result, is(equalTo(1))); verify(exchange).invoke(eq("unbind"), any(), eq(true)); } |
BindingController implements CategoryController { @Override public ManagementResponse invoke(ConfiguredObject<?> root, List<String> path, String operation, Map<String, Object> parameters, boolean isPost, final boolean isSecure) throws ManagementException { Object result = get(root, path, Collections.emptyMap()); if (result instanceof Collection && ((Collection)result).size() == 1) { LegacyConfiguredObject object = (LegacyConfiguredObject) ((Collection<?>)result).iterator().next(); return object.invoke(operation, parameters, isSecure); } throw createBadRequestManagementException(String.format("Operation '%s' cannot be invoked for Binding path '%s'", operation, String.join("/", path))); } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes,
final boolean isPost); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void invoke() { final List<String> path = Arrays.asList("my-vhn", "my-vh", "my-exchange", "my-queue", "my-binding"); final String operationName = "getStatistics"; final Map<String, Object> parameters = Collections.emptyMap(); final List<String> hierarchy = Arrays.asList("virtualhostnode", "virtualhost", "exchange", "queue", "binding"); when(_managementController.getCategoryHierarchy(_root, "Binding")).thenReturn(hierarchy); final LegacyConfiguredObject exchange = mock(LegacyConfiguredObject.class); when(exchange.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-exchange"); when(exchange.getCategory()).thenReturn("Exchange"); final LegacyConfiguredObject vh = mock(LegacyConfiguredObject.class); when(exchange.getParent("VirtualHost")).thenReturn(vh); final LegacyConfiguredObject queue = mock(LegacyConfiguredObject.class); when(queue.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("my-queue"); final Collection<LegacyConfiguredObject> queues = Collections.singletonList(queue); when(vh.getChildren("Queue")).thenReturn(queues); final Binding binding = mock(Binding.class); when(binding.getName()).thenReturn("my-binding"); when(binding.getDestination()).thenReturn("my-queue"); when(binding.getBindingKey()).thenReturn("my-binding"); final Collection<Binding> bindings = Collections.singletonList(binding); when(exchange.getAttribute("bindings")).thenReturn(bindings); final Collection<LegacyConfiguredObject> exchanges = Collections.singletonList(exchange); doReturn(exchanges).when(_nextVersionManagementController).get(any(), eq("exchange"), any(), any()); final ManagementResponse result = _controller.invoke(_root, path, operationName, parameters, true, true); assertThat(result, is(notNullValue())); assertThat(result.getResponseCode(), is(equalTo(200))); assertThat(result.getBody(), is(notNullValue())); assertThat(result.getBody(), is(equalTo(Collections.emptyMap()))); } |
BindingController implements CategoryController { @Override public Object getPreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters) throws ManagementException { throw createBadRequestManagementException("Preferences not supported for Binding"); } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes,
final boolean isPost); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void getPreferences() { final List<String> path = Arrays.asList("vhn", "vh", "exchange", "queue", "binding"); final Map<String, List<String>> parameters = Collections.emptyMap(); try { _controller.getPreferences(_root, path, parameters); fail("Binding preferences are unknown"); } catch (ManagementException e) { } } |
BindingController implements CategoryController { @Override public void setPreferences(ConfiguredObject<?> root, List<String> path, Object preferences, Map<String, List<String>> parameters, boolean isPost) throws ManagementException { throw createBadRequestManagementException("Preferences not supported for Binding"); } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes,
final boolean isPost); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void setPreferences() { final List<String> path = Arrays.asList("vhn", "vh", "exchange", "queue", "binding"); final Map<String, List<String>> parameters = Collections.emptyMap(); try { _controller.setPreferences(_root, path, Collections.singletonMap("Binding-Preferences", Collections.singleton(Collections.singletonMap("value", "foo"))), parameters, true); fail("Binding preferences are unknown"); } catch (ManagementException e) { } } |
BindingController implements CategoryController { @Override public int deletePreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters) throws ManagementException { throw createBadRequestManagementException("Preferences not supported for Binding"); } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, Object> attributes,
final boolean isPost); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root,
List<String> path,
String operation,
Map<String, Object> parameters,
boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root,
List<String> path,
Object preferences,
Map<String, List<String>> parameters,
boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root,
List<String> path,
Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; } | @Test public void deletePreferences() { final List<String> path = Arrays.asList("vhn", "vh", "exchange", "queue", "binding"); final Map<String, List<String>> parameters = Collections.emptyMap(); try { _controller.deletePreferences(_root, path, parameters); fail("Binding preferences are unknown"); } catch (ManagementException e) { } } |
LegacyManagementController extends AbstractLegacyConfiguredObjectController { @Override protected Map<String, List<String>> convertQueryParameters(final Map<String, List<String>> parameters) { return parameters; } LegacyManagementController(final ManagementController nextVersionManagementController,
final String modelVersion); @Override Object formatConfiguredObject(final Object content,
final Map<String, List<String>> parameters,
final boolean isSecureOrAllowedOnInsecureChannel); } | @Test public void convertQueryParameters() { final Map<String, List<String>> parameters = Collections.singletonMap("depth", Collections.singletonList("1")); final Map<String, List<String>> converted = _controller.convertQueryParameters(parameters); assertThat(converted, is(equalTo(parameters))); } |
LegacyManagementController extends AbstractLegacyConfiguredObjectController { @Override public Object formatConfiguredObject(final Object content, final Map<String, List<String>> parameters, final boolean isSecureOrAllowedOnInsecureChannel) { final int depth = getIntParameterFromRequest(parameters, DEPTH_PARAM, DEFAULT_DEPTH); final int oversizeThreshold = getIntParameterFromRequest(parameters, OVERSIZE_PARAM, DEFAULT_OVERSIZE); final boolean actuals = Boolean.parseBoolean(getParameter(ACTUALS_PARAM, parameters)); final String excludeInheritedContextParameter = getParameter(EXCLUDE_INHERITED_CONTEXT_PARAM, parameters); final boolean excludeInheritedContext = excludeInheritedContextParameter == null || Boolean.parseBoolean(excludeInheritedContextParameter); final boolean responseAsList = Boolean.parseBoolean(getParameter(SINGLETON_MODEL_OBJECT_RESPONSE_AS_LIST, parameters)); return formatConfiguredObject(content, isSecureOrAllowedOnInsecureChannel, depth, oversizeThreshold, actuals, excludeInheritedContext, responseAsList); } LegacyManagementController(final ManagementController nextVersionManagementController,
final String modelVersion); @Override Object formatConfiguredObject(final Object content,
final Map<String, List<String>> parameters,
final boolean isSecureOrAllowedOnInsecureChannel); } | @Test public void formatConfiguredObject() { final String objectName = "test-object"; final String hostName = "test-vhn"; final Map<String, List<String>> parameters = Collections.singletonMap("depth", Collections.singletonList("1")); final LegacyConfiguredObject object = mock(LegacyConfiguredObject.class); final LegacyConfiguredObject vhn = mock(LegacyConfiguredObject.class); when(object.getAttributeNames()).thenReturn(Arrays.asList(LegacyConfiguredObject.NAME, LegacyConfiguredObject.TYPE)); when(object.getAttribute(LegacyConfiguredObject.NAME)).thenReturn(objectName); when(object.getAttribute(LegacyConfiguredObject.TYPE)).thenReturn("Broker"); when(object.getCategory()).thenReturn("Broker"); when(object.getChildren("VirtualHostNode")).thenReturn(Collections.singletonList(vhn)); when(vhn.getAttributeNames()).thenReturn(Arrays.asList(LegacyConfiguredObject.NAME, LegacyConfiguredObject.TYPE)); when(vhn.getAttribute(LegacyConfiguredObject.NAME)).thenReturn(hostName); when(vhn.getAttribute(LegacyConfiguredObject.TYPE)).thenReturn("VirtualHostNode"); when(vhn.getCategory()).thenReturn("VirtualHostNode"); Object data = _controller.formatConfiguredObject(object, parameters, true); assertThat(data, is(instanceOf(Map.class))); Map<?, ?> formatted = (Map<?, ?>) data; assertThat(formatted.get(LegacyConfiguredObject.NAME), is(equalTo(objectName))); assertThat(formatted.get(LegacyConfiguredObject.TYPE), is(equalTo("Broker"))); Object vhns = formatted.get("virtualhostnodes"); assertThat(vhns, is(instanceOf(Collection.class))); Collection<?> nodes = (Collection<?>)vhns; assertThat(nodes.size(), is(equalTo(1))); Object node = nodes.iterator().next(); assertThat(node, is(instanceOf(Map.class))); Map<?, ?> formattedNode = (Map<?, ?>) node; assertThat(formattedNode.get(LegacyConfiguredObject.NAME), is(equalTo(hostName))); assertThat(formattedNode.get(LegacyConfiguredObject.TYPE), is(equalTo("VirtualHostNode"))); } |
LegacyCategoryControllerFactory implements CategoryControllerFactory { @Override public CategoryController createController(final String type, final LegacyManagementController legacyManagementController) { if (SUPPORTED_CATEGORIES.containsKey(type)) { return new LegacyCategoryController(legacyManagementController, type, SUPPORTED_CATEGORIES.get(type), DEFAULT_TYPES.get(type), legacyManagementController.getTypeControllersByCategory(type)); } else { throw new IllegalArgumentException(String.format("Unsupported type '%s'", type)); } } @Override CategoryController createController(final String type,
final LegacyManagementController legacyManagementController); @Override Set<String> getSupportedCategories(); @Override String getModelVersion(); @Override String getType(); static final String CATEGORY_BROKER; static final String CATEGORY_AUTHENTICATION_PROVIDER; static final String CATEGORY_PORT; static final String CATEGORY_VIRTUAL_HOST; static final Map<String, String> SUPPORTED_CATEGORIES; static final Map<String, String> DEFAULT_TYPES; } | @Test public void createController() { SUPPORTED_CATEGORIES.keySet().forEach(category-> { final CategoryController controller = _factory.createController(category, _nextVersionManagementController); assertThat(controller.getCategory(), is(equalTo(category))); }); } |
GenericCategoryController implements CategoryController { @Override public String getCategory() { return _name; } protected GenericCategoryController(final LegacyManagementController managementController,
final ManagementController nextVersionManagementController,
final String name,
final String defaultType,
final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root,
final List<String> path,
final String operation,
final Map<String, Object> parameters,
final boolean isPost,
final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Object preferences,
final Map<String, List<String>> parameters,
final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); } | @Test public void getCategory() { assertThat(_controller.getCategory(), is(equalTo(TEST_CATEGORY))); } |
GenericCategoryController implements CategoryController { @Override public String getDefaultType() { return _defaultType; } protected GenericCategoryController(final LegacyManagementController managementController,
final ManagementController nextVersionManagementController,
final String name,
final String defaultType,
final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root,
final List<String> path,
final String operation,
final Map<String, Object> parameters,
final boolean isPost,
final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Object preferences,
final Map<String, List<String>> parameters,
final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); } | @Test public void getDefaultType() { assertThat(_controller.getDefaultType(), is(equalTo(DEFAULT_TYPE))); } |
GenericCategoryController implements CategoryController { @Override public LegacyManagementController getManagementController() { return _managementController; } protected GenericCategoryController(final LegacyManagementController managementController,
final ManagementController nextVersionManagementController,
final String name,
final String defaultType,
final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root,
final List<String> path,
final String operation,
final Map<String, Object> parameters,
final boolean isPost,
final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Object preferences,
final Map<String, List<String>> parameters,
final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); } | @Test public void getManagementController() { assertThat(_controller.getManagementController(), is(equalTo(_managementController))); } |
GenericCategoryController implements CategoryController { @Override public Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters) throws ManagementException { final Object content = _nextVersionManagementController.get(root, getNextVersionCategory(), path, convertQueryParametersToNextVersion(parameters)); return convert(content); } protected GenericCategoryController(final LegacyManagementController managementController,
final ManagementController nextVersionManagementController,
final String name,
final String defaultType,
final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root,
final List<String> path,
final String operation,
final Map<String, Object> parameters,
final boolean isPost,
final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Object preferences,
final Map<String, List<String>> parameters,
final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); } | @Test public void get() { final List<String> path = Arrays.asList("test1", "test2"); final Map<String, List<String>> parameters = Collections.singletonMap("testParam", Collections.singletonList("testValue")); final LegacyConfiguredObject result = mock(LegacyConfiguredObject.class); when(result.getAttribute(LegacyConfiguredObject.TYPE)).thenReturn(DEFAULT_TYPE); final LegacyConfiguredObject convertedResult = mock(LegacyConfiguredObject.class); when(_nextVersionManagementController.get(_root, TEST_CATEGORY, path, parameters)).thenReturn(result); when(_typeController.convertFromNextVersion(result)).thenReturn(convertedResult); final Object readResult = _controller.get(_root, path, parameters); assertThat(readResult, is(equalTo(convertedResult))); verify(_nextVersionManagementController).get(_root, TEST_CATEGORY, path, parameters); } |
GenericCategoryController implements CategoryController { @Override public LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root, List<String> path, Map<String, Object> attributes, boolean isPost) throws ManagementException { final Map<String, Object> body = convertAttributesToNextVersion(root, path, attributes); final Object configuredObject = _nextVersionManagementController.createOrUpdate(root, getNextVersionCategory(), path, body, isPost); if (configuredObject instanceof LegacyConfiguredObject) { LegacyConfiguredObject object = (LegacyConfiguredObject) configuredObject; return convertFromNextVersion(object); } return null; } protected GenericCategoryController(final LegacyManagementController managementController,
final ManagementController nextVersionManagementController,
final String name,
final String defaultType,
final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root,
final List<String> path,
final String operation,
final Map<String, Object> parameters,
final boolean isPost,
final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Object preferences,
final Map<String, List<String>> parameters,
final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); } | @Test public void createOrUpdate() { final List<String> path = Arrays.asList("test1", "test2"); final Map<String, Object> attributes = Collections.singletonMap("test", "testValue"); final LegacyConfiguredObject result = mock(LegacyConfiguredObject.class); final LegacyConfiguredObject convertedResult = mock(LegacyConfiguredObject.class); when(result.getAttribute(LegacyConfiguredObject.TYPE)).thenReturn(DEFAULT_TYPE); when(_typeController.convertAttributesToNextVersion(_root, path, attributes)).thenReturn(attributes); when(_typeController.convertFromNextVersion(result)).thenReturn(convertedResult); when(_nextVersionManagementController.createOrUpdate(_root, TEST_CATEGORY, path, attributes, false)) .thenReturn(result); when(_typeController.convertFromNextVersion(result)).thenReturn(convertedResult); final Object createResult = _controller.createOrUpdate(_root, path, attributes, false); assertThat(createResult, is(equalTo(convertedResult))); verify(_nextVersionManagementController).createOrUpdate(_root, TEST_CATEGORY, path, attributes, false); } |
GenericCategoryController implements CategoryController { @Override public int delete(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters) throws ManagementException { return _nextVersionManagementController.delete(root, getNextVersionCategory(), path, convertQueryParametersToNextVersion(parameters)); } protected GenericCategoryController(final LegacyManagementController managementController,
final ManagementController nextVersionManagementController,
final String name,
final String defaultType,
final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root,
final List<String> path,
final String operation,
final Map<String, Object> parameters,
final boolean isPost,
final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Object preferences,
final Map<String, List<String>> parameters,
final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); } | @Test public void delete() { final List<String> path = Arrays.asList("test1", "test2"); final Map<String, List<String>> parameters = Collections.singletonMap("testParam", Collections.singletonList("testValue")); final int result = 1; when(_nextVersionManagementController.delete(_root, TEST_CATEGORY, path, parameters)).thenReturn(result); final Object deleteResult = _controller.delete(_root, path, parameters); assertThat(deleteResult, is(equalTo(result))); verify(_nextVersionManagementController).delete(_root, TEST_CATEGORY, path, parameters); } |
GenericCategoryController implements CategoryController { @Override public ManagementResponse invoke(final ConfiguredObject<?> root, final List<String> path, final String operation, final Map<String, Object> parameters, final boolean isPost, final boolean isSecure) throws ManagementException { Object result = get(root, path, Collections.emptyMap()); if (result instanceof LegacyConfiguredObject) { final LegacyConfiguredObject legacyConfiguredObject = (LegacyConfiguredObject) result; return legacyConfiguredObject.invoke(operation, parameters, isSecure); } else { throw createBadRequestManagementException(String.format("Configured object %s/%s is not found", getManagementController().getCategoryMapping( getCategory()), String.join("/", path))); } } protected GenericCategoryController(final LegacyManagementController managementController,
final ManagementController nextVersionManagementController,
final String name,
final String defaultType,
final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root,
final List<String> path,
final String operation,
final Map<String, Object> parameters,
final boolean isPost,
final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Object preferences,
final Map<String, List<String>> parameters,
final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); } | @Test public void invoke() { final List<String> path = Arrays.asList("test1", "test2"); final String operationName = "testOperation"; final Map<String, Object> operationParameters = Collections.singletonMap("testParam", "testValue"); final LegacyConfiguredObject result = mock(LegacyConfiguredObject.class); when(result.getAttribute(LegacyConfiguredObject.TYPE)).thenReturn(DEFAULT_TYPE); final LegacyConfiguredObject convertedResult = mock(LegacyConfiguredObject.class); when(_nextVersionManagementController.get(eq(_root), eq(TEST_CATEGORY), eq(path), eq(Collections.emptyMap()))).thenReturn(result); when(_typeController.convertFromNextVersion(result)).thenReturn(convertedResult); final Object operationValue = "testValue"; final ManagementResponse operationResult = new ControllerManagementResponse(ResponseType.DATA, operationValue); when(convertedResult.invoke(operationName, operationParameters, true)).thenReturn(operationResult); final ManagementResponse response = _controller.invoke(_root, path, operationName, operationParameters, true, true); assertThat(response, is(notNullValue())); assertThat(response.getResponseCode(), is(equalTo(200))); assertThat(response.getBody(), is(equalTo(operationValue))); verify(_nextVersionManagementController).get(_root, TEST_CATEGORY, path, Collections.emptyMap()); verify(convertedResult).invoke(operationName, operationParameters, true); } |
GenericCategoryController implements CategoryController { @Override public Object getPreferences(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters) throws ManagementException { return _nextVersionManagementController.getPreferences(root, getNextVersionCategory(), path, parameters); } protected GenericCategoryController(final LegacyManagementController managementController,
final ManagementController nextVersionManagementController,
final String name,
final String defaultType,
final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root,
final List<String> path,
final String operation,
final Map<String, Object> parameters,
final boolean isPost,
final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Object preferences,
final Map<String, List<String>> parameters,
final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); } | @Test public void getPreferences() { final List<String> path = Arrays.asList("test1", "test2"); final Map<String, List<String>> parameters = Collections.singletonMap("testParam", Collections.singletonList("testValue")); final Object result = mock(Object.class); when(_nextVersionManagementController.getPreferences(_root, TEST_CATEGORY, path, parameters)).thenReturn(result); final Object preferences = _controller.getPreferences(_root, path, parameters); assertThat(preferences, is(equalTo(result))); verify(_nextVersionManagementController).getPreferences(_root, TEST_CATEGORY, path, parameters); } |
GenericCategoryController implements CategoryController { @Override @SuppressWarnings("unchecked") public void setPreferences(final ConfiguredObject<?> root, final List<String> path, final Object preferences, final Map<String, List<String>> parameters, final boolean isPost) throws ManagementException { _nextVersionManagementController.setPreferences(root, getNextVersionCategory(), path, preferences, parameters, isPost); } protected GenericCategoryController(final LegacyManagementController managementController,
final ManagementController nextVersionManagementController,
final String name,
final String defaultType,
final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root,
final List<String> path,
final String operation,
final Map<String, Object> parameters,
final boolean isPost,
final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Object preferences,
final Map<String, List<String>> parameters,
final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); } | @Test public void setPreferences() { final List<String> path = Arrays.asList("test1", "test2"); final Map<String, List<String>> parameters = Collections.singletonMap("testParam", Collections.singletonList("testValue")); final Object preferences = mock(Object.class); _controller.setPreferences(_root, path, preferences, parameters, true); verify(_nextVersionManagementController).setPreferences(_root, TEST_CATEGORY, path, preferences, parameters, true); } |
GenericCategoryController implements CategoryController { @Override public int deletePreferences(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters) throws ManagementException { return _nextVersionManagementController.deletePreferences(root, getNextVersionCategory(), path, parameters); } protected GenericCategoryController(final LegacyManagementController managementController,
final ManagementController nextVersionManagementController,
final String name,
final String defaultType,
final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root,
final List<String> path,
final String operation,
final Map<String, Object> parameters,
final boolean isPost,
final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Object preferences,
final Map<String, List<String>> parameters,
final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); } | @Test public void deletePreferences() { final List<String> path = Arrays.asList("test1", "test2"); final Map<String, List<String>> parameters = Collections.singletonMap("testParam", Collections.singletonList("testValue")); _controller.deletePreferences(_root, path, parameters); verify(_nextVersionManagementController).deletePreferences(_root, TEST_CATEGORY, path, parameters); } |
GenericCategoryController implements CategoryController { protected ManagementController getNextVersionManagementController() { return _nextVersionManagementController; } protected GenericCategoryController(final LegacyManagementController managementController,
final ManagementController nextVersionManagementController,
final String name,
final String defaultType,
final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root,
final List<String> path,
final String operation,
final Map<String, Object> parameters,
final boolean isPost,
final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Object preferences,
final Map<String, List<String>> parameters,
final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); } | @Test public void getNextVersionManagementController() { assertThat(_controller.getNextVersionManagementController(), is(equalTo(_nextVersionManagementController))); } |
GenericCategoryController implements CategoryController { protected Map<String, Object> convertAttributesToNextVersion(final ConfiguredObject<?> root, final List<String> path, final Map<String, Object> attributes) { TypeController typeController = getTypeController(attributes); if (typeController != null) { return typeController.convertAttributesToNextVersion(root, path, attributes); } return attributes; } protected GenericCategoryController(final LegacyManagementController managementController,
final ManagementController nextVersionManagementController,
final String name,
final String defaultType,
final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root,
List<String> path,
Map<String, Object> attributes,
boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root,
final List<String> path,
final String operation,
final Map<String, Object> parameters,
final boolean isPost,
final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root,
final List<String> path,
final Object preferences,
final Map<String, List<String>> parameters,
final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root,
final List<String> path,
final Map<String, List<String>> parameters); } | @Test public void convertAttributesToNextVersion() { final List<String> path = Arrays.asList("test1", "test2"); final Map<String, Object> attributes = Collections.singletonMap("testParam", "testValue"); final Map<String, Object> convertedAttributes = Collections.singletonMap("testParam", "testValue2"); when(_typeController.convertAttributesToNextVersion(_root, path, attributes)).thenReturn(convertedAttributes); final Map<String, Object> converted = _controller.convertAttributesToNextVersion(_root, path, attributes); assertThat(converted, is(equalTo(convertedAttributes))); } |
RestUserPreferenceHandler { public void handlePUT(ConfiguredObject<?> target, RequestInfo requestInfo, Object providedObject) { UserPreferences userPreferences = target.getUserPreferences(); if (userPreferences == null) { throw new NotFoundException("User preferences are not available"); } final List<String> preferencesParts = requestInfo.getPreferencesParts(); if (preferencesParts.size() == 2) { if (!(providedObject instanceof Map)) { throw new IllegalArgumentException("expected object"); } Map<String, Object> providedAttributes = (Map<String, Object>) providedObject; String type = preferencesParts.get(0); String name = preferencesParts.get(1); ensureAttributeMatches(providedAttributes, "name", name); ensureAttributeMatches(providedAttributes, "type", type); Preference preference = PreferenceFactory.fromAttributes(target, providedAttributes); awaitFuture(userPreferences.replaceByTypeAndName(type, name , preference)); } else if (preferencesParts.size() == 1) { String type = preferencesParts.get(0); if (!(providedObject instanceof List)) { throw new IllegalArgumentException("expected a list of objects"); } List<Preference> replacementPreferences = validateAndConvert(target, type, (List<Object>) providedObject); awaitFuture(userPreferences.replaceByType(type, replacementPreferences)); } else if (preferencesParts.size() == 0) { if (!(providedObject instanceof Map)) { throw new IllegalArgumentException("expected object"); } List<Preference> replacementPreferences = validateAndConvert(target, (Map<String, Object>) providedObject); awaitFuture(userPreferences.replace(replacementPreferences)); } else { throw new IllegalArgumentException(String.format("unexpected path '%s'", Joiner.on("/").join(preferencesParts))); } } RestUserPreferenceHandler(final long preferenceOperationTimeout); void handleDELETE(final UserPreferences userPreferences, final RequestInfo requestInfo); void handlePUT(ConfiguredObject<?> target, RequestInfo requestInfo, Object providedObject); void handlePOST(ConfiguredObject<?> target, RequestInfo requestInfo, Object providedObject); Object handleGET(UserPreferences userPreferences, RequestInfo requestInfo); } | @Test public void testPutWithVisibilityList_ValidGroup() throws Exception { final RequestInfo requestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Arrays.asList("X-testtype", "myprefname") ); final Map<String, Object> pref = new HashMap<>(); pref.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); pref.put(Preference.VISIBILITY_LIST_ATTRIBUTE, Collections.singletonList(MYGROUP_SERIALIZATION)); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { _handler.handlePUT(_configuredObject, requestInfo, pref); Set<Preference> preferences = awaitPreferenceFuture(_userPreferences.getPreferences()); assertEquals("Unexpected number of preferences", (long) 1, (long) preferences.size()); Preference prefModel = preferences.iterator().next(); final Set<Principal> visibilityList = prefModel.getVisibilityList(); assertEquals("Unexpected number of principals in visibility list", (long) 1, (long) visibilityList.size()); Principal principal = visibilityList.iterator().next(); assertEquals("Unexpected member of visibility list", MYGROUP, principal.getName()); return null; } } ); }
@Test public void testPutWithVisibilityList_InvalidGroup() throws Exception { final RequestInfo requestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Arrays.asList("X-testtype", "myprefname") ); final Map<String, Object> pref = new HashMap<>(); pref.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); pref.put(Preference.VISIBILITY_LIST_ATTRIBUTE, Collections.singletonList("Invalid Group")); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { try { _handler.handlePUT(_configuredObject, requestInfo, pref); fail("Expected exception not thrown"); } catch (IllegalArgumentException e) { } return null; } } ); }
@Test public void testPutByTypeAndName() throws Exception { final String prefName = "myprefname"; final RequestInfo requestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Arrays.asList("X-testtype", prefName) ); final Map<String, Object> pref = new HashMap<>(); pref.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { _handler.handlePUT(_configuredObject, requestInfo, pref); Set<Preference> preferences = awaitPreferenceFuture(_userPreferences.getPreferences()); assertEquals("Unexpected number of preferences", (long) 1, (long) preferences.size()); Preference prefModel = preferences.iterator().next(); assertEquals("Unexpected preference name", prefName, prefModel.getName()); return null; } } ); }
@Test public void testReplaceViaPutByTypeAndName() throws Exception { final String prefName = "myprefname"; final RequestInfo requestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Arrays.asList("X-testtype", prefName) ); final Map<String, Object> pref = new HashMap<>(); pref.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); final Preference createdPreference = Subject.doAs(_subject, new PrivilegedAction<Preference>() { @Override public Preference run() { _handler.handlePUT(_configuredObject, requestInfo, pref); Set<Preference> preferences = awaitPreferenceFuture (_userPreferences.getPreferences()); assertEquals("Unexpected number of preferences", (long) 1, (long) preferences.size()); Preference prefModel = preferences.iterator().next(); assertEquals("Unexpected preference name", prefName, prefModel.getName()); return prefModel; } } ); final Map<String, Object> replacementPref = new HashMap<>(); replacementPref.put(Preference.ID_ATTRIBUTE, createdPreference.getId().toString()); replacementPref.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); final String changedDescription = "Replace that maintains id"; replacementPref.put(Preference.DESCRIPTION_ATTRIBUTE, changedDescription); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { _handler.handlePUT(_configuredObject, requestInfo, replacementPref); Set<Preference> preferences = awaitPreferenceFuture(_userPreferences.getPreferences()); assertEquals("Unexpected number of preferences after update", (long) 1, (long) preferences.size()); Preference updatedPref = preferences.iterator().next(); assertEquals("Unexpected preference id", createdPreference.getId(), updatedPref.getId()); assertEquals("Unexpected preference name", prefName, updatedPref.getName()); assertEquals("Unexpected preference description", changedDescription, updatedPref.getDescription()); return null; } } ); replacementPref.remove(Preference.ID_ATTRIBUTE); final String changedDescription2 = "Replace that omits id"; replacementPref.put(Preference.DESCRIPTION_ATTRIBUTE, changedDescription2); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { _handler.handlePUT(_configuredObject, requestInfo, replacementPref); Set<Preference> preferences = awaitPreferenceFuture(_userPreferences.getPreferences()); assertEquals("Unexpected number of preferences after update", (long) 1, (long) preferences.size()); Preference updatedPref = preferences.iterator().next(); assertFalse("Replace without id should create new id", createdPreference.getId().equals(updatedPref.getId())); assertEquals("Unexpected preference name", prefName, updatedPref.getName()); assertEquals("Unexpected preference description", changedDescription2, updatedPref.getDescription()); return null; } } ); }
@Test public void testReplaceViaPutByType() throws Exception { final String prefName = "myprefname"; final RequestInfo requestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Arrays.asList("X-testtype") ); final Map<String, Object> pref = new HashMap<>(); pref.put(Preference.NAME_ATTRIBUTE, prefName); pref.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { _handler.handlePUT(_configuredObject, requestInfo, Lists.newArrayList(pref)); Set<Preference> preferences = awaitPreferenceFuture(_userPreferences.getPreferences()); assertEquals("Unexpected number of preferences", (long) 1, (long) preferences.size()); Preference prefModel = preferences.iterator().next(); assertEquals("Unexpected preference name", prefName, prefModel.getName()); return null; } } ); final String replacementPref1Name = "myprefreplacement1"; final String replacementPref2Name = "myprefreplacement2"; final Map<String, Object> replacementPref1 = new HashMap<>(); replacementPref1.put(Preference.NAME_ATTRIBUTE, replacementPref1Name); replacementPref1.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); final Map<String, Object> replacementPref2 = new HashMap<>(); replacementPref2.put(Preference.NAME_ATTRIBUTE, replacementPref2Name); replacementPref2.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { _handler.handlePUT(_configuredObject, requestInfo, Lists.newArrayList(replacementPref1, replacementPref2)); Set<Preference> preferences = awaitPreferenceFuture(_userPreferences.getPreferences()); assertEquals("Unexpected number of preferences after update", (long) 2, (long) preferences.size()); Set<String> prefNames = new HashSet<>(preferences.size()); for (Preference pref : preferences) { prefNames.add(pref.getName()); } assertTrue("Replacement preference " + replacementPref1Name + " not found.", prefNames.contains(replacementPref1Name)); assertTrue("Replacement preference " + replacementPref2Name + " not found.", prefNames.contains(replacementPref2Name)); return null; } } ); }
@Test public void testReplaceAllViaPut() throws Exception { final String pref1Name = "mypref1name"; final String pref1Type = "X-testtype1"; final String pref2Name = "mypref2name"; final String pref2Type = "X-testtype2"; final RequestInfo requestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Collections.<String>emptyList() ); final Map<String, Object> pref1 = new HashMap<>(); pref1.put(Preference.NAME_ATTRIBUTE, pref1Name); pref1.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); pref1.put(Preference.TYPE_ATTRIBUTE, pref1Type); final Map<String, Object> pref2 = new HashMap<>(); pref2.put(Preference.NAME_ATTRIBUTE, pref2Name); pref2.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); pref2.put(Preference.TYPE_ATTRIBUTE, pref2Type); final Map<String, List<Map<String, Object>>> payload = new HashMap<>(); payload.put(pref1Type, Collections.singletonList(pref1)); payload.put(pref2Type, Collections.singletonList(pref2)); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { _handler.handlePUT(_configuredObject, requestInfo, payload); Set<Preference> preferences = awaitPreferenceFuture(_userPreferences.getPreferences()); assertEquals("Unexpected number of preferences", (long) 2, (long) preferences.size()); return null; } } ); final String replacementPref1Name = "myprefreplacement1"; final Map<String, Object> replacementPref1 = new HashMap<>(); replacementPref1.put(Preference.NAME_ATTRIBUTE, replacementPref1Name); replacementPref1.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); replacementPref1.put(Preference.TYPE_ATTRIBUTE, pref1Type); payload.clear(); payload.put(pref1Type, Collections.singletonList(replacementPref1)); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { _handler.handlePUT(_configuredObject, requestInfo, payload); Set<Preference> preferences = awaitPreferenceFuture(_userPreferences.getPreferences()); assertEquals("Unexpected number of preferences after update", (long) 1, (long) preferences.size()); Preference prefModel = preferences.iterator().next(); assertEquals("Unexpected preference name", replacementPref1Name, prefModel.getName()); return null; } } ); } |
RestUserPreferenceHandler { public void handlePOST(ConfiguredObject<?> target, RequestInfo requestInfo, Object providedObject) { UserPreferences userPreferences = target.getUserPreferences(); if (userPreferences == null) { throw new NotFoundException("User preferences are not available"); } final List<String> preferencesParts = requestInfo.getPreferencesParts(); final Set<Preference> preferences = new LinkedHashSet<>(); if (preferencesParts.size() == 1) { String type = preferencesParts.get(0); if (!(providedObject instanceof List)) { throw new IllegalArgumentException("expected a list of objects"); } preferences.addAll(validateAndConvert(target, type, (List<Object>) providedObject)); } else if (preferencesParts.size() == 0) { if (!(providedObject instanceof Map)) { throw new IllegalArgumentException("expected object"); } preferences.addAll(validateAndConvert(target, (Map<String, Object>) providedObject)); } else { throw new IllegalArgumentException(String.format("unexpected path '%s'", Joiner.on("/").join(preferencesParts))); } awaitFuture(userPreferences.updateOrAppend(preferences)); } RestUserPreferenceHandler(final long preferenceOperationTimeout); void handleDELETE(final UserPreferences userPreferences, final RequestInfo requestInfo); void handlePUT(ConfiguredObject<?> target, RequestInfo requestInfo, Object providedObject); void handlePOST(ConfiguredObject<?> target, RequestInfo requestInfo, Object providedObject); Object handleGET(UserPreferences userPreferences, RequestInfo requestInfo); } | @Test public void testPostToTypeWithVisibilityList_ValidGroup() throws Exception { final RequestInfo typeRequestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Arrays.asList("X-testtype") ); final Map<String, Object> pref = new HashMap<>(); pref.put(Preference.NAME_ATTRIBUTE, "testPref"); pref.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); pref.put(Preference.VISIBILITY_LIST_ATTRIBUTE, Collections.singletonList(MYGROUP_SERIALIZATION)); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { _handler.handlePOST(_configuredObject, typeRequestInfo, Collections.singletonList(pref)); Set<Preference> preferences = awaitPreferenceFuture(_userPreferences.getPreferences()); assertEquals("Unexpected number of preferences", (long) 1, (long) preferences.size()); Preference prefModel = preferences.iterator().next(); final Set<Principal> visibilityList = prefModel.getVisibilityList(); assertEquals("Unexpected number of principals in visibility list", (long) 1, (long) visibilityList.size()); Principal principal = visibilityList.iterator().next(); assertEquals("Unexpected member of visibility list", MYGROUP, principal.getName()); return null; } } ); }
@Test public void testPostToRootWithVisibilityList_ValidGroup() throws Exception { final RequestInfo rootRequestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Collections.<String>emptyList() ); final Map<String, Object> pref = new HashMap<>(); pref.put(Preference.NAME_ATTRIBUTE, "testPref"); pref.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); pref.put(Preference.VISIBILITY_LIST_ATTRIBUTE, Collections.singletonList(MYGROUP_SERIALIZATION)); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { final Map<String, List<Map<String, Object>>> payload = Collections.singletonMap("X-testtype2", Collections.singletonList(pref)); _handler.handlePOST(_configuredObject, rootRequestInfo, payload); Set<Preference> preferences = awaitPreferenceFuture(_userPreferences.getPreferences()); assertEquals("Unexpected number of preferences", (long) 1, (long) preferences.size()); Preference prefModel = preferences.iterator().next(); final Set<Principal> visibilityList = prefModel.getVisibilityList(); assertEquals("Unexpected number of principals in visibility list", (long) 1, (long) visibilityList.size()); Principal principal = visibilityList.iterator().next(); assertEquals("Unexpected member of visibility list", MYGROUP, principal.getName()); return null; } } ); }
@Test public void testPostToTypeWithVisibilityList_InvalidGroup() throws Exception { final RequestInfo requestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Arrays.asList("X-testtype") ); final Map<String, Object> pref = new HashMap<>(); pref.put(Preference.NAME_ATTRIBUTE, "testPref"); pref.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); pref.put(Preference.VISIBILITY_LIST_ATTRIBUTE, Collections.singletonList("Invalid Group")); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { try { _handler.handlePOST(_configuredObject, requestInfo, Collections.singletonList(pref)); fail("Expected exception not thrown"); } catch (IllegalArgumentException e) { } return null; } } ); }
@Test public void testPostToRootWithVisibilityList_InvalidGroup() throws Exception { final RequestInfo requestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Collections.<String>emptyList() ); final Map<String, Object> pref = new HashMap<>(); pref.put(Preference.NAME_ATTRIBUTE, "testPref"); pref.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); pref.put(Preference.VISIBILITY_LIST_ATTRIBUTE, Collections.singletonList("Invalid Group")); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { try { final Map<String, List<Map<String, Object>>> payload = Collections.singletonMap("X-testType", Collections.singletonList(pref)); _handler.handlePOST(_configuredObject, requestInfo, payload); fail("Expected exception not thrown"); } catch (IllegalArgumentException e) { } return null; } } ); } |
RestUserPreferenceHandler { public Object handleGET(UserPreferences userPreferences, RequestInfo requestInfo) { if (userPreferences == null) { throw new NotFoundException("User preferences are not available"); } final List<String> preferencesParts = requestInfo.getPreferencesParts(); final Map<String, List<String>> queryParameters = requestInfo.getQueryParameters(); UUID id = getIdFromQueryParameters(queryParameters); final ListenableFuture<Set<Preference>> allPreferencesFuture; if (requestInfo.getType() == RequestType.USER_PREFERENCES) { allPreferencesFuture = userPreferences.getPreferences(); } else if (requestInfo.getType() == RequestType.VISIBLE_PREFERENCES) { allPreferencesFuture = userPreferences.getVisiblePreferences(); } else { throw new IllegalStateException(String.format( "RestUserPreferenceHandler called with a unsupported request type: %s", requestInfo.getType())); } final Set<Preference> allPreferences; allPreferences = awaitFuture(allPreferencesFuture); if (preferencesParts.size() == 2) { String type = preferencesParts.get(0); String name = preferencesParts.get(1); Preference foundPreference = null; for (Preference preference : allPreferences) { if (preference.getType().equals(type) && preference.getName().equals(name)) { if (id == null || id.equals(preference.getId())) { foundPreference = preference; } break; } } if (foundPreference != null) { return foundPreference.getAttributes(); } else { String errorMessage; if (id == null) { errorMessage = String.format("Preference with name '%s' of type '%s' cannot be found", name, type); } else { errorMessage = String.format("Preference with name '%s' of type '%s' and id '%s' cannot be found", name, type, id); } throw new NotFoundException(errorMessage); } } else if (preferencesParts.size() == 1) { String type = preferencesParts.get(0); List<Map<String, Object>> preferences = new ArrayList<>(); for (Preference preference : allPreferences) { if (preference.getType().equals(type)) { if (id == null || id.equals(preference.getId())) { preferences.add(preference.getAttributes()); } } } return preferences; } else if (preferencesParts.size() == 0) { final Map<String, List<Map<String, Object>>> preferences = new HashMap<>(); for (Preference preference : allPreferences) { if (id == null || id.equals(preference.getId())) { final String type = preference.getType(); if (!preferences.containsKey(type)) { preferences.put(type, new ArrayList<Map<String, Object>>()); } preferences.get(type).add(preference.getAttributes()); } } return preferences; } else { throw new IllegalArgumentException(String.format("unexpected path '%s'", Joiner.on("/").join(preferencesParts))); } } RestUserPreferenceHandler(final long preferenceOperationTimeout); void handleDELETE(final UserPreferences userPreferences, final RequestInfo requestInfo); void handlePUT(ConfiguredObject<?> target, RequestInfo requestInfo, Object providedObject); void handlePOST(ConfiguredObject<?> target, RequestInfo requestInfo, Object providedObject); Object handleGET(UserPreferences userPreferences, RequestInfo requestInfo); } | @Test public void testGetHasCorrectVisibilityList() throws Exception { final RequestInfo rootRequestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Collections.<String>emptyList() ); final String type = "X-testtype"; Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { Map<String, Object> prefAttributes = createPreferenceAttributes( null, null, type, "testpref", null, MYUSER_SERIALIZATION, Collections.singleton(MYGROUP_SERIALIZATION), Collections.<String, Object>emptyMap()); Preference preference = PreferenceFactory.fromAttributes(_configuredObject, prefAttributes); awaitPreferenceFuture(_userPreferences.updateOrAppend(Collections.singleton(preference))); Map<String, List<Map<String, Object>>> typeToPreferenceListMap = (Map<String, List<Map<String, Object>>>) _handler.handleGET(_userPreferences, rootRequestInfo); assertEquals("Unexpected preference map size", (long) 1, (long) typeToPreferenceListMap.size()); assertEquals("Unexpected type in preference map", type, typeToPreferenceListMap.keySet().iterator().next()); List<Map<String, Object>> preferences = typeToPreferenceListMap.get(type); assertEquals("Unexpected number of preferences", (long) 1, (long) preferences.size()); Set<Principal> visibilityList = (Set<Principal>) preferences.get(0).get("visibilityList"); assertEquals("Unexpected number of principals in visibility list", (long) 1, (long) visibilityList.size()); assertTrue("Unexpected principal in visibility list", GenericPrincipal.principalsEqual(_groupPrincipal, visibilityList.iterator().next())); return null; } } ); }
@Test public void testGetById() throws Exception { Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { final String type = "X-testtype"; Map<String, Object> pref1Attributes = createPreferenceAttributes( null, null, type, "testpref", null, MYUSER_SERIALIZATION, null, Collections.<String, Object>emptyMap()); Preference p1 = PreferenceFactory.fromAttributes(_configuredObject, pref1Attributes); Map<String, Object> pref2Attributes = createPreferenceAttributes( null, null, type, "testpref2", null, MYUSER_SERIALIZATION, null, Collections.<String, Object>emptyMap()); Preference p2 = PreferenceFactory.fromAttributes(_configuredObject, pref2Attributes); awaitPreferenceFuture(_userPreferences.updateOrAppend(Arrays.asList(p1, p2))); UUID id = p1.getId(); final RequestInfo rootRequestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.singletonMap("id", Collections.singletonList(id.toString())) ); Map<String, List<Map<String, Object>>> typeToPreferenceListMap = (Map<String, List<Map<String, Object>>>) _handler.handleGET(_userPreferences, rootRequestInfo); assertEquals("Unexpected p1 map size", (long) 1, (long) typeToPreferenceListMap.size()); assertEquals("Unexpected type in p1 map", type, typeToPreferenceListMap.keySet() .iterator().next()); List<Map<String, Object>> preferences = typeToPreferenceListMap.get(type); assertEquals("Unexpected number of preferences", (long) 1, (long) preferences.size()); assertEquals("Unexpected id", id, preferences.get(0).get(Preference.ID_ATTRIBUTE)); return null; } } ); }
@Test public void testGetVisiblePreferencesByRoot() throws Exception { final String prefName = "testpref"; final String prefType = "X-testtype"; final RequestInfo rootRequestInfo = RequestInfo.createVisiblePreferencesRequestInfo(Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String, List<String>>emptyMap() ); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { final Set<Preference> preferences = new HashSet<>(); Map<String, Object> pref1Attributes = createPreferenceAttributes( null, null, prefType, prefName, null, MYUSER_SERIALIZATION, Collections.singleton(MYGROUP_SERIALIZATION), Collections.<String, Object>emptyMap()); Preference p1 = PreferenceFactory.fromAttributes(_configuredObject, pref1Attributes); preferences.add(p1); Map<String, Object> pref2Attributes = createPreferenceAttributes( null, null, prefType, "testPref2", null, MYUSER_SERIALIZATION, Collections.<String>emptySet(), Collections.<String, Object>emptyMap()); Preference p2 = PreferenceFactory.fromAttributes(_configuredObject, pref2Attributes); preferences.add(p2); awaitPreferenceFuture(_userPreferences.updateOrAppend(preferences)); return null; } } ); Subject testSubject2 = TestPrincipalUtils.createTestSubject("testUser2", MYGROUP); Subject.doAs(testSubject2, new PrivilegedAction<Void>() { @Override public Void run() { Map<String, List<Map<String, Object>>> typeToPreferenceListMap = (Map<String, List<Map<String, Object>>>) _handler.handleGET(_userPreferences, rootRequestInfo); assertEquals("Unexpected preference map size", (long) 1, (long) typeToPreferenceListMap.size()); assertEquals("Unexpected prefType in preference map", prefType, typeToPreferenceListMap.keySet().iterator().next()); List<Map<String, Object>> preferences = typeToPreferenceListMap.get(prefType); assertEquals("Unexpected number of preferences", (long) 1, (long) preferences.size()); assertEquals("Unexpected name of preferences", prefName, preferences.get(0).get(Preference.NAME_ATTRIBUTE)); Set<Principal> visibilityList = (Set<Principal>) preferences.get(0).get(Preference.VISIBILITY_LIST_ATTRIBUTE); assertEquals("Unexpected number of principals in visibility list", (long) 1, (long) visibilityList.size()); assertTrue("Unexpected principal in visibility list", GenericPrincipal.principalsEqual(_groupPrincipal, visibilityList.iterator().next())); assertTrue("Unexpected owner", GenericPrincipal.principalsEqual(_userPrincipal, (Principal) preferences.get(0).get(Preference.OWNER_ATTRIBUTE))); return null; } } ); }
@Test public void testGetVisiblePreferencesByType() throws Exception { final String prefName = "testpref"; final String prefType = "X-testtype"; final RequestInfo rootRequestInfo = RequestInfo.createVisiblePreferencesRequestInfo(Collections.<String>emptyList(), Arrays.asList(prefType), Collections.<String, List<String>>emptyMap() ); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { final Set<Preference> preferences = new HashSet<>(); Map<String, Object> pref1Attributes = createPreferenceAttributes( null, null, prefType, prefName, null, MYUSER_SERIALIZATION, Collections.singleton(MYGROUP_SERIALIZATION), Collections.<String, Object>emptyMap()); Preference p1 = PreferenceFactory.fromAttributes(_configuredObject, pref1Attributes); preferences.add(p1); Map<String, Object> pref2Attributes = createPreferenceAttributes( null, null, prefType, "testPref2", null, MYUSER_SERIALIZATION, Collections.<String>emptySet(), Collections.<String, Object>emptyMap()); Preference p2 = PreferenceFactory.fromAttributes(_configuredObject, pref2Attributes); preferences.add(p2); awaitPreferenceFuture(_userPreferences.updateOrAppend(preferences)); return null; } } ); Subject testSubject2 = TestPrincipalUtils.createTestSubject("testUser2", MYGROUP); Subject.doAs(testSubject2, new PrivilegedAction<Void>() { @Override public Void run() { List<Map<String, Object>> preferences = (List<Map<String, Object>>) _handler.handleGET(_userPreferences, rootRequestInfo); assertEquals("Unexpected number of preferences", (long) 1, (long) preferences.size()); assertEquals("Unexpected name of preferences", prefName, preferences.get(0).get(Preference.NAME_ATTRIBUTE)); Set<Principal> visibilityList = (Set<Principal>) preferences.get(0).get(Preference.VISIBILITY_LIST_ATTRIBUTE); assertEquals("Unexpected number of principals in visibility list", (long) 1, (long) visibilityList.size()); assertTrue("Unexpected principal in visibility list", GenericPrincipal.principalsEqual(_groupPrincipal, visibilityList.iterator().next())); assertTrue("Unexpected owner", GenericPrincipal.principalsEqual(_userPrincipal, (Principal) preferences.get(0) .get(Preference.OWNER_ATTRIBUTE))); return null; } } ); }
@Test public void testGetVisiblePreferencesByTypeAndName() throws Exception { final String prefName = "testpref"; final String prefType = "X-testtype"; final RequestInfo rootRequestInfo = RequestInfo.createVisiblePreferencesRequestInfo(Collections.<String>emptyList(), Arrays.asList(prefType, prefName), Collections.<String, List<String>>emptyMap() ); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { final Set<Preference> preferences = new HashSet<>(); Map<String, Object> pref1Attributes = createPreferenceAttributes( null, null, prefType, prefName, null, MYUSER_SERIALIZATION, Collections.singleton(MYGROUP_SERIALIZATION), Collections.<String, Object>emptyMap()); Preference p1 = PreferenceFactory.fromAttributes(_configuredObject, pref1Attributes); preferences.add(p1); Map<String, Object> pref2Attributes = createPreferenceAttributes( null, null, prefType, "testPref2", null, MYUSER_SERIALIZATION, Collections.<String>emptySet(), Collections.<String, Object>emptyMap()); Preference p2 = PreferenceFactory.fromAttributes(_configuredObject, pref2Attributes); preferences.add(p2); awaitPreferenceFuture(_userPreferences.updateOrAppend(preferences)); return null; } } ); Subject testSubject2 = TestPrincipalUtils.createTestSubject("testUser2", MYGROUP); Subject.doAs(testSubject2, new PrivilegedAction<Void>() { @Override public Void run() { Map<String, Object> preference = (Map<String, Object>) _handler.handleGET(_userPreferences, rootRequestInfo); assertEquals("Unexpected name of preferences", prefName, preference.get(Preference.NAME_ATTRIBUTE)); Set<Principal> visibilityList = (Set<Principal>) preference.get(Preference.VISIBILITY_LIST_ATTRIBUTE); assertEquals("Unexpected number of principals in visibility list", (long) 1, (long) visibilityList.size()); assertTrue("Unexpected principal in visibility list", GenericPrincipal.principalsEqual(_groupPrincipal, visibilityList.iterator().next())); assertTrue("Unexpected owner", GenericPrincipal.principalsEqual(_userPrincipal, (Principal) preference.get(Preference.OWNER_ATTRIBUTE))); return null; } } ); } |
RestUserPreferenceHandler { public void handleDELETE(final UserPreferences userPreferences, final RequestInfo requestInfo) { if (userPreferences == null) { throw new NotFoundException("User preferences are not available"); } final List<String> preferencesParts = requestInfo.getPreferencesParts(); final Map<String, List<String>> queryParameters = requestInfo.getQueryParameters(); UUID id = getIdFromQueryParameters(queryParameters); String type = null; String name = null; if (preferencesParts.size() == 2) { type = preferencesParts.get(0); name = preferencesParts.get(1); } else if (preferencesParts.size() == 1) { type = preferencesParts.get(0); } else if (preferencesParts.size() == 0) { } else { throw new IllegalArgumentException(String.format("unexpected path '%s'", Joiner.on("/").join(preferencesParts))); } awaitFuture(userPreferences.delete(type, name, id)); } RestUserPreferenceHandler(final long preferenceOperationTimeout); void handleDELETE(final UserPreferences userPreferences, final RequestInfo requestInfo); void handlePUT(ConfiguredObject<?> target, RequestInfo requestInfo, Object providedObject); void handlePOST(ConfiguredObject<?> target, RequestInfo requestInfo, Object providedObject); Object handleGET(UserPreferences userPreferences, RequestInfo requestInfo); } | @Test public void testDeleteById() throws Exception { Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { final String type = "X-testtype"; Map<String, Object> pref1Attributes = createPreferenceAttributes( null, null, type, "testpref", null, MYUSER_SERIALIZATION, null, Collections.<String, Object>emptyMap()); Preference p1 = PreferenceFactory.fromAttributes(_configuredObject, pref1Attributes); Map<String, Object> pref2Attributes = createPreferenceAttributes( null, null, type, "testpref2", null, MYUSER_SERIALIZATION, null, Collections.<String, Object>emptyMap()); Preference p2 = PreferenceFactory.fromAttributes(_configuredObject, pref2Attributes); awaitPreferenceFuture(_userPreferences.updateOrAppend(Arrays.asList(p1, p2))); UUID id = p1.getId(); final RequestInfo rootRequestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.singletonMap("id", Collections.singletonList(id.toString())) ); _handler.handleDELETE(_userPreferences, rootRequestInfo); final Set<Preference> retrievedPreferences = awaitPreferenceFuture(_userPreferences.getPreferences()); assertEquals("Unexpected number of preferences", (long) 1, (long) retrievedPreferences.size()); assertTrue("Unexpected type in p1 map", retrievedPreferences.contains(p2)); return null; } } ); } |
RequestInfoParser { public RequestInfo parse(final HttpServletRequest request) { final String servletPath = request.getServletPath(); final String pathInfo = (request.getPathInfo() != null ? request.getPathInfo() : ""); List<String> parts = HttpManagementUtil.getPathInfoElements(servletPath, pathInfo); Map<String, List<String>> queryParameters = parseQueryString(request.getQueryString()); final String method = request.getMethod(); if ("POST".equals(method)) { return parsePost(servletPath, pathInfo, parts, queryParameters); } else if ("PUT".equals(method)) { return parsePut(servletPath, pathInfo, parts, queryParameters); } else if ("GET".equals(method)) { return parseGet(servletPath, pathInfo, parts, queryParameters); } else if ("DELETE".equals(method)) { return parseDelete(servletPath, pathInfo, parts, queryParameters); } else { throw new IllegalArgumentException(String.format("Unexpected method type '%s' for path '%s%s'", method, servletPath, pathInfo)); } } RequestInfoParser(final Class<? extends ConfiguredObject>... hierarchy); RequestInfo parse(final HttpServletRequest request); } | @Test public void testGetNoHierarchy() { RequestInfoParser parser = new RequestInfoParser(); configureRequest("GET", "servletPath", null); RequestInfo info = parser.parse(_request); assertEquals("Unexpected request type", RequestType.MODEL_OBJECT, info.getType()); assertEquals("Unexpected model parts", Collections.emptyList(), info.getModelParts()); }
@Test public void testGetWithHierarchy() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class); final String vhnName = "testVHNName"; final String vhName = "testVHName"; final String pathInfo = "/" + vhnName + "/" + vhName; configureRequest("GET", "servletPath", pathInfo); RequestInfo info = parser.parse(_request); assertEquals("Unexpected request type", RequestType.MODEL_OBJECT, info.getType()); assertEquals("Unexpected model parts", Arrays.asList(vhnName, vhName), info.getModelParts()); assertTrue("Expected exact object request", info.isSingletonRequest()); }
@Test public void testGetParent() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class); final String vhnName = "testVHNName"; configureRequest("GET", "servletPath", "/" + vhnName); RequestInfo info = parser.parse(_request); assertEquals("Unexpected request type", RequestType.MODEL_OBJECT, info.getType()); assertEquals("Unexpected model parts", Arrays.asList(vhnName), info.getModelParts()); assertFalse("Expected exact object request", info.isSingletonRequest()); }
@Test public void testGetTooManyParts() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class); try { configureRequest("GET", "servletPath", "/testVHNName/testOp/invalidAdditionalPart"); parser.parse(_request); fail("Expected exception"); } catch (IllegalArgumentException e) { } }
@Test public void testPostToParent() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class); final String vhnName = "testVHNName"; final String pathInfo = "/" + vhnName; configureRequest("POST", "servletPath", pathInfo); RequestInfo info = parser.parse(_request); assertEquals("Unexpected request type", RequestType.MODEL_OBJECT, info.getType()); assertEquals("Unexpected model parts", Arrays.asList(vhnName), info.getModelParts()); }
@Test public void testPostToObject() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class); final String vhnName = "testVHNName"; final String vhName = "testVHName"; final String pathInfo = "/" + vhnName + "/" + vhName; configureRequest("POST", "servletPath", pathInfo); RequestInfo info = parser.parse(_request); assertEquals("Unexpected request type", RequestType.MODEL_OBJECT, info.getType()); assertEquals("Unexpected model parts", Arrays.asList(vhnName, vhName), info.getModelParts()); }
@Test public void testPostTooFewParts() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class, Queue.class); try { configureRequest("POST", "servletPath", "/testVHNName"); parser.parse(_request); fail("Expected exception"); } catch (IllegalArgumentException e) { } }
@Test public void testPostTooManyParts() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class, Queue.class); try { configureRequest("POST", "servletPath", "/testVHNName/testVNName/testQueue/testOp/testUnknown"); parser.parse(_request); fail("Expected exception"); } catch (IllegalArgumentException e) { } }
@Test public void testPutToObject() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class); final String vhnName = "testVHNName"; final String vhName = "testVHName"; final String pathInfo = "/" + vhnName + "/" + vhName; configureRequest("PUT", "servletPath", pathInfo); RequestInfo info = parser.parse(_request); assertEquals("Unexpected request type", RequestType.MODEL_OBJECT, info.getType()); assertEquals("Unexpected model parts", Arrays.asList(vhnName, vhName), info.getModelParts()); }
@Test public void testPutToParent() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class, Queue.class); final String vhnName = "testVHNName"; final String vhName = "testVHName"; configureRequest("PUT", "servletPath", "/" + vhnName + "/" + vhName); RequestInfo info = parser.parse(_request); assertEquals("Unexpected request type", RequestType.MODEL_OBJECT, info.getType()); assertEquals("Unexpected model parts", Arrays.asList(vhnName, vhName), info.getModelParts()); }
@Test public void testPutTooFewParts() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class, Queue.class); try { configureRequest("PUT", "servletPath", "/testVHNName"); parser.parse(_request); fail("Expected exception"); } catch (IllegalArgumentException e) { } }
@Test public void testPutTooManyParts() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class, Queue.class); try { configureRequest("PUT", "servletPath", "/testVHNName/testVNName/testQueue/testUnknown"); parser.parse(_request); fail("Expected exception"); } catch (IllegalArgumentException e) { } }
@Test public void testDeleteObject() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class); final String vhnName = "testVHNName"; final String vhName = "testVHName"; final String pathInfo = "/" + vhnName + "/" + vhName; configureRequest("DELETE", "servletPath", pathInfo); RequestInfo info = parser.parse(_request); assertEquals("Unexpected request type", RequestType.MODEL_OBJECT, info.getType()); assertEquals("Unexpected model parts", Arrays.asList(vhnName, vhName), info.getModelParts()); }
@Test public void testDeleteParent() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class, Queue.class); final String vhnName = "testVHNName"; final String vhName = "testVHName"; configureRequest("DELETE", "servletPath", "/" + vhnName + "/" + vhName); RequestInfo info = parser.parse(_request); assertEquals("Unexpected request type", RequestType.MODEL_OBJECT, info.getType()); assertEquals("Unexpected model parts", Arrays.asList(vhnName, vhName), info.getModelParts()); }
@Test public void testDeleteTooManyParts() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class, Queue.class); try { configureRequest("DELETE", "servletPath", "/testVHNName/testVNName/testQueue/testUnknown"); parser.parse(_request); fail("Expected exception"); } catch (IllegalArgumentException e) { } }
@Test public void testParseWithURLEncodedName() throws UnsupportedEncodingException { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class); final String vhnName = "vhnName/With/slashes?and&other/stuff"; final String encodedVHNName = URLEncoder.encode(vhnName, StandardCharsets.UTF_8.name()); configureRequest("GET", "servletPath", "/" + encodedVHNName); RequestInfo info = parser.parse(_request); assertEquals("Unexpected request type", RequestType.MODEL_OBJECT, info.getType()); assertEquals("Unexpected model parts", Arrays.asList(vhnName), info.getModelParts()); }
@Test public void testWildHierarchy() { RequestInfoParser parser = new RequestInfoParser(VirtualHostNode.class, VirtualHost.class); configureRequest("GET", "servletPath", "/*/*"); assertTrue("Fully wildcarded path should be wild", parser.parse(_request).hasWildcard()); configureRequest("GET", "servletPath", "/myvhn/*"); assertTrue("Partially wildcarded path should be wild too", parser.parse(_request).hasWildcard()); configureRequest("GET", "servletPath", "/myvhn/myvh"); assertFalse("Path with no wildcards should not be wild", parser.parse(_request).hasWildcard()); } |
StringTypeConstructor extends VariableWidthTypeConstructor<String> { @Override public String construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException { int size; if (!in.hasRemaining(getSize())) { throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Cannot construct string: insufficient input data"); } if (getSize() == 1) { size = in.getUnsignedByte(); } else { size = in.getInt(); } if (!in.hasRemaining(size)) { throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Cannot construct string: insufficient input data"); } byte[] data = new byte[size]; in.get(data); ByteBuffer buffer = ByteBuffer.wrap(data); String cached = getCache().getIfPresent(buffer); if (cached == null) { cached = new String(data, UTF_8); getCache().put(buffer, cached); } return cached; } private StringTypeConstructor(int size); static StringTypeConstructor getInstance(int i); @Override String construct(final QpidByteBuffer in, final ValueHandler handler); } | @Test public void construct() throws Exception { StringTypeConstructor constructor = StringTypeConstructor.getInstance(1); Cache<ByteBuffer, String> original = StringTypeConstructor.getCache(); Cache<ByteBuffer, String> cache = CacheBuilder.newBuilder().maximumSize(2).build(); StringTypeConstructor.setCache(cache); try { String string1 = constructor.construct(QpidByteBuffer.wrap(new byte[]{4, 't', 'e', 's', 't'}), null); String string2 = constructor.construct(QpidByteBuffer.wrap(new byte[]{4, 't', 'e', 's', 't'}), null); assertEquals(string1, string2); assertSame(string1, string2); } finally { cache.cleanUp(); StringTypeConstructor.setCache(original); } } |
ConfiguredObjectToMapConverter { public Map<String, Object> convertObjectToMap(final ConfiguredObject<?> confObject, Class<? extends ConfiguredObject> clazz, ConverterOptions converterOptions ) { Map<String, Object> object = new LinkedHashMap<>(); incorporateAttributesIntoMap(confObject, object, converterOptions); incorporateStatisticsIntoMap(confObject, object); if(converterOptions.getDepth() > 0) { incorporateChildrenIntoMap(confObject, clazz, object, converterOptions); } return object; } Map<String, Object> convertObjectToMap(final ConfiguredObject<?> confObject,
Class<? extends ConfiguredObject> clazz,
ConverterOptions converterOptions
); static final String STATISTICS_MAP_KEY; } | @Test public void testConfiguredObjectWithSingleStatistics() throws Exception { final String statisticName = "statisticName"; final int statisticValue = 10; when(_configuredObject.getStatistics()).thenReturn(Collections.singletonMap(statisticName, (Number) statisticValue)); Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, ConfiguredObject.class, new ConfiguredObjectToMapConverter.ConverterOptions( 0, false, 120, false, false)); Map<String, Object> statsAsMap = (Map<String, Object>) resultMap.get(STATISTICS_MAP_KEY); assertNotNull("Statistics should be part of map", statsAsMap); assertEquals("Unexpected number of statistics", (long) 1, (long) statsAsMap.size()); assertEquals("Unexpected statistic value", statisticValue, statsAsMap.get(statisticName)); }
@Test public void testConfiguredObjectWithSingleNonConfiguredObjectAttribute() throws Exception { final String attributeName = "attribute"; final String attributeValue = "value"; Model model = createTestModel(); when(_configuredObject.getModel()).thenReturn(model); configureMockToReturnOneAttribute(_configuredObject, attributeName, attributeValue); Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, ConfiguredObject.class, new ConfiguredObjectToMapConverter.ConverterOptions( 0, false, 120, false, false)); assertEquals("Unexpected number of attributes", (long) 1, (long) resultMap.size()); assertEquals("Unexpected attribute value", attributeValue, resultMap.get(attributeName)); }
@Test public void testConfiguredObjectWithSingleConfiguredObjectAttribute() throws Exception { final String attributeName = "attribute"; final ConfiguredObject attributeValue = mock(ConfiguredObject.class); when(attributeValue.getName()).thenReturn("attributeConfiguredObjectName"); configureMockToReturnOneAttribute(_configuredObject, attributeName, attributeValue); Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, ConfiguredObject.class, new ConfiguredObjectToMapConverter.ConverterOptions( 0, false, 120, false, false)); assertEquals("Unexpected number of attributes", (long) 1, (long) resultMap.size()); assertEquals("Unexpected attribute value", "attributeConfiguredObjectName", resultMap.get(attributeName)); }
@Test public void testConfiguredObjectWithChildAndDepth1() { final String childAttributeName = "childattribute"; final String childAttributeValue = "childvalue"; Model model = createTestModel(); TestChild mockChild = mock(TestChild.class); when(mockChild.getModel()).thenReturn(model); when(_configuredObject.getModel()).thenReturn(model); configureMockToReturnOneAttribute(mockChild, childAttributeName, childAttributeValue); when(_configuredObject.getChildren(TestChild.class)).thenReturn(Arrays.asList(mockChild)); Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, ConfiguredObject.class, new ConfiguredObjectToMapConverter.ConverterOptions( 1, false, 120, false, false)); assertEquals("Unexpected parent map size", (long) 1, (long) resultMap.size()); final List<Map<String, Object>> childList = (List<Map<String, Object>>) resultMap.get("testchilds"); assertEquals("Unexpected number of children", (long) 1, (long) childList.size()); final Map<String, Object> childMap = childList.get(0); assertEquals("Unexpected child map size", (long) 1, (long) childMap.size()); assertNotNull(childMap); assertEquals("Unexpected child attribute value", childAttributeValue, childMap.get(childAttributeName)); }
@Test public void testActuals() { final String childAttributeName = "childattribute"; final String childAttributeValue = "childvalue"; final String childActualAttributeValue = "${actualvalue}"; final Map<String,Object> actualContext = Collections.<String,Object>singletonMap("key","value"); final Set<String> inheritedKeys = new HashSet<>(Arrays.asList("key","inheritedkey")); Model model = createTestModel(); TestChild mockChild = mock(TestChild.class); when(mockChild.getModel()).thenReturn(model); when(_configuredObject.getModel()).thenReturn(model); when(_configuredObject.getAttributeNames()).thenReturn(Collections.singletonList(ConfiguredObject.CONTEXT)); when(_configuredObject.getContextValue(eq(String.class), eq("key"))).thenReturn("value"); when(_configuredObject.getContextValue(eq(String.class),eq("inheritedkey"))).thenReturn("foo"); when(_configuredObject.getContextKeys(anyBoolean())).thenReturn(inheritedKeys); when(_configuredObject.getContext()).thenReturn(actualContext); when(_configuredObject.getActualAttributes()).thenReturn(Collections.singletonMap(ConfiguredObject.CONTEXT, actualContext)); when(mockChild.getAttributeNames()).thenReturn(Arrays.asList(childAttributeName, ConfiguredObject.CONTEXT)); when(mockChild.getAttribute(childAttributeName)).thenReturn(childAttributeValue); when(mockChild.getActualAttributes()).thenReturn(Collections.singletonMap(childAttributeName, childActualAttributeValue)); when(_configuredObject.getChildren(TestChild.class)).thenReturn(Arrays.asList(mockChild)); Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, ConfiguredObject.class, new ConfiguredObjectToMapConverter.ConverterOptions( 1, true, 120, false, true)); assertEquals("Unexpected parent map size", (long) 2, (long) resultMap.size()); assertEquals("Incorrect context", resultMap.get(ConfiguredObject.CONTEXT), actualContext); List<Map<String, Object>> childList = (List<Map<String, Object>>) resultMap.get("testchilds"); assertEquals("Unexpected number of children", (long) 1, (long) childList.size()); Map<String, Object> childMap = childList.get(0); assertNotNull(childMap); assertEquals("Unexpected child map size", (long) 1, (long) childMap.size()); assertEquals("Unexpected child attribute value", childActualAttributeValue, childMap.get(childAttributeName)); resultMap = _converter.convertObjectToMap(_configuredObject, ConfiguredObject.class, new ConfiguredObjectToMapConverter.ConverterOptions(1, false, 120, false, true)); assertEquals("Unexpected parent map size", (long) 2, (long) resultMap.size()); Map<String, Object> effectiveContext = new HashMap<>(); effectiveContext.put("key","value"); assertEquals("Incorrect context", effectiveContext, resultMap.get(ConfiguredObject.CONTEXT)); childList = (List<Map<String, Object>>) resultMap.get("testchilds"); assertEquals("Unexpected number of children", (long) 1, (long) childList.size()); childMap = childList.get(0); assertEquals("Unexpected child map size", (long) 1, (long) childMap.size()); assertNotNull(childMap); assertEquals("Unexpected child attribute value", childAttributeValue, childMap.get(childAttributeName)); }
@Test public void testOversizedAttributes() { Model model = createTestModel(); ConfiguredObjectTypeRegistry typeRegistry = model.getTypeRegistry(); final Map<String, ConfiguredObjectAttribute<?, ?>> attributeTypes = typeRegistry.getAttributeTypes(TestChild.class); final ConfiguredObjectAttribute longAttr = mock(ConfiguredObjectMethodAttribute.class); when(longAttr.isOversized()).thenReturn(true); when(longAttr.getOversizedAltText()).thenReturn(""); when(attributeTypes.get(eq("longAttr"))).thenReturn(longAttr); TestChild mockChild = mock(TestChild.class); when(mockChild.getModel()).thenReturn(model); when(_configuredObject.getModel()).thenReturn(model); configureMockToReturnOneAttribute(mockChild, "longAttr", "this is not long"); when(_configuredObject.getChildren(TestChild.class)).thenReturn(Arrays.asList(mockChild)); Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, ConfiguredObject.class, new ConfiguredObjectToMapConverter.ConverterOptions( 1, false, 20, false, false)); Object children = resultMap.get("testchilds"); assertNotNull(children); final boolean condition5 = children instanceof Collection; assertTrue(condition5); assertTrue(((Collection)children).size() == 1); Object attrs = ((Collection)children).iterator().next(); final boolean condition4 = attrs instanceof Map; assertTrue(condition4); assertEquals("this is not long", ((Map) attrs).get("longAttr")); resultMap = _converter.convertObjectToMap(_configuredObject, ConfiguredObject.class, new ConfiguredObjectToMapConverter.ConverterOptions(1, false, 8, false, false)); children = resultMap.get("testchilds"); assertNotNull(children); final boolean condition3 = children instanceof Collection; assertTrue(condition3); assertTrue(((Collection)children).size() == 1); attrs = ((Collection)children).iterator().next(); final boolean condition2 = attrs instanceof Map; assertTrue(condition2); assertEquals("this...", ((Map) attrs).get("longAttr")); when(longAttr.getOversizedAltText()).thenReturn("test alt text"); resultMap = _converter.convertObjectToMap(_configuredObject, ConfiguredObject.class, new ConfiguredObjectToMapConverter.ConverterOptions(1, false, 8, false, false)); children = resultMap.get("testchilds"); assertNotNull(children); final boolean condition1 = children instanceof Collection; assertTrue(condition1); assertTrue(((Collection)children).size() == 1); attrs = ((Collection)children).iterator().next(); final boolean condition = attrs instanceof Map; assertTrue(condition); assertEquals("test alt text", ((Map) attrs).get("longAttr")); }
@Test public void testSecureAttributes() { Model model = createTestModel(); ConfiguredObjectTypeRegistry typeRegistry = model.getTypeRegistry(); Map<String, ConfiguredObjectAttribute<?, ?>> attributeTypes = typeRegistry.getAttributeTypes(TestChild.class); ConfiguredObjectAttribute secureAttribute = mock(ConfiguredObjectMethodAttribute.class); when(secureAttribute.isSecure()).thenReturn(true); when(secureAttribute.isSecureValue(any())).thenReturn(true); when(attributeTypes.get(eq("secureAttribute"))).thenReturn(secureAttribute); TestChild mockChild = mock(TestChild.class); when(mockChild.getModel()).thenReturn(model); when(_configuredObject.getModel()).thenReturn(model); configureMockToReturnOneAttribute(mockChild, "secureAttribute", "*****"); when(mockChild.getActualAttributes()).thenReturn(Collections.singletonMap("secureAttribute", "secret")); when(_configuredObject.getChildren(TestChild.class)).thenReturn(Arrays.asList(mockChild)); when(model.getParentType(TestChild.class)).thenReturn((Class)TestChild.class); when(_configuredObject.getCategoryClass()).thenReturn(TestChild.class); when(mockChild.isDurable()).thenReturn(true); Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, ConfiguredObject.class, new ConfiguredObjectToMapConverter.ConverterOptions( 1, false, 20, false, false)); Object children = resultMap.get("testchilds"); assertNotNull(children); final boolean condition3 = children instanceof Collection; assertTrue(condition3); assertTrue(((Collection)children).size() == 1); Object attrs = ((Collection)children).iterator().next(); final boolean condition2 = attrs instanceof Map; assertTrue(condition2); assertEquals("*****", ((Map) attrs).get("secureAttribute")); resultMap = _converter.convertObjectToMap(_configuredObject, ConfiguredObject.class, new ConfiguredObjectToMapConverter.ConverterOptions(1, true, 20, true, false)); children = resultMap.get("testchilds"); assertNotNull(children); final boolean condition1 = children instanceof Collection; assertTrue(condition1); assertTrue(((Collection)children).size() == 1); attrs = ((Collection)children).iterator().next(); final boolean condition = attrs instanceof Map; assertTrue(condition); assertEquals("*****", ((Map) attrs).get("secureAttribute")); }
@Test public void testIncludeInheritedContextAndEffective() { TestEngine engine = createEngineWithContext(); ConfiguredObjectToMapConverter.ConverterOptions options = new ConfiguredObjectToMapConverter.ConverterOptions( 1, false, 0, false, false); Map<String, Object> resultMap = _converter.convertObjectToMap(engine, TestEngine.class, options); Map<String, String> context = getContext(resultMap); assertTrue("Unexpected size of context", context.size() >= 5); assertEquals("Unexpected engine context content", CHILD_CONTEXT_PROPERTY_EFFECTIVE_VALUE, context.get(CHILD_CONTEXT_PROPERTY_NAME)); assertEquals("Unexpected car context content", PARENT_CONTEXT_PROPERTY1_ACTUAL_VALUE, context.get(PARENT_CONTEXT_PROPERTY1_NAME)); assertEquals("Unexpected car context content", PARENT_CONTEXT_PROPERTY2_EFFECTIVE_VALUE, context.get(PARENT_CONTEXT_PROPERTY2_NAME)); assertEquals("Unexpected system context content", TEST_SYSTEM_PROPERTY1_ACTUAL_VALUE, context.get(TEST_SYSTEM_PROPERTY1_NAME)); assertEquals("Unexpected system context content", TEST_SYSTEM_PROPERTY2_EFFECTIVE_VALUE, context.get(TEST_SYSTEM_PROPERTY2_NAME)); }
@Test public void testIncludeInheritedContextAndActual() { TestEngine engine = createEngineWithContext(); ConfiguredObjectToMapConverter.ConverterOptions options = new ConfiguredObjectToMapConverter.ConverterOptions( 1, true, 0, false, false); Map<String, Object> resultMap = _converter.convertObjectToMap(engine, TestEngine.class, options); Map<String, String> context = getContext(resultMap); assertTrue("Unexpected size of context", context.size() >= 5); assertEquals("Unexpected engine context content", CHILD_CONTEXT_PROPERTY_ACTUAL_VALUE, context.get(CHILD_CONTEXT_PROPERTY_NAME)); assertEquals("Unexpected car context content", PARENT_CONTEXT_PROPERTY1_ACTUAL_VALUE, context.get(PARENT_CONTEXT_PROPERTY1_NAME)); assertEquals("Unexpected car context content", PARENT_CONTEXT_PROPERTY2_ACTUAL_VALUE, context.get(PARENT_CONTEXT_PROPERTY2_NAME)); assertEquals("Unexpected system context content", TEST_SYSTEM_PROPERTY1_ACTUAL_VALUE, context.get(TEST_SYSTEM_PROPERTY1_NAME)); assertEquals("Unexpected system context content", TEST_SYSTEM_PROPERTY2_ACTUAL_VALUE, context.get(TEST_SYSTEM_PROPERTY2_NAME)); }
@Test public void testExcludeInheritedContextAndEffective() { TestEngine engine = createEngineWithContext(); ConfiguredObjectToMapConverter.ConverterOptions options = new ConfiguredObjectToMapConverter.ConverterOptions( 1, false, 0, false, true); Map<String, Object> resultMap = _converter.convertObjectToMap(engine, TestEngine.class, options); Map<String, String> context = getContext(resultMap); assertEquals("Unexpected size of context", (long) 1, (long) context.size()); assertEquals("Unexpected context content", CHILD_CONTEXT_PROPERTY_EFFECTIVE_VALUE, context.get(CHILD_CONTEXT_PROPERTY_NAME)); }
@Test public void testExcludeInheritedContextAndActual() { TestEngine engine = createEngineWithContext(); ConfiguredObjectToMapConverter.ConverterOptions options = new ConfiguredObjectToMapConverter.ConverterOptions( 1, true, 0, false, true); Map<String, Object> resultMap = _converter.convertObjectToMap(engine, TestEngine.class, options); Map<String, String> context = getContext(resultMap); assertEquals("Unexpected size of context", (long) 1, (long) context.size()); assertEquals("Unexpected context content", CHILD_CONTEXT_PROPERTY_ACTUAL_VALUE, context.get(CHILD_CONTEXT_PROPERTY_NAME)); } |
ConfiguredObjectQuery { public List<List<Object>> getResults() { return _results; } ConfiguredObjectQuery(List<ConfiguredObject<?>> objects, String selectClause, String whereClause); ConfiguredObjectQuery(List<ConfiguredObject<?>> objects,
String selectClause,
String whereClause,
String orderByClause); ConfiguredObjectQuery(List<ConfiguredObject<?>> objects,
String selectClause,
String whereClause,
String orderByClause,
String limitClause,
String offsetClause); List<List<Object>> getResults(); List<String> getHeaders(); int getTotalNumberOfRows(); static final int DEFAULT_LIMIT; static final int DEFAULT_OFFSET; } | @Test public void testNoClauses_TwoResult() { final UUID object1Uuid = UUID.randomUUID(); final String object1Name = "obj1"; final UUID object2Uuid = UUID.randomUUID(); final String object2Name = "obj2"; ConfiguredObject obj1 = createCO(new HashMap<String, Object>() {{ put(ConfiguredObject.ID, object1Uuid); put(ConfiguredObject.NAME, object1Name); put("foo", "bar"); }}); ConfiguredObject obj2 = createCO(new HashMap<String, Object>() {{ put(ConfiguredObject.ID, object2Uuid); put(ConfiguredObject.NAME, object2Name); }}); _objects.add(obj1); _objects.add(obj2); _query = new ConfiguredObjectQuery(_objects, null, null); List<List<Object>> results = _query.getResults(); assertEquals("Unexpected number of results", (long) 2, (long) results.size()); final Iterator<List<Object>> iterator = results.iterator(); List<Object> row1 = iterator.next(); assertEquals("Unexpected row", Lists.newArrayList(object1Uuid, object1Name), row1); List<Object> row2 = iterator.next(); assertEquals("Unexpected row", Lists.newArrayList(object2Uuid, object2Name), row2); }
@Test public void testQuery_DateInequality() { final long now = System.currentTimeMillis(); final UUID objectUuid = UUID.randomUUID(); final long oneDayInMillis = TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS); final Date yesterday = new Date(now - oneDayInMillis); final Date tomorrow = new Date(now + oneDayInMillis); ConfiguredObject nonMatch = createCO(new HashMap<String, Object>() {{ put(ConfiguredObject.ID, UUID.randomUUID()); put(DATE_ATTR, yesterday); }}); ConfiguredObject match = createCO(new HashMap<String, Object>() {{ put(ConfiguredObject.ID, objectUuid); put(DATE_ATTR, tomorrow); }}); _objects.add(nonMatch); _objects.add(match); _query = new ConfiguredObjectQuery(_objects, String.format("%s,%s", ConfiguredObject.ID, DATE_ATTR), String.format("%s > NOW()", DATE_ATTR)); List<List<Object>> results = _query.getResults(); assertEquals("Unexpected number of results", (long) 1, (long) results.size()); final Iterator<List<Object>> iterator = results.iterator(); List<Object> row = iterator.next(); assertEquals("Unexpected row", objectUuid, row.get(0)); }
@Test public void testQuery_DateEquality() { final long now = System.currentTimeMillis(); final ZonedDateTime zonedDateTime = Instant.ofEpochMilli(now).atZone(ZoneId.systemDefault()); String nowIso8601Str = DateTimeFormatter.ISO_ZONED_DATE_TIME.format(zonedDateTime); final UUID objectUuid = UUID.randomUUID(); ConfiguredObject nonMatch = createCO(new HashMap<String, Object>() {{ put(ConfiguredObject.ID, UUID.randomUUID()); put(DATE_ATTR, new Date(0)); }}); ConfiguredObject match = createCO(new HashMap<String, Object>() {{ put(ConfiguredObject.ID, objectUuid); put(DATE_ATTR, new Date(now)); }}); _objects.add(nonMatch); _objects.add(match); _query = new ConfiguredObjectQuery(_objects, String.format("%s,%s", ConfiguredObject.ID, DATE_ATTR), String.format("%s = TO_DATE('%s')", DATE_ATTR, nowIso8601Str)); List<List<Object>> results = _query.getResults(); assertEquals("Unexpected number of results", (long) 1, (long) results.size()); final Iterator<List<Object>> iterator = results.iterator(); List<Object> row = iterator.next(); assertEquals("Unexpected row", objectUuid, row.get(0)); }
@Test public void testQuery_DateExpressions() { final UUID objectUuid = UUID.randomUUID(); ConfiguredObject match = createCO(new HashMap<String, Object>() {{ put(ConfiguredObject.ID, objectUuid); put(DATE_ATTR, new Date(0)); }}); _objects.add(match); _query = new ConfiguredObjectQuery(_objects, String.format("%s,%s", ConfiguredObject.ID, DATE_ATTR), String.format("%s = DATE_ADD(TO_DATE('%s'), '%s')", DATE_ATTR, "1970-01-01T10:00:00Z", "-PT10H")); List<List<Object>> results = _query.getResults(); assertEquals("Unexpected number of results", (long) 1, (long) results.size()); final Iterator<List<Object>> iterator = results.iterator(); List<Object> row = iterator.next(); assertEquals("Unexpected row", objectUuid, row.get(0)); }
@Test public void testDateToString() { final UUID objectUuid = UUID.randomUUID(); ConfiguredObject match = createCO(new HashMap<String, Object>() {{ put(ConfiguredObject.ID, objectUuid); put(DATE_ATTR, new Date(0)); }}); _objects.add(match); _query = new ConfiguredObjectQuery(_objects, String.format("%s, TO_STRING(%s)", ConfiguredObject.ID, DATE_ATTR), null); List<List<Object>> results = _query.getResults(); assertEquals("Unexpected number of results", (long) 1, (long) results.size()); final Iterator<List<Object>> iterator = results.iterator(); List<Object> row = iterator.next(); assertEquals("Unexpected row", Lists.newArrayList(objectUuid, "1970-01-01T00:00:00Z"), row); }
@Test public void testDateToFormattedString() { final UUID objectUuid = UUID.randomUUID(); ConfiguredObject match = createCO(new HashMap<String, Object>() {{ put(ConfiguredObject.ID, objectUuid); put(DATE_ATTR, new Date(0)); }}); _objects.add(match); _query = new ConfiguredObjectQuery(_objects, String.format("%s, TO_STRING(%s,'%s', 'UTC')", ConfiguredObject.ID, DATE_ATTR, "%1$tF %1$tZ"), null); List<List<Object>> results = _query.getResults(); assertEquals("Unexpected number of results", (long) 1, (long) results.size()); final Iterator<List<Object>> iterator = results.iterator(); List<Object> row = iterator.next(); assertEquals("Unexpected row", Lists.newArrayList(objectUuid, "1970-01-01 UTC"), row); }
@Test public void testQuery_EnumEquality() { final UUID objectUuid = UUID.randomUUID(); ConfiguredObject obj = createCO(new HashMap<String, Object>() {{ put(ConfiguredObject.ID, objectUuid); put(ENUM_ATTR, Snakes.PYTHON); put(ENUM2_ATTR, Snakes.PYTHON); }}); _objects.add(obj); _query = new ConfiguredObjectQuery(_objects, String.format("%s", ConfiguredObject.ID), String.format("%s = '%s'", ENUM_ATTR, Snakes.PYTHON)); List<List<Object>> results = _query.getResults(); assertEquals("Unexpected number of results - enumAttr equality with enum constant", (long) 1, (long) results.size()); List<Object> row = _query.getResults().iterator().next(); assertEquals("Unexpected row", objectUuid, row.get(0)); _query = new ConfiguredObjectQuery(_objects, String.format("%s", ConfiguredObject.ID), String.format("'%s' = %s", Snakes.PYTHON, ENUM_ATTR)); results = _query.getResults(); assertEquals("Unexpected number of results - enum constant equality with enumAttr", (long) 1, (long) results.size()); row = _query.getResults().iterator().next(); assertEquals("Unexpected row", objectUuid, row.get(0)); _query = new ConfiguredObjectQuery(_objects, String.format("%s", ConfiguredObject.ID), String.format("%s <> '%s'", ENUM_ATTR, "toad")); results = _query.getResults(); assertEquals("Unexpected number of results - enumAttr not equal enum constant", (long) 1, (long) results.size()); _query = new ConfiguredObjectQuery(_objects, String.format("%s", ConfiguredObject.ID), String.format("%s = %s", ENUM_ATTR, ENUM2_ATTR)); results = _query.getResults(); assertEquals("Unexpected number of results - two attributes of type enum", (long) 1, (long) results.size()); }
@Test public void testQuery_EnumEquality_InExpresssions() { final UUID objectUuid = UUID.randomUUID(); ConfiguredObject obj = createCO(new HashMap<String, Object>() {{ put(ConfiguredObject.ID, objectUuid); put(ENUM_ATTR, Snakes.PYTHON); put(ENUM2_ATTR, Snakes.PYTHON); }}); _objects.add(obj); _query = new ConfiguredObjectQuery(_objects, String.format("%s", ConfiguredObject.ID), String.format("%s in ('%s', '%s', '%s')", ENUM_ATTR, "toad", Snakes.VIPER, Snakes.PYTHON)); List<List<Object>> results = _query.getResults(); assertEquals("Unexpected number of results - emumAttr with set including the enum's constants", (long) 1, (long) results.size()); _query = new ConfiguredObjectQuery(_objects, String.format("%s", ConfiguredObject.ID), String.format("%s in (%s)", ENUM_ATTR, ENUM2_ATTR)); results = _query.getResults(); assertEquals("Unexpected number of results - enumAttr with set including enum2Attr", (long) 1, (long) results.size()); _query = new ConfiguredObjectQuery(_objects, String.format("%s", ConfiguredObject.ID), String.format("'%s' in (%s)", Snakes.PYTHON, ENUM_ATTR)); results = _query.getResults(); assertEquals("Unexpected number of results - attribute within the set", (long) 1, (long) results.size()); }
@Test public void testSingleOrderByClause() { final int NUMBER_OF_OBJECTS = 3; for (int i = 0; i < NUMBER_OF_OBJECTS; ++i) { final int foo = (i + 1) % NUMBER_OF_OBJECTS; ConfiguredObject object = createCO(new HashMap<String, Object>() {{ put("foo", foo); }}); _objects.add(object); } ConfiguredObject object = createCO(new HashMap<String, Object>() {{ put("foo", null); }}); _objects.add(object); List<List<Object>> results; _query = new ConfiguredObjectQuery(_objects, "foo", null, "foo ASC"); results = _query.getResults(); assertQueryResults(new Object[][]{{null}, {0}, {1}, {2}}, results); _query = new ConfiguredObjectQuery(_objects, "foo", null, "foo DESC"); results = _query.getResults(); assertQueryResults(new Object[][]{{2}, {1}, {0}, {null}}, results); _query = new ConfiguredObjectQuery(_objects, "foo", null, "foo"); results = _query.getResults(); assertQueryResults(new Object[][]{{null}, {0}, {1}, {2}}, results); }
@Test public void testAliasInOrderByClause() { _objects.add(createCO(new HashMap<String, Object>() {{ put("foo", 2); }})); _objects.add(createCO(new HashMap<String, Object>() {{ put("foo", 1); }})); _objects.add(createCO(new HashMap<String, Object>() {{ put("foo", 4); }})); _query = new ConfiguredObjectQuery(_objects, "foo AS bar", null, "bar ASC"); assertQueryResults(new Object[][]{{1}, {2}, {4}}, _query.getResults()); }
@Test public void testExpressionToTermsOfAliasInOrderByClause() { _objects.add(createCO(new HashMap<String, Object>() {{ put("foo1", "A"); put("foo2", "B"); }})); _objects.add(createCO(new HashMap<String, Object>() {{ put("foo1", "A"); put("foo2", "A"); }})); _query = new ConfiguredObjectQuery(_objects, "foo1 AS bar1, foo2", null, "CONCAT(bar, foo2) ASC"); assertQueryResults(new Object[][]{{"A", "A"}, {"A", "B"}}, _query.getResults()); }
@Test public void testDelimitedAliasInOrderByClause() { _objects.add(createCO(new HashMap<String, Object>() {{ put("foo", 2); }})); _objects.add(createCO(new HashMap<String, Object>() {{ put("foo", 1); }})); _objects.add(createCO(new HashMap<String, Object>() {{ put("foo", 4); }})); _query = new ConfiguredObjectQuery(_objects, "foo AS \"yogi bear\"", null, "\"yogi bear\" DESC"); assertQueryResults(new Object[][]{{4}, {2}, {1}}, _query.getResults()); }
@Test public void testTwoOrderByClauses() { ConfiguredObject object; object = createCO(new HashMap<String, Object>() {{ put("foo", 1); put("bar", 1); }}); _objects.add(object); object = createCO(new HashMap<String, Object>() {{ put("foo", 1); put("bar", 2); }}); _objects.add(object); object = createCO(new HashMap<String, Object>() {{ put("foo", 2); put("bar", 0); }}); _objects.add(object); _query = new ConfiguredObjectQuery(_objects, "foo,bar", null, "foo, bar"); assertQueryResults(new Object[][]{{1, 1}, {1, 2}, {2, 0}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "foo,bar", null, "foo DESC, bar"); assertQueryResults(new Object[][]{{2, 0}, {1, 1}, {1, 2}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "foo,bar", null, "foo DESC, bar DESC"); assertQueryResults(new Object[][]{{2, 0}, {1, 2}, {1, 1}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "foo,bar", null, "foo, bar DESC"); assertQueryResults(new Object[][]{{1, 2}, {1, 1}, {2, 0}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "foo,bar", null, "bar, foo"); assertQueryResults(new Object[][]{{2, 0}, {1, 1}, {1, 2}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "foo,bar", null, "bar DESC, foo"); assertQueryResults(new Object[][]{{1, 2}, {1, 1}, {2, 0}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "foo,bar", null, "bar, foo DESC"); assertQueryResults(new Object[][]{{2, 0}, {1, 1}, {1, 2}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "foo,bar", null, "bar DESC, foo DESC"); assertQueryResults(new Object[][]{{1, 2}, {1, 1}, {2, 0}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "foo,bar", null, "boo DESC, foo DESC, bar"); assertQueryResults(new Object[][]{{2, 0}, {1, 1}, {1, 2}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "foo, bar", null, "1, 2"); assertQueryResults(new Object[][]{{1, 1}, {1, 2}, {2, 0}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "foo, bar", null, "2, 1"); assertQueryResults(new Object[][]{{2, 0}, {1, 1}, {1, 2}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "foo, bar", null, "foo, 2 DESC"); assertQueryResults(new Object[][]{{1, 2}, {1, 1}, {2, 0}}, _query.getResults()); }
@Test public void testLimitWithoutOffset() { int numberOfTestObjects = 3; for(int i=0;i<numberOfTestObjects;i++) { final String name = "test-" + i; ConfiguredObject object = createCO(new HashMap<String, Object>() {{ put("name", name); }}); _objects.add(object); } _query = new ConfiguredObjectQuery(_objects, "name", null, "name", "1", "0"); assertQueryResults(new Object[][]{{"test-0"}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "name", null, "name", "1", "1"); assertQueryResults(new Object[][]{{"test-1"}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "name", null, "name", "1", "3"); assertQueryResults(new Object[0][1], _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "name", null, "name", "-1", "1"); assertQueryResults(new Object[][]{{"test-1"},{"test-2"}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "name", null, "name", "-1", "-4"); assertQueryResults(new Object[][]{{"test-0"},{"test-1"},{"test-2"}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "name", null, "name", "-1", "-2"); assertQueryResults(new Object[][]{{"test-1"},{"test-2"}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "name", null, "name", "invalidLimit", "invalidOffset"); assertQueryResults(new Object[][]{{"test-0"},{"test-1"},{"test-2"}}, _query.getResults()); _query = new ConfiguredObjectQuery(_objects, "name", null, "name", null, null); assertQueryResults(new Object[][]{{"test-0"},{"test-1"},{"test-2"}}, _query.getResults()); } |
GunzipOutputStream extends InflaterOutputStream { @Override public void write(final byte data[], final int offset, final int length) throws IOException { try(ByteArrayInputStream bais = new ByteArrayInputStream(data, offset, length)) { int b; while ((b = bais.read()) != -1) { if (_streamState == StreamState.DONE) { _streamState = StreamState.HEADER_PARSING; _crc.reset(); _header.reset(); _trailer.reset(); inf.reset(); } if (_streamState == StreamState.HEADER_PARSING) { _header.headerByte(b); if (_header.getState() == HeaderState.DONE) { _streamState = StreamState.INFLATING; continue; } } if (_streamState == StreamState.INFLATING) { _singleByteArray[0] = (byte) b; super.write(_singleByteArray, 0, 1); if (inf.finished()) { _streamState = StreamState.TRAILER_PARSING; continue; } } if (_streamState == StreamState.TRAILER_PARSING) { if (_trailer.trailerByte(b)) { _trailer.verify(_crc); _streamState = StreamState.DONE; continue; } } } } } GunzipOutputStream(final OutputStream targetOutputStream); @Override void write(final byte data[], final int offset, final int length); } | @Test public void testDecompressing() throws Exception { final byte[] originalUncompressedInput = generateTestBytes(); final byte[] compressedBytes = GZIPUtils.compressBufferToArray(ByteBuffer.wrap(originalUncompressedInput)); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); GunzipOutputStream guos = new GunzipOutputStream(outputStream); guos.write(compressedBytes); guos.close(); assertArrayEquals("Unexpected content", originalUncompressedInput, outputStream.toByteArray()); }
@Test public void testDecompressingWithEmbeddedFileName() throws Exception { byte[] data = Base64.getDecoder().decode(GZIP_CONTENT_WITH_EMBEDDED_FILE_NAME); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); GunzipOutputStream guos = new GunzipOutputStream(outputStream); guos.write(data); guos.close(); assertEquals("Unexpected content", TEST_TEXT, new String(outputStream.toByteArray())); }
@Test public void testDecompressingMultipleMembers() throws Exception { byte[] data = Base64.getDecoder().decode(GZIP_CONTENT_WITH_MULTIPLE_MEMBERS); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); GunzipOutputStream guos = new GunzipOutputStream(outputStream); for (int i = 0; i < data.length; i++) { guos.write(data[i]); } guos.close(); StringBuilder expected = new StringBuilder(TEST_TEXT); expected.append(TEST_TEXT2); assertEquals("Unexpected content", expected.toString(), new String(outputStream.toByteArray())); } |
ReportRunner { public static ReportRunner<?> createRunner(final String reportName, final Map<String, String[]> parameterMap) { QueueReport<?> report = getReport(reportName); setReportParameters(report, parameterMap); return new ReportRunner<>(report); } private ReportRunner(final QueueReport<T> report); boolean isBinaryReport(); static ReportRunner<?> createRunner(final String reportName, final Map<String, String[]> parameterMap); String getContentType(); final T runReport(Queue<?> queue); } | @Test public void testInvalidReportName() { try { ReportRunner.createRunner("unknown", Collections.<String, String[]>emptyMap()); fail("Unknown report name should throw exception"); } catch(IllegalArgumentException e) { assertEquals("Unknown report: unknown", e.getMessage()); } } |
OAuth2InteractiveAuthenticator implements HttpRequestInteractiveAuthenticator { @Override public AuthenticationHandler getAuthenticationHandler(final HttpServletRequest request, final HttpManagementConfiguration configuration) { final Port<?> port = configuration.getPort(request); if (configuration.getAuthenticationProvider(request) instanceof OAuth2AuthenticationProvider) { final OAuth2AuthenticationProvider oauth2Provider = (OAuth2AuthenticationProvider) configuration.getAuthenticationProvider(request); final Map<String, String> requestParameters; try { requestParameters = getRequestParameters(request); } catch (IllegalArgumentException e) { return new FailedAuthenticationHandler(400, "Some request parameters are included more than once " + request, e); } String error = requestParameters.get("error"); if (error != null) { int responseCode = decodeErrorAsResponseCode(error); String errorDescription = requestParameters.get("error_description"); if (responseCode == 403) { LOGGER.debug("Resource owner denies the access request"); return new FailedAuthenticationHandler(responseCode, "Resource owner denies the access request"); } else { LOGGER.warn("Authorization endpoint failed, error : '{}', error description '{}'", error, errorDescription); return new FailedAuthenticationHandler(responseCode, String.format("Authorization request failed :'%s'", error)); } } final String authorizationCode = requestParameters.get("code"); if (authorizationCode == null) { final String authorizationRedirectURL = buildAuthorizationRedirectURL(request, oauth2Provider); return response -> { final NamedAddressSpace addressSpace = configuration.getPort(request).getAddressSpace(request.getServerName()); LOGGER.debug("Sending redirect to authorization endpoint {}", oauth2Provider.getAuthorizationEndpointURI(addressSpace)); response.sendRedirect(authorizationRedirectURL); }; } else { final HttpSession httpSession = request.getSession(); String state = requestParameters.get("state"); if (state == null) { LOGGER.warn("Deny login attempt with wrong state: {}", state); return new FailedAuthenticationHandler(400, "No state set on request with authorization code grant: " + request); } if (!checkState(request, state)) { LOGGER.warn("Deny login attempt with wrong state: {}", state); return new FailedAuthenticationHandler(401, "Received request with wrong state: " + state); } final String redirectUri = (String) httpSession.getAttribute(HttpManagementUtil.getRequestSpecificAttributeName( REDIRECT_URI_SESSION_ATTRIBUTE, request)); final String originalRequestUri = (String) httpSession.getAttribute(HttpManagementUtil.getRequestSpecificAttributeName( ORIGINAL_REQUEST_URI_SESSION_ATTRIBUTE, request)); final NamedAddressSpace addressSpace = configuration.getPort(request).getAddressSpace(request.getServerName()); return new AuthenticationHandler() { @Override public void handleAuthentication(final HttpServletResponse response) throws IOException { AuthenticationResult authenticationResult = oauth2Provider.authenticateViaAuthorizationCode(authorizationCode, redirectUri, addressSpace); try { SubjectCreator subjectCreator = port.getSubjectCreator(request.isSecure(), request.getServerName()); SubjectAuthenticationResult result = subjectCreator.createResultWithGroups(authenticationResult); Subject original = result.getSubject(); if (original == null) { throw new SecurityException("Only authenticated users can access the management interface"); } Broker broker = (Broker) oauth2Provider.getParent(); HttpManagementUtil.createServletConnectionSubjectAssertManagementAccessAndSave(broker, request, original); LOGGER.debug("Successful login. Redirect to original resource {}", originalRequestUri); response.sendRedirect(originalRequestUri); } catch (SecurityException e) { if (e instanceof AccessControlException) { LOGGER.info("User '{}' is not authorised for management", authenticationResult.getMainPrincipal()); response.sendError(403, "User is not authorised for management"); } else { LOGGER.info("Authentication failed", authenticationResult.getCause()); response.sendError(401); } } } }; } } else { return null; } } @Override String getType(); @Override AuthenticationHandler getAuthenticationHandler(final HttpServletRequest request,
final HttpManagementConfiguration configuration); @Override LogoutHandler getLogoutHandler(final HttpServletRequest request,
final HttpManagementConfiguration configuration); } | @Test public void testInitialRedirect() throws Exception { Map<String, Object> sessionAttributes = new HashMap<>(); HttpServletRequest mockRequest = createMockRequest(TEST_REQUEST_HOST, TEST_REQUEST_PATH, Collections.singletonMap("baz", "fnord"), sessionAttributes); HttpRequestInteractiveAuthenticator.AuthenticationHandler authenticationHandler = _authenticator.getAuthenticationHandler(mockRequest, _mockConfiguration); assertNotNull("Authenticator does not feel responsible", authenticationHandler); final boolean condition = !(authenticationHandler instanceof OAuth2InteractiveAuthenticator.FailedAuthenticationHandler); assertTrue("Authenticator has failed unexpectedly", condition); HttpServletResponse mockResponse = mock(HttpServletResponse.class); authenticationHandler.handleAuthentication(mockResponse); ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class); verify(mockResponse).sendRedirect(argument.capture()); Map<String, String> params = getRedirectParameters(argument.getValue()); assertTrue("Wrong redirect host", argument.getValue().startsWith(TEST_AUTHORIZATION_ENDPOINT)); assertEquals("Wrong response_type", "code", params.get("response_type")); assertEquals("Wrong client_id", TEST_CLIENT_ID, params.get("client_id")); assertEquals("Wrong redirect_uri", TEST_REQUEST_HOST, params.get("redirect_uri")); assertEquals("Wrong scope", TEST_OAUTH2_SCOPE, params.get("scope")); String stateAttrName = HttpManagementUtil.getRequestSpecificAttributeName(OAuth2InteractiveAuthenticator.STATE_NAME, mockRequest); assertNotNull("State was not set on the session", sessionAttributes.get(stateAttrName)); assertEquals("Wrong state", (String) sessionAttributes.get(stateAttrName), params.get("state")); }
@Test public void testValidLogin() throws Exception { Map<String, Object> sessionAttributes = new HashMap<>(); sessionAttributes.put(OAuth2InteractiveAuthenticator.STATE_NAME, TEST_STATE); sessionAttributes.put(OAuth2InteractiveAuthenticator.ORIGINAL_REQUEST_URI_SESSION_ATTRIBUTE, TEST_REQUEST); sessionAttributes.put(OAuth2InteractiveAuthenticator.REDIRECT_URI_SESSION_ATTRIBUTE, TEST_REQUEST_HOST); Map<String, String> requestParameters = new HashMap<>(); requestParameters.put("state", TEST_STATE); requestParameters.put("code", TEST_VALID_AUTHORIZATION_CODE); HttpServletRequest mockRequest = createMockRequest(TEST_REQUEST_HOST, TEST_REQUEST_PATH, requestParameters, sessionAttributes); HttpRequestInteractiveAuthenticator.AuthenticationHandler authenticationHandler = _authenticator.getAuthenticationHandler(mockRequest, _mockConfiguration); assertNotNull("Authenticator does not feel responsible", authenticationHandler); final boolean condition1 = !(authenticationHandler instanceof OAuth2InteractiveAuthenticator.FailedAuthenticationHandler); assertTrue("Authenticator has failed unexpectedly", condition1); HttpServletResponse mockResponse = mock(HttpServletResponse.class); authenticationHandler.handleAuthentication(mockResponse); ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class); verify(mockResponse).sendRedirect(argument.capture()); assertEquals("Wrong redirect", TEST_REQUEST, argument.getValue()); String attrSubject = HttpManagementUtil.getRequestSpecificAttributeName(ATTR_SUBJECT, mockRequest); assertNotNull("No subject on session", sessionAttributes.get(attrSubject)); final boolean condition = sessionAttributes.get(attrSubject) instanceof Subject; assertTrue("Subject on session is no a Subject", condition); final Set<Principal> principals = ((Subject) sessionAttributes.get(attrSubject)).getPrincipals(); assertEquals("Subject created with unexpected principal", TEST_AUTHORIZED_USER, principals.iterator().next().getName()); }
@Test public void testNoStateOnSession() throws Exception { Map<String, Object> sessionAttributes = new HashMap<>(); sessionAttributes.put(OAuth2InteractiveAuthenticator.ORIGINAL_REQUEST_URI_SESSION_ATTRIBUTE, TEST_REQUEST); sessionAttributes.put(OAuth2InteractiveAuthenticator.REDIRECT_URI_SESSION_ATTRIBUTE, TEST_REQUEST_HOST); Map<String, String> requestParameters = new HashMap<>(); requestParameters.put("state", TEST_STATE); requestParameters.put("code", TEST_VALID_AUTHORIZATION_CODE); HttpServletRequest mockRequest = createMockRequest(TEST_REQUEST_HOST, TEST_REQUEST_PATH, requestParameters, sessionAttributes); HttpRequestInteractiveAuthenticator.AuthenticationHandler authenticationHandler = _authenticator.getAuthenticationHandler(mockRequest, _mockConfiguration); assertNotNull("Authenticator does not feel responsible", authenticationHandler); final boolean condition = authenticationHandler instanceof OAuth2InteractiveAuthenticator.FailedAuthenticationHandler; assertTrue("Authenticator did not fail with no state on session", condition); }
@Test public void testNoStateOnRequest() throws Exception { Map<String, Object> sessionAttributes = new HashMap<>(); sessionAttributes.put(OAuth2InteractiveAuthenticator.STATE_NAME, TEST_STATE); sessionAttributes.put(OAuth2InteractiveAuthenticator.ORIGINAL_REQUEST_URI_SESSION_ATTRIBUTE, TEST_REQUEST); sessionAttributes.put(OAuth2InteractiveAuthenticator.REDIRECT_URI_SESSION_ATTRIBUTE, TEST_REQUEST_HOST); Map<String, String> requestParameters = new HashMap<>(); requestParameters.put("code", TEST_VALID_AUTHORIZATION_CODE); HttpServletRequest mockRequest = createMockRequest(TEST_REQUEST_HOST, TEST_REQUEST_PATH, requestParameters, sessionAttributes); HttpRequestInteractiveAuthenticator.AuthenticationHandler authenticationHandler = _authenticator.getAuthenticationHandler(mockRequest, _mockConfiguration); assertNotNull("Authenticator does not feel responsible", authenticationHandler); final boolean condition = authenticationHandler instanceof OAuth2InteractiveAuthenticator.FailedAuthenticationHandler; assertTrue("Authenticator did not fail with no state on request", condition); }
@Test public void testWrongStateOnRequest() throws Exception { Map<String, Object> sessionAttributes = new HashMap<>(); sessionAttributes.put(OAuth2InteractiveAuthenticator.STATE_NAME, TEST_STATE); sessionAttributes.put(OAuth2InteractiveAuthenticator.ORIGINAL_REQUEST_URI_SESSION_ATTRIBUTE, TEST_REQUEST); sessionAttributes.put(OAuth2InteractiveAuthenticator.REDIRECT_URI_SESSION_ATTRIBUTE, TEST_REQUEST_HOST); Map<String, String> requestParameters = new HashMap<>(); requestParameters.put("state", "WRONG" + TEST_STATE); requestParameters.put("code", TEST_VALID_AUTHORIZATION_CODE); HttpServletRequest mockRequest = createMockRequest(TEST_REQUEST_HOST, TEST_REQUEST_PATH, requestParameters, sessionAttributes); HttpRequestInteractiveAuthenticator.AuthenticationHandler authenticationHandler = _authenticator.getAuthenticationHandler(mockRequest, _mockConfiguration); assertNotNull("Authenticator does not feel responsible", authenticationHandler); final boolean condition = authenticationHandler instanceof OAuth2InteractiveAuthenticator.FailedAuthenticationHandler; assertTrue("Authenticator did not fail with wrong state on request", condition); }
@Test public void testInvalidAuthorizationCode() throws Exception { Map<String, Object> sessionAttributes = new HashMap<>(); sessionAttributes.put(OAuth2InteractiveAuthenticator.STATE_NAME, TEST_STATE); sessionAttributes.put(OAuth2InteractiveAuthenticator.ORIGINAL_REQUEST_URI_SESSION_ATTRIBUTE, TEST_REQUEST); sessionAttributes.put(OAuth2InteractiveAuthenticator.REDIRECT_URI_SESSION_ATTRIBUTE, TEST_REQUEST_HOST); Map<String, String> requestParameters = new HashMap<>(); requestParameters.put("state", TEST_STATE); requestParameters.put("code", TEST_INVALID_AUTHORIZATION_CODE); HttpServletRequest mockRequest = createMockRequest(TEST_REQUEST_HOST, TEST_REQUEST_PATH, requestParameters, sessionAttributes); HttpRequestInteractiveAuthenticator.AuthenticationHandler authenticationHandler = _authenticator.getAuthenticationHandler(mockRequest, _mockConfiguration); assertNotNull("Authenticator does not feel responsible", authenticationHandler); final boolean condition = !(authenticationHandler instanceof OAuth2InteractiveAuthenticator.FailedAuthenticationHandler); assertTrue("Authenticator has failed unexpectedly", condition); HttpServletResponse mockResponse = mock(HttpServletResponse.class); authenticationHandler.handleAuthentication(mockResponse); verify(mockResponse).sendError(eq(401)); }
@Test public void testUnauthorizedAuthorizationCode() throws Exception { Map<String, Object> sessionAttributes = new HashMap<>(); sessionAttributes.put(OAuth2InteractiveAuthenticator.STATE_NAME, TEST_STATE); sessionAttributes.put(OAuth2InteractiveAuthenticator.ORIGINAL_REQUEST_URI_SESSION_ATTRIBUTE, TEST_REQUEST); sessionAttributes.put(OAuth2InteractiveAuthenticator.REDIRECT_URI_SESSION_ATTRIBUTE, TEST_REQUEST_HOST); Map<String, String> requestParameters = new HashMap<>(); requestParameters.put("state", TEST_STATE); requestParameters.put("code", TEST_UNAUTHORIZED_AUTHORIZATION_CODE); HttpServletRequest mockRequest = createMockRequest(TEST_REQUEST_HOST, TEST_REQUEST_PATH, requestParameters, sessionAttributes); HttpRequestInteractiveAuthenticator.AuthenticationHandler authenticationHandler = _authenticator.getAuthenticationHandler(mockRequest, _mockConfiguration); assertNotNull("Authenticator does not feel responsible", authenticationHandler); final boolean condition = !(authenticationHandler instanceof OAuth2InteractiveAuthenticator.FailedAuthenticationHandler); assertTrue("Authenticator has failed unexpectedly", condition); HttpServletResponse mockResponse = mock(HttpServletResponse.class); authenticationHandler.handleAuthentication(mockResponse); verify(mockResponse).sendError(eq(403), any(String.class)); } |
OAuth2PreemptiveAuthenticator implements HttpRequestPreemptiveAuthenticator { @Override public Subject attemptAuthentication(final HttpServletRequest request, final HttpManagementConfiguration configuration) { final Port<?> port = configuration.getPort(request); final AuthenticationProvider<?> authenticationProvider = configuration.getAuthenticationProvider(request); String authorizationHeader = request.getHeader("Authorization"); String accessToken = null; if (authorizationHeader != null && authorizationHeader.startsWith(BEARER_PREFIX)) { accessToken = authorizationHeader.substring(BEARER_PREFIX.length()); } if (accessToken != null && authenticationProvider instanceof OAuth2AuthenticationProvider) { OAuth2AuthenticationProvider<?> oAuth2AuthProvider = (OAuth2AuthenticationProvider<?>) authenticationProvider; AuthenticationResult authenticationResult = oAuth2AuthProvider.authenticateViaAccessToken(accessToken, null); SubjectCreator subjectCreator = port.getSubjectCreator(request.isSecure(), request.getServerName()); SubjectAuthenticationResult result = subjectCreator.createResultWithGroups(authenticationResult); return result.getSubject(); } return null; } @Override Subject attemptAuthentication(final HttpServletRequest request,
final HttpManagementConfiguration configuration); @Override String getType(); } | @Test public void testAttemptAuthenticationSuccessful() throws Exception { HttpServletRequest mockRequest = mock(HttpServletRequest.class); when(mockRequest.getServerName()).thenReturn("localhost"); when(mockRequest.getHeader("Authorization")).thenReturn("Bearer " + TEST_VALID_ACCESS_TOKEN); Subject subject = _authenticator.attemptAuthentication(mockRequest, _mockConfiguration); assertNotNull("Authenticator failed unexpectedly", subject); final Set<Principal> principals = subject.getPrincipals(); assertEquals("Subject created with unexpected principal", TEST_AUTHORIZED_USER, principals.iterator().next().getName()); }
@Test public void testAttemptAuthenticationUnauthorizedUser() throws Exception { HttpServletRequest mockRequest = mock(HttpServletRequest.class); when(mockRequest.getServerName()).thenReturn("localhost"); when(mockRequest.getHeader("Authorization")).thenReturn("Bearer " + TEST_UNAUTHORIZED_ACCESS_TOKEN); Subject subject = _authenticator.attemptAuthentication(mockRequest, _mockConfiguration); assertNotNull("Authenticator failed unexpectedly", subject); final Set<Principal> principals = subject.getPrincipals(); assertEquals("Subject created with unexpected principal", TEST_UNAUTHORIZED_USER, principals.iterator().next().getName()); }
@Test public void testAttemptAuthenticationInvalidToken() throws Exception { HttpServletRequest mockRequest = mock(HttpServletRequest.class); when(mockRequest.getServerName()).thenReturn("localhost"); when(mockRequest.getHeader("Authorization")).thenReturn("Bearer " + TEST_INVALID_ACCESS_TOKEN); Subject subject = _authenticator.attemptAuthentication(mockRequest, _mockConfiguration); assertNull("Authenticator did not fail with invalid access token", subject); }
@Test public void testAttemptAuthenticationMissingHeader() throws Exception { HttpServletRequest mockRequest = mock(HttpServletRequest.class); Subject subject = _authenticator.attemptAuthentication(mockRequest, _mockConfiguration); assertNull("Authenticator did not failed without authentication header", subject); }
@Test public void testAttemptAuthenticationMalformedHeader() throws Exception { HttpServletRequest mockRequest = mock(HttpServletRequest.class); when(mockRequest.getHeader("Authorization")).thenReturn("malformed Bearer " + TEST_UNAUTHORIZED_ACCESS_TOKEN); Subject subject = _authenticator.attemptAuthentication(mockRequest, _mockConfiguration); assertNull("Authenticator did not failed with malformed authentication header", subject); } |
PrometheusContentFactory implements ContentFactory { @Override public Content createContent(final ConfiguredObject<?> object, final Map<String, String[]> filter) { final String[] includeDisabledValues = filter.get(INCLUDE_DISABLED); boolean includeDisabled = includeDisabledValues!= null && includeDisabledValues.length == 1 && Boolean.parseBoolean(includeDisabledValues[0]); if (!includeDisabled) { Boolean val = object.getContextValue(Boolean.class, INCLUDE_DISABLED_CONTEXT_VARIABLE); if (val != null) { includeDisabled = val; } } final String[] includedMetricNames = filter.get(INCLUDE_METRIC); final IncludeMetricPredicate metricIncludeFilter = new IncludeMetricPredicate(includedMetricNames == null || includedMetricNames.length == 0 ? Collections.emptySet() : new HashSet<>(Arrays.asList(includedMetricNames))); final QpidCollector qpidCollector = new QpidCollector(object, new IncludeDisabledStatisticPredicate(includeDisabled), metricIncludeFilter); return new Content() { @Override public void write(final OutputStream outputStream) throws IOException { try (final Writer writer = new OutputStreamWriter(outputStream)) { TextFormat.write004(writer, Collections.enumeration(qpidCollector.collect())); writer.flush(); } } @Override public void release() { } @SuppressWarnings("unused") @RestContentHeader("Content-Type") public String getContentType() { return TextFormat.CONTENT_TYPE_004; } }; } @Override Content createContent(final ConfiguredObject<?> object, final Map<String, String[]> filter); @Override String getType(); } | @Test public void testCreateContent() throws Exception { final Content content = _prometheusContentFactory.createContent(_root, Collections.emptyMap()); assertThat(content, is(notNullValue())); Collection<String> metrics; try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { content.write(output); metrics = getMetricLines(output.toByteArray()); } assertThat(metrics, is(notNullValue())); assertThat(metrics.size(), is(equalTo(1))); String metric = metrics.iterator().next(); assertThat(metric, startsWith(QPID_TEST_CAR_MILEAGE_COUNT)); }
@Test public void testCreateContentIncludeDisabled() throws Exception { final Content content = _prometheusContentFactory.createContent(_root, Collections.singletonMap(INCLUDE_DISABLED, new String[]{"true"})); assertThat(content, is(notNullValue())); Collection<String> metrics; try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { content.write(output); metrics = getMetricLines(output.toByteArray()); } assertThat(metrics, is(notNullValue())); assertThat(metrics.size(), is(equalTo(2))); Map<String, String> metricsMap = convertMetricsToMap(metrics); assertThat(metricsMap.containsKey(QPID_TEST_CAR_MILEAGE_COUNT), equalTo(Boolean.TRUE)); assertThat(metricsMap.containsKey(QPID_TEST_CAR_AGE), equalTo(Boolean.TRUE)); }
@Test public void testCreateContentIncludeDisabledUsingContextVariable() throws Exception { _root.setContextVariable(INCLUDE_DISABLED_CONTEXT_VARIABLE, "true"); final Content content = _prometheusContentFactory.createContent(_root, Collections.emptyMap()); assertThat(content, is(notNullValue())); Collection<String> metrics; try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { content.write(output); metrics = getMetricLines(output.toByteArray()); } assertThat(metrics, is(notNullValue())); assertThat(metrics.size(), is(equalTo(2))); Map<String, String> metricsMap = convertMetricsToMap(metrics); assertThat(metricsMap.containsKey(QPID_TEST_CAR_MILEAGE_COUNT), equalTo(Boolean.TRUE)); assertThat(metricsMap.containsKey(QPID_TEST_CAR_AGE), equalTo(Boolean.TRUE)); }
@Test public void testCreateContentIncludeName() throws Exception { final Map<String, String[]> filter = new HashMap<>(); filter.put(INCLUDE_DISABLED, new String[]{"true"}); filter.put(INCLUDE_METRIC, new String[]{QPID_TEST_CAR_AGE}); final Content content = _prometheusContentFactory.createContent(_root, filter); assertThat(content, is(notNullValue())); Collection<String> metrics; try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { content.write(output); metrics = getMetricLines(output.toByteArray()); } assertThat(metrics, is(notNullValue())); assertThat(metrics.size(), is(equalTo(1))); String metric = metrics.iterator().next(); assertThat(metric, startsWith(QPID_TEST_CAR_AGE)); } |
QpidCollector extends Collector { @Override public List<MetricFamilySamples> collect() { final List<MetricFamilySamples> metricFamilySamples = new ArrayList<>(); addObjectMetrics(_root, Collections.emptyList(), new HashMap<>(), metricFamilySamples); addChildrenMetrics(metricFamilySamples, _root, Collections.singletonList("name")); return metricFamilySamples; } QpidCollector(final ConfiguredObject<?> root,
final Predicate<ConfiguredObjectStatistic<?,?>> includeStatisticFilter,
final Predicate<String> includeMetricFilter); @Override List<MetricFamilySamples> collect(); } | @Test public void testCollectForHierarchyOfTwoObjects() { createTestEngine(ELECTRIC_ENGINE_NAME, TestElecEngineImpl.TEST_ELEC_ENGINE_TYPE); _root.move(DESIRED_MILEAGE); final List<Collector.MetricFamilySamples> metrics = _qpidCollector.collect(); final String[] expectedFamilyNames = {QPID_TEST_CAR_MILEAGE_COUNT, QPID_TEST_ENGINE_TEMPERATURE_TOTAL}; final Map<String, Collector.MetricFamilySamples> metricsMap = convertMetricFamilySamplesIntoMapAndAssert(metrics, expectedFamilyNames); final Collector.MetricFamilySamples carMetricFamilySamples = metricsMap.get(QPID_TEST_CAR_MILEAGE_COUNT); assertMetricFamilySamplesSize(carMetricFamilySamples, 1); final Collector.MetricFamilySamples.Sample carSample = carMetricFamilySamples.samples.get(0); assertThat(carSample.value, closeTo(DESIRED_MILEAGE, 0.01)); assertThat(carSample.labelNames.size(), is(equalTo(0))); final Collector.MetricFamilySamples engineMetricFamilySamples = metricsMap.get( QPID_TEST_ENGINE_TEMPERATURE_TOTAL); assertMetricFamilySamplesSize(engineMetricFamilySamples, 1); final Collector.MetricFamilySamples.Sample engineSample = engineMetricFamilySamples.samples.get(0); assertThat(engineSample.labelNames, is(equalTo(Collections.singletonList("name")))); assertThat(engineSample.labelValues, is(equalTo(Collections.singletonList(ELECTRIC_ENGINE_NAME)))); assertThat(engineSample.value, Matchers.closeTo(TestAbstractEngineImpl.TEST_TEMPERATURE, 0.01)); }
@Test public void testCollectForHierarchyOfThreeObjects() { final TestInstrumentPanel instrumentPanel = getTestInstrumentPanel(); createTestSensor(instrumentPanel); final List<Collector.MetricFamilySamples> metrics = _qpidCollector.collect(); final String[] expectedFamilyNames = {QPID_TEST_CAR_MILEAGE_COUNT, QPID_TEST_SENSOR_ALERT_COUNT}; final Map<String, Collector.MetricFamilySamples> metricsMap = convertMetricFamilySamplesIntoMapAndAssert(metrics, expectedFamilyNames); final Collector.MetricFamilySamples carMetricFamilySamples = metricsMap.get(QPID_TEST_CAR_MILEAGE_COUNT); assertMetricFamilySamplesSize(carMetricFamilySamples, 1); final Collector.MetricFamilySamples.Sample carSample = carMetricFamilySamples.samples.get(0); assertThat(carSample.labelNames.size(), is(equalTo(0))); assertThat(carSample.labelValues.size(), is(equalTo(0))); assertThat(carSample.value, closeTo(0, 0.01)); final Collector.MetricFamilySamples sensorlMetricFamilySamples = metricsMap.get(QPID_TEST_SENSOR_ALERT_COUNT); assertMetricFamilySamplesSize(sensorlMetricFamilySamples, 1); final Collector.MetricFamilySamples.Sample sensorSample = sensorlMetricFamilySamples.samples.get(0); assertThat(sensorSample.labelNames, is(equalTo(Arrays.asList("name", "test_instrument_panel_name")))); assertThat(sensorSample.labelValues, is(equalTo(Arrays.asList(SENSOR, INSTRUMENT_PANEL_NAME)))); }
@Test public void testCollectForSiblingObjects() { createTestEngine(ELECTRIC_ENGINE_NAME, TestElecEngineImpl.TEST_ELEC_ENGINE_TYPE); createTestEngine(PETROL_ENGINE_NAME, TestPetrolEngineImpl.TEST_PETROL_ENGINE_TYPE); final List<Collector.MetricFamilySamples> metrics = _qpidCollector.collect(); final String[] expectedFamilyNames = {QPID_TEST_CAR_MILEAGE_COUNT, QPID_TEST_ENGINE_TEMPERATURE_TOTAL}; final Map<String, Collector.MetricFamilySamples> metricsMap = convertMetricFamilySamplesIntoMapAndAssert(metrics, expectedFamilyNames); final Collector.MetricFamilySamples carMetricFamilySamples = metricsMap.get(QPID_TEST_CAR_MILEAGE_COUNT); assertMetricFamilySamplesSize(carMetricFamilySamples, 1); final Collector.MetricFamilySamples.Sample carSample = carMetricFamilySamples.samples.get(0); assertThat(carSample.labelNames.size(), is(equalTo(0))); assertThat(carSample.labelValues.size(), is(equalTo(0))); final Collector.MetricFamilySamples engineMetricFamilySamples = metricsMap.get( QPID_TEST_ENGINE_TEMPERATURE_TOTAL); assertMetricFamilySamplesSize(engineMetricFamilySamples, 2); final String[] engineNames = {PETROL_ENGINE_NAME, ELECTRIC_ENGINE_NAME}; for (String engineName : engineNames) { final Collector.MetricFamilySamples.Sample sample = findSampleByLabelValue(engineMetricFamilySamples, engineName); assertThat(sample.labelNames, is(equalTo(Collections.singletonList("name")))); assertThat(sample.labelValues, is(equalTo(Collections.singletonList(engineName)))); assertThat(sample.value, Matchers.closeTo(TestAbstractEngineImpl.TEST_TEMPERATURE, 0.01)); } }
@Test public void testCollectWithFilter(){ createTestEngine(ELECTRIC_ENGINE_NAME, TestElecEngineImpl.TEST_ELEC_ENGINE_TYPE); _root.move(DESIRED_MILEAGE); _qpidCollector = new QpidCollector(_root, new IncludeDisabledStatisticPredicate(true), new IncludeMetricPredicate(Collections.singleton(QPID_TEST_CAR_AGE_COUNT))); final List<Collector.MetricFamilySamples> metrics = _qpidCollector.collect(); final String[] expectedFamilyNames = {QPID_TEST_CAR_AGE_COUNT}; final Map<String, Collector.MetricFamilySamples> metricsMap = convertMetricFamilySamplesIntoMapAndAssert(metrics, expectedFamilyNames); final Collector.MetricFamilySamples engineMetricFamilySamples = metricsMap.get(QPID_TEST_CAR_AGE_COUNT); assertMetricFamilySamplesSize(engineMetricFamilySamples, 1); final Collector.MetricFamilySamples.Sample engineSample = engineMetricFamilySamples.samples.get(0); assertThat(engineSample.labelNames, is(equalTo(Collections.emptyList()))); assertThat(engineSample.labelValues, is(equalTo(Collections.emptyList()))); assertThat(engineSample.value, Matchers.closeTo(0.0, 0.01)); } |
QpidCollector extends Collector { static String toSnakeCase(final String simpleName) { final StringBuilder sb = new StringBuilder(); final char[] chars = simpleName.toCharArray(); for (int i = 0; i < chars.length; i++) { final char ch = chars[i]; if (Character.isUpperCase(ch)) { if (i > 0) { sb.append('_'); } sb.append(Character.toLowerCase(ch)); } else { sb.append(ch); } } return sb.toString(); } QpidCollector(final ConfiguredObject<?> root,
final Predicate<ConfiguredObjectStatistic<?,?>> includeStatisticFilter,
final Predicate<String> includeMetricFilter); @Override List<MetricFamilySamples> collect(); } | @Test public void testToSnakeCase() { assertThat(QpidCollector.toSnakeCase("carEngineOilChanges"), is(equalTo("car_engine_oil_changes"))); } |
QpidCollector extends Collector { static String getFamilyName(final Class<? extends ConfiguredObject> categoryClass, ConfiguredObjectStatistic<?, ?> statistics) { String metricName = statistics.getMetricName(); if (metricName == null || metricName.isEmpty()) { metricName = generateMetricName(statistics); } return String.format("qpid_%s_%s", toSnakeCase(categoryClass.getSimpleName()), metricName); } QpidCollector(final ConfiguredObject<?> root,
final Predicate<ConfiguredObjectStatistic<?,?>> includeStatisticFilter,
final Predicate<String> includeMetricFilter); @Override List<MetricFamilySamples> collect(); } | @Test public void getFamilyNameForCumulativeStatistic() { for (int i = 0; i < UNITS.length; i++) { final ConfiguredObjectStatistic<?, ?> statistics = mock(ConfiguredObjectStatistic.class); when(statistics.getUnits()).thenReturn(UNITS[i]); when(statistics.getStatisticType()).thenReturn(StatisticType.CUMULATIVE); when(statistics.getName()).thenReturn("diagnosticData"); final String familyName = QpidCollector.getFamilyName(TestCar.class, statistics); final String expectedName = String.format("qpid_test_car_diagnostic_data%s%s", UNIT_SUFFIXES[i], getSuffix(UNITS[i],QpidCollector.COUNT_SUFFIX)); assertThat(String.format("unexpected metric name for units %s", UNITS[i]), familyName, is(equalTo(expectedName))); } }
@Test public void getFamilyNameForCumulativeStatisticContainingCountInName() { final ConfiguredObjectStatistic<?, ?> statistics = mock(ConfiguredObjectStatistic.class); when(statistics.getUnits()).thenReturn(StatisticUnit.BYTES); when(statistics.getStatisticType()).thenReturn(StatisticType.CUMULATIVE); when(statistics.getName()).thenReturn("CountOfDiagnosticData"); final String familyName = QpidCollector.getFamilyName(TestCar.class, statistics); assertThat(familyName, is(equalTo("qpid_test_car_count_of_diagnostic_data"))); }
@Test public void getFamilyNameForPointInTimeStatistic() { for (int i = 0; i < UNITS.length; i++) { final ConfiguredObjectStatistic<?, ?> statistics = mock(ConfiguredObjectStatistic.class); when(statistics.getUnits()).thenReturn(UNITS[i]); when(statistics.getStatisticType()).thenReturn(StatisticType.POINT_IN_TIME); when(statistics.getName()).thenReturn("diagnosticData"); final String familyName = QpidCollector.getFamilyName(TestCar.class, statistics); final String expectedName = String.format("qpid_test_car_diagnostic_data%s%s", UNIT_SUFFIXES[i], getSuffix(UNITS[i],QpidCollector.TOTAL_SUFFIX)); assertThat(String.format("unexpected metric name for units %s", UNITS[i]), familyName, is(equalTo(expectedName))); } } |
ArrayUtils { public static <T> T[] clone(T[] array) { return array != null ? array.clone() : null; } private ArrayUtils(); static T[] clone(T[] array); static boolean isEmpty(Object[] array); } | @Test public void testClone_NullInput() { assertNull(ArrayUtils.clone(null)); }
@Test public void testClone_EmptyInput() { String[] data = new String[0]; String[] result = ArrayUtils.clone(data); assertArrayEquals(data, result); assertNotSame(data, result); }
@Test public void testClone() { String[] data = new String[]{"A", null, "B", "CC"}; String[] result = ArrayUtils.clone(data); assertArrayEquals(data, result); assertNotSame(data, result); } |
UnsettledDelivery { public Binary getDeliveryTag() { return _deliveryTag; } UnsettledDelivery(final Binary deliveryTag, final LinkEndpoint<?, ?> linkEndpoint); Binary getDeliveryTag(); LinkEndpoint<?, ?> getLinkEndpoint(); @Override boolean equals(final Object o); @Override int hashCode(); } | @Test public void testGetDeliveryTag() { assertThat(_unsettledDelivery.getDeliveryTag(), is(equalTo(_deliveryTag))); } |
ArrayUtils { public static boolean isEmpty(Object[] array) { return array == null || array.length == 0; } private ArrayUtils(); static T[] clone(T[] array); static boolean isEmpty(Object[] array); } | @Test public void testIsEmpty_NullInput() { assertTrue(ArrayUtils.isEmpty(null)); }
@Test public void testIsEmpty_EmptyInput() { assertTrue(ArrayUtils.isEmpty(new String[0])); }
@Test public void testIsEmpty() { assertFalse(ArrayUtils.isEmpty(new String[]{"A"})); assertFalse(ArrayUtils.isEmpty(new String[]{"A", "B"})); assertFalse(ArrayUtils.isEmpty(new String[]{null})); } |
CallerDataFilter { public StackTraceElement[] filter(StackTraceElement[] elements) { if (elements == null) { return new StackTraceElement[0]; } for (int depth = elements.length - 1; depth >= 0; --depth) { final StackTraceElement element = elements[depth]; if (isMessageMethod(element.getMethodName()) && isMessageLogger(element.getClassName())) { final int length = elements.length - (depth + 1); if (length > 0) { final StackTraceElement[] stackTrace = new StackTraceElement[length]; System.arraycopy(elements, depth + 1, stackTrace, 0, length); return stackTrace; } return elements; } } return elements; } StackTraceElement[] filter(StackTraceElement[] elements); } | @Test public void testFilter_nullAsInput() { StackTraceElement[] result = _filter.filter(null); assertNotNull(result); assertEquals(0, result.length); }
@Test public void testFilter_emptyInput() { StackTraceElement[] result = _filter.filter(new StackTraceElement[0]); assertNotNull(result); assertEquals(0, result.length); }
@Test public void testFilter_withoutLogger() { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); StackTraceElement[] result = _filter.filter(stackTrace); assertNotNull(result); assertTrue(Arrays.deepEquals(stackTrace, result)); }
@Test public void testFilter_withLogger() { _logger.message(() -> "ClassName"); StackTraceElement[] result = _filter.filter(_logger.getStackTrace()); assertNotNull(result); final String loggerName = _logger.getClass().getName(); assertFalse(Arrays.stream(result).anyMatch(e -> e.getClassName().contains(loggerName))); }
@Test public void testFilter_withLogger_InvalidMethod() { _logger.isEnabled(); StackTraceElement[] stackTrace = _logger.getStackTrace(); StackTraceElement[] result = _filter.filter(_logger.getStackTrace()); assertNotNull(result); assertTrue(Arrays.deepEquals(stackTrace, result)); }
@Test public void testFilter_withLoggerOnly() { _logger.message(() -> "ClassName"); final String loggerName = _logger.getClass().getName(); StackTraceElement[] stackTrace = Arrays.stream(_logger.getStackTrace()) .filter(e -> e.getClassName().contains(loggerName)) .toArray(StackTraceElement[]::new); StackTraceElement[] result = _filter.filter(stackTrace); assertNotNull(result); assertTrue(Arrays.deepEquals(stackTrace, result)); }
@Test public void testFilter_withUnknownClass() { StackTraceElement element1 = new StackTraceElement("unknown_class_xyz", "message", "file", 7); StackTraceElement element2 = new StackTraceElement("unknown_class_xyz", "message", "file", 17); final StackTraceElement[] stackTrace = {element1, element2}; StackTraceElement[] result = _filter.filter(stackTrace); assertNotNull(result); assertTrue(Arrays.deepEquals(stackTrace, result)); } |
UnsettledDelivery { public LinkEndpoint<?, ?> getLinkEndpoint() { return _linkEndpoint; } UnsettledDelivery(final Binary deliveryTag, final LinkEndpoint<?, ?> linkEndpoint); Binary getDeliveryTag(); LinkEndpoint<?, ?> getLinkEndpoint(); @Override boolean equals(final Object o); @Override int hashCode(); } | @Test public void testGetLinkEndpoint() { assertThat(_unsettledDelivery.getLinkEndpoint(), is(equalTo(_linkEndpoint))); } |
GelfMessageStaticFields implements Validator<Map<String, Object>> { public static Validator<Map<String, Object>> validator() { return VALIDATOR; } private GelfMessageStaticFields(); static Validator<Map<String, Object>> validator(); static void validateStaticFields(Map<String, Object> value, ConfiguredObject<?> object, String attribute); @Override void validate(Map<String, Object> map, final ConfiguredObject<?> object, final String attribute); } | @Test public void testValidator() { assertNotNull("Factory method has to produce a instance", GelfMessageStaticFields.validator()); } |
GelfMessageStaticFields implements Validator<Map<String, Object>> { public static void validateStaticFields(Map<String, Object> value, ConfiguredObject<?> object, String attribute) { validator().validate(value, object, attribute); } private GelfMessageStaticFields(); static Validator<Map<String, Object>> validator(); static void validateStaticFields(Map<String, Object> value, ConfiguredObject<?> object, String attribute); @Override void validate(Map<String, Object> map, final ConfiguredObject<?> object, final String attribute); } | @Test public void testValidate_NullAsInput() { TestConfiguredObject object = new TestConfiguredObject(); try { GelfMessageStaticFields.validateStaticFields(null, object, "attr"); fail("An exception is expected"); } catch (IllegalConfigurationException e) { assertEquals("Attribute 'attr instance of org.apache.qpid.server.logging.logback.validator.TestConfiguredObject named 'TestConfiguredObject' cannot be 'null'", e.getMessage()); } catch (RuntimeException e) { fail("A generic exception is not expected"); } }
@Test public void testValidateKey_NullAsInput() { TestConfiguredObject object = new TestConfiguredObject(); try { Map<String, Object> map = new HashMap<>(); map.put("B", "B"); map.put(null, "A"); GelfMessageStaticFields.validateStaticFields(map, object, "attr"); fail("An exception is expected"); } catch (IllegalConfigurationException e) { assertEquals("Key of 'attr attribute instance of org.apache.qpid.server.logging.logback.validator.TestConfiguredObject named 'TestConfiguredObject' cannot be 'null'. Key pattern is: [\\w\\.\\-]+", e.getMessage()); } catch (RuntimeException e) { fail("A generic exception is not expected"); } }
@Test public void testValidateValue_NullAsInput() { TestConfiguredObject object = new TestConfiguredObject(); try { Map<String, Object> map = new HashMap<>(); map.put("B", "B"); map.put("A", null); GelfMessageStaticFields.validateStaticFields(map, object, "attr"); fail("An exception is expected"); } catch (IllegalConfigurationException e) { assertEquals("Value of 'attr attribute instance of org.apache.qpid.server.logging.logback.validator.TestConfiguredObject named 'TestConfiguredObject' cannot be 'null', as it has to be a string or number", e.getMessage()); } catch (RuntimeException e) { fail("A generic exception is not expected"); } }
@Test public void testValidateKey_ValidInput() { TestConfiguredObject object = new TestConfiguredObject(); try { Map<String, Object> map = new HashMap<>(); map.put("B", "AB"); map.put("A", 234); GelfMessageStaticFields.validateStaticFields(map, object, "attr"); } catch (RuntimeException e) { fail("Any exception is not expected"); } }
@Test public void testValidateKey_InvalidInput() { TestConfiguredObject object = new TestConfiguredObject(); try { GelfMessageStaticFields.validateStaticFields(Collections.singletonMap("{abc}", "true"), object, "attr"); fail("An exception is expected"); } catch (IllegalConfigurationException e) { assertEquals("Key of 'attr attribute instance of org.apache.qpid.server.logging.logback.validator.TestConfiguredObject named 'TestConfiguredObject' cannot be '{abc}'. Key pattern is: [\\w\\.\\-]+", e.getMessage()); } catch (RuntimeException e) { fail("A generic exception is not expected"); } }
@Test public void testValidateValue_InvalidInput() { TestConfiguredObject object = new TestConfiguredObject(); try { GelfMessageStaticFields.validateStaticFields(Collections.singletonMap("A", true), object, "attr"); fail("An exception is expected"); } catch (IllegalConfigurationException e) { assertEquals("Value of 'attr attribute instance of org.apache.qpid.server.logging.logback.validator.TestConfiguredObject named 'TestConfiguredObject' cannot be 'true', as it has to be a string or number", e.getMessage()); } catch (RuntimeException e) { fail("A generic exception is not expected"); } } |
Port implements Validator<Integer>, Predicate<Integer> { public static Validator<Integer> validator() { return VALIDATOR; } private Port(); static Validator<Integer> validator(); static void validatePort(Integer value, ConfiguredObject<?> object, String attribute); @Override boolean test(Integer value); @Override void validate(Integer value, ConfiguredObject<?> object, String attribute); } | @Test public void testValidator() { assertNotNull("Factory method has to produce a instance", Port.validator()); } |
Port implements Validator<Integer>, Predicate<Integer> { public static void validatePort(Integer value, ConfiguredObject<?> object, String attribute) { validator().validate(value, object, attribute); } private Port(); static Validator<Integer> validator(); static void validatePort(Integer value, ConfiguredObject<?> object, String attribute); @Override boolean test(Integer value); @Override void validate(Integer value, ConfiguredObject<?> object, String attribute); } | @Test public void testValidate_NullAsInput() { TestConfiguredObject object = new TestConfiguredObject(); try { Port.validatePort(null, object, "attr"); fail("An exception is expected"); } catch (IllegalConfigurationException e) { assertEquals("Attribute 'attr' instance of org.apache.qpid.server.logging.logback.validator.TestConfiguredObject named 'TestConfiguredObject' cannot have value 'null' as it has to be in range [1, 65535]", e.getMessage()); } catch (RuntimeException e) { fail("A generic exception is not expected"); } }
@Test public void testValidate_ValidInput() { TestConfiguredObject object = new TestConfiguredObject(); try { Port.validatePort(14420, object, "attr"); } catch (RuntimeException e) { fail("Any exception is not expected"); } }
@Test public void testValidate_InvalidInput() { TestConfiguredObject object = new TestConfiguredObject(); try { Port.validatePort(170641, object, "attr"); fail("An exception is expected"); } catch (IllegalConfigurationException e) { assertEquals("Attribute 'attr' instance of org.apache.qpid.server.logging.logback.validator.TestConfiguredObject named 'TestConfiguredObject' cannot have value '170641' as it has to be in range [1, 65535]", e.getMessage()); } catch (RuntimeException e) { fail("A generic exception is not expected"); } } |
UnsettledDelivery { @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final UnsettledDelivery that = (UnsettledDelivery) o; return Objects.equals(_deliveryTag, that._deliveryTag) && Objects.equals(_linkEndpoint, that._linkEndpoint); } UnsettledDelivery(final Binary deliveryTag, final LinkEndpoint<?, ?> linkEndpoint); Binary getDeliveryTag(); LinkEndpoint<?, ?> getLinkEndpoint(); @Override boolean equals(final Object o); @Override int hashCode(); } | @Test public void testEqualsToNewUnsettledDeliveryWithTheSameFields() { assertThat(_unsettledDelivery.equals(new UnsettledDelivery(_deliveryTag, _linkEndpoint)), is(equalTo(true))); }
@Test public void testEqualsToNewUnsettledDeliveryWithEqualsFields() { assertThat(_unsettledDelivery.equals(new UnsettledDelivery(new Binary(DATA), _linkEndpoint)), is(equalTo(true))); }
@Test public void testNotEqualsWhenDeliveryTagIsDifferent() { assertThat(_unsettledDelivery.equals(new UnsettledDelivery(new Binary(new byte[]{(byte) 32, (byte) 33}), _linkEndpoint)), is(equalTo(false))); }
@Test public void testNotEqualsWhenLinkEndpointIsDifferent() { final LinkEndpoint<?, ?> linkEndpoint = mock(LinkEndpoint.class); assertThat(_unsettledDelivery.equals(new UnsettledDelivery(new Binary(new byte[]{(byte) 32, (byte) 33}), linkEndpoint)), is(equalTo(false))); } |
AtLeastZero extends AtLeast { public static Validator<Integer> validator() { return VALIDATOR; } private AtLeastZero(); static Validator<Integer> validator(); static void validateValue(Integer value, ConfiguredObject<?> object, String attribute); } | @Test public void validator() { assertNotNull("Factory method has to produce a instance", AtLeastZero.validator()); } |
AtLeastZero extends AtLeast { public static void validateValue(Integer value, ConfiguredObject<?> object, String attribute) { validator().validate(value, object, attribute); } private AtLeastZero(); static Validator<Integer> validator(); static void validateValue(Integer value, ConfiguredObject<?> object, String attribute); } | @Test public void testValidate_NullAsInput() { TestConfiguredObject object = new TestConfiguredObject(); try { AtLeastZero.validateValue(null, object, "attr"); fail("An exception is expected"); } catch (IllegalConfigurationException e) { assertEquals("Attribute 'attr' instance of org.apache.qpid.server.logging.logback.validator.TestConfiguredObject named 'TestConfiguredObject' cannot have value 'null' as it has to be at least 0", e.getMessage()); } catch (RuntimeException e) { fail("A generic exception is not expected"); } }
@Test public void testValidate_ValidInput() { TestConfiguredObject object = new TestConfiguredObject(); try { AtLeastZero.validateValue(2, object, "attr"); } catch (RuntimeException e) { fail("Any exception is not expected"); } }
@Test public void testValidate_InvalidInput() { TestConfiguredObject object = new TestConfiguredObject(); try { AtLeastZero.validateValue(-1, object, "attr"); fail("An exception is expected"); } catch (IllegalConfigurationException e) { assertEquals("Attribute 'attr' instance of org.apache.qpid.server.logging.logback.validator.TestConfiguredObject named 'TestConfiguredObject' cannot have value '-1' as it has to be at least 0", e.getMessage()); } catch (RuntimeException e) { fail("A generic exception is not expected"); } } |
AtLeast implements Validator<Integer>, Predicate<Integer> { @Override public void validate(Integer value, ConfiguredObject<?> object, String attribute) { if (!test(value)) { throw new IllegalConfigurationException(errorMessage(value, object, attribute)); } } AtLeast(int min); @Override boolean test(Integer value); @Override void validate(Integer value, ConfiguredObject<?> object, String attribute); } | @Test public void testValidate_NullAsInput() { TestConfiguredObject object = new TestConfiguredObject(); Validator<Integer> validator = new AtLeast(42); try { validator.validate(null, object, "attr"); fail("An exception is expected"); } catch (IllegalConfigurationException e) { assertEquals("Attribute 'attr' instance of org.apache.qpid.server.logging.logback.validator.TestConfiguredObject named 'TestConfiguredObject' cannot have value 'null' as it has to be at least 42", e.getMessage()); } catch (RuntimeException e) { fail("A generic exception is not expected"); } }
@Test public void testValidate_ValidInput() { TestConfiguredObject object = new TestConfiguredObject(); Validator<Integer> validator = new AtLeast(42); try { validator.validate(42, object, "attr"); } catch (RuntimeException e) { fail("Any exception is not expected"); } }
@Test public void testValidate_InvalidInput() { TestConfiguredObject object = new TestConfiguredObject(); Validator<Integer> validator = new AtLeast(42); try { validator.validate(41, object, "attr"); fail("An exception is expected"); } catch (IllegalConfigurationException e) { assertEquals("Attribute 'attr' instance of org.apache.qpid.server.logging.logback.validator.TestConfiguredObject named 'TestConfiguredObject' cannot have value '41' as it has to be at least 42", e.getMessage()); } catch (RuntimeException e) { fail("A generic exception is not expected"); } } |
AtLeastOne extends AtLeast { public static Validator<Integer> validator() { return VALIDATOR; } private AtLeastOne(); static Validator<Integer> validator(); static void validateValue(Integer value, ConfiguredObject<?> object, String attribute); } | @Test public void validator() { assertNotNull("Factory method has to produce a instance", AtLeastOne.validator()); } |
AtLeastOne extends AtLeast { public static void validateValue(Integer value, ConfiguredObject<?> object, String attribute) { validator().validate(value, object, attribute); } private AtLeastOne(); static Validator<Integer> validator(); static void validateValue(Integer value, ConfiguredObject<?> object, String attribute); } | @Test public void testValidate_NullAsInput() { TestConfiguredObject object = new TestConfiguredObject(); try { AtLeastOne.validateValue(null, object, "attr"); fail("An exception is expected"); } catch (IllegalConfigurationException e) { assertEquals("Attribute 'attr' instance of org.apache.qpid.server.logging.logback.validator.TestConfiguredObject named 'TestConfiguredObject' cannot have value 'null' as it has to be at least 1", e.getMessage()); } catch (RuntimeException e) { fail("A generic exception is not expected"); } }
@Test public void testValidate_ValidInput() { TestConfiguredObject object = new TestConfiguredObject(); try { AtLeastOne.validateValue(2, object, "attr"); } catch (RuntimeException e) { fail("Any exception is not expected"); } }
@Test public void testValidate_InvalidInput() { TestConfiguredObject object = new TestConfiguredObject(); try { AtLeastOne.validateValue(0, object, "attr"); fail("An exception is expected"); } catch (IllegalConfigurationException e) { assertEquals("Attribute 'attr' instance of org.apache.qpid.server.logging.logback.validator.TestConfiguredObject named 'TestConfiguredObject' cannot have value '0' as it has to be at least 1", e.getMessage()); } catch (RuntimeException e) { fail("A generic exception is not expected"); } } |
FrameHandler implements ProtocolHandler { @Override public ProtocolHandler parse(QpidByteBuffer in) { try { LOGGER.debug("RECV {} bytes", in.remaining()); Error frameParsingError = null; int size; int remaining; List<ChannelFrameBody> channelFrameBodies = new ArrayList<>(); while ((remaining = in.remaining()) >=8 && frameParsingError == null) { size = in.getInt(); if (size < 8) { frameParsingError = createFramingError( "specified frame size %d smaller than minimum frame header size %d", size, 8); break; } if(size > _connectionHandler.getMaxFrameSize()) { frameParsingError = createFramingError( "specified frame size %d larger than maximum frame header size %d", size, _connectionHandler.getMaxFrameSize()); break; } if(remaining < size) { in.position(in.position()-4); break; } int dataOffset = (in.get() << 2) & 0x3FF; if (dataOffset < 8) { frameParsingError = createFramingError( "specified frame data offset %d smaller than minimum frame header size %d", dataOffset, 8); break; } if (dataOffset > size) { frameParsingError = createFramingError( "specified frame data offset %d larger than the frame size %d", dataOffset, size); break; } byte type = in.get(); switch(type) { case 0: if(_isSasl) { frameParsingError = createFramingError("received an AMQP frame type when expecting an SASL frame"); } break; case 1: if(!_isSasl) { frameParsingError = createFramingError("received a SASL frame type when expecting an AMQP frame"); } break; default: frameParsingError = createFramingError("unknown frame type: %d", type); } if(frameParsingError != null) { break; } int channel = in.getUnsignedShort(); if (dataOffset != 8) { in.position(in.position() + dataOffset - 8); } try (QpidByteBuffer dup = in.slice()) { dup.limit(size - dataOffset); in.position(in.position() + size - dataOffset); final boolean hasFrameBody = dup.hasRemaining(); Object frameBody; if (hasFrameBody) { frameBody = _valueHandler.parse(dup); if (dup.hasRemaining()) { if (frameBody instanceof Transfer) { try (QpidByteBuffer payload = dup.slice()) { ((Transfer) frameBody).setPayload(payload); } } else { frameParsingError = createFramingError( "Frame length %d larger than contained frame body %s.", size, frameBody); break; } } } else { frameBody = null; if(_isSasl) { frameParsingError = createFramingError( "Empty (heartbeat) frames are not permitted during SASL negotiation"); break; } } channelFrameBodies.add(new ChannelFrameBody() { @Override public int getChannel() { return channel; } @Override public Object getFrameBody() { return frameBody; } }); if (_isSasl) { break; } } catch (AmqpErrorException ex) { frameParsingError = ex.getError(); } } if (frameParsingError != null) { _connectionHandler.handleError(frameParsingError); _errored = true; } else { _connectionHandler.receive(channelFrameBodies); } } catch (RuntimeException e) { if (e instanceof ServerScopedRuntimeException) { throw e; } LOGGER.warn("Unexpected exception handling frame", e); _connectionHandler.handleError(this.createError(AmqpError.INTERNAL_ERROR, e.toString())); } return this; } FrameHandler(final ValueHandler valueHandler, final ConnectionHandler connectionHandler, final boolean isSasl); @Override ProtocolHandler parse(QpidByteBuffer in); @Override boolean isDone(); static final Logger LOGGER; } | @Test public void testSaslHeartbeat() { ConnectionHandler connectionHandler = mock(ConnectionHandler.class); when(connectionHandler.getMaxFrameSize()).thenReturn(MAX_FRAME_SIZE); FrameHandler handler = new FrameHandler(_valueHandler, connectionHandler, true); QpidByteBuffer body = QpidByteBuffer.allocate(false, 8); body.putInt(8); body.put((byte)2); body.put((byte)1); body.putShort(UnsignedShort.ZERO.shortValue()); body.flip(); handler.parse(body); ArgumentCaptor<Error> errorCaptor = ArgumentCaptor.forClass(Error.class); verify(connectionHandler).handleError(errorCaptor.capture()); Error error = errorCaptor.getValue(); assertNotNull(error); assertEquals(ConnectionError.FRAMING_ERROR, error.getCondition()); assertEquals("Empty (heartbeat) frames are not permitted during SASL negotiation", error.getDescription()); }
@Test public void testOversizedFrame() { ConnectionHandler connectionHandler = mock(ConnectionHandler.class); when(connectionHandler.getMaxFrameSize()).thenReturn(MAX_FRAME_SIZE); FrameHandler handler = new FrameHandler(_valueHandler, connectionHandler, true); QpidByteBuffer body = QpidByteBuffer.allocate(false, MAX_FRAME_SIZE + 8); body.putInt(body.capacity()); body.put((byte) 2); body.put((byte) 1); body.putShort(UnsignedShort.ZERO.shortValue()); body.position(body.capacity()); body.flip(); handler.parse(body); ArgumentCaptor<Error> errorCaptor = ArgumentCaptor.forClass(Error.class); verify(connectionHandler).handleError(errorCaptor.capture()); Error error = errorCaptor.getValue(); assertNotNull(error); assertEquals(ConnectionError.FRAMING_ERROR, error.getCondition()); assertEquals(String.format("specified frame size %s larger than maximum frame header size %s", body.capacity(), MAX_FRAME_SIZE), error.getDescription()); } |
GraylogAppender extends AsyncAppender { static GraylogAppender newInstance(Context context, GelfAppenderConfiguration config) { final GraylogAppender appender = new GraylogAppender(config); appender.setContext(context); appender.setQueueSize(config.getMessageBufferCapacity()); appender.setNeverBlock(true); appender.setMaxFlushTime(config.getMessagesFlushTimeOut()); appender.setIncludeCallerData(config.isCallerDataIncluded()); return appender; } private GraylogAppender(GelfAppenderConfiguration configuration); @Override void start(); @Override void setName(final String name); @Override void setContext(final Context context); @Override void doAppend(ILoggingEvent eventObject); } | @Test public void testNewInstance() { TestGelfAppenderConfiguration logger = new TestGelfAppenderConfiguration(); Context context = new LoggerContext(); GraylogAppender appender = GraylogAppender.newInstance(context, logger); assertNotNull(appender); } |
GraylogAppender extends AsyncAppender { @Override public void start() { if (!isStarted()) { final GelfEncoder encoder = buildEncoder(getContext(), _configuration); encoder.start(); final GelfTcpAppender appender = newGelfTcpAppender(getContext(), _configuration); appender.setEncoder(encoder); appender.setName(getName()); appender.start(); addAppender(appender); } super.start(); } private GraylogAppender(GelfAppenderConfiguration configuration); @Override void start(); @Override void setName(final String name); @Override void setContext(final Context context); @Override void doAppend(ILoggingEvent eventObject); } | @Test public void testStart() { TestGelfAppenderConfiguration logger = new TestGelfAppenderConfiguration(); Context context = new LoggerContext(); GraylogAppender appender = logger.newAppender(context); appender.setName("GelfAppender"); appender.start(); assertTrue(appender.isStarted()); assertEquals("GelfAppender", appender.getName()); Iterator<Appender<ILoggingEvent>> iterator = appender.iteratorForAppenders(); Appender<ILoggingEvent> app = null; while (iterator.hasNext()) { app = iterator.next(); assertNotNull(app); assertTrue(app.isStarted()); assertEquals("GelfAppender", app.getName()); assertEquals(context, app.getContext()); assertTrue(app instanceof GelfTcpAppender); } assertNotNull(app); }
@Test public void testRemoteHost() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withRemoteHost("Remote"); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfTcpAppender gelfAppender = extractGelfAppender(appender); assertNotNull(gelfAppender); assertEquals("Remote", gelfAppender.getGraylogHost()); }
@Test public void testRemoteHost_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); GelfTcpAppender gelfAppender = extractGelfAppender(appender); assertNotNull(gelfAppender); assertEquals("localhost", gelfAppender.getGraylogHost()); }
@Test public void testPort() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withPort(42456); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfTcpAppender gelfAppender = extractGelfAppender(appender); assertNotNull(gelfAppender); assertEquals(42456, gelfAppender.getGraylogPort()); }
@Test public void testPort_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); GelfTcpAppender gelfAppender = extractGelfAppender(appender); assertNotNull(gelfAppender); assertEquals(12201, gelfAppender.getGraylogPort()); }
@Test public void testReconnectInterval_withRounding() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withReconnectionInterval(11456); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfTcpAppender gelfAppender = extractGelfAppender(appender); assertNotNull(gelfAppender); assertEquals(12, gelfAppender.getReconnectInterval()); }
@Test public void testReconnectInterval_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); GelfTcpAppender gelfAppender = extractGelfAppender(appender); assertNotNull(gelfAppender); assertEquals(60, gelfAppender.getReconnectInterval()); }
@Test public void testReconnectInterval() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withReconnectionInterval(11000); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfTcpAppender gelfAppender = extractGelfAppender(appender); assertNotNull(gelfAppender); assertEquals(11, gelfAppender.getReconnectInterval()); }
@Test public void testConnectTimeout() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withConnectionTimeout(1123); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfTcpAppender gelfAppender = extractGelfAppender(appender); assertNotNull(gelfAppender); assertEquals(1123, gelfAppender.getConnectTimeout()); }
@Test public void testConnectTimeout_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); GelfTcpAppender gelfAppender = extractGelfAppender(appender); assertNotNull(gelfAppender); assertEquals(15000, gelfAppender.getConnectTimeout()); }
@Test public void testMaximumReconnectionAttempts() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withMaximumReconnectionAttempts(17); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfTcpAppender gelfAppender = extractGelfAppender(appender); assertNotNull(gelfAppender); assertEquals(17, gelfAppender.getMaxRetries()); }
@Test public void testMaximumReconnectionAttempts_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); GelfTcpAppender gelfAppender = extractGelfAppender(appender); assertNotNull(gelfAppender); assertEquals(2, gelfAppender.getMaxRetries()); }
@Test public void testRetryDelay() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withRetryDelay(178); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfTcpAppender gelfAppender = extractGelfAppender(appender); assertNotNull(gelfAppender); assertEquals(178, gelfAppender.getRetryDelay()); }
@Test public void testRetryDelay_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); GelfTcpAppender gelfAppender = extractGelfAppender(appender); assertNotNull(gelfAppender); assertEquals(3000, gelfAppender.getRetryDelay()); }
@Test public void testMessageOriginHost() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withMessageOriginHost("Broker"); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertEquals("Broker", gelfEncoder.getOriginHost()); }
@Test public void testRawMessageIncluded_True() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withRawMessageIncluded(true); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertTrue(gelfEncoder.isIncludeRawMessage()); }
@Test public void testRawMessageIncluded_False() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withRawMessageIncluded(false); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertFalse(gelfEncoder.isIncludeRawMessage()); }
@Test public void testRawMessageIncluded_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertFalse(gelfEncoder.isIncludeRawMessage()); }
@Test public void testEventMarkerIncluded_True() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withEventMarkerIncluded(true); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertTrue(gelfEncoder.isIncludeMarker()); }
@Test public void testEventMarkerIncluded_False() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withEventMarkerIncluded(false); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertFalse(gelfEncoder.isIncludeMarker()); }
@Test public void testEventMarkerIncluded_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertTrue(gelfEncoder.isIncludeMarker()); }
@Test public void testMdcPropertiesIncluded_True() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withMdcPropertiesIncluded(true); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertTrue(gelfEncoder.isIncludeMdcData()); }
@Test public void testMdcPropertiesIncluded_False() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withMdcPropertiesIncluded(false); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertFalse(gelfEncoder.isIncludeMdcData()); }
@Test public void testMdcPropertiesIncluded_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertTrue(gelfEncoder.isIncludeMdcData()); }
@Test public void testCallerDataIncluded_True() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withCallerDataIncluded(true); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertTrue(gelfEncoder.isIncludeCallerData()); }
@Test public void testCallerDataIncluded_False() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withCallerDataIncluded(false); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertFalse(gelfEncoder.isIncludeCallerData()); }
@Test public void testCallerDataIncluded_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertFalse(gelfEncoder.isIncludeCallerData()); }
@Test public void testRootExceptionDataIncluded_True() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withRootExceptionDataIncluded(true); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertTrue(gelfEncoder.isIncludeRootCauseData()); }
@Test public void testRootExceptionDataIncluded_False() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withRootExceptionDataIncluded(false); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertFalse(gelfEncoder.isIncludeRootCauseData()); }
@Test public void testRootExceptionDataIncluded_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertFalse(gelfEncoder.isIncludeRootCauseData()); }
@Test public void testLogLevelNameIncluded_True() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withLogLevelNameIncluded(true); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertTrue(gelfEncoder.isIncludeLevelName()); }
@Test public void testLogLevelNameIncluded_False() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withLogLevelNameIncluded(false); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertFalse(gelfEncoder.isIncludeLevelName()); }
@Test public void testLogLevelNameIncluded_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); assertFalse(gelfEncoder.isIncludeLevelName()); }
@Test public void testStaticFields() { Map<String, Object> staticFields = new HashMap<>(2); staticFields.put("A", "A.A"); staticFields.put("B", 234); TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().addStaticFields(staticFields); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); Map<String, Object> fields = gelfEncoder.getStaticFields(); assertNotNull(fields); assertEquals(2, fields.size()); assertEquals("A.A", fields.get("A")); assertEquals(234, fields.get("B")); }
@Test public void testStaticFields_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); GelfEncoder gelfEncoder = extractGelfEncoder(appender); assertNotNull(gelfEncoder); Map<String, Object> fields = gelfEncoder.getStaticFields(); assertNotNull(fields); assertTrue(fields.isEmpty()); }
@Test public void testMessageBufferCapacity() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withMessageBufferCapacity(789); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); assertEquals(789, appender.getQueueSize()); }
@Test public void testMessageBufferCapacity_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); assertEquals(256, appender.getQueueSize()); }
@Test public void testMessagesFlushTimeOut() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration().withMessagesFlushTimeOut(567); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.start(); assertEquals(567, appender.getMaxFlushTime()); }
@Test public void testMessagesFlushTimeOut_Default() { Context context = new LoggerContext(); GraylogAppender appender = new DefaultGelfAppenderConfiguration().newAppender(context); appender.start(); assertEquals(1000, appender.getMaxFlushTime()); } |
GraylogAppender extends AsyncAppender { @Override public void setName(final String name) { super.setName(name); iteratorForAppenders().forEachRemaining(item -> item.setName(name)); } private GraylogAppender(GelfAppenderConfiguration configuration); @Override void start(); @Override void setName(final String name); @Override void setContext(final Context context); @Override void doAppend(ILoggingEvent eventObject); } | @Test public void testSetName() { TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration(); Context context = new LoggerContext(); GraylogAppender appender = configuration.newAppender(context); appender.setName("GelfAppender"); appender.start(); appender.setName("NewGelfAppender"); Iterator<Appender<ILoggingEvent>> iterator = appender.iteratorForAppenders(); while (iterator.hasNext()) { Appender<ILoggingEvent> app = iterator.next(); assertNotNull(app); assertEquals("NewGelfAppender", app.getName()); } } |
GraylogAppender extends AsyncAppender { @Override public void setContext(final Context context) { super.setContext(context); iteratorForAppenders().forEachRemaining(item -> item.setContext(context)); } private GraylogAppender(GelfAppenderConfiguration configuration); @Override void start(); @Override void setName(final String name); @Override void setContext(final Context context); @Override void doAppend(ILoggingEvent eventObject); } | @Test public void testSetContext() { TestGelfAppenderConfiguration logger = new TestGelfAppenderConfiguration(); Context context = new LoggerContext(); GraylogAppender appender = logger.newAppender(context); appender.setName("GelfAppender"); appender.start(); appender.setContext(context); Iterator<Appender<ILoggingEvent>> iterator = appender.iteratorForAppenders(); while (iterator.hasNext()) { Appender<ILoggingEvent> app = iterator.next(); assertNotNull(app); assertEquals(context, app.getContext()); } } |
UnsettledDelivery { @Override public int hashCode() { return Objects.hash(_deliveryTag, _linkEndpoint); } UnsettledDelivery(final Binary deliveryTag, final LinkEndpoint<?, ?> linkEndpoint); Binary getDeliveryTag(); LinkEndpoint<?, ?> getLinkEndpoint(); @Override boolean equals(final Object o); @Override int hashCode(); } | @Test public void testHashCode() { int expected = Objects.hash(_deliveryTag, _linkEndpoint); assertThat(_unsettledDelivery.hashCode(), is(equalTo(expected))); } |
DeliveryRegistryImpl implements DeliveryRegistry { @Override public void addDelivery(final UnsignedInteger deliveryId, final UnsettledDelivery unsettledDelivery) { _deliveries.put(deliveryId, unsettledDelivery); _deliveryIds.put(unsettledDelivery, deliveryId); } @Override void addDelivery(final UnsignedInteger deliveryId, final UnsettledDelivery unsettledDelivery); @Override void removeDelivery(final UnsignedInteger deliveryId); @Override UnsettledDelivery getDelivery(final UnsignedInteger deliveryId); @Override void removeDeliveriesForLinkEndpoint(final LinkEndpoint<?, ?> linkEndpoint); @Override UnsignedInteger getDeliveryId(final Binary deliveryTag, final LinkEndpoint<?, ?> linkEndpoint); @Override int size(); } | @Test public void addDelivery() { assertThat(_registry.size(), is(equalTo(0))); _registry.addDelivery(DELIVERY_ID, _unsettledDelivery); assertThat(_registry.size(), is(equalTo(1))); } |
GraylogAppender extends AsyncAppender { @Override public void doAppend(ILoggingEvent eventObject) { super.doAppend(LoggingEvent.wrap(eventObject)); } private GraylogAppender(GelfAppenderConfiguration configuration); @Override void start(); @Override void setName(final String name); @Override void setContext(final Context context); @Override void doAppend(ILoggingEvent eventObject); } | @Test public void testDoAppend() { Context context = new LoggerContext(); TestGelfAppenderConfiguration configuration = new TestGelfAppenderConfiguration(); GraylogAppender appender = configuration.newAppender(context); try { appender.doAppend(new TestLoggingEvent()); } catch (RuntimeException e) { fail("Any exception is not expected"); } } |
LoggingEvent implements ILoggingEvent { public static ILoggingEvent wrap(ILoggingEvent event) { return event != null ? new LoggingEvent(event) : null; } private LoggingEvent(ILoggingEvent event); static ILoggingEvent wrap(ILoggingEvent event); @Override String getThreadName(); @Override Level getLevel(); @Override String getMessage(); @Override Object[] getArgumentArray(); @Override String getFormattedMessage(); @Override String getLoggerName(); @Override LoggerContextVO getLoggerContextVO(); @Override IThrowableProxy getThrowableProxy(); @Override StackTraceElement[] getCallerData(); @Override boolean hasCallerData(); @Override Marker getMarker(); @Override Map<String, String> getMDCPropertyMap(); @Deprecated @Override Map<String, String> getMdc(); @Override long getTimeStamp(); @Override void prepareForDeferredProcessing(); } | @Test public void testWrap_NullAsInput() { assertNull(LoggingEvent.wrap(null)); }
@Test public void testWrap() { assertNotNull(LoggingEvent.wrap(new TestLoggingEvent())); } |
LoggingEvent implements ILoggingEvent { @Override public String getThreadName() { return _event.getThreadName(); } private LoggingEvent(ILoggingEvent event); static ILoggingEvent wrap(ILoggingEvent event); @Override String getThreadName(); @Override Level getLevel(); @Override String getMessage(); @Override Object[] getArgumentArray(); @Override String getFormattedMessage(); @Override String getLoggerName(); @Override LoggerContextVO getLoggerContextVO(); @Override IThrowableProxy getThrowableProxy(); @Override StackTraceElement[] getCallerData(); @Override boolean hasCallerData(); @Override Marker getMarker(); @Override Map<String, String> getMDCPropertyMap(); @Deprecated @Override Map<String, String> getMdc(); @Override long getTimeStamp(); @Override void prepareForDeferredProcessing(); } | @Test public void testGetThreadName() { TestLoggingEvent event = new TestLoggingEvent(); ILoggingEvent wrapper = LoggingEvent.wrap(event); assertNotNull(wrapper); assertEquals(event.getThreadName(), wrapper.getThreadName()); } |
LoggingEvent implements ILoggingEvent { @Override public Level getLevel() { return _event.getLevel(); } private LoggingEvent(ILoggingEvent event); static ILoggingEvent wrap(ILoggingEvent event); @Override String getThreadName(); @Override Level getLevel(); @Override String getMessage(); @Override Object[] getArgumentArray(); @Override String getFormattedMessage(); @Override String getLoggerName(); @Override LoggerContextVO getLoggerContextVO(); @Override IThrowableProxy getThrowableProxy(); @Override StackTraceElement[] getCallerData(); @Override boolean hasCallerData(); @Override Marker getMarker(); @Override Map<String, String> getMDCPropertyMap(); @Deprecated @Override Map<String, String> getMdc(); @Override long getTimeStamp(); @Override void prepareForDeferredProcessing(); } | @Test public void testGetLevel() { TestLoggingEvent event = new TestLoggingEvent(); ILoggingEvent wrapper = LoggingEvent.wrap(event); assertNotNull(wrapper); assertEquals(event.getLevel(), wrapper.getLevel()); } |
LoggingEvent implements ILoggingEvent { @Override public String getMessage() { return _event.getMessage(); } private LoggingEvent(ILoggingEvent event); static ILoggingEvent wrap(ILoggingEvent event); @Override String getThreadName(); @Override Level getLevel(); @Override String getMessage(); @Override Object[] getArgumentArray(); @Override String getFormattedMessage(); @Override String getLoggerName(); @Override LoggerContextVO getLoggerContextVO(); @Override IThrowableProxy getThrowableProxy(); @Override StackTraceElement[] getCallerData(); @Override boolean hasCallerData(); @Override Marker getMarker(); @Override Map<String, String> getMDCPropertyMap(); @Deprecated @Override Map<String, String> getMdc(); @Override long getTimeStamp(); @Override void prepareForDeferredProcessing(); } | @Test public void testGetMessage() { TestLoggingEvent event = new TestLoggingEvent(); ILoggingEvent wrapper = LoggingEvent.wrap(event); assertNotNull(wrapper); assertEquals(event.getMessage(), wrapper.getMessage()); } |
DeliveryRegistryImpl implements DeliveryRegistry { @Override public void removeDelivery(final UnsignedInteger deliveryId) { UnsettledDelivery unsettledDelivery = _deliveries.remove(deliveryId); if (unsettledDelivery != null) { _deliveryIds.remove(unsettledDelivery); } } @Override void addDelivery(final UnsignedInteger deliveryId, final UnsettledDelivery unsettledDelivery); @Override void removeDelivery(final UnsignedInteger deliveryId); @Override UnsettledDelivery getDelivery(final UnsignedInteger deliveryId); @Override void removeDeliveriesForLinkEndpoint(final LinkEndpoint<?, ?> linkEndpoint); @Override UnsignedInteger getDeliveryId(final Binary deliveryTag, final LinkEndpoint<?, ?> linkEndpoint); @Override int size(); } | @Test public void removeDelivery() { _registry.addDelivery(DELIVERY_ID, _unsettledDelivery); assertThat(_registry.size(), is(equalTo(1))); _registry.removeDelivery(DELIVERY_ID); assertThat(_registry.size(), is(equalTo(0))); assertThat(_registry.getDelivery(UnsignedInteger.ZERO), is(nullValue())); } |
LoggingEvent implements ILoggingEvent { @Override public Object[] getArgumentArray() { return _event.getArgumentArray(); } private LoggingEvent(ILoggingEvent event); static ILoggingEvent wrap(ILoggingEvent event); @Override String getThreadName(); @Override Level getLevel(); @Override String getMessage(); @Override Object[] getArgumentArray(); @Override String getFormattedMessage(); @Override String getLoggerName(); @Override LoggerContextVO getLoggerContextVO(); @Override IThrowableProxy getThrowableProxy(); @Override StackTraceElement[] getCallerData(); @Override boolean hasCallerData(); @Override Marker getMarker(); @Override Map<String, String> getMDCPropertyMap(); @Deprecated @Override Map<String, String> getMdc(); @Override long getTimeStamp(); @Override void prepareForDeferredProcessing(); } | @Test public void testGetArgumentArray() { TestLoggingEvent event = new TestLoggingEvent(); ILoggingEvent wrapper = LoggingEvent.wrap(event); assertNotNull(wrapper); assertTrue(Arrays.deepEquals(event.getArgumentArray(), wrapper.getArgumentArray())); } |
LoggingEvent implements ILoggingEvent { @Override public String getFormattedMessage() { return _event.getFormattedMessage(); } private LoggingEvent(ILoggingEvent event); static ILoggingEvent wrap(ILoggingEvent event); @Override String getThreadName(); @Override Level getLevel(); @Override String getMessage(); @Override Object[] getArgumentArray(); @Override String getFormattedMessage(); @Override String getLoggerName(); @Override LoggerContextVO getLoggerContextVO(); @Override IThrowableProxy getThrowableProxy(); @Override StackTraceElement[] getCallerData(); @Override boolean hasCallerData(); @Override Marker getMarker(); @Override Map<String, String> getMDCPropertyMap(); @Deprecated @Override Map<String, String> getMdc(); @Override long getTimeStamp(); @Override void prepareForDeferredProcessing(); } | @Test public void testGetFormattedMessage() { TestLoggingEvent event = new TestLoggingEvent(); ILoggingEvent wrapper = LoggingEvent.wrap(event); assertNotNull(wrapper); assertEquals(event.getFormattedMessage(), wrapper.getFormattedMessage()); } |
LoggingEvent implements ILoggingEvent { @Override public String getLoggerName() { return _event.getLoggerName(); } private LoggingEvent(ILoggingEvent event); static ILoggingEvent wrap(ILoggingEvent event); @Override String getThreadName(); @Override Level getLevel(); @Override String getMessage(); @Override Object[] getArgumentArray(); @Override String getFormattedMessage(); @Override String getLoggerName(); @Override LoggerContextVO getLoggerContextVO(); @Override IThrowableProxy getThrowableProxy(); @Override StackTraceElement[] getCallerData(); @Override boolean hasCallerData(); @Override Marker getMarker(); @Override Map<String, String> getMDCPropertyMap(); @Deprecated @Override Map<String, String> getMdc(); @Override long getTimeStamp(); @Override void prepareForDeferredProcessing(); } | @Test public void testGetLoggerName() { TestLoggingEvent event = new TestLoggingEvent(); ILoggingEvent wrapper = LoggingEvent.wrap(event); assertNotNull(wrapper); assertEquals(event.getLoggerName(), wrapper.getLoggerName()); } |
LoggingEvent implements ILoggingEvent { @Override public LoggerContextVO getLoggerContextVO() { return _event.getLoggerContextVO(); } private LoggingEvent(ILoggingEvent event); static ILoggingEvent wrap(ILoggingEvent event); @Override String getThreadName(); @Override Level getLevel(); @Override String getMessage(); @Override Object[] getArgumentArray(); @Override String getFormattedMessage(); @Override String getLoggerName(); @Override LoggerContextVO getLoggerContextVO(); @Override IThrowableProxy getThrowableProxy(); @Override StackTraceElement[] getCallerData(); @Override boolean hasCallerData(); @Override Marker getMarker(); @Override Map<String, String> getMDCPropertyMap(); @Deprecated @Override Map<String, String> getMdc(); @Override long getTimeStamp(); @Override void prepareForDeferredProcessing(); } | @Test public void testGetLoggerContextVO() { TestLoggingEvent event = new TestLoggingEvent(); ILoggingEvent wrapper = LoggingEvent.wrap(event); assertNotNull(wrapper); assertEquals(event.getLoggerContextVO(), wrapper.getLoggerContextVO()); } |
LoggingEvent implements ILoggingEvent { @Override public IThrowableProxy getThrowableProxy() { return _event.getThrowableProxy(); } private LoggingEvent(ILoggingEvent event); static ILoggingEvent wrap(ILoggingEvent event); @Override String getThreadName(); @Override Level getLevel(); @Override String getMessage(); @Override Object[] getArgumentArray(); @Override String getFormattedMessage(); @Override String getLoggerName(); @Override LoggerContextVO getLoggerContextVO(); @Override IThrowableProxy getThrowableProxy(); @Override StackTraceElement[] getCallerData(); @Override boolean hasCallerData(); @Override Marker getMarker(); @Override Map<String, String> getMDCPropertyMap(); @Deprecated @Override Map<String, String> getMdc(); @Override long getTimeStamp(); @Override void prepareForDeferredProcessing(); } | @Test public void testGetThrowableProxy() { TestLoggingEvent event = new TestLoggingEvent(); ILoggingEvent wrapper = LoggingEvent.wrap(event); assertNotNull(wrapper); assertEquals(event.getThrowableProxy(), wrapper.getThrowableProxy()); } |
LoggingEvent implements ILoggingEvent { @Override public Marker getMarker() { return _event.getMarker(); } private LoggingEvent(ILoggingEvent event); static ILoggingEvent wrap(ILoggingEvent event); @Override String getThreadName(); @Override Level getLevel(); @Override String getMessage(); @Override Object[] getArgumentArray(); @Override String getFormattedMessage(); @Override String getLoggerName(); @Override LoggerContextVO getLoggerContextVO(); @Override IThrowableProxy getThrowableProxy(); @Override StackTraceElement[] getCallerData(); @Override boolean hasCallerData(); @Override Marker getMarker(); @Override Map<String, String> getMDCPropertyMap(); @Deprecated @Override Map<String, String> getMdc(); @Override long getTimeStamp(); @Override void prepareForDeferredProcessing(); } | @Test public void testGetMarker() { TestLoggingEvent event = new TestLoggingEvent(); ILoggingEvent wrapper = LoggingEvent.wrap(event); assertNotNull(wrapper); assertEquals(event.getMarker(), wrapper.getMarker()); } |
LoggingEvent implements ILoggingEvent { @Deprecated @Override public Map<String, String> getMdc() { return _event.getMdc(); } private LoggingEvent(ILoggingEvent event); static ILoggingEvent wrap(ILoggingEvent event); @Override String getThreadName(); @Override Level getLevel(); @Override String getMessage(); @Override Object[] getArgumentArray(); @Override String getFormattedMessage(); @Override String getLoggerName(); @Override LoggerContextVO getLoggerContextVO(); @Override IThrowableProxy getThrowableProxy(); @Override StackTraceElement[] getCallerData(); @Override boolean hasCallerData(); @Override Marker getMarker(); @Override Map<String, String> getMDCPropertyMap(); @Deprecated @Override Map<String, String> getMdc(); @Override long getTimeStamp(); @Override void prepareForDeferredProcessing(); } | @Test public void testGetMdc() { TestLoggingEvent event = new TestLoggingEvent(); ILoggingEvent wrapper = LoggingEvent.wrap(event); assertNotNull(wrapper); Map<String, String> originalMap = event.getMdc(); Map<String, String> map = wrapper.getMdc(); assertEquals(originalMap.keySet(), map.keySet()); for (Map.Entry<String, String> entry : originalMap.entrySet()) { assertEquals(entry.getValue(), map.get(entry.getKey())); } } |
LoggingEvent implements ILoggingEvent { @Override public long getTimeStamp() { return _event.getTimeStamp(); } private LoggingEvent(ILoggingEvent event); static ILoggingEvent wrap(ILoggingEvent event); @Override String getThreadName(); @Override Level getLevel(); @Override String getMessage(); @Override Object[] getArgumentArray(); @Override String getFormattedMessage(); @Override String getLoggerName(); @Override LoggerContextVO getLoggerContextVO(); @Override IThrowableProxy getThrowableProxy(); @Override StackTraceElement[] getCallerData(); @Override boolean hasCallerData(); @Override Marker getMarker(); @Override Map<String, String> getMDCPropertyMap(); @Deprecated @Override Map<String, String> getMdc(); @Override long getTimeStamp(); @Override void prepareForDeferredProcessing(); } | @Test public void testGetTimeStamp() { TestLoggingEvent event = new TestLoggingEvent(); ILoggingEvent wrapper = LoggingEvent.wrap(event); assertNotNull(wrapper); assertEquals(event.getTimeStamp(), wrapper.getTimeStamp()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.