Example usage for org.json.simple JSONValue JSONValue

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

Introduction

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

Prototype

JSONValue

Source Link

Usage

From source file:Controladora.ConexionAPI.java

public List<Usuario> sendGetListaUsuarios(String token) {
    httpClient = null; // Objeto a travs del cual realizamos las peticiones
    request = null; // Objeto para realizar las peticiines HTTP GET o POST
    status = 0; // Cdigo de la respuesta HTTP
    reader = null; // Se usa para leer la respuesta a la peticin
    line = null; // Se usa para leer cada una de las lineas de texto de la respuesta

    List<Usuario> listaauxiliar = new ArrayList<Usuario>();
    Usuario usuario = new Usuario();

    // Instanciamos el objeto
    httpClient = new HttpClient();
    // Invocamos por GET
    String url = "http://localhost:8090/api/usuarios/";
    request = new GetMethod(url);
    // Aadimos los parmetros que deseemos a la peticin 
    request.setRequestHeader("token", token);
    try {//from  w  ww  .j a  v  a  2s .c o m
        // Leemos el cdigo de la respuesta HTTP que nos devuelve el servidor
        status = httpClient.executeMethod(request);
        // Vemos si la peticin se ha realizado satisfactoriamente
        if (status != HttpStatus.SC_OK) {
            System.out.println("Error\t" + request.getStatusCode() + "\t" + request.getStatusText() + "\t"
                    + request.getStatusLine());
        } else {
            // Leemos el contenido de la respuesta y realizamos el tratamiento de la misma.
            // En nuestro caso, simplemente mostramos el resultado por la salida estndar
            reader = new BufferedReader(
                    new InputStreamReader(request.getResponseBodyAsStream(), request.getResponseCharSet()));

            JSONParser parser = new JSONParser();

            JSONValue jsonvalue = new JSONValue();

            String tkn = null;

            System.out.println("entro AL WHILE");

            listaauxiliar = null;
            line = reader.readLine();
            while (line != null) {
                System.out.println(line);

                System.out.println("uno");
                // JSONObject jso = (JSONObject) parser.parse(line);
                JSONArray jo = (JSONArray) jsonvalue.parse(line);
                //(JSONArray) jso.get("");
                System.out.println("antes de iterar");
                Iterator<String> iterator = jo.iterator();
                System.out.println("depues de iterar");
                while (iterator.hasNext()) {
                    System.out.println("Entro al while iterador");
                    System.out.println(iterator.next());
                }
                System.out.println("SALIO al while iterador");
                /*usuario.setMail((String) jo.get("mail"));
                usuario.setNombre((String) jo.get("nombre"));
                usuario.setUsuario((String) jo.get("usuario"));
                listaauxiliar.add(usuario);
                        
                System.out.println((String) jo.get("mail"));
                System.out.println((String) jo.get("nombre"));
                System.out.println((String) jo.get("usuario"));*/

                line = reader.readLine();
            }
        }
    } catch (Exception ex) {
        System.err.println("Error\t: " + ex.getMessage());

        ex.printStackTrace();
    } finally {
        // Liberamos la conexin. (Tambin libera los stream asociados)
        request.releaseConnection();
    }
    return listaauxiliar;
}

From source file:org.wso2.carbon.appmgt.mdm.restconnector.utils.RestUtils.java

/**
 * If not exists generate new access key or return existing one.
 *
 * @param remoteServer bean that holds information about remote server
 * @param generateNewKey whether generate new access key or not
 * @return generated access key/*w  w w.j  ava2  s.  c om*/
 */
public static String getAPIToken(RemoteServer remoteServer, boolean generateNewKey) {

    if (!generateNewKey) {
        if (!(AuthHandler.authKey == null || "null".equals(AuthHandler.authKey))) {
            return AuthHandler.authKey;
        }
    }

    HttpClient httpClient = AppManagerUtil.getHttpClient(remoteServer.getTokenApiURL());
    HttpPost postMethod = null;
    HttpResponse response = null;
    String responseString = "";
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(
                new BasicNameValuePair(Constants.RestConstants.GRANT_TYPE, Constants.RestConstants.PASSWORD));
        nameValuePairs
                .add(new BasicNameValuePair(Constants.RestConstants.USERNAME, remoteServer.getAuthUser()));
        nameValuePairs
                .add(new BasicNameValuePair(Constants.RestConstants.PASSWORD, remoteServer.getAuthPass()));
        URIBuilder uriBuilder = new URIBuilder(remoteServer.getTokenApiURL());
        uriBuilder.addParameters(nameValuePairs);
        postMethod = new HttpPost(uriBuilder.build());

        postMethod.setHeader(Constants.RestConstants.AUTHORIZATION,
                Constants.RestConstants.BASIC + new String(Base64.encodeBase64((remoteServer.getClientKey()
                        + Constants.RestConstants.COLON + remoteServer.getClientSecret()).getBytes())));
        postMethod.setHeader(Constants.RestConstants.CONTENT_TYPE,
                Constants.RestConstants.APPLICATION_FORM_URL_ENCODED);
    } catch (URISyntaxException e) {
        String errorMessage = "Cannot construct the Httppost. Url Encoded error.";
        log.error(errorMessage, e);
        return null;
    }
    try {
        if (log.isDebugEnabled()) {
            log.debug("Sending POST request to API Token endpoint. Request path:  "
                    + remoteServer.getTokenApiURL());
        }

        response = httpClient.execute(postMethod);
        int statusCode = response.getStatusLine().getStatusCode();

        if (log.isDebugEnabled()) {
            log.debug("Status code " + statusCode + " received while accessing the API Token endpoint.");
        }

    } catch (IOException e) {
        String errorMessage = "Cannot connect to Token API Endpoint.";
        log.error(errorMessage, e);
        return null;
    }

    try {
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            responseString = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
        }

    } catch (IOException e) {
        String errorMessage = "Cannot get response body for auth.";
        log.error(errorMessage, e);
        return null;
    }
    JSONObject token = (JSONObject) new JSONValue().parse(responseString);

    AuthHandler.authKey = String.valueOf(token.get(Constants.RestConstants.ACCESS_TOKEN));
    return AuthHandler.authKey;
}

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  va  2s  .  co 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 .  java 2 s. c o 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//w w  w.  ja  v  a 2s  .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.appmgt.mdm.wso2mdm.MDMOperationsImpl.java

private String getAPIToken(String tokenApiURL, String clientKey, String clientSecret, String authUser,
        String authPass, boolean generateNewKey) {

    if (!generateNewKey) {
        if (!(AuthHandler.authKey == null || "null".equals(AuthHandler.authKey))) {
            return AuthHandler.authKey;
        }/*  www . ja v  a  2  s .  com*/
    }

    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(tokenApiURL);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new NameValuePair("grant_type", "password"));
    nameValuePairs.add(new NameValuePair("username", authUser));
    nameValuePairs.add(new NameValuePair("password", authPass));
    postMethod
            .setQueryString((NameValuePair[]) nameValuePairs.toArray(new NameValuePair[nameValuePairs.size()]));
    postMethod.addRequestHeader("Authorization",
            "Basic " + new String(Base64.encodeBase64((clientKey + ":" + clientSecret).getBytes())));
    postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    try {
        if (log.isDebugEnabled())
            log.debug("Sending POST request to API Token endpoint. Request path:  " + tokenApiURL);
        int statusCode = httpClient.executeMethod(postMethod);
        if (log.isDebugEnabled())
            log.debug("Status code " + statusCode + " received while accessing the API Token endpoint.");
    } catch (IOException e) {
        String errorMessage = "Cannot connect to Token API Endpoint";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
        return null;
    }

    String response = null;
    try {
        response = postMethod.getResponseBodyAsString();
    } catch (IOException e) {
        String errorMessage = "Cannot get response body for auth";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
        return null;
    }

    JSONObject token = (JSONObject) new JSONValue().parse(response);

    AuthHandler.authKey = String.valueOf(token.get("access_token"));
    return AuthHandler.authKey;
}

From source file:org.wso2.carbon.appmgt.mobile.store.Devices.java

private User setUserData(User user, String userString) {
    JSONObject userObj = (JSONObject) new JSONValue().parse(userString);
    user.setUsername((String) userObj.get("username"));
    user.setTenantDomain((String) userObj.get("tenantDomain"));
    user.setTenantId(Integer.valueOf(String.valueOf(userObj.get("tenantId"))));
    return user;//from  w  w w  .  jav  a 2  s  .c  om
}

From source file:org.wso2.carbon.appmgt.mobile.store.Operations.java

/**
 * Performs action on MDM//w ww.  j  a  v a 2s .c  o m
 * @param currentUser User who perform the action
 * @param tenantId Tenant Id
 * @param type Type of the resource (device, user or role)
 * @param params Collection of ids of the type
 */
public String performAction(String currentUser, String action, int tenantId, String type, String app,
        String[] params, String schedule, String isRemovable) throws MobileApplicationException {
    if (log.isDebugEnabled())
        log.debug("Action: " + action + ", tenantId: " + tenantId + ", type: " + type + ", app: " + app);
    MobileConfigurations configurations = MobileConfigurations.getInstance();

    ApplicationOperationAction applicationOperationAction = new ApplicationOperationAction();
    User user = new User();
    JSONObject userObj = (JSONObject) new JSONValue().parse(currentUser);
    user.setUsername((String) userObj.get("username"));
    user.setTenantDomain((String) userObj.get("tenantDomain"));
    user.setTenantId(Integer.valueOf(String.valueOf(userObj.get("tenantId"))));
    applicationOperationAction.setUser(user);
    applicationOperationAction.setAction(action);
    applicationOperationAction.setTenantId(tenantId);
    applicationOperationAction.setType(type);
    applicationOperationAction.setParams(params);
    applicationOperationAction.setConfigParams(configurations.getActiveMDMProperties());
    applicationOperationAction.setSchedule(schedule);
    applicationOperationAction.setIsRemovable(isRemovable);

    try {

        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(PrivilegedCarbonContext
                .getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName());

        CarbonContext cCtx = CarbonContext.getThreadLocalCarbonContext();
        Registry registry = cCtx.getRegistry(RegistryType.USER_GOVERNANCE);

        GovernanceUtils.loadGovernanceArtifacts((UserRegistry) registry);
        GenericArtifactManager artifactManager = new GenericArtifactManager((UserRegistry) registry,
                "mobileapp");
        GenericArtifact artifact = artifactManager.getGenericArtifact(app);

        ApplicationOperations applicationOperations = MDMServiceReferenceHolder.getInstance().getMDMOperation();
        App appToInstall = AppDataLoader.load(new App(), artifact, action, tenantId);
        applicationOperationAction.setApp(appToInstall);
        return applicationOperations.performAction(applicationOperationAction);

    } catch (UserStoreException e) {
        log.error("error occurred at the user store", e);
    } catch (GovernanceException e) {
        log.error("error occurred from governance registry", e);
    } catch (RegistryException e) {
        log.error("error occurred from registry", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

    return null;

}

From source file:org.wso2.carbon.appmgt.rest.api.store.impl.DevicesApiServiceImpl.java

@Override
public Response devicesGet(String query, Integer limit, Integer offset, String accept, String ifNoneMatch) {
    List<DeviceInfoDTO> allMatchedDevices = new ArrayList<>();
    DeviceListDTO deviceListDTO;//from  w  w w . j ava 2s. c  o m
    Devices devices = new Devices();
    String username = RestApiUtil.getLoggedInUsername();
    String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    int tenantId = -1;

    //pre-processing
    //setting default limit and offset values if they are not set
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    query = query == null ? "" : query;

    String searchType = AppMConstants.SEARCH_CONTENT_TYPE;
    String searchContent = "";
    if (!StringUtils.isBlank(query)) {
        String[] querySplit = query.split(":");
        if (querySplit.length == 2 && StringUtils.isNotBlank(querySplit[0])
                && StringUtils.isNotBlank(querySplit[1])) {
            searchType = querySplit[0];
            searchContent = querySplit[1];
        } else if (querySplit.length == 1) {
            searchContent = query;
        } else {
            RestApiUtil.handleBadRequest("Provided query parameter '" + query + "' is invalid", log);
        }
    }

    if (!searchContent.isEmpty()) {
        //currently it support only mobile apps. Query is given to support future enhancements
        if (!searchContent.equals("mobile")) {
            RestApiUtil.handleBadRequest(
                    "Provided query parameter value '" + searchContent + "' is not supported.", log);
        }
    }

    try {
        tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                .getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        RestApiUtil.handleInternalServerError("Error while initializing UserStore", e, log);
    }

    //building request parameters to required format
    String[] users = { username };
    JSONObject userObj = new JSONObject();
    userObj.put("username", username);
    userObj.put("tenantDomain", tenantDomain);
    userObj.put("tenantId", tenantId);

    String deviceList;
    try {
        deviceList = devices.getDevicesList(userObj.toJSONString(), tenantId, "user", users);
    } catch (MobileApplicationException e) {
        log.error("Error occurred while retrieving devices list");
        return RestApiUtil.buildInternalServerErrorException().getResponse();
    }

    if (deviceList.isEmpty()) {
        String errorMessage = "No devices found.";
        return RestApiUtil.buildNotFoundException(errorMessage, null).getResponse();
    }

    JSONArray deviceArr = (JSONArray) new JSONValue().parse(deviceList);

    for (int i = 0; i < deviceArr.size(); i++) {
        JSONObject jsonObject = (JSONObject) deviceArr.get(i);
        DeviceInfoDTO deviceInfoDTO = new DeviceInfoDTO();
        deviceInfoDTO.setId((String) jsonObject.get("id"));
        deviceInfoDTO.setImage((String) jsonObject.get("image"));
        deviceInfoDTO.setModel((String) jsonObject.get("model"));
        deviceInfoDTO.setName((String) jsonObject.get("name"));
        deviceInfoDTO.setPlatform((String) jsonObject.get("platform"));
        deviceInfoDTO.setPlatformVersion((String) jsonObject.get("platform_version"));
        deviceInfoDTO.setType((String) jsonObject.get("type"));
        allMatchedDevices.add(deviceInfoDTO);
    }

    if (allMatchedDevices.isEmpty()) {
        String errorMessage = "No result found.";
        return RestApiUtil.buildNotFoundException(errorMessage, null).getResponse();
    }

    deviceListDTO = DeviceMappingUtil.fromAPIListToDTO(allMatchedDevices, offset, limit);
    DeviceMappingUtil.setPaginationParams(deviceListDTO, query, offset, limit, allMatchedDevices.size());
    return Response.ok().entity(deviceListDTO).build();
}

From source file:org.wso2.carbon.appmgt.services.api.v1.apps.mobile.MobileAppService.java

@POST
@Consumes("application/json")
@Path("subscribe/tenant/{tenantDomain}/{type}/{typeId}")
public List<MobileApp> subscribeResource(@Context final HttpServletResponse servletResponse,
        @PathParam("type") String type, @PathParam("typeId") String typeId,
        @PathParam("tenantDomain") String tenantDomain, @Context HttpHeaders headers, String appsJSONString) {

    String currentApp = null;//from ww w  .j  a  va  2  s . c o m
    JSONArray appsIds = (JSONArray) new JSONValue().parse(appsJSONString);
    List<MobileApp> mobileApps = new ArrayList<MobileApp>();
    MobileApp mobileApp = null;

    try {

        Registry registry = doAuthorizeAndGetRegistry(tenantDomain, headers);
        int tenantId = ((UserRegistry) registry).getTenantId();

        GovernanceUtils.loadGovernanceArtifacts((UserRegistry) registry);
        GenericArtifactManager artifactManager = new GenericArtifactManager((UserRegistry) registry,
                "mobileapp");

        Iterator<String> iterator = appsIds.iterator();
        while (iterator.hasNext()) {
            String appId = iterator.next();
            currentApp = appId;
            GenericArtifact artifact = artifactManager.getGenericArtifact(appId);
            mobileApp = MobileAppDataLoader.load(new MobileApp(), artifact, tenantId, true);
            mobileApps.add(mobileApp);

            if (mobileApp != null) {

                if ("role".equals(type)) {
                    UserStoreManager userStoreManager = ((UserRegistry) registry).getUserRealm()
                            .getUserStoreManager();
                    String[] users = userStoreManager.getUserListOfRole(typeId);
                    for (String userId : users) {
                        subscribeApp(registry, userId, appId);
                        showAppVisibilityToUser(artifact.getPath(), userId, "ALLOW");
                    }
                } else if ("user".equals(type)) {
                    subscribeApp(registry, typeId, appId);
                    showAppVisibilityToUser(artifact.getPath(), typeId, "ALLOW");
                }

            }

        }

    } catch (GovernanceException e) {
        String errorMessage = "GovernanceException occurred";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
    } catch (UnauthorizedUserException e) {
        String errorMessage = "User is not authorized to access the API";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
        try {
            servletResponse.sendError(Response.Status.UNAUTHORIZED.getStatusCode());
        } catch (IOException e1) {
            errorMessage = "RegistryException occurred";
            if (log.isDebugEnabled()) {
                log.error(errorMessage, e1);
            } else {
                log.error(errorMessage);
            }
        }
    } catch (UserStoreException e) {
        String errorMessage = "UserStoreException occurred";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
    } catch (RegistryException e) {
        String errorMessage = "RegistryException occurred";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
    } catch (Exception e) {
        String errorMessage = String.format("Exception occurred while subscribe %s %s to app %", type, typeId,
                currentApp);
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
        try {
            servletResponse.sendError(Response.Status.UNAUTHORIZED.getStatusCode());
        } catch (IOException e1) {
            errorMessage = "RegistryException occurred";
            if (log.isDebugEnabled()) {
                log.error(errorMessage, e1);
            } else {
                log.error(errorMessage);
            }
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    return mobileApps;

}