Example usage for org.json JSONObject append

List of usage examples for org.json JSONObject append

Introduction

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

Prototype

public JSONObject append(String key, Object value) throws JSONException 

Source Link

Document

Append values to the array under a key.

Usage

From source file:biblivre3.cataloging.bibliographic.RecordDTO.java

@Override
public JSONObject toJSONObject(Properties properties) {
    JSONObject data = new JSONObject();
    try {/*from ww w.  j  a v a  2 s . com*/
        data.putOpt("title", this.getTitle());

        data.putOpt("holdings_count", this.getTotalCount());
        data.putOpt("holdings_available", this.getAvailableCount());
        data.putOpt("holdings_lent", this.getLentCount());
        data.putOpt("holdings_reserved", this.getReservedCount());

        if (this.getMaterialType() != null) {
            data.putOpt("material_type", this.getMaterialType().getCode());
        }

        if (this.getFields() != null) {
            for (String[] field : this.getFields()) {
                JSONObject jsonField = new JSONObject();
                jsonField.put("field", field[0]);
                jsonField.put("label", I18nUtils.getText(properties, field[0]));
                jsonField.put("value", field[1]);

                data.append("fields", jsonField);
            }
        }

        if (this.getLinks() != null) {
            Subfield subF = null;
            Subfield subY = null;
            Subfield subD = null;
            Subfield subU = null;

            String file = null;
            String name = null;
            String path = null;
            String uri = null;

            for (DataField field : this.getLinks()) {
                JSONObject jsonLink = new JSONObject();

                subF = field.getSubfield('f');
                file = subF == null ? "" : subF.getData();
                subY = field.getSubfield('y');
                name = subY == null ? "" : subY.getData();
                subD = field.getSubfield('d');
                path = subD == null ? "" : subD.getData();
                subU = field.getSubfield('u');
                uri = subU == null ? "" : subU.getData();

                if (StringUtils.isBlank(file)) {
                    file = name;
                }

                if (StringUtils.isBlank(file)) {
                    file = uri;
                }

                if (StringUtils.isNotBlank(file)) {
                    if (path == null || path.isEmpty()) {
                        path = Config.getConfigProperty(ConfigurationEnum.DIGITAL_MEDIA);
                    }
                    if (name == null || name.isEmpty()) {
                        name = file;
                    }

                    jsonLink.put("path", path);
                    jsonLink.put("file", file);
                    jsonLink.put("name", name);
                    jsonLink.put("uri", uri);

                    data.append("links", jsonLink);
                }
            }
        }

        if (this.getHoldings() != null) {
            for (HoldingDTO dto : this.getHoldings()) {
                data.append("holdings", dto.toJSONObject(properties));
            }
        }

        if (this.getJson() != null) {
            data.put("data", this.getJson());
        }

        if (this.getMarc() != null) {
            data.put("data", this.getMarc());
        }
    } catch (JSONException e) {
    }

    return data;
}

From source file:org.eclipse.orion.server.logs.jobs.ListRollingFileAppendersJob.java

@Override
protected IStatus performJob() {
    try {//from   ww w  .j ava 2 s .  c o m
        List<RollingFileAppender<ILoggingEvent>> appenders = logService.getRollingFileAppenders();

        JSONObject appendersJSON = new JSONObject();
        appendersJSON.put(ProtocolConstants.KEY_CHILDREN, new JSONArray());
        for (RollingFileAppender<ILoggingEvent> appender : appenders) {

            RollingFileAppenderResource rollingFileAppender = new RollingFileAppenderResource(appender,
                    baseLocation);

            if (rollingFileAppender.getArchivedLogFiles() == null)
                LogUtils.attachArchivedLogFiles(appender, rollingFileAppender, logService);

            appendersJSON.append(ProtocolConstants.KEY_CHILDREN, rollingFileAppender.toJSON());
        }

        return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, appendersJSON);

    } catch (Exception e) {
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An error occured when listing rolling file appenders", e);
    }
}

From source file:Logica.SesionWeb.java

@Override
public void mandarMensaje(Mensaje mensaje) {
    try {/* w ww  . j  a v  a2 s . co m*/
        if (sesion.isOpen()) {
            JSONObject json = new JSONObject();
            json.append("envia", mensaje.getEnvia());
            json.append("recibe", mensaje.getRecibe());
            json.append("mensaje", mensaje.getMensaje());
            json.append("fecha", mensaje.getFecha());
            json.append("tipo", "MENSAJE");
            sesion.getBasicRemote().sendText(json.toString());
        }
    } catch (IOException ex) {
        Logger.getLogger(SesionWeb.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Logica.SesionWeb.java

@Override
public void notificarUsuariosLogeados(HashMap<String, Usuario> usuariosConectados) {
    try {/*from  w ww . jav  a  2  s.com*/
        if (sesion.isOpen()) {
            JSONObject objetoJSON = new JSONObject();
            JSONArray usuarios = new JSONArray();
            for (Map.Entry<String, Usuario> entry : usuariosConectados.entrySet()) {
                String nick = entry.getKey();
                usuarios.put(nick);
            }
            objetoJSON.put("usuarios", usuarios);
            objetoJSON.append("tipo", "CONTACTOS");
            sesion.getBasicRemote().sendText(objetoJSON.toString());
        }
    } catch (IOException ex) {
        Logger.getLogger(SesionWeb.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Logica.SesionWeb.java

@Override
public void exitoAlLogear(Usuario usuario) {
    try {/*from ww w. j a  v  a 2 s. com*/
        if (sesion.isOpen()) {
            sesion.getUserProperties().put("nick", usuario.getNick());
            JSONObject objetoJSON = new JSONObject();
            objetoJSON.append("tipo", "OK");
            objetoJSON.append("token", usuario.getToken());
            System.out.println(usuario.toString());
            System.out.println(usuario.getToken());
            sesion.getBasicRemote().sendText(objetoJSON.toString());
        }
    } catch (IOException ex) {
        Logger.getLogger(SesionWeb.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Logica.SesionWeb.java

@Override
public void notificarError(TipoMensaje tipoMensaje, String mensaje) {
    try {/*from  w w w  .j  a  va  2  s .co  m*/
        JSONObject o = new JSONObject();
        o.append("tipo", "" + tipoMensaje);
        o.append("mensaje", mensaje);
        sesion.getBasicRemote().sendText(o.toString());
        sesion.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY,
                "Algo salio muy mal... o no tan mal(como login mal viste..)"));
    } catch (IOException ex) {
        Logger.getLogger(ChatEndpoint.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:charitypledge.Pledge.java

public void JsonWrite(String[] args) {

    String[] values = args;//w w  w  .  j  a v  a  2  s.c  om
    JSONObject obj = new JSONObject();
    JSONArray objArray = new JSONArray();
    try {
        if (args == null || values.length == 0) {
            throw new Exception("Noting to write to file");
        } else {
            String title = "";
            String value = "";

            for (int i = (values.length - 1); i >= 0; i--) {
                if ((i % 2) == 0) {
                    title = values[i];
                    obj.put(title, value);
                } else {
                    value = values[i];
                }
            }
            objArray.put(obj);
        }

        try {
            try {
                InputStream foo = new FileInputStream(JSONFile);
                JSONTokener t = new JSONTokener(foo);
                JSONObject json = new JSONObject(t);
                foo.close();
                FileWriter file = new FileWriter(JSONFile);
                json.append("contributors", obj);
                file.write(json.toString(5));
                file.close();
                tableRefresh();
            } catch (FileNotFoundException e) {
                JSONWriter jsonWriter;
                try {
                    jsonWriter = new JSONWriter(new FileWriter(JSONFile));
                    jsonWriter.object();
                    jsonWriter.key("contributors");
                    jsonWriter.array();
                    jsonWriter.endArray();
                    jsonWriter.endObject();
                    InputStream foo = new FileInputStream(JSONFile);
                    JSONTokener t = new JSONTokener(foo);
                    JSONObject json = new JSONObject(t);
                    foo.close();
                    FileWriter file = new FileWriter(JSONFile);
                    json.append("contributors", obj);
                    file.write(json.toString(5));
                    file.close();
                    tableRefresh();
                } catch (IOException f) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        int pic = JOptionPane.ERROR_MESSAGE;
        JOptionPane.showMessageDialog(null, e, "", pic);
    }
}

From source file:biblivre3.cataloging.bibliographic.BiblioSearchResultsDTO.java

@Override
public JSONObject toJSONObject(Properties properties) {
    JSONObject json = new JSONObject();

    try {// ww  w.  j  ava 2 s . c om
        json.put("totalPages", this.totalPages);
        json.put("totalRecords", this.totalRecords);
        json.put("currentPage", this.currentPage);
        json.put("recordsPerPage", this.recordsPerPage);

        for (ResultRow rr : this.al) {
            json.append("results", rr.toJSONObject(null));
        }
    } catch (JSONException e) {
    }

    return json;
}

From source file:org.eclipse.orion.server.cf.handlers.v1.AppsHandlerV1.java

private IStatus getApps(Target target) throws Exception {
    String appsUrl = target.getSpace().getCFJSON().getJSONObject("entity").getString("apps_url");
    //      appsUrl = appsUrl.replaceAll("apps", "summary");
    URI appsURI = URIUtil.toURI(target.getUrl()).resolve(appsUrl);

    GetMethod getAppsMethod = new GetMethod(appsURI.toString());
    HttpUtil.configureHttpMethod(getAppsMethod, target);
    getAppsMethod.setQueryString("inline-relations-depth=2"); //$NON-NLS-1$

    ServerStatus getAppsStatus = HttpUtil.executeMethod(getAppsMethod);
    if (!getAppsStatus.isOK())
        return getAppsStatus;

    /* extract available apps */
    JSONObject appsJSON = getAppsStatus.getJsonData();

    if (appsJSON.getInt(CFProtocolConstants.V2_KEY_TOTAL_RESULTS) < 1) {
        return new ServerStatus(IStatus.OK, HttpServletResponse.SC_OK, null, null);
    }/*from   www . j  a  v a2 s. co  m*/

    JSONObject result = new JSONObject();
    JSONArray resources = appsJSON.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES);
    for (int k = 0; k < resources.length(); ++k) {
        JSONObject appJSON = resources.getJSONObject(k);
        App2 app = new App2();
        app.setCFJSON(appJSON);
        result.append("Apps", app.toJSON());
    }

    return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
}

From source file:org.eclipse.orion.server.logs.jobs.ListLoggersJob.java

@Override
protected IStatus performJob() {
    try {//  w  w  w . j ava  2  s.c  o  m
        List<Logger> loggers = logService.getLoggers();

        JSONObject loggersJSON = new JSONObject();
        loggersJSON.put(ProtocolConstants.KEY_CHILDREN, new JSONArray());
        for (Logger logger : loggers) {
            LoggerResource loggerResource = new LoggerResource();

            loggerResource.setBaseLocation(baseLocation);
            loggerResource.setName(logger.getName());
            loggerResource.setLevel(logger.getLevel());
            loggerResource.setEffectiveLevel(logger.getEffectiveLevel());

            loggersJSON.append(ProtocolConstants.KEY_CHILDREN, loggerResource.toJSON());
        }

        return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, loggersJSON);

    } catch (Exception e) {
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An error occured when listing loggers", e);
    }
}