@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { Navigator<MutableMap<Object, Object>> j = Jsonya.newInstance().map(); BasicHttpRequest req = (BasicHttpRequest)request; String url = req.getRequestLine().getUri(); URI uri = URI.create(url); String method = req.getRequestLine().getMethod(); boolean expectsPost = uri.getPath().equals("/post"); if (expectsPost && !method.equals("POST") || !expectsPost && !method.equals("GET")) { throw new IllegalStateException("Method " + method + " not allowed on " + url); } List<NameValuePair> params = URLEncodedUtils.parse(uri, "UTF-8"); if (!params.isEmpty()) { j.push().at("args"); for (NameValuePair param : params) { j.put(param.getName(), param.getValue()); } j.pop(); } j.put("origin", "127.0.0.1"); j.put("url", serverUrl + url); response.setHeader("Content-Type", "application/json"); response.setStatusCode(200); response.setEntity(new StringEntity(j.toString())); } public void setServerUrl(String serverUrl) {
@SuppressWarnings("rawtypes") @Test public void testJsonyaWithList() { Navigator<MutableMap<Object, Object>> n = europeMap(); n.at("europe", "uk", "neighbours").list().add("ireland") .root().at("europe", "france", "neighbours").list().add("spain", "germany").add("switzerland") .root().at("europe", "france", "neighbours").add("lux"); Object l = n.root().at("europe", "france", "neighbours").get(); Assert.assertTrue(l instanceof List); Assert.assertEquals(((List)l).size(), 4); // this wants a map, so it creates a map in the list n.put("east", "germany", "south", "spain"); Assert.assertEquals(((List)l).size(), 5); Map nd = (Map) ((List)l).get(4); Assert.assertEquals(nd.size(), 2); Map nd2 = (Map) n.root().get("europe", "france", "neighbours", 4); Assert.assertEquals(nd2.size(), 2); }
protected String extractPlanYamlString(ConfigBag parameters) { Object planRaw = parameters.getStringKey(BLUEPRINT_CAMP_PLAN.getName()); if (planRaw instanceof String && Strings.isBlank((String)planRaw)) planRaw = null; String url = parameters.get(BLUEPRINT_TYPE); if (url!=null && planRaw!=null) throw new IllegalArgumentException("Cannot supply both plan and url"); if (url==null && planRaw==null) throw new IllegalArgumentException("Must supply plan or url"); Map<String, Object> config = asMap(parameters, BLUEPRINT_CONFIG); if (planRaw==null) { planRaw = Jsonya.at("services").list().put("serviceType", url).putIfNotNull("brooklyn.config", config).getRootMap(); } else { if (config!=null) throw new IllegalArgumentException("Cannot supply plan with config"); } // planRaw might be a yaml string, or a map; if a map, convert to string if (planRaw instanceof Map) planRaw = Jsonya.of((Map<?,?>)planRaw).toString(); if (!(planRaw instanceof String)) throw new IllegalArgumentException("Invalid "+JavaClassNames.simpleClassName(planRaw)+" value for CAMP plan: "+planRaw); // now *all* the data is in planRaw; that is what will be submitted return (String)planRaw; }
MutableMap.of(com.google.common.net.HttpHeaders.CONTENT_TYPE, "application/json"), Jsonya.newInstance() .put("blueprintType", TestApplication.class.getName()) .put("blueprintConfig", MutableMap.of(TestEntity.CONF_NAME.getName(), "foo")) .toString().getBytes()); log.info("Deploy effector invoked, result: "+result); HttpTestUtils.assertHealthyStatusCode( result.getResponseCode() );
Navigator<MutableMap<Object, Object>> attrs = Jsonya.newInstancePrimitive().at("brooklyn"); if (Strings.isNonBlank(primary)) attrs.at(primary); attrs.at("config"); attrs.put( entity().config().getBag().getAllConfig() ); attrs.root().put((Map<?,?>)Tasks.resolveDeepValue(entity().getConfig(CHEF_LAUNCH_ATTRIBUTES), Object.class, entity().getExecutionContext())); } catch (Exception e) { Exceptions.propagate(e); } runList, (Map<String, Object>) attrs.root().get()));
Navigator<MutableMap<Object, Object>> attrs = Jsonya.newInstancePrimitive().at("brooklyn"); if (Strings.isNonBlank(primary)) attrs.at(primary); attrs.at("config"); attrs.put( entity().config().getBag().getAllConfig() ); attrs.root().put((Map<?,?>)Tasks.resolveDeepValue(entity().getConfig(CHEF_LAUNCH_ATTRIBUTES), Object.class, entity().getExecutionContext())); } catch (Exception e) { Exceptions.propagate(e); } runList, (Map<String, Object>) attrs.root().get()));
if (others.length>0) { map(); } else { addInternal(focus, focus, o1, others); return this;
@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" }) protected void startWithKnifeAsync() { // TODO prestart, ports (as above); also, note, some aspects of this are untested as we need a chef server String primary = getPrimaryCookbook(); // put all config under brooklyn/cookbook/config Navigator<MutableMap<Object, Object>> attrs = Jsonya.newInstancePrimitive().at("brooklyn"); if (Strings.isNonBlank(primary)) attrs.at(primary); attrs.at("config"); attrs.put( entity().config().getBag().getAllConfig() ); // and put launch attrs at root try { attrs.root().put((Map<?,?>)Tasks.resolveDeepValue(entity().getConfig(CHEF_LAUNCH_ATTRIBUTES), Object.class, entity().getExecutionContext())); } catch (Exception e) { Exceptions.propagate(e); } Collection<? extends String> runList = entity().getConfig(CHEF_LAUNCH_RUN_LIST); if (runList==null) runList = entity().getConfig(CHEF_RUN_LIST); if (runList==null) { if (Strings.isNonBlank(primary)) runList = ImmutableList.of(primary+"::"+"start"); else throw new IllegalStateException("Require a primary cookbook or a run_list to effect "+"start"+" on "+entity()); } DynamicTasks.queue( ChefServerTasks.knifeConvergeTask() .knifeNodeName(getNodeName()) .knifeRunList(Strings.join(runList, ",")) .knifeAddAttributes((Map) attrs.root().get()) .knifeRunTwice(entity().getConfig(CHEF_RUN_CONVERGE_TWICE)) ); }
@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" }) protected void startWithKnifeAsync() { // TODO prestart, ports (as above); also, note, some aspects of this are untested as we need a chef server String primary = getPrimaryCookbook(); // put all config under brooklyn/cookbook/config Navigator<MutableMap<Object, Object>> attrs = Jsonya.newInstancePrimitive().at("brooklyn"); if (Strings.isNonBlank(primary)) attrs.at(primary); attrs.at("config"); attrs.put( entity().config().getBag().getAllConfig() ); // and put launch attrs at root try { attrs.root().put((Map<?,?>)Tasks.resolveDeepValue(entity().getConfig(CHEF_LAUNCH_ATTRIBUTES), Object.class, entity().getExecutionContext())); } catch (Exception e) { Exceptions.propagate(e); } Collection<? extends String> runList = entity().getConfig(CHEF_LAUNCH_RUN_LIST); if (runList==null) runList = entity().getConfig(CHEF_RUN_LIST); if (runList==null) { if (Strings.isNonBlank(primary)) runList = ImmutableList.of(primary+"::"+"start"); else throw new IllegalStateException("Require a primary cookbook or a run_list to effect "+"start"+" on "+entity()); } DynamicTasks.queue( ChefServerTasks.knifeConvergeTask() .knifeNodeName(getNodeName()) .knifeRunList(Strings.join(runList, ",")) .knifeAddAttributes((Map) attrs.root().get()) .knifeRunTwice(entity().getConfig(CHEF_RUN_CONVERGE_TWICE)) ); }
@Override protected void startWithKnifeAsync() { Entities.warnOnIgnoringConfig(entity(), ChefConfig.CHEF_LAUNCH_RUN_LIST); Entities.warnOnIgnoringConfig(entity(), ChefConfig.CHEF_LAUNCH_ATTRIBUTES); DynamicTasks.queue( ChefServerTasks .knifeConvergeRunList("postgresql::server") .knifeAddAttributes(Jsonya .at("postgresql", "config").add( "port", entity().getPostgreSqlPort(), "listen_addresses", "*").getRootMap()) .knifeAddAttributes(Jsonya .at("postgresql", "pg_hba").list().map().add( "type", "host", "db", "all", "user", "all", "addr", "0.0.0.0/0", "method", "md5").getRootMap()) // no other arguments currenty supported; chef will pick a password for us ); } @Override
@Test public void testJsonyaPushPop() { Navigator<MutableMap<Object, Object>> m = europeMap(); Assert.assertTrue(m.getFocusMap().containsKey("europe")); Assert.assertFalse(m.getFocusMap().containsKey("edinburgh")); m.push(); m.at("europe", "uk"); Assert.assertTrue(m.getFocusMap().containsKey("edinburgh")); Assert.assertFalse(m.getFocusMap().containsKey("europe")); m.pop(); Assert.assertTrue(m.getFocusMap().containsKey("europe")); Assert.assertFalse(m.getFocusMap().containsKey("edinburgh")); // also check 'get' does not change focus m.get("europe", "uk"); Assert.assertTrue(m.getFocusMap().containsKey("europe")); Assert.assertFalse(m.getFocusMap().containsKey("edinburgh")); }
@Test public void testPrimitivedAndLiteralledMap() { Object foo = new Object() { @Override public String toString() { return "FOO"; } }; MutableMap<Object, Object> map = MutableMap.<Object,Object>of("a", 1, 2, Arrays.<Object>asList(true, 8, "8"), 'C', foo); Map<Object, Object> mapL = Jsonya.newInstanceLiteral().put(map).getRootMap(); Assert.assertEquals(mapL, map); Assert.assertEquals(mapL.get('C'), foo); Map<Object, Object> mapP = Jsonya.newInstancePrimitive().put(map).getRootMap(); Assert.assertNotEquals(mapP, map); Assert.assertEquals(mapP.get('C'), foo.toString()); Assert.assertEquals(MutableMap.copyOf(mapP).add('C', null), MutableMap.copyOf(map).add('C', null)); }
@Test(groups="Integration") public void testProvisioningPropertiesViaJsonya() throws Exception { Entity app = createAndStartApplication( Jsonya.newInstance() .put("location", "localhost") .at("services").list() .put("type", EmptySoftwareProcess.class.getName()) .at("provisioning.properties").put("minRam", 16384) .root().toString()); waitForApplicationTasks(app); log.info("App started:"); Entities.dumpInfo(app); EmptySoftwareProcess entity = (EmptySoftwareProcess) app.getChildren().iterator().next(); Map<String, Object> pp = entity.getConfig(EmptySoftwareProcess.PROVISIONING_PROPERTIES); Assert.assertEquals(pp.get("minRam"), 16384); }
/** as {@link #get(Class)} but always wrapped in a {@link Maybe}, absent if null * @throws ClassCastException if object exists here but of the wrong type */ public @Nonnull <V> Maybe<V> getMaybe(Class<V> type) { return Maybe.fromNullable(get(type)); }
@Override public T call(ConfigBag parameters) { MutableMap<String, String> headers = MutableMap.of(com.google.common.net.HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()); byte[] httpBody = Jsonya.of(parameters.getAllConfig()).toString().getBytes(); String effectorUrl = Urls.mergePaths("effectors", Urls.encode(remoteEffectorName)); HttpToolResponse result = ((BrooklynEntityMirror)entity()).http().post(effectorUrl, headers, httpBody); if (resultParser!=null) return resultParser.apply(result); else return null; } }
/** includes the given attributes in the attributes to be passed to chef; * when combining with other attributes, this uses {@link Jsonya} semantics to add * (a deep add, combining lists and maps) */ public KnifeConvergeTaskFactory<RET> knifeAddAttributes(Map<? extends Object, ? extends Object> attributes) { if (attributes!=null && !attributes.isEmpty()) { Jsonya.of(knifeAttributes).add(attributes); } return self(); }
/** returns a {@link Map} at the given focus, creating if needed (so never null), * throwing if it exists already and is not a map */ public T getFocusMap() { map(); return (T)focus; }