Example usage for org.json.simple JSONArray toJSONString

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

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:com.cabserver.handler.Admin.java

@GET
@Path("drivers/list/non-company")
@Produces(MediaType.TEXT_HTML)//from   w w w. ja v  a 2  s  .  c o  m
public Response getNonCompanyDriversList() {
    JSONArray arryTM = new JSONArray();
    try {

        TravelMaster tm = new TravelMaster();

        ArrayList<DriverMaster> driverMasterArryList = DatabaseManager.getAllNonCompanyDriverDetails();

        for (DriverMaster tmpDm : driverMasterArryList) {
            JSONObject obj1 = new JSONObject();

            obj1.put("code", "200");
            obj1.put("msg", "Drivers list fetched.");
            obj1.put("driverId", tmpDm.getDriverId());
            obj1.put("firstName", tmpDm.getFirstName());
            obj1.put("lastName", tmpDm.getLastName());
            obj1.put("phone", tmpDm.getPhoneNumber());
            obj1.put("age", tmpDm.getAge() + "");
            obj1.put("sex", tmpDm.getSex());
            obj1.put("licNumber", tmpDm.getDriverLicense());
            obj1.put("address", tmpDm.getAddress());
            obj1.put("currAddress", tmpDm.getCurrAddr());
            obj1.put("driverStatus", tmpDm.getDriverStatus());
            obj1.put("driverCategory", tmpDm.getDriverCategory());

            arryTM.add(obj1);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    if (arryTM.size() < 1) {

        /*
         * log.info("getNonCompanyDriversList >> Drivers search ErrorCode is "
         * + Constants.BOOKING_FAILED_CODE + ".");
         */

        JSONObject obj1 = new JSONObject();
        obj1.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE"));
        obj1.put("msg", "Drivers list not found.");
        arryTM.add(obj1);

        return Response.status(200).entity(arryTM.toJSONString()).build();
    } else {
        return Response.status(200).entity(arryTM.toJSONString()).build();
    }

}

From source file:com.cabserver.handler.Admin.java

@GET
@Path("bookings/pending")
@Produces(MediaType.TEXT_HTML)/*www  . ja  v  a  2  s .c om*/
public Response getPendingBookingsList(String jsonData) {
    // String data = "";
    JSONArray arryTM = new JSONArray();
    try {

        ArrayList<TravelMaster> trvlMstrArryLst = DatabaseManager.getAllBookingDetailsByStatusCode();

        for (TravelMaster tmpTm : trvlMstrArryLst) {
            JSONObject obj1 = new JSONObject();

            obj1.put("code", "200");
            obj1.put("msg", "Bookings list fetched.");
            obj1.put("bookingId", tmpTm.getBookingId());
            obj1.put("userId", tmpTm.getUserId());
            obj1.put("name", tmpTm.getTravellerName());
            obj1.put("phone", tmpTm.getTravellerPhone());
            obj1.put("datetime", tmpTm.getBookingDateTime().toString());
            obj1.put("from", tmpTm.getFrom());
            obj1.put("to", tmpTm.getTo());
            obj1.put("bookingStatus", tmpTm.getBookingStatus());
            obj1.put("bookingStatusCode", tmpTm.getBookingStatusCode());
            obj1.put("isBefore", tmpTm.isBefore());

            obj1.put("noOfPassengers", tmpTm.getNoOfPassengers());
            obj1.put("mobileOperator", tmpTm.getMobileOperator());
            obj1.put("airline", tmpTm.getAirline());
            obj1.put("flightNumber", tmpTm.getFlightNumber());

            arryTM.add(obj1);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    if (arryTM.size() < 1) {

        log.info("getPendingBookingsList >> No pending bookings found. HTTP bookingStatus code is "
                + ConfigDetails.constants.get("BOOKING_FAILED_CODE") + ".");

        JSONObject obj1 = new JSONObject();
        obj1.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE"));
        obj1.put("msg", "No pending bookings.");
        arryTM.add(obj1);

        return Response.status(200).entity(arryTM.toJSONString()).build();
    } else {
        return Response.status(200).entity(arryTM.toJSONString()).build();
    }

}

From source file:com.cabserver.handler.Driver.java

@GET
@Path("locations")
@Produces(MediaType.TEXT_HTML)// ww  w.  j a va2s.com
public Response getDriversLocation() {
    // String data = "";

    JSONArray jsonArray = null;
    try {

        // log.info("Inside Driver >> getDriversLocation");

        if (CacheBuilder.driversDataMap.size() > 0) {

            Set<Long> keys = CacheBuilder.driversDataMap.keySet();
            jsonArray = new JSONArray();

            for (long key : keys) {
                try {

                    DriverMaster dm = CacheBuilder.driversDataMap.get(key);

                    long currentTime = MyUtil.getCalanderFromDateStr(MyUtil.getCurrentDateFormattedString())
                            .getTimeInMillis();
                    long driverLastLocUpdateTime = dm.getLocationUpdateTime().getTime();

                    long driverInActiveTimeDiff = currentTime - driverLastLocUpdateTime;

                    if (driverInActiveTimeDiff < Long
                            .parseLong(ConfigDetails.constants.get("DRIVER_MAP_ICON_DISABLE_TIME"))) {

                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put("driverId", dm.getDriverId() + "");
                        map.put("firstName", dm.getFirstName());
                        map.put("phoneNumber", dm.getPhoneNumber());
                        map.put("driverStatus", dm.getDriverStatus());
                        map.put("currAddr", dm.getCurrAddr());
                        map.put("currLongt", dm.getCurrLongt());
                        map.put("currLat", dm.getCurrLat());
                        map.put("bookingId", dm.getBookingId());
                        map.put("code", "200");
                        map.put("msg", "Driver details fetched.");
                        JSONObject obj = new JSONObject();
                        obj.putAll(map);
                        jsonArray.add(obj);

                    } else {
                        log.info("getDriversLocation >> DriverId= " + dm.getDriverId() + " is Inactive");
                    }

                } catch (Exception e) {

                }
            }

        } else {

            HashMap<String, String> map = new HashMap<String, String>();
            map.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE"));
            map.put("msg", "No drivers are provisioned.");
            JSONObject obj = new JSONObject();
            obj.putAll(map);
            jsonArray.add(obj);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    if (jsonArray.size() < 1) {

        log.info("getDriversLocation >> Bookings Error. HTTP bookingStatus code is "
                + ConfigDetails.constants.get("BOOKING_FAILED_CODE") + ".");

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE"));
        map.put("msg", "Server Error.");
        JSONObject obj = new JSONObject();
        obj.putAll(map);
        jsonArray.add(obj);

        return Response.status(200).entity(jsonArray.toJSONString()).build();
    } else {
        return Response.status(200).entity(jsonArray.toJSONString()).build();
    }

}

From source file:ca.mcgill.cs.creco.logic.ConcreteServiceFacade.java

@Override
public String getCompletions(String pInput) {
    if (pInput.length() <= MIN_NUMBER_OF_TYPED_LETTERS) {
        return "";
    }//from w  w w  .  jav  a 2  s  .  c o m
    String[] result_set = new String[100];
    int pointer = 0;
    String temp = new String("");
    int index = 0;
    JSONArray response = new JSONArray();
    JSONObject obj = new JSONObject();

    for (Category category : aDataStore.getCategories()) {
        if (category.getNumberOfProducts() == 0) {
            continue;
        }
        if (category.getName().toLowerCase().contains(pInput.toLowerCase())) {
            result_set[pointer++] = category.getName().toLowerCase();
            result_set[pointer++] = "Category";
        }
    }
    Set<String> collectedbrandstillnow = new HashSet<String>();
    Set<String> collectedtexttillnow = new HashSet<String>();
    Set<String> brands = new HashSet<String>();
    Set<String> textSearch = new HashSet<String>();
    for (Product productname : aDataStore.getProducts()) {
        if (productname.getName().toLowerCase().contains(pInput.toLowerCase())) {
            for (String productspace : productname.getName().toLowerCase().split(" ")) {
                if (productspace.contains(pInput.toLowerCase())) {
                    if (productspace.equals(productname.getBrandName().toLowerCase())) {
                        if (collectedbrandstillnow.contains(productspace)) {

                        } else {
                            collectedbrandstillnow.add(productspace);
                            brands.add(productspace);
                        }
                    } else if (collectedtexttillnow.contains(productspace)
                            || collectedbrandstillnow.contains(productspace)) {
                    } else {
                        collectedtexttillnow.add(productspace);
                        int count = 0;
                        for (int i = 0; i < productspace.length(); i++) {
                            if (Character.isDigit(productspace.charAt(i))) {
                                count++;
                            }
                        }
                        if (count < 2 && !productspace.contains("(") && !productspace.contains(")")) {
                            textSearch.add(productspace);
                        }
                    }
                }
            }
        }
    }

    for (String brandname : brands) {
        if (Arrays.asList(result_set).contains(brandname)) {
            index = Arrays.asList(result_set).indexOf(brandname);
            result_set[index + 1] = result_set[index + 1].concat("|Brand");
            temp = result_set[0];
            result_set[0] = result_set[index];
            result_set[index] = temp;
            temp = result_set[1];
            result_set[1] = result_set[index + 1];
            result_set[index + 1] = temp;
        } else {
            result_set[pointer++] = brandname;
            result_set[pointer++] = "Brand";
        }
    }
    for (String textname : textSearch) {
        if (Arrays.asList(result_set).contains(textname)) {
            index = Arrays.asList(result_set).indexOf(textname);
            result_set[index + 1] = result_set[index + 1].concat("|Product");
            temp = result_set[0];
            result_set[0] = result_set[index];
            result_set[index] = temp;
            temp = result_set[1];
            result_set[1] = result_set[index + 1];
            result_set[index + 1] = temp;
        } else {
            result_set[pointer++] = textname;
            result_set[pointer++] = "Product";
        }
    }

    for (index = 0; index < result_set.length; index = index + 2) {
        obj.put("name", result_set[index]);
        obj.put("type", result_set[index + 1]);
        response.add(obj);
        obj = new JSONObject();
    }
    return response.toJSONString();
}

From source file:net.sourceforge.fenixedu.domain.student.Registration.java

@SuppressWarnings("unchecked")
public static String readAllStudentInfo() {
    JSONArray infos = new JSONArray();
    for (Registration registration : Bennu.getInstance().getRegistrationsSet()) {
        if (registration.isConcluded()) {
            ExecutionYear conclusionYear = new RegistrationConclusionBean(registration)
                    .calculateConclusionYear();
            String endDate = Integer.toString(conclusionYear.getEndDateYearMonthDay().getYear());
            String startDate = Integer.toString(registration.getStartDate().getYear());
            String studentName = registration.getName();
            String email = registration.getEmail();
            String number = Integer.toString(registration.getNumber());
            // String number =
            // Integer.toString(registration.getStudent().getNumber());
            String degreeRemoteOid = registration.getDegree().getExternalId();
            String username = registration.getPerson().getUsername();
            JSONObject studentInfo = new JSONObject();
            studentInfo.put("username", username);
            studentInfo.put("studentName", studentName);
            studentInfo.put("email", email);
            studentInfo.put("number", number);
            studentInfo.put("endDate", endDate);
            studentInfo.put("startDate", startDate);
            studentInfo.put("degreeRemoteOid", degreeRemoteOid);
            infos.add(studentInfo);/*from w  w w  .j av  a 2 s .  c  o  m*/
        }
    }
    final String jsonString = infos.toJSONString();
    return jsonString;
}

From source file:com.cabserver.handler.Admin.java

@POST
@Path("customers/list")
@Produces(MediaType.TEXT_HTML)//from   w  w  w .ja  v  a  2 s .  c  o m
public Response getCustomersList(String jsonData) {
    // String data = "";
    // HashMap<String, String> responseMap = new HashMap<String, String>();
    JSONArray arryTM = new JSONArray();
    try {

        // log.info("getCustomersList >> before decoding =" + jsonData);

        jsonData = (URLDecoder.decode(jsonData, "UTF-8"));

        // log.info("getCustomersList >> after decoding =" + jsonData);

        // jsonData = jsonData.split("=")[1];

        if (jsonData.contains("=")) {
            jsonData = jsonData.split("=")[1];
            // log.info("getCustomersList >> = sign found");
        }

        log.info("getCustomersList >> after split =" + jsonData);

        TravelMaster tm = new TravelMaster();

        if (jsonData != null && jsonData.length() > 1) {

            // Gson gson = new Gson();
            JSONParser parser = new JSONParser();
            JSONObject obj = (JSONObject) parser.parse(jsonData);

            String phone = (String) obj.get("phone");
            // log.info("phone =" + phone);
            String name = (String) obj.get("name");
            // log.info("name =" + name);
            String mailId = (String) obj.get("mailId");
            // log.info("mailId =" + mailId);

            ArrayList<UserMaster> userMasterArryList = DatabaseManager.searchUsersFromUserMaster(phone, name,
                    mailId);

            for (UserMaster tmpUm : userMasterArryList) {
                JSONObject obj1 = new JSONObject();

                obj1.put("code", "200");
                obj1.put("msg", "Customers list fetched.");
                obj1.put("userId", tmpUm.getUserId());
                obj1.put("firstName", tmpUm.getFirstName());
                obj1.put("lastName", tmpUm.getLastName());
                obj1.put("phone", tmpUm.getPhone());
                obj1.put("sex", tmpUm.getSex());
                obj1.put("mailId", tmpUm.getMailId());
                obj1.put("address", tmpUm.getAddress());
                obj1.put("mobileOperator", tmpUm.getMobileOperator());

                arryTM.add(obj1);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (arryTM.size() < 1) {

        log.info("getCustomersList >> Customers search Error. HTTP customers search error code is "
                + ConfigDetails.constants.get("BOOKING_FAILED_CODE") + ".");

        JSONObject obj1 = new JSONObject();
        obj1.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE"));
        obj1.put("msg", "Customers list not found.");
        arryTM.add(obj1);

        return Response.status(200).entity(arryTM.toJSONString()).build();
    } else {
        return Response.status(200).entity(arryTM.toJSONString()).build();
    }

}

From source file:net.sourceforge.fenixedu.domain.student.Student.java

protected String getRegistrationsAsJSON(Set<Registration> registrations) {
    JSONArray infos = new JSONArray();
    int i = 0;//from   w  ww  .j a  v a  2  s.c om
    for (Registration registration : registrations) {
        JSONObject studentInfoForJobBank = new JSONObject();
        studentInfoForJobBank.put("username", registration.getPerson().getUsername());
        studentInfoForJobBank.put("hasPersonalDataAuthorization",
                registration.getStudent().hasPersonalDataAuthorizationForProfessionalPurposesAt().toString());
        Person person = registration.getStudent().getPerson();
        studentInfoForJobBank.put("dateOfBirth", person.getDateOfBirthYearMonthDay() == null ? null
                : person.getDateOfBirthYearMonthDay().toString());
        studentInfoForJobBank.put("nationality",
                person.getCountry() == null ? null : person.getCountry().getName());
        PhysicalAddress defaultPhysicalAddress = person.getDefaultPhysicalAddress();
        studentInfoForJobBank.put("address",
                defaultPhysicalAddress == null ? null : defaultPhysicalAddress.getAddress());
        studentInfoForJobBank.put("area",
                defaultPhysicalAddress == null ? null : defaultPhysicalAddress.getArea());
        studentInfoForJobBank.put("areaCode",
                defaultPhysicalAddress == null ? null : defaultPhysicalAddress.getAreaCode());
        studentInfoForJobBank.put("districtSubdivisionOfResidence", defaultPhysicalAddress == null ? null
                : defaultPhysicalAddress.getDistrictSubdivisionOfResidence());
        studentInfoForJobBank.put("mobilePhone", person.getDefaultMobilePhoneNumber());
        studentInfoForJobBank.put("phone", person.getDefaultPhoneNumber());
        studentInfoForJobBank.put("email", person.getEmailForSendingEmails());
        studentInfoForJobBank.put("remoteRegistrationOID", registration.getExternalId());
        studentInfoForJobBank.put("number", registration.getNumber().toString());
        studentInfoForJobBank.put("degreeOID", registration.getDegree().getExternalId());
        studentInfoForJobBank.put("isConcluded",
                String.valueOf(registration.isRegistrationConclusionProcessed()));
        studentInfoForJobBank.put("curricularYear", String.valueOf(registration.getCurricularYear()));
        for (CycleCurriculumGroup cycleCurriculumGroup : registration.getLastStudentCurricularPlan()
                .getCycleCurriculumGroups()) {
            studentInfoForJobBank.put(cycleCurriculumGroup.getCycleType().name(),
                    cycleCurriculumGroup.getAverage().toString());

        }
        infos.add(studentInfoForJobBank);
    }
    return infos.toJSONString();
}

From source file:hoot.services.controllers.ingest.BasemapResource.java

@POST
@Path("/upload")
@Produces(MediaType.TEXT_PLAIN)/*from   w  ww. j av a2s.  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.cabserver.handler.Admin.java

@POST
@Path("drivers/list")
@Produces(MediaType.TEXT_HTML)/*  w w  w.j av  a  2s .  co m*/
public Response getDriversList(String jsonData) {
    // String data = "";
    // HashMap<String, String> responseMap = new HashMap<String, String>();
    JSONArray arryTM = new JSONArray();
    try {

        // log.info("getDriversList >> before decoding =" + jsonData);

        jsonData = (URLDecoder.decode(jsonData, "UTF-8"));

        // log.info("getDriversList >> after decoding =" + jsonData);

        // jsonData = jsonData.split("=")[1];

        if (jsonData.contains("=")) {
            jsonData = jsonData.split("=")[1];
            // log.info("getDriversList >> = sign found");
        }

        log.info("getDriversList >> after split =" + jsonData);

        // TravelMaster tm = new TravelMaster();

        if (jsonData != null && jsonData.length() > 1) {

            // Gson gson = new Gson();
            JSONParser parser = new JSONParser();
            JSONObject obj = (JSONObject) parser.parse(jsonData);

            String phone = (String) obj.get("phone");
            // log.info("phone =" + phone);
            String name = (String) obj.get("name");
            // log.info("name =" + name);
            String licNumber = (String) obj.get("licNumber");
            // log.info("licNumber =" + licNumber);

            ArrayList<DriverMaster> driverMasterArryList = DatabaseManager.searchDriversFromDriverMaster(phone,
                    name, licNumber);

            for (DriverMaster tmpDm : driverMasterArryList) {
                JSONObject obj1 = new JSONObject();

                obj1.put("code", "200");
                obj1.put("msg", "Drivers list fetched.");
                obj1.put("driverId", tmpDm.getDriverId());
                obj1.put("firstName", tmpDm.getFirstName());
                obj1.put("lastName", tmpDm.getLastName());
                obj1.put("phone", tmpDm.getPhoneNumber());
                obj1.put("age", tmpDm.getAge() + "");
                obj1.put("sex", tmpDm.getSex());
                obj1.put("mailId", tmpDm.getMailId());
                obj1.put("licNumber", tmpDm.getDriverLicense());
                obj1.put("address", tmpDm.getAddress());
                obj1.put("currAddress", tmpDm.getCurrAddr());
                obj1.put("driverStatus", tmpDm.getDriverStatus());
                obj1.put("driverCategory", tmpDm.getDriverCategory());
                obj1.put("mobileOperator", tmpDm.getMobileOperator());

                arryTM.add(obj1);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (arryTM.size() < 1) {

        log.info("getDriversList >> Drivers search ErrorCcode is "
                + ConfigDetails.constants.get("BOOKING_FAILED_CODE") + ".");

        JSONObject obj1 = new JSONObject();
        obj1.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE"));
        obj1.put("msg", "Drivers list not found.");
        arryTM.add(obj1);

        return Response.status(200).entity(arryTM.toJSONString()).build();
    } else {
        return Response.status(200).entity(arryTM.toJSONString()).build();
    }

}

From source file:i5.las2peer.services.mobsos.SurveyService.java

@GET
@Produces(MediaType.APPLICATION_JSON)//from w ww.j a  va 2s .c  om
@Path("oidc/clients")
public HttpResponse getClientsMetadata() {

    String onAction = "retrieving metadata for clients";

    JSONArray result = new JSONArray();

    try {

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rset = null;

        try {
            conn = dataSource.getConnection();
            stmt = conn.prepareStatement(
                    "select client_id, client_name, client_description, client_uri, logo_uri from " + oidcSchema
                            + ".client_details order by client_name asc");

            rset = stmt.executeQuery();

            while (rset.next()) {
                JSONObject meta = new JSONObject();
                meta.put("id", rset.getString("client_id"));
                meta.put("name", rset.getString("client_name"));
                meta.put("description", rset.getString("client_description"));
                meta.put("uri", rset.getString("client_uri"));
                meta.put("logo", rset.getString("logo_uri"));
                result.add(meta);
            }

            HttpResponse rr = new HttpResponse(result.toJSONString());
            rr.setStatus(200);
            return rr;

        } catch (SQLException | UnsupportedOperationException e) {
            return internalError(onAction + e.getMessage());
        } finally {
            try {
                if (rset != null)
                    rset.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
            try {
                if (stmt != null)
                    stmt.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
            try {
                if (conn != null)
                    conn.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
        }
    }

    catch (Exception e) {
        e.printStackTrace();
        return internalError(onAction + " " + e.getMessage());
    }
}