Java Code Examples for net.sf.json.JSONArray#size()

The following examples show how to use net.sf.json.JSONArray#size() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RecordPermissionsRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Iterates over the JSONArray of users or groups and adds an AllOf with a single Match to the provided AnyOf.
 *
 * @param array The JSONArray of users or groups to iterate over
 * @param attributeDesignator the AttributeDesignatorType to apply to the MatchType
 * @param anyOfArray the AnyOfType to add the AllOf statement to
 */
private void addUsersOrGroupsToAnyOf(JSONArray array, AttributeDesignatorType attributeDesignator,
                                     AnyOfType... anyOfArray) {
    for (int i = 0; i < array.size(); i++) {
        String value = array.optString(i);
        if (StringUtils.isEmpty(value)) {
            throw new IllegalArgumentException("Invalid JSON representation of a Policy."
                    + " User or group not set properly.");
        }
        AttributeValueType userAttrVal = createAttributeValue(XSD.STRING, value);

        MatchType userMatch = createMatch(XACML.STRING_EQUALS, attributeDesignator, userAttrVal);
        AllOfType userAllOf = new AllOfType();
        userAllOf.getMatch().add(userMatch);
        for (AnyOfType anyOf : anyOfArray) {
            anyOf.getAllOf().add(userAllOf);
        }
    }
}
 
Example 2
Source File: StateRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getStatesWithoutFiltersTest() {
    Response response = target().path("states").request().get();
    assertEquals(response.getStatus(), 200);
    verify(stateManager).getStates(anyString(), anyString(), anySetOf(Resource.class));
    try {
        String str = response.readEntity(String.class);
        JSONArray arr = JSONArray.fromObject(str);
        assertEquals(results.size(), arr.size());
        for (int i = 0; i < arr.size(); i++) {
            JSONObject object = arr.optJSONObject(i);
            assertNotNull(object);
            assertTrue(results.keySet().contains(vf.createIRI(object.get("id").toString())));
        }
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 3
Source File: ParallelsDesktopConnectorSlaveComputer.java    From jenkins-parallels with MIT License 6 votes vote down vote up
public boolean checkVmExists(String vmId)
{
	try
	{
		RunVmCallable command = new RunVmCallable("list", "-i", "--json");
		String callResult = forceGetChannel().call(command);
		JSONArray vms = (JSONArray)JSONSerializer.toJSON(callResult);
		for (int i = 0; i < vms.size(); i++)
		{
			JSONObject vmInfo = vms.getJSONObject(i);
			if (vmId.equals(vmInfo.getString("ID")) || vmId.equals(vmInfo.getString("Name")))
				return true;
		}
		return true;
	}
	catch (Exception ex)
	{
		LOGGER.log(Level.SEVERE, ex.toString());
	}
	return false;
}
 
Example 4
Source File: VoteDeleted.java    From gerrit-events with MIT License 6 votes vote down vote up
@Override
public void fromJson(JSONObject json) {
    super.fromJson(json);
    comment = getString(json, COMMENT);
    if (json.containsKey(REVIEWER)) {
        this.reviewer = new Account(json.getJSONObject(REVIEWER));
    }
    if (json.containsKey(REMOVER)) {
        this.remover = new Account(json.getJSONObject(REMOVER));
    }
    if (json.containsKey(APPROVALS)) {
        JSONArray eventApprovals = json.getJSONArray(APPROVALS);
        for (int i = 0; i < eventApprovals.size(); i++) {
            approvals.add(new Approval(eventApprovals.getJSONObject(i)));
        }
    }
}
 
Example 5
Source File: Awvs.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
public List<Target> targets(){
    JSONObject obj = targetsJSON();
    List <Target> list = new ArrayList<>();
    if (obj.containsKey("targets")){
        JSONArray scans = obj.getJSONArray("targets");
        for (int i = 0; i < scans.size(); i++) {
            JSONObject scan = scans.getJSONObject(i);
            try {
                Target s = this.toBean(scan.toString(), Target. class);
                list.add(s);
            } catch (IOException e) {
                continue;
            }
        }
    }
    return list;
}
 
Example 6
Source File: Config.java    From pdf-extract with GNU General Public License v3.0 6 votes vote down vote up
private List<NormalizeInfo> getNormalizeList(JSONArray jArray) {
	List<NormalizeInfo> list = new ArrayList<>();
	if (jArray != null) {
		for (int j = 0, jlen = jArray.size(); j < jlen; j++) {

			JSONArray jNormalize = (JSONArray) jArray.get(j);

			String left = jNormalize.getString(0);
			String right = jNormalize.getString(1);

			if (!common.IsEmpty(left) && right.length() > 0) {
				NormalizeInfo norm = new NormalizeInfo();
				norm.search = left;
				norm.replace = right;
				list.add(norm);
			}
		}
	}
	return list;
}
 
Example 7
Source File: GeoServerListWorkspacesCommand.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> computeResults(final OperationParams params) throws Exception {
  final Response getWorkspacesResponse = geoserverClient.getWorkspaces();

  final ArrayList<String> results = new ArrayList<>();
  if (getWorkspacesResponse.getStatus() == Status.OK.getStatusCode()) {
    results.add("\nList of GeoServer workspaces:");

    final JSONObject jsonResponse = JSONObject.fromObject(getWorkspacesResponse.getEntity());

    final JSONArray workspaces = jsonResponse.getJSONArray("workspaces");
    for (int i = 0; i < workspaces.size(); i++) {
      final String wsName = workspaces.getJSONObject(i).getString("name");
      results.add("  > " + wsName);
    }

    results.add("---\n");
    return results;
  }
  final String errorMessage =
      "Error getting GeoServer workspace list: "
          + getWorkspacesResponse.readEntity(String.class)
          + "\nGeoServer Response Code = "
          + getWorkspacesResponse.getStatus();
  return handleError(getWorkspacesResponse, errorMessage);
}
 
Example 8
Source File: ReadJSONStepExecution.java    From pipeline-utility-steps-plugin with MIT License 5 votes vote down vote up
private List<Object> transformToArrayList(JSONArray array) {
    List<Object> result = new ArrayList<>(array.size());
    for (Object arrayItem : array) {
        result.add(transformToJavaLangStructures(arrayItem));
    }
    return result;
}
 
Example 9
Source File: Differential.java    From phabricator-jenkins-plugin with MIT License 5 votes vote down vote up
/**
 * Get the list of changed files in the diff.
 *
 * @return the list of changed files in the diff.
 */
public Set<String> getChangedFiles() {
    Set<String> changedFiles = new HashSet<String>();
    JSONArray changes = rawJSON.getJSONArray("changes");
    for (int i = 0; i < changes.size(); i++) {
        JSONObject change = changes.getJSONObject(i);
        String file = (String) change.get("currentPath");
        if (file != null) {
            changedFiles.add(file);
        }
    }
    return changedFiles;
}
 
Example 10
Source File: JsonUtil.java    From zxl with Apache License 2.0 5 votes vote down vote up
public static <E extends Table> Table parse(String json, Class<E> clazz) throws Exception {
	JSONObject jsonObject = JSONObject.fromObject(json);
	E entity = clazz.newInstance();
	if (jsonObject.containsKey("id"))
		entity.setId(jsonObject.getString("id"));
	for (Field field : ReflectUtil.getAllFields(clazz)) {
		if (!HBaseUtil.isFamily(field)) {
			continue;
		}
		if (HBaseUtil.isBaseFamily(field)) {
			Family family = new Family();
			family.putJsonObject(jsonObject.getJSONObject(field.getName()));
			ReflectUtil.setFieldValue(entity, field, family);
		} else if (HBaseUtil.isArrayFamily(field)) {
			JSONArray familyArray = jsonObject.getJSONArray(field.getName());
			Class<?> genericClass = ReflectUtil.getParameterizedType(field);
			List<Object> list = new ArrayList<Object>();
			if (genericClass == String.class) {
				for (int i = 0; i < familyArray.size(); i++) {
					list.add(familyArray.getString(i));
				}
			} else if (Family.class.isAssignableFrom(genericClass)) {
				for (int i = 0; i < familyArray.size(); i++) {
					list.add(new Family(familyArray.getJSONObject(i)));
				}
			} else {
				LogUtil.warn(LOGGER, field.getName() + "����Family���ͣ�");
			}
		} else {
			LogUtil.warn(LOGGER, "������ݿ��ѯ���ʱ��������[" + field.getName() + "]");
		}
	}
	return entity;
}
 
Example 11
Source File: Change.java    From gerrit-events with MIT License 5 votes vote down vote up
@Override
public void fromJson(JSONObject json) {
    project = getString(json, PROJECT);
    branch = getString(json, BRANCH);
    id = getString(json, ID);
    number = getString(json, NUMBER);
    subject = getString(json, SUBJECT);
    createdOn = getDate(json, CREATED_ON);
    lastUpdated = getDate(json, LAST_UPDATED);
    if (json.containsKey(OWNER)) {
        owner = new Account(json.getJSONObject(OWNER));
    }
    if (json.containsKey(COMMENTS)) {
        comments = new ArrayList<Comment>();
        JSONArray eventApprovals = json.getJSONArray(COMMENTS);
        for (int i = 0; i < eventApprovals.size(); i++) {
            comments.add(new Comment(eventApprovals.getJSONObject(i)));
        }
    }
    if (json.containsKey(COMMIT_MESSAGE)) {
        commitMessage = getString(json, COMMIT_MESSAGE);
    }
    if (json.containsKey(TOPIC)) {
        String topicName = getString(json, TOPIC);
        if (StringUtils.isNotEmpty(topicName)) {
            topicObject = new Topic(topicName);
        }
    }

    url = getString(json, URL);
    status = GerritChangeStatus.fromString(getString(json, STATUS));
    wip = getBoolean(json, WIP, false);
    _private = getBoolean(json, PRIVATE, false);
}
 
Example 12
Source File: ContentReviewServiceTurnitinOC.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public ArrayList<Webhook> getWebhooks() throws Exception {
	ArrayList<Webhook> webhooks = new ArrayList<>();

	HashMap<String, Object> response = makeHttpCall("GET",
			getNormalizedServiceUrl() + "webhooks",
			BASE_HEADERS,
			null,
			null);

	// Get response:
	int responseCode = !response.containsKey(RESPONSE_CODE) ? 0 : (int) response.get(RESPONSE_CODE);
	String responseMessage = !response.containsKey(RESPONSE_MESSAGE) ? "" : (String) response.get(RESPONSE_MESSAGE);
	String responseBody = !response.containsKey(RESPONSE_BODY) ? "" : (String) response.get(RESPONSE_BODY);

	if(StringUtils.isNotEmpty(responseBody) 
			&& responseCode >= 200 
			&& responseCode < 300
			&& !"[]".equals(responseBody)) {
		// Loop through response via JSON, convert objects to Webhooks
		JSONArray webhookList = JSONArray.fromObject(responseBody);
		for (int i=0; i < webhookList.size(); i++) {
			JSONObject webhookJSON = webhookList.getJSONObject(i);
			if (webhookJSON.has("id") && webhookJSON.has("url")) {
				webhooks.add(new Webhook(webhookJSON.getString("id"), webhookJSON.getString("url")));
			}
		}
	}else {
		log.info("getWebhooks: " + responseMessage);
	}
	
	return webhooks;
}
 
Example 13
Source File: SQLMapInner.java    From TrackRay with GNU General Public License v3.0 5 votes vote down vote up
public String dataScan(){
    JSONObject json = toJSON(get(server + "scan/" + taskid + "/data").body());
    if (json.containsKey("data")){
        JSONArray data = json.getJSONArray("data");
        if(data.size()>0){
            this.result= data.toString();
            log.info("存在注入:"+ this.result);
        }
    }
    return result;
}
 
Example 14
Source File: BaiduFanyi.java    From squirrelAI with Apache License 2.0 5 votes vote down vote up
public static String getBaiduFanyi(String text) {

        int intMath = 0;
        String md5 = "";
        String returnData = "";
        try {
            intMath = (int) (Math.random() * 100);
            md5 = setMD5(appid + text + String.valueOf(intMath) + key);

            connection = Jsoup.connect("http://api.fanyi.baidu.com/api/trans/vip/translate");
            connection.header("Content-Type", "application/json");
            connection.header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            connection.data("q", text);
            connection.data("from", "auto");
            connection.data("to", "auto");
            connection.data("appid", appid);
            connection.data("salt", String.valueOf(intMath));
            connection.data("sign", md5);
            connection.ignoreContentType(true);
            connection.userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36");
            connection.timeout(5000);

            document = connection.post();
            String strDocJosn = document.text();

            JSONObject jsonObject = JSONObject.fromObject(strDocJosn);
            JSONArray jsonArray = jsonObject.getJSONArray("trans_result");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                returnData = jsonObject1.getString("dst");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnData;

    }
 
Example 15
Source File: Engine.java    From acunetix-plugin with MIT License 5 votes vote down vote up
public Boolean checkScanProfileExists(String profileId) throws IOException {
    JSONArray profiles = getScanningProfiles();
    for (int i = 0; i < profiles.size(); i++) {
        JSONObject item = profiles.getJSONObject(i);
        String profile_id = item.getString("profile_id");
        if (profile_id.equals(profileId)) {
            return true;
        }
    }
    return false;
}
 
Example 16
Source File: JwGetAutoReplyRuleAPI.java    From jeewx-api with Apache License 2.0 4 votes vote down vote up
/**
 * 获取自动回复规则
 * @param accessToken
 * @return
 */
public static AutoReplyInfoRule getAutoReplyInfoRule(String accessToken) throws WexinReqException{
	AutoReplyRuleGet arr = new AutoReplyRuleGet();
	arr.setAccess_token(accessToken);
	JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(arr);
	Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE);
	
	AutoReplyInfoRule autoReplyInfoRule = (AutoReplyInfoRule) JSONObject.toBean(result,new CustomJsonConfig(AutoReplyInfoRule.class, "keyword_autoreply_info"));
	JSONObject keywordAutoReplyInfoJsonObj = result.getJSONObject("keyword_autoreply_info");
	if(keywordAutoReplyInfoJsonObj!=null && !JSONUtils.isNull(keywordAutoReplyInfoJsonObj)){
		/**关键词自动回复的信息 */
		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);
					}
					keyWordAutoReplyInfo.setKeyword_list_info(listKeywordListInfo);
				}
				
				/**处理关键字回复信息 */
				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);
							}
							replyListInfo.setNews_info(listNewsInfo);
						}
						listReplyListInfo.add(replyListInfo);
					}
					keyWordAutoReplyInfo.setReply_list_info(listReplyListInfo);
				}
				
				listKeyWordAutoReplyInfo.add(keyWordAutoReplyInfo);
			}
			autoReplyInfoRule.setKeyword_autoreply_info(listKeyWordAutoReplyInfo);
		}
	}
	
	return autoReplyInfoRule;
}
 
Example 17
Source File: Http.java    From BotLibre with Eclipse Public License 1.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
public Vertex convertElement(Object json, Network network) {
	try {
		if (json == null) {
			return null;
		}
		Vertex object = null;
		if (json instanceof JSONObject) {
			object = network.createVertex();
			for (Iterator iterator = ((JSONObject)json).keys(); iterator.hasNext(); ) {
				String name = (String)iterator.next();
				Object value = ((JSONObject)json).get(name);
				if (value == null) {
					continue;
				}
				Primitive key = new Primitive(name);
				Vertex target = convertElement(value, network);
				object.addRelationship(key, target);
			}
		} else if (json instanceof JSONArray) {
			object = network.createInstance(Primitive.ARRAY);
			JSONArray array = (JSONArray)json;
			for (int index = 0; index < array.size(); index++) {
				Vertex element = convertElement(array.get(index), network);
				object.addRelationship(Primitive.ELEMENT, element, index);
			}
		} else if (json instanceof JSONNull) {
			object = network.createInstance(Primitive.NULL);
		} else if (json instanceof String) {
			object = network.createVertex(json);
		} else if (json instanceof Number) {
			object = network.createVertex(json);
		} else if (json instanceof Date) {
			object = network.createVertex(json);
		} else if (json instanceof Boolean) {
			object = network.createVertex(json);
		} else {
			log("Unknown JSON object", Level.INFO, json);
		}
		return object;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
Example 18
Source File: TestGoogleSearch.java    From albert with MIT License 4 votes vote down vote up
public static void main(String[] args) throws ClientProtocolException, IOException {
		StringBuffer sb = new StringBuffer(); 
		HttpClient client = ProxyUtil.getHttpClient();
		 HttpGet httpGet = new HttpGet(Constants.GOOGLE_SEARCH_URL+"哈哈"+"&start=1&num=10");
		 HttpResponse response = client.execute(httpGet);
		 
		 Header[] headers = response.getAllHeaders();
		 
		 if(200!=response.getStatusLine().getStatusCode()){
			  System.out.println("无法访问");
		 }
		 
		 HttpEntity entry = response.getEntity();
		 
		 if(entry != null)
		  {
		    InputStreamReader is = new InputStreamReader(entry.getContent());
		    BufferedReader br = new BufferedReader(is);
		    String str = null;
		    while((str = br.readLine()) != null)
		    {
		     sb.append(str.trim());
		    }
		    br.close();
		  }
		 
		 
		 
//		 System.out.println(sb.toString());
		  JSONArray jsonArray = null;
		  JSONObject jsonObject=null;
		  jsonArray = JSONObject.fromObject(sb.toString()).getJSONArray("items");
		  
		  GoogleSearchResult googleSearchResult =new GoogleSearchResult();
		  
		  for(int i=0,length=jsonArray.size();i<length;i++){
			  jsonObject = jsonArray.getJSONObject(i);
			  googleSearchResult.setHtmlTitle(jsonObject.getString("htmlTitle"));
			  googleSearchResult.setLink(jsonObject.getString("link"));
			  googleSearchResult.setLink(jsonObject.getString("htmlSnippet"));
			  if(jsonObject.containsKey("pagemap")&&jsonObject.getJSONObject("pagemap").containsKey("cse_thumbnail")){
				  googleSearchResult.setSrc(jsonObject.getJSONObject("pagemap").getJSONArray("cse_thumbnail").getJSONObject(0).getString("src"));
				  googleSearchResult.setWidth(jsonObject.getJSONObject("pagemap").getJSONArray("cse_thumbnail").getJSONObject(0).getString("width"));
				  googleSearchResult.setHeight(jsonObject.getJSONObject("pagemap").getJSONArray("cse_thumbnail").getJSONObject(0).getString("height"));
			  }
			  System.out.println(googleSearchResult.toString());
		  }
		 
	}
 
Example 19
Source File: WorkflowServiceImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected ResultTO submitForApproval(final String site, String submittedBy, final String request,
                                     final boolean delete) throws ServiceLayerException {
    RequestContext requestContext = RequestContextBuilder.buildSubmitContext(site, submittedBy);
    ResultTO result = new ResultTO();
    try {
        SimpleDateFormat format = new SimpleDateFormat(StudioConstants.DATE_PATTERN_WORKFLOW_WITH_TZ);
        JSONObject requestObject = JSONObject.fromObject(request);
        JSONArray items = requestObject.getJSONArray(JSON_KEY_ITEMS);
        int length = items.size();
        if (length > 0) {
            for (int index = 0; index < length; index++) {
                objectStateService.setSystemProcessing(site, items.optString(index), true);
            }
        }
        boolean isNow = (requestObject.containsKey(JSON_KEY_SCHEDULE)) ?
                StringUtils.equalsIgnoreCase(requestObject.getString(JSON_KEY_SCHEDULE), JSON_KEY_IS_NOW) : false;
        ZonedDateTime scheduledDate = null;
        if (!isNow) {
            scheduledDate = (requestObject.containsKey(JSON_KEY_SCHEDULED_DATE)) ?
                    getScheduledDate(site, format, requestObject.getString(JSON_KEY_SCHEDULED_DATE)) : null;
        }
        boolean sendEmail = (requestObject.containsKey(JSON_KEY_SEND_EMAIL)) ?
                requestObject.getBoolean(JSON_KEY_SEND_EMAIL) : false;

        String environment = (requestObject != null && requestObject.containsKey(JSON_KEY_ENVIRONMENT))
                ? requestObject.getString(JSON_KEY_ENVIRONMENT) : null;

        String submissionComment = (requestObject != null && requestObject.containsKey(JSON_KEY_SUBMISSION_COMMENT))
                ? requestObject.getString(JSON_KEY_SUBMISSION_COMMENT) : null;
        // TODO: check scheduled date to make sure it is not null when isNow
        // = true and also it is not past


        String schDate = null;
        if (requestObject.containsKey(JSON_KEY_SCHEDULED_DATE)) {
            schDate = requestObject.getString(JSON_KEY_SCHEDULED_DATE);
        }
        if (length > 0) {
            List<DmDependencyTO> submittedItems = new ArrayList<DmDependencyTO>();
            for (int index = 0; index < length; index++) {
                String stringItem = items.optString(index);
                DmDependencyTO submittedItem = getSubmittedItem(site, stringItem, format, schDate,null);
                String user = submittedBy;
                submittedItems.add(submittedItem);
                if (delete) {
                    submittedItem.setSubmittedForDeletion(true);
                }
            }
            submittedItems.addAll(addDependenciesForSubmitForApproval(site, submittedItems, format, schDate));
            List<String> submittedPaths = new ArrayList<String>();
            for (DmDependencyTO goLiveItem : submittedItems) {
                submittedPaths.add(goLiveItem.getUri());
                objectStateService.setSystemProcessing(site, goLiveItem.getUri(), true);
                DependencyRules rule = new DependencyRules(site);
                rule.setObjectStateService(objectStateService);
                rule.setContentService(contentService);
                Set<DmDependencyTO> depSet = rule.applySubmitRule(goLiveItem);
                for (DmDependencyTO dep : depSet) {
                    submittedPaths.add(dep.getUri());
                    objectStateService.setSystemProcessing(site, dep.getUri(), true);
                }
            }
            List<DmError> errors = submitToGoLive(submittedItems, scheduledDate, sendEmail, delete, requestContext,
                    submissionComment, environment);
            SiteFeed siteFeed = siteService.getSite(site);
            AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
            auditLog.setOperation(OPERATION_REQUEST_PUBLISH);
            auditLog.setActorId(submittedBy);
            auditLog.setSiteId(siteFeed.getId());
            auditLog.setPrimaryTargetId(site);
            auditLog.setPrimaryTargetType(TARGET_TYPE_CONTENT_ITEM);
            auditLog.setPrimaryTargetValue(site);
            auditServiceInternal.insertAuditLog(auditLog);
            result.setSuccess(true);
            result.setStatus(200);
            result.setMessage(notificationService.getNotificationMessage(site, NotificationMessageType
                        .CompleteMessages,COMPLETE_SUBMIT_TO_GO_LIVE_MSG,Locale.ENGLISH));
            for (String relativePath : submittedPaths) {
                objectStateService.setSystemProcessing(site, relativePath, false);
            }
        }
    } catch (Exception e) {
        result.setSuccess(false);
        result.setMessage(e.getMessage());
        logger.error("Error while submitting content for approval.", e);
    }
    return result;

}
 
Example 20
Source File: ComProfileFieldDaoImpl.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public ComProfileField mapRow(ResultSet resultSet, int row) throws SQLException {
	ComProfileField readProfileField = new ComProfileFieldImpl();

	readProfileField.setCompanyID(resultSet.getInt(FIELD_COMPANY_ID));
	readProfileField.setShortname(resultSet.getString(FIELD_SHORTNAME));
	readProfileField.setDescription(resultSet.getString(FIELD_DESCRIPTION));
	readProfileField.setColumn(resultSet.getString(FIELD_COLUMN_NAME));
	readProfileField.setDefaultValue(resultSet.getString(FIELD_DEFAULT_VALUE));
	readProfileField.setModeEdit(resultSet.getInt(FIELD_MODE_EDIT));
	readProfileField.setModeInsert(resultSet.getInt(FIELD_MODE_INSERT));
	readProfileField.setCreationDate(resultSet.getTimestamp(FIELD_CREATION_DATE));
	readProfileField.setChangeDate(resultSet.getTimestamp(FIELD_CHANGE_DATE));
	readProfileField.setHistorize(resultSet.getBoolean(FIELD_HISTORIZE));

	Object sortObject = resultSet.getObject(FIELD_SORT);
	if (sortObject != null) {
		readProfileField.setSort(((Number)sortObject).intValue());
	} else {
		readProfileField.setSort(MAX_SORT_INDEX);
	}

	Object lineObject = resultSet.getObject(FIELD_LINE);
	if (lineObject != null) {
		readProfileField.setLine(((Number)lineObject).intValue());
	} else {
		readProfileField.setLine(0);
	}

	Object interestObject = resultSet.getObject(FIELD_ISINTEREST);
	if (interestObject != null) {
		readProfileField.setInterest(((Number)interestObject).intValue());
	} else {
		readProfileField.setInterest(0);
	}

	String allowedValuesJson = resultSet.getString(FIELD_ALLOWED_VALUES);
	String[] allowedValues = null;
	if (allowedValuesJson != null) {
		try {
			JSONArray array = JSONArray.fromObject(allowedValuesJson);
			allowedValues = new String[array.size()];
			for (int i = 0; i < array.size(); i++) {
				allowedValues[i] = array.getString(i);
			}
		} catch (JSONException e) {
			logger.error("Error occurred while parsing JSON: " + e.getMessage(), e);
		}
	}
	readProfileField.setAllowedValues(allowedValues);

	return readProfileField;
}