Java Code Examples for org.json.JSONObject.remove()

The following are Jave code examples for showing how to use remove() of the org.json.JSONObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: chromium-for-android-56-debug-video   File: CastMessageHandler.java   View Source Code Vote up 11 votes
/**
 * Remove 'null' fields from a JSONObject. This method calls itself recursively until all the
 * fields have been looked at.
 * TODO(mlamouri): move to some util class?
 */
private static void removeNullFields(Object object) throws JSONException {
    if (object instanceof JSONArray) {
        JSONArray array = (JSONArray) object;
        for (int i = 0; i < array.length(); ++i) removeNullFields(array.get(i));
    } else if (object instanceof JSONObject) {
        JSONObject json = (JSONObject) object;
        JSONArray names = json.names();
        if (names == null) return;
        for (int i = 0; i < names.length(); ++i) {
            String key = names.getString(i);
            if (json.isNull(key)) {
                json.remove(key);
            } else {
                removeNullFields(json.get(key));
            }
        }
    }
}
 
Example 2
Project: TinyURL   File: TinyURL.java   View Source Code Vote up 9 votes
public static JSONObject getURLDetails(String shortURL) {
	JSONObject json = new JSONObject();
	try {
		Record record = db.readKey(Constants.URLS, shortURL);
		json.append(Constants.SHORT_URL, shortURL);
		json.append(Constants.LONG_URL, record.getString(Constants.LONG_URL));
		json.append(Constants.HIT_COUNT, record.getLong(Constants.HIT_COUNT));
		Date date = new Date(record.getLong(Constants.TIMESTAMP));
		DateFormat format = new SimpleDateFormat( "MM/dd/yyyy HH:mm:ss");
		json.append(Constants.TIMESTAMP, format.format(date));
	} catch (Exception e) {
		e.printStackTrace();
		try {
			json.append(Constants.MESSAGE, Constants.INVALID_SHORT_URL);
			json.remove(Constants.SHORT_URL);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
	}
	return json;
}
 
Example 3
Project: solo-spring   File: ArticleQueryService.java   View Source Code Vote up 8 votes
/**
 * Removes unused properties of the specified article.
 * <p>
 * Remains the following properties:
 * <ul>
 * <li>{@link Article#ARTICLE_TITLE article title}</li>
 * <li>{@link Article#ARTICLE_PERMALINK article permalink}</li>
 * </ul>
 * </p>
 *
 * @param article
 *            the specified article
 * @see #removeUnusedProperties(java.util.List)
 */
public void removeUnusedProperties(final JSONObject article) {
	article.remove(Keys.OBJECT_ID);
	article.remove(Article.ARTICLE_AUTHOR_EMAIL);
	article.remove(Article.ARTICLE_ABSTRACT);
	article.remove(Article.ARTICLE_COMMENT_COUNT);
	article.remove(Article.ARTICLE_CONTENT);
	article.remove(Article.ARTICLE_CREATE_DATE);
	article.remove(Article.ARTICLE_TAGS_REF);
	article.remove(Article.ARTICLE_UPDATE_DATE);
	article.remove(Article.ARTICLE_VIEW_COUNT);
	article.remove(Article.ARTICLE_RANDOM_DOUBLE);
	article.remove(Article.ARTICLE_IS_PUBLISHED);
	article.remove(Article.ARTICLE_PUT_TOP);
	article.remove(Article.ARTICLE_HAD_BEEN_PUBLISHED);
}
 
Example 4
Project: letv   File: MobclickAgentJSInterface.java   View Source Code Vote up 8 votes
public boolean onJsPrompt(WebView webView, String str, String str2, String str3, JsPromptResult jsPromptResult) {
    if ("ekv".equals(str2)) {
        try {
            JSONObject jSONObject = new JSONObject(str3);
            Map hashMap = new HashMap();
            String str4 = (String) jSONObject.remove("id");
            int intValue = jSONObject.isNull(DownloadVideoTable.COLUMN_DURATION) ? 0 : ((Integer) jSONObject.remove(DownloadVideoTable.COLUMN_DURATION)).intValue();
            Iterator keys = jSONObject.keys();
            while (keys.hasNext()) {
                String str5 = (String) keys.next();
                hashMap.put(str5, jSONObject.getString(str5));
            }
            MobclickAgent.getAgent().a(this.b.a, str4, hashMap, (long) intValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (!NotificationCompat.CATEGORY_EVENT.equals(str2)) {
        return this.a.onJsPrompt(webView, str, str2, str3, jsPromptResult);
    } else {
        try {
            JSONObject jSONObject2 = new JSONObject(str3);
            String optString = jSONObject2.optString("label");
            if ("".equals(optString)) {
                optString = null;
            }
            MobclickAgent.getAgent().a(this.b.a, jSONObject2.getString("tag"), optString, (long) jSONObject2.optInt(DownloadVideoTable.COLUMN_DURATION), 1);
        } catch (Exception e2) {
        }
    }
    jsPromptResult.confirm();
    return true;
}
 
Example 5
Project: spring-data-documentdb   File: MappingDocumentDbConverter.java   View Source Code Vote up 7 votes
protected <R extends Object> R readInternal(final DocumentDbPersistentEntity<?> entity, Class<R> type,
                                            final Document sourceDocument) {
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    try {
        final DocumentDbPersistentProperty idProperty = entity.getIdProperty();
        final Object idValue = sourceDocument.getId();

        final JSONObject jsonObject = new JSONObject(sourceDocument.toJson());
        if (idProperty != null) {
            // Replace the key id to the actual id field name in domain
            jsonObject.remove("id");
            jsonObject.put(idProperty.getName(), idValue);
        }

        return objectMapper.readValue(jsonObject.toString(), type);
    } catch (IOException e) {
        throw  new IllegalStateException("Failed to read the source document " + sourceDocument.toJson()
                + "  to target type " + type, e);
    }
}
 
Example 6
Project: NewKakaoBot   File: FileManager.java   View Source Code Vote up 7 votes
public void removeData(String path, String key) {
    createFile(path);

    try {
        BufferedReader reader = new BufferedReader(new FileReader(new File(KAKAOBOT_HOME, path)));

        String line;
        StringBuilder result = new StringBuilder();
        while((line = reader.readLine()) != null) {
            result.append(line);
            result.append("\n");
        }

        JSONObject json = new JSONObject(result.toString() + "");
        json.remove(key);

        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(KAKAOBOT_HOME, path)));

        writer.write(json.toString());

        reader.close();
        writer.close();
    } catch(IOException err) {
        err.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example 7
Project: yacy_grid_mcp   File: SusiAction.java   View Source Code Vote up 6 votes
/**
 * An action is backed with a JSON data structure. That can be retrieved here.
 * @return the json structure of the action
 */
public JSONObject toJSONClone() {
    JSONObject j = new JSONObject(true);
    this.json.keySet().forEach(key -> j.put(key, this.json.get(key))); // make a clone
    if (j.has("expression")) {
        j.remove("phrases");
        j.remove("select");
    }
    return j;
}
 
Example 8
Project: Daejeon-People   File: MyPage.java   View Source Code Vote up 6 votes
@Override
public void handle(RoutingContext ctx) {
	String clientId = UserManager.getEncryptedIdFromSession(ctx);
	
	JSONObject response = UserManager.getUserInfo(clientId);
	response.remove("id");
	
	ctx.response().setStatusCode(200);
	ctx.response().end(response.toString());
	ctx.response().close();
}
 
Example 9
Project: mdw-demo   File: SlackRoutingStrategy.java   View Source Code Vote up 6 votes
public URL getDestination(Object request, Map<String,String> headers) {

        String requestUrl = headers.get(Listener.METAINFO_REQUEST_URL);
        if (StringHelper.isEmpty(requestUrl) || !requestUrl.contains("com/centurylink/mdw/slack"))
            return null;

        try {
            String callbackId = null;
            JSONObject message = new JSONObject(request.toString());

            if (requestUrl.endsWith("event")) {
                SlackEvent event = new SlackEvent(message);
                callbackId = event.getCallbackId();
            }
            else {
                SlackRequest slackReq = new SlackRequest(message);
                callbackId = slackReq.getCallbackId();
            }

            if (callbackId == null) {
                logger.debug("Received message for Slack routing, but missing callback_id");
                return null;
            }
            else {
                String[] array = callbackId.split("://");
                if (array.length < 2 || array[1].indexOf("/") < 0) {
                    logger.debug("Received message for Slack routing, but malformed callback_id");
                    return null;
                }
                String instance = array[1].substring(0, array[1].indexOf("/"));
                message.remove("token");
                request = message.toString();
                return buildURL(headers, instance);
            }
        }
        catch (Throwable e) {
            logger.exception(null, "Received Slack message for routing, but could not parse out destination", e);
        }
        return null;
    }
 
Example 10
Project: logistimo-web-service   File: CRConfigMigrator.java   View Source Code Vote up 6 votes
/**
 * Update configurations for a list of keys
 *
 * @param keys - list of config key to migrate
 */
public static boolean update(List<String> keys) {
  try {
    Map<String, String> conf = readConfig(keys);
    if (conf == null) {
      return false;
    }
    List<String> confSystem = new ArrayList<>(0);
    //process
    for (String domainId : conf.keySet()) {
      xLog.info("Parsing config for domain {0}", domainId);
      JSONObject config = new JSONObject(conf.get(domainId));
      JSONObject inventory = (JSONObject) config.get("invntry");
      JSONObject optmz = (JSONObject) config.get("optmz");
      String compute = (String) optmz.get("compute");
      if (inventory.has("cr") || inventory.has("dispcr")) {
        xLog.info("New configuration already set for: {0}", domainId);
        confSystem.add(domainId);
        continue;
      }
      if (optmz.has("compute-crfreqs")) {
        optmz.remove("compute-crfreqs");
      }
      if (inventory.has("manualcr")) {
        String manualcr = (String) inventory.get("manualcr");
        inventory.put("cr", "0");
        inventory.put("manualcrfreq", manualcr);
        inventory.put("dispcr", true);
        inventory.put("dcrfreq", manualcr);
        optmz.put("compute", "-1");
        inventory.remove("manualcr");
        xLog.info("Configuration set for manualcr: {0}" + domainId);
      } else if ("0".equals(compute)) {
        inventory.put("cr", "1");
        inventory.put("dispcr", false);
        optmz.put("compute", "-1");
        xLog.info("Configuration set for Automatic: {0}" + domainId);
      } else if ("100".equals(compute) || "200".equals(compute)) {
        inventory.put("cr", "1");
        inventory.put("dispcr", false);
        xLog.info("Configuration set for Demand forecast/OOQ: {0}" + domainId);
      } else if ("-1".equals(compute)) {
        inventory.put("cr", "-1");
        inventory.put("dispcr", false);
        xLog.info("Configuration set for forecasting as NONE: {0}" + domainId);
      }
      inventory.put("showpr", false);
      config.put("invntry", inventory);
      config.put("optmz", optmz);
      conf.put(domainId, String.valueOf(config));
    }
    //update
    ps = connection.prepareStatement(CONFIG_UPDATE_QUERY);
    for (String confKeys : conf.keySet()) {
      if (!confSystem.contains(confKeys)) {
        ps.setString(1, conf.get(confKeys));
        ps.setString(2, confKeys);
        ps.addBatch();
      }
    }
    int[] count = ps.executeBatch();
    xLog.info("{0} domains updated out of {1}", count.length, conf.size());
  } catch (Exception e) {
    xLog.warn("Error in updating configuration: " + e);
    return false;
  } finally {
    if (ps != null) {
      try {
        ps.close();
      } catch (SQLException ignored) {
        xLog.warn("Exception while closing prepared statement", ignored);
      }
    }
  }
  return true;
}
 
Example 11
Project: logistimo-web-service   File: NotificationBuilder.java   View Source Code Vote up 6 votes
private String buildJson(JSONObject jsonObject, String eventConfigJson, Boolean action)
    throws ServiceException {
  if (jsonObject == null) {
    return "";
  }
  try {
    JSONObject eventJSON = new JSONObject(eventConfigJson);
    Iterator<String> iteratorNew = jsonObject.keys();
    Iterator<String> iteratorConfig = eventJSON.keys();
    while (iteratorNew.hasNext()) {
      String key = iteratorNew.next();
      JSONArray obj = null;
      while (iteratorConfig.hasNext()) {
        if (key.equalsIgnoreCase(iteratorConfig.next())) {
          obj = eventJSON.getJSONArray(key);
          break;
        }
      }
      if (obj != null && obj.length() > 0) {
        obj = buildJSONArray(obj, jsonObject, key, action);
        eventJSON.remove(key);
        eventJSON.put(key, obj);
      } else {
        eventJSON.put(key, jsonObject.get(key));
      }
    }
    return eventJSON.toString();
  } catch (JSONException e) {
    throw new ServiceException("Error while building JSON object for notifications", e);
  }
}
 
Example 12
Project: alfresco-remote-api   File: RuleServiceTest.java   View Source Code Vote up 6 votes
public void testUpdateRule() throws Exception
{
    JSONObject jsonRule = createRule(testNodeRef);

    String ruleId = jsonRule.getJSONObject("data").getString("id");

    Response getResponse = sendRequest(new GetRequest(formateRuleUrl(testNodeRef, ruleId)), 200);

    JSONObject before = new JSONObject(getResponse.getContentAsString());

    // do some changes
    before.put("description", "this is modified description for test_rule");

    // do some changes for action object
    JSONObject beforeAction = before.getJSONObject("action");
    // no changes for actions list  
    beforeAction.remove("actions");
    // clear conditions
    beforeAction.put("conditions", new JSONArray());

    Response putResponse = sendRequest(new PutRequest(formateRuleUrl(testNodeRef, ruleId), before.toString(), "application/json"), 200);

    JSONObject after = new JSONObject(putResponse.getContentAsString());

    // sent and retrieved objects should be the same (except ids and urls)
    // this means that all changes was saved
    checkUpdatedRule(before, after);
}
 
Example 13
Project: boohee_v5.6   File: MobclickAgentJSInterface.java   View Source Code Vote up 6 votes
public boolean onJsPrompt(WebView webView, String str, String str2, String str3,
                          JsPromptResult jsPromptResult) {
    if ("ekv".equals(str2)) {
        try {
            JSONObject jSONObject = new JSONObject(str3);
            Map hashMap = new HashMap();
            String str4 = (String) jSONObject.remove("id");
            int intValue = jSONObject.isNull(SportRecordDao.DURATION) ? 0 : ((Integer)
                    jSONObject.remove(SportRecordDao.DURATION)).intValue();
            Iterator keys = jSONObject.keys();
            while (keys.hasNext()) {
                String str5 = (String) keys.next();
                hashMap.put(str5, jSONObject.getString(str5));
            }
            MobclickAgent.getAgent().a(this.b.a, str4, hashMap, (long) intValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (!"event".equals(str2)) {
        return this.a.onJsPrompt(webView, str, str2, str3, jsPromptResult);
    } else {
        try {
            JSONObject jSONObject2 = new JSONObject(str3);
            String optString = jSONObject2.optString("label");
            if ("".equals(optString)) {
                optString = null;
            }
            MobclickAgent.getAgent().a(this.b.a, jSONObject2.getString(DownloadService
                    .EXTRA_TAG), optString, (long) jSONObject2.optInt(SportRecordDao
                    .DURATION), 1);
        } catch (Exception e2) {
        }
    }
    jsPromptResult.confirm();
    return true;
}
 
Example 14
Project: solo-spring   File: RhythmArticleSender.java   View Source Code Vote up 5 votes
public void action(final Event<JSONObject> event) throws EventException {
	final JSONObject data = event.getData();

	logger.debug("Processing an event[type={}, data={}] in listener[className={}]", event.getType(), data,
			RhythmArticleSender.class);
	try {
		final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);

		if (!originalArticle.getBoolean(Article.ARTICLE_IS_PUBLISHED)) {
			logger.debug("Ignores post article[title={}] to Rhythm",
					originalArticle.getString(Article.ARTICLE_TITLE));

			return;
		}

		final JSONObject preference = preferenceQueryService.getPreference();

		if (null == preference) {
			throw new EventException("Not found preference");
		}

		if (!StringUtils.isBlank(originalArticle.optString(Article.ARTICLE_VIEW_PWD))) {
			return;
		}

		if (Latkes.getServePath().contains("localhost")) {
			logger.info("Solo runs on local server, so should not send this article[id={}, title={}] to Rhythm",
					originalArticle.getString(Keys.OBJECT_ID), originalArticle.getString(Article.ARTICLE_TITLE));
			return;
		}

		final HTTPRequest httpRequest = new HTTPRequest();

		httpRequest.setURL(ADD_ARTICLE_URL);
		httpRequest.setRequestMethod(RequestMethod.POST);
		final JSONObject requestJSONObject = new JSONObject();
		final JSONObject article = new JSONObject();

		article.put(Keys.OBJECT_ID, originalArticle.getString(Keys.OBJECT_ID));
		article.put(Article.ARTICLE_TITLE, originalArticle.getString(Article.ARTICLE_TITLE));
		article.put(Article.ARTICLE_PERMALINK, originalArticle.getString(Article.ARTICLE_PERMALINK));
		article.put(Article.ARTICLE_TAGS_REF, originalArticle.getString(Article.ARTICLE_TAGS_REF));
		article.put(Article.ARTICLE_AUTHOR_EMAIL, originalArticle.getString(Article.ARTICLE_AUTHOR_EMAIL));
		article.put(Article.ARTICLE_CONTENT, originalArticle.getString(Article.ARTICLE_CONTENT));
		article.put(Article.ARTICLE_CREATE_DATE,
				((Date) originalArticle.get(Article.ARTICLE_CREATE_DATE)).getTime());
		article.put(Common.POST_TO_COMMUNITY, originalArticle.getBoolean(Common.POST_TO_COMMUNITY));

		// Removes this property avoid to persist
		originalArticle.remove(Common.POST_TO_COMMUNITY);

		requestJSONObject.put(Article.ARTICLE, article);
		requestJSONObject.put(Common.BLOG_VERSION, SoloConstant.VERSION);
		requestJSONObject.put(Common.BLOG, "B3log Solo");
		requestJSONObject.put(Option.ID_C_BLOG_TITLE, preference.getString(Option.ID_C_BLOG_TITLE));
		requestJSONObject.put("blogHost", Latkes.getServePath());
		requestJSONObject.put("userB3Key", preference.optString(Option.ID_C_KEY_OF_SOLO));
		requestJSONObject.put("clientAdminEmail", preference.optString(Option.ID_C_ADMIN_EMAIL));
		requestJSONObject.put("clientRuntimeEnv", Latkes.getRuntimeEnv().name());

		httpRequest.setPayload(requestJSONObject.toString().getBytes("UTF-8"));

		urlFetchService.fetchAsync(httpRequest);
	} catch (final Exception e) {
		logger.error("Sends an article to Rhythm error: {}", e.getMessage());
	}

	logger.debug("Sent an article to Rhythm");
}
 
Example 15
Project: solo-spring   File: RhythmArticleUpdater.java   View Source Code Vote up 5 votes
public void action(final Event<JSONObject> event) throws EventException {
	final JSONObject data = event.getData();

	logger.debug("Processing an event[type={}, data={}] in listener[className={}]", event.getType(), data,
			RhythmArticleUpdater.class);
	try {
		final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);

		if (!originalArticle.getBoolean(Article.ARTICLE_IS_PUBLISHED)) {
			logger.debug("Ignores post article[title={}] to Rhythm",
					originalArticle.getString(Article.ARTICLE_TITLE));

			return;
		}

		final JSONObject preference = preferenceQueryService.getPreference();

		if (null == preference) {
			throw new EventException("Not found preference");
		}

		if (!StringUtils.isBlank(originalArticle.optString(Article.ARTICLE_VIEW_PWD))) {
			return;
		}

		if (Latkes.getServePath().contains("localhost")) {
			logger.info("Solo runs on local server, so should not send this article[id={}, title={}] to Rhythm",
					originalArticle.getString(Keys.OBJECT_ID), originalArticle.getString(Article.ARTICLE_TITLE));
			return;
		}

		final HTTPRequest httpRequest = new HTTPRequest();

		httpRequest.setURL(UPDATE_ARTICLE_URL);
		httpRequest.setRequestMethod(RequestMethod.PUT);
		final JSONObject requestJSONObject = new JSONObject();
		final JSONObject article = new JSONObject();

		article.put(Keys.OBJECT_ID, originalArticle.getString(Keys.OBJECT_ID));
		article.put(Article.ARTICLE_TITLE, originalArticle.getString(Article.ARTICLE_TITLE));
		article.put(Article.ARTICLE_PERMALINK, originalArticle.getString(Article.ARTICLE_PERMALINK));
		article.put(Article.ARTICLE_TAGS_REF, originalArticle.getString(Article.ARTICLE_TAGS_REF));
		article.put(Article.ARTICLE_AUTHOR_EMAIL, originalArticle.getString(Article.ARTICLE_AUTHOR_EMAIL));
		article.put(Article.ARTICLE_CONTENT, originalArticle.getString(Article.ARTICLE_CONTENT));
		article.put(Article.ARTICLE_CREATE_DATE,
				((Date) originalArticle.get(Article.ARTICLE_CREATE_DATE)).getTime());
		article.put(Common.POST_TO_COMMUNITY, originalArticle.getBoolean(Common.POST_TO_COMMUNITY));

		// Removes this property avoid to persist
		originalArticle.remove(Common.POST_TO_COMMUNITY);

		requestJSONObject.put(Article.ARTICLE, article);
		requestJSONObject.put(Common.BLOG_VERSION, SoloConstant.VERSION);
		requestJSONObject.put(Common.BLOG, "B3log Solo");
		requestJSONObject.put(Option.ID_C_BLOG_TITLE, preference.getString(Option.ID_C_BLOG_TITLE));
		requestJSONObject.put("blogHost", Latkes.getServerHost() + ":" + Latkes.getServerPort());
		requestJSONObject.put("userB3Key", preference.optString(Option.ID_C_KEY_OF_SOLO));
		requestJSONObject.put("clientAdminEmail", preference.optString(Option.ID_C_ADMIN_EMAIL));
		requestJSONObject.put("clientRuntimeEnv", Latkes.getRuntimeEnv().name());

		httpRequest.setPayload(requestJSONObject.toString().getBytes("UTF-8"));

		urlFetchService.fetchAsync(httpRequest);
	} catch (final Exception e) {
		logger.error("Sends an article to Rhythm error: {}", e.getMessage());
	}

	logger.debug("Sent an article to Rhythm");
}
 
Example 16
Project: solo-spring   File: LoginProcessor.java   View Source Code Vote up 5 votes
/**
 * Logins.
 * 
 * <p>
 * Renders the response with a json object, for example,
 * 
 * <pre>
 * {
 *     "isLoggedIn": boolean,
 *     "msg": "" // optional, exists if isLoggedIn equals to false
 * }
 * </pre>
 * </p>
 *
 * @param context
 *            the specified context
 */
@RequestMapping(value = "/login", method = RequestMethod.POST)
public void login(final HttpServletRequest request, final HttpServletResponse response, @RequestBody String body) {
	final JSONRenderer renderer = new JSONRenderer();
	final JSONObject jsonObject = new JSONObject();

	renderer.setJSONObject(jsonObject);

	try {
		jsonObject.put(Common.IS_LOGGED_IN, false);
		final String loginFailLabel = langPropsService.get("loginFailLabel");

		jsonObject.put(Keys.MSG, loginFailLabel);

		body = URLDecoder.decode(body, "UTF-8");
		final JSONObject requestJSONObject = new JSONObject(body);
		final String userEmail = requestJSONObject.getString(User.USER_EMAIL);
		final String userPwd = requestJSONObject.getString(User.USER_PASSWORD);

		if (StringUtils.isBlank(userEmail) || StringUtils.isBlank(userPwd)) {
			renderer.render(request, response);
			return;
		}

		logger.info("Login[email={}]", userEmail);

		final JSONObject user = userQueryService.getUserByEmail(userEmail);

		if (null == user) {
			logger.warn("Not found user[email={}]", userEmail);
			renderer.render(request, response);
			return;
		}

		if (MD5.hash(userPwd).equals(user.getString(User.USER_PASSWORD))) {
			Sessions.login(request, response, user);

			logger.info("Logged in[email={}]", userEmail);

			jsonObject.put(Common.IS_LOGGED_IN, true);

			if (Role.VISITOR_ROLE.equals(user.optString(User.USER_ROLE))) {
				jsonObject.put("to", Latkes.getServePath());
			} else {
				jsonObject.put("to", Latkes.getServePath() + Common.ADMIN_INDEX_URI);
			}

			jsonObject.remove(Keys.MSG);
			renderer.render(request, response);
			return;
		}

		logger.warn("Wrong password[{}]", userPwd);
	} catch (final Exception e) {
		logger.error(e.getMessage(), e);
	}
	renderer.render(request, response);
}
 
Example 17
Project: solo-spring   File: RepairProcessor.java   View Source Code Vote up 5 votes
/**
 * Removes unused properties of each article.
 *
 * @param context
 *            the specified context
 */
@RequestMapping(value = "/fix/normalization/articles/properties", method = RequestMethod.POST)
public void removeUnusedArticleProperties(final HttpServletRequest request, final HttpServletResponse response) {
	logger.info("Processes remove unused article properties");

	final TextHTMLRenderer renderer = new TextHTMLRenderer();
	// Transaction transaction = null;

	try {
		final JSONArray articles = articleDao.get(new Query()).getJSONArray(Keys.RESULTS);

		if (articles.length() <= 0) {
			renderer.setContent("No unused article properties");
			renderer.render(request, response);
			return;
		}

		// transaction = articleDao.beginTransaction();

		final Set<String> keyNames = Repositories.getKeyNames(Article.ARTICLE);

		for (int i = 0; i < articles.length(); i++) {
			final JSONObject article = articles.getJSONObject(i);

			final JSONArray names = article.names();
			final Set<String> nameSet = CollectionUtils.jsonArrayToSet(names);

			if (nameSet.removeAll(keyNames)) {
				for (final String unusedName : nameSet) {
					article.remove(unusedName);
				}

				articleDao.update(article.getString(Keys.OBJECT_ID), article);
				logger.info("Found an article[id={}] exists unused properties[{}]",
						article.getString(Keys.OBJECT_ID), nameSet);
			}
		}

		// transaction.commit();
	} catch (final Exception e) {
		// if (null != transaction && transaction.isActive()) {
		// transaction.rollback();
		// }

		logger.error(e.getMessage(), e);
		renderer.setContent("Removes unused article properties failed, error msg[" + e.getMessage() + "]");
	}
	renderer.render(request, response);
}
 
Example 18
Project: marathonv5   File: AbstractPreferences.java   View Source Code Vote up 5 votes
public void setValue(String section, String property, Object value) {
    JSONObject oSection = getSection(section);
    if (value == null)
        oSection.remove(property);
    else
        oSection.put(property, value);
    save(section);
}
 
Example 19
Project: logistimo-web-service   File: IRPostConfigMigrator.java   View Source Code Vote up 5 votes
/**
 * Update configurations for a list of keys
 *
 * @param keys - list of config key to migrate
 */
public static boolean update(List<String> keys) {
  try {
    Map<String, String> conf = readConfig(keys);
    if (conf == null) {
      return false;
    }
    //process
    for (String domainId : conf.keySet()) {
      xLog.info("Parsing config for domain {0}", domainId);
      JSONObject config = new JSONObject(conf.get(domainId));
      if (config.has("ogr")) {
        boolean isPostIssue = config.getBoolean("ogi");
        boolean isPostReceipt = config.getBoolean("ogr");
        config.remove("ogr");
        if (!isPostIssue && isPostReceipt) {
          xLog.info("Config updated for domain {0}", domainId);
          config.put("ogi", true);
        }
        conf.put(domainId, String.valueOf(config));
      }
    }
    //update
    ps = connection.prepareStatement(CONFIG_UPDATE_QUERY);
    for (String confKeys : conf.keySet()) {
      ps.setString(1, conf.get(confKeys));
      ps.setString(2, confKeys);
      ps.addBatch();
    }
    int[] count = ps.executeBatch();
    xLog.info("{0} domains updated out of {1}", count.length, conf.size());
  } catch (Exception e) {
    xLog.warn("Error in updating configuration: " + e);
    return false;
  } finally {
    if (ps != null) {
      try {
        ps.close();
      } catch (SQLException ignored) {
        xLog.warn("Exception while closing prepared statement", ignored);
      }
    }
  }
  return true;
}
 
Example 20
Project: solo-spring   File: PageQueryService.java   View Source Code Vote up 4 votes
/**
 * Gets pages by the specified request json object.
 * 
 * @param requestJSONObject
 *            the specified request json object, for example,
 * 
 *            <pre>
 * {
 *     "paginationCurrentPageNum": 1,
 *     "paginationPageSize": 20,
 *     "paginationWindowSize": 10
 * }, see {@link Pagination} for more details
 *            </pre>
 * 
 * @return for example,
 * 
 *         <pre>
 * {
 *     "pagination": {
 *         "paginationPageCount": 100,
 *         "paginationPageNums": [1, 2, 3, 4, 5]
 *     },
 *     "pages": [{
 *         "oId": "",
 *         "pageTitle": "",
 *         "pageCommentCount": int,
 *         "pageOrder": int,
 *         "pagePermalink": "",
 *         "pageCommentable": boolean,
 *         "pageType": "",
 *         "pageOpenTarget": ""
 *      }, ....]
 * }
 *         </pre>
 * 
 * @throws ServiceException
 *             service exception
 * @see Pagination
 */
public JSONObject getPages(final JSONObject requestJSONObject) throws ServiceException {
	final JSONObject ret = new JSONObject();

	try {
		final int currentPageNum = requestJSONObject.getInt(Pagination.PAGINATION_CURRENT_PAGE_NUM);
		final int pageSize = requestJSONObject.getInt(Pagination.PAGINATION_PAGE_SIZE);
		final int windowSize = requestJSONObject.getInt(Pagination.PAGINATION_WINDOW_SIZE);

		final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize)
				.addSort(Page.PAGE_ORDER, SortDirection.ASCENDING).setPageCount(1);
		final JSONObject result = pageDao.get(query);
		final int pageCount = result.getJSONObject(Pagination.PAGINATION).getInt(Pagination.PAGINATION_PAGE_COUNT);

		final JSONObject pagination = new JSONObject();
		final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);

		pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
		pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);

		final JSONArray pages = result.getJSONArray(Keys.RESULTS);

		for (int i = 0; i < pages.length(); i++) { // remove unused
													// properties
			final JSONObject page = pages.getJSONObject(i);

			page.remove(Page.PAGE_CONTENT);
		}

		ret.put(Pagination.PAGINATION, pagination);
		ret.put(Page.PAGES, pages);

		return ret;
	} catch (final Exception e) {
		logger.error("Gets pages failed", e);

		throw new ServiceException(e);
	}
}