Example usage for org.json.simple JSONArray JSONArray

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

Introduction

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

Prototype

JSONArray

Source Link

Usage

From source file:me.uni.sushilkumar.geodine.util.WhatsCooking.java

/** 
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request//  w  w w.j a va 2s .c  o m
 * @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 {
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    try {
        JSONObject obj = new JSONObject();
        JSONArray array = new JSONArray();
        DBConnection con = new DBConnection();
        ArrayList<String> cuisineList = con.getCuisineList();
        Random generator = new Random();
        int size = cuisineList.size();
        for (int i = 0; i < 10; i++) {
            JSONObject temp = new JSONObject();
            String title = cuisineList.get(generator.nextInt(size));
            //title=WordUtils.capitalize(title);
            temp.put("title", title);
            title = title.replaceAll("\\s+", "-");
            String link = "cuisine/" + title;
            temp.put("link", link);
            array.add(temp);
        }
        obj.put("links", array);
        out.println(obj.toJSONString());
    } catch (SQLException ex) {
        Logger.getLogger(WhatsCooking.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

From source file:bhl.pages.handler.PagesListHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn)
        throws MissingDocumentException {
    try {//from www .jav a 2 s  . com
        String docid = request.getParameter(Params.DOCID);
        if (docid != null) {
            Connection conn = Connector.getConnection();
            String[] keys = new String[2];
            keys[0] = JSONKeys.BHL_PAGE_ID;
            keys[1] = JSONKeys.PAGE_SEQUENCE;
            String[] pages = conn.listCollectionBySubKey(Database.PAGES, JSONKeys.IA_IDENTIFIER, docid, keys);
            JSONArray list = new JSONArray();
            for (int i = 0; i < pages.length; i++) {
                JSONObject jobj = (JSONObject) JSONValue.parse(pages[i]);
                Number pageNo = (Number) jobj.get(JSONKeys.PAGE_SEQUENCE);
                Number pageId = (Number) jobj.get(JSONKeys.BHL_PAGE_ID);
                System.out.println("pageNo=" + pageNo + " pageId=" + pageId);
                PageDesc ps = new PageDesc(new Integer(pageNo.intValue()).toString(),
                        new Integer(pageId.intValue()).toString());
                list.add(ps.toJSONObject());
            }
            PagesGetHandler.sortList(list);
            response.setContentType("application/json");
            response.getWriter().print(list.toJSONString());
        } else
            throw new Exception("Must specify document identifier");
    } catch (Exception e) {
        throw new MissingDocumentException(e);
    }
}

From source file:com.product.Product.java

/**
 * Retrieves representation of an instance of com.oracle.products.ProductResource
 * @return an instance of java.lang.String
 *//* w  ww . j  a va2s .  co m*/
@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:at.uni_salzburg.cs.ckgroup.cscpp.mapper.registry.RegistryPersistence.java

@SuppressWarnings("unchecked")
public static void storeRegistry(File registryFile, Map<String, IRegistrationData> registrationData)
        throws IOException {
    synchronized (lock) {
        JSONArray obj = new JSONArray();
        for (Entry<String, IRegistrationData> entry : registrationData.entrySet()) {
            IRegistrationData rd = entry.getValue();
            obj.add(rd);//from w w w. j a  v a  2 s  .c  o m
        }

        PrintWriter pw = new PrintWriter(registryFile);
        pw.print(obj.toString());
        pw.close();
        LOG.info("Registry successfully saved to file " + registryFile);
    }
}

From source file:com.mycompany.rent.controllers.MapController.java

@RequestMapping(value = "/data", method = RequestMethod.GET)
public File homePage(Map model) throws IOException {

    List<ForRent> allRentals = new ArrayList();

    allRentals = forRentDao.allRentals();

    JSONObject responseDetailsJson = new JSONObject();
    JSONArray array = new JSONArray();
    for (ForRent f : allRentals) {
        array.add(f.getLat());/*from  w w w .ja v a  2 s.  c  om*/
        array.add(f.getLon());
    }

    responseDetailsJson.put("data", (Object) array);//Here you can see the data in json format

    File file = new File("/home/brennan/_repos/rent/src/main/webapp/json/data.json");

    String path = file.getPath();

    try {

        // Writing to a file  
        file.createNewFile();
        FileWriter fileWriter = new FileWriter(file);

        fileWriter.write(responseDetailsJson.toJSONString());
        fileWriter.flush();
        fileWriter.close();

    } catch (IOException e) {

    }

    FileReader fr = new FileReader(file);

    return file;
}

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

@SuppressWarnings("unchecked")
@Override//from w  ww . ja va2  s .  c  o  m
public HttpEntity createDocument(Project project) {

    JSONObject projectObject = new JSONObject();
    projectObject.put("title", project.getTitle());
    String startDate = project.getStartDate() != null ? formatDate(project.getStartDate()) : null;
    projectObject.put("startDate", startDate);
    String endDate = project.getEndDate() != null ? formatDate(project.getEndDate()) : null;
    projectObject.put("endDate", endDate);
    projectObject.put("numberOfPages", project.getNumberOfPages());
    projectObject.put("numberOfVolumes", project.getNumberOfVolumes());
    projectObject.put("fileFormatDmsExport", project.getFileFormatDmsExport());
    projectObject.put("fileFormatInternal", project.getFileFormatInternal());
    String archived = project.getProjectIsArchived() != null ? project.getProjectIsArchived().toString() : null;
    projectObject.put("archived", archived);
    projectObject.put("processes", addObjectRelation(project.getProcesses()));
    projectObject.put("users", addObjectRelation(project.getUsers()));

    JSONArray projectFileGroups = new JSONArray();
    List<ProjectFileGroup> projectProjectFileGroups = project.getProjectFileGroups();
    for (ProjectFileGroup projectFileGroup : projectProjectFileGroups) {
        JSONObject projectFileGroupObject = new JSONObject();
        projectFileGroupObject.put("name", projectFileGroup.getName());
        projectFileGroupObject.put("path", projectFileGroup.getPath());
        projectFileGroupObject.put("mimeType", projectFileGroup.getMimeType());
        projectFileGroupObject.put("suffix", projectFileGroup.getSuffix());
        projectFileGroupObject.put("folder", projectFileGroup.getFolder());
        projectFileGroups.add(projectFileGroupObject);
    }
    projectObject.put("projectFileGroups", projectFileGroups);

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

From source file:formatter.handler.get.MetadataHandler.java

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, String urn)
        throws FormatterException {
    // we need the docid only
    // return the metadata for the document
    try {/* w w w  .ja  v  a  2s.co m*/
        this.docid = request.getParameter(Params.DOCID);
        Connection conn = Connector.getConnection();
        String bson = conn.getFromDb(Database.METADATA, docid);
        if (bson != null) {
            JSONObject jObj = (JSONObject) JSONValue.parse(bson);
            JSONArray sources;
            if (jObj.containsKey(JSONKeys.SOURCES)) {
                sources = (JSONArray) jObj.get(JSONKeys.SOURCES);
            } else
                sources = new JSONArray();
            response.setContentType("application/json");
            response.getWriter().write(sources.toJSONString());
        }
    } catch (Exception e) {
        throw new FormatterException(e);
    }
}

From source file:com.appzone.sim.services.handlers.MtLogCheckServiceHandler.java

@Override
protected String doProcess(HttpServletRequest request) {

    String sinceStr = request.getParameter(KEY_SINCE);
    logger.debug("request mt logs since: {}", sinceStr);

    long since = Long.parseLong(sinceStr);

    List<MtMessage> messages = mtMessageRepository.find(since);

    JSONArray list = new JSONArray();

    for (MtMessage mtMessage : messages) {

        String message = mtMessage.getMessage();
        String addresses = JSONValue.toJSONString(mtMessage.getAddresses());
        String receivedDate = "" + mtMessage.getReceivedDate();

        JSONObject json = new JSONObject();
        json.put(JSON_KEY_MESSAGE, message);
        json.put(JSON_KEY_ADDRESSES, JSONValue.parse(addresses));
        json.put(JSON_KEY_RECEIVED_DATE, receivedDate);

        list.add(json);//  ww  w  . jav a2 s  .c  om
    }

    logger.debug("returning response: {}", list);

    return list.toJSONString();
}

From source file:com.flaptor.indextank.api.resources.DeleteDocs.java

/**
 * @see java.lang.Runnable#run()//from  w w w .  j  a v a  2  s  . c o m
 */
public void run() {
    IndexEngineApi api = (IndexEngineApi) ctx().getAttribute("api");
    try {
        Object parse = JSONValue.parseWithException(req().getReader());
        if (parse instanceof JSONObject) { // 200, 400, 404, 409, 503
            JSONObject jo = (JSONObject) parse;
            try {
                deleteDocument(api, jo);
                res().setStatus(200);
                return;

            } catch (Exception e) {
                e.printStackTrace();
                if (LOG_ENABLED)
                    LOG.severe(e.getMessage());
                res().setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
        } else if (parse instanceof JSONArray) {
            JSONArray statuses = new JSONArray();
            JSONArray ja = (JSONArray) parse;
            if (!validateDocuments(ja)) {
                res().setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
            boolean hasError = false;
            for (Object o : ja) {
                JSONObject jo = (JSONObject) o;
                JSONObject status = new JSONObject();
                try {
                    deleteDocument(api, jo);
                    status.put("added", true);
                } catch (Exception e) {
                    status.put("added", false);
                    status.put("error", "Invalid or missing argument"); // TODO: descriptive error msg
                    hasError = true;
                }
                statuses.add(status);
            }
            print(statuses.toJSONString());
            return;
        }
    } catch (IOException e) {
        if (LOG_ENABLED)
            LOG.severe("DELETE doc, parse input " + e.getMessage());
    } catch (ParseException e) {
        if (LOG_ENABLED)
            LOG.severe("DELETE doc, parse input " + e.getMessage());
    } catch (Exception e) {
        if (LOG_ENABLED)
            LOG.severe("DELETE doc " + e.getMessage());
    }
    res().setStatus(503);
    print("Service unavailable"); // TODO: descriptive error msg
}

From source file:hd3gtv.mydmam.db.orm.AutotestOrm.java

public static AutotestOrm populate(int index) {
    AutotestOrm result = new AutotestOrm();

    result.key = "THISISMYKEY" + String.valueOf(index);
    result.strvalue = "Hello world with cnts";
    result.bytvalue = result.strvalue.toUpperCase().getBytes();
    result.intvalue = 42;/*  w w w.j a v  a  2s. c  o m*/
    result.lngvalue = -3329447494103907027L;
    result.bolvalue = true;
    result.fltvalue = 6.55957f;
    result.dlbvalue = (double) result.lngvalue / 11d;
    result.uuivalue = UUID.fromString("110E8400-E29B-11D4-A716-446655440000");
    result.jsovalue = new JSONObject();
    result.jsovalue.put("Hello", "world");
    result.jsovalue.put("Count", index);
    result.jsavalue = new JSONArray();
    result.jsavalue.add("One");
    result.jsavalue.add(42);
    result.jsavalue.add("Un");
    try {
        result.addressvalue = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    result.sbuvalue = new StringBuffer();
    result.sbuvalue.append(result.key);
    result.sbuvalue.append(result.strvalue);
    result.sbuvalue.append(result.lngvalue);
    result.calendarvalue = Calendar.getInstance();
    result.calendarvalue.set(1995, 05, 23, 10, 04, 8);
    result.calendarvalue.set(Calendar.MILLISECOND, 666);
    result.dtevalue = result.calendarvalue.getTime();
    result.strarrayvalue = new String[2];
    result.strarrayvalue[0] = result.strvalue;
    result.strarrayvalue[1] = result.key;
    result.serializvalue = new HashMap<String, String>();
    result.serializvalue.put("Some var", result.strvalue);
    result.serializvalue.put("Other var", result.uuivalue.toString());

    result.enumvalue = MyEnum.ME;

    result.iamempty = "";
    result.iamanindex = index;
    result.donttouchme = "F*ck you";
    return result;
}