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:ProductServlet.java

private String getResults(String query, String... params) throws SQLException, ClassNotFoundException {
    StringBuilder results = new StringBuilder();
    String result = "a";

    try (Connection conn = getConnection()) {
        PreparedStatement pstmt = conn.prepareStatement(query);

        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
        }//from w  ww. ja  va2s . co  m

        ResultSet rs = pstmt.executeQuery();
        JSONObject resultObj = new JSONObject();
        JSONArray productArr = new JSONArray();

        while (rs.next()) {
            Map productMap = new LinkedHashMap();
            productMap.put("productID", rs.getInt("productID"));
            productMap.put("name", rs.getString("name"));
            productMap.put("description", rs.getString("description"));
            productMap.put("quantity", rs.getInt("quantity"));
            productArr.add(productMap);
        }
        resultObj.put("product", productArr);
        result = resultObj.toString();

    } catch (SQLException ex) {
        Logger.getLogger(ProductServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

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

@SuppressWarnings("unchecked")
@Override/*  www. ja  v a2s  .  c  o  m*/
public JSONObject delete(String object, String selection) {
    JSONObject response = new JSONObject();
    JSONArray errors = new JSONArray();
    UniCommand uCommand = null;
    UniFile uFile = null;
    try {
        uCommand = mSession.command();
        if (selection == null)
            uCommand.setCommand(String.format(SIMPLE_QUERY_FORMAT, object).toString());
        else
            uCommand.setCommand(String.format(SELECTION_QUERY_FORMAT, object, selection).toString());
        UniSelectList uSelect = mSession.selectList(0);
        uCommand.exec();
        uFile = mSession.openFile(object);
        UniString recordID = null;
        while ((recordID = uSelect.next()).length() > 0)
            uFile.deleteRecord(recordID);
        JSONArray rows = new JSONArray();
        JSONArray rowData = new JSONArray();
        rows.add(rowData);
        response.put("result", rows);
    } catch (UniSessionException e) {
        e.printStackTrace();
        errors.add("error getting command: " + e.getMessage());
    } catch (UniCommandException e) {
        e.printStackTrace();
        errors.add(e.getMessage());
    } catch (UniSelectListException e) {
        e.printStackTrace();
        errors.add(e.getMessage());
    } catch (UniFileException e) {
        e.printStackTrace();
        errors.add(e.getMessage());
    } finally {
        if (uFile != null) {
            try {
                uFile.close();
            } catch (UniFileException e) {
                e.printStackTrace();
            }
        }
    }
    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:app.model.game.ExeChooserModel.java

public JSONArray listfJSON(String directoryName) {
    JSONArray files = new JSONArray();
    File directory = new File(directoryName);

    // get all the files from a directory
    File[] fList = directory.listFiles();

    for (File file : fList) {
        if (file.isFile()) {
            if (listableFileTypes.contains(FilenameUtils.getExtension(file.getName()).toLowerCase())) {
                Map f = new LinkedHashMap();
                f.put("type", "file");
                f.put("name", file.getName());
                files.add(f);
            }//from   w  ww  .j  a v a2s .  c  o m
        }

        else if (file.isDirectory()) {
            Map folder = new LinkedHashMap();
            folder.put("type", "folder");
            folder.put("name", file.getName());
            folder.put("child", listfJSON(file.getAbsolutePath()));
            files.add(folder);
        }
    }

    return files;
}

From source file:com.assignment4.productdetails.java

@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)//from w w w  .  j  av a2  s .c  o m
public String getproduct(@PathParam("id") int id) throws SQLException {

    if (conn == null) {
        return "it not able to connect";
    } else {
        String query = "Select * from products where product_id = ?";
        PreparedStatement prestmt = conn.prepareStatement(query);
        prestmt.setInt(1, id);
        ResultSet res = prestmt.executeQuery();
        String results = "";
        JSONArray podtAr = new JSONArray();
        while (res.next()) {
            Map pdtmap = new LinkedHashMap();
            pdtmap.put("productID", res.getInt("product_id"));
            pdtmap.put("name", res.getString("name"));
            pdtmap.put("description", res.getString("description"));
            pdtmap.put("quantity", res.getInt("quantity"));
            podtAr.add(pdtmap);
        }
        results = podtAr.toString();

        return results;
    }

}

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

@SuppressWarnings("unchecked")
@Override/*from  www. j av  a  2  s  .  c  om*/
public JSONObject execute(String statement) {
    JSONObject response = new JSONObject();
    JSONArray errors = new JSONArray();
    Statement s = null;
    ResultSet rs = null;
    try {
        s = mConnection.createStatement();
        rs = s.executeQuery(statement);
        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:com.piusvelte.hydra.UnidataConnection.java

@SuppressWarnings("unchecked")
@Override//from  w  ww  .  jav  a2 s.co  m
public JSONObject update(String object, String[] columns, String[] values, String selection) {
    JSONObject response = new JSONObject();
    JSONArray errors = new JSONArray();
    UniFile uFile = null;
    try {
        int[] locs = getDictLocs(object, columns);
        UniCommand uCommand = mSession.command();
        if (selection == null)
            uCommand.setCommand(String.format(SIMPLE_QUERY_FORMAT, object).toString());
        else
            uCommand.setCommand(String.format(SELECTION_QUERY_FORMAT, object, selection).toString());
        UniSelectList uSelect = mSession.selectList(0);
        uCommand.exec();
        uFile = mSession.openFile(object);
        UniString recordID = null;
        while ((recordID = uSelect.next()).length() > 0) {
            UniDynArray record = new UniDynArray(uFile.read(recordID));
            for (int c = 0; c < columns.length; c++) {
                if ((locs[c] > 0) && !("@ID").equals(columns[c]))
                    record.replace(locs[c], values[c]);
            }
            uFile.write(recordID, record);
        }
        JSONArray rows = new JSONArray();
        JSONArray rowData = new JSONArray();
        rows.add(rowData);
        response.put("result", rows);
    } catch (UniSessionException e) {
        e.printStackTrace();
        errors.add(e.getMessage());
    } catch (UniCommandException e) {
        e.printStackTrace();
        errors.add(e.getMessage());
    } catch (UniFileException e) {
        e.printStackTrace();
        errors.add(e.getMessage());
    } catch (UniSelectListException e) {
        e.printStackTrace();
        errors.add(e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        errors.add(e.getMessage());
    } finally {
        if (uFile != null) {
            try {
                uFile.close();
            } catch (UniFileException e) {
                e.printStackTrace();
            }
        }
    }
    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.product.Product.java

/**
 * Retrieves representation of an instance of com.oracle.products.ProductResource
 * @return an instance of java.lang.String
 *///from w  w  w  .j  a  v  a 2s .  com
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getAllProducts() throws SQLException {
    if (connect == null) {
        return "not connected";
    } else {
        String query = "Select * from products";
        PreparedStatement prepstmnt = connect.prepareStatement(query);
        ResultSet rs = prepstmnt.executeQuery();
        String result = "";
        JSONArray productArr = new JSONArray();
        while (rs.next()) {
            Map productMap = new LinkedHashMap();
            productMap.put("productID", rs.getInt("product_id"));
            productMap.put("name", rs.getString("name"));
            productMap.put("description", rs.getString("description"));
            productMap.put("quantity", rs.getInt("quantity"));
            productArr.add(productMap);
        }
        result = productArr.toString();
        return result.replace("},", "},\n");
    }

}

From source file:de.unirostock.sems.caroweb.Converter.java

private void run(HttpServletRequest request, HttpServletResponse response, String uploadedName, String[] req,
        File tmp, File out, Path STORAGE) throws ServletException, IOException {
    cleanUp();/*from  w  w w. ja  v a  2s.co m*/

    uploadedName.replaceAll("[^A-Za-z0-9 ]", "_");
    if (uploadedName.length() < 3)
        uploadedName += "container";

    CaRoConverter conv = null;

    if (req[1].equals("caro"))
        conv = new CaToRo(tmp);
    else if (req[1].equals("roca"))
        conv = new RoToCa(tmp);
    else {
        error(request, response, "do not know what to do");
        return;
    }
    conv.convertTo(out);

    List<CaRoNotification> notifications = conv.getNotifications();

    Path result = null;
    if (out.exists()) {
        result = Files.createTempFile(STORAGE, uploadedName,
                "-converted-" + CaRoWebutils.getTimeStamp() + "." + (req[1].equals("caro") ? "ro" : "omex"));
        try {
            Files.copy(out.toPath(), result, StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            notifications.add(new CaRoNotification(CaRoNotification.SERVERITY_ERROR,
                    "wasn't able to copy converted container to storage"));
        }
    }

    JSONArray errors = new JSONArray();
    JSONArray warnings = new JSONArray();
    JSONArray notes = new JSONArray();
    for (CaRoNotification note : notifications)
        if (note.getSeverity() == CaRoNotification.SERVERITY_ERROR)
            errors.add(note.getMessage());
        else if (note.getSeverity() == CaRoNotification.SERVERITY_WARN)
            warnings.add(note.getMessage());
        else if (note.getSeverity() == CaRoNotification.SERVERITY_NOTE)
            notes.add(note.getMessage());

    JSONObject json = new JSONObject();
    json.put("errors", errors);
    json.put("warnings", warnings);
    json.put("notifications", notes);

    if (result != null && Files.exists(result)) {
        json.put("checkout", result.getFileName().toString());
        if (request.getParameter("redirect") != null && request.getParameter("redirect").equals("checkout")) {
            response.sendRedirect("/checkout/" + result.getFileName().toString());
        }
    }

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    PrintWriter outWriter = response.getWriter();
    outWriter.print(json);
    out.delete();
}

From source file:com.products.ProductResource.java

/**
 * Retrieves representation of an instance of com.oracle.products.ProductResource
 * @return an instance of java.lang.String
 *//*from  w  w w.jav  a 2s  .  c o  m*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getAllProducts() throws SQLException {
    if (co == null) {
        return "not connected";
    } else {
        String query = "Select * from product";
        PreparedStatement pstmt = co.prepareStatement(query);
        ResultSet rs = pstmt.executeQuery();
        String result = "";
        JSONArray productArr = new JSONArray();
        while (rs.next()) {
            Map productMap = new LinkedHashMap();
            productMap.put("productID", rs.getInt("product_id"));
            productMap.put("name", rs.getString("name"));
            productMap.put("description", rs.getString("description"));
            productMap.put("quantity", rs.getInt("quantity"));
            productArr.add(productMap);
        }
        result = productArr.toString();
        return result.replace("},", "},\n");
    }

}

From source file:modelo.ParametrizacionManagers.TipoVisita.java

public JSONArray getTiposVisitas() throws SQLException {
    //Ejecutamos la consulta y obtenemos el ResultSet
    SeleccionarTipoVisita select = new SeleccionarTipoVisita();
    ResultSet rset = select.getTiposVisitas();

    //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("descripcion", rset.getString("DESCRIPCION"));

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

    }/*w  ww .j  a v  a 2s  .  c om*/

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