Example usage for org.json JSONArray get

List of usage examples for org.json JSONArray get

Introduction

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

Prototype

public Object get(int index) throws JSONException 

Source Link

Document

Get the object value associated with an index.

Usage

From source file:com.optimizely.ab.config.parser.JsonConfigParser.java

private Condition parseConditions(JSONArray conditionJson) {
    List<Condition> conditions = new ArrayList<Condition>();
    String operand = (String) conditionJson.get(0);

    for (int i = 1; i < conditionJson.length(); i++) {
        Object obj = conditionJson.get(i);
        if (obj instanceof JSONArray) {
            conditions.add(parseConditions(conditionJson.getJSONArray(i)));
        } else {//from  ww w.  j  a  va  2 s  .c o  m
            JSONObject conditionMap = (JSONObject) obj;
            conditions.add(new UserAttribute((String) conditionMap.get("name"),
                    (String) conditionMap.get("type"), (String) conditionMap.get("value")));
        }
    }

    Condition condition;
    if (operand.equals("and")) {
        condition = new AndCondition(conditions);
    } else if (operand.equals("or")) {
        condition = new OrCondition(conditions);
    } else {
        condition = new NotCondition(conditions.get(0));
    }

    return condition;
}

From source file:org.steveleach.scoresheet.support.JsonCodec.java

/**
 * Populates a model from a JSON string representation.
 *
 * @param model/*  www .  ja  va 2 s . c om*/
 *          the model to load the data into
 * @param json
 * @throws JSONException
 */
public void fromJson(ScoresheetModel model, String json) throws JSONException {
    model.getEvents().clear();

    if ((json == null) || (json.length() == 0)) {
        throw new JSONException("No content provided for JSON decoder");
    }

    JSONObject root = new JSONObject(json);

    if (root.has("homeTeam")) {
        loadTeam(root.getJSONObject("homeTeam"), model.getHomeTeam());
        loadTeam(root.getJSONObject("awayTeam"), model.getAwayTeam());
    } else {
        model.getHomeTeam().setName(root.optString("homeTeamName", "Home"));
        model.getAwayTeam().setName(root.optString("awayTeamName", "Home"));
    }
    model.setGameLocation(root.optString("location", ""));

    model.setGameDateTime(getDate(root.optString("gameDate", "")));

    JSONArray jsonEvents = root.getJSONArray("events");
    for (int n = 0; n < jsonEvents.length(); n++) {
        JSONObject jsonEvent = (JSONObject) jsonEvents.get(n);
        String eventType = jsonEvent.getString("eventType");
        GameEvent event = null;
        if (eventType.equals("Goal")) {
            GoalEvent goal = new GoalEvent();
            goal.setAssist1(jsonEvent.optInt("assist1", 0));
            goal.setAssist2(jsonEvent.optInt("assist2", 0));
            event = goal;
        } else if (eventType.equals("Penalty")) {
            PenaltyEvent penalty = new PenaltyEvent();
            penalty.setMinutes(jsonEvent.optInt("minutes", 2));
            penalty.setPlusMins(jsonEvent.optInt("plusMins", 0));
            event = penalty;
        } else if (eventType.equals("Period end")) {
            event = new PeriodEndEvent();
        }
        event.setSubType(jsonEvent.getString("subType"));
        event.setPeriod(jsonEvent.getInt("period"));
        event.setGameTime(jsonEvent.getString("gameTime"));
        event.setTeam(jsonEvent.getString("team"));
        event.setPlayer(getInt(jsonEvent.get("player")));

        model.addEvent(event);
    }
}

From source file:org.steveleach.scoresheet.support.JsonCodec.java

private void loadTeamPlayers(JSONArray jsonPlayers, Team team) throws JSONException {
    for (int n = 0; n < jsonPlayers.length(); n++) {
        JSONObject jsonPlayer = (JSONObject) jsonPlayers.get(n);

        Player player = new Player();
        player.setNumber(jsonPlayer.getInt("number"));
        player.setName(jsonPlayer.optString("name", ""));
        player.setPlaying(jsonPlayer.optBoolean("active", true));

        team.getPlayers().put(player.getNumber(), player);
    }//  w w w . j ava2s .  c  o  m
}

From source file:org.official.json.JSONML.java

/**
 * Reverse the JSONML transformation, making an XML text from a JSONArray.
 * @param ja A JSONArray.//from   w  w  w  .  j  av a 2 s. c  om
 * @return An XML string.
 * @throws JSONException
 */
public static String toString(JSONArray ja) throws JSONException {
    int i;
    JSONObject jo;
    String key;
    Iterator<String> keys;
    int length;
    Object object;
    StringBuilder sb = new StringBuilder();
    String tagName;
    String value;

    // Emit <tagName

    tagName = ja.getString(0);
    XML.noSpace(tagName);
    tagName = XML.escape(tagName);
    sb.append('<');
    sb.append(tagName);

    object = ja.opt(1);
    if (object instanceof JSONObject) {
        i = 2;
        jo = (JSONObject) object;

        // Emit the attributes

        keys = jo.keys();
        while (keys.hasNext()) {
            key = keys.next();
            XML.noSpace(key);
            value = jo.optString(key);
            if (value != null) {
                sb.append(' ');
                sb.append(XML.escape(key));
                sb.append('=');
                sb.append('"');
                sb.append(XML.escape(value));
                sb.append('"');
            }
        }
    } else {
        i = 1;
    }

    // Emit content in body

    length = ja.length();
    if (i >= length) {
        sb.append('/');
        sb.append('>');
    } else {
        sb.append('>');
        do {
            object = ja.get(i);
            i += 1;
            if (object != null) {
                if (object instanceof String) {
                    sb.append(XML.escape(object.toString()));
                } else if (object instanceof JSONObject) {
                    sb.append(toString((JSONObject) object));
                } else if (object instanceof JSONArray) {
                    sb.append(toString((JSONArray) object));
                }
            }
        } while (i < length);
        sb.append('<');
        sb.append('/');
        sb.append(tagName);
        sb.append('>');
    }
    return sb.toString();
}

From source file:org.official.json.JSONML.java

/**
 * Reverse the JSONML transformation, making an XML text from a JSONObject.
 * The JSONObject must contain a "tagName" property. If it has children,
 * then it must have a "childNodes" property containing an array of objects.
 * The other properties are attributes with string values.
 * @param jo A JSONObject.//  www .  j  a v a  2s  . co  m
 * @return An XML string.
 * @throws JSONException
 */
public static String toString(JSONObject jo) throws JSONException {
    StringBuilder sb = new StringBuilder();
    int i;
    JSONArray ja;
    String key;
    Iterator<String> keys;
    int length;
    Object object;
    String tagName;
    String value;

    //Emit <tagName

    tagName = jo.optString("tagName");
    if (tagName == null) {
        return XML.escape(jo.toString());
    }
    XML.noSpace(tagName);
    tagName = XML.escape(tagName);
    sb.append('<');
    sb.append(tagName);

    //Emit the attributes

    keys = jo.keys();
    while (keys.hasNext()) {
        key = keys.next();
        if (!"tagName".equals(key) && !"childNodes".equals(key)) {
            XML.noSpace(key);
            value = jo.optString(key);
            if (value != null) {
                sb.append(' ');
                sb.append(XML.escape(key));
                sb.append('=');
                sb.append('"');
                sb.append(XML.escape(value));
                sb.append('"');
            }
        }
    }

    //Emit content in body

    ja = jo.optJSONArray("childNodes");
    if (ja == null) {
        sb.append('/');
        sb.append('>');
    } else {
        sb.append('>');
        length = ja.length();
        for (i = 0; i < length; i += 1) {
            object = ja.get(i);
            if (object != null) {
                if (object instanceof String) {
                    sb.append(XML.escape(object.toString()));
                } else if (object instanceof JSONObject) {
                    sb.append(toString((JSONObject) object));
                } else if (object instanceof JSONArray) {
                    sb.append(toString((JSONArray) object));
                } else {
                    sb.append(object.toString());
                }
            }
        }
        sb.append('<');
        sb.append('/');
        sb.append(tagName);
        sb.append('>');
    }
    return sb.toString();
}

From source file:de.luhmer.owncloudnewsreader.reader.GoogleReaderApi.GoogleReaderMethods.java

@SuppressWarnings("unused")
public static ArrayList<RssFile> getFeeds(String _USERNAME, String _PASSWORD, String _TAG_LABEL) {
    Log.d("mygr", "METHOD: getUnreadFeeds()");

    ArrayList<RssFile> items = new ArrayList<RssFile>();

    String returnString = null;/*from  w  ww  .j av  a  2 s  .  c o  m*/

    /*
    String _TAG_LABEL = null;
    try {
       //_TAG_LABEL = "stream/contents/user/" + AuthenticationManager.getGoogleUserID(_USERNAME, _PASSWORD) + "/state/com.google/reading-list?n=1000&r=n&xt=user/-/state/com.google/read";
       _TAG_LABEL = "stream/contents/user/-/state/com.google/reading-list?n=1000&r=n&xt=user/-/state/com.google/read";
    }catch(Exception e){
       e.printStackTrace();
    }*/

    try {

        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(GoogleReaderConstants._API_URL + _TAG_LABEL);
        request.addHeader("Authorization", GoogleReaderConstants._AUTHPARAMS
                + AuthenticationManager.getGoogleAuthKey(_USERNAME, _PASSWORD));

        HttpResponse response = client.execute(request);

        returnString = HttpHelper.request(response);

        try {
            JSONObject jObj = new JSONObject(returnString);
            JSONArray jItems = (JSONArray) jObj.get("items");
            for (int i = 0; i < jItems.length(); i++) {
                JSONObject jItem = jItems.getJSONObject(i);

                try {
                    String streamID = jItem.optJSONObject("origin").optString("streamId");
                    String feedTitel = jItem.getString("title");
                    String feedID = jItem.optString("id");
                    String content = "";
                    String link = "";
                    String timestamp = jItem.optString("published");

                    JSONObject jSummary = jItem.optJSONObject("summary");
                    JSONObject jContent = jItem.optJSONObject("content");

                    //JSONArray jCategories

                    if (jSummary != null)
                        content = (String) jItem.getJSONObject("summary").get("content");

                    if (jContent != null)
                        content = (String) jItem.getJSONObject("content").get("content");

                    //if(jItem.has("origin"));
                    //   link = (String) jItem.getJSONObject("origin").get("htmlUrl");

                    if (jItem.has("alternate"))
                        ;
                    link = (String) jItem.optJSONArray("alternate").getJSONObject(0).getString("href");

                    JSONArray jCategories = jItem.optJSONArray("categories");
                    List<String> categories = new ArrayList<String>();
                    if (jCategories != null) {
                        for (int t = 0; t < jCategories.length(); t++)
                            categories.add((String) jCategories.get(t));
                    }

                    Boolean starred = false;
                    Boolean read = false;

                    if (_TAG_LABEL.equals(Constants._TAG_LABEL_STARRED)) {
                        starred = true;
                        read = true;
                    }

                    content = content.replaceAll("<img[^>]*feedsportal.com.*>", "");
                    content = content
                            .replaceAll("<img[^>]*statisches.auslieferung.commindo-media-ressourcen.de.*>", "");
                    content = content.replaceAll("<img[^>]*auslieferung.commindo-media-ressourcen.de.*>", "");
                    content = content.replaceAll("<img[^>]*rss.buysellads.com.*>", "");

                    //content = (String) jItem.getJSONObject("content").get("content");
                    /*
                    RssFile sItem = new  RssFile(0, feedTitel, link, content, read, 0, feedID, categories, streamID, new Date(Long.parseLong(timestamp) * 1000), starred, null, null);//TODO implement this here again
                    items.add(sItem);*/
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            //Log.d("HI", jObj.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        /*
        Pattern pattern = Pattern.compile("\"alternate\":\\[\\{\"href\":\"(.*?)\",");
        Matcher matcher = pattern.matcher(returnString);
                
        ArrayList<String> resultList = new ArrayList<String>();
                
        while (matcher.find())
           resultList.add(matcher.group(1));
                
        String[] ret = new String[resultList.size()];
        resultList.toArray(ret);*/
        //return ret;

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return items;
}

From source file:ai.ilikeplaces.logic.Listeners.ListenerMain.java

/**
 * @param request__/*  ww w . jav  a2s  .com*/
 * @param response__
 */
@Override
public void processRequest(final ItsNatServletRequest request__, final ItsNatServletResponse response__) {
    new AbstractListener(request__, response__) {
        protected String location;

        protected String superLocation;

        protected Long WOEID;

        /**
         * Initialize your document here by appending fragments
         */
        @Override
        @SuppressWarnings("unchecked")
        @_todo(task = "If location is not available, it should be added through a w" + "id"
                + "get(or fragment maybe?)")
        protected final void init(final ItsNatHTMLDocument itsNatHTMLDocument__,
                final HTMLDocument hTMLDocument__, final ItsNatDocument itsNatDocument__,
                final Object... initArgs) {
            final SmartLogger sl = SmartLogger.start(Loggers.LEVEL.DEBUG, "Location Page.", 60000, null, true);

            //this.location = (String) request_.getServletRequest().getAttribute(RBGet.config.getString("HttpSessionAttr.location"));
            getLocationSuperLocation: {
                final String[] attr = ((String) request__.getServletRequest()
                        .getAttribute(RBGet.globalConfig.getString(HTTP_SESSION_ATTR_LOCATION))).split("_");
                location = attr[0];
                if (attr.length == 3) {
                    superLocation = attr[2];
                } else {
                    superLocation = EMPTY;
                }
                tryLocationId: {
                    try {
                        final String w = request__.getServletRequest().getParameter(Location.WOEID);
                        if (w != null) {
                            WOEID = Long.parseLong(request__.getServletRequest().getParameter(Location.WOEID));
                        }
                    } catch (final NumberFormatException e) {
                        Loggers.USER_EXCEPTION.error(WRONG_WOEID_FORMAT, e);
                    }
                }
            }

            sl.appendToLogMSG(RETURNING_LOCATION + location + TO_USER);

            final ResourceBundle gUI = ResourceBundle.getBundle(AI_ILIKEPLACES_RBS_GUI);

            layoutNeededForAllPages: {
                setLoginWidget: {
                    try {
                        new SignInOn(request__, $(Main_login_widget),
                                new SignInOnCriteria().setHumanId(new HumanId(getUsername()))
                                        .setSignInOnDisplayComponent(
                                                SignInOnCriteria.SignInOnDisplayComponent.MOMENTS)) {
                        };
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOGIN_WIDGET, t);
                    }
                }

                SEO: {
                    try {
                        setMainTitle: {
                            $(mainTitle).setTextContent(
                                    MessageFormat.format(gUI.getString("woeidpage.title"), location));
                        }
                        setMetaDescription: {
                            $(mainMetaDesc).setAttribute(MarkupTag.META.content(),
                                    MessageFormat.format(gUI.getString("woeidpage.desc"), location));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SEO, t);
                    }
                }
                signOnDisplayLink: {
                    try {
                        if (getUsername() != null) {
                            $(Main_othersidebar_identity).setTextContent(
                                    gUI.getString(AI_ILIKEPLACES_LOGIC_LISTENERS_LISTENER_MAIN_0004)
                                            + getUsernameAsValid());
                        } else {
                            $(Main_othersidebar_identity).setTextContent(
                                    gUI.getString(AI_ILIKEPLACES_LOGIC_LISTENERS_LISTENER_MAIN_0005)
                                            + location);
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SIGN_ON_DISPLAY_LINK, t);
                    }
                }
                setProfileLink: {
                    try {
                        if (getUsername() != null) {
                            $(Main_othersidebar_profile_link).setAttribute(MarkupTag.A.href(),
                                    Controller.Page.Profile.getURL());
                        } else {
                            $(Main_othersidebar_profile_link).setAttribute(MarkupTag.A.href(),
                                    Controller.Page.signup.getURL());
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_PROFILE_LINK, t);
                    }
                }
                setProfilePhotoLink: {
                    try {
                        if (getUsername() != null) {
                            /**
                             * TODO check for db failure
                             */
                            String url = DB.getHumanCRUDHumanLocal(true)
                                    .doDirtyRHumansProfilePhoto(new HumanId(getUsernameAsValid()))
                                    .returnValueBadly();
                            url = url == null ? null : RBGet.globalConfig.getString(PROFILE_PHOTOS) + url;
                            if (url != null) {
                                $(Main_profile_photo).setAttribute(MarkupTag.IMG.src(), url);
                                //displayBlock($(Main_profile_photo));
                            } else {
                                //displayNone($(Main_profile_photo));
                            }
                        } else {
                            //displayNone($(Main_profile_photo));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_PROFILE_PHOTO_LINK, t);
                    }
                }
            }

            final Return<Location> r;
            if (WOEID != null) {
                r = DB.getHumanCRUDLocationLocal(true).doRLocation(WOEID, REFRESH_SPEC);
            } else {
                r = new ReturnImpl<Location>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION,
                        "Search Unavailable", false);
                //r = DB.getHumanCRUDLocationLocal(true).dirtyRLocation(location, superLocation);
            }

            if (r.returnStatus() == 0 && r.returnValue() != null) {
                final Location existingLocation_ = r.returnValue();

                GEO: {
                    if (existingLocation_.getLocationGeo1() == null
                            || existingLocation_.getLocationGeo2() == null) {
                        final Client ygpClient = YAHOO_GEO_PLANET_FACTORY
                                .getInstance(RBGet.globalConfig.getString("where.yahooapis.com.v1.place"));
                        final Place place = ygpClient.getPlace(existingLocation_.getLocationId().toString());
                        existingLocation_.setLocationGeo1(Double.toString(place.getCoordinates().getY()));
                        existingLocation_.setLocationGeo2(Double.toString(place.getCoordinates().getX()));

                        new Thread(new Runnable() {

                            @Override
                            public void run() {
                                DB.getHumanCRUDLocationLocal(true).doULocationLatLng(
                                        new Obj<Long>(existingLocation_.getLocationId()),
                                        new Obj<Double>(place.getCoordinates().getY()),
                                        new Obj<Double>(place.getCoordinates().getX()));
                            }
                        }).run();
                    }
                }

                final Location locationSuperSet = existingLocation_.getLocationSuperSet();
                GEO_WIDGET: {
                    new ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Comment(request__,
                            new CommentCriteria(), $(Controller.Page.Main_right_column)) {
                        @Override
                        protected void init(CommentCriteria commentCriteria) {
                            final ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Place place = new ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Place(
                                    request__, new PlaceCriteria()
                                            //This Place
                                            .setPlaceNamePre("Exciting events in ")
                                            .setPlaceName(existingLocation_.getLocationName())
                                            .setPlaceLat(existingLocation_.getLocationGeo1())
                                            .setPlaceLng(existingLocation_.getLocationGeo2())
                            //Parent Place
                            //.setPlaceSuperName(locationSuperSet.getLocationName())
                            //.setPlaceSuperLat(locationSuperSet.getLocationGeo1())
                            //.setPlaceSuperLng(locationSuperSet.getLocationGeo2())
                            //Parent WOEID
                            //.setPlaceSuperWOEID(locationSuperSet.getWOEID().toString())
                            , $$(CommentIds.commentPerson));
                            place.$$displayNone(place.$$(
                                    ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Place.PlaceIds.placeWidget));
                        }
                    };
                }

                final List<String> titleManifest = new ArrayList<String>();

                EVENTS_WIDGETS: {
                    try {
                        /* final JSONObject jsonObject = Modules.getModules().getYahooUplcomingFactory()
                            .getInstance("http://upcoming.yahooapis.com/services/rest/")
                            .get("",
                                    new HashMap<String, String>() {
                                        {//Don't worry, this is a static initializer of this map :)
                                            put("method", "event.search");
                                            put("woeid", WOEID.toString());
                                            put("format", "json");
                                        }
                                    }
                                
                            );
                         final JSONArray events = jsonObject.getJSONObject("rsp").getJSONArray("event");*/

                        final JSONObject jsonObject = Modules.getModules().getEventulFactory()
                                .getInstance("http://api.eventful.com/json/events/search/")
                                .get("", new HashMap<String, String>() {
                                    {//Don't worry, this is a static initializer of this map :)
                                        put("location", "" + existingLocation_.getLocationGeo1() + ","
                                                + existingLocation_.getLocationGeo2());
                                        put("within", "" + 100);
                                    }
                                }

                        );

                        Loggers.debug("Eventful Reply:" + jsonObject.toString());

                        //                            final String eventName = eventJSONObject.getString("title");
                        //                            final String eventUrl = eventJSONObject.getString("url");
                        //                            final String eventDate = eventJSONObject.getString("start_time");
                        //                            final String eventVenue = eventJSONObject.getString("venue_name");

                        final JSONArray events = jsonObject.getJSONObject("events").getJSONArray("event");

                        for (int i = 0; i < events.length(); i++) {
                            final JSONObject eventJSONObject = new JSONObject(events.get(i).toString());

                            titleManifest.add(eventJSONObject.get("title").toString());

                            final String photoUrl;
                            String temp = null;
                            try {
                                temp = eventJSONObject.getJSONObject("image").get("url").toString();
                            } catch (final Throwable e) {
                                SmartLogger.g().l(e.getMessage());
                            } finally {
                                photoUrl = temp;
                            }
                            //The pain I go through to make variables final :D

                            new Event(request__, new EventCriteria()
                                    .setEventName(eventJSONObject.get("title").toString())
                                    .setEventStartDate(eventJSONObject.get("start_time").toString())
                                    .setEventPhoto(photoUrl)
                                    .setPlaceCriteria(new PlaceCriteria()
                                            .setPlaceNamePre("This event is taking place in ")
                                            .setPlaceName(existingLocation_.getLocationName())
                                            .setPlaceLat(eventJSONObject.get("latitude").toString())
                                            .setPlaceLng(eventJSONObject.get("longitude").toString())
                                            //Parent Place
                                            .setPlaceSuperNamePre(
                                                    existingLocation_.getLocationName() + " is located in ")
                                            .setPlaceSuperName(locationSuperSet.getLocationName())
                                            .setPlaceSuperLat(locationSuperSet.getLocationGeo1())
                                            .setPlaceSuperLng(locationSuperSet.getLocationGeo2())
                                            //Parent WOEID
                                            .setPlaceSuperWOEID(locationSuperSet.getWOEID().toString())

                            ), $(Controller.Page.Main_right_column));
                        }
                    } catch (final JSONException e) {
                        sl.l("Error fetching data from Yahoo Upcoming: " + e.getMessage());
                    }
                }

                TWITTER_WIDGETS: {
                    try {
                        final Query _query = new Query(
                                "fun OR happening OR enjoy OR nightclub OR restaurant OR party OR travel :)");
                        _query.geoCode(
                                new GeoLocation(Double.parseDouble(existingLocation_.getLocationGeo1()),
                                        Double.parseDouble(existingLocation_.getLocationGeo2())),
                                40, Query.MILES);
                        _query.setResultType(Query.MIXED);
                        final QueryResult result = TWITTER.search(_query);

                        //final QueryResult result = TWITTER.search(new Query("Happy").geoCode(new GeoLocation(Double.parseDouble(existingLocation_.getLocationGeo1()), Double.parseDouble(existingLocation_.getLocationGeo2())), 160, Query.MILES));
                        for (Status tweet : result.getTweets()) {
                            new ai.ilikeplaces.logic.Listeners.widgets.schema.thing.Person(request__,
                                    new PersonCriteria().setPersonName(tweet.getUser().getName())
                                            .setPersonPhoto(tweet.getUser().getProfileImageURL())
                                            .setPersonData(tweet.getText()),
                                    $(Main_right_column));
                            titleManifest.add(tweet.getText());
                        }
                        if (result.getTweets().size() == 0) {
                            sl.l("No twitter results found");
                        }
                    } catch (final Throwable t) {
                        sl.l("An error occurred during twitter fetch:" + t.getMessage());
                    }
                }

                SEO: {
                    setMetaGEOData: {
                        $(Main_ICBM).setAttribute(MarkupTag.META.content(), existingLocation_.getLocationGeo1()
                                + COMMA + existingLocation_.getLocationGeo2());
                        $(Main_geoposition).setAttribute(MarkupTag.META.content(),
                                existingLocation_.getLocationGeo1() + COMMA
                                        + existingLocation_.getLocationGeo2());
                        $(Main_geoplacename).setAttribute(MarkupTag.META.content(),
                                existingLocation_.getLocationName());
                        $(Main_georegion).setAttribute(MarkupTag.META.content(),
                                locationSuperSet.getLocationName());
                    }
                }

                setLocationIdForJSReference: {
                    try {
                        final Element hiddenLocationIdInputTag = $(INPUT);
                        hiddenLocationIdInputTag.setAttribute(INPUT.type(), INPUT.typeValueHidden());
                        hiddenLocationIdInputTag.setAttribute(INPUT.id(), JSCodeToSend.LocationId);
                        hiddenLocationIdInputTag.setAttribute(INPUT.value(),
                                existingLocation_.getLocationId().toString());
                        hTMLDocument__.getBody().appendChild(hiddenLocationIdInputTag);

                        $(Main_location_name).setAttribute(INPUT.value(),
                                existingLocation_.getLocationName() + "");
                        $(Main_super_location_name).setAttribute(INPUT.value(),
                                locationSuperSet.getLocationName() + "");
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOCATION_ID_FOR_JSREFERENCE, t);
                    }
                }

                setLocationNameForJSReference: {
                    try {
                        final Element hiddenLocationIdInputTag = $(INPUT);
                        hiddenLocationIdInputTag.setAttribute(INPUT.type(), INPUT.typeValueHidden());
                        hiddenLocationIdInputTag.setAttribute(INPUT.id(), JSCodeToSend.LocationName);
                        hiddenLocationIdInputTag.setAttribute(INPUT.value(),
                                existingLocation_.getLocationName() + OF + locationSuperSet.getLocationName());
                        hTMLDocument__.getBody().appendChild(hiddenLocationIdInputTag);
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOCATION_NAME_FOR_JSREFERENCE, t);
                    }
                }

                setLocationAsPageTopic: {
                    try {

                        final StringBuilder title = new StringBuilder();

                        for (final String titleGuest : titleManifest) {
                            title.append(titleGuest);
                        }

                        final String finalTitle = title.toString();

                        $(Main_center_main_location_title).setTextContent(finalTitle.isEmpty()
                                ? (THIS_IS + existingLocation_.getLocationName() + OF + locationSuperSet)
                                : finalTitle);

                        for (final Element element : generateLocationLinks(DB.getHumanCRUDLocationLocal(true)
                                .doDirtyRLocationsBySuperLocation(existingLocation_))) {
                            $(Main_location_list).appendChild(element);
                            displayBlock($(Main_notice_sh));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_SET_LOCATION_AS_PAGE_TOPIC, t);
                    }
                }
            } else {
                noSupportForNewLocations: {
                    try {
                        //                            $(Main_notice).appendChild(($(P).appendChild(
                        //                                    hTMLDocument__.createTextNode(RBGet.logMsgs.getString("CANT_FIND_LOCATION")
                        //                                            + " Were you looking for "
                        //                                    ))));
                        //                            for (final Element element : generateLocationLinks(DB.getHumanCRUDLocationLocal(true).dirtyRLikeLocations(location))) {
                        //                                $(Main_notice).appendChild(element);
                        //                                displayBlock($(Main_notice_sh));
                        //                            }
                        NotSupportingLikeSearchTooForNow: {
                            $(Main_notice).appendChild(($(P).appendChild(hTMLDocument__
                                    .createTextNode(RBGet.logMsgs.getString("CANT_FIND_LOCATION")))));
                        }
                    } catch (final Throwable t) {
                        sl.l(ERROR_IN_UC_NO_SUPPORT_FOR_NEW_LOCATIONS, t);
                    }
                }
            }
            sl.complete(Loggers.LEVEL.SERVER_STATUS, Loggers.DONE);
        }

        /**
         * Use ItsNatHTMLDocument variable stored in the AbstractListener class
         */
        @Override
        protected void registerEventListeners(final ItsNatHTMLDocument itsNatHTMLDocument__,
                final HTMLDocument hTMLDocument__, final ItsNatDocument itsNatDocument__) {
        }

        private List<Element> generateLocationLinks(final List<Location> locationList) {
            final ElementComposer UList = ElementComposer.compose($(UL)).$ElementSetAttribute(MarkupTag.UL.id(),
                    PLACE_LIST);

            for (Location location : locationList) {
                final Element link = $(A);

                link.setTextContent(TRAVEL_TO + location.getLocationName() + OF
                        + location.getLocationSuperSet().getLocationName());

                link.setAttribute(A.href(),
                        PAGE + location.getLocationName() + _OF_
                                + location.getLocationSuperSet().getLocationName()
                                + Parameter.get(Location.WOEID, location.getWOEID().toString(), true));

                link.setAttribute(A.alt(), PAGE + location.getLocationName() + _OF_
                        + location.getLocationSuperSet().getLocationName());

                link.setAttribute(A.title(), CLICK_TO_EXPLORE + location.getLocationName() + OF
                        + location.getLocationSuperSet().getLocationName());

                link.setAttribute(A.classs(), VTIP);

                final Element linkDiv = $(DIV);

                linkDiv.appendChild(link);

                UList.wrapThis(ElementComposer.compose($(LI)).wrapThis(linkDiv).get());
            }

            final List<Element> elements = new ArrayList<Element>();
            elements.add(UList.get());
            return elements;
        }

        private Element generateLocationLink(final Location location) {
            final Element link = $(A);
            link.setTextContent(TRAVEL_TO + location.getLocationName() + OF
                    + location.getLocationSuperSet().getLocationName());
            link.setAttribute(A.href(),
                    PAGE + location.getLocationName() + _OF_ + location.getLocationSuperSet().getLocationName()
                            + Parameter.get(Location.WOEID, location.getWOEID().toString(), true));

            link.setAttribute(A.alt(), PAGE + location.getLocationName() + _OF_
                    + location.getLocationSuperSet().getLocationName());
            return link;
        }

        private Element generateSimpleLocationLink(final Location location) {
            final Element link = $(A);
            link.setTextContent(location.getLocationName());
            link.setAttribute(A.href(), PAGE + location.getLocationName()
                    + Parameter.get(Location.WOEID, location.getWOEID().toString(), true));

            link.setAttribute(A.alt(), PAGE + location.getLocationName());
            return link;
        }
    };//Listener
}

From source file:org.uiautomation.ios.context.BaseWebInspector.java

public Object executeScript(String script, JSONArray args) {

    try {/*from ww  w  .ja  v  a2  s  .  c  om*/
        RemoteWebElement document = getDocument();
        RemoteWebElement window = context.getWindow();
        JSONObject cmd = new JSONObject();

        JSONArray arguments = new JSONArray();
        int nbParam = args.length();
        for (int i = 0; i < nbParam; i++) {
            Object arg = args.get(i);
            if (arg instanceof JSONObject) {
                JSONObject jsonArg = (JSONObject) arg;
                if (jsonArg.optString("ELEMENT") != null) {
                    // TODO use driver factory to check the  pageId
                    NodeId n = new NodeId(Integer.parseInt(jsonArg.optString("ELEMENT").split("_")[1]));
                    RemoteWebElement rwep = new RemoteWebElement(n, this);
                    arguments.put(new JSONObject().put("objectId", rwep.getRemoteObject().getId()));
                }
            } else if (arg instanceof JSONArray) {
                JSONArray jsonArr = (JSONArray) arg;
                // maybe by executing some JS returning the array, and using that result
                // as a param ?
                throw new WebDriverException("no support argument = array.");
            } else {
                arguments.put(new JSONObject().put("value", arg));
            }

        }

        if (!context.isOnMainFrame()) {
            arguments.put(new JSONObject().put("objectId", document.getRemoteObject().getId()));
            arguments.put(new JSONObject().put("objectId", window.getRemoteObject().getId()));

            String contextObject = "{'document': arguments[" + nbParam + "], 'window': arguments["
                    + (nbParam + 1) + "]}";
            script = "with (" + contextObject + ") {" + script + "}";

        }

        cmd.put("method", "Runtime.callFunctionOn");
        cmd.put("params",
                new JSONObject().put("objectId", document.getRemoteObject().getId())
                        .put("functionDeclaration", "(function() { " + script + "})")
                        .put("arguments", arguments).put("returnByValue", false));
        JSONObject response = sendCommand(cmd);
        checkForJSErrors(response);
        Object o = cast(response);
        return o;
    } catch (JSONException e) {
        throw new WebDriverException(e);
    }

}

From source file:com.yasiradnan.Schedule.ScheduleMainActivity.java

private void getJsonData() {
    try {/*from w ww  .  j  ava  2s  . c o m*/
        InputStream inStream = this.getResources().openRawResource(R.raw.program);
        JSONArray jsonArray = JSONReader.parseStream(inStream);

        totalPages = jsonArray.length();
        data = new ScheduleItem[totalPages][];

        for (int counter = 0; counter < jsonArray.length(); counter++) {
            JSONObject jsonObject = jsonArray.getJSONObject(counter);
            String getDate = jsonObject.getString("date");
            JSONArray getFirstArray = new JSONArray(jsonObject.getString("events"));

            int itemsCount = getFirstArray.length();

            ArrayList<ScheduleItem> items = new ArrayList<ScheduleItem>();

            for (int i = 0; i < itemsCount; i++) {

                JSONObject getJSonObj = (JSONObject) getFirstArray.get(i);
                String time = getJSonObj.getString("time");
                String title = getJSonObj.getString("title");
                int typeId = getJSonObj.getInt("type_id");

                items.add(new ScheduleItem(time, title, typeId, getDate));

                /* a session entry contains multiple sub events */
                if (typeId == 0) {

                    JSONArray getEventsArray = new JSONArray(getJSonObj.getString("events"));

                    for (int j = 0; j < getEventsArray.length(); j++) {

                        JSONObject getJSonEventobj = (JSONObject) getEventsArray.get(j);
                        int typeEventId = getJSonEventobj.getInt("type_id");

                        if (typeEventId == 1) {

                            String EventInfo = getJSonEventobj.getString("info");
                            String EventTitle = getJSonEventobj.getString("title");
                            String Eventtime = getJSonEventobj.getString("time");
                            items.add(new ScheduleItem(Eventtime, EventTitle, EventInfo, typeEventId, getDate));
                        } else {

                            String EventTitle = getJSonEventobj.getString("title");
                            String Eventtime = getJSonEventobj.getString("time");
                            items.add(new ScheduleItem(Eventtime, EventTitle, typeEventId, getDate));
                        }
                    }
                }
            }

            data[counter] = items.toArray(new ScheduleItem[0]);
        }

    } catch (Exception e) {
        // TODO: handle exception
        Log.getStackTraceString(e);
    }
}

From source file:com.muzima.service.HTMLFormObservationCreator.java

private List<Observation> createMultipleObservation(String conceptName, JSONArray jsonArray)
        throws JSONException, ConceptController.ConceptFetchException, ConceptController.ConceptSaveException {
    List<Observation> observations = new ArrayList<Observation>();
    for (int i = 0; i < jsonArray.length(); i++) {
        if (jsonArray.get(i) instanceof JSONObject) {
            observations.addAll(extractObservationFromJSONObject(jsonArray.getJSONObject(i)));
        } else {//from  w  ww  .  ja v  a  2s  .  co  m
            observations.add(createObservation(conceptName, jsonArray.getString(i)));
        }
    }
    return observations;
}