@Override public boolean configure(StaplerRequest req, JSONObject json) throws hudson.model.Descriptor.FormException { // for compatibility reasons, the actual value is stored in Jenkins Jenkins j = Jenkins.get(); final JSONObject optJSONObject = json.optJSONObject("useProjectNamingStrategy"); if (optJSONObject != null) { final JSONObject strategyObject = optJSONObject.getJSONObject("namingStrategy"); final String className = strategyObject.getString("$class"); try { Class clazz = Class.forName(className, true, j.getPluginManager().uberClassLoader); final ProjectNamingStrategy strategy = (ProjectNamingStrategy) req.bindJSON(clazz, strategyObject); j.setProjectNamingStrategy(strategy); } catch (ClassNotFoundException e) { throw new FormException(e, "namingStrategy"); } } if (j.getProjectNamingStrategy() == null) { j.setProjectNamingStrategy(DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY); } return true; } }
/** * 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()); } }
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); j.setSlaveAgentPort(new ServerTcpPort(json.getJSONObject("slaveAgentPort")).getPort()); } catch (IOException e) { throw new hudson.model.Descriptor.FormException(e, "slaveAgentPortType"); if (json.has("agentProtocol")) { Object protocols = json.get("agentProtocol"); if (protocols instanceof JSONArray) { for (int i = 0; i < ((JSONArray) protocols).size(); i++) { agentProtocols.add(((JSONArray) protocols).getString(i));
/** * Create a response containing the supplied "data". * @param data The data. */ JSONObjectResponse(@Nonnull Map<?,?> data) { this(); this.jsonObject.put("data", JSONObject.fromObject(data)); }
private boolean needToAddToCurrentView(StaplerRequest req) throws ServletException { String json = req.getParameter("json"); if (json != null && json.length() > 0) { // Submitted via UI JSONObject form = req.getSubmittedForm(); return form.has("addToCurrentView") && form.getBoolean("addToCurrentView"); } else { // Submitted via API return true; } }
@Test public void testPost() throws Exception { String xml = "<wfs:GetFeature " + "service=\"WFS\" " + "outputFormat=\"" + JSONType.json + "\" " + "version=\"1.0.0\" " + "xmlns:cdf=\"http://www.opengis.net/cite/data\" " + "xmlns:ogc=\"http://www.opengis.net/ogc\" " + "xmlns:wfs=\"http://www.opengis.net/wfs\" " + "> " + "<wfs:Query typeName=\"sf:PrimitiveGeoFeature\"> " + "</wfs:Query> " + "</wfs:GetFeature>"; String out = postAsServletResponse("wfs", xml).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")); }
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 rsp.sendRedirect(".");
/** * Accepts the update to the node configuration. */ @RequirePOST public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(CONFIGURE); String proposedName = Util.fixEmptyAndTrim(req.getSubmittedForm().getString("name")); Jenkins.checkGoodName(proposedName); Node node = getNode(); if (node == null) { throw new ServletException("No such node " + nodeName); } if ((!proposedName.equals(nodeName)) && Jenkins.getActiveInstance().getNode(proposedName) != null) { throw new FormException(Messages.ComputerSet_SlaveAlreadyExists(proposedName), "name"); } String nExecutors = req.getSubmittedForm().getString("numExecutors"); if (StringUtils.isBlank(nExecutors) || Integer.parseInt(nExecutors)<=0) { throw new FormException(Messages.Slave_InvalidConfig_Executors(nodeName), "numExecutors"); } Node result = node.reconfigure(req, req.getSubmittedForm()); Jenkins.getInstance().getNodesObject().replaceNode(this.getNode(), result); // take the user back to the agent top page. rsp.sendRedirect2("../" + result.getNodeName() + '/'); }
makeDisabled(json.optBoolean("disable")); jdk = json.optString("jdk", null); if(json.optBoolean("hasCustomQuietPeriod", json.has("quiet_period"))) { quietPeriod = json.optInt("quiet_period"); } else { quietPeriod = null; if(json.optBoolean("hasCustomScmCheckoutRetryCount", json.has("scmCheckoutRetryCount"))) { scmCheckoutRetryCount = json.optInt("scmCheckoutRetryCount"); } else { scmCheckoutRetryCount = null; blockBuildWhenDownstreamBuilding = json.optBoolean("blockBuildWhenDownstreamBuilding"); blockBuildWhenUpstreamBuilding = json.optBoolean("blockBuildWhenUpstreamBuilding"); customWorkspace = Util.fixEmptyAndTrim(req.getParameter("customWorkspace.directory")); } else if(json.optBoolean("hasCustomWorkspace", json.has("customWorkspace"))) { customWorkspace = Util.fixEmptyAndTrim(json.optString("customWorkspace")); } else { customWorkspace = null; if (json.has("scmCheckoutStrategy")) scmCheckoutStrategy = req.bindJSON(SCMCheckoutStrategy.class, json.getJSONObject("scmCheckoutStrategy")); else scmCheckoutStrategy = null;
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("enabled", plugin.isEnabled()); pluginInfo.put("bundled", plugin.isBundled); pluginInfo.put("deleted", plugin.isDeleted()); pluginInfo.put("downgradable", plugin.isDowngradable()); pluginInfo.put("website", plugin.getUrl()); List<Dependency> dependencies = plugin.getDependencies(); if (dependencies != null && !dependencies.isEmpty()) { pluginInfo.put("dependencies", dependencyMap); } else { pluginInfo.put("dependencies", Collections.emptyMap()); for (UpdateSite site : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) { for (UpdateSite.Plugin plugin: site.getAvailables()) { JSONObject pluginInfo = allPlugins.get(plugin.name); if(pluginInfo == null) { pluginInfo = new JSONObject(); pluginInfo.put("installed", false); pluginInfo.put("name", plugin.name);
@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()); }
/** * Really creates a new agent. */ @RequirePOST public synchronized void doDoCreateItem( StaplerRequest req, StaplerResponse rsp, @QueryParameter String name, @QueryParameter String type ) throws IOException, ServletException, FormException { final Jenkins app = Jenkins.getInstance(); app.checkPermission(Computer.CREATE); String fixedName = Util.fixEmptyAndTrim(name); checkName(fixedName); JSONObject formData = req.getSubmittedForm(); formData.put("name", fixedName); // TODO type is probably NodeDescriptor.id but confirm Node result = NodeDescriptor.all().find(type).newInstance(req, formData); app.addNode(result); // take the user back to the agent list top page rsp.sendRedirect2("."); }
/** * 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; }
/** * Accepts submission from the configuration page. */ @RequirePOST public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { JSONObject src = req.getSubmittedForm(); String newName = src.getString("name"), redirect = "."; XmlFile oldFile = null; if(!name.equals(newName)) { Jenkins.checkGoodName(newName); oldFile = getConfigFile(); // rename getParent().logRecorders.remove(name); this.name = newName; getParent().logRecorders.put(name,this); redirect = "../" + Util.rawEncode(newName) + '/'; } List<Target> newTargets = req.bindJSONToList(Target.class, src.get("targets")); for (Target t : newTargets) t.enable(); targets.replaceBy(newTargets); save(); if (oldFile!=null) oldFile.delete(); rsp.sendRedirect2(redirect); }
/** * {@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; }
@SuppressWarnings("unused") @RequirePOST public HttpResponse doStepsToJson(StaplerRequest req) { Jenkins.getInstance().checkPermission(Jenkins.READ); JSONObject result = new JSONObject(); String groovyAsString = req.getParameter("jenkinsfile"); if (!StringUtils.isEmpty(groovyAsString)) { try { List<ModelASTStep> steps = Converter.scriptToPlainSteps(groovyAsString); JSONArray array = new JSONArray(); for (ModelASTStep step : steps) { array.add(step.toJSON()); } result.accumulate("result", "success"); result.accumulate("json", array); } catch (Exception e) { reportFailure(result, e); } } else { reportFailure(result, "No content found for 'jenkinsfile' parameter"); } return HttpResponses.okJSON(result); }
@RequirePOST public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, ServletException { try { Jenkins.getInstance().checkPermission(UPLOAD_PLUGINS); String fileName = Util.getFileName(fileItem.getName()); if("".equals(fileName)){ return new HttpRedirect("advanced"); JSONArray dependencies = new JSONArray(); try { Manifest m = new JarFile(t).getManifest(); dependencies.add(new JSONObject() .element("name", attrs[0]) .element("version", attrs[1]) .element("optional", p.contains("resolution:=optional"))); JSONObject cfg = new JSONObject(). element("name", baseName). element("version", "0"). // unused but mandatory element("url", t.toURI().toString()). element("dependencies", dependencies); new UpdateSite(UpdateCenter.ID_UPLOAD, null).new Plugin(UpdateCenter.ID_UPLOAD, cfg).deploy(true); return new HttpRedirect("../updateCenter");
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException { // collapse the structure to remain backward compatible with the JSON structure before 1. String name = d.getJsonSafeClassName(); JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object. json.putAll(js); return d.configure(req, js); }