Example usage for org.json.simple JSONObject toString

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

Introduction

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

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:anotadorderelacoes.model.UtilidadesPacotes.java

/**
 * Converte um arquivo de sada do parser PALAVRAS para o formato JSON
 * aceito pela ARS.// www  .  j a va  2s  . c  o  m
 *
 * @param arquivoPalavras Arquivo resultante do parser PALAVRAS
 * @param arquivoSaida Arquivo de texto convertido para o formato JSON
 */
public static void conveterPalavrasJson(File arquivoPalavras, File arquivoSaida) {

    BufferedReader br;
    BufferedWriter bw;
    String linha;
    int contadorSentencas = 1;

    JSONObject sentenca = new JSONObject();
    JSONArray tokens = new JSONArray();

    sentenca.put("id", contadorSentencas++);
    sentenca.put("texto", "");
    sentenca.put("comentarios", "");

    sentenca.put("termos", new JSONArray());
    sentenca.put("relacoes", new JSONArray());
    sentenca.put("anotadores", new JSONArray());

    sentenca.put("anotada", false);
    sentenca.put("ignorada", false);

    try {

        //br = new BufferedReader( new FileReader( arquivoPalavras ) );
        br = new BufferedReader(new InputStreamReader(new FileInputStream(arquivoPalavras), "UTF-8"));
        //bw = new BufferedWriter( new FileWriter( arquivoSaida ) );
        bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(arquivoSaida), "UTF-8"));

        bw.write("# Arquivo \"" + arquivoPalavras.getName() + "\" convertido para o formato JSON\n");
        bw.write("===\n");

        while ((linha = br.readLine()) != null) {

            //System.out.println( "DEBUG: " + linha );

            // Fim de uma sentena
            if (linha.equals("</s>")) {

                String texto = "";
                for (Object token : tokens)
                    texto += ((JSONObject) token).get("t") + " ";
                texto = texto.substring(0, texto.length() - 1);
                sentenca.put("texto", texto);

                sentenca.put("tokens", tokens);
                bw.write(sentenca.toString() + "\n");

                sentenca = new JSONObject();
                tokens = new JSONArray();
                sentenca.put("id", contadorSentencas++);
                sentenca.put("texto", "");
                sentenca.put("comentarios", "");
                sentenca.put("termos", new JSONArray());
                sentenca.put("relacoes", new JSONArray());
                sentenca.put("anotadores", new JSONArray());
                sentenca.put("anotada", false);
                sentenca.put("ignorada", false);

            }

            // Lendo uma sentena
            // Transformaes adaptadas do script "criar-pacotes.pl"
            else {

                linha = linha.replace("", "<<");
                linha = linha.replace("", ">>");
                linha = linha.replace("", "o");

                Matcher matcher;

                // Apenas para tratar as sentenas que tm "secretaria" (e.g. 96524)
                if (linha.matches("(.*\\t.*)\\t.*")) {
                    matcher = Pattern.compile("(.*\\t.*)\\t.*").matcher(linha);
                    matcher.find();
                    linha = matcher.group(1);
                }

                //if ( linha.matches( "<s id=\"(\\d+)\">" ) ) {
                if (patterns[0].matcher(linha).find()) {
                    matcher = Pattern.compile("<s id=\"(\\d+)\">").matcher(linha);
                    matcher.find();
                    sentenca.put("id", matcher.group(1));
                } else if (linha.startsWith("$,")) {
                    tokens.add(novoToken(",", ",", null, null));
                }
                //else if ( linha.matches( "^\\$(.)$" ) ) {
                else if (patterns[1].matcher(linha).find()) {
                    matcher = Pattern.compile("^\\$(.)$").matcher(linha);
                    matcher.find();
                    tokens.add(novoToken(matcher.group(1), matcher.group(1), null, null));
                }
                //                    else if ( linha.matches( "^\\$(..)" ) ) {
                else if (patterns[2].matcher(linha).find()) {
                    matcher = Pattern.compile("^\\$(..)").matcher(linha);
                    matcher.find();
                    tokens.add(novoToken(matcher.group(1), matcher.group(1), null, null));
                }
                //                    else if ( linha.matches( "^\\$(%)" ) ) {
                else if (patterns[3].matcher(linha).find()) {
                    matcher = Pattern.compile("^\\$(%)").matcher(linha);
                    matcher.find();
                    tokens.add(novoToken(matcher.group(1), matcher.group(1), null, null));
                }
                // Linha normal
                //                    else if ( linha.matches( "^(.*)\\t ?\\[([^\\]]+)\\] ([^@]+) (@.*)$" ) ) {
                else if (patterns[4].matcher(linha).find()) {
                    matcher = Pattern.compile("^(.*)\\t ?\\[([^\\]]+)\\] ([^@]+) (@.*)$").matcher(linha);
                    matcher.find();
                    tokens.add(
                            novoToken(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4)));
                }
                // Alguns tokens no tm a tag sinttica
                //                    else if ( linha.matches( "^(.*)\\t ?\\[([^\\]]+)\\] ([^@]+)$" ) ) {
                else if (patterns[5].matcher(linha).find()) {
                    matcher = Pattern.compile("^(.*)\\t ?\\[([^\\]]+)\\] ([^@]+)$").matcher(linha);
                    matcher.find();
                    tokens.add(novoToken(matcher.group(1), matcher.group(2), matcher.group(3), null));
                }
                // E alguns no tm o lema
                //                    else if ( linha.matches( "^(.*)\\t ?([^@]+) (@.*)$" ) ) {
                else if (patterns[6].matcher(linha).find()) {
                    matcher = Pattern.compile("^(.*)\\t ?([^@]+) (@.*)$").matcher(linha);
                    matcher.find();
                    tokens.add(novoToken(matcher.group(1), null, matcher.group(2), matcher.group(3)));
                }
                // s vezes tem alguns tokens que vm sem nada, so tratados como pontuao
                //                    else if ( linha.matches( "^(.*)$" ) ) {
                else if (patterns[7].matcher(linha).find()) {
                    matcher = Pattern.compile("^(.*)$").matcher(linha);
                    matcher.find();
                    tokens.add(novoToken(matcher.group(1), matcher.group(2), null, null));
                } else {
                    System.out.println("PROBLEMA!");
                    System.out.println(linha);
                }

            }
        }

        String texto = "";
        for (Object token : tokens)
            texto += ((JSONObject) token).get("t") + " ";
        texto = texto.substring(0, texto.length() - 1);
        sentenca.put("texto", texto);

        sentenca.put("tokens", tokens);
        bw.write(sentenca.toString() + "\n");

        bw.close();
        br.close();

        Logger.getLogger("ARS logger").log(Level.INFO, "Arquivo JSON \"{0}\" gravado.",
                arquivoSaida.getAbsolutePath());

    } catch (FileNotFoundException ex) {
        Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex);
    }

}

From source file:com.ba.forms.receipt.BAReceiptAction.java

public ActionForward baGet(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONObject json = new JSONObject();
    BAReceiptDTO dto = new BAReceiptDTO();
    try {/*from ww w .  j av a  2 s  .  c  om*/
        logger.info(" get method starts here");
        String advanceId = request.getParameter("search");
        HashMap hashMpReceiptDet = BAReceiptFactory.getInstanceOfBAReceiptFactory().getReceiptDtls(advanceId);
        json.put("exception", "");
        json.put("ReceiptDets", hashMpReceiptDet);
        json.put("ReceiptExit", hashMpReceiptDet.size());

        //                 logger.warn("strCurrent PageNo ------------->"+objPageCount);
    } catch (Exception ex) {
        logger.error("The Exception is  :" + ex);
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    }
    response.getWriter().write(json.toString());
    return null;

}

From source file:com.ba.forms.bookingForm.BABookingAction.java

public ActionForward baGet(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONObject json = new JSONObject();
    BABookingDTO vo = new BABookingDTO();

    try {/*from w  w  w .j a v  a 2 s .  co  m*/
        logger.info(" get method starts here");
        String foodId = request.getParameter("search");
        HashMap hashMpBookingDet = BABookingFactory.getInstanceOfBABookingFactory().getBookingDtls(foodId);
        json.put("exception", "");
        json.put("BookingDets", hashMpBookingDet);
        json.put("BookingExit", hashMpBookingDet.size());

        //  logger.warn("strCurrent PageNo ------------->"+objPageCount);
    } catch (Exception ex) {
        logger.error("The Exception is  :" + ex);
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    }
    response.getWriter().write(json.toString());
    return null;

}

From source file:io.openvidu.java.client.Session.java

@SuppressWarnings("unchecked")
private void getSessionIdHttp() throws OpenViduJavaClientException, OpenViduHttpException {
    if (this.hasSessionId()) {
        return;/*w  w w  .ja  v a2 s. co  m*/
    }

    HttpPost request = new HttpPost(OpenVidu.urlOpenViduServer + OpenVidu.API_SESSIONS);

    JSONObject json = new JSONObject();
    json.put("mediaMode", properties.mediaMode().name());
    json.put("recordingMode", properties.recordingMode().name());
    json.put("defaultOutputMode", properties.defaultOutputMode().name());
    json.put("defaultRecordingLayout", properties.defaultRecordingLayout().name());
    json.put("defaultCustomLayout", properties.defaultCustomLayout());
    json.put("customSessionId", properties.customSessionId());
    StringEntity params = null;
    try {
        params = new StringEntity(json.toString());
    } catch (UnsupportedEncodingException e1) {
        throw new OpenViduJavaClientException(e1.getMessage(), e1.getCause());
    }

    request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    request.setEntity(params);

    HttpResponse response;
    try {
        response = OpenVidu.httpClient.execute(request);
    } catch (IOException e2) {
        throw new OpenViduJavaClientException(e2.getMessage(), e2.getCause());
    }
    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
            JSONObject responseJson = httpResponseToJson(response);
            this.sessionId = (String) responseJson.get("id");
            this.createdAt = (long) responseJson.get("createdAt");
            log.info("Session '{}' created", this.sessionId);
        } else if (statusCode == org.apache.http.HttpStatus.SC_CONFLICT) {
            // 'customSessionId' already existed
            this.sessionId = properties.customSessionId();
        } else {
            throw new OpenViduHttpException(statusCode);
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}

From source file:jp.aegif.nemaki.rest.GroupResource.java

@DELETE
@Path("/delete/{id}")
@Produces(MediaType.APPLICATION_JSON)//w w  w . j a  v  a  2  s  .c  o m
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String delete(@PathParam("repositoryId") String repositoryId, @PathParam("id") String groupId) {

    boolean status = true;
    JSONObject result = new JSONObject();
    JSONArray errMsg = new JSONArray();

    //Existing group
    Group group = principalService.getGroupById(repositoryId, groupId);
    if (group == null) {
        status = false;
        addErrMsg(errMsg, ITEM_GROUP, ErrorCode.ERR_NOTFOUND);
    }

    //Delete the group
    if (status) {
        try {
            principalService.deleteGroup(repositoryId, group.getId());
        } catch (Exception ex) {
            addErrMsg(errMsg, ITEM_GROUP, ErrorCode.ERR_DELETE);
        }
    }
    result = makeResult(status, result, errMsg);
    return result.toString();
}

From source file:jp.aegif.nemaki.rest.GroupResource.java

@SuppressWarnings("unchecked")
@GET/*from   w ww . j a  v a2 s  . c o m*/
@Path("/list")
@Produces(MediaType.APPLICATION_JSON)
public String list(@PathParam("repositoryId") String repositoryId) {
    boolean status = true;
    JSONObject result = new JSONObject();
    JSONArray listJSON = new JSONArray();
    JSONArray errMsg = new JSONArray();

    List<Group> groupList;
    try {
        groupList = principalService.getGroups(repositoryId);
        for (Group group : groupList) {
            JSONObject groupJSON = convertGroupToJson(group);
            listJSON.add(groupJSON);
        }
        result.put(ITEM_ALLGROUPS, listJSON);
    } catch (Exception ex) {
        ex.printStackTrace();
        addErrMsg(errMsg, ITEM_ALLGROUPS, ErrorCode.ERR_LIST);
    }
    result = makeResult(status, result, errMsg);
    return result.toString();
}

From source file:com.ba.forms.advanceBookingForm.BAAdvanceBookingAction.java

public ActionForward baGet(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONObject json = new JSONObject();
    BAAdvanceBookingDTO dto = new BAAdvanceBookingDTO();
    try {//w w  w.ja  va  2 s . c o  m
        logger.info(" get method starts here");
        String advanceId = request.getParameter("search");
        HashMap hashMpAdvanceBookingDet = BAAdvanceBookingFactory.getInstanceOfBAAdvanceBookingFactory1()
                .getAdvanceBookingDtls(advanceId);
        json.put("exception", "");
        json.put("AdvanceBookingDets", hashMpAdvanceBookingDet);
        json.put("AdvanceBookingExit", hashMpAdvanceBookingDet.size());

        //                 logger.warn("strCurrent PageNo ------------->"+objPageCount);
    } catch (Exception ex) {
        logger.error("The Exception is  :" + ex);
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    }
    response.getWriter().write(json.toString());
    return null;

}

From source file:control.ParametrizacionServlets.InsertarActParamFisicoquimicos.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w w w  .  j  a  va 2 s . c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    JSONObject respError = new JSONObject();

    try {

        //Obtenemos los datos enviados.
        String mayorInicial = request.getParameter("mayorInicial");
        String mayorFinal = request.getParameter("mayorFinal");
        Double rangoFinal = Double.parseDouble(request.getParameter("rangoFinal"));
        Double rangoInicial = Double.parseDouble(request.getParameter("rangoInicial"));
        Integer parametro = Integer.parseInt(request.getParameter("parametro"));
        Integer actividad = Integer.parseInt(request.getParameter("actividad"));
        String mostrarRango = request.getParameter("mostrarRango");

        //Creamos el manager para registrar la informacion
        ActParamFisicoquimicos manager = new ActParamFisicoquimicos();

        respError = manager.insertar(actividad, parametro, rangoInicial, rangoFinal, mayorInicial, mayorFinal,
                mostrarRango);

        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");
        response.getWriter().write(respError.toString());

    } catch (Exception ex) {
        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");
        respError.put("error", 0);
        response.getWriter().write(respError.toString());
    }

}

From source file:com.ba.forms.settlement.BASettlementAction.java

public ActionForward getRoomRentDets(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONObject json = new JSONObject();
    BASettlementDTO vo = new BASettlementDTO();

    try {/*w w  w .j a v a2s .  c om*/
        logger.info(" get method starts here");
        String roomId = request.getParameter("roomId");
        String bookingId = request.getParameter("bookingId");
        HashMap hashMpRoomTariffDet = BASettlementFactory.getInstanceOfBASettlementFactory()
                .getRoomRentDets(bookingId, roomId);
        json.put("exception", "");
        json.put("SettlementDets", hashMpRoomTariffDet);
        json.put("SettlementExit", hashMpRoomTariffDet.size());

        logger.warn("strCurrent PageNo ------------->" + objPageCount);
    } catch (Exception ex) {
        logger.error("The Exception is  :" + ex);
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    }
    response.getWriter().write(json.toString());
    return null;

}

From source file:com.ba.forms.settlement.BASettlementAction.java

public ActionForward baGet(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONObject json = new JSONObject();
    BASettlementDTO vo = new BASettlementDTO();

    try {//  w w  w  .  j a v  a 2 s  .c  o m
        logger.info(" get method starts here");
        String roomId = request.getParameter("roomId");
        String bookingId = request.getParameter("bookingId");
        HashMap hashMpSettlementDet = BASettlementFactory.getInstanceOfBASettlementFactory()
                .getSettlementDtls(bookingId, roomId);
        json.put("exception", "");
        json.put("SettlementDets", hashMpSettlementDet);
        json.put("SettlementExit", hashMpSettlementDet.size());

        logger.warn("strCurrent PageNo ------------->" + objPageCount);
    } catch (Exception ex) {
        logger.error("The Exception is  :" + ex);
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    }
    response.getWriter().write(json.toString());
    return null;

}