Example usage for com.google.gson JsonObject toString

List of usage examples for com.google.gson JsonObject toString

Introduction

In this page you can find the example usage for com.google.gson JsonObject toString.

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:com.elasticrtc.tutorial.recording.ws.RecorderHandler.java

License:Apache License

public void sendPlayEnd(WebSocketSession session, MediaPipeline pipeline) {
    try {/*from   ww w.  ja  v a  2  s.c  o  m*/
        JsonObject response = new JsonObject();
        response.addProperty("id", "playEnd");
        session.sendMessage(new TextMessage(response.toString()));
    } catch (IOException e) {
        log.error("Error sending playEndOfStream message", e);
    }
    // Release pipeline
    pipeline.release();
}

From source file:com.ericsson.eiffel.remrem.publish.controller.ProducerController.java

License:Apache License

/**
 * This controller provides single RemRem REST API End Point for both RemRem
 * Generate and Publish./*from ww  w  .  j  a v a  2 s  . c  om*/
 *
 * @param msgProtocol
 *            message protocol (required)
 * @param msgType
 *            message type (required)
 * @param userDomain
 *            user domain (not required)
 * @param tag
 *            (not required)
 * @param routingKey
 *            (not required)
 * @param parseData
 *            (not required, default=false)
 * @return A response entity which contains http status and result
 *
 * @use A typical CURL command: curl -H "Content-Type: application/json" -X POST
 *      --data "@inputGenerate_activity_finished.txt"
 *      "http://localhost:8986/generateAndPublish/?mp=eiffelsemantics&msgType=EiffelActivityFinished"
 */

@SuppressWarnings({ "rawtypes", "unchecked" })
@ApiOperation(value = "To generate and publish eiffel event to message bus", response = String.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Event sent successfully"),
        @ApiResponse(code = 400, message = "Invalid event content"),
        @ApiResponse(code = 404, message = "RabbitMq properties not found"),
        @ApiResponse(code = 500, message = "Internal server error"),
        @ApiResponse(code = 503, message = "Message protocol is invalid") })
@RequestMapping(value = "/generateAndPublish", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity generateAndPublish(
        @ApiParam(value = "message protocol", required = true) @RequestParam(value = "mp") final String msgProtocol,
        @ApiParam(value = "message type", required = true) @RequestParam("msgType") final String msgType,
        @ApiParam(value = "user domain") @RequestParam(value = "ud", required = false) final String userDomain,
        @ApiParam(value = "tag") @RequestParam(value = "tag", required = false) final String tag,
        @ApiParam(value = "routing key") @RequestParam(value = "rk", required = false) final String routingKey,
        @ApiParam(value = "parse data") @RequestParam(value = "parseData", required = false, defaultValue = "false") final Boolean parseData,
        @ApiParam(value = "JSON message", required = true) @RequestBody final JsonObject bodyJson) {

    String bodyJsonOut = null;
    if (parseData) {
        // -- parse params in incoming request -> body -------------
        EventTemplateHandler eventTemplateHandler = new EventTemplateHandler();
        JsonNode parsedTemplate = eventTemplateHandler.eventTemplateParser(bodyJson.toString(), msgType);
        bodyJsonOut = parsedTemplate.toString();
        log.info("Parsed template: " + bodyJsonOut);
    } else {
        bodyJsonOut = bodyJson.toString();
    }

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<>(bodyJsonOut, headers);

    try {
        ResponseEntity<String> response = restTemplate.postForEntity(generateURLTemplate.getUrl(), entity,
                String.class, generateURLTemplate.getMap(msgProtocol, msgType));

        if (response.getStatusCode() == HttpStatus.OK) {
            log.info("The result from REMReM Generate is: " + response.getStatusCodeValue());

            // publishing requires an array if you want status code
            String responseBody = "[" + response.getBody() + "]";
            MsgService msgService = PublishUtils.getMessageService(msgProtocol, msgServices);

            log.debug("mp: " + msgProtocol);
            log.debug("body: " + responseBody);
            log.debug("user domain suffix: " + userDomain + " tag: " + tag + " routing key: " + routingKey);
            if (msgService != null && msgProtocol != null) {
                rmqHelper.rabbitMqPropertiesInit(msgProtocol);
            }
            SendResult result = messageService.send(responseBody, msgService, userDomain, tag, routingKey);
            return new ResponseEntity(result, messageService.getHttpStatus());
        } else {
            return response;
        }
    } catch (RemRemPublishException e) {
        return new ResponseEntity(e.getMessage(), HttpStatus.NOT_FOUND);
    } catch (Exception e) {
        log.info("The result from REMReM Generate is not OK and have value: " + e.getMessage());
        if (e.getMessage().startsWith(Integer.toString(HttpStatus.BAD_REQUEST.value()))) {
            return new ResponseEntity(parser.parse(RemremPublishServiceConstants.GENERATE_BAD_REQUEST),
                    HttpStatus.BAD_REQUEST);
        } else if (e.getMessage().startsWith(Integer.toString(HttpStatus.SERVICE_UNAVAILABLE.value()))) {
            return new ResponseEntity(parser.parse(RemremPublishServiceConstants.GENERATE_NO_SERVICE_ERROR),
                    HttpStatus.SERVICE_UNAVAILABLE);
        } else if (e.getMessage().startsWith(Integer.toString(HttpStatus.UNAUTHORIZED.value()))) {
            return new ResponseEntity(parser.parse(RemremPublishServiceConstants.GENERATE_UNAUTHORIZED),
                    HttpStatus.UNAUTHORIZED);
        } else {
            return new ResponseEntity(parser.parse(RemremPublishServiceConstants.GENERATE_INTERNAL_ERROR),
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:com.ericsson.eiffel.remrem.semantics.schemas.SchemaFile.java

License:Apache License

/**
 * @param jsonFileName/*from w w  w . ja  va  2  s .  co  m*/
 *            -name of the input json file is to be created is an input
 *            parameter to this method
 * @param jsonObject
 *            -josnObject having required properties to generate events is
 *            an input parameter to this method
 */
public void createNewInputJsonSchema(String jsonFileName, JsonObject jsonObject) {
    String currentWorkingDir = EiffelConstants.USER_DIR;
    FileWriter writer = null;
    String copyFilePath = currentWorkingDir + File.separator + EiffelConstants.INPUT_EIFFEL_SCHEMAS;
    String newFileName = copyFilePath + File.separator + jsonFileName + EiffelConstants.JSON_MIME_TYPE;
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonParser jp = new JsonParser();
    JsonElement je = jp.parse(jsonObject.toString());
    String prettyJsonString = gson.toJson(je);
    try {
        writer = new FileWriter(newFileName);
        writer.write(prettyJsonString);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            writer.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.ericsson.eiffel.remrem.semantics.SemanticsService.java

License:Apache License

private String createErrorResponse(final String message, final String cause) {
    JsonObject errorResponse = new JsonObject();
    errorResponse.addProperty(MESSAGE, message);
    errorResponse.addProperty(CAUSE, cause.replace("\n", ""));
    return errorResponse.toString();
}

From source file:com.ericsson.eiffel.remrem.semantics.SemanticsService.java

License:Apache License

private String createErrorResponse(final String message, final ArrayList<String> supportedEventTypes) {
    JsonObject errorResponse = new JsonObject();
    errorResponse.addProperty(RESULT, ERROR);
    errorResponse.addProperty(MESSAGE, UNKNOWN_EVENT_TYPE_REQUESTED + "  -  " + message);
    errorResponse.addProperty(SUPPORTED_EVENT_TYPES, supportedEventTypes.toString());
    return errorResponse.toString();
}

From source file:com.ericsson.eiffel.remrem.semantics.validator.EiffelValidator.java

License:Apache License

public void validate(JsonObject jsonObjectInput) throws EiffelValidationException {
    try {//  ww w  .j  a  v a  2  s.c  o  m
        ProcessingReport report = validationSchema.validate(JsonLoader.fromString(jsonObjectInput.toString()));
        if (!report.isSuccess()) {
            log.warn(jsonObjectInput.toString());
            throw new EiffelValidationException(getErrorsList(report));
        }
        log.debug("VALIDATED. Schema used: {}", schemaResourceName);
    } catch (Exception e) {
        String message = "Cannot validate given JSON string";
        log.debug(message, e);
        throw new EiffelValidationException(message, e);
    }
}

From source file:com.ethos.business.general.ModuloEtudiantes.java

public String guardarRegistroModuloEstudiantes(JsonObject registro) throws ParseException {
    System.out.println("kkkkkkkkkk");
    String respuesta = "NOK";

    JsonObject perioAcaJsonObject;//w ww.  java 2s  .c om
    JsonObject datosJsonObject;
    JsonObject paisEsculaJsonObject;
    JsonObject departamentoEstudioJsonObject;
    JsonObject ciudadEscuelaJsonObject;
    JsonObject fechaGraduacionJsonObject;
    JsonObject categoriSisbenperioAcaJsonObject;
    JsonObject fondoPensionesJsonObject;
    JsonObject epsJsonObject;
    SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/yyyy");

    EstudianteModel estudiantemodel = new EstudianteModel();

    perioAcaJsonObject = registro.get("periodoAca").getAsJsonObject();
    datosJsonObject = registro.getAsJsonObject();
    System.out.println(datosJsonObject.toString());
    paisEsculaJsonObject = registro.get("paisEscuela").getAsJsonObject();
    departamentoEstudioJsonObject = registro.get("depEscuela").getAsJsonObject();
    ciudadEscuelaJsonObject = registro.get("ciudad").getAsJsonObject();
    categoriSisbenperioAcaJsonObject = registro.get("sisben").getAsJsonObject();
    epsJsonObject = registro.get("eps").getAsJsonObject();

    estudiantemodel.setIdPeriodoAcademico(perioAcaJsonObject.get("idCodigo").getAsInt());
    estudiantemodel.setNomEscuelaSecun(datosJsonObject.get("nomEscu").getAsString());
    estudiantemodel.setIdPaisSecundaria(paisEsculaJsonObject.get("sCodigo").getAsInt());
    estudiantemodel.setIdDptoSecundaria(departamentoEstudioJsonObject.get("sCodigo").getAsInt());
    estudiantemodel.setIdCiudadEscuela(ciudadEscuelaJsonObject.get("sCodigo").getAsInt());
    estudiantemodel.setFechaGradoSecunda(formatoFecha.parse(datosJsonObject.get("fecGraSec").getAsString()));
    estudiantemodel.setiCategoriaSisben(categoriSisbenperioAcaJsonObject.get("iIdCategoriaSisben").getAsInt());
    estudiantemodel.setFondoPensiones(datosJsonObject.get("pensCesantias").getAsString());
    estudiantemodel.setIdEps(epsJsonObject.get("id_Eps").getAsInt());

    int peri = estudiantemodel.getIdPeriodoAcademico();
    String n = estudiantemodel.getNomEscuelaSecun();
    int p = estudiantemodel.getIdPaisSecundaria();
    int d = estudiantemodel.getIdDptoSecundaria();
    int c = estudiantemodel.getIdCiudadEscuela();
    Date f = estudiantemodel.getFechaGradoSecunda();
    int ca = estudiantemodel.getiCategoriaSisben();
    String pen = estudiantemodel.getFondoPensiones();
    int e = estudiantemodel.getIdEps();

    String resultadoGuardarDatos = moduloCompleEstudiante.insert(estudiantemodel);
    String r = estudiantemodel.getNomEscuelaSecun();
    System.out.println("Imprimir......" + r + "," + peri + "," + p + "," + d + "," + c + "," + f.toString()
            + ",z " + ca + "," + pen + "," + e);
    System.out.println("resultado......" + resultadoGuardarDatos);
    return respuesta;
}

From source file:com.ethos.control.general.LoginControl.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w w w . j ava2  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 {

    HttpSession session = request.getSession();

    String json = " ";
    String respuesta = "";

    HashMap mapDataUser;
    ValidaLogin validaLogin = new ValidaLogin();
    try {
        JsonObject dataJson;
        FuncionesGenerales funcion = new FuncionesGenerales();
        BufferedReader reader = request.getReader();
        dataJson = funcion.recibirDatos(reader);
        //            System.out.println("json " + dataJson);

        if (!dataJson.toString().equalsIgnoreCase("{}")) {

            mapDataUser = validaLogin.autenticarCredenciales(dataJson);
            session.setAttribute("idUser", mapDataUser.get("idUser").toString());
            session.setAttribute("codUser", mapDataUser.get("codUser").toString());
            session.setAttribute("idPerfil", mapDataUser.get("idPerfil").toString());
            respuesta = mapDataUser.get("respuesta").toString();
            session.setMaxInactiveInterval(5 * 60);
            System.out.println("TIMEOUT: " + session.getMaxInactiveInterval());
            json = new Gson().toJson(respuesta);

        } else {
            session.invalidate();
            json = new Gson().toJson("Por favor ingresar sus credenciales");
        }
    } catch (Exception e) {
        session.invalidate();
        System.out.println("Error en LoginControl al validar credenciales: " + e);
    }

    response.setContentType("application/json;charset=Utf-8");
    response.getWriter().write(json);
}

From source file:com.eventual.singleton.Administracion.java

@Override
public void notificarNumeroUsuarios() {
    JsonObject notificacion = new JsonObject();
    administradores.values().forEach((admin) -> {
        try {//from w  ww . j  av  a 2s  .co m
            notificacion.addProperty("tipo", "CONECTADOS");
            notificacion.addProperty("conectados", this.chat.getConectados().size());
            admin.getSesion().getBasicRemote().sendText(notificacion.toString());
        } catch (IOException ex) {
            Logger.getLogger(Administracion.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
}

From source file:com.eventual.singleton.Administracion.java

@Override
public void notificarNumeroMensajes() {
    JsonObject notificacion = new JsonObject();
    administradores.values().forEach((u) -> {
        try {/*from   www.ja  v  a 2  s.  co m*/
            notificacion.addProperty("tipo", "NUMERO_MENSAJES");
            u.getSesion().getBasicRemote().sendText(notificacion.toString());
        } catch (IOException ex) {
            Logger.getLogger(Administracion.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
}