/** * Installs a list of plugins from a JSON POST. * @param req The request object. * @return A JSON response that includes a "correlationId" in the "data" element. * That "correlationId" can then be used in calls to * {@link UpdateCenter#doInstallStatus(org.kohsuke.stapler.StaplerRequest)}. * @throws IOException Error reading JSON payload fro request. */ @RequirePOST @Restricted(DoNotUse.class) // WebOnly public HttpResponse doInstallPlugins(StaplerRequest req) throws IOException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); String payload = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding()); JSONObject request = JSONObject.fromObject(payload); JSONArray pluginListJSON = request.getJSONArray("plugins"); List<String> plugins = new ArrayList<>(); for (int i = 0; i < pluginListJSON.size(); i++) { plugins.add(pluginListJSON.getString(i)); } UUID correlationId = UUID.randomUUID(); try { boolean dynamicLoad = request.getBoolean("dynamicLoad"); install(plugins, dynamicLoad, correlationId); JSONObject responseData = new JSONObject(); responseData.put("correlationId", correlationId.toString()); return hudson.util.HttpResponses.okJSON(responseData); } catch (Exception e) { return hudson.util.HttpResponses.errorJSON(e.getMessage()); } }
/** * @param list the list of auth urls to serialize * @return {@code null} if {@code list} is null, empty, or contains only null objects; the JSON * array representation of {@code list} otherwise, with any null element stripped off. */ public static String toString(List<LayerIdentifierInfo> list) { if (list == null || list.isEmpty()) { return null; } JSONArray array = new JSONArray(); for (LayerIdentifierInfo id : list) { if (id == null) { continue; } JSONObject jsonId = new JSONObject(); jsonId.put(AUTHORITY, id.getAuthority()); jsonId.put(IDENTIFIER, id.getIdentifier()); array.add(jsonId); } if (array.size() == 0) { // list was made of only null objects? return null; } String serialized = array.toString(); return serialized; } }
JSONObject formData = req.getSubmittedForm(); JSONArray a = JSONArray.fromObject(formData.get("parameter")); String name = jo.getString("name"); WaitingItem item = Jenkins.getInstance().getQueue().schedule( getJob(), delay.getTimeInSeconds(), new ParametersAction(values), new CauseAction(new Cause.UserIdCause())); if (item!=null) { String url = formData.optString("redirectTo"); if (url==null || !Util.isSafeToRedirectTo(url)) // avoid open redirect url = req.getContextPath()+'/'+item.getUrl(); rsp.sendRedirect(formData.optInt("statusCode",SC_CREATED), url); } else
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { rsp.setContentType(Flavor.JSON.contentType); PrintWriter w = rsp.getWriter(); JSONArray.fromObject(this).write(w); } }
/** * Like {@link #doInstallNecessaryPlugins(StaplerRequest)} but only checks if everything is installed * or if some plugins need updates or installation. * * This method runs without side-effect. I'm still requiring the ADMINISTER permission since * XML file can contain various external references and we don't configure parsers properly against * that. * * @since 1.483 */ @RequirePOST public JSONArray doPrevalidateConfig(StaplerRequest req) throws IOException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); JSONArray response = new JSONArray(); for (Map.Entry<String,VersionNumber> p : parseRequestedPlugins(req.getInputStream()).entrySet()) { PluginWrapper pw = getPlugin(p.getKey()); JSONObject j = new JSONObject() .accumulate("name", p.getKey()) .accumulate("version", p.getValue().toString()); if (pw == null) { // install new response.add(j.accumulate("mode", "missing")); } else if (pw.isOlderThan(p.getValue())) { // upgrade response.add(j.accumulate("mode", "old")); } // else already good } return response; }
@Test public void testGetSimpleJson() throws Exception { MockHttpServletResponse response = getAsServletResponse( "wfs?request=GetFeature&version=1.0.0&typename=sf:PrimitiveGeoFeature&maxfeatures=1&outputformat=" + JSONType.simple_json, ""); assertEquals("application/json", response.getContentType()); assertEquals("UTF-8", response.getCharacterEncoding()); String out = response.getContentAsString(); JSONObject rootObject = JSONObject.fromObject(out); assertEquals(rootObject.get("type"), "FeatureCollection"); JSONArray featureCol = rootObject.getJSONArray("features"); JSONObject aFeature = featureCol.getJSONObject(0); assertEquals(aFeature.getString("geometry_name"), "surfaceProperty"); }
@Test public void testGetJsonIdPolicyFalse() throws Exception { MockHttpServletResponse response = getAsServletResponse( "wfs?request=GetFeature&version=1.0.0&typename=sf:PrimitiveGeoFeature&maxfeatures=1&outputformat=" + JSONType.simple_json + "&format_options=" + JSONType.ID_POLICY + ":false"); assertEquals("application/json", response.getContentType()); String out = response.getContentAsString(); JSONObject rootObject = JSONObject.fromObject(out); assertEquals(rootObject.get("type"), "FeatureCollection"); JSONArray featureCol = rootObject.getJSONArray("features"); JSONObject aFeature = featureCol.getJSONObject(0); assertFalse("supress id", aFeature.containsKey("id")); }
private void testAllBuildings(JSONObject collection) { assertEquals("FeatureCollection", collection.getString("type")); final JSONArray features = collection.getJSONArray("features"); assertEquals(2 , features.size()); JSONObject feature = (JSONObject) features.get(0); assertEquals("Feature", feature.getString("type")); assertEquals("113", feature.getJSONObject("properties").getString("FID")); feature = (JSONObject) features.get(1); assertEquals("Feature", feature.getString("type")); assertEquals("114", feature.getJSONObject("properties").getString("FID")); }
public boolean configure(StaplerRequest req, JSONObject json) throws hudson.model.Descriptor.FormException { Jenkins j = Jenkins.getInstance(); j.checkPermission(Jenkins.ADMINISTER); if (json.has("useSecurity")) { JSONObject security = json.getJSONObject("useSecurity"); j.setDisableRememberMe(security.optBoolean("disableRememberMe", false)); j.setSecurityRealm(SecurityRealm.all().newInstanceFromRadioList(security, "realm")); j.setAuthorizationStrategy(AuthorizationStrategy.all().newInstanceFromRadioList(security, "authorization")); if (json.has("markupFormatter")) { j.setMarkupFormatter(req.bindJSON(MarkupFormatter.class, json.getJSONObject("markupFormatter"))); } else { j.setMarkupFormatter(null); Object protocols = json.get("agentProtocol"); if (protocols instanceof JSONArray) { for (int i = 0; i < ((JSONArray) protocols).size(); i++) { agentProtocols.add(((JSONArray) protocols).getString(i));
/** * Renders HTTP response. */ public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { // Date needs to be converted into iso-8601 date format. JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(Date.class,new JsonValueProcessor() { public Object processArrayValue(Object value, JsonConfig jsonConfig) { if (value==null) return null; synchronized (SDF) { return SDF.format(value); } } public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) { return processArrayValue(value,jsonConfig); } }); JSONObject o = new JSONObject(); o.put("events", JSONArray.fromObject(this,config)); rsp.setContentType("application/javascript;charset=UTF-8"); o.write(rsp.getWriter()); } }
@Override protected synchronized JSON data() { JSONArray r = new JSONArray(); for (User u : modified) { UserInfo i = users.get(u); JSONObject entry = new JSONObject(). accumulate("id", u.getId()). accumulate("fullName", u.getFullName()). accumulate("url", u.getUrl()). accumulate("avatar", i.avatar != null ? i.avatar : Stapler.getCurrentRequest().getContextPath() + Functions.getResourcePath() + "/images/" + iconSize + "/user.png"). accumulate("timeSortKey", i.getTimeSortKey()). accumulate("lastChangeTimeString", i.getLastChangeTimeString()); Job<?,?> p = i.getJob(); if (p != null) { entry.accumulate("projectUrl", p.getUrl()).accumulate("projectFullDisplayName", p.getFullDisplayName()); } r.add(entry); } modified.clear(); return r; }
assertEquals(JSONType.json, response.getContentType()); assertTrue("UTF-8".equals(response.getCharacterEncoding())); String result = response.getContentAsString(); JSONObject rootObject = JSONObject.fromObject(result); print(rootObject); assertEquals(rootObject.get("type"), "FeatureCollection"); JSONArray featureCol = rootObject.getJSONArray("features"); JSONObject aFeature = featureCol.getJSONObject(0); assertTrue(aFeature.getJSONObject("geometry").isNullObject()); JSONObject properties = aFeature.getJSONObject("properties");
JSONArray keywordAutoReplyInfos = keywordAutoReplyInfoJsonObj.getJSONArray("list"); if(keywordAutoReplyInfos!=null){ List<KeyWordAutoReplyInfo> listKeyWordAutoReplyInfo = new ArrayList<KeyWordAutoReplyInfo>(); for(int i=0;i<keywordAutoReplyInfos.size();i++){ KeyWordAutoReplyInfo keyWordAutoReplyInfo = (KeyWordAutoReplyInfo) JSONObject.toBean(keywordAutoReplyInfos.getJSONObject(i),new CustomJsonConfig(KeyWordAutoReplyInfo.class, new String[]{"keyword_list_info","reply_list_info"})); JSONArray keywordListInfos = keywordAutoReplyInfos.getJSONObject(i).getJSONArray("keyword_list_info"); if(keywordListInfos!=null){ List<KeywordListInfo> listKeywordListInfo = new ArrayList<KeywordListInfo>(); for(int j=0;j<keywordListInfos.size();j++){ KeywordListInfo keywordListInfo = (KeywordListInfo) JSONObject.toBean(keywordListInfos.getJSONObject(j),KeywordListInfo.class); listKeywordListInfo.add(keywordListInfo); JSONArray replyListInfos = keywordAutoReplyInfos.getJSONObject(i).getJSONArray("reply_list_info"); if(replyListInfos!=null){ List<ReplyListInfo> listReplyListInfo = new ArrayList<ReplyListInfo>(); for(int j=0;j<replyListInfos.size();j++){ ReplyListInfo replyListInfo = (ReplyListInfo) JSONObject.toBean(keywordListInfos.getJSONObject(j),new CustomJsonConfig(ReplyListInfo.class, "news_info")); JSONObject newsInfoJsonObj = replyListInfos.getJSONObject(j).getJSONObject("news_info"); if(newsInfoJsonObj!=null && !JSONUtils.isNull(newsInfoJsonObj)){ JSONArray newsInfos = newsInfoJsonObj.getJSONArray("list"); List<WxArticleConfig> listNewsInfo = new ArrayList<WxArticleConfig>(); for (int k = 0; k < newsInfos.size(); k++) { WxArticleConfig wxArticleConfig = (WxArticleConfig) JSONObject.toBean(newsInfos.getJSONObject(k), WxArticleConfig.class); listNewsInfo.add(wxArticleConfig);
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); JSONArray response = new JSONArray(); Map<String,JSONObject> allPlugins = new HashMap<>(); for (PluginWrapper plugin : plugins) { JSONObject pluginInfo = new JSONObject(); pluginInfo.put("installed", true); pluginInfo.put("name", plugin.getShortName()); pluginInfo.put("title", plugin.getDisplayName()); pluginInfo.put("active", plugin.isActive()); pluginInfo.put("dependencies", Collections.emptyMap()); response.add(pluginInfo); for (UpdateSite site : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) { for (UpdateSite.Plugin plugin: site.getAvailables()) { JSONObject pluginInfo = allPlugins.get(plugin.name); pluginInfo.put("dependencies", plugin.dependencies); pluginInfo.put("website", plugin.wiki); response.add(pluginInfo);
/** * {@inheritDoc} */ @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { if (Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)) { if (!json.has("restrictions")) { // JENKINS-36090 stapler "helpfully" does not submit the restrictions if there are none // and hence you can never delete the laste one json.put("restrictions", new JSONArray()); } req.bindJSON(this, json); return super.configure(req, json); } return false; }
@RequirePOST public void doCheck(StaplerRequest req, StaplerResponse res) throws Exception { if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } final Map<Source, String> issues = checkWith(new YamlSource<HttpServletRequest>(req, YamlSource.READ_FROM_REQUEST)); res.setContentType("application/json"); final JSONArray warnings = new JSONArray(); issues.entrySet().stream().map(e -> new JSONObject().accumulate("line", e.getKey().line).accumulate("warning", e.getValue())) .forEach(warnings::add); warnings.write(res.getWriter()); }
private JSONObject getWidgetByName(JSONArray widgetsJson, final String widgetName) { for (int i=0; i<widgetsJson.size(); i++) { JSONObject widgetJson = widgetsJson.getJSONObject(i); if (widgetJson.getString("name").equals(widgetName)) { return widgetJson; } } return null; }
Jenkins jenkins = Jenkins.get(); JSONArray pluginCategories = JSONArray.fromObject(getPlatformPluginList().toString()); for (Iterator<?> categoryIterator = pluginCategories.iterator(); categoryIterator.hasNext();) { Object category = categoryIterator.next(); if (category instanceof JSONObject) { JSONObject cat = (JSONObject)category; JSONArray plugins = cat.getJSONArray("plugins"); nextPlugin: for (Iterator<?> pluginIterator = plugins.iterator(); pluginIterator.hasNext();) { Object pluginData = pluginIterator.next(); if (pluginData instanceof JSONObject) { JSONObject plugin = (JSONObject)pluginData; if (plugin.has("added")) { String sinceVersion = plugin.getString("added"); if (sinceVersion != null) { VersionNumber v = new VersionNumber(sinceVersion); String pluginName = plugin.getString("name"); if (null == jenkins.getPluginManager().getPlugin(pluginName)) { for (UpdateSite site : jenkins.getUpdateCenter().getSiteList()) { UpdateSite.Plugin sitePlug = site.getPlugin(pluginName); if (sitePlug != null if (plugins.isEmpty()) { categoryIterator.remove();
/** * @param str a JSON array representation of a list of {@link AuthorityURLInfo} objects * @return the list of parsed authrority URL from the argument JSON array * @throws IllegalArgumentException if {@code str} can't be parsed to a JSONArray */ public static List<AuthorityURLInfo> fromString(String str) throws IllegalArgumentException { try { final JSONArray array; array = JSONArray.fromObject(str); final int size = array.size(); List<AuthorityURLInfo> list = new ArrayList<AuthorityURLInfo>(size); JSONObject jsonAuth; for (int i = 0; i < size; i++) { jsonAuth = array.getJSONObject(i); AuthorityURL auth = new AuthorityURL(); auth.setName(jsonAuth.getString(NAME)); auth.setHref(jsonAuth.getString(HREF)); list.add(auth); } return list; } catch (JSONException e) { throw new IllegalArgumentException(e.getMessage(), e); } }