Example usage for org.json JSONObject has

List of usage examples for org.json JSONObject has

Introduction

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

Prototype

public boolean has(String key) 

Source Link

Document

Determine if the JSONObject contains a specific key.

Usage

From source file:cz.karry.vpnc.LunaService.java

@LunaServiceThread.PublicMethod
public void disconnectVpn(final ServiceMessage msg) throws JSONException, LSException {
    JSONObject jsonObj = msg.getJSONPayload();
    if (!jsonObj.has("name")) {
        msg.respondError("1", "Improperly formatted request. (" + jsonObj.toString() + ")");
        return;/*w ww .  j a  va 2s  . c  om*/
    }

    String name = jsonObj.getString("name");
    VpnConnection conn = vpnConnections.get(name);
    if (conn == null) {
        msg.respondError("2", "Connection '" + name + "' is not registered.");
        return;
    }

    conn.addStateListener(new ConnectionStateListenerImpl(msg, conn, this.getNextListenerId()));
    conn.diconnect();
    //msg.respondTrue();
}

From source file:cz.karry.vpnc.LunaService.java

@LunaServiceThread.PublicMethod
public void connectVpn(final ServiceMessage msg) throws JSONException, LSException {
    JSONObject jsonObj = msg.getJSONPayload();

    tcpLogger.log("invoke connectVpn " + jsonObj.toString());

    if ((!jsonObj.has("type")) || (!jsonObj.has("name")) || (!jsonObj.has("display_name"))
            || (!jsonObj.has("configuration"))) {
        msg.respondError("1", "Improperly formatted request. (" + jsonObj.toString() + ")");
        return;/* w  ww  . ja v a 2 s .co m*/
    }

    String type = jsonObj.getString("type");
    String name = jsonObj.getString("name");
    String displayName = jsonObj.getString("display_name");
    JSONObject configuration = jsonObj.getJSONObject("configuration");

    if (!name.matches("^[a-zA-Z]{1}[a-zA-Z0-9]*$")) {
        msg.respondError("2", "Bad session name format.");
        return;
    }

    if (type.toLowerCase().equals("pptp")) {
        String host = configuration.getString("host").replaceAll("\n", "\\\\n");

        String user = configuration.getString("pptp_user").replaceAll("\n", "\\\\n");
        String pass = configuration.getString("pptp_password").replaceAll("\n", "\\\\n");
        String mppe = configuration.getString("pptp_mppe").replaceAll("\n", "\\\\n");
        String mppe_stateful = configuration.getString("pptp_mppe_stateful").replaceAll("\n", "\\\\n");
        connectPptpVpn(msg, name, displayName, host, user, pass, mppe, mppe_stateful);
        return;
    } else if (type.toLowerCase().equals("openvpn")) {
        String host = configuration.getString("host").replaceAll("\n", "\\\\n");

        String topology = configuration.getString("openvpn_topology");
        String protocol = configuration.getString("openvpn_protocol");
        String cipher = configuration.getString("openvpn_cipher");
        this.connectOpenVPN(msg, name, displayName, host, topology, protocol, cipher);
        return;
    } else if (type.toLowerCase().equals("cisco")) {
        String host = configuration.getString("host").replaceAll("\n", "\\\\n");

        String userid = configuration.getString("cisco_userid").replaceAll("\n", "\\\\n");
        String userpass = configuration.getString("cisco_userpass").replaceAll("\n", "\\\\n");
        String groupid = configuration.getString("cisco_groupid").replaceAll("\n", "\\\\n");
        String grouppass = configuration.getString("cisco_grouppass").replaceAll("\n", "\\\\n");
        String userpasstype = configuration.getString("cisco_userpasstype");
        String grouppasstype = configuration.getString("cisco_grouppasstype");
        String domain = configuration.has("cisco_domain") && configuration.getString("cisco_domain") != null
                && configuration.getString("cisco_domain").trim().length() > 0
                        ? "Domain " + configuration.getString("cisco_domain")
                        : "";
        tcpLogger.log("use domain \"" + domain + "\"");
        this.connectCiscoVpn(msg, name, displayName, host, userid, userpass, userpasstype, groupid, grouppass,
                grouppasstype, domain);
        return;
    }

    msg.respondError("3", "Undefined vpn type (" + type + ").");
}

From source file:com.iespuig.attendancemanager.StudentFetchr.java

public ArrayList<Student> fetchStudent(Classblock classBlock) {
    ArrayList<Student> items = new ArrayList<Student>();

    SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(context);
    String schoolName = SP.getString(("schoolName"), "");
    String urlServer = SP.getString("urlServer", "");

    Format formatter = new SimpleDateFormat("ddMMyyyy");

    try {/*from ww w .  j  a v a2s . c  o m*/
        String url = Uri.parse(urlServer).buildUpon().appendQueryParameter("action", ACTION_GET_STUDENTS)
                .appendQueryParameter("school", schoolName)
                .appendQueryParameter("login", User.getInstance().getLogin())
                .appendQueryParameter("password", User.getInstance().getPassword())
                .appendQueryParameter("idGroup", String.valueOf(classBlock.getIdGroup()))
                .appendQueryParameter("idClassBlock", String.valueOf(classBlock.getId()))
                .appendQueryParameter("date", formatter.format(classBlock.getDate())).build().toString();

        Log.i(TAG, "url: " + url);

        String data = AtmNet.getUrl(url);
        Log.i(TAG, "url: " + data);

        JSONObject jsonObject = new JSONObject(data);
        JSONArray jsonArray = new JSONArray(jsonObject.getString("data"));

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject row = jsonArray.getJSONObject(i);

            Student item = new Student();

            item.setId(row.getInt("id"));
            item.setFullname(row.getString("fullname"));
            item.setName(row.getString("name"));
            item.setSurname1(row.getString("surname1"));
            item.setSurname2(row.getString("surname2"));
            item.setMissType(0);
            item.setNotMaterial(false);
            item.setNetworkTransit(false);

            if (row.has("misses")) {
                JSONArray misses = row.getJSONArray("misses");
                for (int j = 0; j < misses.length(); j++) {
                    int miss = misses.getInt(j);
                    if (miss > NOT_MISS && miss <= EXPULSION) {
                        item.setMissType(miss);
                    }
                    if (miss == NOT_MATERIAL)
                        item.setNotMaterial(true);
                }
            }

            items.add(item);
        }
    } catch (IOException ioe) {
        Log.e(TAG, "Failed to fetch items", ioe);

    } catch (JSONException je) {
        Log.e(TAG, "Failed to parse JSON", je);
    }
    return items;
}

From source file:com.iespuig.attendancemanager.StudentFetchr.java

public Boolean addMisses(Miss missDelete, Miss missAdd) {

    SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(context);
    String schoolName = SP.getString(("schoolName"), "");
    String urlServer = SP.getString("urlServer", "");

    Format formatter = new SimpleDateFormat("ddMMyyyy");

    try {//from w w w .  ja  v a  2  s . c  om
        if (!missDelete.isEmpty()) {
            String url = Uri.parse(urlServer).buildUpon().appendQueryParameter("action", ACTION_DELETE_MISS)
                    .appendQueryParameter("school", schoolName)
                    .appendQueryParameter("login", User.getInstance().getLogin())
                    .appendQueryParameter("password", User.getInstance().getPassword())
                    .appendQueryParameter("idStudent", String.valueOf(missDelete.getIdStudent()))
                    .appendQueryParameter("type", String.valueOf(missDelete.getType()))
                    .appendQueryParameter("idClassblock", String.valueOf(missDelete.getIdClassblock()))
                    .appendQueryParameter("date", formatter.format(missDelete.getDate())).build().toString();

            Log.i(TAG, "url delete: " + url);

            String data = AtmNet.getUrl(url);
            Log.i(TAG, "url delete: " + data);
            JSONObject jsonObject = new JSONObject(data);

            if (!jsonObject.has("result")) {
                return false;
            }
        }

        if (!missAdd.isEmpty()) {
            String url = Uri.parse(urlServer).buildUpon().appendQueryParameter("action", ACTION_ADD_MISS)
                    .appendQueryParameter("school", schoolName)
                    .appendQueryParameter("login", User.getInstance().getLogin())
                    .appendQueryParameter("password", User.getInstance().getPassword())
                    .appendQueryParameter("idStudent", String.valueOf(missAdd.getIdStudent()))
                    .appendQueryParameter("type", String.valueOf(missAdd.getType()))
                    .appendQueryParameter("idClassblock", String.valueOf(missAdd.getIdClassblock()))
                    .appendQueryParameter("date", formatter.format(missAdd.getDate()))
                    .appendQueryParameter("idSubject", String.valueOf(missAdd.getIdSubject())).build()
                    .toString();

            Log.i(TAG, "url add: " + url);

            String data = AtmNet.getUrl(url);
            Log.i(TAG, "url add: " + data);
            JSONObject jsonObject = new JSONObject(data);

            if (!jsonObject.has("result")) {
                return false;
            }
        }
    } catch (IOException ioe) {
        Log.e(TAG, "Failed to fetch items", ioe);

    } catch (JSONException je) {
        Log.e(TAG, "Failed to parse JSON", je);
    }

    return true;
}

From source file:com.iespuig.attendancemanager.StudentFetchr.java

public Boolean updateCheckList(Classblock classblock) {

    SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(context);
    String schoolName = SP.getString(("schoolName"), "");
    String urlServer = SP.getString("urlServer", "");

    Format formatter = new SimpleDateFormat("ddMMyyyy");
    String action_checklist;//from w  w w  . j  ava2s  .  c  o  m

    try {

        if (classblock.isList())
            action_checklist = ACTION_CHECKED_CHECKLIST;
        else
            action_checklist = ACTION_UNCHECKED__CHECKLIST;

        String url = Uri.parse(urlServer).buildUpon().appendQueryParameter("action", action_checklist)
                .appendQueryParameter("school", schoolName)
                .appendQueryParameter("login", User.getInstance().getLogin())
                .appendQueryParameter("password", User.getInstance().getPassword())
                .appendQueryParameter("idClassblock", String.valueOf(classblock.getId()))
                .appendQueryParameter("date", formatter.format(classblock.getDate())).build().toString();

        Log.i(TAG, "url checklist: " + url);

        String data = AtmNet.getUrl(url);
        Log.i(TAG, "url checklist: " + data);
        JSONObject jsonObject = new JSONObject(data);

        if (!jsonObject.has("result")) {
            return false;
        }
    } catch (IOException ioe) {
        Log.e(TAG, "Failed to fetch items", ioe);

    } catch (JSONException je) {
        Log.e(TAG, "Failed to parse JSON", je);
    }

    return true;
}

From source file:org.mapsforge.poi.exchange.GeoJsonPoiReader.java

PointOfInterest fromFeature(JSONObject feature) throws JSONException {
    String type = feature.getString("type").toString();
    PointOfInterest point;//from   w ww.j  a  va2 s  .  co m
    String name = null;
    String url = null;
    Long id = null;

    if (type.equals("Feature")) {
        point = fromPoint(feature.getJSONObject("geometry"));

        if (feature.has("properties")) {
            JSONObject properties = feature.getJSONObject("properties");
            if (properties.has("name")) {
                name = properties.getString("name");
            }
            if (properties.has("url")) {
                url = properties.getString("url");
            }
            if (properties.has("id")) {
                id = properties.getLong("id");
            }
        }

    } else {
        throw new IllegalArgumentException();
    }

    return new PoiBuilder(id, point.getLatitude(), point.getLongitude(), this.category).setName(name)
            .setUrl(url).build();
}

From source file:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java

public static String geocode(Context context, double latitude, double longitude) {
    String addressString = String.format("%.4f, %.4f", latitude, longitude);
    try {//w  w  w. jav a2 s .  com
        String apiKey = Global.getApiKey(context);
        String server = Global.getApiUrl(context);
        String url = server + "/api/osm/location?apiKey=" + apiKey + "&location=" + latitude + "&location="
                + longitude;
        String response = WebReporter.getHttpURLResponse(url, false);

        JSONObject json = null;
        JSONArray jsonArray = null;

        if (response == null)
            return addressString;

        try {
            jsonArray = new JSONArray(response);
        } catch (JSONException e) {
            return addressString;
        }
        try {
            for (int i = 0; i < jsonArray.length(); i++) {
                json = jsonArray.getJSONObject(i);
                if (json.has("error")) {
                    String error = json.getString("error");
                    return null;
                } else {
                    addressString = "";
                    json = json.getJSONObject("address");
                    String number = "";
                    if (json.has("house_number")) {
                        number = json.getString("house_number");
                        addressString += number + " ";
                    }
                    String road = json.getString("road");
                    addressString += road;// + suburb;
                    return addressString;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
    }

    return addressString;
}

From source file:com.rincliu.library.common.reference.social.weibo.RLWeiboHelper.java

private RequestListener getRequestListener(final Context context, final ReqHandler handler) {
    return new RequestListener() {
        @Override/*w ww .j  a v  a  2s .  co  m*/
        public void onComplete(String arg0) {
            handler.onSucceed();
        }

        @Override
        public void onError(WeiboException exception) {
            String msg = exception.getMessage();
            if (msg != null && !msg.equals("")) {
                try {
                    JSONObject obj = new JSONObject(msg);
                    if (obj != null && obj.has("error")) {
                        handler.onFail(obj.get("error").toString());
                    } else {
                        handler.onFail(context.getString(R.string.weibo_unknow_error));
                    }
                } catch (JSONException e) {
                    handler.onFail(context.getString(R.string.weibo_unknow_error));
                }
            } else {
                handler.onFail(context.getString(R.string.weibo_unknow_error));
            }
        }

        @Override
        public void onIOException(IOException arg0) {
            handler.onFail(context.getString(R.string.weibo_io_error));
        }
    };
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.AppObj.java

public static Intent getLaunchIntent(Context context, DbObj obj) {
    JSONObject content = obj.getJson();
    if (content.has(ANDROID_PACKAGE_NAME)) {
        Uri appFeed = obj.getContainingFeed().getUri();
        String action = content.optString(ANDROID_ACTION);
        String pkgName = content.optString(ANDROID_PACKAGE_NAME);
        String className = content.optString(ANDROID_CLASS_NAME);

        Intent launch = new Intent(action);
        launch.setClassName(pkgName, className);
        launch.addCategory(Intent.CATEGORY_LAUNCHER);
        // TODO: feed for related objs, not parent feed
        launch.putExtra(AppState.EXTRA_FEED_URI, appFeed);
        launch.putExtra(AppState.EXTRA_OBJ_HASH, obj.getHash());
        // TODO: Remove
        launch.putExtra("obj", content.toString());

        List<ResolveInfo> resolved = context.getPackageManager().queryIntentActivities(launch, 0);
        if (resolved.size() > 0) {
            return launch;
        }//  w w w .  j a va  2 s .  co  m

        Intent market = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + pkgName));
        return market;
    } else if (content.has(WEB_URL)) {
        Intent app = new Intent(Intent.ACTION_VIEW, Uri.parse(content.optString(WEB_URL)));
        app.setClass(context, AppFinderActivity.class);
        app.putExtra(Musubi.EXTRA_FEED_URI, Feed.uriForName(obj.getFeedName()));
        return app;
    }
    return null;
}

From source file:com.zaizi.alfresco.crowd.authentication.filter.CrowdSSOFilter.java

/**
 * <p>Enable the SSO, obtaining a Crowd token for the already authenticated user and putting it into a Crowd cookie<p>
 * //from   w w  w . ja v  a  2  s . c  om
 * @param remote the {@code RemoteClient} object to communicate with Alfresco
 * @param cookieManager the {@code CookieManager} object used to obtain and create cookies
 * @param request the {@code HttpServletRequest} object
 * @param response the {@code HttpServletResponse} object where put the token to
 */
private void enableSSO(RemoteClient remote, CookieManager cookieManager, HttpServletRequest request,
        HttpServletResponse response) {
    Response resp = remote.call(CROWD_GET_TOKEN);
    try {
        JSONObject jsonResponse = new JSONObject(resp.getResponse());
        if (jsonResponse.has(TOKEN_KEY))
            cookieManager.putCookieValue(request, response, CROWD_COOKIE_NAME, -1,
                    jsonResponse.getString(TOKEN_KEY));
    } catch (JSONException e) {
        logger.debug("Unable to process the response");
    }
}