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:hoot.services.controllers.ingest.BasemapResource.java

@POST
@Path("/upload")
@Produces(MediaType.TEXT_PLAIN)//  w  ww.  ja  va2  s. c  o  m
public Response processUpload(@QueryParam("INPUT_NAME") final String inputName,
        @QueryParam("PROJECTION") final String projection, @Context HttpServletRequest request) {
    String groupId = UUID.randomUUID().toString();
    JSONArray jobsArr = new JSONArray();
    try {
        File uploadDir = new File(homeFolder + "/upload/");
        uploadDir.mkdir();

        String repFolderPath = homeFolder + "/upload/" + groupId;
        File dir = new File(repFolderPath);
        dir.mkdir();

        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new ServletException("Content type is not multipart/form-data");
        }
        DiskFileItemFactory fileFactory = new DiskFileItemFactory();
        File filesDir = new File(repFolderPath);
        fileFactory.setRepository(filesDir);
        ServletFileUpload uploader = new ServletFileUpload(fileFactory);

        Map<String, String> uploadedFiles = new HashMap<String, String>();
        Map<String, String> uploadedFilesPaths = new HashMap<String, String>();
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();

        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            String fileName = fileItem.getName();

            String uploadedPath = repFolderPath + "/" + fileName;
            File file = new File(uploadedPath);
            fileItem.write(file);

            String[] nameParts = fileName.split("\\.");
            if (nameParts.length > 1) {
                String extension = nameParts[nameParts.length - 1].toLowerCase();
                String filename = nameParts[0];

                if (_basemapRasterExt.get(extension) != null) {
                    uploadedFiles.put(filename, extension);
                    uploadedFilesPaths.put(filename, fileName);
                    log.debug("Saving uploaded:" + filename);
                }

            }

        }

        Iterator it = uploadedFiles.entrySet().iterator();
        while (it.hasNext()) {
            String jobId = UUID.randomUUID().toString();
            Map.Entry pairs = (Map.Entry) it.next();
            String fName = pairs.getKey().toString();
            String ext = pairs.getValue().toString();

            log.debug("Preparing Basemap Ingest for :" + fName);
            String inputFileName = "";
            String bmName = inputName;

            if (bmName != null && bmName.length() > 0) {
                bmName = bmName;
            } else {
                bmName = fName;
            }

            inputFileName = uploadedFilesPaths.get(fName);

            try {
                JSONArray commandArgs = new JSONArray();
                JSONObject arg = new JSONObject();
                arg.put("INPUT", "upload/" + groupId + "/" + inputFileName);
                commandArgs.add(arg);

                arg = new JSONObject();
                arg.put("INPUT_NAME", bmName);
                commandArgs.add(arg);

                arg = new JSONObject();
                arg.put("RASTER_OUTPUT_DIR", _tileServerPath + "/BASEMAP");
                commandArgs.add(arg);

                arg = new JSONObject();
                if (projection != null && projection.length() > 0) {
                    arg.put("PROJECTION", projection);
                } else {
                    arg.put("PROJECTION", "auto");
                }
                commandArgs.add(arg);

                arg = new JSONObject();
                arg.put("JOB_PROCESSOR_DIR", _ingestStagingPath + "/BASEMAP");
                commandArgs.add(arg);

                String argStr = createBashPostBody(commandArgs);
                postJobRquest(jobId, argStr);

                JSONObject res = new JSONObject();
                res.put("jobid", jobId);
                res.put("name", bmName);

                jobsArr.add(res);

            } catch (Exception ex) {
                ResourceErrorHandler.handleError("Error processing upload: " + ex.getMessage(),
                        Status.INTERNAL_SERVER_ERROR, log);
            }

        }

    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error processing upload: " + ex.getMessage(),
                Status.INTERNAL_SERVER_ERROR, log);
    }

    return Response.ok(jobsArr.toJSONString(), MediaType.APPLICATION_JSON).build();
}

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

@SuppressWarnings("unchecked")
@Override//w w w . j a v a 2 s .c  o m
public JSONObject delete(String object, String selection) {
    JSONObject response = new JSONObject();
    JSONArray errors = new JSONArray();
    Statement s = null;
    ResultSet rs = null;
    try {
        s = mConnection.createStatement();
        rs = s.executeQuery(String.format(DELETE_QUERY, object, selection).toString());
        response.put("result", getResult(rs));
    } catch (SQLException e) {
        errors.add(e.getMessage());
    } finally {
        if (s != null) {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    errors.add(e.getMessage());
                }
            }
            try {
                s.close();
            } catch (SQLException e) {
                errors.add(e.getMessage());
            }
        }
    }
    response.put("errors", errors);
    if (!response.containsKey("result")) {
        JSONArray rows = new JSONArray();
        JSONArray rowData = new JSONArray();
        rows.add(rowData);
        response.put("result", rows);
    }
    return response;
}

From source file:productClass.java

private String getResults(String query, String... params) {
    String result = new String();
    try (Connection conn = getConnection()) {
        PreparedStatement pstmt = conn.prepareStatement(query);
        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
        }//  www .  ja  v  a2s  . c  o  m
        ResultSet rs = pstmt.executeQuery();
        JSONArray productArr = new JSONArray();
        while (rs.next()) {
            //Mapping the objects
            Map productMapping = new LinkedHashMap();
            productMapping.put("productID", rs.getInt("productID"));
            productMapping.put("name", rs.getString("name"));
            productMapping.put("description", rs.getString("description"));
            productMapping.put("quantity", rs.getInt("quantity"));
            productArr.add(productMapping);
        }
        result = productArr.toString();
    } catch (SQLException ex) {
        Logger.getLogger(productClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result.replace("},", "},\n");
}

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

@SuppressWarnings("unchecked")
@Override//  www. jav  a2 s  .c  om
public JSONObject delete(String object, String selection) {
    JSONObject response = new JSONObject();
    JSONArray errors = new JSONArray();
    Statement s = null;
    ResultSet rs = null;
    try {
        s = mConnection.createStatement();
        rs = s.executeQuery(String.format(DELETE_QUERY, object, selection).toString());
        response.put("result", getResult(rs));
    } catch (SQLException e) {
        errors.add(e.getMessage());
        e.printStackTrace();
    } finally {
        if (s != null) {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    errors.add(e.getMessage());
                }
            }
            try {
                s.close();
            } catch (SQLException e) {
                errors.add(e.getMessage());
            }
        }
    }
    response.put("errors", errors);
    if (!response.containsKey("result")) {
        JSONArray rows = new JSONArray();
        JSONArray rowData = new JSONArray();
        rows.add(rowData);
        response.put("result", rows);
    }
    return response;
}

From source file:com.intuit.tweetstest.TweetsController.java

protected JSONArray retrieveTweetsFromDB(DB db, List<String> followingList, int count) throws ParseException {
    JSONArray tweetsArray = new JSONArray();
    DBCollection tweetsCollection = db.getCollection("tweetscollection");
    DBObject tweetsQuery = new BasicDBObject("user", new BasicDBObject("$in", followingList));
    DBObject excludeId = new BasicDBObject("_id", 0);
    DBCursor cursor = tweetsCollection.find(tweetsQuery, excludeId).sort(new BasicDBObject("tweetedOn", -1))
            .limit(count);/*from w  ww.  ja va2s.  c o m*/
    for (DBObject tweet : cursor) {
        JSONObject tweetJson = (JSONObject) new JSONParser().parse(tweet.toString());
        tweetsArray.add(tweetJson);
    }
    return tweetsArray;
}

From source file:hoot.services.controllers.job.ExportJobResource.java

/**
 * <NAME>Export Service Job Execute</NAME>
 * <DESCRIPTION>/*from  ww  w.  ja  v  a  2 s.  co  m*/
 *    Asynchronous export service.
 * </DESCRIPTION>
 * <PARAMETERS>
 * <translation>
 *    Translation script name.
 * </translation>
 * <inputtype>
 *  [db | file] db means input from hoot db will be used. file mean a file path will be specified.
 * </inputtype>
 * <input>
 * Input name. for inputtype = db then specify name from hoot db. For inputtype=file, specify full path to a file.
 * </input>
 * <outputtype>
 *    [gdb | shp | wfs]. gdb will produce file gdb, shp will output shapefile. if outputtype = wfs then a wfs front end will be created
 * </outputtype>
 * <removereview>
 * Removes all unreviewed items. NOTE: removereview will alway be true.
 * </removereview>
 * </PARAMETERS>
 * <OUTPUT>
 *    Job ID
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/job/export/execute</URL>
 *    <REQUEST_TYPE>POST</REQUEST_TYPE>
 *    <INPUT>
 * {
* "translation":"MGCP.js",
* "inputtype":"db",
* "input":"ToyTestA",
* "outputtype":"gdb",
* "removereview" : "false"
*
* }
 *   </INPUT>
 * <OUTPUT>{"jobid":"24d1400e-434e-45e0-9afe-372215490be2"}</OUTPUT>
 * </EXAMPLE>
 * @param params
 * @return
 */
@POST
@Path("/execute")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response process(String params) {
    String jobId = UUID.randomUUID().toString();
    jobId = "ex_" + jobId.replace("-", "");
    try {
        JSONArray commandArgs = parseParams(params);

        JSONObject arg = new JSONObject();
        arg.put("outputfolder", tempOutputPath + "/" + jobId);
        commandArgs.add(arg);

        arg = new JSONObject();
        arg.put("output", jobId);
        commandArgs.add(arg);

        String type = getParameterValue("outputtype", commandArgs);
        if (type != null && type.equalsIgnoreCase("wfs")) {
            arg = new JSONObject();
            arg.put("outputname", jobId);
            commandArgs.add(arg);

            String dbname = HootProperties.getProperty("dbName");
            String userid = HootProperties.getProperty("dbUserId");
            String pwd = HootProperties.getProperty("dbPassword");
            String host = HootProperties.getProperty("dbHost");
            String[] hostParts = host.split(":");

            String pgUrl = "host='" + hostParts[0] + "' port='" + hostParts[1] + "' user='" + userid
                    + "' password='" + pwd + "' dbname='" + wfsStoreDb + "'";

            arg = new JSONObject();
            arg.put("PG_URL", pgUrl);
            commandArgs.add(arg);

            JSONObject osm2orgCommand = _createPostBody(commandArgs);
            // this may need change in the future if we decided to use user defined ouputname..
            String outname = jobId;

            JSONArray wfsArgs = new JSONArray();
            JSONObject param = new JSONObject();
            param.put("value", outname);
            param.put("paramtype", String.class.getName());
            param.put("isprimitivetype", "false");
            wfsArgs.add(param);

            JSONObject prepareItemsForReviewCommand = _createReflectionSycJobReq(wfsArgs,
                    "hoot.services.controllers.wfs.WfsManager", "createWfsResource");

            JSONArray jobArgs = new JSONArray();
            jobArgs.add(osm2orgCommand);
            jobArgs.add(prepareItemsForReviewCommand);

            postChainJobRquest(jobId, jobArgs.toJSONString());
        } else {
            // replace with with getParameterValue
            boolean paramFound = false;
            for (int i = 0; i < commandArgs.size(); i++) {
                JSONObject jo = (JSONObject) commandArgs.get(i);
                Object oo = jo.get("outputname");
                if (oo != null) {
                    String strO = (String) oo;
                    if (strO.length() > 0) {
                        paramFound = true;
                        break;
                    }
                }
            }

            if (paramFound == false) {
                arg = new JSONObject();
                arg.put("outputname", jobId);
                commandArgs.add(arg);
            }

            String argStr = createPostBody(commandArgs);
            postJobRquest(jobId, argStr);
        }
    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error exporting data: " + ex.toString(), Status.INTERNAL_SERVER_ERROR,
                log);
    }
    JSONObject res = new JSONObject();
    res.put("jobid", jobId);
    return Response.ok(res.toJSONString(), MediaType.APPLICATION_JSON).build();
}

From source file:com.imagelake.control.InterfaceDAOImp.java

public String listPrivilages() {
    String sb = "";
    JSONArray ja = new JSONArray();
    try {/* www . jav  a2 s.  c  om*/
        String sql3 = "SELECT * FROM user_type WHERE user_type_id!=4";
        PreparedStatement ps3 = DBFactory.getConnection().prepareStatement(sql3);
        ResultSet rs3 = ps3.executeQuery();
        while (rs3.next()) {
            JSONObject jo = new JSONObject();
            jo.put("id", rs3.getString(1));
            jo.put("type", rs3.getString(2));
            ja.add(jo);
        }
        sb = "json=" + ja.toJSONString();
    } catch (Exception e) {
        e.printStackTrace();
        sb = "msg=Internal server error,Please try again later.";
    }
    return sb;
}

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

@SuppressWarnings("unchecked")
@Override//ww  w . j a v  a2 s .co m
public JSONObject execute(String statement) {
    JSONObject response = new JSONObject();
    JSONArray errors = new JSONArray();
    try {
        UniCommand uCommand = mSession.command();
        uCommand.setCommand(statement);
        uCommand.exec();
        String[] fmValues = uCommand.response().split(UniTokens.AT_FM, -1);
        JSONArray rows = new JSONArray();
        for (String fmValue : fmValues) {
            JSONArray rowData = new JSONArray();
            String[] vmValues = fmValue.split(UniTokens.AT_VM, -1);
            for (String vmValue : vmValues)
                rowData.add(vmValue);
            rows.add(rowData);
        }
        response.put("result", rows);
    } catch (UniSessionException e) {
        errors.add(e.getMessage());
    } catch (UniCommandException e) {
        errors.add(e.getMessage());
    }
    response.put("errors", errors);
    if (!response.containsKey("result")) {
        JSONArray rows = new JSONArray();
        JSONArray rowData = new JSONArray();
        rows.add(rowData);
        response.put("result", rows);
    }
    return response;
}

From source file:modelo.ParametrizacionManagers.TiemposBackup.java

/**
 * // w  w w. j  ava2s.  c o  m
 * Obtiene la informacion de las unidades de medida y
 * guarda todo en un JSONArray para entregarselo a la vista.
 * 
 * @return JSONArray
 * @throws SQLException 
 */
public JSONArray getTiemposBackup() throws SQLException {

    //Ejecutamos la consulta y obtenemos el ResultSet
    SeleccionarTiemposBackup select = new SeleccionarTiemposBackup();
    ResultSet rset = select.getTiemposBackup();

    //Creamos los JSONArray para guardar los objetos JSON
    JSONArray jsonArray = new JSONArray();
    JSONArray jsonArreglo = new JSONArray();
    //Recorremos el ResultSet, armamos el objeto JSON con la info y guardamos
    //en el JSONArray.
    while (rset.next()) {

        //Armamos el objeto JSON con la informacion del registro
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("codigo", rset.getString("CODIGO"));
        jsonObject.put("tiempo", rset.getString("DIAS_BACKUP"));

        //Guardamos el JSONObject en el JSONArray y lo enviamos a la vista.
        jsonArray.add(jsonObject.clone());

    }

    jsonArreglo.add(jsonArray);
    select.desconectar();
    return jsonArreglo;

}

From source file:gr.aueb.mipmapgui.controller.file.ActionInitialize.java

private void getSavedUserFiles(String user) {
    JSONArray taskFileArr = new JSONArray();

    ActionCreateUserDirectory actionCreateUserDirectory = new ActionCreateUserDirectory(modello);
    actionCreateUserDirectory.performAction(user);
    ActionCleanDirectory actionCleanDirectory = new ActionCleanDirectory(modello);
    actionCleanDirectory.performAction(user);

    File tasksDir = new File(Costanti.SERVER_MAIN_FOLDER + Costanti.SERVER_FILES_FOLDER + user + "/");
    String[] taskFiles = tasksDir.list(DirectoryFileFilter.INSTANCE);
    for (String file : taskFiles) {
        if (!file.equalsIgnoreCase("temp")) {
            taskFileArr.add(file);
        }/*from w w w.  ja  va 2 s.  co  m*/
    }
    JSONObject.put("savedTasks", taskFileArr);
}