/** * Construct an object from parameters input by a user. * * <p>Not using {@link DataBoundConstructor}, but using {@link * Descriptor#newInstance(StaplerRequest, JSONObject)}. * * @param req * @param formData * @param fieldName used for exception information. * @return * @throws hudson.model.Descriptor.FormException */ private BuildStep bindJSONWithDescriptor( StaplerRequest req, JSONObject formData, String fieldName) throws hudson.model.Descriptor.FormException { if (formData == null || formData.isNullObject()) { return null; } String clazzName = formData.optString("$class", null); if (clazzName == null) { // Fall back on the legacy stapler-class attribute. clazzName = formData.optString("stapler-class", null); } if (clazzName == null) { throw new FormException("No $class or stapler-class is specified", fieldName); } try { @SuppressWarnings("unchecked") Class<? extends Describable<?>> clazz = (Class<? extends Describable<?>>) Jenkins.getInstance().getPluginManager().uberClassLoader.loadClass(clazzName); Descriptor<?> d = Jenkins.getInstance().getDescriptorOrDie(clazz); return (BuildStep) d.newInstance(req, formData); } catch (ClassNotFoundException e) { throw new FormException( String.format("Failed to instantiate: class not found %s", clazzName), e, fieldName); } }
@Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { deviceApiUrl = json.optString("deviceApiUrl"); androidHome = json.optString("androidSdkHome"); save(); return true; }
public static ChatUserBoss fromJson(JSONObject jsonObject) { if (jsonObject != null) { ChatUserBoss chatUserBoss = new ChatUserBoss(); chatUserBoss.setUid(jsonObject.optLong(JSON_PROPERTIES_UID)); chatUserBoss.setCompanyName(jsonObject.optString(JSON_PROPERTIES_COMPANY_NAME)); chatUserBoss.setAddress(jsonObject.optString(JSON_PROPERTIES_ADDRESS)); chatUserBoss.setApproveStatus(jsonObject.optInt(JSON_PROPERTIES_APPROVE_STATUS)); chatUserBoss.setJobTitle(jsonObject.optString(JSON_PROPERTIES_JOB_TITLE)); return chatUserBoss; } return null; }
@Override public BuildWrapper newInstance(StaplerRequest req, JSONObject formData) throws FormException { String deviceApiUrl = null; String tag = null; deviceApiUrl = formData.optString("deviceApiUrl"); if (Strings.isNullOrEmpty(deviceApiUrl)) { deviceApiUrl = this.deviceApiUrl; } tag = formData.optString("tag"); return new AndroidRemote(deviceApiUrl, tag); }
ImportTransform transform(JSONObject json) throws IOException { ImportTransform transform; String type = json.getString("type"); if ("DateFormatTransform".equalsIgnoreCase(type)) { transform = new DateFormatTransform(json.getString("field"), json.optString("format", null)); } else if ("IntegerFieldToDateTransform".equalsIgnoreCase(type)) { transform = new IntegerFieldToDateTransform(json.getString("field")); } else if ("CreateIndexTransform".equalsIgnoreCase(type)) { transform = new CreateIndexTransform(json.getString("field")); } else if ("AttributeRemapTransform".equalsIgnoreCase(type)) { Class clazz; try { clazz = Class.forName(json.getString("target")); } catch (ClassNotFoundException cnfe) { throw new RuntimeException("unable to locate target class " + json.getString("target")); } transform = new AttributeRemapTransform(json.getString("field"), clazz); } else if ("AttributesToPointGeometryTransform".equalsIgnoreCase(type)) { String latField = json.getString("latField"); String lngField = json.getString("lngField"); transform = new AttributesToPointGeometryTransform(latField, lngField); } else if ("ReprojectTransform".equalsIgnoreCase(type)) { CoordinateReferenceSystem source = json.has("source") ? crs(json.getString("source")) : null; CoordinateReferenceSystem target = json.has("target") ? crs(json.getString("target")) : null; try { transform = new ReprojectTransform(source, target); } catch (Exception e) { throw new RuntimeException("Error parsing reproject transform", e); } } else { throw new RuntimeException("parsing of " + type + " not implemented"); } return transform; }
/** Accepts submission from the configuration page. */ @RequirePOST public synchronized void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { checkPermission(CONFIGURE); description = req.getParameter("description"); keepDependencies = req.getParameter("keepDependencies") != null; try { JSONObject json = req.getSubmittedForm(); setDisplayName(json.optString("displayNameOrNull")); if (req.getParameter("logrotate") != null) logRotator = LogRotator.DESCRIPTOR.newInstance(req, json.getJSONObject("logrotate")); else logRotator = null; DescribableList<JobProperty<?>, JobPropertyDescriptor> t = new DescribableList<JobProperty<?>, JobPropertyDescriptor>(NOOP, getAllProperties()); t.rebuild( req, json.optJSONObject("properties"), JobPropertyDescriptor.getPropertyDescriptors(Job.this.getClass())); properties.clear(); for (JobProperty p : t) { p.setOwner(this); properties.add(p); } submit(req, rsp); save(); ItemListener.fireOnUpdated(this); String newName = req.getParameter("name"); final ProjectNamingStrategy namingStrategy = Jenkins.getInstance().getProjectNamingStrategy(); if (newName != null && !newName.equals(name)) { // check this error early to avoid HTTP response splitting. Jenkins.checkGoodName(newName); namingStrategy.checkName(newName); rsp.sendRedirect("rename?newName=" + URLEncoder.encode(newName, "UTF-8")); } else { if (namingStrategy.isForceExistingJobs()) { namingStrategy.checkName(name); } FormApply.success(".").generateResponse(req, rsp, null); } } catch (JSONException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println("Failed to parse form data. Please report this problem as a bug"); pw.println("JSON=" + req.getSubmittedForm()); pw.println(); e.printStackTrace(pw); rsp.setStatus(SC_BAD_REQUEST); sendError(sw.toString(), req, rsp, true); } }
@Override public boolean configure(StaplerRequest req, JSONObject formData) { super.configure(req, formData); if (formData.containsKey("triggerScript")) { this.triggerScript = formData.optString("triggerScript", ""); } return true; }
@Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { String t = json.optString("pollingThreadCount", null); if (t == null || t.length() == 0) setPollingThreadCount(0); else setPollingThreadCount(Integer.parseInt(t)); // Save configuration save(); return true; }
/** * Take the GitLab Data and parse through it. { # "before": * "95790bf891e76fee5e1747ab589903a6a1f80f22", # "after": * "da1560886d4f094c3e6c9ef40349f7d38b5d27d7", # "ref": "refs/heads/master", # "commits": [ # { # * "id": "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327", # "message": "Update Catalan translation to * e38cb41.", # "timestamp": "2011-12-12T14:27:31+02:00", # "url": * "http://localhost/diaspora/commits/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327", # "author": { # * "name": "Jordi Mallach", # "email": "*****@*****.**", # } # }, .... more commits # ] # } * * @param data */ private void generateBuild(String data, Job project, StaplerRequest req, StaplerResponse rsp) { JSONObject json = JSONObject.fromObject(data); LOGGER.log(Level.FINE, "data: {0}", json.toString(4)); String objectType = json.optString("object_kind"); if (objectType != null && objectType.equals("merge_request")) { this.generateMergeRequestBuild(data, project, req, rsp); } else { this.generatePushBuild(data, project, req, rsp); } }
public NameValuePair[] addSigParamTpHttpRequest(String sigInfoJson) { JSONObject sigObj = new JSONObject(sigInfoJson); Iterator<String> keys = sigObj.keys(); NameValuePair[] nvps = new NameValuePair[sigObj.length()]; int i = 0; while (keys.hasNext()) { String key = keys.next(); nvps[i] = new NameValuePair(key, sigObj.optString(key, "")); i++; } return nvps; }
/** * Obtain value from a key in formdata. * * @param formData JSONObject. * @param key key to extract value for. * @return value. */ private Integer getValueFromFormData(JSONObject formData, String key) { if (formData.has(key)) { String testData = formData.optString(key); if (testData == null || testData.equals("")) { return null; } else { try { return Integer.parseInt(testData); } catch (NumberFormatException nfe) { return null; } } } return null; }
public void startResponseReqBody() { ParameterParser parameter = getParameterParser(); String command = parameter.getParameter("command"); if (command != null) { doCommand(command, parameter); return; } JSONObject json = (JSONObject) parameter.getJsonObject(); if (json != null) { command = json.optString("command"); Object paramObj = json.opt("param"); doObjCommand(command, paramObj); return; } completeResponse("404"); }
public TimezoneMap getTimezoneMap(UpdateInfo updateInfo) throws Exception { OAuthConsumer consumer = setupConsumer(updateInfo.apiKey); String api_key = guestService.getApiKeyAttribute(updateInfo.apiKey, "bodymediaConsumerKey"); JSONArray timezoneMapJson = getUserTimezoneHistory(updateInfo, api_key, consumer); TimezoneMap ret = new TimezoneMap(); try { for (int i = 0; i < timezoneMapJson.size(); i++) { JSONObject jsonRecord = timezoneMapJson.getJSONObject(i); final String tzName = jsonRecord.getString("value"); final String startDateStr = jsonRecord.getString("startDate"); final String endDateStr = jsonRecord.optString("endDate"); DateTime startDate; DateTime endDate; DateTimeZone tz; tz = DateTimeZone.forID(tzName); startDate = tzmapFormatter.parseDateTime(startDateStr); if (endDateStr.equals("")) { // Last entry in table has no endDate, set it to be one day in the future endDate = new DateTime(tz).plusDays(1); } else { endDate = tzmapFormatter.parseDateTime(endDateStr); } ret.add(startDate.getMillis(), endDate.getMillis(), tz); } } catch (Throwable e) { StringBuilder sb = new StringBuilder( "module=updateQueue component=updater action=BodymediaUpdater.getTimezoneMap") .append(" message=\"exception while getting timezone map\" connector=") .append(updateInfo.apiKey.getConnector().toString()) .append(" guestId=") .append(updateInfo.apiKey.getGuestId()) .append(" stackTrace=<![CDATA[") .append(Utils.stackTrace(e)) .append("]]>"); ; logger.info(sb.toString()); } return ret; }
/* (non-Javadoc) * @see com.funambol.json.converter.Converter#fromJSON(java.lang.String) */ public JsonAuthResponse fromJSON(String jsonContent) { JSONObject jsonRoot = JSONObject.fromObject(jsonContent); JSONObject jsonData = jsonRoot.getJSONObject(JsonAuthResponseModel.DATA.getValue()); Logger.info("JsonAuthResponse fromJSON's data: " + jsonData.toString()); JsonAuthResponse jsonAuthResponse = new JsonAuthResponse(); Logger.info( "JsonAuthResponse fromJSON's sessionid: " + jsonData.getString(JsonAuthResponseModel.SESSIONID.getValue())); jsonAuthResponse.setSessionID(jsonData.getString(JsonAuthResponseModel.SESSIONID.getValue())); // this property will be used when the customer needs to // use the unique ID instead of the username that comes from the client; // this happens when the username from the client is a sort of alias String customerUserID = jsonData.optString(customerUserIdLabel); if (customerUserID != null) { jsonAuthResponse.setCustomerUserID(customerUserID); } return jsonAuthResponse; }
@Override public void setValues(JSONObject formData) { gerritHostName = formData.optString("gerritHostName", DEFAULT_GERRIT_HOSTNAME); gerritSshPort = formData.optInt("gerritSshPort", DEFAULT_GERRIT_SSH_PORT); gerritProxy = formData.optString("gerritProxy", DEFAULT_GERRIT_PROXY); gerritUserName = formData.optString("gerritUserName", DEFAULT_GERRIT_USERNAME); gerritEMail = formData.optString("gerritEMail", ""); notificationLevel = Notify.valueOf( formData.optString("notificationLevel", Config.DEFAULT_NOTIFICATION_LEVEL.toString())); String file = formData.optString("gerritAuthKeyFile", null); if (file != null) { gerritAuthKeyFile = new File(file); } else { gerritAuthKeyFile = DEFAULT_GERRIT_AUTH_KEY_FILE; } gerritAuthKeyFilePassword = Secret.fromString( formData.optString("gerritAuthKeyFilePassword", DEFAULT_GERRIT_AUTH_KEY_FILE_PASSWORD)); if (formData.has("buildCurrentPatchesOnly")) { JSONObject currentPatchesOnly = formData.getJSONObject("buildCurrentPatchesOnly"); buildCurrentPatchesOnly = BuildCancellationPolicy.createPolicyFromJSON(currentPatchesOnly); } else { buildCurrentPatchesOnly = new BuildCancellationPolicy(); } numberOfWorkerThreads = formData.optInt("numberOfReceivingWorkerThreads", DEFAULT_NR_OF_RECEIVING_WORKER_THREADS); if (numberOfWorkerThreads <= 0) { numberOfWorkerThreads = DEFAULT_NR_OF_RECEIVING_WORKER_THREADS; } numberOfSendingWorkerThreads = formData.optInt("numberOfSendingWorkerThreads", DEFAULT_NR_OF_SENDING_WORKER_THREADS); if (numberOfSendingWorkerThreads <= 0) { numberOfSendingWorkerThreads = DEFAULT_NR_OF_SENDING_WORKER_THREADS; } if (formData.isEmpty()) { gerritBuildStartedVerifiedValue = DEFAULT_GERRIT_BUILD_STARTED_VERIFIED_VALUE; gerritBuildSuccessfulVerifiedValue = DEFAULT_GERRIT_BUILD_SUCCESSFUL_VERIFIED_VALUE; gerritBuildFailedVerifiedValue = DEFAULT_GERRIT_BUILD_FAILURE_VERIFIED_VALUE; gerritBuildUnstableVerifiedValue = DEFAULT_GERRIT_BUILD_UNSTABLE_VERIFIED_VALUE; gerritBuildNotBuiltVerifiedValue = DEFAULT_GERRIT_BUILD_NOT_BUILT_VERIFIED_VALUE; gerritBuildStartedCodeReviewValue = DEFAULT_GERRIT_BUILD_STARTED_CODE_REVIEW_VALUE; gerritBuildSuccessfulCodeReviewValue = DEFAULT_GERRIT_BUILD_SUCCESSFUL_CODE_REVIEW_VALUE; gerritBuildFailedCodeReviewValue = DEFAULT_GERRIT_BUILD_FAILURE_CODE_REVIEW_VALUE; gerritBuildUnstableCodeReviewValue = DEFAULT_GERRIT_BUILD_UNSTABLE_CODE_REVIEW_VALUE; gerritBuildNotBuiltCodeReviewValue = DEFAULT_GERRIT_BUILD_NOT_BUILT_CODE_REVIEW_VALUE; } else { gerritBuildStartedVerifiedValue = getValueFromFormData(formData, "gerritBuildStartedVerifiedValue"); gerritBuildSuccessfulVerifiedValue = getValueFromFormData(formData, "gerritBuildSuccessfulVerifiedValue"); gerritBuildFailedVerifiedValue = getValueFromFormData(formData, "gerritBuildFailedVerifiedValue"); gerritBuildUnstableVerifiedValue = getValueFromFormData(formData, "gerritBuildUnstableVerifiedValue"); gerritBuildNotBuiltVerifiedValue = getValueFromFormData(formData, "gerritBuildNotBuiltVerifiedValue"); gerritBuildStartedCodeReviewValue = getValueFromFormData(formData, "gerritBuildStartedCodeReviewValue"); gerritBuildSuccessfulCodeReviewValue = getValueFromFormData(formData, "gerritBuildSuccessfulCodeReviewValue"); gerritBuildFailedCodeReviewValue = getValueFromFormData(formData, "gerritBuildFailedCodeReviewValue"); gerritBuildUnstableCodeReviewValue = getValueFromFormData(formData, "gerritBuildUnstableCodeReviewValue"); gerritBuildNotBuiltCodeReviewValue = getValueFromFormData(formData, "gerritBuildNotBuiltCodeReviewValue"); } gerritVerifiedCmdBuildStarted = formData.optString( "gerritVerifiedCmdBuildStarted", "gerrit review <CHANGE>,<PATCHSET> --message 'Build Started <BUILDURL> <STARTED_STATS>' " + "--verified <VERIFIED> --code-review <CODE_REVIEW>"); gerritVerifiedCmdBuildFailed = formData.optString( "gerritVerifiedCmdBuildFailed", "gerrit review <CHANGE>,<PATCHSET> --message 'Build Failed <BUILDS_STATS>' " + "--verified <VERIFIED> --code-review <CODE_REVIEW>"); gerritVerifiedCmdBuildSuccessful = formData.optString( "gerritVerifiedCmdBuildSuccessful", "gerrit review <CHANGE>,<PATCHSET> --message 'Build Successful <BUILDS_STATS>' " + "--verified <VERIFIED> --code-review <CODE_REVIEW>"); gerritVerifiedCmdBuildUnstable = formData.optString( "gerritVerifiedCmdBuildUnstable", "gerrit review <CHANGE>,<PATCHSET> --message 'Build Unstable <BUILDS_STATS>' " + "--verified <VERIFIED> --code-review <CODE_REVIEW>"); gerritVerifiedCmdBuildNotBuilt = formData.optString( "gerritVerifiedCmdBuildNotBuilt", "gerrit review <CHANGE>,<PATCHSET> --message 'No Builds Executed <BUILDS_STATS>' " + "--verified <VERIFIED> --code-review <CODE_REVIEW>"); gerritFrontEndUrl = formData.optString("gerritFrontEndUrl", DEFAULT_GERRIT_HOSTNAME); enableManualTrigger = formData.optBoolean("enableManualTrigger", DEFAULT_ENABLE_MANUAL_TRIGGER); enablePluginMessages = formData.optBoolean("enablePluginMessages", DEFAULT_ENABLE_PLUGIN_MESSAGES); buildScheduleDelay = formData.optInt("buildScheduleDelay", DEFAULT_BUILD_SCHEDULE_DELAY); if (buildScheduleDelay < 0) { buildScheduleDelay = 0; } dynamicConfigRefreshInterval = formData.optInt("dynamicConfigRefreshInterval", DEFAULT_DYNAMIC_CONFIG_REFRESH_INTERVAL); projectListFetchDelay = formData.optInt("projectListFetchDelay", DEFAULT_PROJECT_LIST_FETCH_DELAY); projectListRefreshInterval = formData.optInt("projectListRefreshInterval", DEFAULT_PROJECT_LIST_REFRESH_INTERVAL); enableProjectAutoCompletion = formData.optBoolean("enableProjectAutoCompletion", DEFAULT_ENABLE_PROJECT_AUTO_COMPLETION); categories = new LinkedList<VerdictCategory>(); if (formData.has("verdictCategories")) { Object cat = formData.get("verdictCategories"); if (cat instanceof JSONArray) { for (Object jsonObject : (JSONArray) cat) { categories.add(VerdictCategory.createVerdictCategoryFromJSON((JSONObject) jsonObject)); } } else if (cat instanceof JSONObject) { categories.add(VerdictCategory.createVerdictCategoryFromJSON((JSONObject) cat)); } } watchdogTimeoutMinutes = formData.optInt("watchdogTimeoutMinutes", DEFAULT_GERRIT_WATCHDOG_TIMEOUT_MINUTES); watchTimeExceptionData = addWatchTimeExceptionData(formData); if (formData.has("useRestApi")) { useRestApi = true; JSONObject restApi = formData.getJSONObject("useRestApi"); gerritHttpUserName = restApi.optString("gerritHttpUserName", ""); gerritHttpPassword = Secret.fromString(restApi.optString("gerritHttpPassword", "")); restCodeReview = restApi.optBoolean("restCodeReview", true); restVerified = restApi.optBoolean("restVerified", true); } else { useRestApi = false; } replicationConfig = ReplicationConfig.createReplicationConfigFromJSON(formData); }