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

The following examples show how to use org.json.simple.JSONObject#remove() . 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: BoxResource.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * boxインストールが実行されていないか、実行されたがキャッシュの有効期限が切れた場合のレスポンスを作成する.
 * @return レスポンス用JSONオブジェクト
 */
@SuppressWarnings("unchecked")
private JSONObject createResponse(JSONObject values) {
    JSONObject response = new JSONObject();
    response.putAll(values);
    response.remove("cell_id");
    response.remove("box_id");
    response.put("schema", this.getBox().getSchema());
    ProgressInfo.STATUS status = ProgressInfo.STATUS.valueOf((String) values.get("status"));
    if (status == ProgressInfo.STATUS.COMPLETED) {
        response.remove("progress");
        String startedAt = (String) response.remove("started_at");
        response.put("installed_at", startedAt);
    }
    response.put("status", status.value());
    return response;
}
 
Example 2
Source File: Redis.java    From AntiVPN with MIT License 6 votes vote down vote up
public void postVPNRaw(long id, long longIPID, Optional<Boolean> cascade, Optional<Double> consensus, long created) throws StorageException {
    try (Jedis redis = pool.getResource()) {
        JSONObject obj = new JSONObject();
        obj.put("ipID", longIPID);
        obj.put("cascade", cascade.orElse(null));
        obj.put("consensus", consensus.orElse(null));
        obj.put("created", created);

        redis.set(prefix + "vpn_values:" + id, obj.toJSONString());

        obj.remove("ipID");
        obj.put("id", id);
        redis.rpush(prefix + "vpn_values:ip:" + longIPID, obj.toJSONString());
    } catch (JedisException ex) {
        throw new StorageException(isAutomaticallyRecoverable(ex), ex);
    }
}
 
Example 3
Source File: Redis.java    From AntiVPN with MIT License 6 votes vote down vote up
public void loadMCLeaksValues(Set<RawMCLeaksResult> values, boolean truncate) throws StorageException {
    try (Jedis redis = pool.getResource()) {
        if (truncate) {
            deleteNamespace(redis, prefix + "mcleaks_values:");
        }
        long max = 0;
        for (RawMCLeaksResult r : values) {
            max = Math.max(max, r.getID());
            JSONObject obj = new JSONObject();
            obj.put("playerID", r.getLongPlayerID());
            obj.put("result", r.getValue());
            obj.put("created", r.getCreated());

            redis.set(prefix + "mcleaks_values:" + r.getID(), obj.toJSONString());

            obj.remove("playerID");
            obj.put("id", r.getID());
            redis.rpush(prefix + "mcleaks_values:player:" + r.getLongPlayerID(), obj.toJSONString());
        }
        redis.set(prefix + "mcleaks_values:idx", String.valueOf(max));
    } catch (JedisException ex) {
        throw new StorageException(isAutomaticallyRecoverable(ex), ex);
    }
}
 
Example 4
Source File: HostFromPropertiesFileAdapterTest.java    From metron with Apache License 2.0 5 votes vote down vote up
@Test
public void testInitializeAdapter() {
    Map<String, JSONObject> mapKnownHosts = new HashMap<>();
    HostFromPropertiesFileAdapter hfa = new HostFromPropertiesFileAdapter(mapKnownHosts);
    assertFalse(hfa.initializeAdapter(null));
    JSONArray jsonArray = (JSONArray) JSONValue.parse(expectedKnownHostsString);
    Iterator jsonArrayIterator = jsonArray.iterator();
    while(jsonArrayIterator.hasNext()) {
        JSONObject jsonObject = (JSONObject) jsonArrayIterator.next();
        String host = (String) jsonObject.remove("ip");
        mapKnownHosts.put(host, jsonObject);
    }
    hfa = new HostFromPropertiesFileAdapter(mapKnownHosts);
    assertTrue(hfa.initializeAdapter(null));
}
 
Example 5
Source File: WebApiParameter.java    From sepia-assist-server with MIT License 5 votes vote down vote up
@Override
public String extract(String input){
	//define name
	String parameterName = this.getClass().getName();
	String extracted = "";
	
	//check storage first
	ParameterResult pr = nluInput.getStoredParameterResult(parameterName);
	if (pr != null){
		this.found = pr.getFound();
		return pr.getExtracted();
	}
	
	//call endpoint and parse result
	JSONObject response = Connectors.httpPOST(getApiUrl(), this.nluInput.getJson().toJSONString(), null);
	if (Connectors.httpSuccess(response)){
		//System.out.println(response.toJSONString());						//DEBUG
		//System.out.println(nluResult.getBestResultJSON().toJSONString());	//DEBUG
		String result = JSON.getStringOrDefault(response, "result", "fail");
		if (!result.equals("fail")){
			response.remove("result");
			extracted = Interview.INPUT_EXTRACTED + ";;" + response.toJSONString();
		}else{
			return "";
		}
	}else{
		Debugger.println("WebApiParameter - extract FAILED with msg.: " + response.toJSONString(), 1);
		return "";
	}
	
	//store it
	pr = new ParameterResult(parameterName, extracted, this.found);
	this.nluInput.addToParameterResultStorage(pr);
	
	return extracted;
}
 
Example 6
Source File: EventResourceTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * リクエストボディのobjectがない場合にエラーとなること.
 */
@Test(expected = DcCoreException.class)
public void リクエストボディのobjectがない場合にエラーとなること() {
    TestEventResource resource = new TestEventResource();
    JSONObject body = createEventBody();
    body.remove("object");
    StringReader reader = new StringReader(body.toJSONString());
    JSONEvent event = resource.getRequestBody(reader);
    resource.validateEventProperties(event);
}
 
Example 7
Source File: BulkMessageWriterBoltTest.java    From metron with Apache License 2.0 5 votes vote down vote up
@Test
public void testSourceTypeMissing() throws Exception {
  // setup the bolt
  BulkMessageWriterBolt<IndexingConfigurations> bulkMessageWriterBolt = new BulkMessageWriterBolt<IndexingConfigurations>(
        "zookeeperUrl", "INDEXING")
          .withBulkMessageWriter(bulkMessageWriter)
          .withMessageGetter(MessageGetters.JSON_FROM_FIELD.name())
          .withMessageGetterField("message");
  bulkMessageWriterBolt.setCuratorFramework(client);
  bulkMessageWriterBolt.setZKCache(cache);
  bulkMessageWriterBolt.getConfigurations().updateSensorIndexingConfig(BaseEnrichmentBoltTest.sensorType,
          new FileInputStream("../" + BaseEnrichmentBoltTest.sampleSensorIndexingConfigPath));

  // initialize the bolt
  bulkMessageWriterBolt.declareOutputFields(declarer);
  Map stormConf = new HashMap();
  bulkMessageWriterBolt.prepare(stormConf, topologyContext, outputCollector);

  // create a message with no source type
  JSONObject message = (JSONObject) new JSONParser().parse(sampleMessageString);
  message.remove("source.type");
  when(tuple.getValueByField("message")).thenReturn(message);

  // the tuple should be handled as an error and ack'd
  bulkMessageWriterBolt.execute(tuple);
  verify(outputCollector, times(1)).emit(eq(Constants.ERROR_STREAM), any());
  verify(outputCollector, times(1)).ack(tuple);
  verify(outputCollector, times(1)).reportError(any(Throwable.class));
  Mockito.verifyNoMoreInteractions(outputCollector);
}
 
Example 8
Source File: BaseBoltTest.java    From metron with Apache License 2.0 5 votes vote down vote up
public void removeTimingFields(JSONObject message) {
  ImmutableSet keys = ImmutableSet.copyOf(message.keySet());
  for (Object key : keys) {
    if (key.toString().endsWith(".ts")) {
      message.remove(key);
    }
  }
}
 
Example 9
Source File: MetronErrorJSONMatcher.java    From metron with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(Values values) {
  JSONObject actual = (JSONObject) values.get(0);
  actual.remove("timestamp");
  expected.remove("timestamp");
  actual.remove("stack");
  expected.remove("stack");
  actual.remove("guid");
  expected.remove("guid");
  return actual.equals(expected);
}
 
Example 10
Source File: EventResourceTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * リクエストボディのlevelがない場合に場合にエラーとなること.
 */
@Test(expected = DcCoreException.class)
public void リクエストボディのlevelがない場合にエラーとなること() {
    TestEventResource resource = new TestEventResource();
    JSONObject body = createEventBody();
    body.remove("level");
    StringReader reader = new StringReader(body.toJSONString());
    JSONEvent event = resource.getRequestBody(reader);
    resource.validateEventProperties(event);
}
 
Example 11
Source File: UltimateFancy.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
private JSONArray addColorToArray(String text) {
    JSONArray extraArr = new JSONArray();
    ChatColor color = ChatColor.WHITE;
    for (String part : text.split("(?=" + ChatColor.COLOR_CHAR + "[0-9a-fA-Fk-oK-ORr])")) {
        JSONObject objExtraTxt = new JSONObject();
        Matcher match = Pattern.compile("^" + ChatColor.COLOR_CHAR + "([0-9a-fA-Fk-oK-ORr]).*$").matcher(part);
        if (match.find()) {
            color = ChatColor.getByChar(match.group(1).charAt(0));
            if (part.length() == 2) continue;
        }
        objExtraTxt.put("text", ChatColor.stripColor(part));
        if (color.isColor()) {
            objExtraTxt.put("color", color.name().toLowerCase());
            objExtraTxt.remove("obfuscated");
            objExtraTxt.remove("underlined");
            objExtraTxt.remove(ChatColor.STRIKETHROUGH.name().toLowerCase());
        }
        if (color.equals(ChatColor.RESET)) {
            objExtraTxt.put("color", "white");
            objExtraTxt.remove("obfuscated");
            objExtraTxt.remove("underlined");
            objExtraTxt.remove(ChatColor.STRIKETHROUGH.name().toLowerCase());
        }
        if (color.isFormat()) {
            if (color.equals(ChatColor.MAGIC)) {
                objExtraTxt.put("obfuscated", true);
            } else if (color.equals(ChatColor.UNDERLINE)) {
                objExtraTxt.put("underlined", true);
            } else {
                objExtraTxt.put(color.name().toLowerCase(), true);
            }
        }
        extraArr.add(objExtraTxt);
    }
    return extraArr;
}
 
Example 12
Source File: BasicLogstashParser.java    From metron with Apache License 2.0 5 votes vote down vote up
@Override
public List<JSONObject> parse(byte[] raw_message) {
	List<JSONObject> messages = new ArrayList<>();
	try {
		
		/*
		 * We need to create a new JSONParser each time because its 
		 * not serializable and the parser is created on the storm nimbus
		 * node, then transfered to the workers.
		 */
		JSONParser jsonParser = new JSONParser();
		String rawString = new String(raw_message, StandardCharsets.UTF_8);
		JSONObject rawJson = (JSONObject) jsonParser.parse(rawString);
		
		// remove logstash meta fields
		rawJson.remove("@version");
		rawJson.remove("type");
		rawJson.remove("host");
		rawJson.remove("tags");
		
		// rename other keys
		rawJson = mutate(rawJson, "message", "original_string");
		rawJson = mutate(rawJson, "src_ip", "ip_src_addr");
		rawJson = mutate(rawJson, "dst_ip", "ip_dst_addr");
		rawJson = mutate(rawJson, "src_port", "ip_src_port");
		rawJson = mutate(rawJson, "dst_port", "ip_dst_port");
		rawJson = mutate(rawJson, "src_ip", "ip_src_addr");
		
		// convert timestamp to milli since epoch
		long timestamp = LogstashToEpoch((String) rawJson.remove("@timestamp"));
		rawJson.put("timestamp", timestamp);
		messages.add(rawJson);
		return messages;
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}	
}
 
Example 13
Source File: Activity.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Map<String, Object> getActivitySummary(JSONObject activitySummary, String activityType)
{
	Map<String, Object> summary = new HashMap<String, Object>();

	if(activityType.equals("org.alfresco.documentlibrary.file-added"))
	{
		String nodeRefStr = (String)activitySummary.remove("nodeRef");
		if(NodeRef.isNodeRef(nodeRefStr))
		{
			summary.put("objectId", new NodeRef(nodeRefStr).getId());
		}
		else
		{
			throw new RuntimeException("nodeRef " + nodeRefStr + " in activity feed is not a valid NodeRef");
		}
		String parentNodeRefStr = (String)activitySummary.remove("parentNodeRef");
		if(NodeRef.isNodeRef(parentNodeRefStr))
		{
			summary.put("parentObjectId", new NodeRef(parentNodeRefStr).getId());
		}
		else
		{
			throw new RuntimeException("parentNodeRef " + parentNodeRefStr + " in activity feed is not a valid NodeRef");
		}
		summary.put("lastName", activitySummary.get("lastName"));
		summary.put("firstName", activitySummary.get("firstName"));
		summary.put("title", activitySummary.get("title"));
	} else if(activityType.equals("org.alfresco.site.user-joined"))
	{
		summary.put("lastName", activitySummary.get("lastName"));
		summary.put("firstName", activitySummary.get("firstName"));
		summary.put("memberLastName", activitySummary.get("memberLastName"));
		summary.put("memberFirstName", activitySummary.get("memberFirstName"));
		summary.put("memberPersonId", activitySummary.get("memberUserName"));
		summary.put("role", activitySummary.get("role"));
		summary.put("title", activitySummary.get("title"));
	}

	return summary;
}
 
Example 14
Source File: NodeMessage.java    From java-trader with Apache License 2.0 5 votes vote down vote up
public static NodeMessage fromString(String jsonStr) throws Exception
{
    JSONObject json = (JSONObject)(new JSONParser()).parse(jsonStr);
    MsgType type = MsgType.valueOf((String) json.remove(FIELD_TYPE));
    int id = ConversionUtil.toInt(json.remove(FIELD_ID));
    int reqId = ConversionUtil.toInt(json.remove(FIELD_REQID));
    int corrId = ConversionUtil.toInt(json.remove(FIELD_CORRID));
    int errorCode = ConversionUtil.toInt(json.remove(FIELD_ERROR_CODE));
    String errorMsg = (String)json.remove(FIELD_ERROR_MSG);
    Map<String, Object> fields = json;
    NodeMessage result = new NodeMessage(type, id, reqId, corrId, fields);
    result.setErrCode(errorCode);
    result.setErrMsg(errorMsg);
    return result;
}
 
Example 15
Source File: EventResourceTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * リクエストボディのactionがない場合にエラーとなること.
 */
@Test(expected = DcCoreException.class)
public void リクエストボディのactionがない場合にエラーとなること() {
    TestEventResource resource = new TestEventResource();
    JSONObject body = createEventBody();
    body.remove("action");
    StringReader reader = new StringReader(body.toJSONString());
    JSONEvent event = resource.getRequestBody(reader);
    resource.validateEventProperties(event);
}
 
Example 16
Source File: BasicBroParser.java    From metron with Apache License 2.0 5 votes vote down vote up
private boolean replaceKey(JSONObject payload, String toKey, String[] fromKeys) {
  for (String fromKey : fromKeys) {
    if (payload.containsKey(fromKey)) {
      Object value = payload.remove(fromKey);
      payload.put(toKey, value);
      _LOG.trace("[Metron] Added {} to {}", toKey, payload);
      return true;
    }
  }
  return false;
}
 
Example 17
Source File: Node.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new {@code Node} that corresponds to the given JSONObject.
 * 
 * @param node JSONObject describing the node.
 */
Node(JSONObject node) {
    this.properties = node;

    // Children
    Object childrenValue = node.get("children"); // NOI18N
    if (childrenValue != null) {
        initChildren();
        JSONArray childrenArray = (JSONArray)childrenValue;
        List<Node> newChildren = new ArrayList<Node>(childrenArray.size());
        for (Object child : childrenArray) {
            newChildren.add(new Node((JSONObject)child));
        }
        addChildren(newChildren);
    }

    Object shadowRootsValue = node.get("shadowRoots"); // NOI18N
    if (shadowRootsValue instanceof JSONArray) {
        JSONArray shadowRootArray = (JSONArray)shadowRootsValue;
        for (Object shadowRoot : shadowRootArray) {
            addShadowRoot(new Node((JSONObject)shadowRoot));
        }
    }

    // Attributes
    JSONArray array = (JSONArray)getProperties().get("attributes"); // NOI18N
    if (array != null) {
        for (int i=0; i<array.size()/2; i++) {
            String name = (String)array.get(2*i);
            String value = (String)array.get(2*i+1);
            setAttribute(name, value);
        }
    }

    // Content document
    JSONObject document = (JSONObject)getProperties().get("contentDocument"); // NOI18N
    if (document != null) {
        contentDocument = new Node(document);
        contentDocument.parent = this;
        // A node cannot have both children and content document.
        // FRAME doesn't support children at all and children
        // of IFRAME are interpreted when frames are not supported
        // only (i.e. when the content document is null)
        // => no need to ask for children of a node with a content
        // document. We can set children to empty collection immediately.
        initChildren();
    }

    // Cleanup
    node.remove("children"); // NOI18N
    node.remove("attributes"); // NOI18N
    node.remove("contentDocument"); // NOI18N
}
 
Example 18
Source File: SwaggerCreator.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method returns the swagger definition of an api
 * which suits for k8s_apim_operator
 *
 * @param api               API
 * @param oasDefinition     Open API definition
 * @return OAS definition
 * @throws APIManagementException throws if an error occurred
 * @throws ParseException         throws if the oasDefinition is not in json format
 */

public String getOASDefinitionForPrivateJetMode(API api, String oasDefinition)
        throws APIManagementException, ParseException {

    APIDefinition oasParser = OASParserUtil.getOASParser(oasDefinition);
    String apiDefinition = oasParser.getOASDefinitionForPublisher(api, oasDefinition);

    OASParserUtil.SwaggerVersion swaggerVersion = OASParserUtil.getSwaggerVersion(apiDefinition);
    if (swaggerVersion == OASParserUtil.SwaggerVersion.SWAGGER) {
        //parsing swagger 2.0 to openAPI 3.0.1
        OpenAPIParser openAPIParser = new OpenAPIParser();
        SwaggerParseResult swaggerParseResult = openAPIParser.readContents(apiDefinition, null, null);
        if (CollectionUtils.isNotEmpty(swaggerParseResult.getMessages())) {
            log.debug("Errors found when parsing OAS definition");
        }
        OpenAPI openAPI = swaggerParseResult.getOpenAPI();
        apiDefinition = Json.pretty(openAPI);
    }

    //get Json object from parsed openAPI definition
    JSONParser jsonParser = new JSONParser();
    JSONObject apiDefinitionJsonObject = (JSONObject) jsonParser.parse(apiDefinition);

    /**
     * Removing the "security" key from the JSONObject
     */
    apiDefinitionJsonObject.remove(ContainerBasedConstants.SECURITY);
    ((JSONObject) ((JSONObject) apiDefinitionJsonObject.get(ContainerBasedConstants.COMPONENTS))
            .get(ContainerBasedConstants.SECURITY_SCHEMES)).remove(ContainerBasedConstants.DEFAULT);
    Set<String> paths = ((JSONObject) apiDefinitionJsonObject.get(ContainerBasedConstants.PATHS)).keySet();
    Iterator iterator = paths.iterator();

    /**
     * Removing the "security" attribute from each RESTAPI verb of each path in the swagger
     */
    while (iterator.hasNext()) {
        String path = (String) iterator.next();
        Set verbs = ((JSONObject) ((JSONObject) apiDefinitionJsonObject.get(ContainerBasedConstants.PATHS))
                .get(path)).keySet();
        Iterator verbIterator = verbs.iterator();
        while (verbIterator.hasNext()) {
            String verb = (String) verbIterator.next();
            ((JSONObject) ((JSONObject) ((JSONObject) apiDefinitionJsonObject.get(ContainerBasedConstants.PATHS)).
                    get(path)).get(verb)).remove(ContainerBasedConstants.SECURITY);
        }
    }

    String securityType = api.getApiSecurity()
            .replace(ContainerBasedConstants.OAUTH_BASICAUTH_APIKEY_MANDATORY, "");
    Boolean securityTypeOauth2 = isAPISecurityTypeOauth2(securityType);
    Boolean securityTypeBasicAuth = isAPISecurityBasicAuth(securityType);

    if (basicSecurityName != null && securityTypeBasicAuth && !securityTypeOauth2 && !"".equals(basicSecurityName)) {

        SecurityRequirement basicOauthSecurityReq = referBasicAuthInSwagger(basicSecurityName);
        List<SecurityRequirement> basicAuth = new ArrayList<SecurityRequirement>();
        basicAuth.add(basicOauthSecurityReq);
        apiDefinitionJsonObject.put(ContainerBasedConstants.SECURITY, basicAuth);
    } else if (securityTypeOauth2 && !securityTypeBasicAuth) {

        if (oauthSecurityName != null && !"".equals(oauthSecurityName) || jwtSecurityName != null && !"".equals(jwtSecurityName)) {

            SecurityRequirement oauth2SecurityReq = referOauth2InSwagger(oauthSecurityName, jwtSecurityName);
            List<SecurityRequirement> oauth2 = new ArrayList<SecurityRequirement>();
            oauth2.add(oauth2SecurityReq);
            apiDefinitionJsonObject.put(ContainerBasedConstants.SECURITY, oauth2);
        }
    } else if (securityTypeBasicAuth && securityTypeOauth2) {

        if (oauthSecurityName != null && !"".equals(oauthSecurityName) ||
                basicSecurityName != null && !"".equals(basicSecurityName) ||
                jwtSecurityName != null && !"".equals(jwtSecurityName)) {
            List<SecurityRequirement> basicOauthJWT = new ArrayList<SecurityRequirement>();
            SecurityRequirement basicOauthJWTSecurityReq = referBasicOAuth2JWTInSwagger(basicSecurityName,
                    oauthSecurityName, jwtSecurityName);
            basicOauthJWT.add(basicOauthJWTSecurityReq);
            apiDefinitionJsonObject.put(ContainerBasedConstants.SECURITY, basicOauthJWT);
        }
    }
    return Json.pretty(apiDefinitionJsonObject);
}
 
Example 19
Source File: GrokParser.java    From metron with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private Optional<MessageParserResult<JSONObject>> parseSingleLine(byte[] rawMessage) {
  List<JSONObject> messages = new ArrayList<>();
  Map<Object,Throwable> errors = new HashMap<>();
  String originalMessage = null;
  try {
    originalMessage = new String(rawMessage, StandardCharsets.UTF_8);
    LOG.debug("Grok parser parsing message: {}",originalMessage);
    Match gm = grok.match(originalMessage);
    gm.captures();
    JSONObject message = new JSONObject();
    message.putAll(gm.toMap());

    if (message.size() == 0) {
      Throwable rte = new RuntimeException("Grok statement produced a null message. Original message was: "
              + originalMessage + " and the parsed message was: " + message + " . Check the pattern at: "
              + grokPath);
      errors.put(originalMessage, rte);
    } else {
      message.put("original_string", originalMessage);
      for (String timeField : timeFields) {
        String fieldValue = (String) message.get(timeField);
        if (fieldValue != null) {
          message.put(timeField, toEpoch(fieldValue));
        }
      }
      if (timestampField != null) {
        message.put(Constants.Fields.TIMESTAMP.getName(), formatTimestamp(message.get(timestampField)));
      }
      message.remove(patternLabel);
      postParse(message);
      messages.add(message);
      LOG.debug("Grok parser parsed message: {}", message);
    }
  } catch (Exception e) {
    LOG.error(e.getMessage(), e);
    Exception innerException = new IllegalStateException("Grok parser Error: "
            + e.getMessage()
            + " on "
            + originalMessage, e);
    return Optional.of(new DefaultMessageParserResult<>(innerException));
  }
  return Optional.of(new DefaultMessageParserResult<JSONObject>(messages, errors));
}
 
Example 20
Source File: DB.java    From sepia-assist-server with MIT License 4 votes vote down vote up
/**
 * Set a user data list by either overwriting the doc at 'docId' or creating a new one.
 * @return JSONObject with "code" and optionally "_id" if the doc was newly created
 */
public static JSONObject setListData(String docId, String userId, Section section, String indexType, JSONObject listData){
	long tic = Debugger.tic();
	if (userId.isEmpty() || indexType.isEmpty()){
		throw new RuntimeException("setListData - 'userId' or 'indexType' invalid!");
	}
	//safety overwrite
	JSON.put(listData, "user", userId);
	JSON.put(listData, "section", section.name());
	JSON.put(listData, "indexType", indexType);
	
	//Note: if the 'title' is empty this might unintentionally overwrite a list or create a new one
	String title = (String) listData.get("title");
	if ((docId == null || docId.isEmpty()) && (title == null || title.isEmpty())){
		throw new RuntimeException("setUserDataList - 'title' AND 'id' is MISSING! Need at least one.");
	}
	if (section == null || section.name().isEmpty()){
		throw new RuntimeException("setUserDataList - 'section' is MISSING!");
	}
	
	//simply write when no docId is given
	JSONObject setResult;
	if (docId == null || docId.isEmpty()){
		JSON.put(listData, "lastEdit", System.currentTimeMillis());
		setResult = knowledge.setAnyItemData(DB.USERDATA, UserDataList.LISTS_TYPE, listData);
	
	}else{
		listData.remove("_id"); //prevent to have id twice
		JSON.put(listData, "lastEdit", System.currentTimeMillis());
		JSONObject newListData = new JSONObject();
		//double-check if someone tampered with the docID by checking userID via script
		String dataAssign = "";
		for(Object keyObj : listData.keySet()){
			String key = (String) keyObj;
			dataAssign += ("ctx._source." + key + "=params." + key + "; ");
		}
		JSONObject script = JSON.make("lang", "painless",
				"inline", "if (ctx._source.user != params.user) { ctx.op = 'noop'} " + dataAssign.trim(),
				"params", listData);
		JSON.put(newListData, "script", script);//"ctx.op = ctx._source.user == " + userId + "? 'update' : 'none'");
		JSON.put(newListData, "scripted_upsert", true);
		
		int code = knowledge.updateItemData(DB.USERDATA, UserDataList.LISTS_TYPE, docId, newListData);
		setResult = JSON.make("code", code);
	}
	
	//statistics
	Statistics.addOtherApiHit("setListDataInDB");
	Statistics.addOtherApiTime("setListDataInDB", tic);
			
	return setResult;
}