Example usage for org.json JSONObject keys

List of usage examples for org.json JSONObject keys

Introduction

In this page you can find the example usage for org.json JSONObject keys.

Prototype

public Iterator keys() 

Source Link

Document

Get an enumeration of the keys of the JSONObject.

Usage

From source file:com.tassadar.multirommgr.installfragment.UbuntuManifest.java

public boolean downloadAndParse(Device dev) {
    ByteArrayOutputStream out = new ByteArrayOutputStream(8192);
    try {//www  . j  av  a2  s  .co m
        final String url = dev.getUbuntuBaseUrl() + CHANNELS_PATH;
        if (!Utils.downloadFile(url, out, null, true) || out.size() == 0)
            return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        Object rawObject = new JSONTokener(out.toString()).nextValue();
        if (!(rawObject instanceof JSONObject)) {
            Log.e(TAG, "Malformed manifest format!");
            return false;
        }

        JSONObject o = (JSONObject) rawObject;
        SharedPreferences pref = MgrApp.getPreferences();

        Iterator itr = o.keys();
        while (itr.hasNext()) {
            String name = (String) itr.next();
            JSONObject c = o.getJSONObject(name);

            // Skip hidden channels
            if (c.optBoolean("hidden", false) && !pref.getBoolean(SettingsFragment.UTOUCH_SHOW_HIDDEN, false)) {
                continue;
            }

            addChannel(name, c);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }

    // Remove channels without the device we're currently running on and load images
    Iterator<Map.Entry<String, TreeMap<String, UbuntuChannel>>> f_itr = m_flavours.entrySet().iterator();
    while (f_itr.hasNext()) {
        Map<String, UbuntuChannel> channelMap = f_itr.next().getValue();
        Iterator<Map.Entry<String, UbuntuChannel>> c_itr = channelMap.entrySet().iterator();
        while (c_itr.hasNext()) {
            UbuntuChannel c = c_itr.next().getValue();

            // Devices like deb or tilapia won't be in
            // Ubuntu Touch manifests, yet the versions
            // for flo/grouper work fine - select those.
            String dev_name = dev.getName();
            if (!c.hasDevice(dev_name)) {
                dev_name = dev.getBaseVariantName();

                if (!c.hasDevice(dev_name)) {
                    c_itr.remove();
                    continue;
                }
            }

            try {
                if (!c.loadDeviceImages(dev_name, dev))
                    return false;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            // Remove channels with no images for our device
            if (!c.hasImages()) {
                c_itr.remove();
                continue;
            }

            Log.d(TAG, "Got channel: " + c.getDisplayName());
        }

        if (channelMap.isEmpty())
            f_itr.remove();
    }
    return true;
}

From source file:org.protorabbit.json.JSONUtil.java

@SuppressWarnings("unchecked")
public static Object cloneJSON(Object target) {

    if (target == null)
        return JSONObject.NULL;

    if (target instanceof JSONObject) {
        Object o = null;//from  w  w w .  j  av  a 2 s .c o  m
        o = new JSONObject();
        JSONObject jo = (JSONObject) target;
        Iterator<String> it = jo.keys();
        while (it.hasNext()) {
            String key = it.next();
            try {
                ((JSONObject) o).put(key, cloneJSON(jo.get(key)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return o;
    } else if (target instanceof JSONArray) {
        Object o = new JSONArray();
        JSONArray ja = (JSONArray) target;
        int len = ja.length();
        for (int i = 0; i < len; i++) {
            try {
                ((JSONArray) o).put(cloneJSON(ja.get(i)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } else if (target instanceof Long) {
        return new Long(((Long) target).longValue());
    } else if (target instanceof Double) {
        return new Double(((Double) target).doubleValue());
    } else if (target instanceof Integer) {
        return new Integer(((Integer) target).intValue());
    } else if (target instanceof Boolean) {
        return new Boolean(((Boolean) target).booleanValue());
    }
    return target;
}

From source file:org.protorabbit.json.JSONUtil.java

@SuppressWarnings("unchecked")
public static void mixin(JSONObject child, JSONObject parent, String[] skip) {
    Iterator<String> it = parent.keys();
    while (it.hasNext()) {
        String key = it.next();/*from w  ww  . j av  a 2 s  . c o  m*/
        // don't mix in the skip
        for (int i = 0; i < skip.length; i++) {
            if (key.equals(skip[i])) {
                continue;
            }
        }
        if (child.has(key)) {
            continue;
        } else {
            Object o;
            try {
                o = parent.get(key);
                child.put(key, cloneJSON(o));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:tectonicus.blockTypes.BlockRegistry.java

public void deserializeBlockstates() {
    List<BlockVariant> blockVariants = new ArrayList<>();

    Enumeration<? extends ZipEntry> entries = zips.getBaseEntries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        String entryName = entry.getName();
        if (entryName.contains("blockstates")) {
            ZipStackEntry zse = zips.getEntry(entryName);
            try {
                JSONObject obj = new JSONObject(FileUtils.loadJSON(zse.getInputStream()));
                JSONObject variants = obj.getJSONObject("variants");

                Iterator<?> keys = variants.keys();
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    Object variant = variants.get(key);

                    blockVariants.add(BlockVariant.deserializeVariant(key, variant));
                }/*from  w w w  .j  av a 2s  .  c  o m*/
            } catch (Exception e) {
                e.printStackTrace();
            }

            String name = "minecraft:"
                    + StringUtils.removeEnd(entryName.substring(entryName.lastIndexOf("/") + 1), ".json");
            blockStates.put(name, blockVariants);
        }
    }
}

From source file:tectonicus.blockTypes.BlockRegistry.java

public BlockModel loadModel(String modelPath, ZipStack zips, Map<String, String> textureMap) throws Exception {
    ZipStackEntry modelFile = zips.getEntry("assets/minecraft/models/" + modelPath + ".json");

    JSONObject obj = new JSONObject(FileUtils.loadJSON(modelFile.getInputStream()));
    String parent = "";
    if (obj.has("parent")) // Get texture information and then load parent file
    {/*from  w ww  .ja va  2  s  .com*/
        parent = obj.getString("parent");

        return loadModel(parent, zips, populateTextureMap(textureMap, obj.getJSONObject("textures")));
    } else //Load all elements
    {
        Map<String, String> combineMap = new HashMap<>(textureMap);
        if (obj.has("textures")) {
            combineMap.putAll(populateTextureMap(textureMap, obj.getJSONObject("textures")));
        }

        List<BlockElement> elementsList = new ArrayList<>();

        boolean ao = true;
        if (obj.has("ambientocclusion"))
            ao = false;

        JSONArray elements = obj.getJSONArray("elements");
        for (int i = 0; i < elements.length(); i++) {
            Map<String, ElementFace> elementFaces = new HashMap<>();

            JSONObject element = elements.getJSONObject(i);

            JSONArray from = element.getJSONArray("from");
            Vector3f fromVector = new Vector3f((float) from.getDouble(0), (float) from.getDouble(1),
                    (float) from.getDouble(2));
            JSONArray to = element.getJSONArray("to");
            Vector3f toVector = new Vector3f((float) to.getDouble(0), (float) to.getDouble(1),
                    (float) to.getDouble(2));

            Vector3f rotationOrigin = new Vector3f(8.0f, 8.0f, 8.0f);
            String rotationAxis = "y";
            float rotationAngle = 0;
            boolean rotationScale = false;

            if (element.has("rotation")) {
                JSONObject rot = element.getJSONObject("rotation");
                JSONArray rotOrigin = rot.getJSONArray("origin");
                rotationOrigin = new Vector3f((float) rotOrigin.getDouble(0), (float) rotOrigin.getDouble(1),
                        (float) rotOrigin.getDouble(2));

                rotationAxis = rot.getString("axis");

                rotationAngle = (float) rot.getDouble("angle");

                if (element.has("rescale"))
                    rotationScale = true;
            }

            boolean shaded = true;
            if (element.has("shade"))
                shaded = false;

            JSONObject faces = element.getJSONObject("faces");

            Iterator<?> keys = faces.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                JSONObject face = (JSONObject) faces.get(key);

                float u0 = fromVector.x();
                float v0 = fromVector.y();
                float u1 = toVector.x();
                float v1 = toVector.y();

                int rotation = 0;
                if (face.has("rotation"))
                    rotation = face.getInt("rotation");

                //System.out.println("u0="+u0+" v0="+v0+" u1="+u1+" v1="+v1);
                // TODO: Need to test more texture packs
                SubTexture subTexture = new SubTexture(null, u0 * (1.0f / 16.0f), v0 * (1.0f / 16.0f),
                        u1 * (1.0f / 16.0f), v1 * (1.0f / 16.0f));

                StringBuilder tex = new StringBuilder(face.getString("texture"));
                if (tex.charAt(0) == '#') {
                    String texture = tex.deleteCharAt(0).toString();

                    SubTexture te = texturePack
                            .findTexture(StringUtils.removeStart(combineMap.get(texture), "blocks/") + ".png");

                    final float texHeight = te.texture.getHeight();
                    final float texWidth = te.texture.getWidth();
                    final int numTiles = te.texture.getHeight() / te.texture.getWidth();

                    u0 = fromVector.x() / texWidth;
                    v0 = fromVector.y() / texWidth;
                    u1 = toVector.x() / texWidth;
                    v1 = toVector.y() / texWidth;

                    if (face.has("uv")) {
                        //System.out.println("Before: u0="+u0+" v0="+v0+" u1="+u1+" v1="+v1);
                        JSONArray uv = face.getJSONArray("uv");
                        u0 = (float) (uv.getDouble(0) / 16.0f);
                        v0 = (float) (uv.getDouble(1) / 16.0f) / numTiles;
                        u1 = (float) (uv.getDouble(2) / 16.0f);
                        v1 = (float) (uv.getDouble(3) / 16.0f) / numTiles;
                    }

                    System.out.println(texWidth + " x " + texHeight);
                    int frame = 1;
                    if (numTiles > 1) {
                        Random rand = new Random();
                        frame = rand.nextInt(numTiles) + 1;
                    }

                    subTexture = new SubTexture(te.texture, u0,
                            v0 + (float) (frame - 1) * (texWidth / texHeight), u1,
                            v1 + (float) (frame - 1) * (texWidth / texHeight));
                    //subTexture = new SubTexture(test, u0, v0, u1, v1);
                    //System.out.println("u0="+subTexture.u0+" v0="+subTexture.v0+" u1="+subTexture.u1+" v1="+subTexture.v1);
                }

                boolean cullFace = false;
                if (face.has("cullface"))
                    cullFace = true;

                boolean tintIndex = false;
                if (face.has("tintindex"))
                    tintIndex = true;

                ElementFace ef = new ElementFace(subTexture, cullFace, rotation, tintIndex);
                elementFaces.put(key, ef);
            }

            BlockElement be = new BlockElement(fromVector, toVector, rotationOrigin, rotationAxis,
                    rotationAngle, rotationScale, shaded, elementFaces);
            elementsList.add(be);
        }

        return new BlockModel(modelPath, ao, elementsList);
    }
}

From source file:tectonicus.blockTypes.BlockRegistry.java

private Map<String, String> populateTextureMap(Map<String, String> textureMap, JSONObject textures)
        throws JSONException {
    Map<String, String> newTexMap = new HashMap<>();

    Iterator<?> keys = textures.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        StringBuilder tex = new StringBuilder((String) textures.get(key));
        if (tex.charAt(0) == '#') {
            newTexMap.put(key, textureMap.get(tex.deleteCharAt(0).toString()));
        } else {//from   w  ww.j  a v a 2  s .c  om
            newTexMap.put(key, tex.toString());
        }
    }
    return newTexMap;
}

From source file:com.yoloci.fileupload.BundleJSONConverter.java

public static Bundle convertToBundle(JSONObject jsonObject) throws JSONException {
    Bundle bundle = new Bundle();
    @SuppressWarnings("unchecked")
    Iterator<String> jsonIterator = jsonObject.keys();
    while (jsonIterator.hasNext()) {
        String key = jsonIterator.next();
        Object value = jsonObject.get(key);
        if (value == null || value == JSONObject.NULL) {
            // Null is not supported.
            continue;
        }/*from w w w .j a  v a 2 s  .  co m*/

        // Special case JSONObject as it's one way, on the return it would be Bundle.
        if (value instanceof JSONObject) {
            bundle.putBundle(key, convertToBundle((JSONObject) value));
            continue;
        }

        Setter setter = SETTERS.get(value.getClass());
        if (setter == null) {
            throw new IllegalArgumentException("Unsupported type: " + value.getClass());
        }
        setter.setOnBundle(bundle, key, value);
    }

    return bundle;
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private Bundle authFailedNotification(JSONObject result, String username) {
    Bundle user_notification_bundle = new Bundle();
    try {//from   w ww  . jav  a2  s. co  m
        JSONObject error_message = result.getJSONObject(ERRORS);
        String error_type = error_message.keys().next().toString();
        String message = error_message.get(error_type).toString();
        user_notification_bundle.putString(getResources().getString(R.string.user_message), message);
    } catch (JSONException e) {
    }

    if (!username.isEmpty())
        user_notification_bundle.putString(SessionDialog.USERNAME, username);
    user_notification_bundle.putBoolean(RESULT_KEY, false);

    return user_notification_bundle;
}

From source file:org.zaizi.alfresco.redlink.service.search.solr.SensefySolrJSONResultSet.java

/**
 * Detached result set based on that provided
 * //from   w ww  .ja va2  s.  c  o m
 * @param resultSet
 */
@SuppressWarnings("rawtypes")
public SensefySolrJSONResultSet(JSONObject json, SearchParameters searchParameters, NodeService nodeService,
        NodeDAO nodeDao, LimitBy limitBy, int maxResults) {
    // Note all properties are returned as multi-valued from the WildcardField "*" definition in the SOLR schema.xml
    this.nodeService = nodeService;
    this.nodeDao = nodeDao;
    try {
        JSONObject responseHeader = json.getJSONObject("header");
        status = responseHeader.getLong("status");
        queryTime = responseHeader.getLong("qtime");

        JSONObject response = json.getJSONObject("response");
        numberFound = response.getLong("numFound");
        start = response.getLong("start");
        // maxScore = Float.valueOf(response.getString("maxScore"));

        JSONArray docs = response.getJSONArray("docs");

        int numDocs = docs.length();

        ArrayList<Long> rawDbids = new ArrayList<Long>(numDocs);
        ArrayList<Float> rawScores = new ArrayList<Float>(numDocs);
        for (int i = 0; i < numDocs; i++) {
            JSONObject doc = docs.getJSONObject(i);
            Long dbid = doc.getLong("DBID");
            Float score = Float.valueOf(doc.getString("score"));

            rawDbids.add(dbid);
            rawScores.add(score);
        }

        // bulk load

        nodeDao.cacheNodesById(rawDbids);

        // filter out rubbish

        page = new ArrayList<Pair<Long, Float>>(numDocs);
        refs = new ArrayList<NodeRef>(numDocs);
        for (int i = 0; i < numDocs; i++) {
            Long dbid = rawDbids.get(i);
            NodeRef nodeRef = nodeService.getNodeRef(dbid);

            if (nodeRef != null) {
                page.add(new Pair<Long, Float>(dbid, rawScores.get(i)));
                refs.add(nodeRef);
            }
        }

        if (json.has("facets")) {
            JSONObject facets = json.getJSONObject("facets");
            Iterator it = facets.keys();
            while (it.hasNext()) {
                String facetName = (String) it.next();
                JSONObject facetJSON = facets.getJSONObject(facetName);
                ArrayList<Pair<String, Integer>> facetValues = new ArrayList<Pair<String, Integer>>(
                        facetJSON.length());
                Iterator it2 = facetJSON.keys();
                while (it2.hasNext()) {
                    String facetEntryValue = (String) it2.next();
                    int facetEntryCount = facetJSON.getInt(facetEntryValue);
                    Pair<String, Integer> pair = new Pair<String, Integer>(facetEntryValue, facetEntryCount);
                    facetValues.add(pair);
                }
                fieldFacets.put(facetName, facetValues);
            }
        }

    } catch (JSONException e) {

    }
    // We'll say we were unlimited if we got a number less than the limit
    this.resultSetMetaData = new SimpleResultSetMetaData(
            maxResults > 0 && numberFound < maxResults ? LimitBy.UNLIMITED : limitBy,
            PermissionEvaluationMode.EAGER, searchParameters);
}

From source file:com.soomla.store.domain.PurchasableVirtualItem.java

/**
 * see parent//  w ww . j av  a  2  s .  c  o  m
 */
@Override
public JSONObject toJSONObject() {
    JSONObject parentJsonObject = super.toJSONObject();
    JSONObject jsonObject = new JSONObject();
    try {
        Iterator<?> keys = parentJsonObject.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            jsonObject.put(key, parentJsonObject.get(key));
        }

        JSONObject purchasableObj = new JSONObject();

        if (mPurchaseType instanceof PurchaseWithMarket) {
            purchasableObj.put(JSONConsts.PURCHASE_TYPE, JSONConsts.PURCHASE_TYPE_MARKET);

            GoogleMarketItem mi = ((PurchaseWithMarket) mPurchaseType).getGoogleMarketItem();
            purchasableObj.put(JSONConsts.PURCHASE_MARKET_ITEM, mi.toJSONObject());
        } else if (mPurchaseType instanceof PurchaseWithVirtualItem) {
            purchasableObj.put(JSONConsts.PURCHASE_TYPE, JSONConsts.PURCHASE_TYPE_VI);

            purchasableObj.put(JSONConsts.PURCHASE_VI_ITEMID,
                    ((PurchaseWithVirtualItem) mPurchaseType).getTargetItemId());
            purchasableObj.put(JSONConsts.PURCHASE_VI_AMOUNT,
                    ((PurchaseWithVirtualItem) mPurchaseType).getAmount());
        }

        jsonObject.put(JSONConsts.PURCHASABLE_ITEM, purchasableObj);
    } catch (JSONException e) {
        StoreUtils.LogError(TAG, "An error occurred while generating JSON object.");
    }

    return jsonObject;
}