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:org.wso2.carbon.appmgt.mdm.wso2emm.ApplicationOperationsImpl.java

/**
 *
 * @param applicationOperationDevice holds the information needs to retrieve device list
 * @return List of devices//from  w  w  w .j a  v a 2 s .c  o  m
 */

public List<Device> getDevices(ApplicationOperationDevice applicationOperationDevice) {

    HashMap<String, String> configProperties = applicationOperationDevice.getConfigParams();

    String serverURL = configProperties.get(Constants.PROPERTY_SERVER_URL);
    String authUser = configProperties.get(Constants.PROPERTY_AUTH_USER);
    String authPass = configProperties.get(Constants.PROPERTY_AUTH_PASS);

    List<Device> devices = new ArrayList<>();

    HttpClient httpClient = AppManagerUtil.getHttpClient(serverURL);
    int tenantId = applicationOperationDevice.getTenantId();
    String[] params = applicationOperationDevice.getParams();
    HttpGet getMethod = new HttpGet(serverURL + String.format(Constants.API_DEVICE_LIST, tenantId, params[0]));
    getMethod.setHeader(Constants.RestConstants.AUTHORIZATION, Constants.RestConstants.BASIC
            + new String(Base64.encodeBase64((authUser + ":" + authPass).getBytes())));
    try {
        HttpResponse response = httpClient.execute(getMethod);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            String responseString = "";
            if (entity != null) {
                responseString = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
            }

            JSONArray devicesArray = (JSONArray) new JSONValue().parse(responseString);
            if (log.isDebugEnabled())
                log.debug("Devices Received" + devicesArray.toJSONString());
            Iterator<JSONObject> iterator = devicesArray.iterator();
            while (iterator.hasNext()) {
                JSONObject deviceObj = iterator.next();
                Device device = new Device();
                device.setId(deviceObj.get("id").toString());
                JSONObject properties = (JSONObject) new JSONValue()
                        .parse(deviceObj.get("properties").toString());
                device.setName(properties.get("device").toString());
                device.setModel(properties.get("model").toString());
                if ("1".equals(deviceObj.get("platform_id").toString())) {
                    device.setPlatform("android");
                } else if ("2".equals(deviceObj.get("platform_id").toString())) {
                    device.setPlatform("ios");
                } else if ("3".equals(deviceObj.get("platform_id").toString())) {
                    device.setPlatform("ios");
                } else if ("4".equals(deviceObj.get("platform_id").toString())) {
                    device.setPlatform("ios");
                }
                device.setImage(
                        String.format(configProperties.get("ImageURL"), properties.get("model").toString()));
                device.setType("mobileDevice");
                device.setPlatformVersion("0");
                devices.add(device);

            }
        }
    } catch (IOException e) {
        String errorMessage = "Error while getting the device list from WSO2 EMM";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
    }
    return devices;
}

From source file:org.wso2.carbon.appmgt.mdm.wso2emm.MDMOperationsImpl.java

/**
 *
 * @param tenantId tenantId/*from  w w  w.j av  a  2  s  .  co m*/
 * @param type type of the resource. Eg: role, user, device
 * @param params ids of the resources which belong to type
 * @param platform platform of the devices
 * @param platformVersion platform version of the devices
 * @param isSampleDevicesEnabled if MDM is not connected, enable this to display sample devices.
 * @return
 */

public List<Device> getDevices(User currentUser, int tenantId, String type, String[] params, String platform,
        String platformVersion, boolean isSampleDevicesEnabled, HashMap<String, String> configProperties) {

    String serverURL = configProperties.get(Constants.PROPERTY_SERVER_URL);
    String authUser = configProperties.get(Constants.PROPERTY_AUTH_USER);
    String authPass = configProperties.get(Constants.PROPERTY_AUTH_PASS);

    List<Device> devices = new ArrayList<Device>();

    if (isSampleDevicesEnabled) {
        return Sample.getSampleDevices();
    } else {

        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(
                serverURL + String.format(Constants.API_DEVICE_LIST, tenantId, params[0]));
        getMethod.setRequestHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64((authUser + ":" + authPass).getBytes())));
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode == 200) {
                String response = getMethod.getResponseBodyAsString();
                JSONArray devicesArray = (JSONArray) new JSONValue().parse(response);
                if (log.isDebugEnabled())
                    log.debug("Devices Received" + devicesArray.toJSONString());
                Iterator<JSONObject> iterator = devicesArray.iterator();
                while (iterator.hasNext()) {
                    JSONObject deviceObj = iterator.next();
                    Device device = new Device();
                    device.setId(deviceObj.get("id").toString());
                    JSONObject properties = (JSONObject) new JSONValue()
                            .parse(deviceObj.get("properties").toString());
                    device.setName(properties.get("device").toString());
                    device.setModel(properties.get("model").toString());
                    if ("1".equals(deviceObj.get("platform_id").toString())) {
                        device.setPlatform("android");
                    } else if ("2".equals(deviceObj.get("platform_id").toString())) {
                        device.setPlatform("ios");
                    } else if ("3".equals(deviceObj.get("platform_id").toString())) {
                        device.setPlatform("ios");
                    } else if ("4".equals(deviceObj.get("platform_id").toString())) {
                        device.setPlatform("ios");
                    }
                    device.setImage(String.format(configProperties.get("ImageURL"),
                            properties.get("model").toString()));
                    device.setType("mobileDevice");
                    device.setPlatformVersion("0");
                    devices.add(device);

                }
            }
        } catch (IOException e) {
            String errorMessage = "Error while getting the device list from WSO2 EMM";
            if (log.isDebugEnabled()) {
                log.error(errorMessage, e);
            } else {
                log.error(errorMessage);
            }
        }
        return devices;
    }
}

From source file:org.wso2.carbon.appmgt.mdm.wso2mdm.MDMOperationsImpl.java

/**
 *
 * @param tenantId tenantId/* ww w.  ja va  2  s . c om*/
 * @param type type of the resource. Eg: role, user, device
 * @param params ids of the resources which belong to type
 * @param platform platform of the devices
 * @param platformVersion platform version of the devices
 * @param isSampleDevicesEnabled if MDM is not connected, enable this to display sample devices.
 * @return
 */

public List<Device> getDevices(User currentUser, int tenantId, String type, String[] params, String platform,
        String platformVersion, boolean isSampleDevicesEnabled, HashMap<String, String> configProperties) {

    String tokenApiURL = configProperties.get(Constants.PROPERTY_TOKEN_API_URL);
    String clientKey = configProperties.get(Constants.PROPERTY_CLIENT_KEY);
    String clientSecret = configProperties.get(Constants.PROPERTY_CLIENT_SECRET);
    String authUser = configProperties.get(Constants.PROPERTY_AUTH_USER);
    String authPass = configProperties.get(Constants.PROPERTY_AUTH_PASS);

    JSONArray jsonArray = null;

    if (isSampleDevicesEnabled) {
        return Sample.getSampleDevices();
    } else {

        HttpClient httpClient = new HttpClient();

        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);

        String deviceListAPI = String.format(Constants.API_DEVICE_LIST, params[0], tenantDomain);
        String requestURL = configProperties.get(Constants.PROPERTY_SERVER_URL) + deviceListAPI;
        GetMethod getMethod = new GetMethod(requestURL);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        //nameValuePairs.add(new NameValuePair("tenantId", String.valueOf(tenantId)));

        if (platform != null)
            nameValuePairs.add(new NameValuePair("platform", platform));

        if (platformVersion != null)
            nameValuePairs.add(new NameValuePair("platformVersion", platform));

        getMethod.setQueryString(
                (NameValuePair[]) nameValuePairs.toArray(new NameValuePair[nameValuePairs.size()]));
        getMethod.setRequestHeader("Accept", "application/json");

        if (executeMethod(tokenApiURL, clientKey, clientSecret, authUser, authPass, httpClient, getMethod)) {
            try {
                jsonArray = (JSONArray) new JSONValue().parse(new String(getMethod.getResponseBody()));
                if (jsonArray != null) {
                    if (log.isDebugEnabled())
                        log.debug("Devices received from MDM: " + jsonArray.toJSONString());
                }
            } catch (IOException e) {
                String errorMessage = "Invalid response from the devices API";
                if (log.isDebugEnabled()) {
                    log.error(errorMessage, e);
                } else {
                    log.error(errorMessage);
                }
            }
        } else {
            log.error("Getting devices from MDM API failed");
        }
    }

    if (jsonArray == null) {
        jsonArray = (JSONArray) new JSONValue().parse("[]");
    }

    List<Device> devices = new ArrayList<Device>();

    Iterator<JSONObject> iterator = jsonArray.iterator();
    while (iterator.hasNext()) {
        JSONObject deviceObj = iterator.next();

        Device device = new Device();
        device.setId(deviceObj.get("deviceIdentifier").toString() + "---" + deviceObj.get("type").toString());
        device.setName(deviceObj.get("name").toString());
        device.setModel(deviceObj.get("name").toString());
        device.setType("mobileDevice");
        device.setImage("/store/extensions/assets/mobileapp/resources/models/none.png");
        device.setPlatform(deviceObj.get("type").toString());
        devices.add(device);

    }

    return devices;
}

From source file:org.wso2.carbon.dashboard.migratetool.DSPortalAppMigrationTool.java

public void getDashboard() {

    String response = invokeRestAPI("https://localhost:9443/portal/apis/login?username=admin&password=admin",
            "POST", null);
    try {//from  ww  w  .  j  a  v a2  s . com
        JSONObject responseObj = (JSONObject) new JSONParser().parse(response.toString());
        response = invokeRestAPI("https://localhost:9443/portal/apis/dashboards", "GET",
                (String) responseObj.get("sessionId"));
        JSONArray responseArr = (JSONArray) new JSONParser().parse(response.toString());
        for (int dashboardCount = 0; dashboardCount < responseArr.size(); dashboardCount++) {
            // dashboardUpdater((JSONObject) responseArr[dashboardCount]);
        }
        System.out.println(responseArr.toJSONString());
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.device.mgt.input.adapter.extension.transformer.MQTTContentTransformer.java

private String processMultipleEvents(String msg, String deviceIdFromTopic, String deviceIdJsonPath)
        throws ParseException {
    JSONParser jsonParser = new JSONParser();
    JSONArray jsonArray = (JSONArray) jsonParser.parse(msg);
    JSONArray eventsArray = new JSONArray();
    for (int i = 0; i < jsonArray.size(); i++) {
        eventsArray.add(i,/*  w w w.j ava 2s .c  om*/
                processSingleEvent(jsonArray.get(i).toString(), deviceIdFromTopic, deviceIdJsonPath));
    }
    return eventsArray.toJSONString();
}

From source file:ProductRestfulServices.ProductsServices.java

@GET
@Produces(MediaType.APPLICATION_JSON)//from  w  w  w.j  ava  2 s .c o  m
public String getAllProducts() {
    JSONArray array = new JSONArray();
    try {
        String query = "SELECT * FROM product";
        PreparedStatement stmt = con.prepareStatement(query);
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            JSONObject obj = new JSONObject();
            obj.put("productId", rs.getInt("productid"));
            obj.put("productName", rs.getString("name"));
            obj.put("description", rs.getString("description"));
            obj.put("quantity", rs.getInt("quantity"));
            array.add(obj);
        }
    } catch (SQLException e) {
    }
    return array.toJSONString();
}

From source file:pt.ua.scaleus.service.RESTService.java

@GET
@Path("/dataset")
@Produces(MediaType.APPLICATION_JSON)//from   w  w w  .  j  a  va2 s  .c o  m
@Override
public Response listDataset() {
    Set<String> datasets = api.getDatasets().keySet();
    JSONArray json = new JSONArray();
    for (String dataset : datasets) {
        json.add(dataset);
    }
    return Response.status(200).entity(json.toJSONString()).build();
}

From source file:pt.ua.scaleus.service.RESTService.java

@GET
@Path("/properties/{database}/{match}")
@Produces(MediaType.APPLICATION_JSON)/*from  w w  w .  j a v  a2  s  . c  om*/
@Override
public Response getProperties(@PathParam("database") String database, @PathParam("match") String match) {
    JSONArray ja = new JSONArray();
    try {
        Set<String> prop = api.getProperties(database);
        for (String prop1 : prop) {
            if (prop1.contains(match)) {
                ja.add(prop1);
            }
        }
    } catch (Exception ex) {
        log.error("Service failed", ex);
        return Response.serverError().build();
    }
    return Response.status(200).entity(ja.toJSONString()).build();
}

From source file:pt.ua.scaleus.service.RESTService.java

@GET
@Path("/resources/{database}/{match}")
@Produces(MediaType.APPLICATION_JSON)//from  w w  w . j av  a  2  s.  com
@Override
public Response getResources(@PathParam("database") String database, @PathParam("match") String match) {
    JSONArray ja = new JSONArray();
    try {
        Set<String> prop = api.getResources(database);
        for (String prop1 : prop) {
            if (prop1.contains(match)) {
                ja.add(prop1);
            }
        }
    } catch (Exception ex) {
        log.error("Service failed", ex);
        return Response.serverError().build();
    }
    return Response.status(200).entity(ja.toJSONString()).build();
}

From source file:ru.prime.server.news.NewsServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w  w . j  a  v  a 2 s.  c o m
 *
 * @param request servlet request
 * @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;charset=UTF-8");

    PrintWriter out = response.getWriter();

    try {
        JSONArray result = new JSONArray();
        for (int i = 0; i < 10; i++) {
            JSONObject o = new JSONObject();
            o.put("header", "?? " + i);
            result.add(o);
        }

        out.print(result.toJSONString());
    } finally {
        out.close();
    }
}