org.json.JSONObject

Here are the examples of the java api org.json.JSONObject taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

18045 Examples 7

19 Source : JSONParser.java
with GNU General Public License v3.0
from zzzmobile

public clreplaced JSONParser {

    static InputStream iStream = null;

    static JSONArray jarray = null;

    static String jarrayq = null;

    static JSONObject jarrayo = null;

    static String json = "";

    public JSONParser() {
    }

    public JSONArray getJSONFromUrl(String url) {
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEnreplacedy enreplacedy = response.getEnreplacedy();
                InputStream content = enreplacedy.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e("==>", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Parse String to JSON object
        try {
            jarray = new JSONArray(builder.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON Object
        return jarray;
    }

    public JSONObject getOJSONFromUrl(String url) {
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEnreplacedy enreplacedy = response.getEnreplacedy();
                InputStream content = enreplacedy.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e("==>", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Parse String to JSON object
        try {
            jarrayo = new JSONObject(builder.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON Object
        return jarrayo;
    }

    public String getSJSONFromUrl(String url) {
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEnreplacedy enreplacedy = response.getEnreplacedy();
                InputStream content = enreplacedy.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e("==>", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        jarrayq = builder.toString();
        // return JSON Object
        return jarrayq;
    }

    public static boolean isNetworkAvailable(Activity activity) {
        ConnectivityManager connectivity = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

19 Source : CharacterHandler.java
with Apache License 2.0
from Zweihui

/**
 * json 格式化
 *
 * @param json
 * @return
 */
public static String jsonFormat(String json) {
    if (TextUtils.isEmpty(json)) {
        return "Empty/Null json content";
    }
    String message;
    try {
        json = json.trim();
        if (json.startsWith("{")) {
            JSONObject jsonObject = new JSONObject(json);
            message = jsonObject.toString(4);
        } else if (json.startsWith("[")) {
            JSONArray jsonArray = new JSONArray(json);
            message = jsonArray.toString(4);
        } else {
            message = json;
        }
    } catch (JSONException e) {
        message = json;
    }
    return message;
}

19 Source : JsonUtils.java
with Apache License 2.0
from zuoweitan

public static String toJsonString(List<Object> list) {
    if (list == null)
        return null;
    JSONObject object = new JSONObject();
    try {
        for (int i = 0; i < list.size(); i++) {
            try {
                object.put(i + "", list.get(i).toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } catch (Exception e) {
        NLog.e(TAG, "JsonUtils failed :", e);
        return null;
    }
    return object.toString();
}

19 Source : ConversationParse.java
with Apache License 2.0
from zuoweitan

public static Wrap parseFrom(String json) {
    Wrap wrap = null;
    try {
        JSONObject jsonObject = new JSONObject(json);
        wrap = new Wrap();
        if (jsonObject.has("conversationId")) {
            wrap.conversationId = jsonObject.getString("conversationId");
        }
        if (jsonObject.has("unreadcount")) {
            wrap.unreadcount = jsonObject.getInt("unreadcount");
        }
        if (jsonObject.has("updateTime")) {
            wrap.updateTime = jsonObject.getLong("updateTime");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return wrap;
}

19 Source : JSONArray.java
with Apache License 2.0
from zsmoore

@Override
public JSONObject toJSONObject(org.json.JSONArray names) throws JSONException {
    if (names != null && !names.isEmpty() && !this.isEmpty()) {
        org.json.JSONObject jo = new org.json.JSONObject();
        for (int i = 0; i < names.length(); ++i) {
            jo.put(names.getString(i), this.opt(i));
        }
        com.zachary_moore.objects.JSONObject retObj = new com.zachary_moore.objects.JSONObject(originatingKey, parentObject, jo);
        retObj.parseAndReplaceWithWrappers();
        return retObj;
    } else {
        return null;
    }
}

19 Source : RunCommandActivity.java
with GNU General Public License v2.0
from ZorinOS

private void updateView() {
    BackgroundService.RunWithPlugin(this, deviceId, RunCommandPlugin.clreplaced, plugin -> runOnUiThread(() -> {
        ListView view = findViewById(R.id.runcommandslist);
        registerForContextMenu(view);
        commandItems = new ArrayList<>();
        for (JSONObject obj : plugin.getCommandList()) {
            try {
                commandItems.add(new CommandEntry(obj.getString("name"), obj.getString("command"), obj.getString("key")));
            } catch (JSONException e) {
                Log.e("RunCommand", "Error parsing JSON", e);
            }
        }
        Collections.sort(commandItems, (lhs, rhs) -> {
            String lName = ((CommandEntry) lhs).getName();
            String rName = ((CommandEntry) rhs).getName();
            return lName.compareTo(rName);
        });
        ListAdapter adapter = new ListAdapter(RunCommandActivity.this, commandItems);
        view.setAdapter(adapter);
        view.setOnItemClickListener((adapterView, view1, i, l) -> {
            CommandEntry entry = (CommandEntry) commandItems.get(i);
            plugin.runCommand(entry.getKey());
        });
        TextView explanation = findViewById(R.id.addcomand_explanation);
        String text = getString(R.string.addcommand_explanation);
        if (!plugin.canAddCommand()) {
            text += "\n" + getString(R.string.addcommand_explanation2);
        }
        explanation.setText(text);
        explanation.setVisibility(commandItems.isEmpty() ? View.VISIBLE : View.GONE);
    }));
}

19 Source : NetworkPacket.java
with GNU General Public License v2.0
from ZorinOS

public clreplaced NetworkPacket {

    public final static int ProtocolVersion = 7;

    public final static String PACKET_TYPE_IDENreplacedY = "kdeconnect.idenreplacedy";

    public final static String PACKET_TYPE_PAIR = "kdeconnect.pair";

    public final static int PACKET_REPLACEID_MOUSEMOVE = 0;

    public final static int PACKET_REPLACEID_PRESENTERPOINTER = 1;

    public static Set<String> protocolPacketTypes = new HashSet<String>() {

        {
            add(PACKET_TYPE_IDENreplacedY);
            add(PACKET_TYPE_PAIR);
        }
    };

    private long mId;

    String mType;

    private JSONObject mBody;

    private Payload mPayload;

    private JSONObject mPayloadTransferInfo;

    private volatile boolean canceled;

    private NetworkPacket() {
    }

    public NetworkPacket(String type) {
        mId = System.currentTimeMillis();
        mType = type;
        mBody = new JSONObject();
        mPayload = null;
        mPayloadTransferInfo = new JSONObject();
    }

    public boolean isCanceled() {
        return canceled;
    }

    public void cancel() {
        canceled = true;
    }

    public String getType() {
        return mType;
    }

    public long getId() {
        return mId;
    }

    // Most commons getters and setters defined for convenience
    public String getString(String key) {
        return mBody.optString(key, "");
    }

    public String getString(String key, String defaultValue) {
        return mBody.optString(key, defaultValue);
    }

    public void set(String key, String value) {
        if (value == null)
            return;
        try {
            mBody.put(key, value);
        } catch (Exception ignored) {
        }
    }

    public int getInt(String key) {
        return mBody.optInt(key, -1);
    }

    public int getInt(String key, int defaultValue) {
        return mBody.optInt(key, defaultValue);
    }

    public void set(String key, int value) {
        try {
            mBody.put(key, value);
        } catch (Exception ignored) {
        }
    }

    public long getLong(String key) {
        return mBody.optLong(key, -1);
    }

    public long getLong(String key, long defaultValue) {
        return mBody.optLong(key, defaultValue);
    }

    public void set(String key, long value) {
        try {
            mBody.put(key, value);
        } catch (Exception ignored) {
        }
    }

    public boolean getBoolean(String key) {
        return mBody.optBoolean(key, false);
    }

    public boolean getBoolean(String key, boolean defaultValue) {
        return mBody.optBoolean(key, defaultValue);
    }

    public void set(String key, boolean value) {
        try {
            mBody.put(key, value);
        } catch (Exception ignored) {
        }
    }

    public double getDouble(String key) {
        return mBody.optDouble(key, Double.NaN);
    }

    public double getDouble(String key, double defaultValue) {
        return mBody.optDouble(key, defaultValue);
    }

    public void set(String key, double value) {
        try {
            mBody.put(key, value);
        } catch (Exception ignored) {
        }
    }

    public JSONArray getJSONArray(String key) {
        return mBody.optJSONArray(key);
    }

    public void set(String key, JSONArray value) {
        try {
            mBody.put(key, value);
        } catch (Exception ignored) {
        }
    }

    public JSONObject getJSONObject(String key) {
        return mBody.optJSONObject(key);
    }

    public void set(String key, JSONObject value) {
        try {
            mBody.put(key, value);
        } catch (JSONException ignored) {
        }
    }

    private Set<String> getStringSet(String key) {
        JSONArray jsonArray = mBody.optJSONArray(key);
        if (jsonArray == null)
            return null;
        Set<String> list = new HashSet<>();
        int length = jsonArray.length();
        for (int i = 0; i < length; i++) {
            try {
                String str = jsonArray.getString(i);
                list.add(str);
            } catch (Exception ignored) {
            }
        }
        return list;
    }

    public Set<String> getStringSet(String key, Set<String> defaultValue) {
        if (mBody.has(key))
            return getStringSet(key);
        else
            return defaultValue;
    }

    public void set(String key, Set<String> value) {
        try {
            JSONArray jsonArray = new JSONArray();
            for (String str : value) {
                jsonArray.put(str);
            }
            mBody.put(key, jsonArray);
        } catch (Exception ignored) {
        }
    }

    public List<String> getStringList(String key) {
        JSONArray jsonArray = mBody.optJSONArray(key);
        if (jsonArray == null)
            return null;
        List<String> list = new ArrayList<>();
        int length = jsonArray.length();
        for (int i = 0; i < length; i++) {
            try {
                String str = jsonArray.getString(i);
                list.add(str);
            } catch (Exception ignored) {
            }
        }
        return list;
    }

    public List<String> getStringList(String key, List<String> defaultValue) {
        if (mBody.has(key))
            return getStringList(key);
        else
            return defaultValue;
    }

    public void set(String key, List<String> value) {
        try {
            JSONArray jsonArray = new JSONArray();
            for (String str : value) {
                jsonArray.put(str);
            }
            mBody.put(key, jsonArray);
        } catch (Exception ignored) {
        }
    }

    public boolean has(String key) {
        return mBody.has(key);
    }

    public String serialize() throws JSONException {
        JSONObject jo = new JSONObject();
        jo.put("id", mId);
        jo.put("type", mType);
        jo.put("body", mBody);
        if (hasPayload()) {
            jo.put("payloadSize", mPayload.payloadSize);
            jo.put("payloadTransferInfo", mPayloadTransferInfo);
        }
        // QJSon does not escape slashes, but Java JSONObject does. Converting to QJson format.
        return jo.toString().replace("\\/", "/") + "\n";
    }

    static public NetworkPacket unserialize(String s) throws JSONException {
        NetworkPacket np = new NetworkPacket();
        JSONObject jo = new JSONObject(s);
        np.mId = jo.getLong("id");
        np.mType = jo.getString("type");
        np.mBody = jo.getJSONObject("body");
        if (jo.has("payloadSize")) {
            np.mPayloadTransferInfo = jo.getJSONObject("payloadTransferInfo");
            np.mPayload = new Payload(jo.getLong("payloadSize"));
        } else {
            np.mPayloadTransferInfo = new JSONObject();
            np.mPayload = new Payload(0);
        }
        return np;
    }

    static public NetworkPacket createIdenreplacedyPacket(Context context) {
        NetworkPacket np = new NetworkPacket(NetworkPacket.PACKET_TYPE_IDENreplacedY);
        String deviceId = DeviceHelper.getDeviceId(context);
        try {
            np.mBody.put("deviceId", deviceId);
            np.mBody.put("deviceName", DeviceHelper.getDeviceName(context));
            np.mBody.put("protocolVersion", NetworkPacket.ProtocolVersion);
            np.mBody.put("deviceType", DeviceHelper.getDeviceType(context).toString());
            np.mBody.put("incomingCapabilities", new JSONArray(PluginFactory.getIncomingCapabilities()));
            np.mBody.put("outgoingCapabilities", new JSONArray(PluginFactory.getOutgoingCapabilities()));
        } catch (Exception e) {
            Log.e("NetworkPackage", "Exception on createIdenreplacedyPacket", e);
        }
        return np;
    }

    public void setPayload(Payload payload) {
        mPayload = payload;
    }

    public Payload getPayload() {
        return mPayload;
    }

    public long getPayloadSize() {
        return mPayload == null ? 0 : mPayload.payloadSize;
    }

    public boolean hasPayload() {
        return (mPayload != null && mPayload.payloadSize != 0);
    }

    public boolean hasPayloadTransferInfo() {
        return (mPayloadTransferInfo.length() > 0);
    }

    public JSONObject getPayloadTransferInfo() {
        return mPayloadTransferInfo;
    }

    public void setPayloadTransferInfo(JSONObject payloadTransferInfo) {
        mPayloadTransferInfo = payloadTransferInfo;
    }

    public static clreplaced Payload {

        private InputStream inputStream;

        private Socket inputSocket;

        private long payloadSize;

        public Payload(long payloadSize) {
            this((InputStream) null, payloadSize);
        }

        public Payload(byte[] data) {
            this(new ByteArrayInputStream(data), data.length);
        }

        /**
         * <b>NOTE: Do not use this to set an SSLSockets InputStream as the payload, use Payload(Socket, long) instead because of this <a href="https://issuetracker.google.com/issues/37018094">bug</a></b>
         */
        public Payload(InputStream inputStream, long payloadSize) {
            this.inputSocket = null;
            this.inputStream = inputStream;
            this.payloadSize = payloadSize;
        }

        public Payload(Socket inputSocket, long payloadSize) throws IOException {
            this.inputSocket = inputSocket;
            this.inputStream = inputSocket.getInputStream();
            this.payloadSize = payloadSize;
        }

        /**
         * <b>NOTE: Do not close the InputStream directly call Payload.close() instead, this is because of this <a href="https://issuetracker.google.com/issues/37018094">bug</a></b>
         */
        public InputStream getInputStream() {
            return inputStream;
        }

        long getPayloadSize() {
            return payloadSize;
        }

        public void close() {
            // TODO: If socket only close socket if that also closes the streams that is
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException ignored) {
            }
            try {
                if (inputSocket != null) {
                    inputSocket.close();
                }
            } catch (IOException ignored) {
            }
        }
    }
}

19 Source : NetworkPacket.java
with GNU General Public License v2.0
from ZorinOS

public void setPayloadTransferInfo(JSONObject payloadTransferInfo) {
    mPayloadTransferInfo = payloadTransferInfo;
}

19 Source : Patcher.java
with MIT License
from zmilla93

public clreplaced Patcher {

    // Github Stuff
    private final String GIT_TAG_KEY = "tag_name";

    private final String API_LATEST_VERSION;

    private final String BLANK_DOWNLOAD;

    // Internal
    private String latestVersion;

    private boolean autoUpdate = true;

    private boolean apiRateLimited = false;

    private boolean coreFileExists;

    private String launcherPath;

    private String launcherFileName;

    private JSONObject launcherJSON;

    private final int MAX_ATTEMPTS = 5;

    private Debugger debugger;

    public Patcher(Debugger debugger) {
        this.debugger = debugger;
        API_LATEST_VERSION = "https://api.github.com/repos/" + References.AUTHOR_NAME + "/" + UpdateManager.TARGET_REPO + "/releases/latest";
        BLANK_DOWNLOAD = "https://github.com/" + References.AUTHOR_NAME + "/" + UpdateManager.TARGET_REPO + "/releases/download/%tag%/%file%";
        // Save launcher path
        try {
            launcherPath = URLDecoder.decode(new File(Patcher.clreplaced.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath(), "UTF-8");
            File launcherFile = new File(launcherPath);
            launcherFileName = launcherFile.getName();
        } catch (URISyntaxException | UnsupportedEncodingException e) {
            debugger.log("Failed to get launch path : " + e.getMessage());
            debugger.log(e.getStackTrace());
        }
    }

    public boolean isUpdateAvailable() {
        debugger.log("Checking for update...");
        debugger.log("Current Version: " + References.getAppVersion());
        latestVersion = fetchLatestVersion();
        if (latestVersion == null) {
            apiRateLimited = true;
            debugger.log("API rate exceeded.");
            return false;
        }
        debugger.log("Latest Version: " + latestVersion);
        if (!latestVersion.matches(References.getAppVersion())) {
            debugger.log("New Version Available : " + latestVersion);
            return true;
        }
        debugger.log("No update found.");
        return false;
    }

    private String fetchLatestVersion() {
        String version;
        BufferedReader br = null;
        InputStream is;
        try {
            is = new URL(API_LATEST_VERSION).openStream();
        } catch (IOException e) {
            return null;
        }
        try {
            br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            StringBuilder builder = new StringBuilder();
            try {
                while (br.ready()) {
                    builder.append(br.readLine());
                }
            } catch (IOException e) {
                debugger.log("Error while fetching latest version : " + e.getMessage());
            }
            JSONObject json = new JSONObject(builder.toString());
            version = json.getString(GIT_TAG_KEY);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    debugger.log(e.getStackTrace());
                }
            }
        }
        return version;
    }

    public boolean downloadFile(String fileName, String urlString, IDownloadTracker tracker) {
        int attempts = 1;
        while (attempts <= MAX_ATTEMPTS) {
            try {
                debugger.log("Downloading '" + fileName + "' from '" + urlString + "'...");
                URL url = new URL(urlString);
                HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
                long fileSize = httpConnection.getContentLength();
                BufferedInputStream in = new BufferedInputStream(httpConnection.getInputStream());
                FileOutputStream fos = new FileOutputStream(App.saveManager.INSTALL_DIRECTORY + File.separator + fileName);
                BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
                byte[] data = new byte[1024];
                long downloadedFileSize = 0;
                int i = 0;
                while ((i = in.read(data, 0, 1024)) >= 0) {
                    downloadedFileSize += i;
                    final int currentProgress = (int) ((((double) downloadedFileSize) / ((double) fileSize)) * 100000d);
                    tracker.downloadPercentCallback(currentProgress);
                    bout.write(data, 0, i);
                }
                bout.close();
                in.close();
                debugger.log("Download complete.");
                return true;
            } catch (IOException e) {
                if (attempts == MAX_ATTEMPTS) {
                    debugger.log("Error downloading file from '" + urlString + "'");
                    return false;
                } else {
                    tracker.textCallback("Download failed, retrying...");
                    debugger.log("Download failed, retrying... (" + attempts + ")");
                    try {
                        Thread.sleep(400);
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }
                    attempts++;
                }
            }
        }
        return false;
    }

    public boolean deleteFile(String fileName) {
        File file = new File(App.saveManager.INSTALL_DIRECTORY + File.separator + fileName);
        if (!file.exists()) {
            return true;
        }
        debugger.log("Deleting file: " + file.getPath());
        int attempts = 0;
        while (file.exists() && attempts < MAX_ATTEMPTS && !file.delete()) {
            debugger.log("Failed to delete temp launcher file");
            debugger.log("Retrying (" + (attempts + 1) + ")...");
            attempts++;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        boolean exists = file.exists();
        if (exists) {
            debugger.log("Failed to delete file.");
        } else {
            debugger.log("File deleted successfully.");
        }
        return exists;
    }

    public boolean copyFile(String sourceName, String destName) {
        File destFile = new File(destName);
        if (destFile.exists()) {
            if (!destFile.delete()) {
                return false;
            }
        }
        Path src = new File(sourceName).toPath();
        Path dest = new File(destName).toPath();
        int attempts = 1;
        debugger.log("Moving file '" + sourceName + "' to '" + destName + "'...");
        while (attempts <= MAX_ATTEMPTS) {
            try {
                Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
                debugger.log("File moved successfully.");
                return true;
            } catch (IOException e) {
                if (attempts < MAX_ATTEMPTS) {
                    System.out.println("Failed to move file, retrying...");
                    attempts++;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }
                } else {
                    debugger.log("Failed to move and overwrite file!");
                    debugger.log("Source: " + sourceName);
                    debugger.log("Destination: " + destName);
                    debugger.log(e.getStackTrace());
                    return false;
                }
            }
        }
        return false;
    }

    // Getters
    public boolean isAutoUpdate() {
        return autoUpdate;
    }

    public String getLatestVersion() {
        return latestVersion;
    }

    public boolean isApiRateLimited() {
        return apiRateLimited;
    }

    public boolean isCoreFileExists() {
        return coreFileExists;
    }
}

19 Source : Patcher.java
with MIT License
from zmilla93

private String fetchLatestVersion() {
    String version;
    BufferedReader br = null;
    InputStream is;
    try {
        is = new URL(API_LATEST_VERSION).openStream();
    } catch (IOException e) {
        return null;
    }
    try {
        br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        StringBuilder builder = new StringBuilder();
        try {
            while (br.ready()) {
                builder.append(br.readLine());
            }
        } catch (IOException e) {
            debugger.log("Error while fetching latest version : " + e.getMessage());
        }
        JSONObject json = new JSONObject(builder.toString());
        version = json.getString(GIT_TAG_KEY);
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                debugger.log(e.getStackTrace());
            }
        }
    }
    return version;
}

19 Source : ResponseEntityToModule.java
with Apache License 2.0
from zion223

public static Object parseJsonObjectToModule(JSONObject jsonObj, Clreplaced<?> clazz) {
    Object moduleObj = null;
    try {
        moduleObj = (Object) clazz.newInstance();
        setFieldValue(moduleObj, jsonObj, clazz);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return moduleObj;
}

19 Source : ResponseEntityToModule.java
with Apache License 2.0
from zion223

public static Object parseJsonToModule(String jsonContent, Clreplaced<?> clazz) {
    Object moduleObj = null;
    try {
        JSONObject jsonObj = new JSONObject(jsonContent);
        moduleObj = parseJsonObjectToModule(jsonObj, clazz);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return moduleObj;
}

19 Source : CommonJsonCallback.java
with Apache License 2.0
from zion223

/**
 * 处理数据
 *
 * @param response
 */
private void handleResponse(Object response) {
    if (response.toString().trim().equals("")) {
        mDisposeDataListener.onFailure(new OkHttpException(NETWORK_ERROR, EMPTY_MSG));
        return;
    }
    try {
        JSONObject resultJson = new JSONObject(response.toString());
        // TODO 加入需要登录判断
        if (mClreplaced == null) {
            mDisposeDataListener.onSuccess(resultJson);
        } else {
            Object obj = new Gson().fromJson(response.toString(), mClreplaced);
            if (obj != null) {
                mDisposeDataListener.onSuccess(obj);
            } else {
                mDisposeDataListener.onFailure(new OkHttpException(JSON_ERROR, EMPTY_MSG));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        mDisposeDataListener.onFailure(new OkHttpException(JSON_ERROR, EMPTY_MSG));
    }
}

19 Source : JMJSObject.java
with Apache License 2.0
from ZhuoKeTeam

public void handleResource(String msg) {
    Log.d(TAG, "handleResource: ====================== come in handleResource");
    Log.d(TAG, msg);
    try {
        // 参数配置项目: http://www.bubuko.com/infodetail-1228020.html
        JSONObject obj = new JSONObject(msg);
        String type = obj.optString("type");
        JSONObject payloadObj = obj.optJSONObject("payload");
        String url = payloadObj.optString("url");
        String domain = payloadObj.optString("domain");
        String uri = payloadObj.optString("uri");
        JSONObject navigationTimingObj = payloadObj.optJSONObject("navigationTiming");
        long pageTime = navigationTimingObj.optLong("pageTime");
        // DNS查询耗时、TCP链接耗时、request请求耗时、解析dom树耗时、白屏时间、domready时间、onload时间等,
        // 而这些参数是通过上面的performance.timing各个属性的差值组成的,计算方法如下:
        // 
        // DNS查询耗时 :domainLookupEnd - domainLookupStart
        long domainLookupStart = navigationTimingObj.optLong("domainLookupStart");
        long domainLookupEnd = navigationTimingObj.optLong("domainLookupEnd");
        long dsnTime = domainLookupEnd - domainLookupStart;
        // 
        // TCP链接耗时 :connectEnd - connectStart
        long connectStart = navigationTimingObj.optLong("connectStart");
        long connectEnd = navigationTimingObj.optLong("connectEnd");
        long tcpTime = connectEnd - connectStart;
        // 
        // request请求耗时 :responseEnd - responseStart
        long responseStart = navigationTimingObj.optLong("responseStart");
        long responseEnd = navigationTimingObj.optLong("responseEnd");
        long requestTime = responseEnd - responseStart;
        // 
        // 解析dom树耗时 : domComplete- domInteractive
        long domInteractive = navigationTimingObj.optLong("domInteractive");
        long domComplete = navigationTimingObj.optLong("domComplete");
        long domTime = domComplete - domInteractive;
        // 
        // 白屏时间 :responseStart - navigationStart
        // long responseStart = navigationTimingObj.optLong("responseStart");
        long navigationStart = navigationTimingObj.optLong("navigationStart");
        long whiteUITime = responseStart - navigationStart;
        // 
        // domready时间 :domContentLoadedEventEnd - navigationStart
        // long navigationStart = navigationTimingObj.optLong("navigationStart");
        long domContentLoadedEventEnd = navigationTimingObj.optLong("domContentLoadedEventEnd");
        long domReadyTime = domContentLoadedEventEnd - navigationStart;
        // 
        // onload时间 :loadEventEnd - navigationStart
        // long navigationStart = navigationTimingObj.optLong("navigationStart");
        long loadEventEnd = navigationTimingObj.optLong("loadEventEnd");
        long onLoadTime = domComplete - domInteractive;
        // 添加数据到监控页面去。
        if (whiteUITime > 0) {
            QPMManager.getInstance().setH5MonitorData(url, whiteUITime);
        }
        Log.d(TAG, "AAA_handleResource: " + "\npageTime=" + pageTime + "\npageTime=" + TimeUtils.millis2String(pageTime) + "\n,dsnTime=" + dsnTime + "\n,tcpTime=" + tcpTime + "\n,requestTime=" + requestTime + "\n,domTime=" + domTime + "\n,whiteUITime=" + whiteUITime + "\n,domReadyTime=" + domReadyTime + "\n,onLoadTime=" + onLoadTime);
        JSONArray resourceTimingArray = payloadObj.optJSONArray("resourceTiming");
        for (int i = 0; i < resourceTimingArray.length(); i++) {
            String data = String.valueOf(resourceTimingArray.get(i));
            JSONObject resObj = new JSONObject(data);
            // TCP链接耗时 :connectEndRes - connectStartRes
            long connectResStart = resObj.optLong("connectStart");
            long connectResEnd = resObj.optLong("connectEnd");
            long tcpResTime = connectResEnd - connectResStart;
            // DNS查询耗时 :domainLookupEnd - domainLookupStart
            long domainLookupResStart = resObj.optLong("domainLookupStart");
            long domainLookupResEnd = resObj.optLong("domainLookupEnd");
            long dsnResTime = domainLookupResEnd - domainLookupResStart;
            // request请求耗时 :responseEnd - responseStart
            long responseResStart = navigationTimingObj.optLong("responseStart");
            long responseResEnd = navigationTimingObj.optLong("responseEnd");
            long requestResTime = responseResEnd - responseResStart;
            long durationResTime = resObj.optLong("duration");
            // resource
            String entryResType = resObj.optString("entryType");
            long fetchResStart = resObj.optLong("fetchStart");
            // script,html,css 等类型
            String initiatorResType = resObj.optString("initiatorType");
            String resName = resObj.optString("name");
            long redirectResEnd = resObj.optLong("redirectEnd");
            long redirectResStart = resObj.optLong("redirectStart");
            long redirectResTime = redirectResEnd - redirectResStart;
            long requestTimeResStart = resObj.optLong("requestStart");
            long secureConnectionResStart = resObj.optLong("secureConnectionStart");
            long startResTime = resObj.optLong("startTime");
            Log.d(TAG, "AAA_Res_handleResource: " + "\nstartResTime=" + startResTime + "\n,dsnTime=" + dsnTime + "\n,dsnResTime=" + dsnResTime + "\n,requestResTime=" + requestResTime + "\n,redirectResTime=" + redirectResTime + "\n,requestTimeResStart=" + requestTimeResStart + "\n,secureConnectionResStart=" + secureConnectionResStart + "\n,durationResTime=" + durationResTime + "\n,entryResType=" + entryResType + "\n,initiatorResType=" + initiatorResType + "\n,resName=" + resName);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

19 Source : GetJson.java
with Apache License 2.0
from zhoubiao188

public JSONObject getJsonString(String str, int comefrom) throws Exception {
    JSONObject jo = null;
    if (comefrom == 1) {
        return new JSONObject(str);
    } else if (comefrom == 2) {
        int indexStart = 0;
        // 字符处理
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '(') {
                indexStart = i;
                break;
            }
        }
        String strNew = "";
        // 分割字符串
        for (int i = indexStart + 1; i < str.length() - 1; i++) {
            strNew += str.charAt(i);
        }
        return new JSONObject(strNew);
    }
    return jo;
}

19 Source : ACache.java
with Apache License 2.0
from zhou-you

public JSONObject getAsJSONObject(String key) {
    String JSONString = getreplacedtring(key);
    try {
        JSONObject obj = new JSONObject(JSONString);
        return obj;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

19 Source : PictureUploadUtil.java
with Apache License 2.0
from zhonglikui

public static List<String> getImageUrlsFromResult(String message) {
    List<String> urls = new ArrayList<>();
    try {
        JSONObject jsonObject = new JSONObject(message);
        JSONArray jsonArray = jsonObject.getJSONArray("urls");
        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                urls.add(jsonArray.optString(i));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return urls;
}

19 Source : TestCaseFactory.java
with MIT License
from ZhongAnTech

public static TestCase getTestCase(String caseJson) throws JSONException {
    JSONObject testjson = new JSONObject(caseJson);
    return new TestCase(testjson);
}

19 Source : TestCaseFactory.java
with MIT License
from ZhongAnTech

public static IStep convertStep(JSONObject role) {
    Object object;
    try {
        Clreplaced<?> stepClreplaced = Clreplaced.forName(STEP_PACKAGE_NAME + role.optString("action"));
        object = stepClreplaced.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    for (Iterator iter = role.keys(); iter.hasNext(); ) {
        String key = (String) iter.next();
        if (key.equals("action"))
            continue;
        Object value = null;
        try {
            value = role.get(key);
        } catch (JSONException e) {
            e.printStackTrace();
            continue;
        }
        reflectObject(object, key, value);
    }
    return (IStep) object;
}

19 Source : TestCase.java
with MIT License
from ZhongAnTech

public clreplaced TestCase {

    private JSONArray jsonSteps;

    private JSONObject testJson;

    public TestCase(JSONObject testJson) {
        this.testJson = testJson;
    }

    public void runCase(String resultPath) throws JSONException {
        // 设定结果路径
        LogUtils.getInstance().setResultPath(resultPath);
        this.jsonSteps = testJson.getJSONArray("steps");
        String versionName = BuildConfig.VERSION_NAME;
        testJson.put("farmerVersion", versionName);
        TestCaseLogListener testCaseLogListener = new TestCaseLogListener();
        LogUtils.getInstance().setLogListener(testCaseLogListener);
        for (int i = 0; i < jsonSteps.length(); i++) {
            JSONObject jStep = null;
            try {
                jStep = jsonSteps.getJSONObject(i);
            } catch (JSONException e) {
                // TODO 添加log输出
                e.printStackTrace();
                continue;
            }
            int errorHandle = 0;
            try {
                errorHandle = jStep.getInt("errorHandle");
            } catch (Exception e) {
            }
            // 创建步骤
            IStep mStep = TestCaseFactory.convertStep(jStep);
            if (mStep == null) {
                // 不明的步骤处理,不做处理
                continue;
            }
            StepResult stepResult = new StepResult();
            stepResult.setStartTime(System.currentTimeMillis());
            boolean isSuccess = mStep.runStep();
            stepResult.setEndTime(System.currentTimeMillis());
            if (isSuccess) {
                stepResult.setResult(StepResult.resultCode.Preplaced);
            } else if (errorHandle == 2) {
                stepResult.setResult(StepResult.resultCode.Warning);
            } else {
                stepResult.setResult(StepResult.resultCode.Fail);
            }
            List logs = testCaseLogListener.pullLogs();
            stepResult.setLogs(logs);
            List images = testCaseLogListener.pullImages();
            stepResult.setImages(images);
            // 加入报告节点
            try {
                jStep.put("result", stepResult.createResult());
                createFile(resultPath);
            } catch (JSONException | IOException e) {
                // 如果生成json 错误的话直接不用跑了
                e.printStackTrace();
                return;
            }
            if (stepResult.getResult() == StepResult.resultCode.Fail) {
                return;
            }
        }
    }

    private void createFile(String path) throws IOException {
        File file = new File(path, "result.json");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream out = new FileOutputStream(file);
        out.write(testJson.toString().getBytes());
        out.flush();
        out.close();
    }
}

19 Source : DataObject.java
with Apache License 2.0
from zhaocq-nlp

public JSONArray getAttentionWeight(int index, String attentionField) {
    JSONObject instanceObj = this.get(index);
    try {
        JSONArray attLists = instanceObj.getJSONArray("attentions");
        for (int i = 0; i < attLists.length(); ++i) {
            JSONObject obj = attLists.getJSONObject(i);
            if (obj.getString("name").equals(attentionField)) {
                return obj.getJSONArray("value");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
    System.exit(0);
    return null;
}

19 Source : DataObject.java
with Apache License 2.0
from zhaocq-nlp

public JSONObject get(int index) {
    try {
        JSONObject obj = this.dataObject.getJSONObject(String.format("%d", index));
        return obj;
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
    return null;
}

19 Source : DataObject.java
with Apache License 2.0
from zhaocq-nlp

public String getAttentionType(int index, String attentionField) {
    JSONObject instanceObj = this.get(index);
    try {
        JSONArray attLists = instanceObj.getJSONArray("attentions");
        for (int i = 0; i < attLists.length(); ++i) {
            JSONObject obj = attLists.getJSONObject(i);
            if (obj.getString("name").equals(attentionField)) {
                return obj.getString("type");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
    System.exit(0);
    return null;
}

19 Source : Request.java
with MIT License
from zhangyd-c

/**
 * An object you use to specify a notification’s content and the condition
 * that triggers its delivery.
 */
public final clreplaced Request {

    // Key name for bundled extras
    static final String EXTRA_OCCURRENCE = "NOTIFICATION_OCCURRENCE";

    // Key name for bundled extras
    public static final String EXTRA_LAST = "NOTIFICATION_LAST";

    // The options spec
    private final Options options;

    // The right trigger for the options
    private final DateTrigger trigger;

    // How often the trigger shall occur
    private final int count;

    // The trigger spec
    private final JSONObject spec;

    // The current trigger date
    private Date triggerDate;

    /**
     * Constructor
     *
     * @param options The options spec.
     */
    public Request(Options options) {
        this.options = options;
        this.spec = options.getTrigger();
        this.count = Math.max(spec.optInt("count"), 1);
        this.trigger = buildTrigger();
        this.triggerDate = trigger.getNextTriggerDate(getBaseDate());
    }

    /**
     * Gets the options spec.
     */
    public Options getOptions() {
        return options;
    }

    /**
     * The identifier for the request.
     *
     * @return The notification ID as the string
     */
    String getIdentifier() {
        return options.getId().toString() + "-" + getOccurrence();
    }

    /**
     * The value of the internal occurrence counter.
     */
    int getOccurrence() {
        return trigger.getOccurrence();
    }

    /**
     * If there's one more trigger date to calculate.
     */
    private boolean hasNext() {
        return triggerDate != null && getOccurrence() <= count;
    }

    /**
     * Moves the internal occurrence counter by one.
     */
    boolean moveNext() {
        if (hasNext()) {
            triggerDate = getNextTriggerDate();
        } else {
            triggerDate = null;
        }
        return this.triggerDate != null;
    }

    /**
     * Gets the current trigger date.
     *
     * @return null if there's no trigger date.
     */
    Date getTriggerDate() {
        Calendar now = Calendar.getInstance();
        if (triggerDate == null)
            return null;
        long time = triggerDate.getTime();
        if ((now.getTimeInMillis() - time) > 60000)
            return null;
        if (time >= spec.optLong("before", time + 1))
            return null;
        return triggerDate;
    }

    /**
     * Gets the next trigger date based on the current trigger date.
     */
    private Date getNextTriggerDate() {
        return trigger.getNextTriggerDate(triggerDate);
    }

    /**
     * Build the trigger specified in options.
     */
    private DateTrigger buildTrigger() {
        Object every = spec.opt("every");
        if (every instanceof JSONObject) {
            List<Integer> cmp1 = getMatchingComponents();
            List<Integer> cmp2 = getSpecialMatchingComponents();
            return new MatchTrigger(cmp1, cmp2);
        }
        Unit unit = getUnit();
        int ticks = getTicks();
        return new IntervalTrigger(ticks, unit);
    }

    /**
     * Gets the unit value.
     */
    private Unit getUnit() {
        Object every = spec.opt("every");
        String unit = "SECOND";
        if (spec.has("unit")) {
            unit = spec.optString("unit", "second");
        } else if (every instanceof String) {
            unit = spec.optString("every", "second");
        }
        return Unit.valueOf(unit.toUpperCase());
    }

    /**
     * Gets the tick value.
     */
    private int getTicks() {
        Object every = spec.opt("every");
        int ticks = 0;
        if (spec.has("at")) {
            ticks = 0;
        } else if (spec.has("in")) {
            ticks = spec.optInt("in", 0);
        } else if (every instanceof String) {
            ticks = 1;
        } else if (!(every instanceof JSONObject)) {
            ticks = spec.optInt("every", 0);
        }
        return ticks;
    }

    /**
     * Gets an array of all date parts to construct a datetime instance.
     *
     * @return [min, hour, day, month, year]
     */
    private List<Integer> getMatchingComponents() {
        JSONObject every = spec.optJSONObject("every");
        return Arrays.asList((Integer) every.opt("minute"), (Integer) every.opt("hour"), (Integer) every.opt("day"), (Integer) every.opt("month"), (Integer) every.opt("year"));
    }

    /**
     * Gets an array of all date parts to construct a datetime instance.
     *
     * @return [min, hour, day, month, year]
     */
    private List<Integer> getSpecialMatchingComponents() {
        JSONObject every = spec.optJSONObject("every");
        return Arrays.asList((Integer) every.opt("weekday"), (Integer) every.opt("weekdayOrdinal"), (Integer) every.opt("weekOfMonth"), (Integer) every.opt("quarter"));
    }

    /**
     * Gets the base date from where to calculate the next trigger date.
     */
    private Date getBaseDate() {
        if (spec.has("at")) {
            return new Date(spec.optLong("at", 0));
        } else if (spec.has("firstAt")) {
            return new Date(spec.optLong("firstAt", 0));
        } else if (spec.has("after")) {
            return new Date(spec.optLong("after", 0));
        } else {
            return new Date();
        }
    }
}

19 Source : Request.java
with MIT License
from zhangyd-c

/**
 * Gets an array of all date parts to construct a datetime instance.
 *
 * @return [min, hour, day, month, year]
 */
private List<Integer> getMatchingComponents() {
    JSONObject every = spec.optJSONObject("every");
    return Arrays.asList((Integer) every.opt("minute"), (Integer) every.opt("hour"), (Integer) every.opt("day"), (Integer) every.opt("month"), (Integer) every.opt("year"));
}

19 Source : Request.java
with MIT License
from zhangyd-c

/**
 * Gets an array of all date parts to construct a datetime instance.
 *
 * @return [min, hour, day, month, year]
 */
private List<Integer> getSpecialMatchingComponents() {
    JSONObject every = spec.optJSONObject("every");
    return Arrays.asList((Integer) every.opt("weekday"), (Integer) every.opt("weekdayOrdinal"), (Integer) every.opt("weekOfMonth"), (Integer) every.opt("quarter"));
}

19 Source : Options.java
with MIT License
from zhangyd-c

/**
 * Gets the list of messages to display.
 *
 * @return null if there are no messages.
 */
Message[] getMessages() {
    Object text = options.opt("text");
    if (text == null || text instanceof String)
        return null;
    JSONArray list = (JSONArray) text;
    if (list.length() == 0)
        return null;
    Message[] messages = new Message[list.length()];
    long now = new Date().getTime();
    for (int i = 0; i < messages.length; i++) {
        JSONObject msg = list.optJSONObject(i);
        String message = msg.optString("message");
        long timestamp = msg.optLong("date", now);
        String person = msg.optString("person", null);
        messages[i] = new Message(message, timestamp, person);
    }
    return messages;
}

19 Source : Manager.java
with MIT License
from zhangyd-c

/**
 * Update local notification specified by ID.
 *
 * @param id       The notification ID.
 * @param updates  JSON object with notification options.
 * @param receiver Receiver to handle the trigger event.
 */
public Notification update(int id, JSONObject updates, Clreplaced<?> receiver) {
    Notification notification = get(id);
    if (notification == null)
        return null;
    notification.update(updates, receiver);
    return notification;
}

19 Source : LocalNotification.java
with MIT License
from zhangyd-c

/**
 * Update multiple local notifications.
 *
 * @param updates Notification properties including their IDs
 */
private void update(JSONArray updates) {
    for (int i = 0; i < updates.length(); i++) {
        JSONObject update = updates.optJSONObject(i);
        int id = update.optInt("id", 0);
        Notification notification = getNotMgr().update(id, update, TriggerReceiver.clreplaced);
        if (notification == null)
            continue;
        fireEvent("update", notification);
    }
}

19 Source : FileTransfer.java
with MIT License
from zhangyd-c

/**
 * Create an error object based on the preplaceded in errorCode
 * @param errorCode      the error
 * @return JSONObject containing the error
 */
private static JSONObject createFileTransferError(int errorCode, String source, String target, String body, Integer httpStatus, Throwable throwable) {
    JSONObject error = null;
    try {
        error = new JSONObject();
        error.put("code", errorCode);
        error.put("source", source);
        error.put("target", target);
        if (body != null) {
            error.put("body", body);
        }
        if (httpStatus != null) {
            error.put("http_status", httpStatus);
        }
        if (throwable != null) {
            String msg = throwable.getMessage();
            if (msg == null || "".equals(msg)) {
                msg = throwable.toString();
            }
            error.put("exception", msg);
        }
    } catch (JSONException e) {
        LOG.e(LOG_TAG, e.getMessage(), e);
    }
    return error;
}

19 Source : FileTransfer.java
with MIT License
from zhangyd-c

/**
 * Create an error object based on the preplaceded in errorCode
 * @param errorCode      the error
 * @return JSONObject containing the error
 */
private static JSONObject createFileTransferError(int errorCode, String source, String target, String body, Integer httpStatus) {
    JSONObject error = null;
    try {
        error = new JSONObject();
        error.put("code", errorCode);
        error.put("source", source);
        error.put("target", target);
        if (body != null) {
            error.put("body", body);
        }
        if (httpStatus != null) {
            error.put("http_status", httpStatus);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return error;
}

19 Source : FileTransfer.java
with MIT License
from zhangyd-c

/**
 * Abort an ongoing upload or download.
 */
private void abort(String objectId) {
    final RequestContext context;
    synchronized (activeRequests) {
        context = activeRequests.remove(objectId);
    }
    if (context != null) {
        File file = context.targetFile;
        if (file != null) {
            file.delete();
        }
        // Trigger the abort callback immediately to minimize latency between it and abort() being called.
        JSONObject error = createFileTransferError(ABORTED_ERR, context.source, context.target, null, -1);
        synchronized (context) {
            context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error));
            context.aborted = true;
        }
        // Closing the streams can block, so execute on a background thread.
        cordova.getThreadPool().execute(new Runnable() {

            public void run() {
                synchronized (context) {
                    safeClose(context.currentInputStream);
                    safeClose(context.currentOutputStream);
                }
            }
        });
    }
}

19 Source : LocalFilesystem.java
with MIT License
from zhangyd-c

@Override
public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
    boolean create = false;
    boolean exclusive = false;
    if (options != null) {
        create = options.optBoolean("create");
        if (create) {
            exclusive = options.optBoolean("exclusive");
        }
    }
    // Check for a ":" character in the file to line up with BB and iOS
    if (path.contains(":")) {
        throw new EncodingException("This path has an invalid \":\" in it.");
    }
    LocalFilesystemURL requestedURL;
    // Check whether the supplied path is absolute or relative
    if (directory && !path.endsWith("/")) {
        path += "/";
    }
    if (path.startsWith("/")) {
        requestedURL = localUrlforFullPath(normalizePath(path));
    } else {
        requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
    }
    File fp = new File(this.filesystemPathForURL(requestedURL));
    if (create) {
        if (exclusive && fp.exists()) {
            throw new FileExistsException("create/exclusive fails");
        }
        if (directory) {
            fp.mkdir();
        } else {
            fp.createNewFile();
        }
        if (!fp.exists()) {
            throw new FileExistsException("create fails");
        }
    } else {
        if (!fp.exists()) {
            throw new FileNotFoundException("path does not exist");
        }
        if (directory) {
            if (fp.isFile()) {
                throw new TypeMismatchException("path doesn't exist or is file");
            }
        } else {
            if (fp.isDirectory()) {
                throw new TypeMismatchException("path doesn't exist or is directory");
            }
        }
    }
    // Return the directory
    return makeEntryForURL(requestedURL);
}

19 Source : LocalFilesystem.java
with MIT License
from zhangyd-c

@Override
public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
    File file = new File(filesystemPathForURL(inputURL));
    if (!file.exists()) {
        throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
    }
    JSONObject metadata = new JSONObject();
    try {
        // Ensure that directories report a size of 0
        metadata.put("size", file.isDirectory() ? 0 : file.length());
        metadata.put("type", resourceApi.getMimeType(Uri.fromFile(file)));
        metadata.put("name", file.getName());
        metadata.put("fullPath", inputURL.path);
        metadata.put("lastModifiedDate", file.lastModified());
    } catch (JSONException e) {
        return null;
    }
    return metadata;
}

19 Source : Filesystem.java
with MIT License
from zhangyd-c

public abstract clreplaced Filesystem {

    protected final Uri rootUri;

    protected final CordovaResourceApi resourceApi;

    public final String name;

    private JSONObject rootEntry;

    public Filesystem(Uri rootUri, String name, CordovaResourceApi resourceApi) {
        this.rootUri = rootUri;
        this.name = name;
        this.resourceApi = resourceApi;
    }

    public interface ReadFileCallback {

        public void handleData(InputStream inputStream, String contentType) throws IOException;
    }

    public static JSONObject makeEntryForURL(LocalFilesystemURL inputURL, Uri nativeURL) {
        try {
            String path = inputURL.path;
            int end = path.endsWith("/") ? 1 : 0;
            String[] parts = path.substring(0, path.length() - end).split("/+");
            String fileName = parts[parts.length - 1];
            JSONObject entry = new JSONObject();
            entry.put("isFile", !inputURL.isDirectory);
            entry.put("isDirectory", inputURL.isDirectory);
            entry.put("name", fileName);
            entry.put("fullPath", path);
            // The file system can't be specified, as it would lead to an infinite loop,
            // but the filesystem name can be.
            entry.put("filesystemName", inputURL.fsName);
            // Backwards compatibility
            entry.put("filesystem", "temporary".equals(inputURL.fsName) ? 0 : 1);
            String nativeUrlStr = nativeURL.toString();
            if (inputURL.isDirectory && !nativeUrlStr.endsWith("/")) {
                nativeUrlStr += "/";
            }
            entry.put("nativeURL", nativeUrlStr);
            return entry;
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public JSONObject makeEntryForURL(LocalFilesystemURL inputURL) {
        Uri nativeUri = toNativeUri(inputURL);
        return nativeUri == null ? null : makeEntryForURL(inputURL, nativeUri);
    }

    public JSONObject makeEntryForNativeUri(Uri nativeUri) {
        LocalFilesystemURL inputUrl = toLocalUri(nativeUri);
        return inputUrl == null ? null : makeEntryForURL(inputUrl, nativeUri);
    }

    public JSONObject getEntryForLocalURL(LocalFilesystemURL inputURL) throws IOException {
        return makeEntryForURL(inputURL);
    }

    public JSONObject makeEntryForFile(File file) {
        return makeEntryForNativeUri(Uri.fromFile(file));
    }

    abstract JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException;

    abstract boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException;

    abstract boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException, NoModificationAllowedException;

    abstract LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException;

    public final JSONArray readEntriesAtLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
        LocalFilesystemURL[] children = listChildren(inputURL);
        JSONArray entries = new JSONArray();
        if (children != null) {
            for (LocalFilesystemURL url : children) {
                entries.put(makeEntryForURL(url));
            }
        }
        return entries;
    }

    abstract JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException;

    public Uri getRootUri() {
        return rootUri;
    }

    public boolean exists(LocalFilesystemURL inputURL) {
        try {
            getFileMetadataForLocalURL(inputURL);
        } catch (FileNotFoundException e) {
            return false;
        }
        return true;
    }

    public Uri nativeUriForFullPath(String fullPath) {
        Uri ret = null;
        if (fullPath != null) {
            String encodedPath = Uri.fromFile(new File(fullPath)).getEncodedPath();
            if (encodedPath.startsWith("/")) {
                encodedPath = encodedPath.substring(1);
            }
            ret = rootUri.buildUpon().appendEncodedPath(encodedPath).build();
        }
        return ret;
    }

    public LocalFilesystemURL localUrlforFullPath(String fullPath) {
        Uri nativeUri = nativeUriForFullPath(fullPath);
        if (nativeUri != null) {
            return toLocalUri(nativeUri);
        }
        return null;
    }

    /**
     * Removes multiple repeated //s, and collapses processes ../s.
     */
    protected static String normalizePath(String rawPath) {
        // If this is an absolute path, trim the leading "/" and replace it later
        boolean isAbsolutePath = rawPath.startsWith("/");
        if (isAbsolutePath) {
            rawPath = rawPath.replaceFirst("/+", "");
        }
        ArrayList<String> components = new ArrayList<String>(Arrays.asList(rawPath.split("/+")));
        for (int index = 0; index < components.size(); ++index) {
            if (components.get(index).equals("..")) {
                components.remove(index);
                if (index > 0) {
                    components.remove(index - 1);
                    --index;
                }
            }
        }
        StringBuilder normalizedPath = new StringBuilder();
        for (String component : components) {
            normalizedPath.append("/");
            normalizedPath.append(component);
        }
        if (isAbsolutePath) {
            return normalizedPath.toString();
        } else {
            return normalizedPath.toString().substring(1);
        }
    }

    /**
     * Gets the free space in bytes available on this filesystem.
     * Subclreplacedes may override this method to return nonzero free space.
     */
    public long getFreeSpaceInBytes() {
        return 0;
    }

    public abstract Uri toNativeUri(LocalFilesystemURL inputURL);

    public abstract LocalFilesystemURL toLocalUri(Uri inputURL);

    public JSONObject getRootEntry() {
        if (rootEntry == null) {
            rootEntry = makeEntryForNativeUri(rootUri);
        }
        return rootEntry;
    }

    public JSONObject getParentForLocalURL(LocalFilesystemURL inputURL) throws IOException {
        Uri parentUri = inputURL.uri;
        String parentPath = new File(inputURL.uri.getPath()).getParent();
        if (!"/".equals(parentPath)) {
            parentUri = inputURL.uri.buildUpon().path(parentPath + '/').build();
        }
        return getEntryForLocalURL(LocalFilesystemURL.parse(parentUri));
    }

    protected LocalFilesystemURL makeDestinationURL(String newName, LocalFilesystemURL srcURL, LocalFilesystemURL destURL, boolean isDirectory) {
        // I know this looks weird but it is to work around a JSON bug.
        if ("null".equals(newName) || "".equals(newName)) {
            newName = srcURL.uri.getLastPathSegment();
            ;
        }
        String newDest = destURL.uri.toString();
        if (newDest.endsWith("/")) {
            newDest = newDest + newName;
        } else {
            newDest = newDest + "/" + newName;
        }
        if (isDirectory) {
            newDest += '/';
        }
        return LocalFilesystemURL.parse(newDest);
    }

    /* Read a source URL (possibly from a different filesystem, srcFs,) and copy it to
	 * the destination URL on this filesystem, optionally with a new filename.
	 * If move is true, then this method should either perform an atomic move operation
	 * or remove the source file when finished.
	 */
    public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName, Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException {
        // First, check to see that we can do it
        if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) {
            throw new NoModificationAllowedException("Cannot move file at source URL");
        }
        final LocalFilesystemURL destination = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory);
        Uri srcNativeUri = srcFs.toNativeUri(srcURL);
        CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(srcNativeUri);
        OutputStream os = null;
        try {
            os = getOutputStreamForURL(destination);
        } catch (IOException e) {
            ofrr.inputStream.close();
            throw e;
        }
        // Closes streams.
        resourceApi.copyResource(ofrr, os);
        if (move) {
            srcFs.removeFileAtLocalURL(srcURL);
        }
        return getEntryForLocalURL(destination);
    }

    public OutputStream getOutputStreamForURL(LocalFilesystemURL inputURL) throws IOException {
        return resourceApi.openOutputStream(toNativeUri(inputURL));
    }

    public void readFileAtURL(LocalFilesystemURL inputURL, long start, long end, ReadFileCallback readFileCallback) throws IOException {
        CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(toNativeUri(inputURL));
        if (end < 0) {
            end = ofrr.length;
        }
        long numBytesToRead = end - start;
        try {
            if (start > 0) {
                ofrr.inputStream.skip(start);
            }
            InputStream inputStream = ofrr.inputStream;
            if (end < ofrr.length) {
                inputStream = new LimitedInputStream(inputStream, numBytesToRead);
            }
            readFileCallback.handleData(inputStream, ofrr.mimeType);
        } finally {
            ofrr.inputStream.close();
        }
    }

    abstract long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, boolean isBinary) throws NoModificationAllowedException, IOException;

    abstract long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException, NoModificationAllowedException;

    // This method should return null if filesystem urls cannot be mapped to paths
    abstract String filesystemPathForURL(LocalFilesystemURL url);

    abstract LocalFilesystemURL URLforFilesystemPath(String path);

    abstract boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL);

    protected clreplaced LimitedInputStream extends FilterInputStream {

        long numBytesToRead;

        public LimitedInputStream(InputStream in, long numBytesToRead) {
            super(in);
            this.numBytesToRead = numBytesToRead;
        }

        @Override
        public int read() throws IOException {
            if (numBytesToRead <= 0) {
                return -1;
            }
            numBytesToRead--;
            return in.read();
        }

        @Override
        public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
            if (numBytesToRead <= 0) {
                return -1;
            }
            int bytesToRead = byteCount;
            if (byteCount > numBytesToRead) {
                // Cast okay; long is less than int here.
                bytesToRead = (int) numBytesToRead;
            }
            int numBytesRead = in.read(buffer, byteOffset, bytesToRead);
            numBytesToRead -= numBytesRead;
            return numBytesRead;
        }
    }
}

19 Source : ContentFilesystem.java
with MIT License
from zhangyd-c

@Override
public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String fileName, JSONObject options, boolean directory) throws IOException, TypeMismatchException, JSONException {
    throw new UnsupportedOperationException("getFile() not supported for content:. Use resolveLocalFileSystemURL instead.");
}

19 Source : AssetFilesystem.java
with MIT License
from zhangyd-c

@Override
public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
    if (options != null && options.optBoolean("create")) {
        throw new UnsupportedOperationException("replacedets are read-only");
    }
    // Check whether the supplied path is absolute or relative
    if (directory && !path.endsWith("/")) {
        path += "/";
    }
    LocalFilesystemURL requestedURL;
    if (path.startsWith("/")) {
        requestedURL = localUrlforFullPath(normalizePath(path));
    } else {
        requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
    }
    // Throws a FileNotFoundException if it doesn't exist.
    getFileMetadataForLocalURL(requestedURL);
    boolean isDir = isDirectory(requestedURL.path);
    if (directory && !isDir) {
        throw new TypeMismatchException("path doesn't exist or is file");
    } else if (!directory && isDir) {
        throw new TypeMismatchException("path doesn't exist or is directory");
    }
    // Return the directory
    return makeEntryForURL(requestedURL);
}

19 Source : BadgeImpl.java
with MIT License
from zhangyd-c

/**
 * Persist the config map so that `autoClear` has same value after restart.
 *
 * @param config The config map to persist.
 */
public void saveConfig(JSONObject config) {
    SharedPreferences.Editor editor = getPrefs().edit();
    editor.putString(CONFIG_KEY, config.toString());
    editor.apply();
}

19 Source : Badge.java
with MIT License
from zhangyd-c

/**
 * Persist the plugin config.
 *
 * @param config The config map to persist.
 */
private void saveConfig(final JSONObject config) {
    cordova.getThreadPool().execute(new Runnable() {

        @Override
        public void run() {
            impl.saveConfig(config);
        }
    });
}

19 Source : CoreAndroid.java
with MIT License
from zhangyd-c

private void sendEventMessage(String action) {
    JSONObject obj = new JSONObject();
    try {
        obj.put("action", action);
    } catch (JSONException e) {
        LOG.e(TAG, "Failed to create event message", e);
    }
    sendEventMessage(new PluginResult(PluginResult.Status.OK, obj));
}

19 Source : CallbackContext.java
with MIT License
from zhangyd-c

/**
 * Helper for success callbacks that just returns the Status.OK by default
 *
 * @param message           The message to add to the success result.
 */
public void success(JSONObject message) {
    sendPluginResult(new PluginResult(PluginResult.Status.OK, message));
}

19 Source : CallbackContext.java
with MIT License
from zhangyd-c

/**
 * Helper for error callbacks that just returns the Status.ERROR by default
 *
 * @param message           The message to add to the error result.
 */
public void error(JSONObject message) {
    sendPluginResult(new PluginResult(PluginResult.Status.ERROR, message));
}

19 Source : InAppBrowser.java
with MIT License
from Zeta36

/**
 * Create a new plugin success result and send it back to JavaScript
 *
 * @param obj a JSONObject contain event payload information
 */
private void sendUpdate(JSONObject obj, boolean keepCallback) {
    sendUpdate(obj, keepCallback, PluginResult.Status.OK);
}

19 Source : InAppBrowser.java
with MIT License
from Zeta36

/**
 * Closes the dialog
 */
public void closeDialog() {
    final AmazonWebView childView = this.inAppWebView;
    // The JS protects against multiple calls, so this should happen only when
    // closeDialog() is called by other native code.
    if (childView == null) {
        return;
    }
    this.cordova.getActivity().runOnUiThread(new Runnable() {

        @Override
        public void run() {
            childView.setWebViewClient(new AmazonWebViewClient() {

                // NB: wait for about:blank before dismissing
                public void onPageFinished(AmazonWebView view, String url) {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                }
            });
            // NB: From SDK 19: "If you call methods on WebView from any thread
            // other than your app's UI thread, it can cause unexpected results."
            // http://developer.android.com/guide/webapps/migrating.html#Threads
            childView.loadUrl("about:blank");
        }
    });
    try {
        JSONObject obj = new JSONObject();
        obj.put("type", EXIT_EVENT);
        sendUpdate(obj, false);
    } catch (JSONException ex) {
        Log.d(LOG_TAG, "Should never happen");
    }
}

19 Source : FileTransfer.java
with MIT License
from Zeta36

/**
 * Create an error object based on the preplaceded in errorCode
 * @param errorCode      the error
 * @return JSONObject containing the error
 */
private static JSONObject createFileTransferError(int errorCode, String source, String target, String body, Integer httpStatus, Throwable throwable) {
    JSONObject error = null;
    try {
        error = new JSONObject();
        error.put("code", errorCode);
        error.put("source", source);
        error.put("target", target);
        if (body != null) {
            error.put("body", body);
        }
        if (httpStatus != null) {
            error.put("http_status", httpStatus);
        }
        if (throwable != null) {
            String msg = throwable.getMessage();
            if (msg == null || "".equals(msg)) {
                msg = throwable.toString();
            }
            error.put("exception", msg);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return error;
}

19 Source : FileUtils.java
with MIT License
from Zeta36

/**
 * Creates or looks up a file.
 *
 * @param baseURLstr base directory
 * @param path file/directory to lookup or create
 * @param options specify whether to create or not
 * @param directory if true look up directory, if false look up file
 * @return a Entry object
 * @throws FileExistsException
 * @throws IOException
 * @throws TypeMismatchException
 * @throws EncodingException
 * @throws JSONException
 */
private JSONObject getFile(String baseURLstr, String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
    try {
        LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
        Filesystem fs = this.filesystemForURL(inputURL);
        if (fs == null) {
            throw new MalformedURLException("No installed handlers for this URL");
        }
        return fs.getFileForLocalURL(inputURL, path, options, directory);
    } catch (IllegalArgumentException e) {
        throw new MalformedURLException("Unrecognized filesystem URL");
    }
}

19 Source : FileUtils.java
with MIT License
from Zeta36

/**
 * Returns a JSON object representing the given File. Internal APIs should be modified
 * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin.
 *
 * @param file the File to convert
 * @return a JSON representation of the given File
 * @throws JSONException
 */
public JSONObject getEntryForFile(File file) throws JSONException {
    JSONObject entry;
    for (Filesystem fs : filesystems) {
        entry = fs.makeEntryForFile(file);
        if (entry != null) {
            return entry;
        }
    }
    return null;
}

19 Source : Filesystem.java
with MIT License
from Zeta36

public abstract clreplaced Filesystem {

    protected final Uri rootUri;

    protected final CordovaResourceApi resourceApi;

    public final String name;

    private JSONObject rootEntry;

    public Filesystem(Uri rootUri, String name, CordovaResourceApi resourceApi) {
        this.rootUri = rootUri;
        this.name = name;
        this.resourceApi = resourceApi;
    }

    public interface ReadFileCallback {

        public void handleData(InputStream inputStream, String contentType) throws IOException;
    }

    public static JSONObject makeEntryForURL(LocalFilesystemURL inputURL, Uri nativeURL) {
        try {
            String path = inputURL.path;
            int end = path.endsWith("/") ? 1 : 0;
            String[] parts = path.substring(0, path.length() - end).split("/+");
            String fileName = parts[parts.length - 1];
            JSONObject entry = new JSONObject();
            entry.put("isFile", !inputURL.isDirectory);
            entry.put("isDirectory", inputURL.isDirectory);
            entry.put("name", fileName);
            entry.put("fullPath", path);
            // The file system can't be specified, as it would lead to an infinite loop,
            // but the filesystem name can be.
            entry.put("filesystemName", inputURL.fsName);
            // Backwards compatibility
            entry.put("filesystem", "temporary".equals(inputURL.fsName) ? 0 : 1);
            String nativeUrlStr = nativeURL.toString();
            if (inputURL.isDirectory && !nativeUrlStr.endsWith("/")) {
                nativeUrlStr += "/";
            }
            entry.put("nativeURL", nativeUrlStr);
            return entry;
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public JSONObject makeEntryForURL(LocalFilesystemURL inputURL) {
        Uri nativeUri = toNativeUri(inputURL);
        return nativeUri == null ? null : makeEntryForURL(inputURL, nativeUri);
    }

    public JSONObject makeEntryForNativeUri(Uri nativeUri) {
        LocalFilesystemURL inputUrl = toLocalUri(nativeUri);
        return inputUrl == null ? null : makeEntryForURL(inputUrl, nativeUri);
    }

    public JSONObject getEntryForLocalURL(LocalFilesystemURL inputURL) throws IOException {
        return makeEntryForURL(inputURL);
    }

    public JSONObject makeEntryForFile(File file) {
        return makeEntryForNativeUri(Uri.fromFile(file));
    }

    abstract JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException;

    abstract boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException;

    abstract boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException, NoModificationAllowedException;

    abstract LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException;

    public final JSONArray readEntriesAtLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
        LocalFilesystemURL[] children = listChildren(inputURL);
        JSONArray entries = new JSONArray();
        if (children != null) {
            for (LocalFilesystemURL url : children) {
                entries.put(makeEntryForURL(url));
            }
        }
        return entries;
    }

    abstract JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException;

    public Uri getRootUri() {
        return rootUri;
    }

    public boolean exists(LocalFilesystemURL inputURL) {
        try {
            getFileMetadataForLocalURL(inputURL);
        } catch (FileNotFoundException e) {
            return false;
        }
        return true;
    }

    public Uri nativeUriForFullPath(String fullPath) {
        Uri ret = null;
        if (fullPath != null) {
            String encodedPath = Uri.fromFile(new File(fullPath)).getEncodedPath();
            if (encodedPath.startsWith("/")) {
                encodedPath = encodedPath.substring(1);
            }
            ret = rootUri.buildUpon().appendEncodedPath(encodedPath).build();
        }
        return ret;
    }

    public LocalFilesystemURL localUrlforFullPath(String fullPath) {
        Uri nativeUri = nativeUriForFullPath(fullPath);
        if (nativeUri != null) {
            return toLocalUri(nativeUri);
        }
        return null;
    }

    /**
     * Removes multiple repeated //s, and collapses processes ../s.
     */
    protected static String normalizePath(String rawPath) {
        // If this is an absolute path, trim the leading "/" and replace it later
        boolean isAbsolutePath = rawPath.startsWith("/");
        if (isAbsolutePath) {
            rawPath = rawPath.replaceFirst("/+", "");
        }
        ArrayList<String> components = new ArrayList<String>(Arrays.asList(rawPath.split("/+")));
        for (int index = 0; index < components.size(); ++index) {
            if (components.get(index).equals("..")) {
                components.remove(index);
                if (index > 0) {
                    components.remove(index - 1);
                    --index;
                }
            }
        }
        StringBuilder normalizedPath = new StringBuilder();
        for (String component : components) {
            normalizedPath.append("/");
            normalizedPath.append(component);
        }
        if (isAbsolutePath) {
            return normalizedPath.toString();
        } else {
            return normalizedPath.toString().substring(1);
        }
    }

    public abstract Uri toNativeUri(LocalFilesystemURL inputURL);

    public abstract LocalFilesystemURL toLocalUri(Uri inputURL);

    public JSONObject getRootEntry() {
        if (rootEntry == null) {
            rootEntry = makeEntryForNativeUri(rootUri);
        }
        return rootEntry;
    }

    public JSONObject getParentForLocalURL(LocalFilesystemURL inputURL) throws IOException {
        Uri parentUri = inputURL.uri;
        String parentPath = new File(inputURL.uri.getPath()).getParent();
        if (!"/".equals(parentPath)) {
            parentUri = inputURL.uri.buildUpon().path(parentPath + '/').build();
        }
        return getEntryForLocalURL(LocalFilesystemURL.parse(parentUri));
    }

    protected LocalFilesystemURL makeDestinationURL(String newName, LocalFilesystemURL srcURL, LocalFilesystemURL destURL, boolean isDirectory) {
        // I know this looks weird but it is to work around a JSON bug.
        if ("null".equals(newName) || "".equals(newName)) {
            newName = srcURL.uri.getLastPathSegment();
            ;
        }
        String newDest = destURL.uri.toString();
        if (newDest.endsWith("/")) {
            newDest = newDest + newName;
        } else {
            newDest = newDest + "/" + newName;
        }
        if (isDirectory) {
            newDest += '/';
        }
        return LocalFilesystemURL.parse(newDest);
    }

    /* Read a source URL (possibly from a different filesystem, srcFs,) and copy it to
	 * the destination URL on this filesystem, optionally with a new filename.
	 * If move is true, then this method should either perform an atomic move operation
	 * or remove the source file when finished.
	 */
    public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName, Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException {
        // First, check to see that we can do it
        if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) {
            throw new NoModificationAllowedException("Cannot move file at source URL");
        }
        final LocalFilesystemURL destination = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory);
        Uri srcNativeUri = srcFs.toNativeUri(srcURL);
        CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(srcNativeUri);
        OutputStream os = null;
        try {
            os = getOutputStreamForURL(destination);
        } catch (IOException e) {
            ofrr.inputStream.close();
            throw e;
        }
        // Closes streams.
        resourceApi.copyResource(ofrr, os);
        if (move) {
            srcFs.removeFileAtLocalURL(srcURL);
        }
        return getEntryForLocalURL(destination);
    }

    public OutputStream getOutputStreamForURL(LocalFilesystemURL inputURL) throws IOException {
        return resourceApi.openOutputStream(toNativeUri(inputURL));
    }

    public void readFileAtURL(LocalFilesystemURL inputURL, long start, long end, ReadFileCallback readFileCallback) throws IOException {
        CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(toNativeUri(inputURL));
        if (end < 0) {
            end = ofrr.length;
        }
        long numBytesToRead = end - start;
        try {
            if (start > 0) {
                ofrr.inputStream.skip(start);
            }
            InputStream inputStream = ofrr.inputStream;
            if (end < ofrr.length) {
                inputStream = new LimitedInputStream(inputStream, numBytesToRead);
            }
            readFileCallback.handleData(inputStream, ofrr.mimeType);
        } finally {
            ofrr.inputStream.close();
        }
    }

    abstract long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, boolean isBinary) throws NoModificationAllowedException, IOException;

    abstract long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException, NoModificationAllowedException;

    // This method should return null if filesystem urls cannot be mapped to paths
    abstract String filesystemPathForURL(LocalFilesystemURL url);

    abstract LocalFilesystemURL URLforFilesystemPath(String path);

    abstract boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL);

    protected clreplaced LimitedInputStream extends FilterInputStream {

        long numBytesToRead;

        public LimitedInputStream(InputStream in, long numBytesToRead) {
            super(in);
            this.numBytesToRead = numBytesToRead;
        }

        @Override
        public int read() throws IOException {
            if (numBytesToRead <= 0) {
                return -1;
            }
            numBytesToRead--;
            return in.read();
        }

        @Override
        public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
            if (numBytesToRead <= 0) {
                return -1;
            }
            int bytesToRead = byteCount;
            if (byteCount > numBytesToRead) {
                // Cast okay; long is less than int here.
                bytesToRead = (int) numBytesToRead;
            }
            int numBytesRead = in.read(buffer, byteOffset, bytesToRead);
            numBytesToRead -= numBytesRead;
            return numBytesRead;
        }
    }
}

19 Source : PushPlugin.java
with MIT License
from Zeta36

/**
 * Sends register/unregiste events to JS
 *
 * @param String
 *            - eventName - "register", "unregister"
 * @param String
 *            - valid registrationId
 */
public static void sendRegistrationIdWithEvent(String event, String registrationId) {
    if (TextUtils.isEmpty(event) || TextUtils.isEmpty(registrationId)) {
        return;
    }
    try {
        JSONObject json;
        json = new JSONObject().put(EVENT, event);
        json.put(REG_ID, registrationId);
        sendJavascript(json);
    } catch (Exception e) {
        Log.getStackTraceString(e);
    }
}

19 Source : ADMMessageHandler.java
with MIT License
from Zeta36

/**
 * {@inheritDoc}
 */
@Override
protected void onRegistrationError(final String errorId) {
    // You should consider a registration error fatal. In response, your app
    // may degrade gracefully, or you may wish to notify the user that this part
    // of your app's functionality is not available.
    try {
        JSONObject json;
        json = new JSONObject().put(PushPlugin.EVENT, ERROR_EVENT);
        json.put(ADMMessageHandler.ERROR_MSG, errorId);
        PushPlugin.sendJavascript(json);
    } catch (Exception e) {
        Log.getStackTraceString(e);
    }
}

See More Examples