Example usage for org.json JSONObject toString

List of usage examples for org.json JSONObject toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONObject.

Usage

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

/**
 * luna-send -t 1 luna://cz.karry.vpnc/random "{}"
 * //from  ww w.j a  v a 2s.  c  o m
 * @param msg
 * @throws JSONException
 * @throws LSException
 */
@LunaServiceThread.PublicMethod
public void random(ServiceMessage msg) throws JSONException, LSException {
    JSONObject reply = new JSONObject();
    reply.put("returnValue", "" + Math.random());
    msg.respond(reply.toString());
}

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

/**
 * sudo ip route add 192.168.100.0/24 via 192.168.100.1
 * sudo ip route add default via 192.168.100.1
 *//*w  w w .  j a v  a2s  . co m*/
@LunaServiceThread.PublicMethod
public void addRoute(ServiceMessage msg) throws JSONException, LSException {

    if ((!msg.getJSONPayload().has("network")) || (!msg.getJSONPayload().has("gateway"))) {
        msg.respondError("1", "Improperly formatted request.");
        return;
    }
    String network = msg.getJSONPayload().getString("network").toLowerCase();
    String gateway = msg.getJSONPayload().getString("gateway").toLowerCase();

    if (!gateway.matches(GATEWAY_REGEXP)) {
        msg.respondError("2", "Bad gateway format.");
        return;
    }
    if (!network.matches(NETWOK_REGEXP)) {
        msg.respondError("3", "Bad network format.");
        return;
    }

    String cmdStr = String.format("ip route add %s via %s", network, gateway);
    CommandLine cmd = new CommandLine(cmdStr);
    if (!cmd.doCmd()) {
        msg.respondError("4", cmd.getResponse());
        return;
    }
    JSONObject reply = new JSONObject();
    reply.put("command", cmdStr);
    msg.respond(reply.toString());
}

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

/**
 * sudo ip route flush 192.168.100.0/24 via 192.168.100.1
 * sudo ip route flush default via 192.168.100.1
 */// ww w  . j  a  v  a  2  s.c  om
@LunaServiceThread.PublicMethod
public void delRoute(ServiceMessage msg) throws JSONException, LSException {

    if ((!msg.getJSONPayload().has("network")) || (!msg.getJSONPayload().has("gateway"))) {
        msg.respondError("1", "Improperly formatted request.");
        return;
    }
    String network = msg.getJSONPayload().getString("network").toLowerCase();
    String gateway = msg.getJSONPayload().getString("gateway").toLowerCase();

    if (!gateway.matches(GATEWAY_REGEXP)) {
        msg.respondError("2", "Bad gateway format.");
        return;
    }
    if (!network.matches(NETWOK_REGEXP)) {
        msg.respondError("3", "Bad network format.");
        return;
    }

    String cmdStr = String.format("ip route flush %s via %s", network, gateway);
    CommandLine cmd = new CommandLine(cmdStr);
    if (!cmd.doCmd()) {
        msg.respondError("4", cmd.getResponse());
        return;
    }
    JSONObject reply = new JSONObject();
    reply.put("command", cmdStr);
    msg.respond(reply.toString());
}

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

@LunaServiceThread.PublicMethod
public void connectionInfo(final ServiceMessage msg) throws JSONException, LSException {
    JSONObject jsonObj = msg.getJSONPayload();
    if (!jsonObj.has("name")) {
        msg.respondError("1", "Improperly formatted request.");
        return;/*  www .j  a  va2 s.c  o m*/
    }

    String name = jsonObj.getString("name");

    JSONObject reply = new JSONObject();
    reply.put("name", name);
    VpnConnection conn = vpnConnections.get(name);
    ConnectionState state = VpnConnection.ConnectionState.INACTIVE;
    String log = "";

    if (conn != null) {
        state = conn.getConnectionState();
        log = conn.getLog();
        if (state == AbstractVpnConnection.ConnectionState.CONNECTED) {
            reply.put("localAddress", conn.getLocalAddress());
        }
    }

    try {
        reply.put("profileName", name);
        reply.put("state", state);
        reply.put("log", log);
        //tcpLogger.log("refresh info: "+reply.toString());
        msg.respond(reply.toString());
    } catch (LSException ex) {
        tcpLogger.log(ex.getMessage(), ex);
    } catch (JSONException ex) {
        tcpLogger.log(ex.getMessage(), ex);
    }
}

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

@LunaServiceThread.PublicMethod
public void getRegisteredConnections(final ServiceMessage msg) throws JSONException, LSException {
    JSONObject reply = new JSONObject();

    try {/*w ww.  jav a 2s .co  m*/
        reply.put("connections", vpnConnections.keySet());
        msg.respond(reply.toString());
    } catch (LSException ex) {
        tcpLogger.log(ex.getMessage(), ex);
    } catch (JSONException ex) {
        tcpLogger.log(ex.getMessage(), ex);
    }
}

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;//from  w w  w.java2 s .  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;/*from   w w  w  .  ja v a  2s  .  c  o  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.google.walkaround.wave.server.attachment.AttachmentMetadataHandler.java

private void doRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Map<AttachmentId, Optional<AttachmentMetadata>> result = attachments.getMetadata(getIds(req),
            MAX_REQUEST_TIME_MS);//ww w.  ja  va2s . c o m
    JSONObject json = new JSONObject();
    try {
        for (Entry<AttachmentId, Optional<AttachmentMetadata>> entry : result.entrySet()) {
            JSONObject metadata = new JSONObject(
                    entry.getValue().isPresent() ? entry.getValue().get().getMetadataJsonString()
                            : INVALID_ATTACHMENT_ID_METADATA_STRING);
            String queryParams = "attachment="
                    + UriEscapers.uriQueryStringEscaper(false).escape(entry.getKey().getId());
            metadata.put("url", "/download?" + queryParams);
            metadata.put("thumbnailUrl", "/thumbnail?" + queryParams);
            json.put(entry.getKey().getId(), metadata);
        }
    } catch (JSONException e) {
        throw new Error(e);
    }
    ServletUtil.writeJsonResult(resp.getWriter(), json.toString());
}

From source file:edu.asu.msse.gnayak2.main.CollectionSkeleton.java

public String callMethod(String request) {
    JSONObject result = new JSONObject();
    try {//from   ww  w .  ja v  a2 s.  c  om
        JSONObject theCall = new JSONObject(request);
        System.out.println(request);
        String method = theCall.getString("method");
        int id = theCall.getInt("id");
        JSONArray params = null;
        if (!theCall.isNull("params")) {
            params = theCall.getJSONArray("params");
            System.out.println(params);
        }
        result.put("id", id);
        result.put("jsonrpc", "2.0");
        if (method.equals("resetFromJsonFile")) {
            mLib.resetFromJsonFile();
            result.put("result", true);
            System.out.println("resetFromJsonCalled");
        } else if (method.equals("remove")) {
            String sName = params.getString(0);
            boolean removed = mLib.remove(sName);
            System.out.println(sName + " deleted");
            result.put("result", removed);
        } else if (method.equals("add")) {
            MovieImpl movie = new MovieImpl(params.getString(0));
            boolean added = mLib.add(movie);
            result.put("result", added);
        } else if (method.equals("get")) {
            String sName = params.getString(0);
            MovieImpl movie = mLib.get(sName);
            result.put("result", movie.toJson());
        } else if (method.equals("getNames")) {
            String[] names = mLib.getNames();
            JSONArray resArr = new JSONArray();
            for (int i = 0; i < names.length; i++) {
                resArr.put(names[i]);
            }
            result.put("result", resArr);
        } else if (method.equals("saveToJsonFile")) {
            boolean saved = mLib.saveToJsonFile();
            result.put("result", saved);
        } else if (method.equals("getModelInformation")) {
            //mLib.resetFromJsonFile();
            result.put("result", mLib.getModelInformation());
        } else if (method.equals("update")) {
            String movieJSONString = params.getString(0);
            Movie mo = new MovieImpl(movieJSONString);
            mLib.updateMovie(mo);
        } else if (method.equals("deleteAndAdd")) {
            String oldMovieJSONString = params.getString(0);
            String editedMovieJSONString = params.getString(1);
            boolean deletionSuccessful = false;
            boolean additionSuccessful = false;
            MovieImpl oldMovie = new MovieImpl(oldMovieJSONString);
            MovieImpl newMovie = new MovieImpl(editedMovieJSONString);
            deletionSuccessful = mLib.deleteMovie(oldMovie);
            additionSuccessful = mLib.add(newMovie);
            result.put("result", deletionSuccessful & additionSuccessful);
        }
    } catch (Exception ex) {
        System.out.println("exception in callMethod: " + ex.getMessage());
    }
    System.out.println("returning: " + result.toString());
    return "HTTP/1.0 200 Data follows\nServer:localhost:8080\nContent-Type:text/plain\nContent-Length:"
            + (result.toString()).length() + "\n\n" + result.toString();
}

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  ww. j  ava2  s .c o  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;
}