Example usage for org.json.simple JSONArray subList

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

Introduction

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

Prototype

public List<E> subList(int fromIndex, int toIndex) 

Source Link

Document

Returns a view of the portion of this list between the specified fromIndex , inclusive, and toIndex , exclusive.

Usage

From source file:me.neatmonster.spacertk.plugins.templates.SBPlugin.java

/**
 * Creats a new Plugin//from   www  .ja v  a2  s  .  c o m
 * @param plugin JSONObject containing the raw information from BukGet
 */
public SBPlugin(final JSONObject plugin) {
    //TODO: should not crash if a field is missing
    name = (String) plugin.get("name");
    status = (String) plugin.get("status");
    link = (String) plugin.get("bukkitdev_link");
    description = (String) plugin.get("desc");
    final JSONArray categoriesJSONArray = (JSONArray) plugin.get("categories");
    @SuppressWarnings("unchecked")
    final List<Object> categoriesListObject = categoriesJSONArray.subList(0, categoriesJSONArray.size());
    for (final Object object : categoriesListObject)
        categories.add((String) object);
    final JSONArray versionsJSONArray = (JSONArray) plugin.get("versions");
    @SuppressWarnings("unchecked")
    final List<Object> versionsListObject = versionsJSONArray.subList(0, versionsJSONArray.size());
    final List<JSONObject> versionsListJSONObjects = new ArrayList<JSONObject>();
    for (final Object object : versionsListObject)
        versionsListJSONObjects.add((JSONObject) object);
    for (final JSONObject object : versionsListJSONObjects)
        versions.add(new Version(object));
}

From source file:me.neatmonster.spacertk.plugins.templates.Version.java

/**
 * Creates a new version// w  w w . j  a  va2 s. c o  m
 * @param version JSONObject containing the raw information from BukGet
 */
public Version(final JSONObject version) {
    date = (Long) version.get("date");
    name = (String) version.get("name");
    filename = (String) version.get("filename");
    md5 = (String) version.get("md5");
    link = (String) version.get("download");
    final JSONArray buildsJSONArray = (JSONArray) version.get("game_versions");
    @SuppressWarnings("unchecked")
    final List<Object> buildsListObject = buildsJSONArray.subList(0, buildsJSONArray.size());
    for (final Object object : buildsListObject)
        builds.add((String) object);

    if (!(version.get("soft_dependencies") instanceof String)) {//Assuming empty list if String
        final JSONArray softDependenciesJSONArray = (JSONArray) version.get("soft_dependencies");
        @SuppressWarnings("unchecked")
        final List<Object> softDependenciesListObject = softDependenciesJSONArray.subList(0,
                softDependenciesJSONArray.size());
        for (final Object object : softDependenciesListObject)
            softDependencies.add((String) object);
    }

    if (!(version.get("hard_dependencies") instanceof String)) { //Assuming empty list if String
        final JSONArray hardDependenciesJSONArray = (JSONArray) version.get("hard_dependencies");
        @SuppressWarnings("unchecked")
        final List<Object> hardDependenciesListObject = hardDependenciesJSONArray.subList(0,
                hardDependenciesJSONArray.size());
        for (final Object object : hardDependenciesListObject)
            hardDependencies.add((String) object);
    }
}

From source file:edu.sjsu.cohort6.esp.service.rest.CourseResource.java

@Override
@PUT//  ww w  .j  ava2s .c  o  m
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{id}")
public Course update(@Auth User user, @PathParam("id") String id, @Valid String courseJson)
        throws ResourceNotFoundException, InternalErrorException, IOException {
    try {
        if (isAdminUser(user)) {
            Course course = null;
            List<Course> courseList = courseDAO.fetchById(getListFromEntityId(id));
            if (courseList != null && !courseList.isEmpty()) {
                course = courseList.get(0);
            }
            if (course == null) {
                throw new ResourceNotFoundException();
            }
            // Parse JSON payload and update the fields that are updated.
            JSONParser parser = new JSONParser();
            JSONObject json = (JSONObject) parser.parse(courseJson);

            String val = (String) json.get("courseName");
            if (val != null) {
                course.setCourseName(val);
            }
            JSONArray arr = (JSONArray) json.get("instructors");
            if (arr != null) {
                course.setInstructors(arr.subList(0, arr.size()));
            }
            val = (String) json.get("startTime");
            if (val != null) {
                course.setStartTime(CommonUtils.getDateFromString(val));
            }
            val = (String) json.get("endTime");
            if (val != null) {
                course.setEndTime(CommonUtils.getDateFromString(val));
            }
            val = json.get("availabilityStatus").toString();
            if (val != null) {
                course.setAvailabilityStatus(Integer.parseInt(val));
            }
            val = (String) json.get("maxCapacity").toString();
            if (val != null) {
                course.setMaxCapacity(Integer.parseInt(val));
            }
            val = (String) json.get("price").toString();
            if (val != null) {
                course.setPrice(Double.parseDouble(val));
            }
            val = (String) json.get("location");
            if (val != null) {
                course.setLocation(val);
            }
            arr = (JSONArray) json.get("keywords");
            if (arr != null) {
                course.setKeywords(arr.subList(0, arr.size()));
            }

            courseDAO.update(getListFromEntity(course));
            return course;
        } else {
            throw new AuthorizationException(
                    "User " + user.getUserName() + " is not allowed to perform this operation");
        }
    } catch (Exception e) {
        throw new InternalErrorException(e);
    }
}

From source file:agileinterop.AgileInterop.java

private static JSONObject getPSRData(String body) throws ParseException, InterruptedException, APIException {
    // Parse body as JSON
    JSONParser parser = new JSONParser();
    JSONArray jsonBody = (JSONArray) parser.parse(body);

    Map<String, Object> data = new HashMap<>();

    class GetObjectData implements Runnable {
        private String psrNumber;
        private Map<String, Object> data;
        private IServiceRequest psr;

        public GetObjectData(String psrNumber, Map<String, Object> data)
                throws APIException, InterruptedException {
            this.psrNumber = psrNumber;
            this.data = data;

            psr = (IServiceRequest) Agile.session.getObject(IServiceRequest.OBJECT_TYPE, psrNumber);
        }/*ww  w .  j a  v a  2 s  .  c om*/

        @Override
        public void run() {
            this.data.put(psrNumber, new HashMap<String, Object>());

            try {
                if (psr != null) {
                    getCellValues();
                    getAttachments();
                    getHistory();
                }
            } catch (APIException ex) {
                Logger.getLogger(AgileInterop.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        private void getCellValues() throws APIException {
            Map<String, Object> cellValues = new HashMap<>();

            long startTime = System.currentTimeMillis();

            // Get cell values
            ICell[] cells = psr.getCells();
            for (ICell cell : cells) {
                if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                    if (cell.getValue() != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                        sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                        cellValues.put(cell.getName(), sdf.format((Date) cell.getValue()));
                    } else {
                        cellValues.put(cell.getName(), cell.toString());
                    }
                } else {
                    cellValues.put(cell.getName(), cell.toString());
                }
            }

            long endTime = System.currentTimeMillis();

            String logMessage = String.format("%s: getCellValues executed in %d milliseconds", psrNumber,
                    endTime - startTime);
            System.out.println(logMessage);

            ((HashMap<String, Object>) this.data.get(psrNumber)).put("cellValues", cellValues);
        }

        private void getAttachments() throws APIException {
            List<Map<String, String>> attachments = new ArrayList<>();

            long startTime = System.currentTimeMillis();

            // Get attachments information
            ITable table = psr.getTable("Attachments");
            ITwoWayIterator tableIterator = table.getTableIterator();
            while (tableIterator.hasNext()) {
                IRow row = (IRow) tableIterator.next();
                Map<String, String> attachment = new HashMap<>();

                ICell[] cells = row.getCells();
                for (ICell cell : cells) {
                    if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                        if (cell.getValue() != null) {
                            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                            sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                            attachment.put(cell.getName(), sdf.format((Date) cell.getValue()));
                        } else {
                            attachment.put(cell.getName(), cell.toString());
                        }
                    } else {
                        attachment.put(cell.getName(), cell.toString());
                    }
                }

                attachments.add(attachment);
            }

            long endTime = System.currentTimeMillis();

            String logMessage = String.format("%s: getAttachments executed in %d milliseconds", psrNumber,
                    endTime - startTime);
            System.out.println(logMessage);

            ((HashMap<String, Object>) this.data.get(psrNumber)).put("attachments", attachments);
        }

        private void getHistory() throws APIException {
            List<Map<String, String>> histories = new ArrayList<>();

            long startTime = System.currentTimeMillis();

            // Get history information
            ITable table = psr.getTable("History");
            ITwoWayIterator tableIterator = table.getTableIterator();
            while (tableIterator.hasNext()) {
                IRow row = (IRow) tableIterator.next();
                Map<String, String> history = new HashMap<>();

                ICell[] cells = row.getCells();
                for (ICell cell : cells) {
                    if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                        if (cell.getValue() != null) {
                            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                            sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                            history.put(cell.getName(), sdf.format((Date) cell.getValue()));
                        } else {
                            history.put(cell.getName(), cell.toString());
                        }
                    } else {
                        history.put(cell.getName(), cell.toString());
                    }
                }

                histories.add(history);
            }

            long endTime = System.currentTimeMillis();

            String logMessage = String.format("%s: getHistory executed in %d milliseconds", psrNumber,
                    endTime - startTime);
            System.out.println(logMessage);

            ((HashMap<String, Object>) this.data.get(psrNumber)).put("history", histories);
        }
    }

    synchronized (data) {
        // Do something funky with the first one
        Thread t = new Thread(new GetObjectData(jsonBody.get(0).toString(), data));
        t.start();
        t.join();

        ExecutorService executor = Executors.newFixedThreadPool(10);
        for (Object object : jsonBody.subList(1, jsonBody.size() - 1)) {
            executor.execute(new Thread(new GetObjectData(object.toString(), data)));
        }

        executor.shutdown();
        while (!executor.isTerminated()) {
        }
    }

    JSONObject obj = new JSONObject();
    obj.put("data", data);
    return obj;
}