Example usage for org.json.simple JSONArray iterator

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

Introduction

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

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this list in proper sequence.

Usage

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

/**
 *
 * @param tenantId tenantId//from w ww.j av  a  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/*from  w w  w.j a v  a 2s . 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 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.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 www  .  j  a v  a  2s.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;

}

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

@POST
@Consumes("application/json")
@Path("unsubscribe/tenant/{tenantDomain}/{type}/{typeId}")
public List<MobileApp> unsubscribeResource(@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 v  a  2s.  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, false);
            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) {
                        unsubscribeApp(registry, userId, appId);
                        showAppVisibilityToUser(artifact.getPath(), userId, "DENY");
                    }
                } else if ("user".equals(type)) {
                    unsubscribeApp(registry, typeId, appId);
                    showAppVisibilityToUser(artifact.getPath(), typeId, "DENY");
                }
            }

        }

    } 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 unsubscribe %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;

}

From source file:org.wso2.toolbox.nlp.table.CountryCodeLoader.java

public static Map<String, String> loadCountries() {
    Map<String, String> countryMap = new HashMap<String, String>();
    JSONParser parser = new JSONParser();

    try {//from   w ww .j ava2  s  . c  o m
        InputStream inputStream = CountryCodeLoader.class.getClassLoader().getResourceAsStream(COUNTRIES_JSON);
        Object obj = null;
        obj = parser.parse(new InputStreamReader(inputStream));

        JSONArray jsonArray = (JSONArray) obj;

        Iterator<JSONObject> it = jsonArray.iterator();

        while (it.hasNext()) {
            JSONObject country = it.next();
            countryMap.put((String) country.get("name"), (String) country.get("code"));
        }

    } catch (ParseException e) {
        logger.error("Error while parsing file [countries.json]", e);
    } catch (IOException e) {
        logger.error("Error while reading file [countries.json]", e);
    }
    return countryMap;
}

From source file:phonedirectory.PhoneDirectoryModel.java

public void jsonToDatabase(String json, String column[]) {

    JSONParser parser = new JSONParser();
    try {//  w w  w .  ja  va 2s  .  c o m
        Connection con = DriverManager.getConnection(url, user, password);
        stmt1 = con.createStatement();
        Object obj = parser.parse(new FileReader(new File(json)));
        JSONObject jsonObject = (JSONObject) obj;
        JSONArray persons = (JSONArray) jsonObject.get("Person");
        Iterator it = persons.iterator();
        while (it.hasNext()) {

            JSONObject jsonObject1 = (JSONObject) it.next();
            stmt = con.prepareStatement("insert into person(name,address) values(?,?)");
            stmt.setString(1, jsonObject1.get("Name").toString());
            stmt.setString(2, jsonObject1.get("Address").toString());
            stmt.executeUpdate();
            stmt.close();

            JSONArray phones = (JSONArray) jsonObject1.get("Phone");
            Iterator it1 = phones.iterator();
            int i = 2;

            rs = stmt1.executeQuery("select person_id from person");
            rs.last();
            int person_id = rs.getInt(1);

            stmt = con.prepareStatement("insert into phone values(?,?,?)");
            while (it1.hasNext()) {
                JSONObject o = ((JSONObject) it1.next());
                stmt.setString(1, o.get(column[i]).toString());
                stmt.setString(2, column[i]);
                stmt.setInt(3, person_id);
                stmt.executeUpdate();
                i++;
            }
            stmt.close();
        }
        con.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:playground.jbischoff.carsharing.data.DriveNowParser.java

public Map<Id<CarsharingVehicleData>, CarsharingVehicleData> grepAndDumpOnlineDatabase(String outputfolder) {
    JSONParser jp = new JSONParser();

    Map<Id<CarsharingVehicleData>, CarsharingVehicleData> currentGrep = new HashMap();
    try {//from w ww . j av a  2  s .co m
        Car2GoParser.disableCertificates();
        GetMethod get = new GetMethod("https://api2.drive-now.com/cities/6099/cars");

        get.setRequestHeader("X-Api-Key", "adf51226795afbc4e7575ccc124face7");

        HttpClient httpclient = new HttpClient();
        httpclient.executeMethod(get);

        BufferedReader in = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));
        JSONObject jsonObject = (JSONObject) jp.parse(in);

        BufferedWriter bw = IOUtils
                .getBufferedWriter(outputfolder + "dn_" + System.currentTimeMillis() + ".json.gz");
        bw.write(jsonObject.toString());
        bw.flush();
        bw.close();

        JSONArray items = (JSONArray) jsonObject.get("items");

        Iterator<JSONObject> iterator = items.iterator();
        while (iterator.hasNext()) {
            JSONObject car = (JSONObject) iterator.next();
            String vin = (String) car.get("id");
            String license = ((String) car.get("licensePlate")).replace(" ", "");

            Id<CarsharingVehicleData> vid = Id.create(vin, CarsharingVehicleData.class);
            String mileage = "0";
            String fuel = car.get("fuelLevel").toString();
            String latitude = car.get("latitude").toString();
            String longitude = car.get("longitude").toString();
            currentGrep.put(vid,
                    new CarsharingVehicleData(vid, license, latitude, longitude, mileage, fuel, "DN"));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return currentGrep;
}

From source file:priceModelValidation.AmazonSpotInstaces.java

@SuppressWarnings("unchecked")
public static void AmazonSpotInstanceOffering(LinkedUSDLModel jmodel) throws IOException, ParseException {

    //First, we fetch the JSON String from AmazonEC2

    String JsonString = IOUtils.toString(new URL(url).openStream());
    JsonString = JsonString.substring(9, JsonString.length() - 1);

    JSONParser parser = new JSONParser();
    Object obj = parser.parse(JsonString);

    JSONObject jsonObject = (JSONObject) obj;

    //Double version = (Double) jsonObject.get("vers");  

    JSONObject configs = (JSONObject) jsonObject.get("config");

    JSONArray regions = (JSONArray) (configs.get("regions"));
    Iterator<JSONObject> iterator = regions.iterator();

    //first region
    JSONObject reg = iterator.next();// ww  w  .  jav a 2  s.c  om
    //System.out.println(reg.get("region"));
    //String region = (String) reg.get("region");

    JSONArray instance_types = (JSONArray) reg.get("instanceTypes");
    Iterator<JSONObject> itemp = instance_types.iterator();

    JSONObject fdt = itemp.next();
    //System.out.println(fdt.get("type"));
    String instanceType = (String) fdt.get("type");

    JSONArray instance_details = (JSONArray) fdt.get("sizes");
    Iterator<JSONObject> itdetail = instance_details.iterator();

    JSONObject cont = itdetail.next();
    //System.out.println(cont.get("size"));
    String instname = (String) cont.get("size");

    JSONArray osoption = (JSONArray) cont.get("valueColumns");
    Iterator<JSONObject> osit = osoption.iterator();

    JSONObject osj = osit.next();
    //System.out.println(osj.get("name"));
    //String OSName = (String) osj.get("name");

    JSONObject instprice = (JSONObject) osj.get("prices");
    // System.out.println(osprice.get("USD"));
    Double instpricej = (Double.parseDouble((String) instprice.get("USD")));

    //first, create the services 
    Service s1 = new Service();

    s1.setName(instname + "-SI-" + instanceType);

    ArrayList<QuantitativeValue> s1QuantFeat = new ArrayList<QuantitativeValue>();//container for the Quantitative Features
    ArrayList<QualitativeValue> s1QualFeat = new ArrayList<QualitativeValue>();//container for the Qualitative Features

    //64 bits   1   3   3,75   1 x 4 SSD*6      Moderada
    QualitativeValue Arch = new QualitativeValue();
    Arch.addType(CLOUDEnum.BIT64.getConceptURI());
    Arch.setHasLabel("64Bits");
    s1QualFeat.add(Arch);

    QuantitativeValue CPUCores = null, CPUSpeed = null;
    CPUCores = new QuantitativeValue();
    CPUSpeed = new QuantitativeValue();

    CPUCores.addType(CLOUDEnum.CPUCORES.getConceptURI());
    CPUCores.setValue(4);

    CPUSpeed.addType(CLOUDEnum.CPUSPEED.getConceptURI());
    CPUSpeed.setValue(13);
    CPUSpeed.setUnitOfMeasurement("ECU");//EC2 Compute Unit
    s1QuantFeat.add(CPUCores);
    s1QuantFeat.add(CPUSpeed);

    // /MEMORYSIZE
    QuantitativeValue MemorySize = new QuantitativeValue();
    MemorySize.addType(CLOUDEnum.MEMORYSIZE.getConceptURI());
    MemorySize.setValue(15);
    MemorySize.setUnitOfMeasurement("E34");//GB
    s1QuantFeat.add(MemorySize);

    //DiskSize, StorageType
    QuantitativeValue DiskSize = new QuantitativeValue();
    QualitativeValue StorageType = new QualitativeValue();

    DiskSize.addType(CLOUDEnum.DISKSIZE.getConceptURI());
    DiskSize.setValue(80);
    DiskSize.setUnitOfMeasurement("E34");// GB

    StorageType.addType(CLOUDEnum.STORAGETYPE.getConceptURI());
    StorageType.setHasLabel("SSD");
    s1QuantFeat.add(DiskSize);
    s1QualFeat.add(StorageType);

    //MONITORING
    QualitativeValue monitoring = new QualitativeValue();
    monitoring.addType(CLOUDEnum.MONITORING.getConceptURI());
    monitoring.setHasLabel("Basic");
    monitoring.setComment(
            "As mtricas de monitoramento bsico (com frequncia de cinco minutos) para instncias do Amazon EC2 so gratuitas, assim como todas as mtricas para os volumes do Amazon EBS, Elastic Load Balancers e as instncias do banco de dados do Amazon RDS.");
    s1QualFeat.add(monitoring);

    //Performance
    QualitativeValue performance = new QualitativeValue();
    performance.addType(CLOUDEnum.PERFORMANCE.getConceptURI());
    performance.setHasLabel("Moderate");

    //OS
    QualitativeValue os = new QualitativeValue();
    os.addType(CLOUDEnum.UNIX.getConceptURI());
    os.setHasLabel("Linux");
    s1QualFeat.add(os);

    //Location
    QualitativeValue Location = new QualitativeValue();
    Location.addType(CLOUDEnum.LOCATION.getConceptURI());
    Location.setHasLabel("East USA - North Virginia");

    //DATA, in order to simplify the modeling of the offering, we'll only consider traffic from the internet into the EC2 instance and from the EC2 instance to the internet

    QuantitativeValue DATAINEXTERNAL = new QuantitativeValue();
    QuantitativeValue DATAININTERNAL = new QuantitativeValue();
    QuantitativeValue DATAOUTEXTERNAL = new QuantitativeValue();
    //QuantitativeValue DATAOUTINTERNAL  = new QuantitativeValue(); 

    DATAINEXTERNAL.addType(CLOUDEnum.DATAINEXTERNAL.getConceptURI());
    DATAINEXTERNAL.setValue(Double.MAX_VALUE);//unlimited
    s1QuantFeat.add(DATAINEXTERNAL);

    DATAININTERNAL.addType(CLOUDEnum.DATAININTERNAL.getConceptURI());
    DATAININTERNAL.setValue(Double.MAX_VALUE);//unlimited
    s1QuantFeat.add(DATAININTERNAL);

    DATAOUTEXTERNAL.addType(CLOUDEnum.DATAOUTEXTERNAL.getConceptURI());
    DATAOUTEXTERNAL.setMaxValue(350 * 1024);//let's assume a maximum of 350TB since in their website there isn't any detailed info about their pricing for transferrals of 350TB++
    DATAOUTEXTERNAL.setUnitOfMeasurement("E34");

    s1QuantFeat.add(DATAOUTEXTERNAL);

    s1.setQuantfeatures(s1QuantFeat);
    s1.setQualfeatures(s1QualFeat);
    //now we create an offering and its priceplan for the created service.

    Offering of = new Offering();
    of.addService(s1);
    of.setName(instname + "-SI Offering");

    PricePlan pp = new PricePlan();
    of.setPricePlan(pp);

    pp.setName("PricePlan-" + instname + "-SI");

    PriceComponent pc_hourly = new PriceComponent();//Component that is responsible for calculating the price per hour of the instance
    pp.addPriceComponent(pc_hourly);
    pc_hourly.setName("HourlyPC-PP" + instname + "-SI");

    PriceFunction pf_hourly = new PriceFunction();
    pc_hourly.setPriceFunction(pf_hourly);
    pf_hourly.setName(instname + "-SI-hourly_cost");

    Usage NumberOfHours = new Usage();
    pf_hourly.addUsageVariable(NumberOfHours);
    NumberOfHours.setName("NumberOfHours" + "TIME" + System.nanoTime());
    NumberOfHours.setComment("The number of hours that you'll be using the instance.");

    Provider CostPerHour = new Provider();
    pf_hourly.addProviderVariable(CostPerHour);
    CostPerHour.setName("CostPerHour" + "TIME" + System.nanoTime());
    QuantitativeValue val = new QuantitativeValue();
    CostPerHour.setValue(val);
    val.setValue(instpricej);
    val.setUnitOfMeasurement("USD");

    pf_hourly.setStringFunction(CostPerHour.getName() + "*" + NumberOfHours.getName());

    PriceComponent traffic_pc = new PriceComponent();//Component responsible for calculating the total price to pay related only to the Data transferral on Amazon EC2
    pp.addPriceComponent(traffic_pc);
    traffic_pc.setName("DataCostPC-PP" + instname + "-OD");

    PriceFunction data_cost_pf = new PriceFunction();
    traffic_pc.setPriceFunction(data_cost_pf);
    data_cost_pf.setName(instname + "-SI-data_transferrals_cost");

    Provider price10 = new Provider();
    data_cost_pf.addProviderVariable(price10);
    price10.setName("price10" + "TIME" + System.nanoTime());
    QuantitativeValue valb = new QuantitativeValue();
    price10.setValue(valb);
    valb.setValue(0.12);
    valb.setUnitOfMeasurement("USD");

    Provider price40 = new Provider();
    data_cost_pf.addProviderVariable(price40);
    price40.setName("price40" + "TIME" + System.nanoTime());
    QuantitativeValue valc = new QuantitativeValue();
    price40.setValue(valc);
    valc.setValue(0.09);
    valc.setUnitOfMeasurement("USD");

    Provider price100 = new Provider();
    data_cost_pf.addProviderVariable(price100);
    price100.setName("price100" + "TIME" + System.nanoTime());
    QuantitativeValue vald = new QuantitativeValue();
    price100.setValue(vald);
    vald.setValue(0.07);
    vald.setUnitOfMeasurement("USD");

    Provider price350 = new Provider();
    data_cost_pf.addProviderVariable(price350);
    price350.setName("price350" + "TIME" + System.nanoTime());
    QuantitativeValue vale = new QuantitativeValue();
    price350.setValue(vale);
    vale.setValue(0.05);
    vale.setUnitOfMeasurement("USD");

    Usage gbout = new Usage();
    data_cost_pf.addUsageVariable(gbout);
    gbout.setName("gbout" + "TIME" + System.nanoTime());
    gbout.setComment("Total GB of data that you expect to send out from Amazon EC2 to the internet.");

    data_cost_pf.setStringFunction("  IF (" + gbout.getName() + "<= 1) ; 1 * 0.00 ~ ELSEIF" + gbout.getName()
            + " > 1 && " + gbout.getName() + " <= 10*1024 ; 1*0.00 + (" + gbout.getName() + "-1) * "
            + price10.getName() + " ~ ELSEIF (" + gbout.getName() + " > 10*1024) && (" + gbout.getName()
            + "<= 40*1024) ; 1*0.00 + 10*1024*" + price10.getName() + " + (" + gbout.getName() + "-10*1024-1)*"
            + price40.getName() + " ~ ELSEIF (" + gbout.getName() + " >= 40*1024) && (" + gbout.getName()
            + " < 100*1024) ; 1*0.00 + 10*1024*" + price10.getName() + " + 40*1024*" + price40.getName()
            + " + (" + gbout.getName() + "-1-10*1024-40*1024)*" + price100.getName() + " ~ ELSEIF ("
            + gbout.getName() + " >= 100*1024) && (" + gbout.getName() + " < 350*1024) ; 1*0.00 + 10*1024*"
            + price10.getName() + " + 40*1024*" + price40.getName() + " + 100*1024*" + price100.getName()
            + " + (" + gbout.getName() + "-1-10*1024-40*1024-100*1024)*" + price350.getName() + "");

    //END

    ArrayList<Offering> offs = new ArrayList<Offering>();
    offs.add(of);

    jmodel.setOfferings(offs);

}

From source file:report.builder.ListBuilder.java

/**
 * Initializes the FieldsMetaData with the key of the JSON data
 * and adds the list to the report's context.
 * @param listObject The JSON list object.
 *///from   ww w .ja v a 2  s  . co m
@Override
public void build(JSONObject json, FieldsMetadata metadata, IContext context) {
    // Iterates on all the list:
    Iterator<?> iter = json.entrySet().iterator();
    while (iter.hasNext()) {
        // Gets the key and the array:
        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iter.next();
        String key = entry.getKey().toString();
        JSONArray array = (JSONArray) entry.getValue();

        // Gets the FieldsMetaData, searching for all different keys on the Map:
        HashSet<String> metaData = new HashSet<String>();
        Iterator<?> iterArray = array.iterator();
        while (iterArray.hasNext()) {
            JSONObject map = (JSONObject) iterArray.next();
            Iterator<?> iterMap = map.entrySet().iterator();
            while (iterMap.hasNext()) {
                Map.Entry<?, ?> entryMap = (Map.Entry<?, ?>) iterMap.next();
                metaData.add(entryMap.getKey().toString());
            }
        }

        // Sets the FieldsMetaData:
        Iterator<?> iterMetaData = metaData.iterator();
        while (iterMetaData.hasNext()) {
            metadata.addFieldAsList(key + "." + iterMetaData.next().toString());
        }

        // Adds the array to the report's context.
        // array can be directly passed as a value for contextMap because it inherits from ArrayList.
        context.put(key, array);
    }
}

From source file:riakdb.RiakDB.java

public static void main(String[] args)
        throws UnknownHostException, ExecutionException, InterruptedException, IOException, ParseException {

    client = RiakClient.newClient(8087, "127.0.0.1");

    YokozunaIndex subIndex = new YokozunaIndex("subInd");
    YokozunaIndex objIndex = new YokozunaIndex("objInd");

    StoreIndex subStoreIndex = new StoreIndex.Builder(subIndex).build();
    StoreIndex objStoreIndex = new StoreIndex.Builder(objIndex).build();

    client.execute(subStoreIndex);//from www  . ja v  a 2s  . co  m
    client.execute(objStoreIndex);

    Namespace subNamespace = new Namespace("sub");
    Namespace objNamespace = new Namespace("obj");

    StoreBucketProperties subProp = new StoreBucketProperties.Builder(subNamespace).withSearchIndex("subInd")
            .build();

    client.execute(subProp);

    StoreBucketProperties objProp = new StoreBucketProperties.Builder(objNamespace).withSearchIndex("objInd")
            .build();
    client.execute(objProp);

    //http://docs.basho.com/riak/latest/dev/using/search/

    int id = 0;
    String filePath = args[0]; //"subjects";
    FileReader reader = new FileReader(filePath);
    JSONParser jsonParser = new JSONParser();
    Object jsonObject = jsonParser.parse(reader);
    JSONArray sub = (JSONArray) jsonObject;
    Iterator i = sub.iterator();

    while (i.hasNext()) {

        RiakObject object = new RiakObject().setContentType("application/json")
                .setValue(BinaryValue.create(i.next().toString()));
        Location location = new Location(subNamespace, Integer.toString(id));

        StoreValue sv = new StoreValue.Builder(object).withLocation(location).build();
        client.execute(sv);
        id = id + 1;
    }

    String filePath2 = args[1]; //"obj";
    FileReader reader2 = new FileReader(filePath2);
    JSONParser jsonParser2 = new JSONParser();
    Object jsonObject2 = jsonParser2.parse(reader2);
    JSONArray obj = (JSONArray) jsonObject2;
    Iterator j = obj.iterator();

    while (j.hasNext()) {

        RiakObject object = new RiakObject().setContentType("application/json")
                .setValue(BinaryValue.create(j.next().toString())); // 
        //id - ?- 
        Location location = new Location(objNamespace, Integer.toString(id));

        StoreValue sv = new StoreValue.Builder(object).withLocation(location).build();
        client.execute(sv);
        id = id + 1;
    }

    String username = "alex";
    String path = "/home/alex/file3";
    String right = "rw";
    boolean status = CanDoIn(username, path, right);
    System.out.println("CanDoIt say " + status);

    client.shutdown();
}