You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@brooklyn.apache.org by he...@apache.org on 2016/02/18 16:47:32 UTC
[14/34] brooklyn-server git commit: [BROOKLYN-183] REST API using CXF
JAX-RS 2.0 implementation
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/6f624c78/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/json/ErrorAndToStringUnknownTypeSerializer.java
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/json/ErrorAndToStringUnknownTypeSerializer.java b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/json/ErrorAndToStringUnknownTypeSerializer.java
new file mode 100644
index 0000000..e529ec9
--- /dev/null
+++ b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/json/ErrorAndToStringUnknownTypeSerializer.java
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.rest.util.json;
+
+import java.io.IOException;
+import java.io.NotSerializableException;
+import java.util.Collections;
+import java.util.Set;
+
+import javax.annotation.Nullable;
+
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.javalang.Reflections;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonStreamContext;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import com.fasterxml.jackson.databind.ser.impl.UnknownSerializer;
+
+/**
+ * for non-json-serializable classes (quite a lot of them!) simply provide a sensible error message and a toString.
+ * TODO maybe we want to attempt to serialize fields instead? (but being careful not to be self-referential!)
+ */
+public class ErrorAndToStringUnknownTypeSerializer extends UnknownSerializer {
+
+ private static final Logger log = LoggerFactory.getLogger(ErrorAndToStringUnknownTypeSerializer.class);
+ private static Set<String> WARNED_CLASSES = Collections.synchronizedSet(MutableSet.<String>of());
+
+ @Override
+ public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
+ if (BidiSerialization.isStrictSerialization())
+ throw new JsonMappingException("Cannot serialize object containing "+value.getClass().getName()+" when strict serialization requested");
+
+ serializeFromError(jgen.getOutputContext(), null, value, jgen, provider);
+ }
+
+ public void serializeFromError(JsonStreamContext ctxt, @Nullable Exception error, Object value, JsonGenerator jgen, SerializerProvider configurableSerializerProvider) throws IOException {
+ if (log.isDebugEnabled())
+ log.debug("Recovering from json serialization error, serializing "+value+": "+error);
+
+ if (BidiSerialization.isStrictSerialization())
+ throw new JsonMappingException("Cannot serialize "
+ + (ctxt!=null && !ctxt.inRoot() ? "object containing " : "")
+ + value.getClass().getName()+" when strict serialization requested");
+
+ if (WARNED_CLASSES.add(value.getClass().getCanonicalName())) {
+ log.warn("Standard serialization not possible for "+value.getClass()+" ("+value+")", error);
+ }
+ JsonStreamContext newCtxt = jgen.getOutputContext();
+
+ // very odd, but flush seems necessary when working with large objects; presumably a buffer which is allowed to clear itself?
+ // without this, when serializing the large (1.5M) Server json object from BrooklynJacksonSerializerTest creates invalid json,
+ // containing: "foo":false,"{"error":true,...
+ jgen.flush();
+
+ boolean createObject = !newCtxt.inObject() || newCtxt.getCurrentName()!=null;
+ if (createObject) {
+ jgen.writeStartObject();
+ }
+
+ if (allowEmpty(value.getClass())) {
+ // write nothing
+ } else {
+
+ jgen.writeFieldName("error");
+ jgen.writeBoolean(true);
+
+ jgen.writeFieldName("errorType");
+ jgen.writeString(NotSerializableException.class.getCanonicalName());
+
+ jgen.writeFieldName("type");
+ jgen.writeString(value.getClass().getCanonicalName());
+
+ jgen.writeFieldName("toString");
+ jgen.writeString(value.toString());
+
+ if (error!=null) {
+ jgen.writeFieldName("causedByError");
+ jgen.writeString(error.toString());
+ }
+
+ }
+
+ if (createObject) {
+ jgen.writeEndObject();
+ }
+
+ while (newCtxt!=null && !newCtxt.equals(ctxt)) {
+ if (jgen.getOutputContext().inArray()) { jgen.writeEndArray(); continue; }
+ if (jgen.getOutputContext().inObject()) { jgen.writeEndObject(); continue; }
+ break;
+ }
+
+ }
+
+ protected boolean allowEmpty(Class<? extends Object> clazz) {
+ if (clazz.getAnnotation(JsonSerialize.class)!=null && Reflections.hasNoNonObjectFields(clazz)) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/6f624c78/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/json/MultimapSerializer.java
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/json/MultimapSerializer.java b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/json/MultimapSerializer.java
new file mode 100644
index 0000000..f750e86
--- /dev/null
+++ b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/json/MultimapSerializer.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.rest.util.json;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Map;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.ser.std.StdSerializer;
+
+import com.google.common.annotations.Beta;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Multimap;
+
+/**
+ * Provides a serializer for {@link Multimap} instances.
+ * <p>
+ * When Brooklyn's Jackson dependency is updated from org.codehaus.jackson:1.9.13 to
+ * com.fasterxml.jackson:2.3+ then this class should be replaced with a dependency on
+ * jackson-datatype-guava and a GuavaModule registered with Brooklyn's ObjectMapper.
+ * Check the guava version when doing the switch as it could be incompatible with the
+ * version used by Brooklyn.
+ */
+@Beta
+public class MultimapSerializer extends StdSerializer<Multimap<?, ?>> {
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ protected MultimapSerializer() {
+ super((Class<Multimap<?, ?>>) (Class) Multimap.class);
+ }
+
+ @Override
+ public void serialize(Multimap<?, ?> value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
+ jgen.writeStartObject();
+ writeEntries(value, jgen, provider);
+ jgen.writeEndObject();
+ }
+
+ private void writeEntries(Multimap<?, ?> value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
+ for (Map.Entry<?, ? extends Collection<?>> entry : value.asMap().entrySet()) {
+ provider.findKeySerializer(provider.constructType(String.class), null)
+ .serialize(entry.getKey(), jgen, provider);
+ provider.defaultSerializeValue(Lists.newArrayList(entry.getValue()), jgen);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/6f624c78/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/json/PossiblyStrictPreferringFieldsVisibilityChecker.java
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/json/PossiblyStrictPreferringFieldsVisibilityChecker.java b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/json/PossiblyStrictPreferringFieldsVisibilityChecker.java
new file mode 100644
index 0000000..e474467
--- /dev/null
+++ b/rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/json/PossiblyStrictPreferringFieldsVisibilityChecker.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.rest.util.json;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Member;
+import java.lang.reflect.Method;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.introspect.AnnotatedField;
+import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
+import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
+import com.fasterxml.jackson.databind.introspect.VisibilityChecker;
+
+import static com.fasterxml.jackson.annotation.JsonAutoDetect.*;
+
+/** a visibility checker which disables getters, but allows private access,
+ * unless {@link BidiSerialization#isStrictSerialization()} is enabled in which case public fields or annotations must be used.
+ * <p>
+ * the reason for this change to visibility
+ * is that getters might generate a copy, resulting in infinite loops, whereas field access should never do so.
+ * (see e.g. test in {@link BrooklynJacksonSerializerTest} which uses a sensor+config object whose getTypeToken
+ * causes infinite recursion)
+ **/
+public class PossiblyStrictPreferringFieldsVisibilityChecker implements VisibilityChecker<PossiblyStrictPreferringFieldsVisibilityChecker> {
+ VisibilityChecker<?>
+ vizDefault = new VisibilityChecker.Std(Visibility.NONE, Visibility.NONE, Visibility.NONE, Visibility.ANY, Visibility.ANY),
+ vizStrict = new VisibilityChecker.Std(Visibility.NONE, Visibility.NONE, Visibility.NONE, Visibility.PUBLIC_ONLY, Visibility.PUBLIC_ONLY);
+
+ @Override public PossiblyStrictPreferringFieldsVisibilityChecker with(JsonAutoDetect ann) { throw new UnsupportedOperationException(); }
+ @Override public PossiblyStrictPreferringFieldsVisibilityChecker with(Visibility v) { throw new UnsupportedOperationException(); }
+ @Override public PossiblyStrictPreferringFieldsVisibilityChecker withVisibility(PropertyAccessor method, Visibility v) { throw new UnsupportedOperationException(); }
+ @Override public PossiblyStrictPreferringFieldsVisibilityChecker withGetterVisibility(Visibility v) { throw new UnsupportedOperationException(); }
+ @Override public PossiblyStrictPreferringFieldsVisibilityChecker withIsGetterVisibility(Visibility v) { throw new UnsupportedOperationException(); }
+ @Override public PossiblyStrictPreferringFieldsVisibilityChecker withSetterVisibility(Visibility v) { throw new UnsupportedOperationException(); }
+ @Override public PossiblyStrictPreferringFieldsVisibilityChecker withCreatorVisibility(Visibility v) { throw new UnsupportedOperationException(); }
+ @Override public PossiblyStrictPreferringFieldsVisibilityChecker withFieldVisibility(Visibility v) { throw new UnsupportedOperationException(); }
+
+ protected VisibilityChecker<?> viz() {
+ return BidiSerialization.isStrictSerialization() ? vizStrict : vizDefault;
+ }
+
+ @Override public boolean isGetterVisible(Method m) {
+ return viz().isGetterVisible(m);
+ }
+
+ @Override
+ public boolean isGetterVisible(AnnotatedMethod m) {
+ return isGetterVisible(m.getAnnotated());
+ }
+
+ @Override
+ public boolean isIsGetterVisible(Method m) {
+ return viz().isIsGetterVisible(m);
+ }
+
+ @Override
+ public boolean isIsGetterVisible(AnnotatedMethod m) {
+ return isIsGetterVisible(m.getAnnotated());
+ }
+
+ @Override
+ public boolean isSetterVisible(Method m) {
+ return viz().isSetterVisible(m);
+ }
+
+ @Override
+ public boolean isSetterVisible(AnnotatedMethod m) {
+ return isSetterVisible(m.getAnnotated());
+ }
+
+ @Override
+ public boolean isCreatorVisible(Member m) {
+ return viz().isCreatorVisible(m);
+ }
+
+ @Override
+ public boolean isCreatorVisible(AnnotatedMember m) {
+ return isCreatorVisible(m.getMember());
+ }
+
+ @Override
+ public boolean isFieldVisible(Field f) {
+ return viz().isFieldVisible(f);
+ }
+
+ @Override
+ public boolean isFieldVisible(AnnotatedField f) {
+ return isFieldVisible(f.getAnnotated());
+ }
+}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/6f624c78/rest/rest-resources/src/main/resources/OSGI-INF/blueprint/service.xml
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/main/resources/OSGI-INF/blueprint/service.xml b/rest/rest-resources/src/main/resources/OSGI-INF/blueprint/service.xml
new file mode 100644
index 0000000..1639fef
--- /dev/null
+++ b/rest/rest-resources/src/main/resources/OSGI-INF/blueprint/service.xml
@@ -0,0 +1,112 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Copyright 2015 The Apache Software Foundation.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0"
+ xmlns:jaxws="http://cxf.apache.org/blueprint/jaxws"
+ xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs"
+ xmlns:cxf="http://cxf.apache.org/blueprint/core"
+ xsi:schemaLocation="
+ http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
+ http://cxf.apache.org/blueprint/jaxws http://cxf.apache.org/schemas/blueprint/jaxws.xsd
+ http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd
+ http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd
+ ">
+
+ <cxf:bus>
+ <cxf:features>
+ <cxf:logging/>
+ </cxf:features>
+ </cxf:bus>
+
+ <reference id="localManagementContext"
+ interface="org.apache.brooklyn.api.mgmt.ManagementContext" />
+
+ <bean id="accessResourceBean" class="org.apache.brooklyn.rest.resources.AccessResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <bean id="activityResourceBean" class="org.apache.brooklyn.rest.resources.ActivityResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <!--<bean id="apidocResourceBean" class="org.apache.brooklyn.rest.resources.ApidocResource" />-->
+ <bean id="applicationResourceBean" class="org.apache.brooklyn.rest.resources.ApplicationResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <bean id="catalogResourceBean" class="org.apache.brooklyn.rest.resources.CatalogResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <bean id="effectorResourceBean" class="org.apache.brooklyn.rest.resources.EffectorResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <bean id="entityConfigResourceBean" class="org.apache.brooklyn.rest.resources.EntityConfigResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <bean id="entityResourceBean" class="org.apache.brooklyn.rest.resources.EntityResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <bean id="locationResourceBean" class="org.apache.brooklyn.rest.resources.LocationResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <bean id="policyConfigResourceBean" class="org.apache.brooklyn.rest.resources.PolicyConfigResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <bean id="policyResourceBean" class="org.apache.brooklyn.rest.resources.PolicyResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <bean id="scriptResourceBean" class="org.apache.brooklyn.rest.resources.ScriptResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <bean id="sensorResourceBean" class="org.apache.brooklyn.rest.resources.SensorResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <bean id="serverResourceBean" class="org.apache.brooklyn.rest.resources.ServerResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <bean id="usageResourceBean" class="org.apache.brooklyn.rest.resources.UsageResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+ <bean id="versionResourceBean" class="org.apache.brooklyn.rest.resources.VersionResource">
+ <property name="managementContext" ref="localManagementContext" />
+ </bean>
+
+ <jaxrs:server id="brooklynRestApiV1" address="/">
+ <jaxrs:serviceBeans>
+ <ref component-id="accessResourceBean" />
+ <ref component-id="activityResourceBean" />
+ <!--<ref component-id="apidocResourceBean" />-->
+ <ref component-id="applicationResourceBean" />
+ <ref component-id="catalogResourceBean" />
+ <ref component-id="effectorResourceBean" />
+ <ref component-id="entityConfigResourceBean" />
+ <ref component-id="entityResourceBean" />
+ <ref component-id="locationResourceBean" />
+ <ref component-id="policyConfigResourceBean" />
+ <ref component-id="policyResourceBean" />
+ <ref component-id="scriptResourceBean" />
+ <ref component-id="sensorResourceBean" />
+ <ref component-id="serverResourceBean" />
+ <ref component-id="usageResourceBean" />
+ <ref component-id="versionResourceBean" />
+ </jaxrs:serviceBeans>
+
+ <jaxrs:providers>
+ <bean class="org.apache.brooklyn.rest.util.DefaultExceptionMapper"/>
+ <bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider"/>
+ <bean class="org.apache.brooklyn.rest.util.FormMapProvider"/>
+ </jaxrs:providers>
+ </jaxrs:server>
+</blueprint>
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/6f624c78/rest/rest-resources/src/main/resources/build-metadata.properties
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/main/resources/build-metadata.properties b/rest/rest-resources/src/main/resources/build-metadata.properties
new file mode 100644
index 0000000..eab85ef
--- /dev/null
+++ b/rest/rest-resources/src/main/resources/build-metadata.properties
@@ -0,0 +1,18 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+git-sha-1 = ${buildNumber}
+git-branch-name = ${scmBranch}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/6f624c78/rest/rest-resources/src/main/resources/not-a-jar-file.txt
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/main/resources/not-a-jar-file.txt b/rest/rest-resources/src/main/resources/not-a-jar-file.txt
new file mode 100644
index 0000000..fbc22fe
--- /dev/null
+++ b/rest/rest-resources/src/main/resources/not-a-jar-file.txt
@@ -0,0 +1,18 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+Test loading of malformed jar file
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/6f624c78/rest/rest-resources/src/main/resources/reset-catalog.xml
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/main/resources/reset-catalog.xml b/rest/rest-resources/src/main/resources/reset-catalog.xml
new file mode 100644
index 0000000..adef40a
--- /dev/null
+++ b/rest/rest-resources/src/main/resources/reset-catalog.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+<catalog>
+ <name>Brooklyn Demos</name>
+
+ <template type="org.apache.brooklyn.entity.stock.BasicApplication" name="Basic application" />
+ <template type="org.apache.brooklyn.test.osgi.entities.SimpleApplication" name="Simple OSGi application">
+ <libraries>
+ <bundle>${bundle-location}</bundle>
+ </libraries>
+ </template>
+ <catalog>
+ <name>Nested catalog</name>
+ <template type="org.apache.brooklyn.test.osgi.entities.SimpleApplication" name="Simple OSGi application">
+ <libraries>
+ <bundle>${bundle-location}</bundle>
+ </libraries>
+ </template>
+ </catalog>
+</catalog>
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/6f624c78/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/domain/ApplicationTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/domain/ApplicationTest.java b/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/domain/ApplicationTest.java
new file mode 100644
index 0000000..f715178
--- /dev/null
+++ b/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/domain/ApplicationTest.java
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.rest.domain;
+
+import static org.apache.brooklyn.rest.util.RestApiTestUtils.asJson;
+import static org.apache.brooklyn.rest.util.RestApiTestUtils.fromJson;
+import static org.apache.brooklyn.rest.util.RestApiTestUtils.jsonFixture;
+import static org.testng.Assert.assertEquals;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.Map;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.core.entity.Entities;
+import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.test.Asserts;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+
+public class ApplicationTest {
+
+ final EntitySpec entitySpec = new EntitySpec("Vanilla Java App", "org.apache.brooklyn.entity.java.VanillaJavaApp",
+ ImmutableMap.of(
+ "initialSize", "1",
+ "creationScriptUrl", "http://my.brooklyn.io/storage/foo.sql"));
+
+ final ApplicationSpec applicationSpec = ApplicationSpec.builder().name("myapp")
+ .entities(ImmutableSet.of(entitySpec))
+ .locations(ImmutableSet.of("/locations/1"))
+ .build();
+
+ final Map<String, URI> links = ImmutableMap.of(
+ "self", URI.create("/applications/" + applicationSpec.getName()),
+ "entities", URI.create("fixtures/entity-summary-list.json"));
+ final ApplicationSummary application = new ApplicationSummary("myapp_id", applicationSpec, Status.STARTING, links);
+
+ @Test
+ public void testSerializeToJSON() throws IOException {
+ assertEquals(asJson(application), jsonFixture("fixtures/application.json"));
+ }
+
+ @Test
+ public void testDeserializeFromJSON() throws IOException {
+ assertEquals(fromJson(jsonFixture("fixtures/application.json"),
+ ApplicationSummary.class), application);
+ }
+
+ @Test
+ public void testTransitionToRunning() {
+ ApplicationSummary running = application.transitionTo(Status.RUNNING);
+ assertEquals(running.getStatus(), Status.RUNNING);
+ }
+
+ @Test
+ public void testAppInAppTest() throws IOException {
+ ManagementContext mgmt = LocalManagementContextForTests.newInstance();
+ try {
+ TestApplication app = mgmt.getEntityManager().createEntity(org.apache.brooklyn.api.entity.EntitySpec.create(TestApplication.class));
+ app.addChild(org.apache.brooklyn.api.entity.EntitySpec.create(TestApplication.class));
+ Asserts.assertEqualsIgnoringOrder(mgmt.getApplications(), ImmutableList.of(app));
+ } finally {
+ Entities.destroyAll(mgmt);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/6f624c78/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/domain/SensorSummaryTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/domain/SensorSummaryTest.java b/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/domain/SensorSummaryTest.java
new file mode 100644
index 0000000..1900c56
--- /dev/null
+++ b/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/domain/SensorSummaryTest.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.rest.domain;
+
+import static org.apache.brooklyn.rest.util.RestApiTestUtils.asJson;
+import static org.apache.brooklyn.rest.util.RestApiTestUtils.fromJson;
+import static org.apache.brooklyn.rest.util.RestApiTestUtils.jsonFixture;
+import static org.testng.Assert.assertEquals;
+
+import java.io.IOException;
+import java.net.URI;
+
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.api.sensor.Sensor;
+import org.apache.brooklyn.core.config.render.RendererHints;
+import org.apache.brooklyn.core.entity.Entities;
+import org.apache.brooklyn.core.sensor.Sensors;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.rest.transform.SensorTransformer;
+
+import com.google.common.collect.ImmutableMap;
+import javax.ws.rs.core.UriBuilder;
+
+public class SensorSummaryTest {
+
+ private SensorSummary sensorSummary = new SensorSummary("redis.uptime", "Integer",
+ "Description", ImmutableMap.of(
+ "self", URI.create("/applications/redis-app/entities/redis-ent/sensors/redis.uptime")));
+
+ private TestApplication app;
+ private TestEntity entity;
+ private ManagementContext mgmt;
+
+ @BeforeMethod(alwaysRun = true)
+ public void setUp() throws Exception {
+ app = TestApplication.Factory.newManagedInstanceForTests();
+ mgmt = app.getManagementContext();
+ entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown() throws Exception {
+ if (mgmt != null) Entities.destroyAll(mgmt);
+ }
+
+ @Test
+ public void testSerializeToJSON() throws IOException {
+ assertEquals(asJson(sensorSummary), jsonFixture("fixtures/sensor-summary.json"));
+ }
+
+ @Test
+ public void testDeserializeFromJSON() throws IOException {
+ assertEquals(fromJson(jsonFixture("fixtures/sensor-summary.json"), SensorSummary.class), sensorSummary);
+ }
+
+ @Test
+ public void testEscapesUriForSensorName() throws IOException {
+ Sensor<String> sensor = Sensors.newStringSensor("name with space");
+ SensorSummary summary = SensorTransformer.sensorSummary(entity, sensor, UriBuilder.fromPath("/"));
+ URI selfUri = summary.getLinks().get("self");
+
+ String expectedUri = "/applications/" + entity.getApplicationId() + "/entities/" + entity.getId() + "/sensors/" + "name%20with%20space";
+
+ assertEquals(selfUri, URI.create(expectedUri));
+ }
+
+ // Previously failed because immutable-map builder threw exception if put same key multiple times,
+ // and the NamedActionWithUrl did not have equals/hashCode
+ @Test
+ public void testSensorWithMultipleOpenUrlActionsRegistered() throws IOException {
+ AttributeSensor<String> sensor = Sensors.newStringSensor("sensor1");
+ entity.sensors().set(sensor, "http://myval");
+ RendererHints.register(sensor, RendererHints.namedActionWithUrl());
+ RendererHints.register(sensor, RendererHints.namedActionWithUrl());
+
+ SensorSummary summary = SensorTransformer.sensorSummary(entity, sensor, UriBuilder.fromPath("/"));
+
+ assertEquals(summary.getLinks().get("action:open"), URI.create("http://myval"));
+ }
+}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/6f624c78/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/filter/HaHotCheckTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/filter/HaHotCheckTest.java b/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/filter/HaHotCheckTest.java
new file mode 100644
index 0000000..4b1faca
--- /dev/null
+++ b/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/filter/HaHotCheckTest.java
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.rest.filter;
+
+import static org.testng.Assert.assertEquals;
+
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityManager;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
+import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
+import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.rest.filter.HaHotCheckResourceFilter;
+import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
+import org.apache.brooklyn.rest.util.HaHotStateCheckClassResource;
+import org.apache.brooklyn.rest.util.HaHotStateCheckResource;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.testng.annotations.Test;
+
+public class HaHotCheckTest extends BrooklynRestResourceTest {
+
+ @Override
+ protected void addBrooklynResources() {
+ addResource(new HaHotCheckResourceFilter());
+ addResource(new HaHotStateCheckResource());
+ addResource(new HaHotStateCheckClassResource());
+
+ ((LocalManagementContext)getManagementContext()).noteStartupComplete();
+ }
+
+ @Override
+ protected boolean isMethodInit() {
+ return true;
+ }
+
+ @Test
+ public void testHaCheck() {
+ HighAvailabilityManager ha = getManagementContext().getHighAvailabilityManager();
+ assertEquals(ha.getNodeState(), ManagementNodeState.MASTER);
+ testResourceFetch("/ha/method/ok", 200);
+ testResourceFetch("/ha/method/fail", 200);
+ testResourceFetch("/ha/class/fail", 200);
+
+ getManagementContext().getHighAvailabilityManager().changeMode(HighAvailabilityMode.STANDBY);
+ assertEquals(ha.getNodeState(), ManagementNodeState.STANDBY);
+
+ testResourceFetch("/ha/method/ok", 200);
+ testResourceFetch("/ha/method/fail", 403);
+ testResourceFetch("/ha/class/fail", 403);
+
+ ((ManagementContextInternal)getManagementContext()).terminate();
+ assertEquals(ha.getNodeState(), ManagementNodeState.TERMINATED);
+
+ testResourceFetch("/ha/method/ok", 200);
+ testResourceFetch("/ha/method/fail", 403);
+ testResourceFetch("/ha/class/fail", 403);
+ }
+
+ @Test
+ public void testHaCheckForce() {
+ HighAvailabilityManager ha = getManagementContext().getHighAvailabilityManager();
+ assertEquals(ha.getNodeState(), ManagementNodeState.MASTER);
+ testResourceForcedFetch("/ha/method/ok", 200);
+ testResourceForcedFetch("/ha/method/fail", 200);
+ testResourceForcedFetch("/ha/class/fail", 200);
+
+ getManagementContext().getHighAvailabilityManager().changeMode(HighAvailabilityMode.STANDBY);
+ assertEquals(ha.getNodeState(), ManagementNodeState.STANDBY);
+
+ testResourceForcedFetch("/ha/method/ok", 200);
+ testResourceForcedFetch("/ha/method/fail", 200);
+ testResourceForcedFetch("/ha/class/fail", 200);
+
+ ((ManagementContextInternal)getManagementContext()).terminate();
+ assertEquals(ha.getNodeState(), ManagementNodeState.TERMINATED);
+
+ testResourceForcedFetch("/ha/method/ok", 200);
+ testResourceForcedFetch("/ha/method/fail", 200);
+ testResourceForcedFetch("/ha/class/fail", 200);
+ }
+
+
+ private void testResourceFetch(String resourcePath, int code) {
+ testResourceFetch(resourcePath, false, code);
+ }
+
+ private void testResourceForcedFetch(String resourcePath, int code) {
+ testResourceFetch(resourcePath, true, code);
+ }
+
+ private void testResourceFetch(String resourcePath, boolean force, int code) {
+ WebClient resource = client().path(resourcePath)
+ .accept(MediaType.APPLICATION_JSON_TYPE);
+ if (force) {
+ resource.header(HaHotCheckResourceFilter.SKIP_CHECK_HEADER, "true");
+ }
+ Response response = resource
+ .get();
+ assertEquals(response.getStatus(), code);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/6f624c78/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/resources/AccessResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/resources/AccessResourceTest.java b/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/resources/AccessResourceTest.java
new file mode 100644
index 0000000..f63676d
--- /dev/null
+++ b/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/resources/AccessResourceTest.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.rest.resources;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+import javax.ws.rs.core.Response;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+
+import org.apache.brooklyn.rest.domain.AccessSummary;
+import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
+
+@Test(singleThreaded = true,
+ // by using a different suite name we disallow interleaving other tests between the methods of this test class, which wrecks the test fixtures
+ suiteName = "AccessResourceTest")
+public class AccessResourceTest extends BrooklynRestResourceTest {
+
+ @SuppressWarnings("unused")
+ private static final Logger log = LoggerFactory.getLogger(AccessResourceTest.class);
+
+ @Test
+ public void testGetAndSetAccessControl() throws Exception {
+ // Default is everything allowed
+ AccessSummary summary = client().path("/access").get(AccessSummary.class);
+ assertTrue(summary.isLocationProvisioningAllowed());
+
+ // Forbid location provisioning
+ Response response = client().path("/access/locationProvisioningAllowed")
+ .query("allowed", "false")
+ .post(null);
+ assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
+
+ AccessSummary summary2 = client().path("/access").get(AccessSummary.class);
+ assertFalse(summary2.isLocationProvisioningAllowed());
+
+ // Allow location provisioning
+ Response response2 = client().path("/access/locationProvisioningAllowed")
+ .query("allowed", "true")
+ .post(null);
+ assertEquals(response2.getStatus(), Response.Status.OK.getStatusCode());
+
+ AccessSummary summary3 = client().path("/access").get(AccessSummary.class);
+ assertTrue(summary3.isLocationProvisioningAllowed());
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/6f624c78/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/resources/ApidocResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/resources/ApidocResourceTest.java b/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/resources/ApidocResourceTest.java
new file mode 100644
index 0000000..af09e67
--- /dev/null
+++ b/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/resources/ApidocResourceTest.java
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.rest.resources;
+
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+
+import java.util.Collection;
+
+import org.apache.brooklyn.rest.BrooklynRestApi;
+import org.apache.brooklyn.rest.api.CatalogApi;
+import org.apache.brooklyn.rest.api.EffectorApi;
+import org.apache.brooklyn.rest.api.EntityApi;
+import org.apache.brooklyn.rest.apidoc.RestApiResourceScanner;
+import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Function;
+import com.google.common.base.Predicate;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+
+import io.swagger.annotations.Api;
+import io.swagger.config.ScannerFactory;
+import io.swagger.models.Operation;
+import io.swagger.models.Path;
+import io.swagger.models.Swagger;
+
+/**
+ * @author Adam Lowe
+ */
+@Test(singleThreaded = true)
+public class ApidocResourceTest extends BrooklynRestResourceTest {
+
+ private static final Logger log = LoggerFactory.getLogger(ApidocResourceTest.class);
+
+ @Override
+ protected void addBrooklynResources() {
+ ScannerFactory.setScanner(new RestApiResourceScanner());
+
+ for (Object o : BrooklynRestApi.getApidocResources()) {
+ addResource(o);
+ }
+ super.addBrooklynResources();
+ }
+
+
+ @Test(enabled = false)
+ public void testRootSerializesSensibly() throws Exception {
+ String data = client().path("/apidoc/swagger.json").get(String.class);
+ log.info("apidoc gives: "+data);
+ // make sure no scala gets in
+ assertFalse(data.contains("$"));
+ assertFalse(data.contains("scala"));
+ // make sure it's an appropriate swagger 2.0 json
+ Swagger swagger = client().path("/apidoc/swagger.json").get(Swagger.class);
+ assertEquals(swagger.getSwagger(), "2.0");
+ }
+
+ @Test(enabled = false)
+ public void testCountRestResources() throws Exception {
+ Swagger swagger = client().path("/apidoc/swagger.json").get(Swagger.class);
+ assertEquals(swagger.getTags().size(), 1 + Iterables.size(BrooklynRestApi.getBrooklynRestResources()));
+ }
+
+ @Test(enabled = false)
+ public void testApiDocDetails() throws Exception {
+ Swagger swagger = client().path("/apidoc/swagger.json").get(Swagger.class);
+ Collection<Operation> operations = getTaggedOperations(swagger, ApidocResource.class.getAnnotation(Api.class).value());
+ assertEquals(operations.size(), 2, "ops="+operations);
+ }
+
+ @Test(enabled = false)
+ public void testEffectorDetails() throws Exception {
+ Swagger swagger = client().path("/apidoc/swagger.json").get(Swagger.class);
+ Collection<Operation> operations = getTaggedOperations(swagger, EffectorApi.class.getAnnotation(Api.class).value());
+ assertEquals(operations.size(), 2, "ops="+operations);
+ }
+
+ @Test(enabled = false)
+ public void testEntityDetails() throws Exception {
+ Swagger swagger = client().path("/apidoc/swagger.json").get(Swagger.class);
+ Collection<Operation> operations = getTaggedOperations(swagger, EntityApi.class.getAnnotation(Api.class).value());
+ assertEquals(operations.size(), 14, "ops="+operations);
+ }
+
+ @Test(enabled = false)
+ public void testCatalogDetails() throws Exception {
+ Swagger swagger = client().path("/apidoc/swagger.json").get(Swagger.class);
+ Collection<Operation> operations = getTaggedOperations(swagger, CatalogApi.class.getAnnotation(Api.class).value());
+ assertEquals(operations.size(), 22, "ops="+operations);
+ }
+
+ /**
+ * Retrieves all operations tagged the given tag from the given swagger spec.
+ */
+ private Collection<Operation> getTaggedOperations(Swagger swagger, final String requiredTag) {
+ Iterable<Operation> allOperations = Iterables.concat(Collections2.transform(swagger.getPaths().values(),
+ new Function<Path, Collection<Operation>>() {
+ @Override
+ public Collection<Operation> apply(Path path) {
+ return path.getOperations();
+ }
+ }));
+
+ return Collections2.filter(ImmutableList.copyOf(allOperations), new Predicate<Operation>() {
+ @Override
+ public boolean apply(Operation operation) {
+ return operation.getTags().contains(requiredTag);
+ }
+ });
+ }
+
+}
+
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/6f624c78/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceIntegrationTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceIntegrationTest.java b/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceIntegrationTest.java
new file mode 100644
index 0000000..743eee4
--- /dev/null
+++ b/rest/rest-resources/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceIntegrationTest.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.rest.resources;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.net.URI;
+import java.util.Set;
+
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+import org.apache.brooklyn.core.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.rest.domain.ApplicationSpec;
+import org.apache.brooklyn.rest.domain.ApplicationSummary;
+import org.apache.brooklyn.rest.domain.EntitySpec;
+import org.apache.brooklyn.rest.domain.EntitySummary;
+import org.apache.brooklyn.rest.domain.SensorSummary;
+import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.collections.MutableMap;
+
+import com.google.common.base.Predicate;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import javax.ws.rs.core.GenericType;
+
+@Test(singleThreaded = true)
+public class ApplicationResourceIntegrationTest extends BrooklynRestResourceTest {
+
+ @SuppressWarnings("unused")
+ private static final Logger log = LoggerFactory.getLogger(ApplicationResourceIntegrationTest.class);
+
+ private final ApplicationSpec redisSpec = ApplicationSpec.builder().name("redis-app")
+ .entities(ImmutableSet.of(new EntitySpec("redis-ent", "org.apache.brooklyn.entity.nosql.redis.RedisStore")))
+ .locations(ImmutableSet.of("localhost"))
+ .build();
+
+ @Test(groups="Integration")
+ public void testDeployRedisApplication() throws Exception {
+ Response response = clientDeploy(redisSpec);
+
+ assertEquals(response.getStatus(), 201);
+ assertEquals(getManagementContext().getApplications().size(), 1);
+ assertTrue(response.getLocation().getPath().startsWith("/applications/"), "path="+response.getLocation().getPath()); // path uses id, rather than app name
+
+ waitForApplicationToBeRunning(response.getLocation());
+ }
+
+ @Test(groups="Integration", dependsOnMethods = "testDeployRedisApplication")
+ public void testListEntities() {
+ Set<EntitySummary> entities = client().path("/applications/redis-app/entities")
+ .get(new GenericType<Set<EntitySummary>>() {});
+
+ for (EntitySummary entity : entities) {
+ client().path(entity.getLinks().get("self")).get();
+ // TODO assertions on the above call?
+
+ Set<EntitySummary> children = client().path(entity.getLinks().get("children"))
+ .get(new GenericType<Set<EntitySummary>>() {});
+ assertEquals(children.size(), 0);
+ }
+ }
+
+ @Test(groups="Integration", dependsOnMethods = "testDeployRedisApplication")
+ public void testListSensorsRedis() {
+ Set<SensorSummary> sensors = client().path("/applications/redis-app/entities/redis-ent/sensors")
+ .get(new GenericType<Set<SensorSummary>>() {});
+ assertTrue(sensors.size() > 0);
+ SensorSummary uptime = Iterables.find(sensors, new Predicate<SensorSummary>() {
+ @Override
+ public boolean apply(SensorSummary sensorSummary) {
+ return sensorSummary.getName().equals("redis.uptime");
+ }
+ });
+ assertEquals(uptime.getType(), "java.lang.Integer");
+ }
+
+ @Test(groups="Integration", dependsOnMethods = { "testListSensorsRedis", "testListEntities" })
+ public void testTriggerRedisStopEffector() throws Exception {
+ Response response = client().path("/applications/redis-app/entities/redis-ent/effectors/stop")
+ .type(MediaType.APPLICATION_JSON_TYPE)
+ .post(toJsonEntity(ImmutableMap.of()));
+ assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode());
+
+ final URI stateSensor = URI.create("/applications/redis-app/entities/redis-ent/sensors/service.state");
+ final String expectedStatus = Lifecycle.STOPPED.toString();
+ Asserts.succeedsEventually(MutableMap.of("timeout", 60 * 1000), new Runnable() {
+ public void run() {
+ // Accept with and without quotes; if don't specify "Accepts" header, then
+ // might get back json or plain text (depending on compiler / java runtime
+ // used for SensorApi!)
+ String val = client().path(stateSensor).get(String.class);
+ assertTrue(expectedStatus.equalsIgnoreCase(val) || ("\""+expectedStatus+"\"").equalsIgnoreCase(val), "state="+val);
+ }
+ });
+ }
+
+ @Test(groups="Integration", dependsOnMethods = "testTriggerRedisStopEffector" )
+ public void testDeleteRedisApplication() throws Exception {
+ int size = getManagementContext().getApplications().size();
+ Response response = client().path("/applications/redis-app")
+ .delete();
+
+ waitForPageNotFoundResponse("/applications/redis-app", ApplicationSummary.class);
+
+ assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode());
+ assertEquals(getManagementContext().getApplications().size(), size-1);
+ }
+
+}