Example usage for org.json.simple JSONArray add

List of usage examples for org.json.simple JSONArray add

Introduction

In this page you can find the example usage for org.json.simple JSONArray add.

Prototype

public boolean add(E e) 

Source Link

Document

Appends the specified element to the end of this list.

Usage

From source file:com.piusvelte.hydra.ApiServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ConnectionManager connMgr = ConnectionManager.getInstance(getServletContext());
    if (connMgr.isAuthenticated(request.getParameter(PARAM_TOKEN))) {
        HydraRequest hydraRequest;/* w  ww  . j  av  a2 s. c  o m*/
        try {
            hydraRequest = HydraRequest.fromPost(request);
        } catch (Exception e) {
            JSONObject j = new JSONObject();
            JSONArray errors = new JSONArray();
            errors.add(e.getMessage());
            response.setStatus(402);
            j.put("errors", errors);
            response.getWriter().write(j.toJSONString());
            return;
        }
        if (hydraRequest.database != null) {
            DatabaseConnection databaseConnection = null;
            connMgr.queueDatabaseRequest(hydraRequest.database);
            try {
                while (databaseConnection == null)
                    databaseConnection = connMgr.getDatabaseConnection(hydraRequest.database);
            } catch (Exception e) {
                e.printStackTrace();
            }
            connMgr.dequeueDatabaseRequest(hydraRequest.database);
            if (databaseConnection != null) {
                if (hydraRequest.isInsert())
                    response.getWriter()
                            .write(databaseConnection
                                    .insert(hydraRequest.target, hydraRequest.columns, hydraRequest.values)
                                    .toJSONString());
                else if (hydraRequest.isSubroutine())
                    response.getWriter().write(databaseConnection
                            .subroutine(hydraRequest.target, hydraRequest.arguments).toJSONString());
                else if (hydraRequest.isExecute())
                    response.getWriter().write(databaseConnection.execute(hydraRequest.command).toJSONString());
                else {
                    JSONObject j = new JSONObject();
                    JSONArray errors = new JSONArray();
                    errors.add("invalid request");
                    response.setStatus(403);
                    j.put("errors", errors);
                    response.getWriter().write(j.toJSONString());
                }
                databaseConnection.release();
            } else if (hydraRequest.queueable) {
                JSONObject j = new JSONObject();
                JSONArray errors = new JSONArray();
                errors.add("no database connection");
                connMgr.queueRequest(hydraRequest.toJSONString());
                errors.add("queued");
                response.setStatus(200);
                j.put("errors", errors);
                response.getWriter().write(j.toJSONString());
            } else {
                response.setStatus(502);
                JSONObject j = new JSONObject();
                JSONArray errors = new JSONArray();
                errors.add("no database connection available");
                j.put("errors", errors);
                response.getWriter().write(j.toJSONString());
            }
            connMgr.cleanDatabaseConnections(hydraRequest.database);
        } else
            response.setStatus(402);
    } else {
        response.setStatus(401);
    }
}

From source file:at.uni_salzburg.cs.ckgroup.cscpp.engine.json.VehicleQuery.java

@SuppressWarnings("unchecked")
public String execute(IServletConfig config, String[] parameters) {

    boolean sendAPs = true;
    boolean sendVVpath = true;

    if (parameters.length > 3) {
        for (String p : parameters[3].trim().split("\\s*,\\s*")) {
            if ("noAPs".equals(p)) {
                sendAPs = false;/* w  w w.j a  va 2 s . c  o m*/
            } else if ("noVvPath".equals(p)) {
                sendVVpath = false;
            }
        }
    }

    //      Map<String, Object> obj=new LinkedHashMap<String, Object>();
    JSONObject obj = new JSONObject();

    for (IVirtualVehicle vehicle : vehicleMap.values()) {

        if (vehicle.isFrozen()) {
            continue;
        }

        //         Map<String, Object> props = new LinkedHashMap<String, Object>();
        JSONObject props = new JSONObject();
        for (Entry<Object, Object> e : vehicle.getProperties().entrySet()) {
            String propertyName = (String) e.getKey();
            if (propSet.contains(propertyName)) {
                props.put(propertyName, e.getValue());
            }
        }

        props.put(PROP_VEHICLE_LOCAL_NAME, vehicle.getWorkDir().getName());

        if (vehicle.isProgramCorrupted()) {
            props.put(PROP_VEHICLE_STATE, "corrupt");
        } else if (vehicle.isCompleted()) {
            props.put(PROP_VEHICLE_STATE, "completed");
        } else if (vehicle.isActive()) {
            props.put(PROP_VEHICLE_STATE, "active");
        } else {
            props.put(PROP_VEHICLE_STATE, "suspended");
        }

        if (vehicle.getCurrentTask() != null) {
            PolarCoordinate p = vehicle.getCurrentTask().getPosition();
            props.put(PROP_VEHICLE_LATITUDE, Double.valueOf(p.getLatitude()));
            props.put(PROP_VEHICLE_LONGITUDE, Double.valueOf(p.getLongitude()));
            props.put(PROP_VEHICLE_ALTITUDE, Double.valueOf(p.getAltitude()));
            props.put(PROP_VEHICLE_TOLERANCE, Double.valueOf(vehicle.getCurrentTask().getTolerance()));

            List<IAction> al = vehicle.getCurrentTask().getActionList();
            if (al != null) {
                JSONArray openActions = new JSONArray();
                for (IAction action : al) {
                    if (!action.isComplete()) {
                        openActions.add(actionsMap.get(action.toString().toUpperCase()));
                    }
                }
                props.put(PROP_VEHICLE_ACTIONS, openActions);
            }

        }

        if (sendAPs) {
            JSONArray actionPoints = new JSONArray();
            for (ITask cmd : vehicle.getTaskList()) {
                JSONObject p = new JSONObject();
                p.put("latitude", cmd.getPosition().getLatitude());
                p.put("longitude", cmd.getPosition().getLongitude());
                //               p.put("altitude", cmd.getPosition().getAltitude());
                p.put("completed", Boolean.valueOf(cmd.isComplete()));
                actionPoints.add(p);
            }
            props.put(PROP_VEHICLE_ACTION_POINTS, actionPoints);
        }

        if (sendVVpath) {
            try {
                String vehicleLog = vehicle.getLog();
                VehicleLogConverter c = new VehicleLogConverter();
                JSONArray a = c.convertToVirtualVehiclePath(vehicleLog);
                props.put(PROP_VEHICLE_PATH, a);

            } catch (IOException e1) {
                e1.printStackTrace();
                LOG.error("Can not read log of vehicle " + vehicle.getWorkDir().getName());
            }
        }

        obj.put(vehicle.getWorkDir().getName(), props);
    }

    return obj.toJSONString();
}

From source file:org.kitodo.data.index.elasticsearch.type.TemplateType.java

@SuppressWarnings("unchecked")
@Override//from  www  .ja v  a  2  s  .c  o  m
public HttpEntity createDocument(Template template) {

    LinkedHashMap<String, String> orderedTemplateMap = new LinkedHashMap<>();
    String process = template.getProcess() != null ? template.getProcess().getId().toString() : "null";
    orderedTemplateMap.put("process", process);

    JSONObject processObject = new JSONObject(orderedTemplateMap);

    JSONArray properties = new JSONArray();
    List<TemplateProperty> templateProperties = template.getProperties();
    for (TemplateProperty property : templateProperties) {
        JSONObject propertyObject = new JSONObject();
        propertyObject.put("title", property.getTitle());
        propertyObject.put("value", property.getValue());
        properties.add(propertyObject);
    }
    processObject.put("properties", properties);

    return new NStringEntity(processObject.toJSONString(), ContentType.APPLICATION_JSON);
}

From source file:org.kitodo.data.index.elasticsearch.type.WorkpieceType.java

@SuppressWarnings("unchecked")
@Override/*w w  w .jav a  2  s .  com*/
public HttpEntity createDocument(Workpiece workpiece) {

    LinkedHashMap<String, String> orderedWorkpieceMap = new LinkedHashMap<>();
    String process = workpiece.getProcess() != null ? workpiece.getProcess().getId().toString() : "null";
    orderedWorkpieceMap.put("process", process);

    JSONObject processObject = new JSONObject(orderedWorkpieceMap);

    JSONArray properties = new JSONArray();
    List<WorkpieceProperty> workpieceProperties = workpiece.getProperties();
    for (WorkpieceProperty property : workpieceProperties) {
        JSONObject propertyObject = new JSONObject();
        propertyObject.put("title", property.getTitle());
        propertyObject.put("value", property.getValue());
        properties.add(propertyObject);
    }
    processObject.put("properties", properties);

    return new NStringEntity(processObject.toJSONString(), ContentType.APPLICATION_JSON);
}

From source file:hoot.services.controllers.ogr.OgrAttributesResource.java

/**
 * This rest endpoint uploads multipart data from UI and then generates attribute output
 * Example: http://localhost:8080//hoot-services/ogr/info/upload?INPUT_TYPE=DIR
 * Output: {"jobId":"e43feae4-0644-47fd-a23c-6249e6e7f7fb"}
 * /*from   ww w .  j ava 2  s . co  m*/
 * After getting the jobId, one can track the progress through job status rest end point
 * Example: http://localhost:8080/hoot-services/job/status/e43feae4-0644-47fd-a23c-6249e6e7f7fb
 * Output: {"jobId":"e43feae4-0644-47fd-a23c-6249e6e7f7fb","statusDetail":null,"status":"complete"}
 * 
 * Once status is "complete"
 * Result attribute can be obtained through
 * Example:http://localhost:8080/hoot-services/ogr/info/e43feae4-0644-47fd-a23c-6249e6e7f7fb
 * output: JSON of attributes
 * 
 * @param inputType : [FILE | DIR] where FILE type should represents zip,shp or OMS and DIR represents FGDB
 * @param request
 * @return
 */
@POST
@Path("/upload")
@Produces(MediaType.TEXT_PLAIN)
public Response processUpload(@QueryParam("INPUT_TYPE") final String inputType,
        @Context HttpServletRequest request) {
    JSONObject res = new JSONObject();
    String jobId = UUID.randomUUID().toString();

    try {
        log.debug("Starting file upload for ogr attribute Process");
        Map<String, String> uploadedFiles = new HashMap<String, String>();
        ;
        Map<String, String> uploadedFilesPaths = new HashMap<String, String>();

        MultipartSerializer ser = new MultipartSerializer();
        ser.serializeUpload(jobId, inputType, uploadedFiles, uploadedFilesPaths, request);

        List<String> filesList = new ArrayList<String>();
        List<String> zipList = new ArrayList<String>();

        Iterator it = uploadedFiles.entrySet().iterator();
        while (it.hasNext()) {

            Map.Entry pairs = (Map.Entry) it.next();
            String fName = pairs.getKey().toString();
            String ext = pairs.getValue().toString();

            String inputFileName = "";

            inputFileName = uploadedFilesPaths.get(fName);

            JSONObject param = new JSONObject();
            // If it is zip file then we crack open to see if it contains FGDB.
            // If so then we add the folder location and desired output name which is fgdb name in the zip
            if (ext.equalsIgnoreCase("ZIP")) {
                zipList.add(fName);
                String zipFilePath = homeFolder + "/upload/" + jobId + "/" + inputFileName;
                ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
                ZipEntry ze = zis.getNextEntry();

                while (ze != null) {

                    String zipName = ze.getName();
                    if (ze.isDirectory()) {

                        if (zipName.toLowerCase().endsWith(".gdb/") || zipName.toLowerCase().endsWith(".gdb")) {
                            String fgdbZipName = zipName;
                            if (zipName.toLowerCase().endsWith(".gdb/")) {
                                fgdbZipName = zipName.substring(0, zipName.length() - 1);
                            }
                            filesList.add("\"" + fName + "/" + fgdbZipName + "\"");
                        }
                    } else {
                        if (zipName.toLowerCase().endsWith(".shp")) {
                            filesList.add("\"" + fName + "/" + zipName + "\"");
                        }

                    }
                    ze = zis.getNextEntry();
                }

                zis.closeEntry();
                zis.close();
            } else {
                filesList.add("\"" + inputFileName + "\"");
            }

        }

        String mergeFilesList = StringUtils.join(filesList.toArray(), ' ');
        String mergedZipList = StringUtils.join(zipList.toArray(), ';');
        JSONArray params = new JSONArray();
        JSONObject param = new JSONObject();
        param.put("INPUT_FILES", mergeFilesList);
        params.add(param);
        param = new JSONObject();
        param.put("INPUT_ZIPS", mergedZipList);
        params.add(param);

        String argStr = createPostBody(params);
        postJobRquest(jobId, argStr);

    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Failed upload: " + ex.toString(), Status.INTERNAL_SERVER_ERROR, log);
    }
    res.put("jobId", jobId);
    return Response.ok(res.toJSONString(), MediaType.APPLICATION_JSON).build();
}

From source file:edu.pitt.dbmi.facebase.hd.InstructionQueueManager.java

/** Tell's Hub DB about the results of the queue processing effort
 * Called after processing of the queue item and construction of the TrueCrypt volume is complete. 
 * Tells Hub where TrueCrypt volume is located, when processing finished, and any error reporting; sets status
 * Sets status='complete' or status='error' in fb_queue row for this queue item
 * Sets Completed=unixEpicTime in fb_queue row for this queue item
 * Sets results=ComplexJSONstring holding path, logs, messages.  That string would look like this:
 * <pre>/*  ww w.j  a  v  a  2s  .c o  m*/
 * {
 *    "path": "/path/to/file/3DData1-2-11-35username.tc",
 *    "log": "",
 *    "messages": [
 *        "File 1102.obj was not found and not included in your zip file.",
 *        "Blah blah blah"
 *    ]
 * }
 * <pre>
 *
 * @param trueCryptFilename the full path name of the trueCrypt file (ie. /var/downloads/FBdata.tc)
 * @param size total size of TrueCrypt file
 * @param qid the queue id of the item that was processed
 * @param errors list of human-readable errors that were encountered (if nonzero, the status will be set to "error", otherwise status="complete".
 * @param logs list of detailed error information that was gathered (usually with Exception.getMessage()). 
 * @return true if successful
 */
boolean updateInstructionToCompleted(String trueCryptFilename, long size, long qid, ArrayList<String> errors,
        ArrayList<String> logs) {
    log.debug("InstructionQueueManager.updateInstructionToCompleted() called.");
    Session session = null;
    Transaction transaction = null;
    long unixEpicTime = System.currentTimeMillis() / 1000L;
    try {
        session = conf.openSession();
        transaction = session.beginTransaction();
        List<InstructionQueueItem> items = getPendingQueueItems(session, qid);
        String sizeString = (new Long(size)).toString();
        //LIKE THIS: jsonResultsString = "{\"path\":\""+trueCryptFilename+"\",\"log\":\"\",\"messages\":[\""+errorsString+"\"],\"size\":\""+sizeString+"\"}";
        Map resultsJSON = new LinkedHashMap();
        resultsJSON.put("path", trueCryptFilename);
        resultsJSON.put("size", sizeString);
        JSONArray messagesJSON = new JSONArray();
        JSONArray logsJSON = new JSONArray();
        for (String message : errors) {
            messagesJSON.add(message);
        }
        resultsJSON.put("messages", messagesJSON);
        for (String log : logs) {
            logsJSON.add(log);
        }
        resultsJSON.put("log", logsJSON);
        //LIKE THIS: jsonResultsString = resultsJSON.toString();...but toString() won't work...need toJSONString():
        String jsonResultsString = JSONValue.toJSONString(resultsJSON);
        if (items != null && items.size() >= 1) {
            InstructionQueueItem item = items.get(0);
            if (errors.isEmpty()) {
                item.setStatus("complete");
            } else {
                item.setStatus("error");
            }
            item.setResults(jsonResultsString);
            item.setCompleted(unixEpicTime);
            session.update(item);
            transaction.commit();
        }
        session.close();
        return true;
    } catch (Throwable t) {
        String errorString = "InstructionQueueManager caught a t in updateInstructionsToCompleted()"
                + t.toString();
        String logString = t.getMessage();
        edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString);
        log.error(errorString, t);
        handleThrowable(t, session, transaction);
    }
    return false;
}

From source file:com.web.mavenproject6.controller.CameraController.java

@ResponseBody
@RequestMapping(value = "/logs", method = RequestMethod.POST)
public String cameraLogs() throws JSONException {
    JSONArray ar = new JSONArray();
    JSONObject resultJson = new JSONObject();
    for (JSONObject j : simpleLog) {
        ar.add(j);
    }/*from   w  ww  .  ja  va  2s. com*/
    resultJson.put("logs", ar);
    return resultJson.toString();

}

From source file:identify.SaveToken.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  ww  .  java  2  s .  c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String acrHeaders = request.getHeader("Access-Control-Request-Headers");
    String acrMethod = request.getHeader("Access-Control-Request-Method");
    String token = request.getParameter("token");
    String username = request.getParameter("username");
    storage.UpdateStorage(token, username);
    JSONObject arrayObj = new JSONObject();
    JSONArray dataArr = new JSONArray();
    arrayObj.put("status", "Ok");
    for (int i = 0; i < storage.getData().size(); i++) {
        JSONObject data = new JSONObject();
        data.put("token", storage.getData().get(i).getToken());
        data.put("username", storage.getData().get(i).getUsername());
        dataArr.add(data);
    }
    if (storage.getData().size() > 9) {
        storage.getData().clear();
    }
    arrayObj.put("storage", dataArr);
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Headers", acrHeaders);
    response.setHeader("Access-Control-Allow-Methods", acrMethod);
    response.setContentType("application/json:charset=UTF-8");
    response.getWriter().write(arrayObj.toString());
}

From source file:modelo.ParametrizacionManagers.Consultores.java

/**
* 
* Llama al delegate para Eliminar un Consultorio
* 
* @param codigo     /* w ww .  j  ava2s  .com*/
* @throws Exception 
*/
public JSONArray Eliminar(int codigo) throws Exception {

    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();

    Integer respError;

    EliminarConsultores delete = new EliminarConsultores(codigo);
    delete.ejecutar();

    respError = delete.getError();

    jsonObject.put("error", respError);

    jsonArray.add(jsonObject);

    return jsonArray;

}

From source file:org.kitodo.data.index.elasticsearch.type.ProcessType.java

@SuppressWarnings("unchecked")
@Override/*from  ww  w  . j  a v a  2  s  .  co m*/
public HttpEntity createDocument(Process process) {

    LinkedHashMap<String, String> orderedProcessMap = new LinkedHashMap<>();
    orderedProcessMap.put("name", process.getTitle());
    orderedProcessMap.put("outputName", process.getOutputName());
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String creationDate = process.getCreationDate() != null ? dateFormat.format(process.getCreationDate())
            : null;
    orderedProcessMap.put("creationDate", creationDate);
    orderedProcessMap.put("wikiField", process.getWikiField());
    String project = process.getProject() != null ? process.getProject().getId().toString() : "null";
    orderedProcessMap.put("project", project);
    String ruleset = process.getRuleset() != null ? process.getRuleset().getId().toString() : "null";
    orderedProcessMap.put("ruleset", ruleset);
    String ldapGroup = process.getDocket() != null ? process.getDocket().getId().toString() : "null";
    orderedProcessMap.put("ldapGroup", ldapGroup);

    JSONObject processObject = new JSONObject(orderedProcessMap);

    JSONArray properties = new JSONArray();
    List<ProcessProperty> processProperties = process.getProperties();
    for (ProcessProperty property : processProperties) {
        JSONObject propertyObject = new JSONObject();
        propertyObject.put("title", property.getTitle());
        propertyObject.put("value", property.getValue());
        properties.add(propertyObject);
    }
    processObject.put("properties", properties);

    return new NStringEntity(processObject.toJSONString(), ContentType.APPLICATION_JSON);
}