Example usage for org.json.simple JSONObject remove

List of usage examples for org.json.simple JSONObject remove

Introduction

In this page you can find the example usage for org.json.simple JSONObject remove.

Prototype

V remove(Object key);

Source Link

Document

Removes the mapping for a key from this map if it is present (optional operation).

Usage

From source file:io.personium.core.model.impl.fs.DavCmpFsImpl.java

@Override
public final ResponseBuilder acl(final Reader reader) {
    // ???????????
    Acl aclToSet = null;//from  ww  w .  j  a  v a2 s  . c o m
    try {
        aclToSet = ObjectIo.unmarshal(reader, Acl.class);
    } catch (Exception e1) {
        throw PersoniumCoreException.Dav.XML_CONTENT_ERROR.reason(e1);
    }
    if (!aclToSet.validateAcl(isCellLevel())) {
        throw PersoniumCoreException.Dav.XML_VALIDATE_ERROR;
    }
    // 
    Lock lock = this.lock();
    try {
        // ?
        this.load();
        if (!this.exists()) {
            throw getNotFoundException().params(this.getUrl());
        }

        // ACL?xml:base???
        String aclBase = aclToSet.getBase();

        // principal?href ? ??Name  ID__id ???
        List<Ace> aceList = aclToSet.getAceList();
        if (aceList != null) {
            for (Ace ace : aceList) {
                String pHref = ace.getPrincipalHref();
                if (pHref != null) {
                    String id = this.cell.roleResourceUrlToId(pHref, aclBase);
                    ace.setPrincipalHref(id);
                }
            }
        }

        JSONParser parser = new JSONParser();
        JSONObject aclJson = null;
        try {
            aclJson = (JSONObject) parser.parse(aclToSet.toJSON());
        } catch (ParseException e) {
            throw PersoniumCoreException.Dav.XML_ERROR.reason(e);
        }
        // ES?xm:base???? TODO ??????
        aclJson.remove(KEY_ACL_BASE);
        this.metaFile.setAcl(aclJson);
        this.metaFile.save();
        // ?
        return javax.ws.rs.core.Response.status(HttpStatus.SC_OK).header(HttpHeaders.ETAG, this.getEtag());
    } finally {
        lock.release();
    }
}

From source file:mml.handler.get.MMLGetVersion1Handler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {/*from   w w w .j  a va 2 s  .  c o  m*/
        Connection conn = Connector.getConnection();
        docid = request.getParameter(Params.DOCID);
        String res = conn.getFromDb(Database.CORTEX, docid);
        if (res != null) {
            JSONObject jObj = (JSONObject) JSONValue.parse(res);
            if (jObj.containsKey(JSONKeys.VERSION1)) {
                version1 = (String) jObj.get(JSONKeys.VERSION1);
                if (!Layers.isNewStyleLayer(version1)) {
                    if (((String) jObj.get(JSONKeys.FORMAT)).startsWith("MVD")) {
                        String body = (String) jObj.get(JSONKeys.BODY);
                        if (body != null) {
                            MVD mvd = MVDFile.internalise(body);
                            String[] all = getAllVersions(mvd);
                            version1 = Layers.upgradeLayerName(all, version1);
                        }
                    } else {
                        String[] all = new String[1];
                        all[0] = version1;
                        version1 = Layers.upgradeLayerName(all, version1);
                    }
                }
            } else if (((String) jObj.get(JSONKeys.FORMAT)).startsWith("MVD")) {
                String body = (String) jObj.get(JSONKeys.BODY);
                if (body != null) {
                    MVD mvd = MVDFile.internalise(body);
                    String[] all = getAllVersions(mvd);
                    String groupPath = mvd.getGroupPath((short) 1);
                    String shortName = mvd.getVersionShortName((short) 1);
                    version1 = Layers.upgradeLayerName(all, groupPath + "/" + shortName);
                    jObj.put(JSONKeys.VERSION1, version1);
                    jObj.remove(JSONKeys._ID);
                    conn.putToDb(Database.CORTEX, docid, jObj.toJSONString());
                } else
                    version1 = ""; // nothing there
            } else
                version1 = "/base";
        } else
            version1 = "";
        response.setContentType("text/plain");
        response.getWriter().write(version1.replaceAll("\\\\/", "/"));
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:com.photon.phresco.framework.rest.api.UtilService.java

@GET
@Path("/killProcess")
@Produces(MediaType.APPLICATION_JSON)//www .  java2 s  .  co  m
public Response killProcess(@QueryParam("actionType") String actionType,
        @QueryParam(REST_QUERY_APPID) String appId, @QueryParam(REST_QUERY_APPDIR_NAME) String appDirName) {
    ResponseInfo responseData = new ResponseInfo();
    // Pass module as param ------------------
    String moduleName = ""; /* for temporary*/
    try {
        String rootModulePath = "";
        String subModuleName = "";
        if (StringUtils.isNotEmpty(moduleName)) {
            rootModulePath = Utility.getProjectHome() + appDirName;
            subModuleName = moduleName;
        } else {
            rootModulePath = Utility.getProjectHome() + appDirName;
        }

        File getpomFileLocation = Utility.getPomFileLocation(rootModulePath, subModuleName);
        File do_not_checkin = new File(
                getpomFileLocation.getParent() + File.separator + Constants.DO_NOT_CHECKIN_DIRY);
        File jsonFile = new File(do_not_checkin.getPath() + File.separator + "process.json");
        if (!jsonFile.exists()) {
            ResponseInfo<List<ApplicationInfo>> finalOutput = responseDataEvaluation(responseData, null, null,
                    RESPONSE_STATUS_SUCCESS, PHR11C00001);
            return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                    .build();
        }
        JSONObject jsonObject = new JSONObject();
        JSONParser parser = new JSONParser();
        FileReader reader = new FileReader(jsonFile);
        jsonObject = (JSONObject) parser.parse(reader);
        Object processId = jsonObject.get(actionType);
        if (processId == null) {
            ResponseInfo<List<ApplicationInfo>> finalOutput = responseDataEvaluation(responseData, null, null,
                    RESPONSE_STATUS_SUCCESS, PHR11C00001);
            return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                    .build();
        }
        if (System.getProperty(Constants.OS_NAME).startsWith(Constants.WINDOWS_PLATFORM)) {
            Runtime.getRuntime().exec("cmd /X /C taskkill /F /T /PID " + processId.toString());
        } else if (System.getProperty(Constants.OS_NAME).startsWith("Mac")) {
            Runtime.getRuntime().exec(Constants.JAVA_UNIX_PROCESS_KILL_CMD + processId.toString());
        }
        LockUtil.removeLock(appId, actionType);
        jsonObject.remove(actionType);
        FileWriter writer = new FileWriter(jsonFile);
        writer.write(jsonObject.toString());
        writer.close();
        reader.close();
        if (jsonObject.size() <= 0) {
            FileUtil.delete(jsonFile);
        }
        ResponseInfo<List<String>> finalOutput = responseDataEvaluation(responseData, null, null,
                RESPONSE_STATUS_SUCCESS, PHR11C00002);
        return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                .build();
    } catch (IOException e) {
        ResponseInfo<ProjectInfo> finalOutput = responseDataEvaluation(responseData, e, null,
                RESPONSE_STATUS_ERROR, PHR11C10001);
        return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                .build();
    } catch (ParseException e) {
        ResponseInfo<ProjectInfo> finalOutput = responseDataEvaluation(responseData, e, null,
                RESPONSE_STATUS_ERROR, PHR11C10002);
        return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                .build();
    } catch (PhrescoException e) {
        ResponseInfo<ProjectInfo> finalOutput = responseDataEvaluation(responseData, e, null,
                RESPONSE_STATUS_ERROR, PHR11C10003);
        return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                .build();
    }
}

From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java

public final Shops delShop(String shopName, Player player) {
    try {// w w  w.j a v a 2s .c  o m
        String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json")));

        JSONParser parser = new JSONParser();

        Object obj = parser.parse(configTable);

        JSONObject jsonObj = (JSONObject) obj;

        JSONArray shopList = (JSONArray) jsonObj.get("shopsArray");

        // Make sure that our array isn't empty
        if (shopList == null) {
            player.sendMessage("\u00A7e<\u00A73mcDropShop : internal error 0x00\u00A7e>");

            return this;
        } else if (jsonObj.get(shopName) == null) {
            player.sendMessage("\u00A7e<\u00A73mcDropShop : internal error 0x01\u00A7e>");

            return this;
        }

        JSONObject shopObj;

        String shopName2;
        int index;
        // Find our shop in our array         
        for (index = 0; index < shopList.size(); index++) {
            shopObj = (JSONObject) (shopList.get(index));

            shopName2 = (String) shopObj.get("shopName");

            if (shopName2.equals(shopName)) {
                break;
            }

        }

        // Remove shop from array
        shopList.remove(index);

        // Update the entire JSON table in memory
        jsonObj.put("shopsArray", shopList);

        // Now remove the shop data from the root
        jsonObj.remove(shopName);

        // Update Shops.json
        FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json");

        shopsJSON.write(jsonObj.toJSONString());

        shopsJSON.flush();
        shopsJSON.close();

        Shops.shops.remove(shopName);

        player.sendMessage("\u00a7aShop removed!");

        return this;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in addShop()");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json");
        e.printStackTrace();
    } catch (IOException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught IOException in addShop()");
        e.printStackTrace();
    }

    return this;
}

From source file:mml.handler.get.MMLGetMMLHandler.java

/**
 * Merge two corcode sets/*from  w  w  w  .  j  a  v  a 2  s.  c  o m*/
 * @param cc1 the first corcode as a STIL JSON object
 * @param cc2 the second corcode as a STIL JSON object
 * @return a STIL object with the two merged arrays
 */
JSONObject mergeCorcodes(JSONObject cc1, JSONObject cc2) {
    JSONArray iArr = (JSONArray) cc1.get("ranges");
    JSONArray jArr = (JSONArray) cc2.get("ranges");
    String style = (String) cc1.get(JSONKeys.STYLE);
    addAbsoluteOffsets(iArr);
    addAbsoluteOffsets(jArr);
    int i = 0;
    int j = 0;
    JSONArray all = new JSONArray();
    while (i < iArr.size() || j < jArr.size()) {
        if (i == iArr.size())
            all.add(jArr.get(j++));
        else if (j == jArr.size())
            all.add(iArr.get(i++));
        else {
            JSONObject iObj = (JSONObject) iArr.get(i);
            JSONObject jObj = (JSONObject) jArr.get(j);
            int iOffset = ((Number) iObj.get(JSONKeys.OFFSET)).intValue();
            int jOffset = ((Number) jObj.get(JSONKeys.OFFSET)).intValue();
            if (iOffset < jOffset) {
                all.add(iObj);
                i++;
            } else if (jOffset < iOffset) {
                all.add(jObj);
                j++;
            } else // equal
            {
                int iLen = ((Number) iObj.get(JSONKeys.LEN)).intValue();
                int jLen = ((Number) jObj.get(JSONKeys.LEN)).intValue();
                if ((iLen == 0 && jLen != 0) || (iLen > jLen)) {
                    all.add(iObj);
                    i++;
                } else if ((jLen == 0 && iLen != 0) || (jLen > iLen)) {
                    all.add(jObj);
                    j++;
                } else {
                    all.add(iObj);
                    i++;
                }
            }
        }
    }
    JSONObject combined = new JSONObject();
    combined.put(JSONKeys.STYLE, style);
    int prev = 0;
    for (i = 0; i < all.size(); i++) {
        JSONObject jObj = (JSONObject) all.get(i);
        int offset = ((Number) jObj.get(JSONKeys.OFFSET)).intValue();
        int reloff = offset - prev;
        prev = offset;
        jObj.remove(JSONKeys.OFFSET);
        jObj.put(JSONKeys.RELOFF, reloff);
    }
    combined.put(JSONKeys.RANGES, all);
    return combined;
}

From source file:com.tresys.jalop.utils.jnltest.Config.ConfigTest.java

@Test
public void updateKnownHostsWorks() throws Exception {
    Config cfg = new Config("/path/to/nothing");

    assertTrue(cfg.getPeerConfigs().isEmpty());

    JSONObject peer0 = new JSONObject();
    JSONArray hosts = new JSONArray();
    JSONArray pubAllow = new JSONArray();
    JSONArray subAllow = new JSONArray();
    peer0.put("hosts", hosts);
    peer0.put("publishAllow", pubAllow);
    peer0.put("subscribeAllow", subAllow);

    assertTrue(cfg.getPeerConfigs().isEmpty());

    cfg.updateKnownHosts(peer0);//from  w  w  w .ja va2s. co m

    JSONObject peer1 = new JSONObject();
    hosts.add("192.168.1.1");
    peer1.put("hosts", hosts);

    pubAllow.add("audit");
    peer1.put("publishAllow", pubAllow);

    subAllow.add("log");
    peer1.put("subscribeAllow", subAllow);

    cfg.updateKnownHosts(peer1);

    JSONObject peer2 = new JSONObject();
    hosts.clear();
    hosts.add("192.168.1.2");
    peer2.put("hosts", hosts);

    pubAllow.clear();
    pubAllow.add("log");
    peer2.put("publishAllow", pubAllow);

    subAllow.clear();
    subAllow.add("audit");
    peer2.put("subscribeAllow", subAllow);

    Map<InetAddress, PeerConfig> peerCfgs = cfg.getPeerConfigs();

    InetAddress addr1 = InetAddresses.forString("192.168.1.1");

    assertTrue(peerCfgs.containsKey(addr1));
    assertTrue(
            peerCfgs.get(InetAddresses.forString("192.168.1.1")).getPublishAllow().contains(RecordType.Audit));
    assertFalse(peerCfgs.get(InetAddresses.forString("192.168.1.1")).getPublishAllow()
            .contains(RecordType.Journal));
    assertFalse(
            peerCfgs.get(InetAddresses.forString("192.168.1.1")).getPublishAllow().contains(RecordType.Log));
    assertTrue(
            peerCfgs.get(InetAddresses.forString("192.168.1.1")).getSubscribeAllow().contains(RecordType.Log));
    assertFalse(peerCfgs.get(InetAddresses.forString("192.168.1.1")).getSubscribeAllow()
            .contains(RecordType.Audit));
    assertFalse(peerCfgs.get(InetAddresses.forString("192.168.1.1")).getSubscribeAllow()
            .contains(RecordType.Journal));

    cfg.updateKnownHosts(peer2);

    peerCfgs = cfg.getPeerConfigs();

    assertTrue(peerCfgs.containsKey(InetAddresses.forString("192.168.1.2")));
    assertFalse(
            peerCfgs.get(InetAddresses.forString("192.168.1.2")).getPublishAllow().contains(RecordType.Audit));
    assertFalse(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getPublishAllow()
            .contains(RecordType.Journal));
    assertTrue(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getPublishAllow().contains(RecordType.Log));
    assertFalse(
            peerCfgs.get(InetAddresses.forString("192.168.1.2")).getSubscribeAllow().contains(RecordType.Log));
    assertFalse(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getSubscribeAllow()
            .contains(RecordType.Journal));
    assertTrue(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getSubscribeAllow()
            .contains(RecordType.Audit));

    peer2.remove("subscribeAllow");

    JSONArray subAllows = new JSONArray();
    subAllows.add("journal");

    peer2.put("subscribeAllow", subAllows);

    cfg.updateKnownHosts(peer2);

    peerCfgs = cfg.getPeerConfigs();

    assertTrue(peerCfgs.containsKey(InetAddresses.forString("192.168.1.2")));
    assertFalse(
            peerCfgs.get(InetAddresses.forString("192.168.1.2")).getPublishAllow().contains(RecordType.Audit));
    assertFalse(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getPublishAllow()
            .contains(RecordType.Journal));
    assertTrue(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getPublishAllow().contains(RecordType.Log));
    assertFalse(
            peerCfgs.get(InetAddresses.forString("192.168.1.2")).getSubscribeAllow().contains(RecordType.Log));
    assertTrue(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getSubscribeAllow()
            .contains(RecordType.Journal));
    assertTrue(peerCfgs.get(InetAddresses.forString("192.168.1.2")).getSubscribeAllow()
            .contains(RecordType.Audit));
}

From source file:com.fujitsu.dc.core.model.impl.es.DavCmpEsImpl.java

@Override
@SuppressWarnings("unchecked")
public final ResponseBuilder acl(final Reader reader) {
    // ???????????
    Acl aclToSet = null;/*w  w  w .ja va  2s.co  m*/
    try {
        aclToSet = ObjectIo.unmarshal(reader, Acl.class);
    } catch (Exception e1) {
        throw DcCoreException.Dav.XML_CONTENT_ERROR.reason(e1);
    }
    if (!aclToSet.validateAcl(isCellLevel())) {
        throw DcCoreException.Dav.XML_VALIDATE_ERROR;
    }
    JSONParser parser = new JSONParser();
    JSONObject aclJson = null;
    try {
        aclJson = (JSONObject) parser.parse(aclToSet.toJSON());
    } catch (ParseException e) {
        throw DcCoreException.Dav.XML_ERROR.reason(e);
    }
    // 
    Lock lock = this.lock();
    try {
        // ACL?xml:base???
        Object objAclBase = aclJson.get(KEY_ACL_BASE);
        String aclBase = null;
        if (objAclBase != null) {
            aclBase = (String) objAclBase;
        }

        // principal?href ? ??Name  ID__id ???
        Object jsonObj = aclJson.get(KEY_ACE);
        JSONArray array = new JSONArray();
        if (jsonObj instanceof JSONObject) {
            array.add(jsonObj);
        } else {
            array = (JSONArray) jsonObj;
        }
        if (array != null) {
            for (Object ace : (JSONArray) array) {
                JSONObject aceJson = (JSONObject) ace;
                JSONObject principal = (JSONObject) aceJson.get(KEY_ACL_PRINCIPAL);
                if (principal.get(KEY_ACL_HREF) != null) {
                    principal.put(KEY_ACL_HREF,
                            roleResourceUrlToId((String) principal.get(KEY_ACL_HREF), aclBase));
                } else if (principal.get(KEY_ACL_ALL) != null) {
                    principal.put(KEY_ACL_ALL, null);
                }

            }
        }
        // ES?xm:base????
        aclJson.remove(KEY_ACL_BASE);
        setAclToJson(aclJson);
        // ????
        DcIndexResponse resp = updateNode();
        this.version = resp.getVersion();
        this.acl = aclToSet;
        // ?
        return javax.ws.rs.core.Response.status(HttpStatus.SC_OK).header(HttpHeaders.ETAG, this.getEtag());
    } finally {
        lock.release();
    }
}

From source file:i5.las2peer.services.mobsos.SurveyService.java

/**
 * TODO: write documentation/*from w w w . jav  a2  s .  c  o m*/
 * 
 * @param form
 * @param response
 * @return
 */
private JSONObject validateResponse(Document form, JSONObject response) {
    JSONObject result = new JSONObject();

    JSONObject questions = extractQuestionInformation(form);

    // then iterate over all question items in the submitted answer and check, if 
    // they fulfill all constraints.

    Iterator<String> ait = response.keySet().iterator();
    while (ait.hasNext()) {

        String qid = ait.next();
        String qval = (String) response.get(qid);

        //System.out.println("Submitted Question ID: "+q.getAttribute("qid"));

        // if question provided in answer is not contained in questionnaire, the answer does not match the questionnaire.
        if (!questions.keySet().contains(qid)) {
            throw new IllegalArgumentException("Questionnaire answer does not match form! Question ID " + qid
                    + " is not defined in questionnaire.");
        }

        // if question provided in answer is contained in questionnaire, check further properties...
        JSONObject question = (JSONObject) questions.get(qid);

        // for each type check further constraints
        String type = (String) question.get("type");
        if (type.equals("qu:DichotomousQuestionPageType")) {

            // for dichotomous questions the only two possible answers are 0 and 1.
            if (!qval.equals("0") && !qval.equals("1")) {
                throw new IllegalArgumentException(
                        "Questionnaire answer does not match questionnaire! The value submitted for question "
                                + qid + " is expected to be either 0 or 1, but was " + qval + "!");
            } else {
                // everything is ok with this question answer.
                // remove entry from hashtable, write entry to result object
                questions.remove(qid);
                result.put(qid, qval);
            }
        } else if (type.equals("qu:OrdinalScaleQuestionPageType")) {
            // for ordinal scale questions the answer must be parseable as an integer,
            // which is 
            try {
                int qvali = Integer.parseInt(qval);

                if (qvali > (int) question.get("maxval") || qvali < (int) question.get("minval")) {
                    throw new IllegalArgumentException(
                            "Questionnaire answer does not match questionnaire! The value submitted for question "
                                    + qid + " is expected to be between " + question.get("minval") + " and "
                                    + question.get("maxval") + ", but was " + qvali + "!");
                } else {
                    // everything is ok with this question answer.
                    // remove entry from hashtable
                    questions.remove(qid);
                    result.put(qid, qval);
                }
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException(
                        "Questionnaire answer does not match questionnaire! The value submitted for question "
                                + qid + " is expected to be parseable as an integer!");
            }

        } else if (type.equals("qu:FreeTextQuestionPageType")) {
            // nothing to check for freetext question pages. Any text can be entered.
            questions.remove(qid);
            result.put(qid, qval);
        }

    }

    Iterator<String> remainingqids = questions.keySet().iterator();
    while (remainingqids.hasNext()) {
        String qid = (String) remainingqids.next();
        int requireds = (int) ((JSONObject) questions.get(qid)).get("required");
        if (requireds == 1) {
            throw new IllegalArgumentException(
                    "Questionnaire answer does not match questionnaire! The mandatory question " + qid
                            + " was not answered!");
        }
    }
    return result;
}

From source file:org.apache.metron.parsers.asa.GrokAsaParser.java

@Override
public List<JSONObject> parse(byte[] raw_message) {

    String toParse = "";
    JSONObject toReturn;
    List<JSONObject> messages = new ArrayList<>();
    try {//from w  w w  . ja v  a2s. c om

        toParse = new String(raw_message, "UTF-8");

        System.out.println("Received message: " + toParse);

        Match gm = grok.match(toParse);
        gm.captures();

        toReturn = new JSONObject();

        toReturn.putAll(gm.toMap());

        String str = toReturn.get("ciscotag").toString();
        String pattern = patternMap.get(str);

        Map<String, Object> response = getMap(pattern, toParse);

        toReturn.putAll(response);

        //System.out.println("*******I MAPPED: " + toReturn);
        long timestamp = convertToEpoch(toReturn.get("MONTH").toString(), toReturn.get("MONTHDAY").toString(),
                toReturn.get("TIME").toString(), true);
        toReturn.put("timestamp", timestamp);

        toReturn.remove("MONTHDAY");
        toReturn.remove("TIME");
        toReturn.remove("MINUTE");
        toReturn.remove("HOUR");
        toReturn.remove("YEAR");
        toReturn.remove("SECOND");

        toReturn.put("ip_src_addr", toReturn.remove("IPORHOST"));
        toReturn.put("original_string", toParse);
        messages.add(toReturn);
        return messages;

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

}

From source file:org.apache.metron.parsers.GrokParser.java

@SuppressWarnings("unchecked")
private Optional<MessageParserResult<JSONObject>> parseMultiLine(byte[] rawMessage) {
    List<JSONObject> messages = new ArrayList<>();
    Map<Object, Throwable> errors = new HashMap<>();
    String originalMessage = null;
    // read the incoming raw data as if it may have multiple lines of logs
    // if there is only only one line, it will just get processed.
    try (BufferedReader reader = new BufferedReader(
            new StringReader(new String(rawMessage, StandardCharsets.UTF_8)))) {
        while ((originalMessage = reader.readLine()) != null) {
            LOG.debug("Grok parser parsing message: {}", originalMessage);
            try {
                Match gm = grok.match(originalMessage);
                gm.captures();//www .j  ava 2  s .  com
                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);
                    continue;
                }
                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);
                errors.put(originalMessage, e);
            }
        }
    } catch (IOException 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<>(messages, errors));
}